or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

ast-nodes.mddocument-processing.mderror-handling.mdindex.mdparse-stringify.mdparser-infrastructure.mdschema-configuration.mdtree-traversal.mdtype-guards.mdutilities.md
tile.json

tessl/npm-yaml

JavaScript parser and stringifier for YAML documents with complete YAML 1.1 and 1.2 support

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/yaml@2.8.x

To install, run

npx @tessl/cli install tessl/npm-yaml@2.8.0

index.mddocs/

YAML

YAML is a definitive JavaScript/TypeScript library for parsing and stringifying YAML documents. It supports both YAML 1.1 and 1.2 specifications, passes all yaml-test-suite tests, handles malformed input gracefully, and preserves comments and formatting. The library provides a three-tiered API architecture for different use cases.

Package Information

  • Package Name: yaml
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install yaml

Core Imports

import { parse, stringify } from "yaml";

For complete API access:

import {
  parse,
  stringify,
  parseDocument,
  parseAllDocuments,
  Document,
  YAMLMap,
  YAMLSeq,
  Scalar,
  isScalar,
  isMap,
  isSeq,
  visit
} from "yaml";

CommonJS:

const { parse, stringify, parseDocument, Document } = require("yaml");

Default import (also available):

import YAML from "yaml";
// Access via YAML.parse(), YAML.stringify(), etc.

Basic Usage

import { parse, stringify } from "yaml";

// Parse YAML string to JavaScript
const data = parse(`
name: John Doe
age: 30
hobbies:
  - reading
  - coding
`);
// Result: { name: 'John Doe', age: 30, hobbies: ['reading', 'coding'] }

// Convert JavaScript to YAML string
const yamlString = stringify({
  title: "My Document",
  items: [1, 2, 3],
  metadata: { created: new Date() }
});

Architecture

YAML provides a three-layered API architecture:

  • Parse & Stringify Layer: Simple functions for common use cases (parse, stringify)
  • Document Layer: Full document handling with AST access, error tracking, and metadata
  • Parser Infrastructure: Low-level lexer, parser, and composer for advanced YAML processing

The library maintains complete type safety throughout all layers and supports both browser and Node.js environments with zero external dependencies.

Capabilities

Simple Parsing & Stringifying

Core functions for converting between YAML strings and JavaScript values. Perfect for configuration files, data serialization, and simple YAML processing tasks.

function parse(src: string, options?: ParseOptions): any;
function stringify(value: any, options?: ToStringOptions): string;

Parse & Stringify

Document Processing

Complete document handling with full AST access, metadata preservation, error tracking, and multi-document support. Ideal for complex YAML processing, comment preservation, and advanced manipulation.

function parseDocument(source: string, options?: ParseOptions): Document;
function parseAllDocuments(source: string, options?: ParseOptions): Document[] | EmptyStream;

class Document<Contents = ParsedNode, Strict = true> {
  constructor(value?: any, replacer?: Replacer, options?: CreateNodeOptions);
  clone(): Document<Contents, Strict>;
  toJS(options?: ToJSOptions): any;
  toString(options?: ToStringOptions): string;
}

Document Processing

AST Node Manipulation

Direct manipulation of YAML Abstract Syntax Tree nodes including scalars, collections, aliases, and pairs. Essential for programmatic YAML generation and fine-grained document control.

class Scalar<T = unknown> {
  constructor(value: T);
  toJSON(): any;
  toString(): string;
}

class YAMLMap<K = unknown, V = unknown> extends Collection {
  static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLMap;
  add(pair: Pair | { key: any; value: any }, overwrite?: boolean): void;
  get(key: unknown, keepScalar?: boolean): unknown;
  set(key: any, value: any): void;
}

class YAMLSeq<T = unknown> extends Collection {
  static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLSeq;
  add(value: T): number;
  get(index: number, keepScalar?: boolean): unknown;
  set(index: number, value: T): void;
}

AST Nodes

Type Guards & Identity

Runtime type checking functions for identifying different node types in the AST. Critical for type-safe node manipulation and traversal.

function isDocument(node: unknown): node is Document;
function isNode(value: unknown): value is Node;
function isScalar(node: unknown): node is Scalar;
function isMap(node: unknown): node is YAMLMap;
function isSeq(node: unknown): node is YAMLSeq;
function isPair(node: unknown): node is Pair;
function isAlias(node: unknown): node is Alias;
function isCollection(node: unknown): node is Collection;

Type Guards

Tree Traversal & Visiting

Visitor pattern implementation for traversing and transforming YAML ASTs. Perfect for complex document analysis, modification, and custom processing workflows.

function visit(node: Node, visitor: visitor): void;
function visitAsync(node: Node, visitor: asyncVisitor): Promise<void>;

type visitor = visitorFn | { [key: string]: visitor };
type visitorFn<T = unknown> = (
  key: number | string | null,
  node: T,
  path: readonly (number | string)[]
) => void | symbol | T | Pair<any, T>;

Tree Traversal

Error Handling & Logging

Comprehensive error reporting with position information, warning system, and configurable logging. Essential for robust YAML processing and debugging.

class YAMLError extends Error {
  name: 'YAMLError';
  code: ErrorCode;
  message: string;
  pos?: [number, number];
}

class YAMLParseError extends YAMLError {
  name: 'YAMLParseError';
  pos: [number, number];
  linePos?: { line: number; col: number };
}

class YAMLWarning extends YAMLError {
  name: 'YAMLWarning';
}

Error Handling

Schema System & Configuration

Extensible schema system with YAML 1.1 and 1.2 support, custom tag definitions, and comprehensive configuration options for parsing, stringifying, and document handling.

class Schema {
  constructor(options: SchemaOptions);
  clone(): Schema;
}

interface ParseOptions {
  keepCstNodes?: boolean;
  keepNodeTypes?: boolean;
  keepBlobsInJSON?: boolean;
  maxAliasCount?: number;
  prettyErrors?: boolean;
}

interface ToStringOptions {
  blockQuote?: boolean | 'folded' | 'literal';
  defaultKeyType?: Scalar.Type | null;
  defaultStringType?: Scalar.Type;
  directives?: boolean | null;
  indent?: number;
  indentSeq?: boolean | null;
}

Schema & Configuration

Parser Infrastructure

Low-level parsing components including lexer, parser, and composer for advanced YAML processing and custom tooling development.

class Lexer {
  lex(src: string): Generator<Token>;
}

class Parser {
  constructor(onNewLine?: (offset: number) => void);
  parse(src: string): Generator<ParsedNode>;
}

class Composer<Contents = ParsedNode, Strict = true> {
  constructor(options?: DocumentOptions & SchemaOptions);
  compose(tokens: Iterable<Token>): Generator<Document<Contents, Strict>>;
}

Parser Infrastructure

Utility Functions

Helper functions for node creation, type conversion, string formatting, and advanced YAML operations exposed through the util export.

function createNode(value: unknown, options?: CreateNodeOptions): Node;
function createPair(key: any, value: any, options?: CreateNodeOptions): Pair;
function toJS(value: unknown, arg?: string | ToJSOptions): any;
function findPair(items: Iterable<unknown>, key: unknown): Pair | undefined;

Utilities

Common Types

type Node = Alias | Scalar | YAMLMap | YAMLSeq;
type ParsedNode = Alias | Scalar<any> | YAMLMap<any, any> | YAMLSeq<any>;

interface Pair<K = unknown, V = unknown> {
  key: K;
  value: V;
  spaceBefore?: boolean;
  comment?: string;
  commentBefore?: string;
}

type Range = [start: number, valueEnd: number, nodeEnd: number];

type ErrorCode = 
  | 'BAD_ALIAS' | 'BAD_DIRECTIVE' | 'BAD_DQ_ESCAPE' | 'BAD_INDENT'
  | 'BAD_PROP_ORDER' | 'BAD_SCALAR_START' | 'BLOCK_AS_IMPLICIT_KEY'
  | 'BLOCK_IN_FLOW' | 'DUPLICATE_KEY' | 'IMPOSSIBLE' | 'KEY_OVER_1024_CHARS'
  | 'MISSING_CHAR' | 'MULTILINE_IMPLICIT_KEY' | 'MULTIPLE_ANCHORS'
  | 'MULTIPLE_DOCS' | 'MULTIPLE_TAGS' | 'TAB_AS_INDENT' | 'TAG_RESOLVE_FAILED'
  | 'UNEXPECTED_TOKEN';