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.00
# YAML
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: yaml
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install yaml`
10
11
## Core Imports
12
13
```typescript
14
import { parse, stringify } from "yaml";
15
```
16
17
For complete API access:
18
19
```typescript
20
import {
21
parse,
22
stringify,
23
parseDocument,
24
parseAllDocuments,
25
Document,
26
YAMLMap,
27
YAMLSeq,
28
Scalar,
29
isScalar,
30
isMap,
31
isSeq,
32
visit
33
} from "yaml";
34
```
35
36
CommonJS:
37
38
```javascript
39
const { parse, stringify, parseDocument, Document } = require("yaml");
40
```
41
42
Default import (also available):
43
44
```typescript
45
import YAML from "yaml";
46
// Access via YAML.parse(), YAML.stringify(), etc.
47
```
48
49
## Basic Usage
50
51
```typescript
52
import { parse, stringify } from "yaml";
53
54
// Parse YAML string to JavaScript
55
const data = parse(`
56
name: John Doe
57
age: 30
58
hobbies:
59
- reading
60
- coding
61
`);
62
// Result: { name: 'John Doe', age: 30, hobbies: ['reading', 'coding'] }
63
64
// Convert JavaScript to YAML string
65
const yamlString = stringify({
66
title: "My Document",
67
items: [1, 2, 3],
68
metadata: { created: new Date() }
69
});
70
```
71
72
## Architecture
73
74
YAML provides a three-layered API architecture:
75
76
- **Parse & Stringify Layer**: Simple functions for common use cases (`parse`, `stringify`)
77
- **Document Layer**: Full document handling with AST access, error tracking, and metadata
78
- **Parser Infrastructure**: Low-level lexer, parser, and composer for advanced YAML processing
79
80
The library maintains complete type safety throughout all layers and supports both browser and Node.js environments with zero external dependencies.
81
82
## Capabilities
83
84
### Simple Parsing & Stringifying
85
86
Core functions for converting between YAML strings and JavaScript values. Perfect for configuration files, data serialization, and simple YAML processing tasks.
87
88
```typescript { .api }
89
function parse(src: string, options?: ParseOptions): any;
90
function stringify(value: any, options?: ToStringOptions): string;
91
```
92
93
[Parse & Stringify](./parse-stringify.md)
94
95
### Document Processing
96
97
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.
98
99
```typescript { .api }
100
function parseDocument(source: string, options?: ParseOptions): Document;
101
function parseAllDocuments(source: string, options?: ParseOptions): Document[] | EmptyStream;
102
103
class Document<Contents = ParsedNode, Strict = true> {
104
constructor(value?: any, replacer?: Replacer, options?: CreateNodeOptions);
105
clone(): Document<Contents, Strict>;
106
toJS(options?: ToJSOptions): any;
107
toString(options?: ToStringOptions): string;
108
}
109
```
110
111
[Document Processing](./document-processing.md)
112
113
### AST Node Manipulation
114
115
Direct manipulation of YAML Abstract Syntax Tree nodes including scalars, collections, aliases, and pairs. Essential for programmatic YAML generation and fine-grained document control.
116
117
```typescript { .api }
118
class Scalar<T = unknown> {
119
constructor(value: T);
120
toJSON(): any;
121
toString(): string;
122
}
123
124
class YAMLMap<K = unknown, V = unknown> extends Collection {
125
static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLMap;
126
add(pair: Pair | { key: any; value: any }, overwrite?: boolean): void;
127
get(key: unknown, keepScalar?: boolean): unknown;
128
set(key: any, value: any): void;
129
}
130
131
class YAMLSeq<T = unknown> extends Collection {
132
static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLSeq;
133
add(value: T): number;
134
get(index: number, keepScalar?: boolean): unknown;
135
set(index: number, value: T): void;
136
}
137
```
138
139
[AST Nodes](./ast-nodes.md)
140
141
### Type Guards & Identity
142
143
Runtime type checking functions for identifying different node types in the AST. Critical for type-safe node manipulation and traversal.
144
145
```typescript { .api }
146
function isDocument(node: unknown): node is Document;
147
function isNode(value: unknown): value is Node;
148
function isScalar(node: unknown): node is Scalar;
149
function isMap(node: unknown): node is YAMLMap;
150
function isSeq(node: unknown): node is YAMLSeq;
151
function isPair(node: unknown): node is Pair;
152
function isAlias(node: unknown): node is Alias;
153
function isCollection(node: unknown): node is Collection;
154
```
155
156
[Type Guards](./type-guards.md)
157
158
### Tree Traversal & Visiting
159
160
Visitor pattern implementation for traversing and transforming YAML ASTs. Perfect for complex document analysis, modification, and custom processing workflows.
161
162
```typescript { .api }
163
function visit(node: Node, visitor: visitor): void;
164
function visitAsync(node: Node, visitor: asyncVisitor): Promise<void>;
165
166
type visitor = visitorFn | { [key: string]: visitor };
167
type visitorFn<T = unknown> = (
168
key: number | string | null,
169
node: T,
170
path: readonly (number | string)[]
171
) => void | symbol | T | Pair<any, T>;
172
```
173
174
[Tree Traversal](./tree-traversal.md)
175
176
### Error Handling & Logging
177
178
Comprehensive error reporting with position information, warning system, and configurable logging. Essential for robust YAML processing and debugging.
179
180
```typescript { .api }
181
class YAMLError extends Error {
182
name: 'YAMLError';
183
code: ErrorCode;
184
message: string;
185
pos?: [number, number];
186
}
187
188
class YAMLParseError extends YAMLError {
189
name: 'YAMLParseError';
190
pos: [number, number];
191
linePos?: { line: number; col: number };
192
}
193
194
class YAMLWarning extends YAMLError {
195
name: 'YAMLWarning';
196
}
197
```
198
199
[Error Handling](./error-handling.md)
200
201
### Schema System & Configuration
202
203
Extensible schema system with YAML 1.1 and 1.2 support, custom tag definitions, and comprehensive configuration options for parsing, stringifying, and document handling.
204
205
```typescript { .api }
206
class Schema {
207
constructor(options: SchemaOptions);
208
clone(): Schema;
209
}
210
211
interface ParseOptions {
212
keepCstNodes?: boolean;
213
keepNodeTypes?: boolean;
214
keepBlobsInJSON?: boolean;
215
maxAliasCount?: number;
216
prettyErrors?: boolean;
217
}
218
219
interface ToStringOptions {
220
blockQuote?: boolean | 'folded' | 'literal';
221
defaultKeyType?: Scalar.Type | null;
222
defaultStringType?: Scalar.Type;
223
directives?: boolean | null;
224
indent?: number;
225
indentSeq?: boolean | null;
226
}
227
```
228
229
[Schema & Configuration](./schema-configuration.md)
230
231
### Parser Infrastructure
232
233
Low-level parsing components including lexer, parser, and composer for advanced YAML processing and custom tooling development.
234
235
```typescript { .api }
236
class Lexer {
237
lex(src: string): Generator<Token>;
238
}
239
240
class Parser {
241
constructor(onNewLine?: (offset: number) => void);
242
parse(src: string): Generator<ParsedNode>;
243
}
244
245
class Composer<Contents = ParsedNode, Strict = true> {
246
constructor(options?: DocumentOptions & SchemaOptions);
247
compose(tokens: Iterable<Token>): Generator<Document<Contents, Strict>>;
248
}
249
```
250
251
[Parser Infrastructure](./parser-infrastructure.md)
252
253
### Utility Functions
254
255
Helper functions for node creation, type conversion, string formatting, and advanced YAML operations exposed through the util export.
256
257
```typescript { .api }
258
function createNode(value: unknown, options?: CreateNodeOptions): Node;
259
function createPair(key: any, value: any, options?: CreateNodeOptions): Pair;
260
function toJS(value: unknown, arg?: string | ToJSOptions): any;
261
function findPair(items: Iterable<unknown>, key: unknown): Pair | undefined;
262
```
263
264
[Utilities](./utilities.md)
265
266
## Common Types
267
268
```typescript { .api }
269
type Node = Alias | Scalar | YAMLMap | YAMLSeq;
270
type ParsedNode = Alias | Scalar<any> | YAMLMap<any, any> | YAMLSeq<any>;
271
272
interface Pair<K = unknown, V = unknown> {
273
key: K;
274
value: V;
275
spaceBefore?: boolean;
276
comment?: string;
277
commentBefore?: string;
278
}
279
280
type Range = [start: number, valueEnd: number, nodeEnd: number];
281
282
type ErrorCode =
283
| 'BAD_ALIAS' | 'BAD_DIRECTIVE' | 'BAD_DQ_ESCAPE' | 'BAD_INDENT'
284
| 'BAD_PROP_ORDER' | 'BAD_SCALAR_START' | 'BLOCK_AS_IMPLICIT_KEY'
285
| 'BLOCK_IN_FLOW' | 'DUPLICATE_KEY' | 'IMPOSSIBLE' | 'KEY_OVER_1024_CHARS'
286
| 'MISSING_CHAR' | 'MULTILINE_IMPLICIT_KEY' | 'MULTIPLE_ANCHORS'
287
| 'MULTIPLE_DOCS' | 'MULTIPLE_TAGS' | 'TAB_AS_INDENT' | 'TAG_RESOLVE_FAILED'
288
| 'UNEXPECTED_TOKEN';
289
```