node_modules: upgrade

This commit is contained in:
Dawid Dziurla
2024-01-17 10:08:10 +01:00
parent 9ff0bc8d99
commit 00765f79cf
320 changed files with 31840 additions and 1039 deletions

View File

@@ -1,4 +1,4 @@
import { ParsedNode } from '../nodes/Node.js';
import type { ParsedNode } from '../nodes/Node.js';
import type { BlockMap, BlockSequence, FlowCollection, SourceToken } from '../parse/cst.js';
import type { ComposeContext, ComposeNode } from './compose-node.js';
import type { ComposeErrorHandler } from './composer.js';

View File

@@ -1,40 +1,52 @@
'use strict';
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var Scalar = require('../nodes/Scalar.js');
var YAMLMap = require('../nodes/YAMLMap.js');
var YAMLSeq = require('../nodes/YAMLSeq.js');
var resolveBlockMap = require('./resolve-block-map.js');
var resolveBlockSeq = require('./resolve-block-seq.js');
var resolveFlowCollection = require('./resolve-flow-collection.js');
function composeCollection(CN, ctx, token, tagToken, onError) {
let coll;
switch (token.type) {
case 'block-map': {
coll = resolveBlockMap.resolveBlockMap(CN, ctx, token, onError);
break;
}
case 'block-seq': {
coll = resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError);
break;
}
case 'flow-collection': {
coll = resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError);
break;
}
}
if (!tagToken)
return coll;
const tagName = ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg));
if (!tagName)
return coll;
// Cast needed due to: https://github.com/Microsoft/TypeScript/issues/3841
function resolveCollection(CN, ctx, token, onError, tagName, tag) {
const coll = token.type === 'block-map'
? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag)
: token.type === 'block-seq'
? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag)
: resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag);
const Coll = coll.constructor;
// If we got a tagName matching the class, or the tag name is '!',
// then use the tagName from the node class used to create it.
if (tagName === '!' || tagName === Coll.tagName) {
coll.tag = Coll.tagName;
return coll;
}
const expType = Node.isMap(coll) ? 'map' : 'seq';
let tag = ctx.schema.tags.find(t => t.collection === expType && t.tag === tagName);
if (tagName)
coll.tag = tagName;
return coll;
}
function composeCollection(CN, ctx, token, tagToken, onError) {
const tagName = !tagToken
? null
: ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg));
const expType = token.type === 'block-map'
? 'map'
: token.type === 'block-seq'
? 'seq'
: token.start.source === '{'
? 'map'
: 'seq';
// shortcut: check if it's a generic YAMLMap or YAMLSeq
// before jumping into the custom tag logic.
if (!tagToken ||
!tagName ||
tagName === '!' ||
(tagName === YAMLMap.YAMLMap.tagName && expType === 'map') ||
(tagName === YAMLSeq.YAMLSeq.tagName && expType === 'seq') ||
!expType) {
return resolveCollection(CN, ctx, token, onError, tagName);
}
let tag = ctx.schema.tags.find(t => t.tag === tagName && t.collection === expType);
if (!tag) {
const kt = ctx.schema.knownTags[tagName];
if (kt && kt.collection === expType) {
@@ -42,13 +54,18 @@ function composeCollection(CN, ctx, token, tagToken, onError) {
tag = kt;
}
else {
onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true);
coll.tag = tagName;
return coll;
if (kt?.collection) {
onError(tagToken, 'BAD_COLLECTION_TYPE', `${kt.tag} used for ${expType} collection, but expects ${kt.collection}`, true);
}
else {
onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true);
}
return resolveCollection(CN, ctx, token, onError, tagName);
}
}
const res = tag.resolve(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options);
const node = Node.isNode(res)
const coll = resolveCollection(CN, ctx, token, onError, tagName, tag);
const res = tag.resolve?.(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options) ?? coll;
const node = identity.isNode(res)
? res
: new Scalar.Scalar(res);
node.range = coll.range;

View File

@@ -1,6 +1,7 @@
import type { Directives } from '../doc/directives.js';
import { Document } from '../doc/Document.js';
import type { ParsedNode } from '../nodes/Node.js';
import type { DocumentOptions, ParseOptions, SchemaOptions } from '../options.js';
import type * as CST from '../parse/cst.js';
import type { ComposeErrorHandler } from './composer.js';
export declare function composeDoc(options: ParseOptions & DocumentOptions & SchemaOptions, directives: Directives, { offset, start, value, end }: CST.Document, onError: ComposeErrorHandler): Document.Parsed<import("../index.js").ParsedNode>;
export declare function composeDoc<Contents extends ParsedNode = ParsedNode, Strict extends boolean = true>(options: ParseOptions & DocumentOptions & SchemaOptions, directives: Directives, { offset, start, value, end }: CST.Document, onError: ComposeErrorHandler): Document.Parsed<Contents, Strict>;

View File

@@ -28,6 +28,7 @@ function composeDoc(options, directives, { offset, start, value, end }, onError)
!props.hasNewline)
onError(props.end, 'MISSING_CHAR', 'Block collection cannot start on same line with directives-end marker');
}
// @ts-expect-error If Contents is set, let's trust the user
doc.contents = value
? composeNode.composeNode(ctx, value, props, onError)
: composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError);

View File

@@ -21,7 +21,7 @@ declare const CN: {
composeNode: typeof composeNode;
composeEmptyNode: typeof composeEmptyNode;
};
export declare type ComposeNode = typeof CN;
export type ComposeNode = typeof CN;
export declare function composeNode(ctx: ComposeContext, token: Token, props: Props, onError: ComposeErrorHandler): ParsedNode;
export declare function composeEmptyNode(ctx: ComposeContext, offset: number, before: Token[] | undefined, pos: number | null, { spaceBefore, comment, anchor, tag, end }: Props, onError: ComposeErrorHandler): import("../index.js").Scalar.Parsed;
export {};

View File

@@ -1,6 +1,6 @@
'use strict';
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var Scalar = require('../nodes/Scalar.js');
var resolveBlockScalar = require('./resolve-block-scalar.js');
var resolveFlowScalar = require('./resolve-flow-scalar.js');
@@ -16,11 +16,11 @@ function composeScalar(ctx, token, tagToken, onError) {
? findScalarTagByName(ctx.schema, value, tagName, tagToken, onError)
: token.type === 'scalar'
? findScalarTagByTest(ctx, value, token, onError)
: ctx.schema[Node.SCALAR];
: ctx.schema[identity.SCALAR];
let scalar;
try {
const res = tag.resolve(value, msg => onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg), ctx.options);
scalar = Node.isScalar(res) ? res : new Scalar.Scalar(res);
scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res);
}
catch (error) {
const msg = error instanceof Error ? error.message : String(error);
@@ -41,7 +41,7 @@ function composeScalar(ctx, token, tagToken, onError) {
}
function findScalarTagByName(schema, value, tagName, tagToken, onError) {
if (tagName === '!')
return schema[Node.SCALAR]; // non-specific tag
return schema[identity.SCALAR]; // non-specific tag
const matchWithTest = [];
for (const tag of schema.tags) {
if (!tag.collection && tag.tag === tagName) {
@@ -62,13 +62,13 @@ function findScalarTagByName(schema, value, tagName, tagToken, onError) {
return kt;
}
onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str');
return schema[Node.SCALAR];
return schema[identity.SCALAR];
}
function findScalarTagByTest({ directives, schema }, value, token, onError) {
const tag = schema.tags.find(tag => tag.default && tag.test?.test(value)) || schema[Node.SCALAR];
const tag = schema.tags.find(tag => tag.default && tag.test?.test(value)) || schema[identity.SCALAR];
if (schema.compat) {
const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ??
schema[Node.SCALAR];
schema[identity.SCALAR];
if (tag.tag !== compat.tag) {
const ts = directives.tagString(tag.tag);
const cs = directives.tagString(compat.tag);

View File

@@ -1,14 +1,14 @@
import { Directives } from '../doc/directives.js';
import { Document } from '../doc/Document.js';
import { ErrorCode, YAMLParseError, YAMLWarning } from '../errors.js';
import { Range } from '../nodes/Node.js';
import type { ParsedNode, Range } from '../nodes/Node.js';
import type { DocumentOptions, ParseOptions, SchemaOptions } from '../options.js';
import type { Token } from '../parse/cst.js';
declare type ErrorSource = number | [number, number] | Range | {
type ErrorSource = number | [number, number] | Range | {
offset: number;
source?: string;
};
export declare type ComposeErrorHandler = (source: ErrorSource, code: ErrorCode, message: string, warning?: boolean) => void;
export type ComposeErrorHandler = (source: ErrorSource, code: ErrorCode, message: string, warning?: boolean) => void;
/**
* Compose a stream of CST nodes into a stream of YAML Documents.
*
@@ -20,7 +20,7 @@ export declare type ComposeErrorHandler = (source: ErrorSource, code: ErrorCode,
* const docs = new Composer().compose(tokens)
* ```
*/
export declare class Composer {
export declare class Composer<Contents extends ParsedNode = ParsedNode, Strict extends boolean = true> {
private directives;
private doc;
private options;
@@ -48,15 +48,15 @@ export declare class Composer {
* @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
* @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
*/
compose(tokens: Iterable<Token>, forceDoc?: boolean, endOffset?: number): Generator<Document.Parsed<import("../nodes/Node.js").ParsedNode>, void, unknown>;
compose(tokens: Iterable<Token>, forceDoc?: boolean, endOffset?: number): Generator<Document.Parsed<Contents, Strict>, void, unknown>;
/** Advance the composer by one CST token. */
next(token: Token): Generator<Document.Parsed<import("../nodes/Node.js").ParsedNode>, void, unknown>;
next(token: Token): Generator<Document.Parsed<Contents, Strict>, void, unknown>;
/**
* Call at end of input to yield any remaining document.
*
* @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
* @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
*/
end(forceDoc?: boolean, endOffset?: number): Generator<Document.Parsed<import("../nodes/Node.js").ParsedNode>, void, unknown>;
end(forceDoc?: boolean, endOffset?: number): Generator<Document.Parsed<Contents, Strict>, void, unknown>;
}
export {};

View File

@@ -3,7 +3,7 @@
var directives = require('../doc/directives.js');
var Document = require('../doc/Document.js');
var errors = require('../errors.js');
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var composeDoc = require('./compose-doc.js');
var resolveEnd = require('./resolve-end.js');
@@ -83,9 +83,9 @@ class Composer {
else if (afterEmptyLine || doc.directives.docStart || !dc) {
doc.commentBefore = comment;
}
else if (Node.isCollection(dc) && !dc.flow && dc.items.length > 0) {
else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) {
let it = dc.items[0];
if (Node.isPair(it))
if (identity.isPair(it))
it = it.key;
const cb = it.commentBefore;
it.commentBefore = cb ? `${comment}\n${cb}` : comment;

View File

@@ -1,6 +1,7 @@
import type { ParsedNode } from '../nodes/Node.js';
import { YAMLMap } from '../nodes/YAMLMap.js';
import type { BlockMap } from '../parse/cst.js';
import { CollectionTag } from '../schema/types.js';
import type { ComposeContext, ComposeNode } from './compose-node.js';
import type { ComposeErrorHandler } from './composer.js';
export declare function resolveBlockMap({ composeNode, composeEmptyNode }: ComposeNode, ctx: ComposeContext, bm: BlockMap, onError: ComposeErrorHandler): YAMLMap.Parsed<ParsedNode, ParsedNode | null>;
export declare function resolveBlockMap({ composeNode, composeEmptyNode }: ComposeNode, ctx: ComposeContext, bm: BlockMap, onError: ComposeErrorHandler, tag?: CollectionTag): YAMLMap.Parsed<ParsedNode, ParsedNode | null>;

View File

@@ -8,8 +8,9 @@ var utilFlowIndentCheck = require('./util-flow-indent-check.js');
var utilMapIncludes = require('./util-map-includes.js');
const startColMsg = 'All mapping items must start at the same column';
function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError) {
const map = new YAMLMap.YAMLMap(ctx.schema);
function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) {
const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap;
const map = new NodeClass(ctx.schema);
if (ctx.atRoot)
ctx.atRoot = false;
let offset = bm.offset;

View File

@@ -1,5 +1,6 @@
import { YAMLSeq } from '../nodes/YAMLSeq.js';
import type { BlockSequence } from '../parse/cst.js';
import { CollectionTag } from '../schema/types.js';
import type { ComposeContext, ComposeNode } from './compose-node.js';
import type { ComposeErrorHandler } from './composer.js';
export declare function resolveBlockSeq({ composeNode, composeEmptyNode }: ComposeNode, ctx: ComposeContext, bs: BlockSequence, onError: ComposeErrorHandler): YAMLSeq.Parsed<import("../index.js").ParsedNode>;
export declare function resolveBlockSeq({ composeNode, composeEmptyNode }: ComposeNode, ctx: ComposeContext, bs: BlockSequence, onError: ComposeErrorHandler, tag?: CollectionTag): YAMLSeq.Parsed<import("../index.js").ParsedNode>;

View File

@@ -4,8 +4,9 @@ var YAMLSeq = require('../nodes/YAMLSeq.js');
var resolveProps = require('./resolve-props.js');
var utilFlowIndentCheck = require('./util-flow-indent-check.js');
function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError) {
const seq = new YAMLSeq.YAMLSeq(ctx.schema);
function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) {
const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq;
const seq = new NodeClass(ctx.schema);
if (ctx.atRoot)
ctx.atRoot = false;
let offset = bs.offset;

View File

@@ -1,6 +1,7 @@
import { YAMLMap } from '../nodes/YAMLMap.js';
import { YAMLSeq } from '../nodes/YAMLSeq.js';
import type { FlowCollection } from '../parse/cst.js';
import { CollectionTag } from '../schema/types.js';
import type { ComposeContext, ComposeNode } from './compose-node.js';
import type { ComposeErrorHandler } from './composer.js';
export declare function resolveFlowCollection({ composeNode, composeEmptyNode }: ComposeNode, ctx: ComposeContext, fc: FlowCollection, onError: ComposeErrorHandler): YAMLMap.Parsed<import("../nodes/Node.js").ParsedNode, import("../nodes/Node.js").ParsedNode | null> | YAMLSeq.Parsed<import("../nodes/Node.js").ParsedNode>;
export declare function resolveFlowCollection({ composeNode, composeEmptyNode }: ComposeNode, ctx: ComposeContext, fc: FlowCollection, onError: ComposeErrorHandler, tag?: CollectionTag): YAMLMap.Parsed<import("../index.js").ParsedNode, import("../index.js").ParsedNode | null> | YAMLSeq.Parsed<import("../index.js").ParsedNode>;

View File

@@ -1,6 +1,6 @@
'use strict';
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var Pair = require('../nodes/Pair.js');
var YAMLMap = require('../nodes/YAMLMap.js');
var YAMLSeq = require('../nodes/YAMLSeq.js');
@@ -11,12 +11,11 @@ var utilMapIncludes = require('./util-map-includes.js');
const blockMsg = 'Block collections are not allowed within flow collections';
const isBlock = (token) => token && (token.type === 'block-map' || token.type === 'block-seq');
function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError) {
function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {
const isMap = fc.start.source === '{';
const fcName = isMap ? 'flow map' : 'flow sequence';
const coll = isMap
? new YAMLMap.YAMLMap(ctx.schema)
: new YAMLSeq.YAMLSeq(ctx.schema);
const NodeClass = (tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq));
const coll = new NodeClass(ctx.schema);
coll.flow = true;
const atRoot = ctx.atRoot;
if (atRoot)
@@ -75,7 +74,7 @@ function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onErr
}
if (prevItemComment) {
let prev = coll.items[coll.items.length - 1];
if (Node.isPair(prev))
if (identity.isPair(prev))
prev = prev.value ?? prev.key;
if (prev.comment)
prev.comment += '\n' + prevItemComment;

View File

@@ -1,4 +1,4 @@
import { ParsedNode } from '../nodes/Node';
import { Pair } from '../nodes/Pair';
import { ComposeContext } from './compose-node';
import type { ParsedNode } from '../nodes/Node.js';
import type { Pair } from '../nodes/Pair.js';
import type { ComposeContext } from './compose-node.js';
export declare function mapIncludes(ctx: ComposeContext, items: Pair<ParsedNode>[], search: ParsedNode): boolean;

View File

@@ -1,6 +1,6 @@
'use strict';
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
function mapIncludes(ctx, items, search) {
const { uniqueKeys } = ctx.options;
@@ -9,8 +9,8 @@ function mapIncludes(ctx, items, search) {
const isEqual = typeof uniqueKeys === 'function'
? uniqueKeys
: (a, b) => a === b ||
(Node.isScalar(a) &&
Node.isScalar(b) &&
(identity.isScalar(a) &&
identity.isScalar(b) &&
a.value === b.value &&
!(a.value === '<<' && ctx.schema.merge));
return items.some(pair => isEqual(pair.key, search));

View File

@@ -1,6 +1,7 @@
import type { YAMLError, YAMLWarning } from '../errors.js';
import { Alias } from '../nodes/Alias.js';
import { Node, NodeType, NODE_TYPE, ParsedNode, Range } from '../nodes/Node.js';
import { NODE_TYPE } from '../nodes/identity.js';
import type { Node, NodeType, ParsedNode, Range } from '../nodes/Node.js';
import { Pair } from '../nodes/Pair.js';
import type { Scalar } from '../nodes/Scalar.js';
import type { YAMLMap } from '../nodes/YAMLMap.js';
@@ -8,22 +9,23 @@ import type { YAMLSeq } from '../nodes/YAMLSeq.js';
import type { CreateNodeOptions, DocumentOptions, ParseOptions, SchemaOptions, ToJSOptions, ToStringOptions } from '../options.js';
import { Schema } from '../schema/Schema.js';
import { Directives } from './directives.js';
export declare type Replacer = any[] | ((key: any, value: any) => unknown);
export type Replacer = any[] | ((key: any, value: any) => unknown);
export declare namespace Document {
interface Parsed<T extends ParsedNode = ParsedNode> extends Document<T> {
/** @ts-ignore The typing of directives fails in TS <= 4.2 */
interface Parsed<Contents extends ParsedNode = ParsedNode, Strict extends boolean = true> extends Document<Contents, Strict> {
directives: Directives;
range: Range;
}
}
export declare class Document<T extends Node = Node> {
export declare class Document<Contents extends Node = Node, Strict extends boolean = true> {
readonly [NODE_TYPE]: symbol;
/** A comment before this Document */
commentBefore: string | null;
/** A comment immediately after this Document */
comment: string | null;
/** The document contents. */
contents: T | null;
directives?: Directives;
contents: Strict extends true ? Contents | null : Contents;
directives: Strict extends true ? Directives | undefined : Directives;
/** Errors encountered during parsing. */
errors: YAMLError[];
options: Required<Omit<ParseOptions & DocumentOptions, '_directives' | 'lineCounter' | 'version'>>;
@@ -49,7 +51,7 @@ export declare class Document<T extends Node = Node> {
*
* Custom Node values that inherit from `Object` still refer to their original instances.
*/
clone(): Document<T>;
clone(): Document<Contents, Strict>;
/** Adds a value to the document. */
add(value: any): void;
/** Adds a value to the document. */
@@ -63,7 +65,7 @@ export declare class Document<T extends Node = Node> {
* `name` will be used as a prefix for a new unique anchor.
* If `name` is undefined, the generated anchor will use 'a' as a prefix.
*/
createAlias(node: Scalar | YAMLMap | YAMLSeq, name?: string): Alias;
createAlias(node: Strict extends true ? Scalar | YAMLMap | YAMLSeq : Node, name?: string): Alias;
/**
* Convert any value into a `Node` using the current schema, recursively
* turning objects into collections.
@@ -90,13 +92,13 @@ export declare class Document<T extends Node = Node> {
* scalar values from their surrounding node; to disable set `keepScalar` to
* `true` (collections are always returned intact).
*/
get(key: unknown, keepScalar?: boolean): unknown;
get(key: unknown, keepScalar?: boolean): Strict extends true ? unknown : any;
/**
* Returns item at `path`, or `undefined` if not found. By default unwraps
* scalar values from their surrounding node; to disable set `keepScalar` to
* `true` (collections are always returned intact).
*/
getIn(path: Iterable<unknown> | null, keepScalar?: boolean): unknown;
getIn(path: Iterable<unknown> | null, keepScalar?: boolean): Strict extends true ? unknown : any;
/**
* Checks if the document includes a value with the key `key`.
*/

View File

@@ -2,11 +2,10 @@
var Alias = require('../nodes/Alias.js');
var Collection = require('../nodes/Collection.js');
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var Pair = require('../nodes/Pair.js');
var toJS = require('../nodes/toJS.js');
var Schema = require('../schema/Schema.js');
var stringify = require('../stringify/stringify.js');
var stringifyDocument = require('../stringify/stringifyDocument.js');
var anchors = require('./anchors.js');
var applyReviver = require('./applyReviver.js');
@@ -23,7 +22,7 @@ class Document {
this.errors = [];
/** Warnings encountered during parsing. */
this.warnings = [];
Object.defineProperty(this, Node.NODE_TYPE, { value: Node.DOC });
Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC });
let _replacer = null;
if (typeof replacer === 'function' || Array.isArray(replacer)) {
_replacer = replacer;
@@ -51,11 +50,9 @@ class Document {
else
this.directives = new directives.Directives({ version });
this.setSchema(version, options);
if (value === undefined)
this.contents = null;
else {
this.contents = this.createNode(value, _replacer, options);
}
// @ts-expect-error We can't really know that this matches Contents.
this.contents =
value === undefined ? null : this.createNode(value, _replacer, options);
}
/**
* Create a deep copy of this Document and its contents.
@@ -64,7 +61,7 @@ class Document {
*/
clone() {
const copy = Object.create(Document.prototype, {
[Node.NODE_TYPE]: { value: Node.DOC }
[identity.NODE_TYPE]: { value: identity.DOC }
});
copy.commentBefore = this.commentBefore;
copy.comment = this.comment;
@@ -74,7 +71,8 @@ class Document {
if (this.directives)
copy.directives = this.directives.clone();
copy.schema = this.schema.clone();
copy.contents = Node.isNode(this.contents)
// @ts-expect-error We can't really know that this matches Contents.
copy.contents = identity.isNode(this.contents)
? this.contents.clone(copy.schema)
: this.contents;
if (this.range)
@@ -140,7 +138,7 @@ class Document {
sourceObjects
};
const node = createNode.createNode(value, tag, ctx);
if (flow && Node.isCollection(node))
if (flow && identity.isCollection(node))
node.flow = true;
setAnchors();
return node;
@@ -169,6 +167,7 @@ class Document {
if (Collection.isEmptyPath(path)) {
if (this.contents == null)
return false;
// @ts-expect-error Presumed impossible if Strict extends false
this.contents = null;
return true;
}
@@ -182,7 +181,7 @@ class Document {
* `true` (collections are always returned intact).
*/
get(key, keepScalar) {
return Node.isCollection(this.contents)
return identity.isCollection(this.contents)
? this.contents.get(key, keepScalar)
: undefined;
}
@@ -193,10 +192,10 @@ class Document {
*/
getIn(path, keepScalar) {
if (Collection.isEmptyPath(path))
return !keepScalar && Node.isScalar(this.contents)
return !keepScalar && identity.isScalar(this.contents)
? this.contents.value
: this.contents;
return Node.isCollection(this.contents)
return identity.isCollection(this.contents)
? this.contents.getIn(path, keepScalar)
: undefined;
}
@@ -204,7 +203,7 @@ class Document {
* Checks if the document includes a value with the key `key`.
*/
has(key) {
return Node.isCollection(this.contents) ? this.contents.has(key) : false;
return identity.isCollection(this.contents) ? this.contents.has(key) : false;
}
/**
* Checks if the document includes a value at `path`.
@@ -212,7 +211,7 @@ class Document {
hasIn(path) {
if (Collection.isEmptyPath(path))
return this.contents !== undefined;
return Node.isCollection(this.contents) ? this.contents.hasIn(path) : false;
return identity.isCollection(this.contents) ? this.contents.hasIn(path) : false;
}
/**
* Sets a value in this document. For `!!set`, `value` needs to be a
@@ -220,6 +219,7 @@ class Document {
*/
set(key, value) {
if (this.contents == null) {
// @ts-expect-error We can't really know that this matches Contents.
this.contents = Collection.collectionFromPath(this.schema, [key], value);
}
else if (assertCollection(this.contents)) {
@@ -231,9 +231,12 @@ class Document {
* boolean to add/remove the item from the set.
*/
setIn(path, value) {
if (Collection.isEmptyPath(path))
if (Collection.isEmptyPath(path)) {
// @ts-expect-error We can't really know that this matches Contents.
this.contents = value;
}
else if (this.contents == null) {
// @ts-expect-error We can't really know that this matches Contents.
this.contents = Collection.collectionFromPath(this.schema, Array.from(path), value);
}
else if (assertCollection(this.contents)) {
@@ -293,8 +296,7 @@ class Document {
keep: !json,
mapAsMap: mapAsMap === true,
mapKeyWarned: false,
maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100,
stringify: stringify.stringify
maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100
};
const res = toJS.toJS(this.contents, jsonArg ?? '', ctx);
if (typeof onAnchor === 'function')
@@ -326,7 +328,7 @@ class Document {
}
}
function assertCollection(contents) {
if (Node.isCollection(contents))
if (identity.isCollection(contents))
return true;
throw new Error('Expected a YAML collection as document contents');
}

View File

@@ -1,4 +1,4 @@
import { Node } from '../nodes/Node.js';
import type { Node } from '../nodes/Node.js';
import type { Document } from './Document.js';
/**
* Verify that the input string is a valid anchor.
@@ -6,10 +6,10 @@ import type { Document } from './Document.js';
* Will throw on errors.
*/
export declare function anchorIsValid(anchor: string): true;
export declare function anchorNames(root: Document | Node): Set<string>;
export declare function anchorNames(root: Document<Node, boolean> | Node): Set<string>;
/** Find a new anchor name with the given `prefix` and a one-indexed suffix. */
export declare function findNewAnchor(prefix: string, exclude: Set<string>): string;
export declare function createNodeAnchors(doc: Document, prefix: string): {
export declare function createNodeAnchors(doc: Document<Node, boolean>, prefix: string): {
onAnchor: (source: unknown) => string;
/**
* With circular references, the source node is only resolved after all
@@ -19,6 +19,6 @@ export declare function createNodeAnchors(doc: Document, prefix: string): {
setAnchors: () => void;
sourceObjects: Map<unknown, {
anchor: string | null;
node: Node<unknown> | null;
node: Node | null;
}>;
};

View File

@@ -1,6 +1,6 @@
'use strict';
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var visit = require('../visit.js');
/**
@@ -57,7 +57,7 @@ function createNodeAnchors(doc, prefix) {
const ref = sourceObjects.get(source);
if (typeof ref === 'object' &&
ref.anchor &&
(Node.isScalar(ref.node) || Node.isCollection(ref.node))) {
(identity.isScalar(ref.node) || identity.isCollection(ref.node))) {
ref.node.anchor = ref.anchor;
}
else {

View File

@@ -1,4 +1,4 @@
export declare type Reviver = (key: unknown, value: unknown) => unknown;
export type Reviver = (key: unknown, value: unknown) => unknown;
/**
* Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec,
* in section 24.5.1.1 "Runtime Semantics: InternalizeJSONProperty" of the

View File

@@ -1,4 +1,4 @@
import { Node } from '../nodes/Node.js';
import type { Node } from '../nodes/Node.js';
import type { Schema } from '../schema/Schema.js';
import type { CollectionTag, ScalarTag } from '../schema/types.js';
import type { Replacer } from './Document.js';

View File

@@ -1,7 +1,7 @@
'use strict';
var Alias = require('../nodes/Alias.js');
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var Scalar = require('../nodes/Scalar.js');
const defaultTagPrefix = 'tag:yaml.org,2002:';
@@ -16,12 +16,12 @@ function findTagObject(value, tagName, tags) {
return tags.find(t => t.identify?.(value) && !t.format);
}
function createNode(value, tagName, ctx) {
if (Node.isDocument(value))
if (identity.isDocument(value))
value = value.contents;
if (Node.isNode(value))
if (identity.isNode(value))
return value;
if (Node.isPair(value)) {
const map = ctx.schema[Node.MAP].createNode?.(ctx.schema, null, ctx);
if (identity.isPair(value)) {
const map = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx);
map.items.push(value);
return map;
}
@@ -65,10 +65,10 @@ function createNode(value, tagName, ctx) {
}
tagObj =
value instanceof Map
? schema[Node.MAP]
? schema[identity.MAP]
: Symbol.iterator in Object(value)
? schema[Node.SEQ]
: schema[Node.MAP];
? schema[identity.SEQ]
: schema[identity.MAP];
}
if (onTagObj) {
onTagObj(tagObj);
@@ -76,9 +76,13 @@ function createNode(value, tagName, ctx) {
}
const node = tagObj?.createNode
? tagObj.createNode(ctx.schema, value, ctx)
: new Scalar.Scalar(value);
: typeof tagObj?.nodeClass?.from === 'function'
? tagObj.nodeClass.from(ctx.schema, value, ctx)
: new Scalar.Scalar(value);
if (tagName)
node.tag = tagName;
else if (!tagObj.default)
node.tag = tagObj.tag;
if (ref)
ref.node = node;
return node;

View File

@@ -1,6 +1,6 @@
'use strict';
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var visit = require('../visit.js');
const escapeChars = {
@@ -118,12 +118,19 @@ class Directives {
onError('Verbatim tags must end with a >');
return verbatim;
}
const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/);
const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);
if (!suffix)
onError(`The ${source} tag has no suffix`);
const prefix = this.tags[handle];
if (prefix)
return prefix + decodeURIComponent(suffix);
if (prefix) {
try {
return prefix + decodeURIComponent(suffix);
}
catch (error) {
onError(String(error));
return null;
}
}
if (handle === '!')
return source; // local tag
onError(`Could not resolve tag: ${source}`);
@@ -146,10 +153,10 @@ class Directives {
: [];
const tagEntries = Object.entries(this.tags);
let tagNames;
if (doc && tagEntries.length > 0 && Node.isNode(doc.contents)) {
if (doc && tagEntries.length > 0 && identity.isNode(doc.contents)) {
const tags = {};
visit.visit(doc.contents, (_key, node) => {
if (Node.isNode(node) && node.tag)
if (identity.isNode(node) && node.tag)
tags[node.tag] = true;
});
tagNames = Object.keys(tags);

4
node_modules/yaml/dist/errors.d.ts generated vendored
View File

@@ -1,6 +1,6 @@
import type { LineCounter } from './parse/line-counter';
export declare 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' | 'MULTIPLE_ANCHORS' | 'MULTIPLE_DOCS' | 'MULTIPLE_TAGS' | 'TAB_AS_INDENT' | 'TAG_RESOLVE_FAILED' | 'UNEXPECTED_TOKEN';
export declare type LinePos = {
export 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' | 'MULTIPLE_ANCHORS' | 'MULTIPLE_DOCS' | 'MULTIPLE_TAGS' | 'TAB_AS_INDENT' | 'TAG_RESOLVE_FAILED' | 'UNEXPECTED_TOKEN' | 'BAD_COLLECTION_TYPE';
export type LinePos = {
line: number;
col: number;
};

2
node_modules/yaml/dist/errors.js generated vendored
View File

@@ -49,7 +49,7 @@ const prettifyError = (src, lc) => (error) => {
let count = 1;
const end = error.linePos[1];
if (end && end.line === line && end.col > col) {
count = Math.min(end.col - col, 80 - ci);
count = Math.max(1, Math.min(end.col - col, 80 - ci));
}
const pointer = ' '.repeat(ci) + '^'.repeat(count);
error.message += `:\n\n${lineStr}\n${pointer}\n`;

3
node_modules/yaml/dist/index.d.ts generated vendored
View File

@@ -3,7 +3,8 @@ export { Document } from './doc/Document.js';
export { Schema } from './schema/Schema.js';
export { ErrorCode, YAMLError, YAMLParseError, YAMLWarning } from './errors.js';
export { Alias } from './nodes/Alias.js';
export { isAlias, isCollection, isDocument, isMap, isNode, isPair, isScalar, isSeq, Node, ParsedNode, Range } from './nodes/Node.js';
export { isAlias, isCollection, isDocument, isMap, isNode, isPair, isScalar, isSeq } from './nodes/identity.js';
export { Node, ParsedNode, Range } from './nodes/Node.js';
export { Pair } from './nodes/Pair.js';
export { Scalar } from './nodes/Scalar.js';
export { YAMLMap } from './nodes/YAMLMap.js';

18
node_modules/yaml/dist/index.js generated vendored
View File

@@ -5,7 +5,7 @@ var Document = require('./doc/Document.js');
var Schema = require('./schema/Schema.js');
var errors = require('./errors.js');
var Alias = require('./nodes/Alias.js');
var Node = require('./nodes/Node.js');
var identity = require('./nodes/identity.js');
var Pair = require('./nodes/Pair.js');
var Scalar = require('./nodes/Scalar.js');
var YAMLMap = require('./nodes/YAMLMap.js');
@@ -26,14 +26,14 @@ exports.YAMLError = errors.YAMLError;
exports.YAMLParseError = errors.YAMLParseError;
exports.YAMLWarning = errors.YAMLWarning;
exports.Alias = Alias.Alias;
exports.isAlias = Node.isAlias;
exports.isCollection = Node.isCollection;
exports.isDocument = Node.isDocument;
exports.isMap = Node.isMap;
exports.isNode = Node.isNode;
exports.isPair = Node.isPair;
exports.isScalar = Node.isScalar;
exports.isSeq = Node.isSeq;
exports.isAlias = identity.isAlias;
exports.isCollection = identity.isCollection;
exports.isDocument = identity.isDocument;
exports.isMap = identity.isMap;
exports.isNode = identity.isNode;
exports.isPair = identity.isPair;
exports.isScalar = identity.isScalar;
exports.isSeq = identity.isSeq;
exports.Pair = Pair.Pair;
exports.Scalar = Scalar.Scalar;
exports.YAMLMap = YAMLMap.YAMLMap;

2
node_modules/yaml/dist/log.d.ts generated vendored
View File

@@ -1,3 +1,3 @@
export declare type LogLevelId = 'silent' | 'error' | 'warn' | 'debug';
export type LogLevelId = 'silent' | 'error' | 'warn' | 'debug';
export declare function debug(logLevel: LogLevelId, ...messages: any[]): void;
export declare function warn(logLevel: LogLevelId, warning: string | Error): void;

2
node_modules/yaml/dist/log.js generated vendored
View File

@@ -6,6 +6,8 @@ function debug(logLevel, ...messages) {
}
function warn(logLevel, warning) {
if (logLevel === 'debug' || logLevel === 'warn') {
// https://github.com/typescript-eslint/typescript-eslint/issues/7478
// eslint-disable-next-line @typescript-eslint/prefer-optional-chain
if (typeof process !== 'undefined' && process.emitWarning)
process.emitWarning(warning);
else

View File

@@ -3,7 +3,7 @@ import type { FlowScalar } from '../parse/cst.js';
import type { StringifyContext } from '../stringify/stringify.js';
import { NodeBase, Range } from './Node.js';
import type { Scalar } from './Scalar';
import type { ToJSContext } from './toJS.js';
import { ToJSContext } from './toJS.js';
import type { YAMLMap } from './YAMLMap.js';
import type { YAMLSeq } from './YAMLSeq.js';
export declare namespace Alias {

View File

@@ -2,11 +2,13 @@
var anchors = require('../doc/anchors.js');
var visit = require('../visit.js');
var identity = require('./identity.js');
var Node = require('./Node.js');
var toJS = require('./toJS.js');
class Alias extends Node.NodeBase {
constructor(source) {
super(Node.ALIAS);
super(identity.ALIAS);
this.source = source;
Object.defineProperty(this, 'tag', {
set() {
@@ -39,7 +41,12 @@ class Alias extends Node.NodeBase {
const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
throw new ReferenceError(msg);
}
const data = anchors.get(source);
let data = anchors.get(source);
if (!data) {
// Resolve anchors for Node.prototype.toJS()
toJS.toJS(source, null, ctx);
data = anchors.get(source);
}
/* istanbul ignore if */
if (!data || data.res === undefined) {
const msg = 'This should not happen: Alias anchor was not resolved?';
@@ -71,12 +78,12 @@ class Alias extends Node.NodeBase {
}
}
function getAliasCount(doc, node, anchors) {
if (Node.isAlias(node)) {
if (identity.isAlias(node)) {
const source = node.resolve(doc);
const anchor = anchors && source && anchors.get(source);
return anchor ? anchor.count * anchor.aliasCount : 0;
}
else if (Node.isCollection(node)) {
else if (identity.isCollection(node)) {
let count = 0;
for (const item of node.items) {
const c = getAliasCount(doc, item, anchors);
@@ -85,7 +92,7 @@ function getAliasCount(doc, node, anchors) {
}
return count;
}
else if (Node.isPair(node)) {
else if (identity.isPair(node)) {
const kc = getAliasCount(doc, node.key, anchors);
const vc = getAliasCount(doc, node.value, anchors);
return Math.max(kc, vc);

View File

@@ -1,6 +1,7 @@
import type { Schema } from '../schema/Schema.js';
import { NodeBase, NODE_TYPE } from './Node.js';
export declare function collectionFromPath(schema: Schema, path: unknown[], value: unknown): import("./Node.js").Node<unknown>;
import { NODE_TYPE } from './identity.js';
import { NodeBase } from './Node.js';
export declare function collectionFromPath(schema: Schema, path: unknown[], value: unknown): import("./Node.js").Node;
export declare const isEmptyPath: (path: Iterable<unknown> | null | undefined) => path is null | undefined;
export declare abstract class Collection extends NodeBase {
static maxFlowStringSingleLineLength: number;

View File

@@ -1,6 +1,7 @@
'use strict';
var createNode = require('../doc/createNode.js');
var identity = require('./identity.js');
var Node = require('./Node.js');
function collectionFromPath(schema, path, value) {
@@ -49,7 +50,7 @@ class Collection extends Node.NodeBase {
const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
if (schema)
copy.schema = schema;
copy.items = copy.items.map(it => Node.isNode(it) || Node.isPair(it) ? it.clone(schema) : it);
copy.items = copy.items.map(it => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it);
if (this.range)
copy.range = this.range.slice();
return copy;
@@ -65,7 +66,7 @@ class Collection extends Node.NodeBase {
else {
const [key, ...rest] = path;
const node = this.get(key, true);
if (Node.isCollection(node))
if (identity.isCollection(node))
node.addIn(rest, value);
else if (node === undefined && this.schema)
this.set(key, collectionFromPath(this.schema, rest, value));
@@ -82,7 +83,7 @@ class Collection extends Node.NodeBase {
if (rest.length === 0)
return this.delete(key);
const node = this.get(key, true);
if (Node.isCollection(node))
if (identity.isCollection(node))
return node.deleteIn(rest);
else
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
@@ -96,18 +97,18 @@ class Collection extends Node.NodeBase {
const [key, ...rest] = path;
const node = this.get(key, true);
if (rest.length === 0)
return !keepScalar && Node.isScalar(node) ? node.value : node;
return !keepScalar && identity.isScalar(node) ? node.value : node;
else
return Node.isCollection(node) ? node.getIn(rest, keepScalar) : undefined;
return identity.isCollection(node) ? node.getIn(rest, keepScalar) : undefined;
}
hasAllNullValues(allowScalar) {
return this.items.every(node => {
if (!Node.isPair(node))
if (!identity.isPair(node))
return false;
const n = node.value;
return (n == null ||
(allowScalar &&
Node.isScalar(n) &&
identity.isScalar(n) &&
n.value == null &&
!n.commentBefore &&
!n.comment &&
@@ -122,7 +123,7 @@ class Collection extends Node.NodeBase {
if (rest.length === 0)
return this.has(key);
const node = this.get(key, true);
return Node.isCollection(node) ? node.hasIn(rest) : false;
return identity.isCollection(node) ? node.hasIn(rest) : false;
}
/**
* Sets a value in this collection. For `!!set`, `value` needs to be a
@@ -135,7 +136,7 @@ class Collection extends Node.NodeBase {
}
else {
const node = this.get(key, true);
if (Node.isCollection(node))
if (identity.isCollection(node))
node.setIn(rest, value);
else if (node === undefined && this.schema)
this.set(key, collectionFromPath(this.schema, rest, value));

View File

@@ -1,36 +1,21 @@
import type { Document } from '../doc/Document.js';
import type { ToJSOptions } from '../options.js';
import { Token } from '../parse/cst.js';
import type { StringifyContext } from '../stringify/stringify.js';
import type { Alias } from './Alias.js';
import type { Pair } from './Pair.js';
import { NODE_TYPE } from './identity.js';
import type { Scalar } from './Scalar.js';
import type { YAMLMap } from './YAMLMap.js';
import type { YAMLSeq } from './YAMLSeq.js';
export declare type Node<T = unknown> = Alias | Scalar<T> | YAMLMap<unknown, T> | YAMLSeq<T>;
export type Node<T = unknown> = Alias | Scalar<T> | YAMLMap<unknown, T> | YAMLSeq<T>;
/** Utility type mapper */
export declare type NodeType<T> = T extends string | number | bigint | boolean | null ? Scalar<T> : T extends Array<any> ? YAMLSeq<NodeType<T[number]>> : T extends {
export type NodeType<T> = T extends string | number | bigint | boolean | null | undefined ? Scalar<T> : T extends Date ? Scalar<string | Date> : T extends Array<any> ? YAMLSeq<NodeType<T[number]>> : T extends {
[key: string]: any;
} ? YAMLMap<NodeType<keyof T>, NodeType<T[keyof T]>> : T extends {
[key: number]: any;
} ? YAMLMap<NodeType<keyof T>, NodeType<T[keyof T]>> : Node;
export declare type ParsedNode = Alias.Parsed | Scalar.Parsed | YAMLMap.Parsed | YAMLSeq.Parsed;
export declare type Range = [number, number, number];
export declare const ALIAS: unique symbol;
export declare const DOC: unique symbol;
export declare const MAP: unique symbol;
export declare const PAIR: unique symbol;
export declare const SCALAR: unique symbol;
export declare const SEQ: unique symbol;
export declare const NODE_TYPE: unique symbol;
export declare const isAlias: (node: any) => node is Alias;
export declare const isDocument: <T extends Node<unknown> = Node<unknown>>(node: any) => node is Document<T>;
export declare const isMap: <K = unknown, V = unknown>(node: any) => node is YAMLMap<K, V>;
export declare const isPair: <K = unknown, V = unknown>(node: any) => node is Pair<K, V>;
export declare const isScalar: <T = unknown>(node: any) => node is Scalar<T>;
export declare const isSeq: <T = unknown>(node: any) => node is YAMLSeq<T>;
export declare function isCollection<K = unknown, V = unknown>(node: any): node is YAMLMap<K, V> | YAMLSeq<V>;
export declare function isNode<T = unknown>(node: any): node is Node<T>;
export declare const hasAnchor: <K = unknown, V = unknown>(node: unknown) => node is Scalar<V> | YAMLMap<K, V> | YAMLSeq<V>;
export type ParsedNode = Alias.Parsed | Scalar.Parsed | YAMLMap.Parsed | YAMLSeq.Parsed;
export type Range = [number, number, number];
export declare abstract class NodeBase {
readonly [NODE_TYPE]: symbol;
/** A comment on or immediately after this */
@@ -56,4 +41,6 @@ export declare abstract class NodeBase {
constructor(type: symbol);
/** Create a copy of this node. */
clone(): NodeBase;
/** A plain JavaScript representation of this node. */
toJS(doc: Document<Node, boolean>, { mapAsMap, maxAliasCount, onAnchor, reviver }?: ToJSOptions): any;
}

76
node_modules/yaml/dist/nodes/Node.js generated vendored
View File

@@ -1,42 +1,12 @@
'use strict';
const ALIAS = Symbol.for('yaml.alias');
const DOC = Symbol.for('yaml.document');
const MAP = Symbol.for('yaml.map');
const PAIR = Symbol.for('yaml.pair');
const SCALAR = Symbol.for('yaml.scalar');
const SEQ = Symbol.for('yaml.seq');
const NODE_TYPE = Symbol.for('yaml.node.type');
const isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS;
const isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC;
const isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP;
const isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR;
const isScalar = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR;
const isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ;
function isCollection(node) {
if (node && typeof node === 'object')
switch (node[NODE_TYPE]) {
case MAP:
case SEQ:
return true;
}
return false;
}
function isNode(node) {
if (node && typeof node === 'object')
switch (node[NODE_TYPE]) {
case ALIAS:
case MAP:
case SCALAR:
case SEQ:
return true;
}
return false;
}
const hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;
var applyReviver = require('../doc/applyReviver.js');
var identity = require('./identity.js');
var toJS = require('./toJS.js');
class NodeBase {
constructor(type) {
Object.defineProperty(this, NODE_TYPE, { value: type });
Object.defineProperty(this, identity.NODE_TYPE, { value: type });
}
/** Create a copy of this node. */
clone() {
@@ -45,22 +15,26 @@ class NodeBase {
copy.range = this.range.slice();
return copy;
}
/** A plain JavaScript representation of this node. */
toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
if (!identity.isDocument(doc))
throw new TypeError('A document argument is required');
const ctx = {
anchors: new Map(),
doc,
keep: true,
mapAsMap: mapAsMap === true,
mapKeyWarned: false,
maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100
};
const res = toJS.toJS(this, '', ctx);
if (typeof onAnchor === 'function')
for (const { count, res } of ctx.anchors.values())
onAnchor(res, count);
return typeof reviver === 'function'
? applyReviver.applyReviver(reviver, { '': res }, '', res)
: res;
}
}
exports.ALIAS = ALIAS;
exports.DOC = DOC;
exports.MAP = MAP;
exports.NODE_TYPE = NODE_TYPE;
exports.NodeBase = NodeBase;
exports.PAIR = PAIR;
exports.SCALAR = SCALAR;
exports.SEQ = SEQ;
exports.hasAnchor = hasAnchor;
exports.isAlias = isAlias;
exports.isCollection = isCollection;
exports.isDocument = isDocument;
exports.isMap = isMap;
exports.isNode = isNode;
exports.isPair = isPair;
exports.isScalar = isScalar;
exports.isSeq = isSeq;

View File

@@ -3,9 +3,9 @@ import type { CollectionItem } from '../parse/cst.js';
import type { Schema } from '../schema/Schema.js';
import type { StringifyContext } from '../stringify/stringify.js';
import { addPairToJSMap } from './addPairToJSMap.js';
import { NODE_TYPE } from './Node.js';
import { NODE_TYPE } from './identity.js';
import type { ToJSContext } from './toJS.js';
export declare function createPair(key: unknown, value: unknown, ctx: CreateNodeContext): Pair<import("./Node.js").Node<unknown>, import("./Alias.js").Alias | import("./Scalar.js").Scalar<unknown> | import("./YAMLMap.js").YAMLMap<unknown, unknown> | import("./YAMLSeq.js").YAMLSeq<unknown>>;
export declare function createPair(key: unknown, value: unknown, ctx: CreateNodeContext): Pair<import("./Node.js").Node, import("./YAMLMap.js").YAMLMap<unknown, unknown> | import("./Scalar.js").Scalar<unknown> | import("./Alias.js").Alias | import("./YAMLSeq.js").YAMLSeq<unknown>>;
export declare class Pair<K = unknown, V = unknown> {
readonly [NODE_TYPE]: symbol;
/** Always Node or null when parsed, but can be set to anything. */

View File

@@ -3,7 +3,7 @@
var createNode = require('../doc/createNode.js');
var stringifyPair = require('../stringify/stringifyPair.js');
var addPairToJSMap = require('./addPairToJSMap.js');
var Node = require('./Node.js');
var identity = require('./identity.js');
function createPair(key, value, ctx) {
const k = createNode.createNode(key, undefined, ctx);
@@ -12,15 +12,15 @@ function createPair(key, value, ctx) {
}
class Pair {
constructor(key, value = null) {
Object.defineProperty(this, Node.NODE_TYPE, { value: Node.PAIR });
Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR });
this.key = key;
this.value = value;
}
clone(schema) {
let { key, value } = this;
if (Node.isNode(key))
if (identity.isNode(key))
key = key.clone(schema);
if (Node.isNode(value))
if (identity.isNode(value))
value = value.clone(schema);
return new Pair(key, value);
}

View File

@@ -1,12 +1,13 @@
'use strict';
var identity = require('./identity.js');
var Node = require('./Node.js');
var toJS = require('./toJS.js');
const isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object');
class Scalar extends Node.NodeBase {
constructor(value) {
super(Node.SCALAR);
super(identity.SCALAR);
this.value = value;
}
toJSON(arg, ctx) {

View File

@@ -1,12 +1,13 @@
import type { BlockMap, FlowCollection } from '../parse/cst.js';
import type { Schema } from '../schema/Schema.js';
import type { StringifyContext } from '../stringify/stringify.js';
import { CreateNodeContext } from '../util.js';
import { Collection } from './Collection.js';
import { ParsedNode, Range } from './Node.js';
import type { ParsedNode, Range } from './Node.js';
import { Pair } from './Pair.js';
import { Scalar } from './Scalar.js';
import type { ToJSContext } from './toJS.js';
export declare type MapLike = Map<unknown, unknown> | Set<unknown> | Record<string | number | symbol, unknown>;
export type MapLike = Map<unknown, unknown> | Set<unknown> | Record<string | number | symbol, unknown>;
export declare function findPair<K = unknown, V = unknown>(items: Iterable<Pair<K, V>>, key: unknown): Pair<K, V> | undefined;
export declare namespace YAMLMap {
interface Parsed<K extends ParsedNode = ParsedNode, V extends ParsedNode | null = ParsedNode | null> extends YAMLMap<K, V> {
@@ -19,6 +20,11 @@ export declare class YAMLMap<K = unknown, V = unknown> extends Collection {
static get tagName(): 'tag:yaml.org,2002:map';
items: Pair<K, V>[];
constructor(schema?: Schema);
/**
* A generic collection parsing method that can be extended
* to other node classes that inherit from YAMLMap
*/
static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLMap<unknown, unknown>;
/**
* Adds a value to the collection.
*

View File

@@ -3,30 +3,58 @@
var stringifyCollection = require('../stringify/stringifyCollection.js');
var addPairToJSMap = require('./addPairToJSMap.js');
var Collection = require('./Collection.js');
var Node = require('./Node.js');
var identity = require('./identity.js');
var Pair = require('./Pair.js');
var Scalar = require('./Scalar.js');
function findPair(items, key) {
const k = Node.isScalar(key) ? key.value : key;
const k = identity.isScalar(key) ? key.value : key;
for (const it of items) {
if (Node.isPair(it)) {
if (identity.isPair(it)) {
if (it.key === key || it.key === k)
return it;
if (Node.isScalar(it.key) && it.key.value === k)
if (identity.isScalar(it.key) && it.key.value === k)
return it;
}
}
return undefined;
}
class YAMLMap extends Collection.Collection {
constructor(schema) {
super(Node.MAP, schema);
this.items = [];
}
static get tagName() {
return 'tag:yaml.org,2002:map';
}
constructor(schema) {
super(identity.MAP, schema);
this.items = [];
}
/**
* A generic collection parsing method that can be extended
* to other node classes that inherit from YAMLMap
*/
static from(schema, obj, ctx) {
const { keepUndefined, replacer } = ctx;
const map = new this(schema);
const add = (key, value) => {
if (typeof replacer === 'function')
value = replacer.call(obj, key, value);
else if (Array.isArray(replacer) && !replacer.includes(key))
return;
if (value !== undefined || keepUndefined)
map.items.push(Pair.createPair(key, value, ctx));
};
if (obj instanceof Map) {
for (const [key, value] of obj)
add(key, value);
}
else if (obj && typeof obj === 'object') {
for (const key of Object.keys(obj))
add(key, obj[key]);
}
if (typeof schema.sortMapEntries === 'function') {
map.items.sort(schema.sortMapEntries);
}
return map;
}
/**
* Adds a value to the collection.
*
@@ -35,7 +63,7 @@ class YAMLMap extends Collection.Collection {
*/
add(pair, overwrite) {
let _pair;
if (Node.isPair(pair))
if (identity.isPair(pair))
_pair = pair;
else if (!pair || typeof pair !== 'object' || !('key' in pair)) {
// In TypeScript, this never happens.
@@ -49,7 +77,7 @@ class YAMLMap extends Collection.Collection {
if (!overwrite)
throw new Error(`Key ${_pair.key} already set`);
// For scalars, keep the old node & its comments and anchors
if (Node.isScalar(prev.value) && Scalar.isScalarValue(_pair.value))
if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value))
prev.value.value = _pair.value;
else
prev.value = _pair.value;
@@ -75,7 +103,7 @@ class YAMLMap extends Collection.Collection {
get(key, keepScalar) {
const it = findPair(this.items, key);
const node = it?.value;
return (!keepScalar && Node.isScalar(node) ? node.value : node) ?? undefined;
return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? undefined;
}
has(key) {
return !!findPair(this.items, key);
@@ -100,7 +128,7 @@ class YAMLMap extends Collection.Collection {
if (!ctx)
return JSON.stringify(this);
for (const item of this.items) {
if (!Node.isPair(item))
if (!identity.isPair(item))
throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
}
if (!ctx.allNullValues && this.hasAllNullValues(false))

View File

@@ -1,8 +1,9 @@
import { CreateNodeContext } from '../doc/createNode.js';
import type { BlockSequence, FlowCollection } from '../parse/cst.js';
import type { Schema } from '../schema/Schema.js';
import type { StringifyContext } from '../stringify/stringify.js';
import { Collection } from './Collection.js';
import { ParsedNode, Range } from './Node.js';
import type { ParsedNode, Range } from './Node.js';
import type { Pair } from './Pair.js';
import { Scalar } from './Scalar.js';
import { ToJSContext } from './toJS.js';
@@ -55,4 +56,5 @@ export declare class YAMLSeq<T = unknown> extends Collection {
set(key: unknown, value: T): void;
toJSON(_?: unknown, ctx?: ToJSContext): unknown[];
toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string;
static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLSeq<unknown>;
}

View File

@@ -1,19 +1,20 @@
'use strict';
var createNode = require('../doc/createNode.js');
var stringifyCollection = require('../stringify/stringifyCollection.js');
var Collection = require('./Collection.js');
var Node = require('./Node.js');
var identity = require('./identity.js');
var Scalar = require('./Scalar.js');
var toJS = require('./toJS.js');
class YAMLSeq extends Collection.Collection {
constructor(schema) {
super(Node.SEQ, schema);
this.items = [];
}
static get tagName() {
return 'tag:yaml.org,2002:seq';
}
constructor(schema) {
super(identity.SEQ, schema);
this.items = [];
}
add(value) {
this.items.push(value);
}
@@ -37,7 +38,7 @@ class YAMLSeq extends Collection.Collection {
if (typeof idx !== 'number')
return undefined;
const it = this.items[idx];
return !keepScalar && Node.isScalar(it) ? it.value : it;
return !keepScalar && identity.isScalar(it) ? it.value : it;
}
/**
* Checks if the collection includes a value with the key `key`.
@@ -61,7 +62,7 @@ class YAMLSeq extends Collection.Collection {
if (typeof idx !== 'number')
throw new Error(`Expected a valid index, not ${key}.`);
const prev = this.items[idx];
if (Node.isScalar(prev) && Scalar.isScalarValue(value))
if (identity.isScalar(prev) && Scalar.isScalarValue(value))
prev.value = value;
else
this.items[idx] = value;
@@ -86,9 +87,24 @@ class YAMLSeq extends Collection.Collection {
onComment
});
}
static from(schema, obj, ctx) {
const { replacer } = ctx;
const seq = new this(schema);
if (obj && Symbol.iterator in Object(obj)) {
let i = 0;
for (let it of obj) {
if (typeof replacer === 'function') {
const key = obj instanceof Set ? it : String(i++);
it = replacer.call(obj, key, it);
}
seq.items.push(createNode.createNode(it, undefined, ctx));
}
}
return seq;
}
}
function asItemIndex(key) {
let idx = Node.isScalar(key) ? key.value : key;
let idx = identity.isScalar(key) ? key.value : key;
if (idx && typeof idx === 'string')
idx = Number(idx);
return typeof idx === 'number' && Number.isInteger(idx) && idx >= 0

View File

@@ -2,15 +2,15 @@
var log = require('../log.js');
var stringify = require('../stringify/stringify.js');
var Node = require('./Node.js');
var identity = require('./identity.js');
var Scalar = require('./Scalar.js');
var toJS = require('./toJS.js');
const MERGE_KEY = '<<';
function addPairToJSMap(ctx, map, { key, value }) {
if (ctx?.doc.schema.merge && isMergeKey(key)) {
value = Node.isAlias(value) ? value.resolve(ctx.doc) : value;
if (Node.isSeq(value))
value = identity.isAlias(value) ? value.resolve(ctx.doc) : value;
if (identity.isSeq(value))
for (const it of value.items)
mergeToJSMap(ctx, map, it);
else if (Array.isArray(value))
@@ -44,7 +44,7 @@ function addPairToJSMap(ctx, map, { key, value }) {
return map;
}
const isMergeKey = (key) => key === MERGE_KEY ||
(Node.isScalar(key) &&
(identity.isScalar(key) &&
key.value === MERGE_KEY &&
(!key.type || key.type === Scalar.Scalar.PLAIN));
// If the value associated with a merge key is a single mapping node, each of
@@ -55,8 +55,8 @@ const isMergeKey = (key) => key === MERGE_KEY ||
// Keys in mapping nodes earlier in the sequence override keys specified in
// later mapping nodes. -- http://yaml.org/type/merge.html
function mergeToJSMap(ctx, map, value) {
const source = ctx && Node.isAlias(value) ? value.resolve(ctx.doc) : value;
if (!Node.isMap(source))
const source = ctx && identity.isAlias(value) ? value.resolve(ctx.doc) : value;
if (!identity.isMap(source))
throw new Error('Merge sources must be maps or map aliases');
const srcMap = source.toJSON(null, ctx, Map);
for (const [key, value] of srcMap) {
@@ -83,7 +83,7 @@ function stringifyKey(key, jsKey, ctx) {
return '';
if (typeof jsKey !== 'object')
return String(jsKey);
if (Node.isNode(key) && ctx && ctx.doc) {
if (identity.isNode(key) && ctx?.doc) {
const strCtx = stringify.createStringifyContext(ctx.doc, {});
strCtx.anchors = new Set();
for (const node of ctx.anchors.keys())

23
node_modules/yaml/dist/nodes/identity.d.ts generated vendored Normal file
View File

@@ -0,0 +1,23 @@
import type { Document } from '../doc/Document.js';
import type { Alias } from './Alias.js';
import type { Node } from './Node.js';
import type { Pair } from './Pair.js';
import type { Scalar } from './Scalar.js';
import type { YAMLMap } from './YAMLMap.js';
import type { YAMLSeq } from './YAMLSeq.js';
export declare const ALIAS: unique symbol;
export declare const DOC: unique symbol;
export declare const MAP: unique symbol;
export declare const PAIR: unique symbol;
export declare const SCALAR: unique symbol;
export declare const SEQ: unique symbol;
export declare const NODE_TYPE: unique symbol;
export declare const isAlias: (node: any) => node is Alias;
export declare const isDocument: <T extends Node = Node>(node: any) => node is Document<T, true>;
export declare const isMap: <K = unknown, V = unknown>(node: any) => node is YAMLMap<K, V>;
export declare const isPair: <K = unknown, V = unknown>(node: any) => node is Pair<K, V>;
export declare const isScalar: <T = unknown>(node: any) => node is Scalar<T>;
export declare const isSeq: <T = unknown>(node: any) => node is YAMLSeq<T>;
export declare function isCollection<K = unknown, V = unknown>(node: any): node is YAMLMap<K, V> | YAMLSeq<V>;
export declare function isNode<T = unknown>(node: any): node is Node<T>;
export declare const hasAnchor: <K = unknown, V = unknown>(node: unknown) => node is Scalar<V> | YAMLMap<K, V> | YAMLSeq<V>;

53
node_modules/yaml/dist/nodes/identity.js generated vendored Normal file
View File

@@ -0,0 +1,53 @@
'use strict';
const ALIAS = Symbol.for('yaml.alias');
const DOC = Symbol.for('yaml.document');
const MAP = Symbol.for('yaml.map');
const PAIR = Symbol.for('yaml.pair');
const SCALAR = Symbol.for('yaml.scalar');
const SEQ = Symbol.for('yaml.seq');
const NODE_TYPE = Symbol.for('yaml.node.type');
const isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS;
const isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC;
const isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP;
const isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR;
const isScalar = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR;
const isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ;
function isCollection(node) {
if (node && typeof node === 'object')
switch (node[NODE_TYPE]) {
case MAP:
case SEQ:
return true;
}
return false;
}
function isNode(node) {
if (node && typeof node === 'object')
switch (node[NODE_TYPE]) {
case ALIAS:
case MAP:
case SCALAR:
case SEQ:
return true;
}
return false;
}
const hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;
exports.ALIAS = ALIAS;
exports.DOC = DOC;
exports.MAP = MAP;
exports.NODE_TYPE = NODE_TYPE;
exports.PAIR = PAIR;
exports.SCALAR = SCALAR;
exports.SEQ = SEQ;
exports.hasAnchor = hasAnchor;
exports.isAlias = isAlias;
exports.isCollection = isCollection;
exports.isDocument = isDocument;
exports.isMap = isMap;
exports.isNode = isNode;
exports.isPair = isPair;
exports.isScalar = isScalar;
exports.isSeq = isSeq;

View File

@@ -1,6 +1,5 @@
import type { Document } from '../doc/Document.js';
import type { stringify } from '../stringify/stringify.js';
import { Node } from './Node.js';
import type { Node } from './Node.js';
export interface AnchorData {
aliasCount: number;
count: number;
@@ -8,14 +7,12 @@ export interface AnchorData {
}
export interface ToJSContext {
anchors: Map<Node, AnchorData>;
doc: Document;
doc: Document<Node, boolean>;
keep: boolean;
mapAsMap: boolean;
mapKeyWarned: boolean;
maxAliasCount: number;
onCreate?: (res: unknown) => void;
/** Requiring this directly in Pair would create circular dependencies */
stringify: typeof stringify;
}
/**
* Recursively convert any node or its contents to native JavaScript

View File

@@ -1,6 +1,6 @@
'use strict';
var Node = require('./Node.js');
var identity = require('./identity.js');
/**
* Recursively convert any node or its contents to native JavaScript
@@ -18,7 +18,7 @@ function toJS(value, arg, ctx) {
return value.map((v, i) => toJS(v, String(i), ctx));
if (value && typeof value.toJSON === 'function') {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
if (!ctx || !Node.hasAnchor(value))
if (!ctx || !identity.hasAnchor(value))
return value.toJSON(arg, ctx);
const data = { aliasCount: 0, count: 1, res: undefined };
ctx.anchors.set(value, data);

19
node_modules/yaml/dist/options.d.ts generated vendored
View File

@@ -8,7 +8,7 @@ import type { LineCounter } from './parse/line-counter.js';
import type { Schema } from './schema/Schema.js';
import type { Tags } from './schema/tags.js';
import type { CollectionTag, ScalarTag } from './schema/types.js';
export declare type ParseOptions = {
export type ParseOptions = {
/**
* Whether integers should be parsed into BigInt rather than number values.
*
@@ -56,7 +56,7 @@ export declare type ParseOptions = {
*/
uniqueKeys?: boolean | ((a: ParsedNode, b: ParsedNode) => boolean);
};
export declare type DocumentOptions = {
export type DocumentOptions = {
/**
* @internal
* Used internally by Composer. If set and includes an explicit version,
@@ -76,7 +76,7 @@ export declare type DocumentOptions = {
*/
version?: '1.1' | '1.2' | 'next';
};
export declare type SchemaOptions = {
export type SchemaOptions = {
/**
* When parsing, warn about compatibility issues with the given schema.
* When stringifying, use scalar styles that are parsed correctly
@@ -133,7 +133,7 @@ export declare type SchemaOptions = {
*/
toStringDefaults?: ToStringOptions;
};
export declare type CreateNodeOptions = {
export type CreateNodeOptions = {
/**
* During node construction, use anchors and aliases to keep strictly equal
* non-null objects as equivalent in YAML.
@@ -163,7 +163,7 @@ export declare type CreateNodeOptions = {
*/
tag?: string;
};
export declare type ToJSOptions = {
export type ToJSOptions = {
/**
* Use Map rather than Object to represent mappings.
*
@@ -189,7 +189,7 @@ export declare type ToJSOptions = {
*/
reviver?: Reviver;
};
export declare type ToStringOptions = {
export type ToStringOptions = {
/**
* Use block quote styles for scalar values where applicable.
* Set to `false` to disable block quotes completely.
@@ -264,6 +264,13 @@ export declare type ToStringOptions = {
* Default: `'false'`
*/
falseStr?: string;
/**
* When true, a single space of padding will be added inside the delimiters
* of non-empty single-line flow collections.
*
* Default: `true`
*/
flowCollectionPadding?: boolean;
/**
* The number of spaces to use when indenting code.
*

View File

@@ -1,6 +1,6 @@
import type { CollectionItem, Document } from './cst.js';
export declare type VisitPath = readonly ['key' | 'value', number][];
export declare type Visitor = (item: CollectionItem, path: VisitPath) => number | symbol | Visitor | void;
export type VisitPath = readonly ['key' | 'value', number][];
export type Visitor = (item: CollectionItem, path: VisitPath) => number | symbol | Visitor | void;
/**
* Apply a visitor to a CST document or item.
*

View File

@@ -72,7 +72,7 @@ export interface BlockSequence {
value?: Token;
}>;
}
export declare type CollectionItem = {
export type CollectionItem = {
start: SourceToken[];
key?: Token | null;
sep?: SourceToken[];
@@ -86,8 +86,8 @@ export interface FlowCollection {
items: CollectionItem[];
end: SourceToken[];
}
export declare type Token = SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection;
export declare type TokenType = SourceToken['type'] | DocumentEnd['type'] | FlowScalar['type'];
export type Token = SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection;
export type TokenType = SourceToken['type'] | DocumentEnd['type'] | FlowScalar['type'];
/** The byte order mark */
export declare const BOM = "\uFEFF";
/** Start of doc-mode */

View File

@@ -1,7 +1,7 @@
import { Composer } from './compose/composer.js';
import type { Reviver } from './doc/applyReviver.js';
import { Document, Replacer } from './doc/Document.js';
import type { ParsedNode } from './nodes/Node.js';
import type { Node, ParsedNode } from './nodes/Node.js';
import type { CreateNodeOptions, DocumentOptions, ParseOptions, SchemaOptions, ToJSOptions, ToStringOptions } from './options.js';
export interface EmptyStream extends Array<Document.Parsed>, ReturnType<Composer['streamInfo']> {
empty: true;
@@ -15,9 +15,9 @@ export interface EmptyStream extends Array<Document.Parsed>, ReturnType<Composer
* EmptyStream and contain additional stream information. In
* TypeScript, you should use `'empty' in docs` as a type guard for it.
*/
export declare function parseAllDocuments<T extends ParsedNode = ParsedNode>(source: string, options?: ParseOptions & DocumentOptions & SchemaOptions): Document.Parsed<T>[] | EmptyStream;
export declare function parseAllDocuments<Contents extends Node = ParsedNode, Strict extends boolean = true>(source: string, options?: ParseOptions & DocumentOptions & SchemaOptions): Array<Contents extends ParsedNode ? Document.Parsed<Contents, Strict> : Document<Contents, Strict>> | EmptyStream;
/** Parse an input string into a single YAML.Document */
export declare function parseDocument<T extends ParsedNode = ParsedNode>(source: string, options?: ParseOptions & DocumentOptions & SchemaOptions): Document.Parsed<T>;
export declare function parseDocument<Contents extends Node = ParsedNode, Strict extends boolean = true>(source: string, options?: ParseOptions & DocumentOptions & SchemaOptions): Contents extends ParsedNode ? Document.Parsed<Contents, Strict> : Document<Contents, Strict>;
/**
* Parse an input string into JavaScript.
*

View File

@@ -1,4 +1,4 @@
import { MAP, SCALAR, SEQ } from '../nodes/Node.js';
import { MAP, SCALAR, SEQ } from '../nodes/identity.js';
import type { Pair } from '../nodes/Pair.js';
import type { SchemaOptions, ToStringOptions } from '../options.js';
import type { CollectionTag, ScalarTag } from './types.js';

View File

@@ -1,6 +1,6 @@
'use strict';
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var map = require('./common/map.js');
var seq = require('./common/seq.js');
var string = require('./common/string.js');
@@ -19,9 +19,9 @@ class Schema {
this.knownTags = resolveKnownTags ? tags.coreKnownTags : {};
this.tags = tags.getTags(customTags, this.name);
this.toStringOptions = toStringDefaults ?? null;
Object.defineProperty(this, Node.MAP, { value: map.map });
Object.defineProperty(this, Node.SCALAR, { value: string.string });
Object.defineProperty(this, Node.SEQ, { value: seq.seq });
Object.defineProperty(this, identity.MAP, { value: map.map });
Object.defineProperty(this, identity.SCALAR, { value: string.string });
Object.defineProperty(this, identity.SEQ, { value: seq.seq });
// Used by createMap()
this.sortMapEntries =
typeof sortMapEntries === 'function'

View File

@@ -1,44 +1,19 @@
'use strict';
var Node = require('../../nodes/Node.js');
var Pair = require('../../nodes/Pair.js');
var identity = require('../../nodes/identity.js');
var YAMLMap = require('../../nodes/YAMLMap.js');
function createMap(schema, obj, ctx) {
const { keepUndefined, replacer } = ctx;
const map = new YAMLMap.YAMLMap(schema);
const add = (key, value) => {
if (typeof replacer === 'function')
value = replacer.call(obj, key, value);
else if (Array.isArray(replacer) && !replacer.includes(key))
return;
if (value !== undefined || keepUndefined)
map.items.push(Pair.createPair(key, value, ctx));
};
if (obj instanceof Map) {
for (const [key, value] of obj)
add(key, value);
}
else if (obj && typeof obj === 'object') {
for (const key of Object.keys(obj))
add(key, obj[key]);
}
if (typeof schema.sortMapEntries === 'function') {
map.items.sort(schema.sortMapEntries);
}
return map;
}
const map = {
collection: 'map',
createNode: createMap,
default: true,
nodeClass: YAMLMap.YAMLMap,
tag: 'tag:yaml.org,2002:map',
resolve(map, onError) {
if (!Node.isMap(map))
if (!identity.isMap(map))
onError('Expected a mapping for this tag');
return map;
}
},
createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx)
};
exports.map = map;

View File

@@ -1,35 +1,19 @@
'use strict';
var createNode = require('../../doc/createNode.js');
var Node = require('../../nodes/Node.js');
var identity = require('../../nodes/identity.js');
var YAMLSeq = require('../../nodes/YAMLSeq.js');
function createSeq(schema, obj, ctx) {
const { replacer } = ctx;
const seq = new YAMLSeq.YAMLSeq(schema);
if (obj && Symbol.iterator in Object(obj)) {
let i = 0;
for (let it of obj) {
if (typeof replacer === 'function') {
const key = obj instanceof Set ? it : String(i++);
it = replacer.call(obj, key, it);
}
seq.items.push(createNode.createNode(it, undefined, ctx));
}
}
return seq;
}
const seq = {
collection: 'seq',
createNode: createSeq,
default: true,
nodeClass: YAMLSeq.YAMLSeq,
tag: 'tag:yaml.org,2002:seq',
resolve(seq, onError) {
if (!Node.isSeq(seq))
if (!identity.isSeq(seq))
onError('Expected a sequence for this tag');
return seq;
}
},
createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx)
};
exports.seq = seq;

View File

@@ -1 +1 @@
export declare const schema: (import("../types.js").ScalarTag | import("../types.js").CollectionTag)[];
export declare const schema: (import("../types.js").CollectionTag | import("../types.js").ScalarTag)[];

View File

@@ -1,5 +1,5 @@
declare type JsonSchema = boolean | ArraySchema | ObjectSchema | NumberSchema | StringSchema;
declare type JsonType = 'array' | 'object' | 'string' | 'number' | 'integer' | 'boolean' | 'null';
type JsonSchema = boolean | ArraySchema | ObjectSchema | NumberSchema | StringSchema;
type JsonType = 'array' | 'object' | 'string' | 'number' | 'integer' | 'boolean' | 'null';
interface CommonSchema {
type?: JsonType | JsonType[];
const?: unknown;

View File

@@ -1,2 +1,2 @@
import { CollectionTag, ScalarTag } from '../types.js';
export declare const schema: (ScalarTag | CollectionTag)[];
export declare const schema: (CollectionTag | ScalarTag)[];

View File

@@ -25,8 +25,8 @@ declare const tagsByName: {
test: RegExp;
};
};
export declare type TagId = keyof typeof tagsByName;
export declare type Tags = Array<ScalarTag | CollectionTag | TagId>;
export type TagId = keyof typeof tagsByName;
export type Tags = Array<ScalarTag | CollectionTag | TagId>;
export declare const coreKnownTags: {
'tag:yaml.org,2002:binary': ScalarTag;
'tag:yaml.org,2002:omap': CollectionTag;
@@ -36,5 +36,5 @@ export declare const coreKnownTags: {
test: RegExp;
};
};
export declare function getTags(customTags: SchemaOptions['customTags'] | undefined, schemaName: string): (ScalarTag | CollectionTag)[];
export declare function getTags(customTags: SchemaOptions['customTags'] | undefined, schemaName: string): (CollectionTag | ScalarTag)[];
export {};

View File

@@ -1,11 +1,11 @@
import type { CreateNodeContext } from '../doc/createNode.js';
import type { Schema } from './Schema.js';
import type { Node } from '../nodes/Node.js';
import type { Scalar } from '../nodes/Scalar.js';
import type { YAMLMap } from '../nodes/YAMLMap.js';
import type { YAMLSeq } from '../nodes/YAMLSeq.js';
import type { ParseOptions } from '../options.js';
import type { StringifyContext } from '../stringify/stringify.js';
import type { Schema } from './Schema.js';
interface TagBase {
/**
* An optional factory function, used e.g. by collections when wrapping JS objects as AST nodes.
@@ -16,7 +16,7 @@ interface TagBase {
* an explicit tag. For most cases, it's unlikely that you'll actually want to
* use this, even if you first think you do.
*/
default: boolean;
default?: boolean;
/**
* If a tag has multiple forms that should be parsed and/or stringified
* differently, use `format` to identify them.
@@ -71,12 +71,20 @@ export interface CollectionTag extends TagBase {
/**
* The `Node` child class that implements this tag.
* If set, used to select this tag when stringifying.
*
* If the class provides a static `from` method, then that
* will be used if the tag object doesn't have a `createNode` method.
*/
nodeClass?: new () => Node;
nodeClass?: {
new (schema?: Schema): Node;
from?: (schema: Schema, obj: unknown, ctx: CreateNodeContext) => Node;
};
/**
* Turns a value into an AST node.
* If returning a non-`Node` value, the output will be wrapped as a `Scalar`.
*
* Note: this is required if nodeClass is not provided.
*/
resolve(value: YAMLMap.Parsed | YAMLSeq.Parsed, onError: (message: string) => void, options: ParseOptions): unknown;
resolve?: (value: YAMLMap.Parsed | YAMLSeq.Parsed, onError: (message: string) => void, options: ParseOptions) => unknown;
}
export {};

View File

@@ -1,5 +1,7 @@
import { YAMLSeq } from '../../nodes/YAMLSeq.js';
import { ToJSContext } from '../../nodes/toJS.js';
import { YAMLSeq } from '../../nodes/YAMLSeq.js';
import { CreateNodeContext } from '../../util.js';
import type { Schema } from '../Schema.js';
import { CollectionTag } from '../types.js';
export declare class YAMLOMap extends YAMLSeq {
static tag: string;
@@ -21,5 +23,6 @@ export declare class YAMLOMap extends YAMLSeq {
* but TypeScript won't allow widening the signature of a child method.
*/
toJSON(_?: unknown, ctx?: ToJSContext): unknown[];
static from(schema: Schema, iterable: unknown, ctx: CreateNodeContext): YAMLOMap;
}
export declare const omap: CollectionTag;

View File

@@ -1,9 +1,9 @@
'use strict';
var YAMLSeq = require('../../nodes/YAMLSeq.js');
var identity = require('../../nodes/identity.js');
var toJS = require('../../nodes/toJS.js');
var Node = require('../../nodes/Node.js');
var YAMLMap = require('../../nodes/YAMLMap.js');
var YAMLSeq = require('../../nodes/YAMLSeq.js');
var pairs = require('./pairs.js');
class YAMLOMap extends YAMLSeq.YAMLSeq {
@@ -28,7 +28,7 @@ class YAMLOMap extends YAMLSeq.YAMLSeq {
ctx.onCreate(map);
for (const pair of this.items) {
let key, value;
if (Node.isPair(pair)) {
if (identity.isPair(pair)) {
key = toJS.toJS(pair.key, '', ctx);
value = toJS.toJS(pair.value, key, ctx);
}
@@ -41,6 +41,12 @@ class YAMLOMap extends YAMLSeq.YAMLSeq {
}
return map;
}
static from(schema, iterable, ctx) {
const pairs$1 = pairs.createPairs(schema, iterable, ctx);
const omap = new this();
omap.items = pairs$1.items;
return omap;
}
}
YAMLOMap.tag = 'tag:yaml.org,2002:omap';
const omap = {
@@ -53,7 +59,7 @@ const omap = {
const pairs$1 = pairs.resolvePairs(seq, onError);
const seenKeys = [];
for (const { key } of pairs$1.items) {
if (Node.isScalar(key)) {
if (identity.isScalar(key)) {
if (seenKeys.includes(key.value)) {
onError(`Ordered maps must not include duplicate keys: ${key.value}`);
}
@@ -64,12 +70,7 @@ const omap = {
}
return Object.assign(new YAMLOMap(), pairs$1);
},
createNode(schema, iterable, ctx) {
const pairs$1 = pairs.createPairs(schema, iterable, ctx);
const omap = new YAMLOMap();
omap.items = pairs$1.items;
return omap;
}
createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx)
};
exports.YAMLOMap = YAMLOMap;

View File

@@ -1,5 +1,5 @@
import type { CreateNodeContext } from '../../doc/createNode.js';
import { ParsedNode } from '../../nodes/Node.js';
import type { ParsedNode } from '../../nodes/Node.js';
import { Pair } from '../../nodes/Pair.js';
import { YAMLMap } from '../../nodes/YAMLMap.js';
import { YAMLSeq } from '../../nodes/YAMLSeq.js';

View File

@@ -1,17 +1,17 @@
'use strict';
var Node = require('../../nodes/Node.js');
var identity = require('../../nodes/identity.js');
var Pair = require('../../nodes/Pair.js');
var Scalar = require('../../nodes/Scalar.js');
var YAMLSeq = require('../../nodes/YAMLSeq.js');
function resolvePairs(seq, onError) {
if (Node.isSeq(seq)) {
if (identity.isSeq(seq)) {
for (let i = 0; i < seq.items.length; ++i) {
let item = seq.items[i];
if (Node.isPair(item))
if (identity.isPair(item))
continue;
else if (Node.isMap(item)) {
else if (identity.isMap(item)) {
if (item.items.length > 1)
onError('Each pair must have its own sequence indicator');
const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null));
@@ -27,7 +27,7 @@ function resolvePairs(seq, onError) {
}
item = pair;
}
seq.items[i] = Node.isPair(item) ? item : new Pair.Pair(item);
seq.items[i] = identity.isPair(item) ? item : new Pair.Pair(item);
}
}
else
@@ -58,8 +58,9 @@ function createPairs(schema, iterable, ctx) {
key = keys[0];
value = it[key];
}
else
throw new TypeError(`Expected { key: value } tuple: ${it}`);
else {
throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);
}
}
else {
key = it;

View File

@@ -1 +1 @@
export declare const schema: (import("../types.js").ScalarTag | import("../types.js").CollectionTag)[];
export declare const schema: (import("../types.js").CollectionTag | import("../types.js").ScalarTag)[];

View File

@@ -1,9 +1,10 @@
import type { Schema } from '../../schema/Schema.js';
import { Pair } from '../../nodes/Pair.js';
import { Scalar } from '../../nodes/Scalar.js';
import { ToJSContext } from '../../nodes/toJS.js';
import { YAMLMap } from '../../nodes/YAMLMap.js';
import type { Schema } from '../../schema/Schema.js';
import type { StringifyContext } from '../../stringify/stringify.js';
import { CreateNodeContext } from '../../util.js';
import type { CollectionTag } from '../types.js';
export declare class YAMLSet<T = unknown> extends YAMLMap<T, Scalar<null> | null> {
static tag: string;
@@ -22,5 +23,6 @@ export declare class YAMLSet<T = unknown> extends YAMLMap<T, Scalar<null> | null
set(key: T, value: null): void;
toJSON(_?: unknown, ctx?: ToJSContext): any;
toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string;
static from(schema: Schema, iterable: unknown, ctx: CreateNodeContext): YAMLSet<unknown>;
}
export declare const set: CollectionTag;

View File

@@ -1,6 +1,6 @@
'use strict';
var Node = require('../../nodes/Node.js');
var identity = require('../../nodes/identity.js');
var Pair = require('../../nodes/Pair.js');
var YAMLMap = require('../../nodes/YAMLMap.js');
@@ -11,7 +11,7 @@ class YAMLSet extends YAMLMap.YAMLMap {
}
add(key) {
let pair;
if (Node.isPair(key))
if (identity.isPair(key))
pair = key;
else if (key &&
typeof key === 'object' &&
@@ -31,8 +31,8 @@ class YAMLSet extends YAMLMap.YAMLMap {
*/
get(key, keepPair) {
const pair = YAMLMap.findPair(this.items, key);
return !keepPair && Node.isPair(pair)
? Node.isScalar(pair.key)
return !keepPair && identity.isPair(pair)
? identity.isScalar(pair.key)
? pair.key.value
: pair.key
: pair;
@@ -59,28 +59,9 @@ class YAMLSet extends YAMLMap.YAMLMap {
else
throw new Error('Set items must all have null values');
}
}
YAMLSet.tag = 'tag:yaml.org,2002:set';
const set = {
collection: 'map',
identify: value => value instanceof Set,
nodeClass: YAMLSet,
default: false,
tag: 'tag:yaml.org,2002:set',
resolve(map, onError) {
if (Node.isMap(map)) {
if (map.hasAllNullValues(true))
return Object.assign(new YAMLSet(), map);
else
onError('Set items must all have null values');
}
else
onError('Expected a mapping for this tag');
return map;
},
createNode(schema, iterable, ctx) {
static from(schema, iterable, ctx) {
const { replacer } = ctx;
const set = new YAMLSet(schema);
const set = new this(schema);
if (iterable && Symbol.iterator in Object(iterable))
for (let value of iterable) {
if (typeof replacer === 'function')
@@ -89,6 +70,26 @@ const set = {
}
return set;
}
}
YAMLSet.tag = 'tag:yaml.org,2002:set';
const set = {
collection: 'map',
identify: value => value instanceof Set,
nodeClass: YAMLSet,
default: false,
tag: 'tag:yaml.org,2002:set',
createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx),
resolve(map, onError) {
if (identity.isMap(map)) {
if (map.hasAllNullValues(true))
return Object.assign(new YAMLSet(), map);
else
onError('Set items must all have null values');
}
else
onError('Expected a mapping for this tag');
return map;
}
};
exports.YAMLSet = YAMLSet;

View File

@@ -45,7 +45,7 @@ function stringifySexagesimal(node) {
}
return (sign +
parts
.map(n => (n < 10 ? '0' + String(n) : String(n)))
.map(n => String(n).padStart(2, '0'))
.join(':')
.replace(/000000\d*$/, '') // % 60 may introduce error
);

View File

@@ -5,7 +5,7 @@ export declare const FOLD_QUOTED = "quoted";
* `'block'` prevents more-indented lines from being folded;
* `'quoted'` allows for `\` escapes, including escaped newlines
*/
export declare type FoldMode = 'flow' | 'block' | 'quoted';
export type FoldMode = 'flow' | 'block' | 'quoted';
export interface FoldOptions {
/**
* Accounts for leading contents on the first line, defaulting to

View File

@@ -1,7 +1,7 @@
import type { Document } from '../doc/Document.js';
import type { Alias } from '../nodes/Alias.js';
import type { ToStringOptions } from '../options.js';
export declare type StringifyContext = {
export type StringifyContext = {
actualString?: boolean;
allNullValues?: boolean;
anchors: Set<string>;
@@ -13,6 +13,7 @@ export declare type StringifyContext = {
indentAtStart?: number;
inFlow: boolean | null;
inStringifyKey?: boolean;
flowCollectionPadding: string;
options: Readonly<Required<Omit<ToStringOptions, 'collectionStyle' | 'indent'>>>;
resolvedAliases?: Set<Alias>;
};

View File

@@ -1,7 +1,7 @@
'use strict';
var anchors = require('../doc/anchors.js');
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var stringifyComment = require('./stringifyComment.js');
var stringifyString = require('./stringifyString.js');
@@ -15,6 +15,7 @@ function createStringifyContext(doc, options) {
doubleQuotedAsJSON: false,
doubleQuotedMinMultiLineLength: 40,
falseStr: 'false',
flowCollectionPadding: true,
indentSeq: true,
lineWidth: 80,
minContentWidth: 20,
@@ -38,6 +39,7 @@ function createStringifyContext(doc, options) {
return {
anchors: new Set(),
doc,
flowCollectionPadding: opt.flowCollectionPadding ? ' ' : '',
indent: '',
indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : ' ',
inFlow,
@@ -52,7 +54,7 @@ function getTagObject(tags, item) {
}
let tagObj = undefined;
let obj;
if (Node.isScalar(item)) {
if (identity.isScalar(item)) {
obj = item.value;
const match = tags.filter(t => t.identify?.(obj));
tagObj =
@@ -73,7 +75,7 @@ function stringifyProps(node, tagObj, { anchors: anchors$1, doc }) {
if (!doc.directives)
return '';
const props = [];
const anchor = (Node.isScalar(node) || Node.isCollection(node)) && node.anchor;
const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor;
if (anchor && anchors.anchorIsValid(anchor)) {
anchors$1.add(anchor);
props.push(`&${anchor}`);
@@ -84,9 +86,9 @@ function stringifyProps(node, tagObj, { anchors: anchors$1, doc }) {
return props.join(' ');
}
function stringify(item, ctx, onComment, onChompKeep) {
if (Node.isPair(item))
if (identity.isPair(item))
return item.toString(ctx, onComment, onChompKeep);
if (Node.isAlias(item)) {
if (identity.isAlias(item)) {
if (ctx.doc.directives)
return item.toString(ctx);
if (ctx.resolvedAliases?.has(item)) {
@@ -101,7 +103,7 @@ function stringify(item, ctx, onComment, onChompKeep) {
}
}
let tagObj = undefined;
const node = Node.isNode(item)
const node = identity.isNode(item)
? item
: ctx.doc.createNode(item, { onTagObj: o => (tagObj = o) });
if (!tagObj)
@@ -111,12 +113,12 @@ function stringify(item, ctx, onComment, onChompKeep) {
ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;
const str = typeof tagObj.stringify === 'function'
? tagObj.stringify(node, ctx, onComment, onChompKeep)
: Node.isScalar(node)
: identity.isScalar(node)
? stringifyString.stringifyString(node, ctx, onComment, onChompKeep)
: node.toString(ctx, onComment, onChompKeep);
if (!props)
return str;
return Node.isScalar(node) || str[0] === '{' || str[0] === '['
return identity.isScalar(node) || str[0] === '{' || str[0] === '['
? `${props} ${str}`
: `${props}\n${ctx.indent}${str}`;
}

View File

@@ -1,7 +1,7 @@
'use strict';
var Collection = require('../nodes/Collection.js');
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var stringify = require('./stringify.js');
var stringifyComment = require('./stringifyComment.js');
@@ -18,15 +18,15 @@ function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, fl
for (let i = 0; i < items.length; ++i) {
const item = items[i];
let comment = null;
if (Node.isNode(item)) {
if (identity.isNode(item)) {
if (!chompKeep && item.spaceBefore)
lines.push('');
addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
if (item.comment)
comment = item.comment;
}
else if (Node.isPair(item)) {
const ik = Node.isNode(item.key) ? item.key : null;
else if (identity.isPair(item)) {
const ik = identity.isNode(item.key) ? item.key : null;
if (ik) {
if (!chompKeep && ik.spaceBefore)
lines.push('');
@@ -62,7 +62,7 @@ function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, fl
return str;
}
function stringifyFlowCollection({ comment, items }, ctx, { flowChars, itemIndent, onComment }) {
const { indent, indentStep, options: { commentString } } = ctx;
const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;
itemIndent += indentStep;
const itemCtx = Object.assign({}, ctx, {
indent: itemIndent,
@@ -75,15 +75,15 @@ function stringifyFlowCollection({ comment, items }, ctx, { flowChars, itemInden
for (let i = 0; i < items.length; ++i) {
const item = items[i];
let comment = null;
if (Node.isNode(item)) {
if (identity.isNode(item)) {
if (item.spaceBefore)
lines.push('');
addCommentBefore(ctx, lines, item.commentBefore, false);
if (item.comment)
comment = item.comment;
}
else if (Node.isPair(item)) {
const ik = Node.isNode(item.key) ? item.key : null;
else if (identity.isPair(item)) {
const ik = identity.isNode(item.key) ? item.key : null;
if (ik) {
if (ik.spaceBefore)
lines.push('');
@@ -91,14 +91,14 @@ function stringifyFlowCollection({ comment, items }, ctx, { flowChars, itemInden
if (ik.comment)
reqNewline = true;
}
const iv = Node.isNode(item.value) ? item.value : null;
const iv = identity.isNode(item.value) ? item.value : null;
if (iv) {
if (iv.comment)
comment = iv.comment;
if (iv.commentBefore)
reqNewline = true;
}
else if (item.value == null && ik && ik.comment) {
else if (item.value == null && ik?.comment) {
comment = ik.comment;
}
}
@@ -131,11 +131,11 @@ function stringifyFlowCollection({ comment, items }, ctx, { flowChars, itemInden
str += `\n${indent}${end}`;
}
else {
str = `${start} ${lines.join(' ')} ${end}`;
str = `${start}${fcPadding}${lines.join(' ')}${fcPadding}${end}`;
}
}
if (comment) {
str += stringifyComment.lineComment(str, commentString(comment), indent);
str += stringifyComment.lineComment(str, indent, commentString(comment));
if (onComment)
onComment();
}

View File

@@ -1,3 +1,4 @@
import { Document } from '../doc/Document.js';
import { ToStringOptions } from '../options.js';
export declare function stringifyDocument(doc: Readonly<Document>, options: ToStringOptions): string;
import type { Document } from '../doc/Document.js';
import type { Node } from '../nodes/Node.js';
import type { ToStringOptions } from '../options.js';
export declare function stringifyDocument(doc: Readonly<Document<Node, boolean>>, options: ToStringOptions): string;

View File

@@ -1,6 +1,6 @@
'use strict';
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var stringify = require('./stringify.js');
var stringifyComment = require('./stringifyComment.js');
@@ -29,7 +29,7 @@ function stringifyDocument(doc, options) {
let chompKeep = false;
let contentComment = null;
if (doc.contents) {
if (Node.isNode(doc.contents)) {
if (identity.isNode(doc.contents)) {
if (doc.contents.spaceBefore && hasDirectives)
lines.push('');
if (doc.contents.commentBefore) {

View File

@@ -1,18 +1,18 @@
'use strict';
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var Scalar = require('../nodes/Scalar.js');
var stringify = require('./stringify.js');
var stringifyComment = require('./stringifyComment.js');
function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
let keyComment = (Node.isNode(key) && key.comment) || null;
let keyComment = (identity.isNode(key) && key.comment) || null;
if (simpleKeys) {
if (keyComment) {
throw new Error('With simple keys, key nodes cannot have comments');
}
if (Node.isCollection(key)) {
if (identity.isCollection(key)) {
const msg = 'With simple keys, collection cannot be used as a key value';
throw new Error(msg);
}
@@ -20,8 +20,8 @@ function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
let explicitKey = !simpleKeys &&
(!key ||
(keyComment && value == null && !ctx.inFlow) ||
Node.isCollection(key) ||
(Node.isScalar(key)
identity.isCollection(key) ||
(identity.isScalar(key)
? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL
: typeof key === 'object'));
ctx = Object.assign({}, ctx, {
@@ -65,51 +65,76 @@ function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
if (keyComment)
str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
}
let vcb = '';
let valueComment = null;
if (Node.isNode(value)) {
if (value.spaceBefore)
vcb = '\n';
if (value.commentBefore) {
const cs = commentString(value.commentBefore);
vcb += `\n${stringifyComment.indentComment(cs, ctx.indent)}`;
}
let vsb, vcb, valueComment;
if (identity.isNode(value)) {
vsb = !!value.spaceBefore;
vcb = value.commentBefore;
valueComment = value.comment;
}
else if (value && typeof value === 'object') {
value = doc.createNode(value);
else {
vsb = false;
vcb = null;
valueComment = null;
if (value && typeof value === 'object')
value = doc.createNode(value);
}
ctx.implicitKey = false;
if (!explicitKey && !keyComment && Node.isScalar(value))
if (!explicitKey && !keyComment && identity.isScalar(value))
ctx.indentAtStart = str.length + 1;
chompKeep = false;
if (!indentSeq &&
indentStep.length >= 2 &&
!ctx.inFlow &&
!explicitKey &&
Node.isSeq(value) &&
identity.isSeq(value) &&
!value.flow &&
!value.tag &&
!value.anchor) {
// If indentSeq === false, consider '- ' as part of indentation where possible
ctx.indent = ctx.indent.substr(2);
ctx.indent = ctx.indent.substring(2);
}
let valueCommentDone = false;
const valueStr = stringify.stringify(value, ctx, () => (valueCommentDone = true), () => (chompKeep = true));
let ws = ' ';
if (vcb || keyComment) {
if (valueStr === '' && !ctx.inFlow)
ws = vcb === '\n' ? '\n\n' : vcb;
else
ws = `${vcb}\n${ctx.indent}`;
if (keyComment || vsb || vcb) {
ws = vsb ? '\n' : '';
if (vcb) {
const cs = commentString(vcb);
ws += `\n${stringifyComment.indentComment(cs, ctx.indent)}`;
}
if (valueStr === '' && !ctx.inFlow) {
if (ws === '\n')
ws = '\n\n';
}
else {
ws += `\n${ctx.indent}`;
}
}
else if (!explicitKey && Node.isCollection(value)) {
const flow = valueStr[0] === '[' || valueStr[0] === '{';
if (!flow || valueStr.includes('\n'))
ws = `\n${ctx.indent}`;
else if (!explicitKey && identity.isCollection(value)) {
const vs0 = valueStr[0];
const nl0 = valueStr.indexOf('\n');
const hasNewline = nl0 !== -1;
const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;
if (hasNewline || !flow) {
let hasPropsLine = false;
if (hasNewline && (vs0 === '&' || vs0 === '!')) {
let sp0 = valueStr.indexOf(' ');
if (vs0 === '&' &&
sp0 !== -1 &&
sp0 < nl0 &&
valueStr[sp0 + 1] === '!') {
sp0 = valueStr.indexOf(' ', sp0 + 1);
}
if (sp0 === -1 || nl0 < sp0)
hasPropsLine = true;
}
if (!hasPropsLine)
ws = `\n${ctx.indent}`;
}
}
else if (valueStr === '' || valueStr[0] === '\n')
else if (valueStr === '' || valueStr[0] === '\n') {
ws = '';
}
str += ws + valueStr;
if (ctx.inFlow) {
if (valueCommentDone && onComment)

View File

@@ -1,3 +1,9 @@
import { Scalar } from '../nodes/Scalar.js';
import type { StringifyContext } from './stringify.js';
export declare function stringifyString(item: Scalar, ctx: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string;
interface StringifyScalar {
value: string;
comment?: string | null;
type?: string;
}
export declare function stringifyString(item: Scalar | StringifyScalar, ctx: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string;
export {};

View File

@@ -3,8 +3,8 @@
var Scalar = require('../nodes/Scalar.js');
var foldFlowLines = require('./foldFlowLines.js');
const getFoldOptions = (ctx) => ({
indentAtStart: ctx.indentAtStart,
const getFoldOptions = (ctx, isBlock) => ({
indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,
lineWidth: ctx.options.lineWidth,
minContentWidth: ctx.options.minContentWidth
});
@@ -117,7 +117,7 @@ function doubleQuotedString(value, ctx) {
str = start ? str + json.slice(start) : json;
return implicitKey
? str
: foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx));
: foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false));
}
function singleQuotedString(value, ctx) {
if (ctx.options.singleQuote === false ||
@@ -129,7 +129,7 @@ function singleQuotedString(value, ctx) {
const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'";
return ctx.implicitKey
? res
: foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx));
: foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
}
function quotedString(value, ctx) {
const { singleQuote } = ctx.options;
@@ -148,6 +148,15 @@ function quotedString(value, ctx) {
}
return qs(value, ctx);
}
// The negative lookbehind avoids a polynomial search,
// but isn't supported yet on Safari: https://caniuse.com/js-regexp-lookbehind
let blockEndNewlines;
try {
blockEndNewlines = new RegExp('(^|(?<!\n))\n+(?!\n|$)', 'g');
}
catch {
blockEndNewlines = /\n+(?!\n|$)/g;
}
function blockString({ comment, type, value }, ctx, onComment, onChompKeep) {
const { blockQuote, commentString, lineWidth } = ctx.options;
// 1. Block can't end in whitespace unless the last line is non-empty.
@@ -191,7 +200,7 @@ function blockString({ comment, type, value }, ctx, onComment, onChompKeep) {
value = value.slice(0, -end.length);
if (end[end.length - 1] === '\n')
end = end.slice(0, -1);
end = end.replace(/\n+(?!\n|$)/g, `$&${indent}`);
end = end.replace(blockEndNewlines, `$&${indent}`);
}
// determine indent indicator from whitespace at value start
let startWithSpace = false;
@@ -227,13 +236,13 @@ function blockString({ comment, type, value }, ctx, onComment, onChompKeep) {
.replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded
// ^ more-ind. ^ empty ^ capture next empty lines only at end of indent
.replace(/\n+/g, `$&${indent}`);
const body = foldFlowLines.foldFlowLines(`${start}${value}${end}`, indent, foldFlowLines.FOLD_BLOCK, getFoldOptions(ctx));
const body = foldFlowLines.foldFlowLines(`${start}${value}${end}`, indent, foldFlowLines.FOLD_BLOCK, getFoldOptions(ctx, true));
return `${header}\n${indent}${body}`;
}
function plainString(item, ctx, onComment, onChompKeep) {
const { type, value } = item;
const { actualString, implicitKey, indent, inFlow } = ctx;
if ((implicitKey && /[\n[\]{},]/.test(value)) ||
const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;
if ((implicitKey && value.includes('\n')) ||
(inFlow && /[[\]{},]/.test(value))) {
return quotedString(value, ctx);
}
@@ -256,9 +265,14 @@ function plainString(item, ctx, onComment, onChompKeep) {
// Where allowed & type not set explicitly, prefer block style for multiline strings
return blockString(item, ctx, onComment, onChompKeep);
}
if (indent === '' && containsDocumentMarker(value)) {
ctx.forceBlockIndent = true;
return blockString(item, ctx, onComment, onChompKeep);
if (containsDocumentMarker(value)) {
if (indent === '') {
ctx.forceBlockIndent = true;
return blockString(item, ctx, onComment, onChompKeep);
}
else if (implicitKey && indent === indentStep) {
return quotedString(value, ctx);
}
}
const str = value.replace(/\n+/g, `$&\n${indent}`);
// Verify that output will be parsed as a string, as e.g. plain numbers and
@@ -272,7 +286,7 @@ function plainString(item, ctx, onComment, onChompKeep) {
}
return implicitKey
? str
: foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx));
: foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
}
function stringifyString(item, ctx, onComment, onChompKeep) {
const { implicitKey, inFlow } = ctx;

View File

@@ -1,6 +1,6 @@
'use strict';
var Node = require('./nodes/Node.js');
var identity = require('./nodes/identity.js');
var publicApi = require('./public-api.js');
var visit = require('./visit.js');
@@ -66,10 +66,10 @@ function addEvents(events, doc, errPos, node) {
events.push('=VAL :');
return;
}
if (errPos !== -1 && Node.isNode(node) && node.range[0] >= errPos)
if (errPos !== -1 && identity.isNode(node) && node.range[0] >= errPos)
throw new Error();
let props = '';
let anchor = Node.isScalar(node) || Node.isCollection(node) ? node.anchor : undefined;
let anchor = identity.isScalar(node) || identity.isCollection(node) ? node.anchor : undefined;
if (anchor) {
if (/\d$/.test(anchor)) {
const alt = anchor.replace(/\d$/, '');
@@ -78,9 +78,9 @@ function addEvents(events, doc, errPos, node) {
}
props = ` &${anchor}`;
}
if (Node.isNode(node) && node.tag)
if (identity.isNode(node) && node.tag)
props += ` <${node.tag}>`;
if (Node.isMap(node)) {
if (identity.isMap(node)) {
const ev = node.flow ? '+MAP {}' : '+MAP';
events.push(`${ev}${props}`);
node.items.forEach(({ key, value }) => {
@@ -89,7 +89,7 @@ function addEvents(events, doc, errPos, node) {
});
events.push('-MAP');
}
else if (Node.isSeq(node)) {
else if (identity.isSeq(node)) {
const ev = node.flow ? '+SEQ []' : '+SEQ';
events.push(`${ev}${props}`);
node.items.forEach(item => {
@@ -97,13 +97,13 @@ function addEvents(events, doc, errPos, node) {
});
events.push('-SEQ');
}
else if (Node.isPair(node)) {
else if (identity.isPair(node)) {
events.push(`+MAP${props}`);
addEvents(events, doc, errPos, node.key);
addEvents(events, doc, errPos, node.value);
events.push('-MAP');
}
else if (Node.isAlias(node)) {
else if (identity.isAlias(node)) {
let alias = node.source;
if (alias && /\d$/.test(alias)) {
const alt = alias.replace(/\d$/, '');

5
node_modules/yaml/dist/util.d.ts generated vendored
View File

@@ -1,9 +1,12 @@
export { createNode, CreateNodeContext } from './doc/createNode.js';
export { debug, LogLevelId, warn } from './log.js';
export { createPair } from './nodes/Pair.js';
export { findPair } from './nodes/YAMLMap.js';
export { toJS, ToJSContext } from './nodes/toJS.js';
export { map as mapTag } from './schema/common/map.js';
export { seq as seqTag } from './schema/common/seq.js';
export { string as stringTag } from './schema/common/string.js';
export { foldFlowLines } from './stringify/foldFlowLines';
export { foldFlowLines, FoldOptions } from './stringify/foldFlowLines';
export { StringifyContext } from './stringify/stringify.js';
export { stringifyNumber } from './stringify/stringifyNumber.js';
export { stringifyString } from './stringify/stringifyString.js';

4
node_modules/yaml/dist/util.js generated vendored
View File

@@ -1,6 +1,8 @@
'use strict';
var createNode = require('./doc/createNode.js');
var log = require('./log.js');
var Pair = require('./nodes/Pair.js');
var YAMLMap = require('./nodes/YAMLMap.js');
var toJS = require('./nodes/toJS.js');
var map = require('./schema/common/map.js');
@@ -12,8 +14,10 @@ var stringifyString = require('./stringify/stringifyString.js');
exports.createNode = createNode.createNode;
exports.debug = log.debug;
exports.warn = log.warn;
exports.createPair = Pair.createPair;
exports.findPair = YAMLMap.findPair;
exports.toJS = toJS.toJS;
exports.mapTag = map.map;

8
node_modules/yaml/dist/visit.d.ts generated vendored
View File

@@ -5,8 +5,8 @@ import type { Pair } from './nodes/Pair.js';
import type { Scalar } from './nodes/Scalar.js';
import type { YAMLMap } from './nodes/YAMLMap.js';
import type { YAMLSeq } from './nodes/YAMLSeq.js';
export declare type visitorFn<T> = (key: number | 'key' | 'value' | null, node: T, path: readonly (Document | Node | Pair)[]) => void | symbol | number | Node | Pair;
export declare type visitor = visitorFn<unknown> | {
export type visitorFn<T> = (key: number | 'key' | 'value' | null, node: T, path: readonly (Document | Node | Pair)[]) => void | symbol | number | Node | Pair;
export type visitor = visitorFn<unknown> | {
Alias?: visitorFn<Alias>;
Collection?: visitorFn<YAMLMap | YAMLSeq>;
Map?: visitorFn<YAMLMap>;
@@ -16,8 +16,8 @@ export declare type visitor = visitorFn<unknown> | {
Seq?: visitorFn<YAMLSeq>;
Value?: visitorFn<Scalar | YAMLMap | YAMLSeq>;
};
export declare type asyncVisitorFn<T> = (key: number | 'key' | 'value' | null, node: T, path: readonly (Document | Node | Pair)[]) => void | symbol | number | Node | Pair | Promise<void | symbol | number | Node | Pair>;
export declare type asyncVisitor = asyncVisitorFn<unknown> | {
export type asyncVisitorFn<T> = (key: number | 'key' | 'value' | null, node: T, path: readonly (Document | Node | Pair)[]) => void | symbol | number | Node | Pair | Promise<void | symbol | number | Node | Pair>;
export type asyncVisitor = asyncVisitorFn<unknown> | {
Alias?: asyncVisitorFn<Alias>;
Collection?: asyncVisitorFn<YAMLMap | YAMLSeq>;
Map?: asyncVisitorFn<YAMLMap>;

36
node_modules/yaml/dist/visit.js generated vendored
View File

@@ -1,6 +1,6 @@
'use strict';
var Node = require('./nodes/Node.js');
var identity = require('./nodes/identity.js');
const BREAK = Symbol('break visit');
const SKIP = Symbol('skip children');
@@ -37,7 +37,7 @@ const REMOVE = Symbol('remove node');
*/
function visit(node, visitor) {
const visitor_ = initVisitor(visitor);
if (Node.isDocument(node)) {
if (identity.isDocument(node)) {
const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));
if (cd === REMOVE)
node.contents = null;
@@ -56,12 +56,12 @@ visit.SKIP = SKIP;
visit.REMOVE = REMOVE;
function visit_(key, node, visitor, path) {
const ctrl = callVisitor(key, node, visitor, path);
if (Node.isNode(ctrl) || Node.isPair(ctrl)) {
if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
replaceNode(key, path, ctrl);
return visit_(key, ctrl, visitor, path);
}
if (typeof ctrl !== 'symbol') {
if (Node.isCollection(node)) {
if (identity.isCollection(node)) {
path = Object.freeze(path.concat(node));
for (let i = 0; i < node.items.length; ++i) {
const ci = visit_(i, node.items[i], visitor, path);
@@ -75,7 +75,7 @@ function visit_(key, node, visitor, path) {
}
}
}
else if (Node.isPair(node)) {
else if (identity.isPair(node)) {
path = Object.freeze(path.concat(node));
const ck = visit_('key', node.key, visitor, path);
if (ck === BREAK)
@@ -124,7 +124,7 @@ function visit_(key, node, visitor, path) {
*/
async function visitAsync(node, visitor) {
const visitor_ = initVisitor(visitor);
if (Node.isDocument(node)) {
if (identity.isDocument(node)) {
const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));
if (cd === REMOVE)
node.contents = null;
@@ -143,12 +143,12 @@ visitAsync.SKIP = SKIP;
visitAsync.REMOVE = REMOVE;
async function visitAsync_(key, node, visitor, path) {
const ctrl = await callVisitor(key, node, visitor, path);
if (Node.isNode(ctrl) || Node.isPair(ctrl)) {
if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
replaceNode(key, path, ctrl);
return visitAsync_(key, ctrl, visitor, path);
}
if (typeof ctrl !== 'symbol') {
if (Node.isCollection(node)) {
if (identity.isCollection(node)) {
path = Object.freeze(path.concat(node));
for (let i = 0; i < node.items.length; ++i) {
const ci = await visitAsync_(i, node.items[i], visitor, path);
@@ -162,7 +162,7 @@ async function visitAsync_(key, node, visitor, path) {
}
}
}
else if (Node.isPair(node)) {
else if (identity.isPair(node)) {
path = Object.freeze(path.concat(node));
const ck = await visitAsync_('key', node.key, visitor, path);
if (ck === BREAK)
@@ -200,34 +200,34 @@ function initVisitor(visitor) {
function callVisitor(key, node, visitor, path) {
if (typeof visitor === 'function')
return visitor(key, node, path);
if (Node.isMap(node))
if (identity.isMap(node))
return visitor.Map?.(key, node, path);
if (Node.isSeq(node))
if (identity.isSeq(node))
return visitor.Seq?.(key, node, path);
if (Node.isPair(node))
if (identity.isPair(node))
return visitor.Pair?.(key, node, path);
if (Node.isScalar(node))
if (identity.isScalar(node))
return visitor.Scalar?.(key, node, path);
if (Node.isAlias(node))
if (identity.isAlias(node))
return visitor.Alias?.(key, node, path);
return undefined;
}
function replaceNode(key, path, node) {
const parent = path[path.length - 1];
if (Node.isCollection(parent)) {
if (identity.isCollection(parent)) {
parent.items[key] = node;
}
else if (Node.isPair(parent)) {
else if (identity.isPair(parent)) {
if (key === 'key')
parent.key = node;
else
parent.value = node;
}
else if (Node.isDocument(parent)) {
else if (identity.isDocument(parent)) {
parent.contents = node;
}
else {
const pt = Node.isAlias(parent) ? 'alias' : 'scalar';
const pt = identity.isAlias(parent) ? 'alias' : 'scalar';
throw new Error(`Cannot replace node with ${pt} parent`);
}
}