JavaScript parser and stringifier for YAML documents with complete YAML 1.1 and 1.2 support
Complete YAML document handling with full AST access, metadata preservation, error tracking, and multi-document support. This layer provides comprehensive control over YAML documents including comments, directives, anchors, and advanced manipulation capabilities.
Parse YAML strings into Document objects with complete metadata and error tracking.
/**
* Parse single YAML document with full AST access
* @param source - YAML string to parse
* @param options - Parsing, document, and schema options
* @returns Document object with full metadata
*/
function parseDocument<Contents extends Node = ParsedNode, Strict extends boolean = true>(
source: string,
options?: ParseOptions & DocumentOptions & SchemaOptions
): Contents extends ParsedNode ? Document.Parsed<Contents, Strict> : Document<Contents, Strict>;
/**
* Parse multiple YAML documents from single string
* @param source - YAML string containing multiple documents
* @param options - Parsing, document, and schema options
* @returns Array of Document objects or EmptyStream
*/
function parseAllDocuments<Contents extends Node = ParsedNode, Strict extends boolean = true>(
source: string,
options?: ParseOptions & DocumentOptions & SchemaOptions
): Array<Document<Contents, Strict>> | EmptyStream;
interface EmptyStream extends Array<Document.Parsed>, ReturnType<Composer['streamInfo']> {
empty: true;
}Usage Examples:
import { parseDocument, parseAllDocuments } from "yaml";
// Single document parsing
const doc = parseDocument(`
# Configuration file
app:
name: MyApp
version: 1.0.0
debug: true
`);
console.log(doc.contents); // AST representation
console.log(doc.errors); // Parse errors array
console.log(doc.warnings); // Warning messages array
console.log(doc.toJS()); // Convert to JavaScript object
// Multiple document parsing
const docs = parseAllDocuments(`
---
document: 1
data: first
---
document: 2
data: second
---
document: 3
data: third
`);
docs.forEach((doc, index) => {
console.log(`Document ${index + 1}:`, doc.toJS());
});
// Handle empty streams
if ('empty' in docs) {
console.log('No documents found');
console.log('Stream info:', docs);
}The Document class provides comprehensive access to YAML document structure and metadata.
class Document<Contents = ParsedNode, Strict = true> {
/** Document contents (root node) */
contents: Contents | null;
/** Document directives */
directives: Directives;
/** Parse errors */
errors: YAMLError[];
/** Warning messages */
warnings: YAMLError[];
/** Document options */
options: Required<DocumentOptions>;
/** Document schema */
schema: Schema;
/** Source range information */
range?: Range;
/**
* Create new document
* @param value - Initial value for document
* @param replacer - Replacer function for filtering
* @param options - Document creation options
*/
constructor(value?: any, replacer?: Replacer, options?: CreateNodeOptions & DocumentOptions & SchemaOptions);
/** Create deep clone of document */
clone(): Document<Contents, Strict>;
/** Convert document to JavaScript object */
toJS(opt?: ToJSOptions): any;
/** Convert document to JSON */
toJSON(): any;
/** Convert document to YAML string */
toString(options?: ToStringOptions): string;
}class Document<Contents, Strict> {
/**
* Add value to document at path
* @param path - Property path as array
* @param value - Value to add
*/
add(path: Iterable<unknown>, value: unknown): void;
/**
* Add value to document in specified location
* @param path - Property path
* @param value - Value to add
*/
addIn(path: Iterable<unknown>, value: unknown): void;
/**
* Delete value from document at path
* @param path - Property path to delete
* @returns True if value was deleted
*/
delete(path: Iterable<unknown>): boolean;
/**
* Delete value from document in specified location
* @param path - Property path to delete
* @returns True if value was deleted
*/
deleteIn(path: Iterable<unknown>): boolean;
/**
* Get value from document at path
* @param path - Property path to retrieve
* @param keepScalar - Keep scalar nodes instead of their values
* @returns Value at path
*/
get(path: Iterable<unknown>, keepScalar?: boolean): unknown;
/**
* Get value from document in specified location
* @param path - Property path to retrieve
* @param keepScalar - Keep scalar nodes instead of their values
* @returns Value at path
*/
getIn(path: Iterable<unknown>, keepScalar?: boolean): unknown;
/**
* Check if document has value at path
* @param path - Property path to check
* @returns True if path exists
*/
has(path: Iterable<unknown>): boolean;
/**
* Check if document has value in specified location
* @param path - Property path to check
* @returns True if path exists
*/
hasIn(path: Iterable<unknown>): boolean;
/**
* Set value in document at path
* @param path - Property path to set
* @param value - Value to set
*/
set(path: Iterable<unknown>, value: any): void;
/**
* Set value in document in specified location
* @param path - Property path to set
* @param value - Value to set
*/
setIn(path: Iterable<unknown>, value: any): void;
}class Document<Contents, Strict> {
/**
* Create alias node referencing existing node
* @param node - Node to create alias for
* @param name - Optional anchor name
* @returns Alias node
*/
createAlias(node: Node, name?: string): Alias;
/**
* Create node from JavaScript value
* @param value - Value to convert to node
* @param options - Node creation options
* @returns Created node
*/
createNode(value: unknown, options?: CreateNodeOptions): Node;
/**
* Create key-value pair node
* @param key - Key for the pair
* @param value - Value for the pair
* @param options - Node creation options
* @returns Pair node
*/
createPair(key: unknown, value: unknown, options?: CreateNodeOptions): Pair;
/**
* Set document schema
* @param id - Schema identifier
* @param customTags - Additional custom tags
*/
setSchema(id?: 'core' | 'failsafe' | 'json' | 'yaml-1.1', customTags?: TagId[]): void;
}Usage Examples:
import { parseDocument, Document } from "yaml";
// Document manipulation
const doc = parseDocument(`
users:
- name: Alice
age: 30
- name: Bob
age: 25
`);
// Path-based access
console.log(doc.get(['users', 0, 'name'])); // 'Alice'
doc.set(['users', 0, 'email'], 'alice@example.com');
doc.delete(['users', 1]); // Remove Bob
// Node creation
const newUser = doc.createNode({
name: 'Charlie',
age: 35,
email: 'charlie@example.com'
});
doc.add(['users'], newUser);
// Alias creation
const aliasNode = doc.createAlias(newUser, 'charlie');
doc.set(['admin'], aliasNode);
console.log(doc.toString());Documents preserve YAML comments and provide access to comment metadata.
// Comments are preserved in nodes
const doc = parseDocument(`
# Main configuration
app:
name: MyApp # Application name
# Version information
version: 1.0.0
`);
// Access comments through node properties
if (isScalar(doc.contents?.get('name', true))) {
console.log(doc.contents.comment); // ' Application name'
}const doc = parseDocument(`
invalid: [unclosed array
duplicate: key
duplicate: key
`);
// Check for errors
doc.errors.forEach(error => {
console.log(`Error: ${error.message}`);
if (error.pos) {
console.log(`Position: ${error.pos[0]}-${error.pos[1]}`);
}
});
// Check for warnings
doc.warnings.forEach(warning => {
console.log(`Warning: ${warning.message}`);
});
// Convert with error handling
try {
const data = doc.toJS();
} catch (error) {
console.log('Conversion failed:', error.message);
}Install with Tessl CLI
npx tessl i tessl/npm-yaml