yaml 2.0.0-7 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/README.md +1 -1
  2. package/browser/dist/compose/compose-doc.js +3 -2
  3. package/browser/dist/compose/compose-node.js +14 -3
  4. package/browser/dist/compose/compose-scalar.js +17 -10
  5. package/browser/dist/compose/composer.js +6 -7
  6. package/browser/dist/compose/resolve-block-map.js +19 -5
  7. package/browser/dist/compose/resolve-block-scalar.js +12 -3
  8. package/browser/dist/compose/resolve-block-seq.js +5 -0
  9. package/browser/dist/compose/resolve-flow-collection.js +18 -6
  10. package/browser/dist/compose/resolve-flow-scalar.js +9 -2
  11. package/browser/dist/compose/resolve-props.js +4 -0
  12. package/browser/dist/compose/util-flow-indent-check.js +15 -0
  13. package/browser/dist/doc/Document.js +73 -16
  14. package/browser/dist/doc/anchors.js +2 -2
  15. package/browser/dist/doc/createNode.js +12 -7
  16. package/browser/dist/doc/directives.js +11 -3
  17. package/browser/dist/index.js +1 -2
  18. package/browser/dist/node_modules/tslib/tslib.es6.js +164 -0
  19. package/browser/dist/nodes/Collection.js +28 -15
  20. package/browser/dist/nodes/Node.js +7 -0
  21. package/browser/dist/nodes/Pair.js +11 -3
  22. package/browser/dist/nodes/Scalar.js +1 -1
  23. package/browser/dist/nodes/YAMLMap.js +6 -5
  24. package/browser/dist/nodes/YAMLSeq.js +2 -2
  25. package/browser/dist/nodes/addPairToJSMap.js +3 -2
  26. package/browser/dist/nodes/toJS.js +3 -1
  27. package/browser/dist/parse/cst-scalar.js +2 -6
  28. package/browser/dist/parse/cst-visit.js +2 -2
  29. package/browser/dist/parse/lexer.js +50 -22
  30. package/browser/dist/parse/parser.js +121 -45
  31. package/browser/dist/public-api.js +4 -5
  32. package/browser/dist/schema/Schema.js +19 -4
  33. package/browser/dist/schema/common/null.js +3 -1
  34. package/browser/dist/schema/core/float.js +4 -1
  35. package/browser/dist/schema/tags.js +17 -13
  36. package/browser/dist/schema/yaml-1.1/float.js +4 -1
  37. package/browser/dist/schema/yaml-1.1/omap.js +1 -1
  38. package/browser/dist/schema/yaml-1.1/pairs.js +2 -1
  39. package/browser/dist/stringify/stringify.js +53 -23
  40. package/browser/dist/stringify/stringifyCollection.js +115 -85
  41. package/browser/dist/stringify/stringifyComment.js +18 -12
  42. package/browser/dist/stringify/stringifyDocument.js +37 -15
  43. package/browser/dist/stringify/stringifyPair.js +35 -21
  44. package/browser/dist/stringify/stringifyString.js +41 -43
  45. package/browser/dist/util.js +3 -0
  46. package/browser/dist/visit.js +150 -62
  47. package/dist/compose/compose-doc.js +3 -2
  48. package/dist/compose/compose-node.d.ts +1 -0
  49. package/dist/compose/compose-node.js +14 -3
  50. package/dist/compose/compose-scalar.js +16 -9
  51. package/dist/compose/composer.d.ts +1 -1
  52. package/dist/compose/composer.js +8 -9
  53. package/dist/compose/resolve-block-map.js +19 -5
  54. package/dist/compose/resolve-block-scalar.js +12 -3
  55. package/dist/compose/resolve-block-seq.js +5 -0
  56. package/dist/compose/resolve-flow-collection.js +18 -6
  57. package/dist/compose/resolve-flow-scalar.js +9 -2
  58. package/dist/compose/resolve-props.d.ts +1 -1
  59. package/dist/compose/resolve-props.js +4 -0
  60. package/dist/compose/util-flow-indent-check.d.ts +3 -0
  61. package/dist/compose/util-flow-indent-check.js +17 -0
  62. package/dist/doc/Document.d.ts +13 -4
  63. package/dist/doc/Document.js +79 -22
  64. package/dist/doc/anchors.d.ts +2 -2
  65. package/dist/doc/anchors.js +2 -2
  66. package/dist/doc/createNode.d.ts +3 -2
  67. package/dist/doc/createNode.js +11 -6
  68. package/dist/doc/directives.d.ts +5 -2
  69. package/dist/doc/directives.js +11 -3
  70. package/dist/index.d.ts +4 -4
  71. package/dist/index.js +1 -2
  72. package/dist/node_modules/tslib/tslib.es6.js +76 -0
  73. package/dist/nodes/Alias.d.ts +7 -3
  74. package/dist/nodes/Collection.d.ts +10 -4
  75. package/dist/nodes/Collection.js +27 -14
  76. package/dist/nodes/Node.d.ts +6 -1
  77. package/dist/nodes/Node.js +7 -0
  78. package/dist/nodes/Pair.d.ts +7 -2
  79. package/dist/nodes/Pair.js +10 -2
  80. package/dist/nodes/Scalar.d.ts +2 -0
  81. package/dist/nodes/Scalar.js +1 -1
  82. package/dist/nodes/YAMLMap.d.ts +5 -1
  83. package/dist/nodes/YAMLMap.js +6 -5
  84. package/dist/nodes/YAMLSeq.d.ts +2 -0
  85. package/dist/nodes/YAMLSeq.js +2 -2
  86. package/dist/nodes/addPairToJSMap.js +2 -1
  87. package/dist/nodes/toJS.js +3 -1
  88. package/dist/options.d.ts +67 -15
  89. package/dist/parse/cst-scalar.d.ts +6 -0
  90. package/dist/parse/cst-scalar.js +2 -6
  91. package/dist/parse/cst-visit.js +2 -2
  92. package/dist/parse/lexer.d.ts +2 -0
  93. package/dist/parse/lexer.js +50 -22
  94. package/dist/parse/parser.js +121 -45
  95. package/dist/public-api.js +4 -5
  96. package/dist/schema/Schema.d.ts +6 -4
  97. package/dist/schema/Schema.js +18 -3
  98. package/dist/schema/common/null.js +3 -1
  99. package/dist/schema/core/float.js +4 -1
  100. package/dist/schema/tags.d.ts +1 -2
  101. package/dist/schema/tags.js +17 -13
  102. package/dist/schema/yaml-1.1/float.js +4 -1
  103. package/dist/schema/yaml-1.1/omap.js +1 -1
  104. package/dist/schema/yaml-1.1/pairs.js +2 -1
  105. package/dist/stringify/stringify.d.ts +5 -3
  106. package/dist/stringify/stringify.js +53 -23
  107. package/dist/stringify/stringifyCollection.d.ts +2 -6
  108. package/dist/stringify/stringifyCollection.js +114 -84
  109. package/dist/stringify/stringifyComment.d.ts +10 -2
  110. package/dist/stringify/stringifyComment.js +19 -12
  111. package/dist/stringify/stringifyDocument.js +36 -14
  112. package/dist/stringify/stringifyPair.js +34 -20
  113. package/dist/stringify/stringifyString.js +41 -43
  114. package/dist/test-events.d.ts +1 -1
  115. package/dist/test-events.js +13 -12
  116. package/dist/util.d.ts +3 -0
  117. package/dist/util.js +6 -0
  118. package/dist/visit.d.ts +49 -10
  119. package/dist/visit.js +149 -60
  120. package/package.json +12 -10
  121. package/util.d.ts +3 -0
  122. package/browser/dist/options.js +0 -17
  123. package/dist/options.js +0 -19
@@ -1,16 +1,18 @@
1
1
  import { MAP, SCALAR, SEQ } from '../nodes/Node.js';
2
2
  import type { Pair } from '../nodes/Pair.js';
3
- import type { SchemaOptions } from '../options.js';
3
+ import type { SchemaOptions, ToStringOptions } from '../options.js';
4
4
  import type { CollectionTag, ScalarTag } from './types.js';
5
- export declare type SchemaName = 'core' | 'failsafe' | 'json' | 'yaml-1.1';
6
5
  export declare class Schema {
6
+ compat: Array<CollectionTag | ScalarTag> | null;
7
7
  knownTags: Record<string, CollectionTag | ScalarTag>;
8
8
  merge: boolean;
9
- name: SchemaName;
9
+ name: string;
10
10
  sortMapEntries: ((a: Pair, b: Pair) => number) | null;
11
11
  tags: Array<CollectionTag | ScalarTag>;
12
+ toStringOptions: Readonly<ToStringOptions> | null;
12
13
  [MAP]: CollectionTag;
13
14
  [SCALAR]: ScalarTag;
14
15
  [SEQ]: CollectionTag;
15
- constructor({ customTags, merge, resolveKnownTags, schema, sortMapEntries }: SchemaOptions);
16
+ constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }: SchemaOptions);
17
+ clone(): Schema;
16
18
  }
@@ -8,17 +8,32 @@ var tags = require('./tags.js');
8
8
 
9
9
  const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
10
10
  class Schema {
11
- constructor({ customTags, merge, resolveKnownTags, schema, sortMapEntries }) {
11
+ constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {
12
+ this.compat = Array.isArray(compat)
13
+ ? tags.getTags(compat, 'compat')
14
+ : compat
15
+ ? tags.getTags(null, compat)
16
+ : null;
12
17
  this.merge = !!merge;
13
- this.name = schema || 'core';
18
+ this.name = (typeof schema === 'string' && schema) || 'core';
14
19
  this.knownTags = resolveKnownTags ? tags.coreKnownTags : {};
15
20
  this.tags = tags.getTags(customTags, this.name);
21
+ this.toStringOptions = toStringDefaults !== null && toStringDefaults !== void 0 ? toStringDefaults : null;
16
22
  Object.defineProperty(this, Node.MAP, { value: map.map });
17
23
  Object.defineProperty(this, Node.SCALAR, { value: string.string });
18
24
  Object.defineProperty(this, Node.SEQ, { value: seq.seq });
19
25
  // Used by createMap()
20
26
  this.sortMapEntries =
21
- sortMapEntries === true ? sortMapEntriesByKey : sortMapEntries || null;
27
+ typeof sortMapEntries === 'function'
28
+ ? sortMapEntries
29
+ : sortMapEntries === true
30
+ ? sortMapEntriesByKey
31
+ : null;
32
+ }
33
+ clone() {
34
+ const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));
35
+ copy.tags = this.tags.slice();
36
+ return copy;
22
37
  }
23
38
  }
24
39
 
@@ -9,7 +9,9 @@ const nullTag = {
9
9
  tag: 'tag:yaml.org,2002:null',
10
10
  test: /^(?:~|[Nn]ull|NULL)?$/,
11
11
  resolve: () => new Scalar.Scalar(null),
12
- stringify: ({ source }, ctx) => source && nullTag.test.test(source) ? source : ctx.options.nullStr
12
+ stringify: ({ source }, ctx) => typeof source === 'string' && nullTag.test.test(source)
13
+ ? source
14
+ : ctx.options.nullStr
13
15
  };
14
16
 
15
17
  exports.nullTag = nullTag;
@@ -22,7 +22,10 @@ const floatExp = {
22
22
  format: 'EXP',
23
23
  test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
24
24
  resolve: str => parseFloat(str),
25
- stringify: ({ value }) => Number(value).toExponential()
25
+ stringify(node) {
26
+ const num = Number(node.value);
27
+ return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
28
+ }
26
29
  };
27
30
  const float = {
28
31
  identify: value => typeof value === 'number',
@@ -1,5 +1,4 @@
1
1
  import { SchemaOptions } from '../options.js';
2
- import type { SchemaName } from './Schema.js';
3
2
  import type { CollectionTag, ScalarTag } from './types.js';
4
3
  declare const tagsByName: {
5
4
  binary: ScalarTag;
@@ -37,5 +36,5 @@ export declare const coreKnownTags: {
37
36
  test: RegExp;
38
37
  };
39
38
  };
40
- export declare function getTags(customTags: SchemaOptions['customTags'] | undefined, schemaName: SchemaName): (ScalarTag | CollectionTag)[];
39
+ export declare function getTags(customTags: SchemaOptions['customTags'] | undefined, schemaName: string): (ScalarTag | CollectionTag)[];
41
40
  export {};
@@ -16,13 +16,13 @@ var schema$2 = require('./yaml-1.1/schema.js');
16
16
  var set = require('./yaml-1.1/set.js');
17
17
  var timestamp = require('./yaml-1.1/timestamp.js');
18
18
 
19
- const schemas = {
20
- core: schema.schema,
21
- failsafe: [map.map, seq.seq, string.string],
22
- json: schema$1.schema,
23
- yaml11: schema$2.schema,
24
- 'yaml-1.1': schema$2.schema
25
- };
19
+ const schemas = new Map([
20
+ ['core', schema.schema],
21
+ ['failsafe', [map.map, seq.seq, string.string]],
22
+ ['json', schema$1.schema],
23
+ ['yaml11', schema$2.schema],
24
+ ['yaml-1.1', schema$2.schema]
25
+ ]);
26
26
  const tagsByName = {
27
27
  binary: binary.binary,
28
28
  bool: bool.boolTag,
@@ -50,13 +50,17 @@ const coreKnownTags = {
50
50
  'tag:yaml.org,2002:timestamp': timestamp.timestamp
51
51
  };
52
52
  function getTags(customTags, schemaName) {
53
- let tags = schemas[schemaName];
53
+ let tags = schemas.get(schemaName);
54
54
  if (!tags) {
55
- const keys = Object.keys(schemas)
56
- .filter(key => key !== 'yaml11')
57
- .map(key => JSON.stringify(key))
58
- .join(', ');
59
- throw new Error(`Unknown schema "${schemaName}"; use one of ${keys}`);
55
+ if (Array.isArray(customTags))
56
+ tags = [];
57
+ else {
58
+ const keys = Array.from(schemas.keys())
59
+ .filter(key => key !== 'yaml11')
60
+ .map(key => JSON.stringify(key))
61
+ .join(', ');
62
+ throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`);
63
+ }
60
64
  }
61
65
  if (Array.isArray(customTags)) {
62
66
  for (const tag of customTags)
@@ -22,7 +22,10 @@ const floatExp = {
22
22
  format: 'EXP',
23
23
  test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
24
24
  resolve: (str) => parseFloat(str.replace(/_/g, '')),
25
- stringify: ({ value }) => Number(value).toExponential()
25
+ stringify(node) {
26
+ const num = Number(node.value);
27
+ return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
28
+ }
26
29
  };
27
30
  const float = {
28
31
  identify: value => typeof value === 'number',
@@ -24,7 +24,7 @@ class YAMLOMap extends YAMLSeq.YAMLSeq {
24
24
  if (!ctx)
25
25
  return super.toJSON(_);
26
26
  const map = new Map();
27
- if (ctx && ctx.onCreate)
27
+ if (ctx === null || ctx === void 0 ? void 0 : ctx.onCreate)
28
28
  ctx.onCreate(map);
29
29
  for (const pair of this.items) {
30
30
  let key, value;
@@ -6,6 +6,7 @@ var Scalar = require('../../nodes/Scalar.js');
6
6
  var YAMLSeq = require('../../nodes/YAMLSeq.js');
7
7
 
8
8
  function resolvePairs(seq, onError) {
9
+ var _a;
9
10
  if (Node.isSeq(seq)) {
10
11
  for (let i = 0; i < seq.items.length; ++i) {
11
12
  let item = seq.items[i];
@@ -20,7 +21,7 @@ function resolvePairs(seq, onError) {
20
21
  ? `${item.commentBefore}\n${pair.key.commentBefore}`
21
22
  : item.commentBefore;
22
23
  if (item.comment) {
23
- const cn = pair.value || pair.key;
24
+ const cn = (_a = pair.value) !== null && _a !== void 0 ? _a : pair.key;
24
25
  cn.comment = cn.comment
25
26
  ? `${item.comment}\n${cn.comment}`
26
27
  : item.comment;
@@ -1,4 +1,5 @@
1
1
  import type { Document } from '../doc/Document.js';
2
+ import type { Alias } from '../nodes/Alias.js';
2
3
  import type { ToStringOptions } from '../options.js';
3
4
  export declare type StringifyContext = {
4
5
  actualString?: boolean;
@@ -10,9 +11,10 @@ export declare type StringifyContext = {
10
11
  indent: string;
11
12
  indentStep: string;
12
13
  indentAtStart?: number;
13
- inFlow?: boolean;
14
+ inFlow: boolean | null;
14
15
  inStringifyKey?: boolean;
15
- options: Readonly<Required<Omit<ToStringOptions, 'indent'>>>;
16
+ options: Readonly<Required<Omit<ToStringOptions, 'collectionStyle' | 'indent'>>>;
17
+ resolvedAliases?: Set<Alias>;
16
18
  };
17
- export declare const createStringifyContext: (doc: Document, options: ToStringOptions) => StringifyContext;
19
+ export declare function createStringifyContext(doc: Document, options: ToStringOptions): StringifyContext;
18
20
  export declare function stringify(item: unknown, ctx: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string;
@@ -2,14 +2,13 @@
2
2
 
3
3
  var anchors = require('../doc/anchors.js');
4
4
  var Node = require('../nodes/Node.js');
5
+ var stringifyComment = require('./stringifyComment.js');
5
6
  var stringifyString = require('./stringifyString.js');
6
7
 
7
- const createStringifyContext = (doc, options) => ({
8
- anchors: new Set(),
9
- doc,
10
- indent: '',
11
- indentStep: typeof options.indent === 'number' ? ' '.repeat(options.indent) : ' ',
12
- options: Object.assign({
8
+ function createStringifyContext(doc, options) {
9
+ const opt = Object.assign({
10
+ blockQuote: true,
11
+ commentString: stringifyComment.stringifyComment,
13
12
  defaultKeyType: null,
14
13
  defaultStringType: 'PLAIN',
15
14
  directives: null,
@@ -21,57 +20,88 @@ const createStringifyContext = (doc, options) => ({
21
20
  minContentWidth: 20,
22
21
  nullStr: 'null',
23
22
  simpleKeys: false,
24
- singleQuote: false,
23
+ singleQuote: null,
25
24
  trueStr: 'true',
26
25
  verifyAliasOrder: true
27
- }, options)
28
- });
26
+ }, doc.schema.toStringOptions, options);
27
+ let inFlow;
28
+ switch (opt.collectionStyle) {
29
+ case 'block':
30
+ inFlow = false;
31
+ break;
32
+ case 'flow':
33
+ inFlow = true;
34
+ break;
35
+ default:
36
+ inFlow = null;
37
+ }
38
+ return {
39
+ anchors: new Set(),
40
+ doc,
41
+ indent: '',
42
+ indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : ' ',
43
+ inFlow,
44
+ options: opt
45
+ };
46
+ }
29
47
  function getTagObject(tags, item) {
48
+ var _a, _b, _c, _d;
30
49
  if (item.tag) {
31
50
  const match = tags.filter(t => t.tag === item.tag);
32
51
  if (match.length > 0)
33
- return match.find(t => t.format === item.format) || match[0];
52
+ return (_a = match.find(t => t.format === item.format)) !== null && _a !== void 0 ? _a : match[0];
34
53
  }
35
54
  let tagObj = undefined;
36
55
  let obj;
37
56
  if (Node.isScalar(item)) {
38
57
  obj = item.value;
39
- const match = tags.filter(t => t.identify && t.identify(obj));
58
+ const match = tags.filter(t => { var _a; return (_a = t.identify) === null || _a === void 0 ? void 0 : _a.call(t, obj); });
40
59
  tagObj =
41
- match.find(t => t.format === item.format) || match.find(t => !t.format);
60
+ (_b = match.find(t => t.format === item.format)) !== null && _b !== void 0 ? _b : match.find(t => !t.format);
42
61
  }
43
62
  else {
44
63
  obj = item;
45
64
  tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);
46
65
  }
47
66
  if (!tagObj) {
48
- // @ts-ignore
49
- const name = obj && obj.constructor ? obj.constructor.name : typeof obj;
67
+ const name = (_d = (_c = obj === null || obj === void 0 ? void 0 : obj.constructor) === null || _c === void 0 ? void 0 : _c.name) !== null && _d !== void 0 ? _d : typeof obj;
50
68
  throw new Error(`Tag not resolved for ${name} value`);
51
69
  }
52
70
  return tagObj;
53
71
  }
54
72
  // needs to be called before value stringifier to allow for circular anchor refs
55
73
  function stringifyProps(node, tagObj, { anchors: anchors$1, doc }) {
74
+ if (!doc.directives)
75
+ return '';
56
76
  const props = [];
57
77
  const anchor = (Node.isScalar(node) || Node.isCollection(node)) && node.anchor;
58
78
  if (anchor && anchors.anchorIsValid(anchor)) {
59
79
  anchors$1.add(anchor);
60
80
  props.push(`&${anchor}`);
61
81
  }
62
- if (node.tag) {
63
- props.push(doc.directives.tagString(node.tag));
64
- }
65
- else if (!tagObj.default) {
66
- props.push(doc.directives.tagString(tagObj.tag));
67
- }
82
+ const tag = node.tag ? node.tag : tagObj.default ? null : tagObj.tag;
83
+ if (tag)
84
+ props.push(doc.directives.tagString(tag));
68
85
  return props.join(' ');
69
86
  }
70
87
  function stringify(item, ctx, onComment, onChompKeep) {
88
+ var _a, _b;
71
89
  if (Node.isPair(item))
72
90
  return item.toString(ctx, onComment, onChompKeep);
73
- if (Node.isAlias(item))
74
- return item.toString(ctx);
91
+ if (Node.isAlias(item)) {
92
+ if (ctx.doc.directives)
93
+ return item.toString(ctx);
94
+ if ((_a = ctx.resolvedAliases) === null || _a === void 0 ? void 0 : _a.has(item)) {
95
+ throw new TypeError(`Cannot stringify circular structure without alias nodes`);
96
+ }
97
+ else {
98
+ if (ctx.resolvedAliases)
99
+ ctx.resolvedAliases.add(item);
100
+ else
101
+ ctx.resolvedAliases = new Set([item]);
102
+ item = item.resolve(ctx.doc);
103
+ }
104
+ }
75
105
  let tagObj = undefined;
76
106
  const node = Node.isNode(item)
77
107
  ? item
@@ -80,7 +110,7 @@ function stringify(item, ctx, onComment, onChompKeep) {
80
110
  tagObj = getTagObject(ctx.doc.schema.tags, node);
81
111
  const props = stringifyProps(node, tagObj, ctx);
82
112
  if (props.length > 0)
83
- ctx.indentAtStart = (ctx.indentAtStart || 0) + props.length + 1;
113
+ ctx.indentAtStart = ((_b = ctx.indentAtStart) !== null && _b !== void 0 ? _b : 0) + props.length + 1;
84
114
  const str = typeof tagObj.stringify === 'function'
85
115
  ? tagObj.stringify(node, ctx, onComment, onChompKeep)
86
116
  : Node.isScalar(node)
@@ -1,11 +1,7 @@
1
1
  import { Collection } from '../nodes/Collection.js';
2
2
  import { StringifyContext } from './stringify.js';
3
- declare type StringifyNode = {
4
- comment: boolean;
5
- str: string;
6
- };
7
3
  interface StringifyCollectionOptions {
8
- blockItem(node: StringifyNode): string;
4
+ blockItemPrefix: string;
9
5
  flowChars: {
10
6
  start: '{';
11
7
  end: '}';
@@ -17,5 +13,5 @@ interface StringifyCollectionOptions {
17
13
  onChompKeep?: () => void;
18
14
  onComment?: () => void;
19
15
  }
20
- export declare function stringifyCollection({ comment, flow, items }: Readonly<Collection>, ctx: StringifyContext, { blockItem, flowChars, itemIndent, onChompKeep, onComment }: StringifyCollectionOptions): string;
16
+ export declare function stringifyCollection(collection: Readonly<Collection>, ctx: StringifyContext, options: StringifyCollectionOptions): string;
21
17
  export {};
@@ -5,120 +5,150 @@ var Node = require('../nodes/Node.js');
5
5
  var stringify = require('./stringify.js');
6
6
  var stringifyComment = require('./stringifyComment.js');
7
7
 
8
- function stringifyCollection({ comment, flow, items }, ctx, { blockItem, flowChars, itemIndent, onChompKeep, onComment }) {
9
- const { indent, indentStep } = ctx;
10
- const inFlow = flow || ctx.inFlow;
11
- if (inFlow)
12
- itemIndent += indentStep;
13
- ctx = Object.assign({}, ctx, { indent: itemIndent, inFlow, type: null });
14
- let singleLineOutput = true;
8
+ function stringifyCollection(collection, ctx, options) {
9
+ var _a;
10
+ const flow = (_a = ctx.inFlow) !== null && _a !== void 0 ? _a : collection.flow;
11
+ const stringify = flow ? stringifyFlowCollection : stringifyBlockCollection;
12
+ return stringify(collection, ctx, options);
13
+ }
14
+ function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
15
+ const { indent, options: { commentString } } = ctx;
16
+ const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });
15
17
  let chompKeep = false; // flag for the preceding node's status
16
- const nodes = items.reduce((nodes, item, i) => {
18
+ const lines = [];
19
+ for (let i = 0; i < items.length; ++i) {
20
+ const item = items[i];
17
21
  let comment = null;
18
22
  if (Node.isNode(item)) {
19
23
  if (!chompKeep && item.spaceBefore)
20
- nodes.push({ comment: true, str: '' });
21
- let cb = item.commentBefore;
22
- if (cb && chompKeep)
23
- cb = cb.replace(/^\n+/, '');
24
- if (cb) {
25
- if (/^\n+$/.test(cb))
26
- cb = cb.substring(1);
27
- // This match will always succeed on a non-empty string
28
- for (const line of cb.match(/^.*$/gm)) {
29
- const str = line === ' ' ? '#' : line ? `#${line}` : '';
30
- nodes.push({ comment: true, str });
31
- }
32
- }
33
- if (item.comment) {
24
+ lines.push('');
25
+ addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
26
+ if (item.comment)
34
27
  comment = item.comment;
35
- singleLineOutput = false;
36
- }
37
28
  }
38
29
  else if (Node.isPair(item)) {
39
30
  const ik = Node.isNode(item.key) ? item.key : null;
40
31
  if (ik) {
41
32
  if (!chompKeep && ik.spaceBefore)
42
- nodes.push({ comment: true, str: '' });
43
- let cb = ik.commentBefore;
44
- if (cb && chompKeep)
45
- cb = cb.replace(/^\n+/, '');
46
- if (cb) {
47
- if (/^\n+$/.test(cb))
48
- cb = cb.substring(1);
49
- // This match will always succeed on a non-empty string
50
- for (const line of cb.match(/^.*$/gm)) {
51
- const str = line === ' ' ? '#' : line ? `#${line}` : '';
52
- nodes.push({ comment: true, str });
53
- }
54
- }
55
- if (ik.comment)
56
- singleLineOutput = false;
57
- }
58
- if (inFlow) {
59
- const iv = Node.isNode(item.value) ? item.value : null;
60
- if (iv) {
61
- if (iv.comment)
62
- comment = iv.comment;
63
- if (iv.comment || iv.commentBefore)
64
- singleLineOutput = false;
65
- }
66
- else if (item.value == null && ik && ik.comment) {
67
- comment = ik.comment;
68
- }
33
+ lines.push('');
34
+ addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);
69
35
  }
70
36
  }
71
37
  chompKeep = false;
72
- let str = stringify.stringify(item, ctx, () => (comment = null), () => (chompKeep = true));
73
- if (inFlow && i < items.length - 1)
74
- str += ',';
75
- str = stringifyComment.addComment(str, itemIndent, comment);
76
- if (chompKeep && (comment || inFlow))
38
+ let str = stringify.stringify(item, itemCtx, () => (comment = null), () => (chompKeep = true));
39
+ if (comment)
40
+ str += stringifyComment.lineComment(str, itemIndent, commentString(comment));
41
+ if (chompKeep && comment)
77
42
  chompKeep = false;
78
- nodes.push({ comment: false, str });
79
- return nodes;
80
- }, []);
43
+ lines.push(blockItemPrefix + str);
44
+ }
81
45
  let str;
82
- if (nodes.length === 0) {
46
+ if (lines.length === 0) {
83
47
  str = flowChars.start + flowChars.end;
84
48
  }
85
- else if (inFlow) {
86
- const { start, end } = flowChars;
87
- const strings = nodes.map(n => n.str);
88
- let singleLineLength = 2;
89
- for (const node of nodes) {
90
- if (node.comment || node.str.includes('\n')) {
91
- singleLineOutput = false;
92
- break;
49
+ else {
50
+ str = lines[0];
51
+ for (let i = 1; i < lines.length; ++i) {
52
+ const line = lines[i];
53
+ str += line ? `\n${indent}${line}` : '\n';
54
+ }
55
+ }
56
+ if (comment) {
57
+ str += '\n' + stringifyComment.indentComment(commentString(comment), indent);
58
+ if (onComment)
59
+ onComment();
60
+ }
61
+ else if (chompKeep && onChompKeep)
62
+ onChompKeep();
63
+ return str;
64
+ }
65
+ function stringifyFlowCollection({ comment, items }, ctx, { flowChars, itemIndent, onComment }) {
66
+ const { indent, indentStep, options: { commentString } } = ctx;
67
+ itemIndent += indentStep;
68
+ const itemCtx = Object.assign({}, ctx, {
69
+ indent: itemIndent,
70
+ inFlow: true,
71
+ type: null
72
+ });
73
+ let reqNewline = false;
74
+ let linesAtValue = 0;
75
+ const lines = [];
76
+ for (let i = 0; i < items.length; ++i) {
77
+ const item = items[i];
78
+ let comment = null;
79
+ if (Node.isNode(item)) {
80
+ if (item.spaceBefore)
81
+ lines.push('');
82
+ addCommentBefore(ctx, lines, item.commentBefore, false);
83
+ if (item.comment)
84
+ comment = item.comment;
85
+ }
86
+ else if (Node.isPair(item)) {
87
+ const ik = Node.isNode(item.key) ? item.key : null;
88
+ if (ik) {
89
+ if (ik.spaceBefore)
90
+ lines.push('');
91
+ addCommentBefore(ctx, lines, ik.commentBefore, false);
92
+ if (ik.comment)
93
+ reqNewline = true;
94
+ }
95
+ const iv = Node.isNode(item.value) ? item.value : null;
96
+ if (iv) {
97
+ if (iv.comment)
98
+ comment = iv.comment;
99
+ if (iv.commentBefore)
100
+ reqNewline = true;
101
+ }
102
+ else if (item.value == null && ik && ik.comment) {
103
+ comment = ik.comment;
93
104
  }
94
- singleLineLength += node.str.length + 2;
95
105
  }
96
- if (!singleLineOutput ||
97
- singleLineLength > Collection.Collection.maxFlowStringSingleLineLength) {
106
+ if (comment)
107
+ reqNewline = true;
108
+ let str = stringify.stringify(item, itemCtx, () => (comment = null));
109
+ if (i < items.length - 1)
110
+ str += ',';
111
+ if (comment)
112
+ str += stringifyComment.lineComment(str, itemIndent, commentString(comment));
113
+ if (!reqNewline && (lines.length > linesAtValue || str.includes('\n')))
114
+ reqNewline = true;
115
+ lines.push(str);
116
+ linesAtValue = lines.length;
117
+ }
118
+ let str;
119
+ const { start, end } = flowChars;
120
+ if (lines.length === 0) {
121
+ str = start + end;
122
+ }
123
+ else {
124
+ if (!reqNewline) {
125
+ const len = lines.reduce((sum, line) => sum + line.length + 2, 2);
126
+ reqNewline = len > Collection.Collection.maxFlowStringSingleLineLength;
127
+ }
128
+ if (reqNewline) {
98
129
  str = start;
99
- for (const s of strings) {
100
- str += s ? `\n${indentStep}${indent}${s}` : '\n';
101
- }
130
+ for (const line of lines)
131
+ str += line ? `\n${indentStep}${indent}${line}` : '\n';
102
132
  str += `\n${indent}${end}`;
103
133
  }
104
134
  else {
105
- str = `${start} ${strings.join(' ')} ${end}`;
135
+ str = `${start} ${lines.join(' ')} ${end}`;
106
136
  }
107
137
  }
108
- else {
109
- const strings = nodes.map(blockItem);
110
- str = strings.shift() || '';
111
- for (const s of strings)
112
- str += s ? `\n${indent}${s}` : '\n';
113
- }
114
138
  if (comment) {
115
- str += '\n' + stringifyComment.stringifyComment(comment, indent);
139
+ str += stringifyComment.lineComment(str, commentString(comment), indent);
116
140
  if (onComment)
117
141
  onComment();
118
142
  }
119
- else if (chompKeep && onChompKeep)
120
- onChompKeep();
121
143
  return str;
122
144
  }
145
+ function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {
146
+ if (comment && chompKeep)
147
+ comment = comment.replace(/^\n+/, '');
148
+ if (comment) {
149
+ const ic = stringifyComment.indentComment(commentString(comment), indent);
150
+ lines.push(ic.trimStart()); // Avoid double indent on first line
151
+ }
152
+ }
123
153
 
124
154
  exports.stringifyCollection = stringifyCollection;
@@ -1,2 +1,10 @@
1
- export declare const stringifyComment: (comment: string, indent: string) => string;
2
- export declare function addComment(str: string, indent: string, comment?: string | null): string;
1
+ /**
2
+ * Stringifies a comment.
3
+ *
4
+ * Empty comment lines are left empty,
5
+ * lines consisting of a single space are replaced by `#`,
6
+ * and all other lines are prefixed with a `#`.
7
+ */
8
+ export declare const stringifyComment: (str: string) => string;
9
+ export declare function indentComment(comment: string, indent: string): string;
10
+ export declare const lineComment: (str: string, indent: string, comment: string) => string;
@@ -1,17 +1,24 @@
1
1
  'use strict';
2
2
 
3
- const stringifyComment = (comment, indent) => /^\n+$/.test(comment)
4
- ? comment.substring(1)
5
- : comment.replace(/^(?!$)(?: $)?/gm, `${indent}#`);
6
- function addComment(str, indent, comment) {
7
- return !comment
8
- ? str
9
- : comment.includes('\n')
10
- ? `${str}\n` + stringifyComment(comment, indent)
11
- : str.endsWith(' ')
12
- ? `${str}#${comment}`
13
- : `${str} #${comment}`;
3
+ /**
4
+ * Stringifies a comment.
5
+ *
6
+ * Empty comment lines are left empty,
7
+ * lines consisting of a single space are replaced by `#`,
8
+ * and all other lines are prefixed with a `#`.
9
+ */
10
+ const stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, '#');
11
+ function indentComment(comment, indent) {
12
+ if (/^\n+$/.test(comment))
13
+ return comment.substring(1);
14
+ return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;
14
15
  }
16
+ const lineComment = (str, indent, comment) => str.endsWith('\n')
17
+ ? indentComment(comment, indent)
18
+ : comment.includes('\n')
19
+ ? '\n' + indentComment(comment, indent)
20
+ : (str.endsWith(' ') ? '' : ' ') + comment;
15
21
 
16
- exports.addComment = addComment;
22
+ exports.indentComment = indentComment;
23
+ exports.lineComment = lineComment;
17
24
  exports.stringifyComment = stringifyComment;