0
# Document Processing
1
2
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.
3
4
## Capabilities
5
6
### Document Parsing
7
8
Parse YAML strings into Document objects with complete metadata and error tracking.
9
10
```typescript { .api }
11
/**
12
* Parse single YAML document with full AST access
13
* @param source - YAML string to parse
14
* @param options - Parsing, document, and schema options
15
* @returns Document object with full metadata
16
*/
17
function parseDocument<Contents extends Node = ParsedNode, Strict extends boolean = true>(
18
source: string,
19
options?: ParseOptions & DocumentOptions & SchemaOptions
20
): Contents extends ParsedNode ? Document.Parsed<Contents, Strict> : Document<Contents, Strict>;
21
22
/**
23
* Parse multiple YAML documents from single string
24
* @param source - YAML string containing multiple documents
25
* @param options - Parsing, document, and schema options
26
* @returns Array of Document objects or EmptyStream
27
*/
28
function parseAllDocuments<Contents extends Node = ParsedNode, Strict extends boolean = true>(
29
source: string,
30
options?: ParseOptions & DocumentOptions & SchemaOptions
31
): Array<Document<Contents, Strict>> | EmptyStream;
32
33
interface EmptyStream extends Array<Document.Parsed>, ReturnType<Composer['streamInfo']> {
34
empty: true;
35
}
36
```
37
38
**Usage Examples:**
39
40
```typescript
41
import { parseDocument, parseAllDocuments } from "yaml";
42
43
// Single document parsing
44
const doc = parseDocument(`
45
# Configuration file
46
app:
47
name: MyApp
48
version: 1.0.0
49
debug: true
50
`);
51
52
console.log(doc.contents); // AST representation
53
console.log(doc.errors); // Parse errors array
54
console.log(doc.warnings); // Warning messages array
55
console.log(doc.toJS()); // Convert to JavaScript object
56
57
// Multiple document parsing
58
const docs = parseAllDocuments(`
59
---
60
document: 1
61
data: first
62
---
63
document: 2
64
data: second
65
---
66
document: 3
67
data: third
68
`);
69
70
docs.forEach((doc, index) => {
71
console.log(`Document ${index + 1}:`, doc.toJS());
72
});
73
74
// Handle empty streams
75
if ('empty' in docs) {
76
console.log('No documents found');
77
console.log('Stream info:', docs);
78
}
79
```
80
81
### Document Class
82
83
The Document class provides comprehensive access to YAML document structure and metadata.
84
85
```typescript { .api }
86
class Document<Contents = ParsedNode, Strict = true> {
87
/** Document contents (root node) */
88
contents: Contents | null;
89
90
/** Document directives */
91
directives: Directives;
92
93
/** Parse errors */
94
errors: YAMLError[];
95
96
/** Warning messages */
97
warnings: YAMLError[];
98
99
/** Document options */
100
options: Required<DocumentOptions>;
101
102
/** Document schema */
103
schema: Schema;
104
105
/** Source range information */
106
range?: Range;
107
108
/**
109
* Create new document
110
* @param value - Initial value for document
111
* @param replacer - Replacer function for filtering
112
* @param options - Document creation options
113
*/
114
constructor(value?: any, replacer?: Replacer, options?: CreateNodeOptions & DocumentOptions & SchemaOptions);
115
116
/** Create deep clone of document */
117
clone(): Document<Contents, Strict>;
118
119
/** Convert document to JavaScript object */
120
toJS(opt?: ToJSOptions): any;
121
122
/** Convert document to JSON */
123
toJSON(): any;
124
125
/** Convert document to YAML string */
126
toString(options?: ToStringOptions): string;
127
}
128
```
129
130
### Document Manipulation Methods
131
132
```typescript { .api }
133
class Document<Contents, Strict> {
134
/**
135
* Add value to document at path
136
* @param path - Property path as array
137
* @param value - Value to add
138
*/
139
add(path: Iterable<unknown>, value: unknown): void;
140
141
/**
142
* Add value to document in specified location
143
* @param path - Property path
144
* @param value - Value to add
145
*/
146
addIn(path: Iterable<unknown>, value: unknown): void;
147
148
/**
149
* Delete value from document at path
150
* @param path - Property path to delete
151
* @returns True if value was deleted
152
*/
153
delete(path: Iterable<unknown>): boolean;
154
155
/**
156
* Delete value from document in specified location
157
* @param path - Property path to delete
158
* @returns True if value was deleted
159
*/
160
deleteIn(path: Iterable<unknown>): boolean;
161
162
/**
163
* Get value from document at path
164
* @param path - Property path to retrieve
165
* @param keepScalar - Keep scalar nodes instead of their values
166
* @returns Value at path
167
*/
168
get(path: Iterable<unknown>, keepScalar?: boolean): unknown;
169
170
/**
171
* Get value from document in specified location
172
* @param path - Property path to retrieve
173
* @param keepScalar - Keep scalar nodes instead of their values
174
* @returns Value at path
175
*/
176
getIn(path: Iterable<unknown>, keepScalar?: boolean): unknown;
177
178
/**
179
* Check if document has value at path
180
* @param path - Property path to check
181
* @returns True if path exists
182
*/
183
has(path: Iterable<unknown>): boolean;
184
185
/**
186
* Check if document has value in specified location
187
* @param path - Property path to check
188
* @returns True if path exists
189
*/
190
hasIn(path: Iterable<unknown>): boolean;
191
192
/**
193
* Set value in document at path
194
* @param path - Property path to set
195
* @param value - Value to set
196
*/
197
set(path: Iterable<unknown>, value: any): void;
198
199
/**
200
* Set value in document in specified location
201
* @param path - Property path to set
202
* @param value - Value to set
203
*/
204
setIn(path: Iterable<unknown>, value: any): void;
205
}
206
```
207
208
### Node Creation Methods
209
210
```typescript { .api }
211
class Document<Contents, Strict> {
212
/**
213
* Create alias node referencing existing node
214
* @param node - Node to create alias for
215
* @param name - Optional anchor name
216
* @returns Alias node
217
*/
218
createAlias(node: Node, name?: string): Alias;
219
220
/**
221
* Create node from JavaScript value
222
* @param value - Value to convert to node
223
* @param options - Node creation options
224
* @returns Created node
225
*/
226
createNode(value: unknown, options?: CreateNodeOptions): Node;
227
228
/**
229
* Create key-value pair node
230
* @param key - Key for the pair
231
* @param value - Value for the pair
232
* @param options - Node creation options
233
* @returns Pair node
234
*/
235
createPair(key: unknown, value: unknown, options?: CreateNodeOptions): Pair;
236
237
/**
238
* Set document schema
239
* @param id - Schema identifier
240
* @param customTags - Additional custom tags
241
*/
242
setSchema(id?: 'core' | 'failsafe' | 'json' | 'yaml-1.1', customTags?: TagId[]): void;
243
}
244
```
245
246
**Usage Examples:**
247
248
```typescript
249
import { parseDocument, Document } from "yaml";
250
251
// Document manipulation
252
const doc = parseDocument(`
253
users:
254
- name: Alice
255
age: 30
256
- name: Bob
257
age: 25
258
`);
259
260
// Path-based access
261
console.log(doc.get(['users', 0, 'name'])); // 'Alice'
262
doc.set(['users', 0, 'email'], 'alice@example.com');
263
doc.delete(['users', 1]); // Remove Bob
264
265
// Node creation
266
const newUser = doc.createNode({
267
name: 'Charlie',
268
age: 35,
269
email: 'charlie@example.com'
270
});
271
doc.add(['users'], newUser);
272
273
// Alias creation
274
const aliasNode = doc.createAlias(newUser, 'charlie');
275
doc.set(['admin'], aliasNode);
276
277
console.log(doc.toString());
278
```
279
280
## Advanced Features
281
282
### Comment Preservation
283
284
Documents preserve YAML comments and provide access to comment metadata.
285
286
```typescript { .api }
287
// Comments are preserved in nodes
288
const doc = parseDocument(`
289
# Main configuration
290
app:
291
name: MyApp # Application name
292
# Version information
293
version: 1.0.0
294
`);
295
296
// Access comments through node properties
297
if (isScalar(doc.contents?.get('name', true))) {
298
console.log(doc.contents.comment); // ' Application name'
299
}
300
```
301
302
### Error and Warning Handling
303
304
```typescript { .api }
305
const doc = parseDocument(`
306
invalid: [unclosed array
307
duplicate: key
308
duplicate: key
309
`);
310
311
// Check for errors
312
doc.errors.forEach(error => {
313
console.log(`Error: ${error.message}`);
314
if (error.pos) {
315
console.log(`Position: ${error.pos[0]}-${error.pos[1]}`);
316
}
317
});
318
319
// Check for warnings
320
doc.warnings.forEach(warning => {
321
console.log(`Warning: ${warning.message}`);
322
});
323
324
// Convert with error handling
325
try {
326
const data = doc.toJS();
327
} catch (error) {
328
console.log('Conversion failed:', error.message);
329
}
330
```