YAML AST Parser

0.0.43 · abandoned · verified Tue Apr 21

yaml-ast-parser is a JavaScript/TypeScript library designed to parse YAML documents into an Abstract Syntax Tree (AST). It is a fork of `js-yaml` but specifically focuses on providing AST representation rather than direct deserialization into JavaScript objects. Key features include the ability to restore parsing after errors, integrate error reporting directly into AST nodes, and built-in support for the `!include` tag commonly used in RAML specifications. The library is currently at version `0.0.43` and appears to be in an abandoned state, with the last GitHub activity several years ago. Its primary differentiator is the granular AST access and specialized `!include` handling, making it suitable for tools that need to analyze or transform YAML structure rather than just consume its data. Developers should be aware of its inactive maintenance status when considering its use in new projects.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse a YAML string into an AST and then recursively traverse the resulting `YAMLNode` structure, printing the kind and value of each node. It highlights the use of `load`, `Kind` enum, and type casting for specific node types like `YAMLScalar`, `YamlMap`, and `YAMLSequence` to access their distinct properties.

import { load, Kind, YAMLScalar, YamlMap, YAMLSequence, YAMLMapping, YAMLNode } from 'yaml-ast-parser';

const yamlContent = `
name: John Doe
age: 30
address:
  street: 123 Main St
  city: Anytown
skills:
  - TypeScript
  - Node.js
  - YAML
`;

function traverseAST(node: YAMLNode, level: number = 0) {
  const indent = '  '.repeat(level);
  console.log(`${indent}Kind: ${Kind[node.kind]} (Pos: ${node.startPosition}-${node.endPosition})`);

  switch (node.kind) {
    case Kind.SCALAR:
      const scalarNode = node as YAMLScalar;
      console.log(`${indent}  Value: '${scalarNode.value}'`);
      break;
    case Kind.MAP:
      const mapNode = node as YamlMap;
      mapNode.mappings.forEach(mapping => {
        console.log(`${indent}  Key: '${(mapping.key as YAMLScalar).value}'`);
        traverseAST(mapping.value, level + 1);
      });
      break;
    case Kind.SEQ:
      const sequenceNode = node as YAMLSequence;
      sequenceNode.items.forEach(item => {
        traverseAST(item, level + 1);
      });
      break;
    case Kind.MAPPING:
      const mappingNode = node as YAMLMapping;
      // Key is a scalar, Value is a general YAMLNode
      console.log(`${indent}  Mapping Key: '${(mappingNode.key as YAMLScalar).value}'`);
      traverseAST(mappingNode.value, level + 1);
      break;
    default:
      // Handle other kinds if necessary
      break;
  }
}

const ast = load(yamlContent);

if (ast) {
  console.log('YAML AST Root Node:');
  traverseAST(ast);
} else {
  console.error('Failed to parse YAML content.');
}

view raw JSON →