### Set up development environment with git clone, submodules, and npm install Source: https://github.com/eemeli/yaml/blob/main/docs/CONTRIBUTING.md Use this shell sequence to clone the yaml repository and install dependencies. Requires npm v7 or later. The git submodule update command fetches the docs and test suite data, which is required by the tests. Run npm test to verify the setup. ```sh git clone https://github.com/eemeli/yaml.git # or your own fork cd yaml git submodule update --init # required by tests; also fetches the docs & test suite data npm install # npm v7 or later is required npm test # just to be sure ``` -------------------------------- ### YAMLSet methods usage example Source: https://github.com/eemeli/yaml/blob/main/docs/05_content_nodes.md Demonstrates using YAMLSet methods (add, delete, get, has) on a YAML document. Shows how to set, get, and delete values, and the resulting document state. Includes a TypeError when calling set on a scalar value. ```javascript const doc = new YAML.Document({ a: 1, b: [2, 3] }) // { a: 1, b: [ 2, 3 ] } doc.set('c', 4) // { a: 1, b: [ 2, 3 ], c: 4 } doc.get('b').push(5) // { a: 1, b: [ 2, 3, 5 ], c: 4 } doc.set('c', 42) // { a: 1, b: [ 2, 3, 5 ], c: 42 } doc.get('c').set('x') // TypeError: doc.get(...).set is not a function doc.value.delete('c') // { a: 1, b: [ 2, 3, 5 ] } doc.get('b').splice(1, 1) // { a: 1, b: [ 2, 5 ] } doc.get('a') // Scalar { value: 1 } doc.get(doc.createNode('a')) // Scalar { value: 1 } doc.get('b')[1] // Scalar { value: 5 } doc.get('c') // undefined ``` -------------------------------- ### Example YAML file (file.yml) Source: https://github.com/eemeli/yaml/blob/main/docs/02_parse_stringify.md Example YAML file used in the documentation to demonstrate parsing and stringifying. It contains two top-level keys, each with a list of strings. ```yaml # file.yml YAML: - A human-readable data serialization language - https://en.wikipedia.org/wiki/YAML yaml: - A complete JavaScript implementation - https://www.npmjs.com/package/yaml ``` -------------------------------- ### Install yaml with npm or deno Source: https://github.com/eemeli/yaml/blob/main/README.md Use this command to install the yaml library. The npm command installs the latest 'next' version with an exact version pin, while the deno command adds the package from jsr. Choose the command that matches your package manager. ```sh npm install --save-exact yaml@next # or deno add jsr:@eemeli/yaml ``` -------------------------------- ### YAML.parse examples Source: https://github.com/eemeli/yaml/blob/main/docs/02_parse_stringify.md Demonstrates YAML.parse with a number, a sequence, and a file read. The reviver and options arguments are optional. Throws on error and may log warnings via console.warn. Only supports a single YAML document. ```javascript import fs from 'fs' import YAML from 'yaml' YAML.parse('3.14159') // 3.14159 YAML.parse('[ true, false, maybe, null ]\n') // [ true, false, 'maybe', null ] const file = fs.readFileSync('./file.yml', 'utf8') YAML.parse(file) // { YAML: // [ 'A human-readable data serialization language', // 'https://en.wikipedia.org/wiki/YAML' ], // yaml: // [ 'A complete JavaScript implementation', // 'https://www.npmjs.com/package/yaml' ] } ``` -------------------------------- ### Accessing document values with get, getPair, and array methods Source: https://github.com/eemeli/yaml/blob/main/docs/04_documents.md Shows how to access top-level collection items using get and getPair, and how to manipulate array-like values with push, splice, and at. The example parses a YAML document and demonstrates the returned Scalar and YAMLSeq objects. ```javascript const doc = parseDocument('a: 1\nb: [2, 3]\n') doc.get('a') // Scalar { value: 1 } doc.getPair('a') // Pair { key: Scalar { value: 'a' }, value: Scalar { value: 1 } } doc.get('b')[0] // Scalar { value: 2 } doc.get('b').push(4) // 3 doc.get('b').splice(1, 1) // YAMLSeq(1) [ Scalar { value: 3 } ] doc.get('b').at(1) // 4 ``` -------------------------------- ### JavaScript output for YAML 1.1 example Source: https://github.com/eemeli/yaml/blob/main/docs/10_yaml_syntax.md This JavaScript object shows the parsed output of the preceding YAML 1.1 example: 'Yes' becomes boolean true, octal '014' becomes 12, sexagesimal '3:25:45' becomes 12345, and the binary block is decoded into a Buffer. ```javascript { true: true, octal: 12, sexagesimal: 12345, picture: Buffer [Uint8Array] [ 71, 73, 70, 56, 57, 97, 12, 0, 12, 0, 132, 0, 0, 255, 255, 247, 245, 245, 238, 233, 233, 229, 102, 102, 102, 0, 0, 0, 231, 231, 231, 94, 94, 94, 243, 243, 237, 142, 142, 142, 224, 224, 224, 159, 159, 159, 147, 147, 147, 167, 167, 167, 158, 158, 158, 105, 94, 16, 39, 32, 130, 10, 1, 0, 59 ] } ``` -------------------------------- ### new Parser(onNewLine?: (offset: number) => void) Source: https://github.com/eemeli/yaml/blob/main/docs/07_parsing_yaml.md Creates a new Parser instance. If an onNewLine callback is provided, it is called with the start position of each new line during parsing. ```APIDOC ## new Parser(onNewLine?: (offset: number) => void) ### Description Creates a new Parser instance. If an onNewLine callback is provided, it is called with the start position of each new line during parsing. ### Constructor `new Parser(onNewLine?: (offset: number) => void)` ### Parameters - **onNewLine** (function) - Optional - Callback invoked with the start position (offset) of each new line, including the start of input. ### Returns A new Parser instance. ``` -------------------------------- ### YAML 1.0 example with legacy tag syntax Source: https://github.com/eemeli/yaml/blob/main/docs/10_yaml_syntax.md This YAML snippet shows YAML 1.0 syntax with a version directive and custom tag shorthands using '!int', '!str', '!!ball', and '!^customer'. This syntax differs significantly from YAML 1.1 and later versions. ```yaml %YAML:1.0 --- date: 2001-01-23 number: !int '123' string: !str 123 pool: !!ball { number: 8 } invoice: !domain.tld,2002/^invoice customers: !seq - !^customer given : Chris family : Dumars ``` -------------------------------- ### Alias class definition and usage example Source: https://github.com/eemeli/yaml/blob/main/docs/05_content_nodes.md Shows the Alias class interface and an example of parsing YAML with anchors and aliases, modifying the aliased object, and stringifying. Demonstrates circular reference support and autogenerated anchors. ```typescript class Alias implements NodeBase { source: string resolve(doc: Document): Scalar | YAMLMap | YAMLSeq | undefined } ``` ```javascript const obj = YAML.parse('[ &x { X: 42 }, Y, *x ]') // => [ { X: 42 }, 'Y', { X: 42 } ] obj[2].Z = 13 // => [ { X: 42, Z: 13 }, 'Y', { X: 42, Z: 13 } ] YAML.stringify(obj) // - &a1 // X: 42 // Z: 13 // - Y // - *a1 ``` -------------------------------- ### ToJS mapAsMap option example Source: https://github.com/eemeli/yaml/blob/main/docs/03_options.md Shows the difference in output when parsing a mapping with object keys, with and without the mapAsMap option. The first parse returns an object with stringified keys, while the second returns a Map with the original key objects. ```javascript parse('{[1, 2]: many}') // { '[ 1, 2 ]': 'many' } ``` ```javascript parse('{[1, 2]: many}', { mapAsMap: true }) // Map { [ 1, 2 ] => 'many' } ``` -------------------------------- ### YAML 1.1 example showing legacy types and binary data Source: https://github.com/eemeli/yaml/blob/main/docs/10_yaml_syntax.md This YAML snippet demonstrates YAML 1.1 syntax with legacy type handling: boolean 'yes', octal '014', sexagesimal '3:25:45', and a binary string using a block literal. These features are changed or removed in YAML 1.2. ```yaml %YAML 1.1 --- true: Yes octal: 014 sexagesimal: 3:25:45 picture: !!binary | R0lGODlhDAAMAIQAAP//9/X 17unp5WZmZgAAAOfn515eXv Pz7Y6OjuDg4J+fn5OTk6enp 56enmleECcgggoBADs= ``` -------------------------------- ### Merge key example with parse() Source: https://github.com/eemeli/yaml/blob/main/docs/03_options.md Demonstrates using a YAML 1.1 merge key (`<<`) with the `merge: true` option. The source defines a base map and a target that merges it, overriding the `b` key. The result shows the merged target with `a: 1` and `b: 'base'`. ```javascript const src = ` source: &base { a: 1, b: 2 } target: <<: *base b: base` const mergeResult = parse(src, { merge: true }) mergeResult.target // { a: 1, b: 'base' } ``` -------------------------------- ### Read and parse a YAML file with Node.js Source: https://github.com/eemeli/yaml/blob/main/README.md Shows how to read a YAML file from disk using Node.js fs module and parse it with the yaml library's parse function. The example reads './file.yml' and outputs the parsed JavaScript object, which contains the same data as the YAML file. ```js import fs from 'node:fs' import { parse } from 'yaml' const file = fs.readFileSync('./file.yml', 'utf8') parse(file) // { YAML: // [ 'A human-readable data serialization language', // 'https://en.wikipedia.org/wiki/YAML' ], // yaml: // [ 'A complete JavaScript implementation', // 'https://www.npmjs.com/package/yaml' ] } ``` -------------------------------- ### lineCounter.addNewLine(offset: number) Source: https://github.com/eemeli/yaml/blob/main/docs/07_parsing_yaml.md Adds the starting index of a new line. Should be called in order, or the internal lineStarts array will need to be sorted before calling linePos(). Bound to the instance, so may be used directly as a callback. ```APIDOC ## lineCounter.addNewLine(offset: number) ### Description Adds the starting index of a new line. Should be called in order, or the internal `lineStarts` array will need to be sorted before calling `linePos()`. Bound to the instance, so may be used directly as a callback. ### Method addNewLine ### Parameters - **offset** (number) - Required - The starting index of the new line. ### Returns Void ### Example ```js const lineCounter = new LineCounter() lineCounter.addNewLine(5) ``` ``` -------------------------------- ### Parse and stringify YAML with yaml package Source: https://github.com/eemeli/yaml/blob/main/README.md Shows how to use the parse and stringify functions from the 'yaml' package. The parse function converts a YAML string into a JavaScript value, while stringify converts a value back into a YAML string. The example demonstrates parsing an array with mixed types and stringifying arrays and objects, including block strings. ```js import { parse, stringify } from 'yaml' parse('[ true, false, maybe, null, 3.14159 ]') // [ true, false, 'maybe', null, 3.14159 ] stringify([true, false, 'maybe', null, 3.14159]) // `- true // - false // - maybe // - null // - 3.14159 // ` stringify({ number: 3, plain: 'string', block: 'two\nlines\n' }) // `number: 3 // plain: string // block: | // two // lines // ` ``` -------------------------------- ### Create Document with YAMLSeq and createPair Source: https://github.com/eemeli/yaml/blob/main/docs/05_content_nodes.md Imports Document and YAMLSeq, creates a new Document with mixed values, pushes a pair created with createPair, and shows the stringified output. ```javascript import { Document, YAMLSeq } from 'yaml' const doc = new Document([ 'some values', 42, { including: 'objects', 3: 'a string' } ]) doc.value.push(doc.createPair(1, 'a number')) doc.toString() // - some values // - 42 // - "3": a string // including: objects // - 1: a number ``` -------------------------------- ### createPair(key, value, options?) Source: https://github.com/eemeli/yaml/blob/main/docs/04_documents.md Recursively wraps key and value into a Pair object. See Creating Nodes for more information. ```APIDOC ## createPair(key, value, options?) ### Description Recursively wraps `key` and `value` into a `Pair` object. See [Creating Nodes](#creating-nodes) for more information. ### Method createPair ### Parameters - **key** (any) - Required - The key for the pair. - **value** (any) - Required - The value for the pair. - **options** (object) - Optional - Options for node creation. ### Returns `Pair` ``` -------------------------------- ### CST.visit example: inserting a scalar into a sequence Source: https://github.com/eemeli/yaml/blob/main/docs/07_parsing_yaml.md Walks a CST document, finds the scalar 'bar' in a sequence, and inserts a new scalar 'bing' before it. The visitor returns the new index to continue traversal. The example then stringifies the modified CST to show the result. ```javascript const [doc] = new Parser().parse('[ foo, bar, baz ]') CST.visit(doc, (item, path) => { if (!CST.isScalar(item.value)) return const scalar = CST.resolveAsScalar(item.value) if (scalar?.value === 'bar') { const parent = CST.visit.parentCollection(doc, path) const idx = path[path.length - 1][1] const { indent } = item.value parent.items.splice(idx, 0, { start: item.start.slice(), value: CST.createScalar('bing', { end: [], indent }) }) return idx + 2 } }) CST.stringify(doc) > '[ foo, bing, bar, baz ]' ``` -------------------------------- ### parse() with intAsBigInt and schema options Source: https://github.com/eemeli/yaml/blob/main/docs/03_options.md Shows how the parse() function behaves with different options: default parsing yields a number, intAsBigInt: true yields a BigInt, and schema: 'failsafe' yields a string. ```javascript import { parse, stringify } from 'yaml' parse('number: 999') // { number: 999 } parse('number: 999', { intAsBigInt: true }) // { number: 999n } parse('number: 999', { schema: 'failsafe' }) // { number: '999' } ``` -------------------------------- ### YAML tag resolution examples Source: https://github.com/eemeli/yaml/blob/main/docs/10_yaml_syntax.md Shows how YAML.parse handles explicit tags and unresolved tags. The first two lines parse strings with and without an explicit !!int tag. The third example uses a custom tag prefix and demonstrates that unresolved tags produce a warning and fall back to string parsing. ```javascript YAML.parse('"42"') // '42' YAML.parse('!!int "42"') // 42 YAML.parse(` %TAG ! tag:example.com,2018:app/ --- !foo 42 `) // YAMLWarning: // The tag tag:example.com,2018:app/foo is unavailable, // falling back to tag:yaml.org,2002:str // '42' ``` -------------------------------- ### get(key) Source: https://github.com/eemeli/yaml/blob/main/docs/04_documents.md Returns the top-level collection item at the given key, or undefined if not found. ```APIDOC ## get(key) ### Description Returns top-level collection item at `key`, or `undefined` if not found. ### Method get ### Parameters - **key** (any) - Required - The key to look up. ### Returns `Node | Pair` ### Example ```js const doc = parseDocument('a: 1\nb: [2, 3]\n') doc.get('a') // Scalar { value: 1 } doc.get('b')[0] // Scalar { value: 2 } doc.get('b').push(4) // 3 doc.get('b').splice(1, 1) // YAMLSeq(1) [ Scalar { value: 3 } ] doc.get('b').at(1) // 4 ``` ``` -------------------------------- ### CST.visit.parentCollection(cst, path) Source: https://github.com/eemeli/yaml/blob/main/docs/07_parsing_yaml.md Gets the immediate parent collection of the item at the given path. Throws an error if the collection is not found. ```APIDOC ## CST.visit.parentCollection(cst, path) ### Description Gets the immediate parent collection of the item at the specified path from the CST root. Throws an error if the collection is not found, which should never happen if the item exists. ### Method CST.visit.parentCollection ### Parameters #### cst (CST.Document | CST.CollectionItem) - Required The root CST document or collection item to search from. #### path (Array<['key' | 'value', number]>) - Required The path steps from the root to the item whose parent collection is desired. ### Returns - **CST.BlockMap | CST.BlockSequence | CST.FlowCollection** - The immediate parent collection of the item at the given path. ### Errors - Throws an error if the collection is not found. ``` -------------------------------- ### Create and stringify a Document with comments Source: https://github.com/eemeli/yaml/blob/main/docs/04_documents.md Imports the Document class from 'yaml', creates a new document with an array of values, sets a commentBefore property, and stringifies it. The output shows the comment separated by a blank line from the document content. ```JavaScript import { Document } from 'yaml' const doc = new Document(['some', 'values', { balloons: 99 }]) doc.commentBefore = ' A commented document' String(doc) // # A commented document // // - some // - values // - balloons: 99 ``` -------------------------------- ### new Composer(options?) Source: https://github.com/eemeli/yaml/blob/main/docs/07_parsing_yaml.md Creates a new Document composer. Does not include an internal Parser instance, so an external one will be needed. Options are used during composition and passed to the new Document constructor. ```APIDOC ## new Composer(options?) ### Description Creates a new Document composer. Does not include an internal Parser instance, so an external one will be needed. Options are used during composition and passed to the new Document constructor. ### Method Constructor ### Parameters #### Options - **options** (ParseOptions & DocumentOptions & SchemaOptions) - Optional - Options to be used during composition and passed to the new Document constructor. ### Example ```js import { Composer, Parser } from 'yaml' const src = 'foo: bar\nfee: [24, "42"]' const tokens = new Parser().parse(src) const docs = new Composer().compose(tokens) console.log(docs.map(doc => doc.toJS())) > [{ foo: 'bar', fee: [24, '42'] }] ``` ``` -------------------------------- ### Using customTags to parse timestamps Source: https://github.com/eemeli/yaml/blob/main/docs/06_custom_tags.md Demonstrates the customTags option with the 'timestamp' tag. Shows that without the tag, the timestamp is parsed as a string, and with the tag, it becomes a Date instance. The example uses parse and parseDocument from the yaml package. ```javascript import { parse, parseDocument } from 'yaml' parse('2001-12-15 2:59:43') // '2001-12-15 2:59:43' parse('!!timestamp 2001-12-15 2:59:43') // 2001-12-15T02:59:43.000Z (Date instance) const doc = parseDocument('2001-12-15 2:59:43', { customTags: ['timestamp'] }) doc.value.value.toDateString() // 'Sat Dec 15 2001' ``` -------------------------------- ### YAML.stringify examples Source: https://github.com/eemeli/yaml/blob/main/docs/02_parse_stringify.md Demonstrates YAML.stringify with a number, an array, and an object. The returned string always ends with a newline. The replacer and options arguments are optional; using a number or string as options sets the indent option. Strings are serialized in the simplest style based on content. ```javascript YAML.stringify(3.14159) // '3.14159\n' YAML.stringify([true, false, 'maybe', null]) // `- true // - false // - maybe // - null // ` YAML.stringify({ number: 3, plain: 'string', block: 'two\nlines\n' }) // `number: 3 // plain: string // block: > // two // // lines // ` ``` -------------------------------- ### Import Scalar, visit, and collection classes Source: https://github.com/eemeli/yaml/blob/main/README.md Imports Scalar, visit, visitAsync, YAMLMap, and YAMLSeq from the yaml package. These are used for creating and manipulating content nodes, visiting and modifying nodes in the AST, and working with collections. ```js import { Scalar, visit, visitAsync, YAMLMap, YAMLSeq } from 'yaml' ``` -------------------------------- ### Compose tokens into documents with Composer Source: https://github.com/eemeli/yaml/blob/main/docs/07_parsing_yaml.md Imports Composer and Parser, parses a YAML source string into CST tokens, then composes them into documents. Logs the resulting JS objects, which match the expected output. ```js import { Composer, Parser } from 'yaml' const src = 'foo: bar\nfee: [24, "42"]' const tokens = new Parser().parse(src) const docs = new Composer().compose(tokens) console.log(docs.map(doc => doc.toJS())) > [{ foo: 'bar', fee: [24, '42'] }] ``` -------------------------------- ### YAML.visit(node, visitor): void Source: https://github.com/eemeli/yaml/blob/main/docs/05_content_nodes.md Applies a visitor function to an AST node or document, walking the tree depth-first. The visitor receives key, node, and path arguments, and its return value controls traversal (e.g., SKIP, BREAK, REMOVE, replace node, or set next index). ```APIDOC ## YAML.visit(node, visitor): void ### Description Applies a visitor to an AST node or document. Walks through the tree (depth-first) starting from `node`, calling a `visitor` function with three arguments: `key`, `node`, and `path`. The return value of the visitor may be used to control the traversal. ### Method Function call ### Endpoint YAML.visit(node, visitor) ### Parameters #### Function Parameters - **node** (Node) - Required - The AST node or document to start traversal from. - **visitor** (Function | Object) - Required - A visitor function or an object with separate visitor functions for each node type (`Map`, `Pair`, `Seq`, `Alias`, `Scalar`). The visitor function receives `key`, `node`, and `path` arguments. ### Return Value - **void** - This function does not return a value. ### Visitor Return Values - **undefined** (default) - Do nothing and continue. - **YAML.visit.SKIP** - Do not visit the children of this node, continue with next sibling. - **YAML.visit.BREAK** - Terminate traversal completely. - **YAML.visit.REMOVE** - Remove the current node, then continue with the next one. - **Node** - Replace the current node, then continue by visiting it. - **number** - While iterating the items of a sequence or map, set the index of the next step. ### Visitor Arguments - **key** - For sequence values and map `Pair`, the node's index in the collection. Within a `Pair`, `'key'` or `'value'`, correspondingly. `null` for the root node. - **node** - The current node. - **path** - The ancestry of the current node. ### Example ```js YAML.visit(doc, { Pair(_, pair) { if (pair.key?.value === '3') return YAML.visit.REMOVE }, Scalar(key, node) { if ( key !== 'key' && typeof node.value === 'string' && node.type === 'PLAIN' ) { node.type = 'QUOTE_SINGLE' } } }) ``` ### Notes - If `visitor` is a single function, it will be called with all values encountered in the tree, including `null` values. - Alternatively, separate visitor functions may be defined for each `Map`, `Pair`, `Seq`, `Alias` and `Scalar` node. - To define the same visitor function for more than one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar) and `Node` (alias, map, seq & scalar) targets. Of all these, only the most specific defined one will be used for each node. ``` -------------------------------- ### Define custom tags and stringify example Source: https://github.com/eemeli/yaml/blob/main/docs/06_custom_tags.md Defines custom tags for RegExp, shared Symbol, null-prototype objects, and Error instances, then stringifies an object using them. The output shows the resulting YAML with custom tags. Custom collection types may provide a nodeClass extending YAMLMap or YAMLSeq. ```javascript import { YAMLMap, stringify } from 'yaml' import { stringifyString } from 'yaml/util' const regexp = { identify: value => value instanceof RegExp, tag: '!re', resolve(str) { const match = str.match(/^\/([\s\S]+)\/([gimuy]*)$/) if (!match) throw new Error('Invalid !re value') return new RegExp(match[1], match[2]) } } const sharedSymbol = { identify: value => value?.constructor === Symbol, tag: '!symbol/shared', resolve: str => Symbol.for(str), stringify(item, ctx, onComment, onChompKeep) { const key = Symbol.keyFor(item.value) if (key === undefined) throw new Error('Only shared symbols are supported') return stringifyString({ value: key }, ctx, onComment, onChompKeep) } } class YAMLNullObject extends YAMLMap { tag = '!nullobject' toJS(doc, ctx) { const obj = super.toJS(doc, ctx, Object) return Object.assign(Object.create(null), obj) } } const nullObject = { tag: '!nullobject', collection: 'map', nodeClass: YAMLNullObject, createNode(nc, obj) { return YAMLNullObject.create(nc, obj) }, identify: v => !!(typeof v === 'object' && v && !Object.getPrototypeOf(v)) } // slightly more complicated object type class YAMLError extends YAMLMap { tag = '!error' toJS(doc, ctx) { const { name, message, stack, ...rest } = super.toJS(doc, ctx, Object) // craft the appropriate error type const Cls = name === 'EvalError' ? EvalError : name === 'RangeError' ? RangeError : name === 'ReferenceError' ? ReferenceError : name === 'SyntaxError' ? SyntaxError : name === 'TypeError' ? TypeError : name === 'URIError' ? URIError : Error if (Cls.name !== name) { Object.defineProperty(er, 'name', { value: name, enumerable: false, configurable: true }) } Object.defineProperty(er, 'stack', { value: stack, enumerable: false, configurable: true }) return Object.assign(er, rest) } } const error = { tag: '!error', collection: 'map', nodeClass: YAMLError, createNode(nc, obj) { const { name, message, stack } = obj // ensure these props remain, even if not enumerable return YAMLNullObject.create(nc, { ...obj, name, message, stack }) }, identify: v => !!(typeof v === 'object' && v && v instanceof Error) } stringify( { regexp: /foo/gi, symbol: Symbol.for('bar'), nullobj: Object.assign(Object.create(null), { a: 1, b: 2 }), error: new Error('This was an error') }, { customTags: [regexp, sharedSymbol, nullObject, error] } ) // regexp: !re /foo/gi // symbol: !symbol/shared bar // nullobj: !nullobject // a: 1 // b: 2 // error: !error // name: Error // message: 'This was an error' // stack: | // at some-file.js:1:3 ``` -------------------------------- ### Use lex() to tokenize a YAML string Source: https://github.com/eemeli/yaml/blob/main/docs/07_parsing_yaml.md Calls the lex function with a sample YAML string and prints the resulting token array using console.dir. The output shows the token sequence including control characters. ```javascript import { lex } from 'yaml' const tokens = lex('foo: bar\nfee:\n [24,"42"]\n') console.dir(tokens) > [ '\x02', '\x1F', 'foo', ':', ' ', '\x1F', 'bar', '\n', '\x1F', 'fee', ':', '\n', ' ', '[', '\x1F', '24', ',', '"42"', ']', '\n' ] ``` -------------------------------- ### createNode(value, options?) Source: https://github.com/eemeli/yaml/blob/main/docs/04_documents.md Recursively wraps any input with appropriate Node containers. See Creating Nodes for more information. ```APIDOC ## createNode(value, options?) ### Description Recursively wraps any input with appropriate `Node` containers. See [Creating Nodes](#creating-nodes) for more information. ### Method createNode ### Parameters - **value** (any) - Required - The value to wrap. - **options** (object) - Optional - Options for node creation. ### Returns `Node` ``` -------------------------------- ### Schema option examples: core, failsafe, json, yaml-1.1 Source: https://github.com/eemeli/yaml/blob/main/docs/03_options.md Shows how the schema option affects parsing of scalar values. The default core schema parses '3' as a number, while failsafe keeps it as a string. The json schema throws a SyntaxError for 'No', while yaml-1.1 parses it as false. The version option also enables yaml-1.1 behavior. ```javascript parse('3') // 3 (Using YAML 1.2 core schema by default) parse('3', { schema: 'failsafe' }) // '3' parse('No') // 'No' parse('No', { schema: 'json' }) // SyntaxError: Unresolved plain scalar "No" parse('No', { schema: 'yaml-1.1' }) // false parse('No', { version: '1.1' }) // false ``` -------------------------------- ### stringify with defaultStringType and nullStr options Source: https://github.com/eemeli/yaml/blob/main/docs/03_options.md Shows how to pass options to stringify() to control string quoting and null representation. The output is shown in the comment lines. ```javascript stringify( { this: null, that: 'value' }, { defaultStringType: 'QUOTE_SINGLE', nullStr: '~' } ) // 'this': ~ // 'that': 'value' ```