JavaScript parser and stringifier for YAML documents with complete YAML 1.1 and 1.2 support
npx @tessl/cli install tessl/npm-yaml@2.8.0YAML 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.
npm install yamlimport { 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.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() }
});YAML provides a three-layered API architecture:
parse, stringify)The library maintains complete type safety throughout all layers and supports both browser and Node.js environments with zero external dependencies.
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;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;
}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;
}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;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>;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';
}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;
}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>>;
}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;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';