id
int64
0
3.78k
code
stringlengths
13
37.9k
declarations
stringlengths
16
64.6k
0
function combineFuncs(a: TestType, b: TestType): TestType { return (elem: AnyNode) => a(elem) || b(elem); }
type TestType = (elem: AnyNode) => boolean;
1
function compileTest(options: TestElementOpts): TestType | null { const funcs = Object.keys(options).map((key) => { const value = options[key]; return Object.prototype.hasOwnProperty.call(Checks, key) ? Checks[key](value) : getAttribCheck(key, value); }); return func...
interface TestElementOpts { tag_name?: string | ((name: string) => boolean); tag_type?: string | ((name: string) => boolean); tag_contains?: string | ((data?: string) => boolean); [attributeName: string]: | undefined | string | ((attributeValue: string) => boolean); }
2
function testElement(options: TestElementOpts, node: AnyNode): boolean { const test = compileTest(options); return test ? test(node) : true; }
interface TestElementOpts { tag_name?: string | ((name: string) => boolean); tag_type?: string | ((name: string) => boolean); tag_contains?: string | ((data?: string) => boolean); [attributeName: string]: | undefined | string | ((attributeValue: string) => boolean); }
3
function getElements( options: TestElementOpts, nodes: AnyNode | AnyNode[], recurse: boolean, limit = Infinity ): AnyNode[] { const test = compileTest(options); return test ? filter(test, nodes, recurse, limit) : []; }
interface TestElementOpts { tag_name?: string | ((name: string) => boolean); tag_type?: string | ((name: string) => boolean); tag_contains?: string | ((data?: string) => boolean); [attributeName: string]: | undefined | string | ((attributeValue: string) => boolean); }
4
function anchorExists(doc: Document, anchor: string): boolean { let found = false visit(doc, { Value(_key: unknown, node: Node) { if (node.anchor === anchor) { found = true return visit.BREAK } } }) return found }
interface Document { type: 'document' offset: number start: SourceToken[] value?: Token end?: SourceToken[] }
5
function anchorExists(doc: Document, anchor: string): boolean { let found = false visit(doc, { Value(_key: unknown, node: Node) { if (node.anchor === anchor) { found = true return visit.BREAK } } }) return found }
class Document<T extends Node = Node> { declare readonly [NODE_TYPE]: symbol /** A comment before this Document */ commentBefore: string | null = null /** A comment immediately after this Document */ comment: string | null = null /** The document contents. */ contents: T | null directives?: Directiv...
6
(error: YAMLError) => { if (error.pos[0] === -1) return error.linePos = error.pos.map(pos => lc.linePos(pos)) as | [LinePos] | [LinePos, LinePos] const { line, col } = error.linePos[0] error.message += ` at line ${line}, column ${col}` let ci = col - 1 let lineStr = src .subst...
class YAMLError extends Error { name: 'YAMLParseError' | 'YAMLWarning' code: ErrorCode message: string pos: [number, number] linePos?: [LinePos] | [LinePos, LinePos] constructor( name: YAMLError['name'], pos: [number, number], code: ErrorCode, message: string ) { super() this.name...
7
function parseOptions(options: ParseOptions) { const prettyErrors = options.prettyErrors !== false const lineCounter = options.lineCounter || (prettyErrors && new LineCounter()) || null return { lineCounter, prettyErrors } }
type ParseOptions = { /** * Whether integers should be parsed into BigInt rather than number values. * * Default: `false` * * https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/BigInt */ intAsBigInt?: boolean /** * Include a `srcToken` value on each parsed `Node`, ...
8
function debug(logLevel: LogLevelId, ...messages: any[]) { if (logLevel === 'debug') console.log(...messages) }
type LogLevelId = 'silent' | 'error' | 'warn' | 'debug'
9
function warn(logLevel: LogLevelId, warning: string | Error) { if (logLevel === 'debug' || logLevel === 'warn') { if (typeof process !== 'undefined' && process.emitWarning) process.emitWarning(warning) else console.warn(warning) } }
type LogLevelId = 'silent' | 'error' | 'warn' | 'debug'
10
(a: ParsedNode, b: ParsedNode) => boolean
type ParsedNode = | Alias.Parsed | Scalar.Parsed | YAMLMap.Parsed | YAMLSeq.Parsed
11
(tags: Tags) => Tags
type Tags = Array<ScalarTag | CollectionTag | TagId>
12
(a: Pair, b: Pair) => number
class Pair<K = unknown, V = unknown> { declare readonly [NODE_TYPE]: symbol /** Always Node or null when parsed, but can be set to anything. */ key: K /** Always Node or null when parsed, but can be set to anything. */ value: V | null /** The CST token that was composed into this pair. */ declare srcT...
13
function stringifyToken(token: Token) { switch (token.type) { case 'block-scalar': { let res = '' for (const tok of token.props) res += stringifyToken(tok) return res + token.source } case 'block-map': case 'block-seq': { let res = '' for (const item of token.items) res +...
type Token = | SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection
14
function stringifyItem({ start, key, sep, value }: CollectionItem) { let res = '' for (const st of start) res += st.source if (key) res += stringifyToken(key) if (sep) for (const st of sep) res += st.source if (value) res += stringifyToken(value) return res }
type CollectionItem = { start: SourceToken[] key?: Token | null sep?: SourceToken[] value?: Token }
15
function getPrevProps(parent: Token) { switch (parent.type) { case 'document': return parent.start case 'block-map': { const it = parent.items[parent.items.length - 1] return it.sep ?? it.start } case 'block-seq': return parent.items[parent.items.length - 1].start /* istanb...
type Token = | SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection
16
function fixFlowSeqItems(fc: FlowCollection) { if (fc.start.type === 'flow-seq-start') { for (const it of fc.items) { if ( it.sep && !it.value && !includesToken(it.start, 'explicit-key-ind') && !includesToken(it.sep, 'map-value-ind') ) { if (it.key) it.value = i...
interface FlowCollection { type: 'flow-collection' offset: number indent: number start: SourceToken items: CollectionItem[] end: SourceToken[] }
17
private *pop(error?: Token): Generator<Token, void> { const token = error ?? this.stack.pop() /* istanbul ignore if should not happen */ if (!token) { const message = 'Tried to pop an empty stack' yield { type: 'error', offset: this.offset, source: '', message } } else if (this.stack.length ...
type Token = | SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection
18
private *document(doc: Document): Generator<Token, void> { if (doc.value) return yield* this.lineEnd(doc) switch (this.type) { case 'doc-start': { if (findNonEmptyIndex(doc.start) !== -1) { yield* this.pop() yield* this.step() } else doc.start.push(this.sourceToken) ...
interface Document { type: 'document' offset: number start: SourceToken[] value?: Token end?: SourceToken[] }
19
private *document(doc: Document): Generator<Token, void> { if (doc.value) return yield* this.lineEnd(doc) switch (this.type) { case 'doc-start': { if (findNonEmptyIndex(doc.start) !== -1) { yield* this.pop() yield* this.step() } else doc.start.push(this.sourceToken) ...
class Document<T extends Node = Node> { declare readonly [NODE_TYPE]: symbol /** A comment before this Document */ commentBefore: string | null = null /** A comment immediately after this Document */ comment: string | null = null /** The document contents. */ contents: T | null directives?: Directiv...
20
private *scalar(scalar: FlowScalar) { if (this.type === 'map-value-ind') { const prev = getPrevProps(this.peek(2)) const start = getFirstKeyStartProps(prev) let sep: SourceToken[] if (scalar.end) { sep = scalar.end sep.push(this.sourceToken) delete scalar.end }...
interface FlowScalar { type: 'alias' | 'scalar' | 'single-quoted-scalar' | 'double-quoted-scalar' offset: number indent: number source: string end?: SourceToken[] }
21
private *blockScalar(scalar: BlockScalar) { switch (this.type) { case 'space': case 'comment': case 'newline': scalar.props.push(this.sourceToken) return case 'scalar': scalar.source = this.source // block-scalar source includes trailing newline this.a...
interface BlockScalar { type: 'block-scalar' offset: number indent: number props: Token[] source: string }
22
private *blockMap(map: BlockMap) { const it = map.items[map.items.length - 1] // it.sep is true-ish if pair already has key or : separator switch (this.type) { case 'newline': this.onKeyLine = false if (it.value) { const end = 'end' in it.value ? it.value.end : undefined ...
interface BlockMap { type: 'block-map' offset: number indent: number items: Array< | { start: SourceToken[]; key?: never; sep?: never; value?: never } | { start: SourceToken[] key: Token | null sep: SourceToken[] value?: Token } > }
23
private *blockSequence(seq: BlockSequence) { const it = seq.items[seq.items.length - 1] switch (this.type) { case 'newline': if (it.value) { const end = 'end' in it.value ? it.value.end : undefined const last = Array.isArray(end) ? end[end.length - 1] : undefined if (...
interface BlockSequence { type: 'block-seq' offset: number indent: number items: Array<{ start: SourceToken[] key?: never sep?: never value?: Token }> }
24
private *flowCollection(fc: FlowCollection) { const it = fc.items[fc.items.length - 1] if (this.type === 'flow-error-end') { let top: Token | undefined do { yield* this.pop() top = this.peek(1) } while (top && top.type === 'flow-collection') } else if (fc.end.length === 0) ...
interface FlowCollection { type: 'flow-collection' offset: number indent: number start: SourceToken items: CollectionItem[] end: SourceToken[] }
25
private startBlockValue(parent: Token) { switch (this.type) { case 'alias': case 'scalar': case 'single-quoted-scalar': case 'double-quoted-scalar': return this.flowScalar(this.type) case 'block-scalar-header': return { type: 'block-scalar', offset: ...
type Token = | SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection
26
private *documentEnd(docEnd: DocumentEnd) { if (this.type !== 'doc-mode') { if (docEnd.end) docEnd.end.push(this.sourceToken) else docEnd.end = [this.sourceToken] if (this.type === 'newline') yield* this.pop() } }
interface DocumentEnd { type: 'doc-end' offset: number source: string end?: SourceToken[] }
27
function setScalarValue( token: Token, value: string, context: { afterKey?: boolean implicitKey?: boolean inFlow?: boolean type?: Scalar.Type } = {} ) { let { afterKey = false, implicitKey = false, inFlow = false, type } = context let indent = 'indent' in token ? token.indent : null if (af...
type Token = | SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection
28
function setBlockScalarValue(token: Token, source: string) { const he = source.indexOf('\n') const head = source.substring(0, he) const body = source.substring(he + 1) + '\n' if (token.type === 'block-scalar') { const header = token.props[0] if (header.type !== 'block-scalar-header') throw new Err...
type Token = | SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection
29
function setFlowScalarValue( token: Token, source: string, type: 'scalar' | 'double-quoted-scalar' | 'single-quoted-scalar' ) { switch (token.type) { case 'scalar': case 'double-quoted-scalar': case 'single-quoted-scalar': token.type = type token.source = source break case 'blo...
type Token = | SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection
30
private setNext(state: State) { this.buffer = this.buffer.substring(this.pos) this.pos = 0 this.lineEndPos = null this.next = state return null }
type State = | 'stream' | 'line-start' | 'block-start' | 'doc' | 'flow' | 'quoted-scalar' | 'block-scalar' | 'plain-scalar'
31
private *parseNext(next: State) { switch (next) { case 'stream': return yield* this.parseStream() case 'line-start': return yield* this.parseLineStart() case 'block-start': return yield* this.parseBlockStart() case 'doc': return yield* this.parseDocument() ...
type State = | 'stream' | 'line-start' | 'block-start' | 'doc' | 'flow' | 'quoted-scalar' | 'block-scalar' | 'plain-scalar'
32
( item: CollectionItem, path: VisitPath ) => number | symbol | Visitor | void
type VisitPath = readonly ['key' | 'value', number][]
33
( item: CollectionItem, path: VisitPath ) => number | symbol | Visitor | void
type CollectionItem = { start: SourceToken[] key?: Token | null sep?: SourceToken[] value?: Token }
34
function _visit( path: VisitPath, item: CollectionItem, visitor: Visitor ): number | symbol | Visitor | void { let ctrl = visitor(item, path) if (typeof ctrl === 'symbol') return ctrl for (const field of ['key', 'value'] as const) { const token = item[field] if (token && 'items' in token) { fo...
type VisitPath = readonly ['key' | 'value', number][]
35
function _visit( path: VisitPath, item: CollectionItem, visitor: Visitor ): number | symbol | Visitor | void { let ctrl = visitor(item, path) if (typeof ctrl === 'symbol') return ctrl for (const field of ['key', 'value'] as const) { const token = item[field] if (token && 'items' in token) { fo...
type CollectionItem = { start: SourceToken[] key?: Token | null sep?: SourceToken[] value?: Token }
36
function _visit( path: VisitPath, item: CollectionItem, visitor: Visitor ): number | symbol | Visitor | void { let ctrl = visitor(item, path) if (typeof ctrl === 'symbol') return ctrl for (const field of ['key', 'value'] as const) { const token = item[field] if (token && 'items' in token) { fo...
type Visitor = ( item: CollectionItem, path: VisitPath ) => number | symbol | Visitor | void
37
function collectionFromPath( schema: Schema, path: unknown[], value: unknown ) { let v = value for (let i = path.length - 1; i >= 0; --i) { const k = path[i] if (typeof k === 'number' && Number.isInteger(k) && k >= 0) { const a: unknown[] = [] a[k] = v v = a } else { v = ne...
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by crea...
38
clone(schema?: Schema): Collection { const copy: Collection = Object.create( Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this) ) if (schema) copy.schema = schema copy.items = copy.items.map(it => isNode(it) || isPair(it) ? it.clone(schema) : it ) if (this.rang...
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by crea...
39
constructor(schema?: Schema) { super(MAP, schema) }
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by crea...
40
toString( ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void ): string { if (!ctx) return JSON.stringify(this) for (const item of this.items) { if (!isPair(item)) throw new Error( `Map items must all be pairs; found ${JSON.stringify(item)} instead` ...
type StringifyContext = { actualString?: boolean allNullValues?: boolean anchors: Set<string> doc: Document forceBlockIndent?: boolean implicitKey?: boolean indent: string indentStep: string indentAtStart?: number inFlow: boolean | null inStringifyKey?: boolean flowCollectionPadding: string op...
41
clone(schema?: Schema): Pair<K, V> { let { key, value } = this if (isNode(key)) key = key.clone(schema) as unknown as K if (isNode(value)) value = value.clone(schema) as unknown as V return new Pair(key, value) }
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by crea...
42
toString( ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void ): string { return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this) }
type StringifyContext = { actualString?: boolean allNullValues?: boolean anchors: Set<string> doc: Document forceBlockIndent?: boolean implicitKey?: boolean indent: string indentStep: string indentAtStart?: number inFlow: boolean | null inStringifyKey?: boolean flowCollectionPadding: string op...
43
abstract toString( ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void ): string
type StringifyContext = { actualString?: boolean allNullValues?: boolean anchors: Set<string> doc: Document forceBlockIndent?: boolean implicitKey?: boolean indent: string indentStep: string indentAtStart?: number inFlow: boolean | null inStringifyKey?: boolean flowCollectionPadding: string op...
44
constructor(schema?: Schema) { super(SEQ, schema) }
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by crea...
45
toString( ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void ): string { if (!ctx) return JSON.stringify(this) return stringifyCollection(this, ctx, { blockItemPrefix: '- ', flowChars: { start: '[', end: ']' }, itemIndent: (ctx.indent || '') + ' ', on...
type StringifyContext = { actualString?: boolean allNullValues?: boolean anchors: Set<string> doc: Document forceBlockIndent?: boolean implicitKey?: boolean indent: string indentStep: string indentAtStart?: number inFlow: boolean | null inStringifyKey?: boolean flowCollectionPadding: string op...
46
resolve(doc: Document): Scalar | YAMLMap | YAMLSeq | undefined { let found: Scalar | YAMLMap | YAMLSeq | undefined = undefined visit(doc, { Node: (_key: unknown, node: Node) => { if (node === this) return visit.BREAK if (node.anchor === this.source) found = node } }) return f...
interface Document { type: 'document' offset: number start: SourceToken[] value?: Token end?: SourceToken[] }
47
resolve(doc: Document): Scalar | YAMLMap | YAMLSeq | undefined { let found: Scalar | YAMLMap | YAMLSeq | undefined = undefined visit(doc, { Node: (_key: unknown, node: Node) => { if (node === this) return visit.BREAK if (node.anchor === this.source) found = node } }) return f...
class Document<T extends Node = Node> { declare readonly [NODE_TYPE]: symbol /** A comment before this Document */ commentBefore: string | null = null /** A comment immediately after this Document */ comment: string | null = null /** The document contents. */ contents: T | null directives?: Directiv...
48
toString( ctx?: StringifyContext, _onComment?: () => void, _onChompKeep?: () => void ) { const src = `*${this.source}` if (ctx) { anchorIsValid(this.source) if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { const msg = `Unresolved alias (the anchor must be se...
type StringifyContext = { actualString?: boolean allNullValues?: boolean anchors: Set<string> doc: Document forceBlockIndent?: boolean implicitKey?: boolean indent: string indentStep: string indentAtStart?: number inFlow: boolean | null inStringifyKey?: boolean flowCollectionPadding: string op...
49
function getAliasCount( doc: Document, node: unknown, anchors: ToJSContext['anchors'] ): number { if (isAlias(node)) { const source = node.resolve(doc) const anchor = anchors && source && anchors.get(source) return anchor ? anchor.count * anchor.aliasCount : 0 } else if (isCollection(node)) { ...
interface Document { type: 'document' offset: number start: SourceToken[] value?: Token end?: SourceToken[] }
50
function getAliasCount( doc: Document, node: unknown, anchors: ToJSContext['anchors'] ): number { if (isAlias(node)) { const source = node.resolve(doc) const anchor = anchors && source && anchors.get(source) return anchor ? anchor.count * anchor.aliasCount : 0 } else if (isCollection(node)) { ...
class Document<T extends Node = Node> { declare readonly [NODE_TYPE]: symbol /** A comment before this Document */ commentBefore: string | null = null /** A comment immediately after this Document */ comment: string | null = null /** The document contents. */ contents: T | null directives?: Directiv...
51
(schema: Schema, value: unknown, ctx: CreateNodeContext) => Node
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by crea...
52
(schema: Schema, value: unknown, ctx: CreateNodeContext) => Node
interface CreateNodeContext { aliasDuplicateObjects: boolean keepUndefined: boolean onAnchor: (source: unknown) => string onTagObj?: (tagObj: ScalarTag | CollectionTag) => void sourceObjects: Map<unknown, { anchor: string | null; node: Node | null }> replacer?: Replacer schema: Schema }
53
( item: Scalar, ctx: StringifyContext, onComment?: () => void, onChompKeep?: () => void ) => string
type StringifyContext = { actualString?: boolean allNullValues?: boolean anchors: Set<string> doc: Document forceBlockIndent?: boolean implicitKey?: boolean indent: string indentStep: string indentAtStart?: number inFlow: boolean | null inStringifyKey?: boolean flowCollectionPadding: string op...
54
( item: Scalar, ctx: StringifyContext, onComment?: () => void, onChompKeep?: () => void ) => string
class Scalar<T = unknown> extends NodeBase { static readonly BLOCK_FOLDED = 'BLOCK_FOLDED' static readonly BLOCK_LITERAL = 'BLOCK_LITERAL' static readonly PLAIN = 'PLAIN' static readonly QUOTE_DOUBLE = 'QUOTE_DOUBLE' static readonly QUOTE_SINGLE = 'QUOTE_SINGLE' value: T /** An optional anchor on this n...
55
constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }: SchemaOptions) { this.compat = Array.isArray(compat) ? getTags(compat, 'compat') : compat ? getTags(null, compat) : null this.merge = !!merge this.name...
type SchemaOptions = { /** * When parsing, warn about compatibility issues with the given schema. * When stringifying, use scalar styles that are parsed correctly * by the `compat` schema as well as the actual schema. * * Default: `null` */ compat?: string | Tags | null /** * Array of additi...
56
({ value }: Scalar) => JSON.stringify(value)
class Scalar<T = unknown> extends NodeBase { static readonly BLOCK_FOLDED = 'BLOCK_FOLDED' static readonly BLOCK_LITERAL = 'BLOCK_LITERAL' static readonly PLAIN = 'PLAIN' static readonly QUOTE_DOUBLE = 'QUOTE_DOUBLE' static readonly QUOTE_SINGLE = 'QUOTE_SINGLE' value: T /** An optional anchor on this n...
57
function intStringify(node: Scalar, radix: number, prefix: string) { const { value } = node if (intIdentify(value) && value >= 0) return prefix + value.toString(radix) return stringifyNumber(node) }
class Scalar<T = unknown> extends NodeBase { static readonly BLOCK_FOLDED = 'BLOCK_FOLDED' static readonly BLOCK_LITERAL = 'BLOCK_LITERAL' static readonly PLAIN = 'PLAIN' static readonly QUOTE_DOUBLE = 'QUOTE_DOUBLE' static readonly QUOTE_SINGLE = 'QUOTE_SINGLE' value: T /** An optional anchor on this n...
58
function createPairs( schema: Schema, iterable: unknown, ctx: CreateNodeContext ) { const { replacer } = ctx const pairs = new YAMLSeq(schema) pairs.tag = 'tag:yaml.org,2002:pairs' let i = 0 if (iterable && Symbol.iterator in Object(iterable)) for (let it of iterable as Iterable<unknown>) { if...
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by crea...
59
function createPairs( schema: Schema, iterable: unknown, ctx: CreateNodeContext ) { const { replacer } = ctx const pairs = new YAMLSeq(schema) pairs.tag = 'tag:yaml.org,2002:pairs' let i = 0 if (iterable && Symbol.iterator in Object(iterable)) for (let it of iterable as Iterable<unknown>) { if...
interface CreateNodeContext { aliasDuplicateObjects: boolean keepUndefined: boolean onAnchor: (source: unknown) => string onTagObj?: (tagObj: ScalarTag | CollectionTag) => void sourceObjects: Map<unknown, { anchor: string | null; node: Node | null }> replacer?: Replacer schema: Schema }
60
constructor(schema?: Schema) { super(schema) this.tag = YAMLSet.tag }
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by crea...
61
toString( ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void ) { if (!ctx) return JSON.stringify(this) if (this.hasAllNullValues(true)) return super.toString( Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep ) els...
type StringifyContext = { actualString?: boolean allNullValues?: boolean anchors: Set<string> doc: Document forceBlockIndent?: boolean implicitKey?: boolean indent: string indentStep: string indentAtStart?: number inFlow: boolean | null inStringifyKey?: boolean flowCollectionPadding: string op...
62
function boolStringify({ value, source }: Scalar, ctx: StringifyContext) { const boolObj = value ? trueTag : falseTag if (source && boolObj.test.test(source)) return source return value ? ctx.options.trueStr : ctx.options.falseStr }
type StringifyContext = { actualString?: boolean allNullValues?: boolean anchors: Set<string> doc: Document forceBlockIndent?: boolean implicitKey?: boolean indent: string indentStep: string indentAtStart?: number inFlow: boolean | null inStringifyKey?: boolean flowCollectionPadding: string op...
63
function boolStringify({ value, source }: Scalar, ctx: StringifyContext) { const boolObj = value ? trueTag : falseTag if (source && boolObj.test.test(source)) return source return value ? ctx.options.trueStr : ctx.options.falseStr }
class Scalar<T = unknown> extends NodeBase { static readonly BLOCK_FOLDED = 'BLOCK_FOLDED' static readonly BLOCK_LITERAL = 'BLOCK_LITERAL' static readonly PLAIN = 'PLAIN' static readonly QUOTE_DOUBLE = 'QUOTE_DOUBLE' static readonly QUOTE_SINGLE = 'QUOTE_SINGLE' value: T /** An optional anchor on this n...
64
function stringifySexagesimal(node: Scalar) { let { value } = node as Scalar<number> let num = (n: number) => n if (typeof value === 'bigint') num = n => BigInt(n) as unknown as number else if (isNaN(value) || !isFinite(value)) return stringifyNumber(node) let sign = '' if (value < 0) { sign = '-' v...
class Scalar<T = unknown> extends NodeBase { static readonly BLOCK_FOLDED = 'BLOCK_FOLDED' static readonly BLOCK_LITERAL = 'BLOCK_LITERAL' static readonly PLAIN = 'PLAIN' static readonly QUOTE_DOUBLE = 'QUOTE_DOUBLE' static readonly QUOTE_SINGLE = 'QUOTE_SINGLE' value: T /** An optional anchor on this n...
65
function intStringify(node: Scalar, radix: number, prefix: string) { const { value } = node if (intIdentify(value)) { const str = value.toString(radix) return value < 0 ? '-' + prefix + str.substr(1) : prefix + str } return stringifyNumber(node) }
class Scalar<T = unknown> extends NodeBase { static readonly BLOCK_FOLDED = 'BLOCK_FOLDED' static readonly BLOCK_LITERAL = 'BLOCK_LITERAL' static readonly PLAIN = 'PLAIN' static readonly QUOTE_DOUBLE = 'QUOTE_DOUBLE' static readonly QUOTE_SINGLE = 'QUOTE_SINGLE' value: T /** An optional anchor on this n...
66
function createSeq(schema: Schema, obj: unknown, ctx: CreateNodeContext) { const { replacer } = ctx const seq = new YAMLSeq(schema) if (obj && Symbol.iterator in Object(obj)) { let i = 0 for (let it of obj as Iterable<unknown>) { if (typeof replacer === 'function') { const key = obj instance...
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by crea...
67
function createSeq(schema: Schema, obj: unknown, ctx: CreateNodeContext) { const { replacer } = ctx const seq = new YAMLSeq(schema) if (obj && Symbol.iterator in Object(obj)) { let i = 0 for (let it of obj as Iterable<unknown>) { if (typeof replacer === 'function') { const key = obj instance...
interface CreateNodeContext { aliasDuplicateObjects: boolean keepUndefined: boolean onAnchor: (source: unknown) => string onTagObj?: (tagObj: ScalarTag | CollectionTag) => void sourceObjects: Map<unknown, { anchor: string | null; node: Node | null }> replacer?: Replacer schema: Schema }
68
function createMap(schema: Schema, obj: unknown, ctx: CreateNodeContext) { const { keepUndefined, replacer } = ctx const map = new YAMLMap(schema) const add = (key: unknown, value: unknown) => { if (typeof replacer === 'function') value = replacer.call(obj, key, value) else if (Array.isArray(replacer) && ...
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by crea...
69
function createMap(schema: Schema, obj: unknown, ctx: CreateNodeContext) { const { keepUndefined, replacer } = ctx const map = new YAMLMap(schema) const add = (key: unknown, value: unknown) => { if (typeof replacer === 'function') value = replacer.call(obj, key, value) else if (Array.isArray(replacer) && ...
interface CreateNodeContext { aliasDuplicateObjects: boolean keepUndefined: boolean onAnchor: (source: unknown) => string onTagObj?: (tagObj: ScalarTag | CollectionTag) => void sourceObjects: Map<unknown, { anchor: string | null; node: Node | null }> replacer?: Replacer schema: Schema }
70
function composeCollection( CN: ComposeNode, ctx: ComposeContext, token: BlockMap | BlockSequence | FlowCollection, tagToken: SourceToken | null, onError: ComposeErrorHandler ) { let coll: YAMLMap.Parsed | YAMLSeq.Parsed switch (token.type) { case 'block-map': { coll = resolveBlockMap(CN, ctx, t...
type ComposeNode = typeof CN
71
function composeCollection( CN: ComposeNode, ctx: ComposeContext, token: BlockMap | BlockSequence | FlowCollection, tagToken: SourceToken | null, onError: ComposeErrorHandler ) { let coll: YAMLMap.Parsed | YAMLSeq.Parsed switch (token.type) { case 'block-map': { coll = resolveBlockMap(CN, ctx, t...
interface ComposeContext { atRoot: boolean directives: Directives options: Readonly<Required<Omit<ParseOptions, 'lineCounter'>>> schema: Readonly<Schema> }
72
function composeCollection( CN: ComposeNode, ctx: ComposeContext, token: BlockMap | BlockSequence | FlowCollection, tagToken: SourceToken | null, onError: ComposeErrorHandler ) { let coll: YAMLMap.Parsed | YAMLSeq.Parsed switch (token.type) { case 'block-map': { coll = resolveBlockMap(CN, ctx, t...
type ComposeErrorHandler = ( source: ErrorSource, code: ErrorCode, message: string, warning?: boolean ) => void
73
function composeNode( ctx: ComposeContext, token: Token, props: Props, onError: ComposeErrorHandler ) { const { spaceBefore, comment, anchor, tag } = props let node: ParsedNode let isSrcToken = true switch (token.type) { case 'alias': node = composeAlias(ctx, token, onError) if (anchor |...
interface Props { spaceBefore: boolean comment: string anchor: SourceToken | null tag: SourceToken | null end: number }
74
function composeNode( ctx: ComposeContext, token: Token, props: Props, onError: ComposeErrorHandler ) { const { spaceBefore, comment, anchor, tag } = props let node: ParsedNode let isSrcToken = true switch (token.type) { case 'alias': node = composeAlias(ctx, token, onError) if (anchor |...
type Token = | SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection
75
function composeNode( ctx: ComposeContext, token: Token, props: Props, onError: ComposeErrorHandler ) { const { spaceBefore, comment, anchor, tag } = props let node: ParsedNode let isSrcToken = true switch (token.type) { case 'alias': node = composeAlias(ctx, token, onError) if (anchor |...
interface ComposeContext { atRoot: boolean directives: Directives options: Readonly<Required<Omit<ParseOptions, 'lineCounter'>>> schema: Readonly<Schema> }
76
function composeNode( ctx: ComposeContext, token: Token, props: Props, onError: ComposeErrorHandler ) { const { spaceBefore, comment, anchor, tag } = props let node: ParsedNode let isSrcToken = true switch (token.type) { case 'alias': node = composeAlias(ctx, token, onError) if (anchor |...
type ComposeErrorHandler = ( source: ErrorSource, code: ErrorCode, message: string, warning?: boolean ) => void
77
function composeEmptyNode( ctx: ComposeContext, offset: number, before: Token[] | undefined, pos: number | null, { spaceBefore, comment, anchor, tag, end }: Props, onError: ComposeErrorHandler ) { const token: FlowScalar = { type: 'scalar', offset: emptyScalarPosition(offset, before, pos), ind...
interface Props { spaceBefore: boolean comment: string anchor: SourceToken | null tag: SourceToken | null end: number }
78
function composeEmptyNode( ctx: ComposeContext, offset: number, before: Token[] | undefined, pos: number | null, { spaceBefore, comment, anchor, tag, end }: Props, onError: ComposeErrorHandler ) { const token: FlowScalar = { type: 'scalar', offset: emptyScalarPosition(offset, before, pos), ind...
interface ComposeContext { atRoot: boolean directives: Directives options: Readonly<Required<Omit<ParseOptions, 'lineCounter'>>> schema: Readonly<Schema> }
79
function composeEmptyNode( ctx: ComposeContext, offset: number, before: Token[] | undefined, pos: number | null, { spaceBefore, comment, anchor, tag, end }: Props, onError: ComposeErrorHandler ) { const token: FlowScalar = { type: 'scalar', offset: emptyScalarPosition(offset, before, pos), ind...
type ComposeErrorHandler = ( source: ErrorSource, code: ErrorCode, message: string, warning?: boolean ) => void
80
function composeAlias( { options }: ComposeContext, { offset, source, end }: FlowScalar, onError: ComposeErrorHandler ) { const alias = new Alias(source.substring(1)) if (alias.source === '') onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string') if (alias.source.endsWith(':')) onError( ...
interface FlowScalar { type: 'alias' | 'scalar' | 'single-quoted-scalar' | 'double-quoted-scalar' offset: number indent: number source: string end?: SourceToken[] }
81
function composeAlias( { options }: ComposeContext, { offset, source, end }: FlowScalar, onError: ComposeErrorHandler ) { const alias = new Alias(source.substring(1)) if (alias.source === '') onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string') if (alias.source.endsWith(':')) onError( ...
interface ComposeContext { atRoot: boolean directives: Directives options: Readonly<Required<Omit<ParseOptions, 'lineCounter'>>> schema: Readonly<Schema> }
82
function composeAlias( { options }: ComposeContext, { offset, source, end }: FlowScalar, onError: ComposeErrorHandler ) { const alias = new Alias(source.substring(1)) if (alias.source === '') onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string') if (alias.source.endsWith(':')) onError( ...
type ComposeErrorHandler = ( source: ErrorSource, code: ErrorCode, message: string, warning?: boolean ) => void
83
function mapIncludes( ctx: ComposeContext, items: Pair<ParsedNode>[], search: ParsedNode ) { const { uniqueKeys } = ctx.options if (uniqueKeys === false) return false const isEqual = typeof uniqueKeys === 'function' ? uniqueKeys : (a: ParsedNode, b: ParsedNode) => a === b || ...
interface ComposeContext { atRoot: boolean directives: Directives options: Readonly<Required<Omit<ParseOptions, 'lineCounter'>>> schema: Readonly<Schema> }
84
function mapIncludes( ctx: ComposeContext, items: Pair<ParsedNode>[], search: ParsedNode ) { const { uniqueKeys } = ctx.options if (uniqueKeys === false) return false const isEqual = typeof uniqueKeys === 'function' ? uniqueKeys : (a: ParsedNode, b: ParsedNode) => a === b || ...
type ParsedNode = | Alias.Parsed | Scalar.Parsed | YAMLMap.Parsed | YAMLSeq.Parsed
85
(a: ParsedNode, b: ParsedNode) => a === b || (isScalar(a) && isScalar(b) && a.value === b.value && !(a.value === '<<' && ctx.schema.merge))
type ParsedNode = | Alias.Parsed | Scalar.Parsed | YAMLMap.Parsed | YAMLSeq.Parsed
86
function resolveFlowScalar( scalar: FlowScalar, strict: boolean, onError: ComposeErrorHandler ): { value: string type: Scalar.PLAIN | Scalar.QUOTE_DOUBLE | Scalar.QUOTE_SINGLE | null comment: string range: Range } { const { offset, type, source, end } = scalar let _type: Scalar.PLAIN | Scalar.QUOTE_DO...
interface FlowScalar { type: 'alias' | 'scalar' | 'single-quoted-scalar' | 'double-quoted-scalar' offset: number indent: number source: string end?: SourceToken[] }
87
function resolveFlowScalar( scalar: FlowScalar, strict: boolean, onError: ComposeErrorHandler ): { value: string type: Scalar.PLAIN | Scalar.QUOTE_DOUBLE | Scalar.QUOTE_SINGLE | null comment: string range: Range } { const { offset, type, source, end } = scalar let _type: Scalar.PLAIN | Scalar.QUOTE_DO...
type ComposeErrorHandler = ( source: ErrorSource, code: ErrorCode, message: string, warning?: boolean ) => void
88
function composeScalar( ctx: ComposeContext, token: FlowScalar | BlockScalar, tagToken: SourceToken | null, onError: ComposeErrorHandler ) { const { value, type, comment, range } = token.type === 'block-scalar' ? resolveBlockScalar(token, ctx.options.strict, onError) : resolveFlowScalar(token,...
interface ComposeContext { atRoot: boolean directives: Directives options: Readonly<Required<Omit<ParseOptions, 'lineCounter'>>> schema: Readonly<Schema> }
89
function composeScalar( ctx: ComposeContext, token: FlowScalar | BlockScalar, tagToken: SourceToken | null, onError: ComposeErrorHandler ) { const { value, type, comment, range } = token.type === 'block-scalar' ? resolveBlockScalar(token, ctx.options.strict, onError) : resolveFlowScalar(token,...
type ComposeErrorHandler = ( source: ErrorSource, code: ErrorCode, message: string, warning?: boolean ) => void
90
function findScalarTagByName( schema: Schema, value: string, tagName: string, tagToken: SourceToken, onError: ComposeErrorHandler ) { if (tagName === '!') return schema[SCALAR] // non-specific tag const matchWithTest: ScalarTag[] = [] for (const tag of schema.tags) { if (!tag.collection && tag.tag =...
interface SourceToken { type: | 'byte-order-mark' | 'doc-mode' | 'doc-start' | 'space' | 'comment' | 'newline' | 'directive-line' | 'anchor' | 'tag' | 'seq-item-ind' | 'explicit-key-ind' | 'map-value-ind' | 'flow-map-start' | 'flow-map-end' | 'flow-seq-start...
91
function findScalarTagByName( schema: Schema, value: string, tagName: string, tagToken: SourceToken, onError: ComposeErrorHandler ) { if (tagName === '!') return schema[SCALAR] // non-specific tag const matchWithTest: ScalarTag[] = [] for (const tag of schema.tags) { if (!tag.collection && tag.tag =...
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by crea...
92
function findScalarTagByName( schema: Schema, value: string, tagName: string, tagToken: SourceToken, onError: ComposeErrorHandler ) { if (tagName === '!') return schema[SCALAR] // non-specific tag const matchWithTest: ScalarTag[] = [] for (const tag of schema.tags) { if (!tag.collection && tag.tag =...
type ComposeErrorHandler = ( source: ErrorSource, code: ErrorCode, message: string, warning?: boolean ) => void
93
function findScalarTagByTest( { directives, schema }: ComposeContext, value: string, token: FlowScalar, onError: ComposeErrorHandler ) { const tag = (schema.tags.find( tag => tag.default && tag.test?.test(value) ) as ScalarTag) || schema[SCALAR] if (schema.compat) { const compat = s...
interface FlowScalar { type: 'alias' | 'scalar' | 'single-quoted-scalar' | 'double-quoted-scalar' offset: number indent: number source: string end?: SourceToken[] }
94
function findScalarTagByTest( { directives, schema }: ComposeContext, value: string, token: FlowScalar, onError: ComposeErrorHandler ) { const tag = (schema.tags.find( tag => tag.default && tag.test?.test(value) ) as ScalarTag) || schema[SCALAR] if (schema.compat) { const compat = s...
interface ComposeContext { atRoot: boolean directives: Directives options: Readonly<Required<Omit<ParseOptions, 'lineCounter'>>> schema: Readonly<Schema> }
95
function findScalarTagByTest( { directives, schema }: ComposeContext, value: string, token: FlowScalar, onError: ComposeErrorHandler ) { const tag = (schema.tags.find( tag => tag.default && tag.test?.test(value) ) as ScalarTag) || schema[SCALAR] if (schema.compat) { const compat = s...
type ComposeErrorHandler = ( source: ErrorSource, code: ErrorCode, message: string, warning?: boolean ) => void
96
( source: ErrorSource, code: ErrorCode, message: string, warning?: boolean ) => void
type ErrorSource = | number | [number, number] | Range | { offset: number; source?: string }
97
( source: ErrorSource, code: ErrorCode, message: string, warning?: boolean ) => void
type ErrorCode = | 'ALIAS_PROPS' | 'BAD_ALIAS' | 'BAD_DIRECTIVE' | 'BAD_DQ_ESCAPE' | 'BAD_INDENT' | 'BAD_PROP_ORDER' | 'BAD_SCALAR_START' | 'BLOCK_AS_IMPLICIT_KEY' | 'BLOCK_IN_FLOW' | 'DUPLICATE_KEY' | 'IMPOSSIBLE' | 'KEY_OVER_1024_CHARS' | 'MISSING_CHAR' | 'MULTILINE_IMPLICIT_KEY' | 'MULT...
98
function getErrorPos(src: ErrorSource): [number, number] { if (typeof src === 'number') return [src, src + 1] if (Array.isArray(src)) return src.length === 2 ? src : [src[0], src[1]] const { offset, source } = src return [offset, offset + (typeof source === 'string' ? source.length : 1)] }
type ErrorSource = | number | [number, number] | Range | { offset: number; source?: string }
99
*next(token: Token) { if (process.env.LOG_STREAM) console.dir(token, { depth: null }) switch (token.type) { case 'directive': this.directives.add(token.source, (offset, message, warning) => { const pos = getErrorPos(token) pos[0] += offset this.onError(pos, 'BAD_DIREC...
type Token = | SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection