/** * Positional information for a YAML error, pointing at the offending * character in the source string. */ interface Mark { /** Zero-based column (characters into the current line). */ column: number; /** Zero-based line number. */ line: number; /** Zero-based absolute offset into the source string. */ position: number; /** A short excerpt of the source around the error, if available. */ snippet?: string; } /** * Base class for all errors raised by `@visulima/yaml`. */ declare class YAMLError extends Error { readonly mark?: Mark; constructor(message: string, mark?: Mark, source?: string); } /** * Raised when the parser encounters malformed YAML input. */ declare class YAMLParseError extends YAMLError { constructor(message: string, mark?: Mark, source?: string); } /** * Raised when a value cannot be represented as YAML during serialization. */ declare class YAMLStringifyError extends YAMLError { constructor(message: string, mark?: Mark, source?: string); } /** * A non-fatal notice (e.g. a duplicate mapping key) collected during parsing. */ declare class YAMLWarning extends YAMLError { constructor(message: string, mark?: Mark, source?: string); } /** * Source spans for block-mapping entries. * * Kept in its own module so the document layer can depend on these types * without pulling the `State` class into the public declaration graph. */ /** * Source span of one `key: value` entry inside a block mapping, recorded only * when `State.mappingRanges` is set (i.e. by `parseDocument`). The document * layer uses these to splice edits into the original text instead of * re-serializing, which is what preserves comments and formatting. */ interface MappingEntryRange { /** Column the key starts at — the indent a sibling entry must match. */ column: number; /** Offset just past the entry's value. */ end: number; key: string; /** Offset of the first character of the key. */ start: number; /** Offset of the first character of the value, or -1 when it is empty. */ valueStart: number; } /** Block mappings in a parse, keyed by the object each one produced. */ type MappingRanges = WeakMap; /** * Maps a source offset to a line and column. * * Errors already carry a resolved position, so this exists for callers that * hold offsets of their own — an editor mapping a node's span to a cursor * position, or a linter reporting against its own ranges. The parser fills it * in as it scans, which costs one array push per line and only when a counter * was supplied. */ declare class LineCounter { /** Offset at which each line begins. Line 1 always starts at 0. */ lineStarts: number[]; /** * Record the start of a new line. * * The parser re-scans on a speculative parse or a rewind, so the same break * can arrive more than once. Line starts are strictly increasing, so an * offset that is not past the last one has already been seen. */ addNewLine(offset: number): void; /** * Resolve an offset to a 1-indexed line and column. * * Binary search rather than a scan, so a lookup stays cheap on a large * document even when a caller resolves many offsets. */ linePos(offset: number): { col: number; line: number; }; } /** Which scalar-resolution rules to apply. */ type SchemaName = "core" | "failsafe" | "json" | "yaml-1.1"; /** One custom scalar type. */ interface ScalarTag { /** * Participate in *implicit* resolution — an untagged scalar matching * {@link ScalarTag.test} resolves through this tag. Without it the tag only * applies when written explicitly (`!!name value`). * @default false */ default?: boolean; /** Recognise a JS value as belonging to this tag, used when serializing. */ identify?: (value: unknown) => boolean; /** Turn the scalar's raw text into a value. */ resolve: (raw: string) => unknown; /** Render a value back to scalar text. Defaults to `String(value)`. */ stringify?: (value: unknown) => string; /** * The tag name. Either a local `!name` / `!!name`, or a fully qualified * `tag:domain,date:name`. */ tag: string; /** Pattern an untagged scalar must match for implicit resolution. */ test?: RegExp; } /** What the `customTags` option accepts. */ type CustomTags = ScalarTag[] | ((tags: ScalarTag[]) => ScalarTag[]); /** * How duplicate keys in a mapping are handled. * * - `error` (default): throw a `YAMLParseError`. * - `overwrite`: keep the last value. * - `ignore`: keep the first value. */ type DuplicateKeyBehavior = "error" | "ignore" | "overwrite"; /** Options accepted by `parse`. */ interface ParseOptions { /** * Extra scalar types. Each tag says how to recognise, resolve and render * one type; set `default` with a `test` pattern to have it participate in * implicit resolution as well as explicit `!!tag` use. */ customTags?: CustomTags; /** * How to treat repeated keys inside a single mapping. * @default "error" */ duplicateKeys?: DuplicateKeyBehavior; /** * Resolve integers to `BigInt` instead of `number`, so values beyond * `Number.MAX_SAFE_INTEGER` survive. Floats are unaffected. * @default false */ intAsBigInt?: boolean; /** * Collects the offset of every line break as the document is scanned, so * `lineCounter.linePos(offset)` can resolve any offset afterwards. */ lineCounter?: LineCounter; /** * Build mappings as `Map` rather than plain objects, which keeps complex * keys (sequences, mappings) as their native values instead of flattening * them to strings. * @default false */ mapAsMap?: boolean; /** * Maximum number of alias nodes that may be resolved. Guards against * "billion laughs" style alias-expansion attacks. * @default 100 */ maxAliasCount?: number; /** * Maximum nesting depth of collections. Guards against a deeply nested * document (`[[[[…`) exhausting the call stack with a `RangeError` that * escapes the `YAMLError` hierarchy. * @default 1000 */ maxDepth?: number; /** * Resolve `<<` merge keys. Disable to treat `<<` as an ordinary key. * @default true */ merge?: boolean; /** * Optional callback invoked for every non-fatal `YAMLWarning`. When * omitted, warnings are silently ignored. */ onWarning?: (warning: YAMLWarning) => void; /** * When `true`, a `__proto__` mapping key becomes an own data property * instead of being assigned through the inherited setter, so a document can * never reach the prototype chain. Merge keys (`<<`) honour this too. * @default true */ preventProtoPollution?: boolean; /** * Applied to every key/value pair after parsing, like the `JSON.parse` * reviver. Returning `undefined` drops the entry. */ reviver?: (key: unknown, value: unknown) => unknown; /** * Which scalar-resolution rules to apply. * * `core` (default) is YAML 1.2 core: `~`/`null`, `true`/`false`, decimal, * hex and octal ints, floats, `.inf`/`.nan`. * `failsafe` resolves nothing; every scalar stays a string. * `json` resolves only the JSON grammar; any other unquoted scalar is a * document error. * `yaml-1.1` is the older, wider set: `yes`/`no`/`on`/`off` as booleans, * `010` as octal, `0b` binaries, `1_000` underscores, sexagesimals, and * timestamps as `Date`. * * Defaults to `yaml-1.1` when {@link ParseOptions.version} is `"1.1"`. * @default "core" */ schema?: SchemaName; /** * Full YAML 1.2 strictness, on by default. The parser always rejects the * unambiguous spec violations (tabs as indentation, malformed directives, * deficient indentation, comments not separated by white space). With * `strict` it additionally rejects the corner cases that both `yaml` and * `js-yaml` accept but the spec forbids: a node property (anchor or tag) * carried onto a new line yet indented no deeper than its parent key; a * block mapping or sequence whose first entry sits on the document-start * line; two anchors or two tags on one node; and a block scalar whose * leading empty lines out-indent its content or that uses a tab for * indentation. Set `strict: false` to relax exactly those checks (closer to * `js-yaml`); it never changes the value of an accepted document, only * whether these malformed inputs throw. * @default true */ strict?: boolean; /** * Keep every mapping key a string, skipping scalar resolution for keys. * @default false */ stringKeys?: boolean; /** * YAML version to assume when the document carries no `%YAML` directive. * `"1.1"` selects the `yaml-1.1` schema unless {@link ParseOptions.schema} * says otherwise. * @default "1.2" */ version?: "1.1" | "1.2"; } /** Options accepted by `stringify`. */ interface StringifyOptions { /** * How to render a multi-line string: `literal` (`|`), `folded` (`>`), or * `false` to always use a quoted style. * @default true */ blockQuote?: "folded" | "literal" | boolean; /** * Force every collection to one style, overriding {@link StringifyOptions.flowLevel}. * @default "any" */ collectionStyle?: "any" | "block" | "flow"; /** * Extra scalar types used when serializing: a value claimed by a tag's * `identify` is written with that tag. */ customTags?: CustomTags; /** * Emit an explicit document-start marker (`---`) before the document. * @default false */ directives?: boolean; /** * String written for `false`. * @default "false" */ falseStr?: string; /** * Pad the inside of flow collections: `{ a: 1 }` rather than `{a: 1}`. * @default true */ flowCollectionPadding?: boolean; /** * Force flow style (`{a: 1, b: [2, 3]}`) for collections nested deeper than * this level. `-1` disables flow style entirely (everything is block * style). `0` makes the whole document flow style. * @default -1 */ flowLevel?: number; /** * When `true`, non-ASCII characters are escaped in double-quoted scalars. * @default false */ forceQuotes?: boolean; /** * Number of spaces used for each indentation level. * @default 2 */ indent?: number; /** * Indent block sequences inside a mapping under their key. * @default true */ indentSeq?: boolean; /** * Keep `undefined` values instead of dropping them, writing them as `null`. * @default false */ keepUndefined?: boolean; /** * Preferred maximum line width for folded scalars. `0` disables folding. * @default 80 */ lineWidth?: number; /** * String written for `null`. * @default "null" */ nullStr?: string; /** * A `JSON.stringify`-style replacer applied to every value before it is * serialized. Return `undefined` to omit the value. */ replacer?: (key: string, value: unknown) => unknown; /** * Prefer single quotes over double quotes when a string must be quoted. * @default false */ singleQuote?: boolean; /** * When `true`, keys with `undefined` values (and `undefined` array members) * are skipped instead of being written as `null`. * @default false */ skipInvalid?: boolean; /** * When `true`, object keys are emitted in sorted order. A comparator can be * supplied for custom ordering. * @default false */ sortKeys?: boolean | ((a: string, b: string) => number); /** * String written for `true`. * @default "true" */ trueStr?: string; } /** * A parsed YAML document plus the diagnostics from reading it. * * Unlike `parse`, constructing a document never throws for malformed input — * the failure is reported in {@link YAMLDocument.errors} and `contents` is * `null`. That lets a caller report the problem in its own words, and lets * `parseAllDocuments` keep going after one bad document. */ declare class YAMLDocument { #private; /** Parse errors. Empty when the document read cleanly. */ readonly errors: YAMLParseError[]; /** Non-fatal notices raised while reading. */ readonly warnings: YAMLWarning[]; /** The parsed value, or `null` when `errors` is non-empty. */ contents: unknown; constructor(source: string, result: { contents: unknown; errors: YAMLParseError[]; warnings: YAMLWarning[]; }, ranges: MappingRanges, stringifyOptions?: StringifyOptions); /** * The document's value as plain JavaScript, resolving aliases and merge * keys. * * `reviver` runs over the converted value the way `JSON.parse`'s does. It * belongs here rather than on the parse options because it rewrites plain * values, and the document holds a node tree until this point. */ toJS(options?: { reviver?: (key: unknown, value: unknown) => unknown; }): unknown; /** Alias of {@link YAMLDocument.toJS}, so `JSON.stringify` works directly. */ toJSON(): unknown; /** * Value at `path`, or `undefined` if any segment is missing. * * This reads from the converted value rather than walking the node tree. * Walking nodes cannot see through an `Alias` or a merge key — both are * resolved by the conversion, against an anchor map that only exists when * the walk starts at the root — so `get("b")` on `a: &x 1\nb: *x` used to * come back `undefined`. The conversion is memoised and dropped whenever an * edit changes the tree. */ getIn(path: ReadonlyArray): unknown; /** Value of a top-level key. */ get(key: number | string): unknown; /** Whether `path` resolves to something present in the document. */ hasIn(path: ReadonlyArray): boolean; /** Whether a top-level key is present. */ has(key: number | string): boolean; /** * Set the value at `path`, creating any missing intermediate mappings. * * The edit is a source splice, so comments, blank lines and key order * elsewhere in the file survive untouched. Only block mappings can be * edited: a path that runs through a flow collection (`{a: 1}`) or a * sequence throws, because there is no unambiguous place to splice. */ setIn(path: ReadonlyArray, value: unknown): void; /** Set a top-level key. */ set(key: number | string, value: unknown): void; /** The document source with every pending edit applied. */ toString(): string; } /** * The node model: an explicit tree of `Scalar`, `YAMLMap`, `YAMLSeq`, `Pair` * and `Alias`, mirroring `yaml`'s. * * `parse` deliberately never builds this — it produces native JavaScript values * in a single pass, which is where its speed comes from. The tree exists for * the cases native values cannot express: distinguishing a quoted `"1"` from * the number `1`, holding an anchor or a tag alongside a value, keeping a * collection's flow/block style, or walking a document generically. */ /** * Discriminant identifying a node's kind. * * A plain string field rather than `instanceof` so the guards keep working * across module instances — two copies of this package in one dependency tree * would otherwise produce nodes that fail each other's checks. */ type NodeKindName = "ALIAS" | "MAP" | "PAIR" | "SCALAR" | "SEQ"; /** How a scalar was written, preserved so it can be written back the same way. */ type ScalarStyle = "BLOCK_FOLDED" | "BLOCK_LITERAL" | "PLAIN" | "QUOTE_DOUBLE" | "QUOTE_SINGLE"; /** Fields every node may carry. */ interface NodeBase { /** Anchor name, without the `&`. */ anchor?: string; /** Comment written after the node, without the `#`. */ comment?: string; /** Comment written on the lines before the node. */ commentBefore?: string; /** Blank line before the node. */ spaceBefore?: boolean; /** Explicit tag, e.g. `!!str`. */ tag?: string; } /** A single value. */ declare class Scalar implements NodeBase { readonly kind: NodeKindName; value: T; anchor?: string; comment?: string; commentBefore?: string; spaceBefore?: boolean; tag?: string; /** The style it was written in, when known. */ type?: ScalarStyle; constructor(value: T); toJSON(): unknown; toString(): string; } /** A reference to an anchored node, written `*name`. */ declare class Alias { readonly kind: NodeKindName; /** The anchor name this points at. */ source: string; comment?: string; commentBefore?: string; spaceBefore?: boolean; constructor(source: string); toString(): string; } /** One `key: value` entry of a mapping. */ declare class Pair { readonly kind: NodeKindName; key: K; value: V; comment?: string; commentBefore?: string; spaceBefore?: boolean; constructor(key: K, value: V); toJSON(): unknown; } declare const isScalar: (value: unknown) => value is Scalar; declare const isAlias: (value: unknown) => value is Alias; declare const isPair: (value: unknown) => value is Pair; declare const isMap: (value: unknown) => value is YAMLMap; declare const isSeq: (value: unknown) => value is YAMLSeq; declare const isCollection: (value: unknown) => value is YAMLMap | YAMLSeq; declare const isNode: (value: unknown) => boolean; /** Shared behaviour of the two collection kinds. */ declare abstract class Collection implements NodeBase { anchor?: string; comment?: string; commentBefore?: string; /** Written in flow style (`[a, b]`) rather than block. */ flow?: boolean; spaceBefore?: boolean; tag?: string; abstract items: unknown[]; /** Read the value at `key`, or `undefined`. */ abstract get(key: unknown, keepScalar?: boolean): unknown; /** Replace or add the value at `key`. */ abstract set(key: unknown, value: unknown): void; /** Whether `key` is present. */ abstract has(key: unknown): boolean; /** Remove `key`, reporting whether anything was removed. */ abstract delete(key: unknown): boolean; /** Read the value at a path of keys. */ getIn(path: Iterable, keepScalar?: boolean): unknown; /** Whether a path of keys resolves. */ hasIn(path: Iterable): boolean; /** Set the value at a path, creating intermediate maps as needed. */ setIn(path: Iterable, value: unknown): void; /** Remove the value at a path. */ deleteIn(path: Iterable): boolean; toJSON(): unknown; } /** A mapping, holding `Pair` items in document order. */ declare class YAMLMap extends Collection { #private; readonly kind: NodeKindName; items: Pair[]; get(key: unknown, keepScalar?: boolean): unknown; set(key: unknown, value: unknown): void; has(key: unknown): boolean; delete(key: unknown): boolean; /** Append a pair without checking for an existing key. */ add(pair: Pair): void; } /** A sequence, indexed by position. */ declare class YAMLSeq extends Collection { readonly kind: NodeKindName; items: unknown[]; get(key: unknown, keepScalar?: boolean): unknown; set(key: unknown, value: unknown): void; has(key: unknown): boolean; delete(key: unknown): boolean; /** Append an item. */ add(value: unknown): void; } /** * Convert a node tree to plain JavaScript. * * `anchors` resolves aliases back to the value their anchor names, so a * document with shared references produces shared references rather than * duplicated copies. * * Merge keys are resolved here rather than while parsing, so the tree keeps the * `<<` pair and its alias and can still be written back out unchanged — the * same split the `yaml` reference makes. */ declare const toJS: (value: unknown, anchors?: Map) => unknown; /** Wrap a plain JavaScript value into a node tree. */ declare const createNode: (value: unknown) => unknown; /** * What a visitor returns: * * - `undefined` — carry on * - {@link SKIP} — do not descend into this node * - {@link BREAK} — stop the whole walk * - {@link REMOVE} — delete this node from its parent * - any node — replace this node in its parent, then descend into it * * The visitor is *not* re-invoked on a node it just returned (`yaml` does * re-invoke). Returning a node the visitor would itself replace therefore * terminates here instead of looping. */ type VisitorFunction = (key: number | string | null, node: unknown, path: ReadonlyArray) => unknown; /** Per-kind handlers; `Node` catches anything without a more specific entry. */ interface Visitor { Alias?: VisitorFunction; Map?: VisitorFunction; Node?: VisitorFunction; Pair?: VisitorFunction; Scalar?: VisitorFunction; Seq?: VisitorFunction; } /** Walk a node tree, applying `visitor` to each node. */ declare const visit: (node: unknown, visitor: Visitor) => void; /** * Parse the first document of a YAML string into a native JavaScript value. * * This is the `yaml`-style entry point. Use {@link parseAll} for multi-document * streams. * @example * ```ts * import { parse } from "@visulima/yaml"; * * parse("foo: bar"); // => { foo: "bar" } * ``` */ declare function parse(source: string, options?: ParseOptions): unknown; declare function parse(source: string, reviver?: ParseOptions["reviver"], options?: ParseOptions): unknown; /** * Parse every document of a multi-document YAML stream, returning them in order. * @example * ```ts * import { parseAll } from "@visulima/yaml"; * * parseAll("---\na: 1\n---\nb: 2"); // => [{ a: 1 }, { b: 2 }] * ``` */ declare const parseAll: (source: string, options?: ParseOptions) => unknown[]; /** * Serialize a JavaScript value to a YAML document string. * @example * ```ts * import { stringify } from "@visulima/yaml"; * * stringify({ foo: "bar" }); // => "foo: bar\n" * ``` */ declare function stringify(value: unknown, options?: StringifyOptions): string; declare function stringify(value: unknown, replacer?: StringifyOptions["replacer"] | unknown[] | null, options?: StringifyOptions | number | string): string; /** * `js-yaml`-compatible alias of {@link parse}. * * Unlike {@link parse}, this defaults to `strict: false` to match `js-yaml`'s * leniency. Pass `{ strict: true }` for full YAML 1.2 strictness. */ declare const load: (source: string, options?: ParseOptions) => unknown; /** * `js-yaml`-compatible multi-document loader. * * When an `iterator` is supplied it is invoked once per document (matching the * `js-yaml` signature); otherwise the parsed documents are returned as an array. * Like {@link load}, this defaults to `strict: false`. */ declare function loadAll(source: string, iterator: (document: unknown) => void, options?: ParseOptions): void; declare function loadAll(source: string, options?: ParseOptions): unknown[]; /** * `js-yaml`-compatible alias of {@link stringify}. */ declare const dump: (value: unknown, options?: StringifyOptions) => string; /** * Parse a document into a node tree — `Scalar` / `YAMLMap` / `YAMLSeq` / `Pair` * / `Alias` — preserving what native values cannot: scalar styles, tags, * anchors, and aliases as references rather than resolved copies. * * Separate from {@link parse}, which never builds a tree; that is what keeps * its single-pass path fast. */ declare const parseNodes: (source: string, options?: ParseOptions) => unknown; /** Every document of a stream as node trees. */ declare const parseAllNodes: (source: string, options?: ParseOptions) => unknown[]; /** * Parse the first document without throwing, returning a {@link YAMLDocument} * that carries its own diagnostics and supports comment-preserving edits. * @example * ```ts * const document = parseDocument("a: 1 # keep me"); * * document.setIn(["b", "c"], 2); * document.toString(); // "a: 1 # keep me\nb:\n c: 2\n" * ``` */ declare const parseDocument: (source: string, options?: ParseOptions) => YAMLDocument; /** * Parse every document of a stream without throwing. A malformed document * reports its error and does not stop the ones after it. */ declare const parseAllDocuments: (source: string, options?: ParseOptions) => YAMLDocument[]; export { Alias, Collection, type DuplicateKeyBehavior, LineCounter, type Mark, type NodeKindName, Pair, type ParseOptions, Scalar, type ScalarStyle, type StringifyOptions, type Visitor, type VisitorFunction, YAMLDocument, YAMLError, YAMLMap, YAMLParseError, YAMLSeq, YAMLStringifyError, YAMLWarning, createNode, dump, isAlias, isCollection, isMap, isNode, isPair, isScalar, isSeq, load, loadAll, parse, parseAll, parseAllDocuments, parseAllNodes, parseDocument, parseNodes, stringify, toJS, visit };