Document.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. import { Alias } from '../nodes/Alias.js';
  2. import { isEmptyPath, collectionFromPath } from '../nodes/Collection.js';
  3. import { NODE_TYPE, DOC, isNode, isCollection, isScalar } from '../nodes/identity.js';
  4. import { Pair } from '../nodes/Pair.js';
  5. import { toJS } from '../nodes/toJS.js';
  6. import { Schema } from '../schema/Schema.js';
  7. import { stringifyDocument } from '../stringify/stringifyDocument.js';
  8. import { anchorNames, findNewAnchor, createNodeAnchors } from './anchors.js';
  9. import { applyReviver } from './applyReviver.js';
  10. import { createNode } from './createNode.js';
  11. import { Directives } from './directives.js';
  12. class Document {
  13. constructor(value, replacer, options) {
  14. /** A comment before this Document */
  15. this.commentBefore = null;
  16. /** A comment immediately after this Document */
  17. this.comment = null;
  18. /** Errors encountered during parsing. */
  19. this.errors = [];
  20. /** Warnings encountered during parsing. */
  21. this.warnings = [];
  22. Object.defineProperty(this, NODE_TYPE, { value: DOC });
  23. let _replacer = null;
  24. if (typeof replacer === 'function' || Array.isArray(replacer)) {
  25. _replacer = replacer;
  26. }
  27. else if (options === undefined && replacer) {
  28. options = replacer;
  29. replacer = undefined;
  30. }
  31. const opt = Object.assign({
  32. intAsBigInt: false,
  33. keepSourceTokens: false,
  34. logLevel: 'warn',
  35. prettyErrors: true,
  36. strict: true,
  37. uniqueKeys: true,
  38. version: '1.2'
  39. }, options);
  40. this.options = opt;
  41. let { version } = opt;
  42. if (options?._directives) {
  43. this.directives = options._directives.atDocument();
  44. if (this.directives.yaml.explicit)
  45. version = this.directives.yaml.version;
  46. }
  47. else
  48. this.directives = new Directives({ version });
  49. this.setSchema(version, options);
  50. // @ts-expect-error We can't really know that this matches Contents.
  51. this.contents =
  52. value === undefined ? null : this.createNode(value, _replacer, options);
  53. }
  54. /**
  55. * Create a deep copy of this Document and its contents.
  56. *
  57. * Custom Node values that inherit from `Object` still refer to their original instances.
  58. */
  59. clone() {
  60. const copy = Object.create(Document.prototype, {
  61. [NODE_TYPE]: { value: DOC }
  62. });
  63. copy.commentBefore = this.commentBefore;
  64. copy.comment = this.comment;
  65. copy.errors = this.errors.slice();
  66. copy.warnings = this.warnings.slice();
  67. copy.options = Object.assign({}, this.options);
  68. if (this.directives)
  69. copy.directives = this.directives.clone();
  70. copy.schema = this.schema.clone();
  71. // @ts-expect-error We can't really know that this matches Contents.
  72. copy.contents = isNode(this.contents)
  73. ? this.contents.clone(copy.schema)
  74. : this.contents;
  75. if (this.range)
  76. copy.range = this.range.slice();
  77. return copy;
  78. }
  79. /** Adds a value to the document. */
  80. add(value) {
  81. if (assertCollection(this.contents))
  82. this.contents.add(value);
  83. }
  84. /** Adds a value to the document. */
  85. addIn(path, value) {
  86. if (assertCollection(this.contents))
  87. this.contents.addIn(path, value);
  88. }
  89. /**
  90. * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
  91. *
  92. * If `node` already has an anchor, `name` is ignored.
  93. * Otherwise, the `node.anchor` value will be set to `name`,
  94. * or if an anchor with that name is already present in the document,
  95. * `name` will be used as a prefix for a new unique anchor.
  96. * If `name` is undefined, the generated anchor will use 'a' as a prefix.
  97. */
  98. createAlias(node, name) {
  99. if (!node.anchor) {
  100. const prev = anchorNames(this);
  101. node.anchor =
  102. // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
  103. !name || prev.has(name) ? findNewAnchor(name || 'a', prev) : name;
  104. }
  105. return new Alias(node.anchor);
  106. }
  107. createNode(value, replacer, options) {
  108. let _replacer = undefined;
  109. if (typeof replacer === 'function') {
  110. value = replacer.call({ '': value }, '', value);
  111. _replacer = replacer;
  112. }
  113. else if (Array.isArray(replacer)) {
  114. const keyToStr = (v) => typeof v === 'number' || v instanceof String || v instanceof Number;
  115. const asStr = replacer.filter(keyToStr).map(String);
  116. if (asStr.length > 0)
  117. replacer = replacer.concat(asStr);
  118. _replacer = replacer;
  119. }
  120. else if (options === undefined && replacer) {
  121. options = replacer;
  122. replacer = undefined;
  123. }
  124. const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};
  125. const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors(this,
  126. // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
  127. anchorPrefix || 'a');
  128. const ctx = {
  129. aliasDuplicateObjects: aliasDuplicateObjects ?? true,
  130. keepUndefined: keepUndefined ?? false,
  131. onAnchor,
  132. onTagObj,
  133. replacer: _replacer,
  134. schema: this.schema,
  135. sourceObjects
  136. };
  137. const node = createNode(value, tag, ctx);
  138. if (flow && isCollection(node))
  139. node.flow = true;
  140. setAnchors();
  141. return node;
  142. }
  143. /**
  144. * Convert a key and a value into a `Pair` using the current schema,
  145. * recursively wrapping all values as `Scalar` or `Collection` nodes.
  146. */
  147. createPair(key, value, options = {}) {
  148. const k = this.createNode(key, null, options);
  149. const v = this.createNode(value, null, options);
  150. return new Pair(k, v);
  151. }
  152. /**
  153. * Removes a value from the document.
  154. * @returns `true` if the item was found and removed.
  155. */
  156. delete(key) {
  157. return assertCollection(this.contents) ? this.contents.delete(key) : false;
  158. }
  159. /**
  160. * Removes a value from the document.
  161. * @returns `true` if the item was found and removed.
  162. */
  163. deleteIn(path) {
  164. if (isEmptyPath(path)) {
  165. if (this.contents == null)
  166. return false;
  167. // @ts-expect-error Presumed impossible if Strict extends false
  168. this.contents = null;
  169. return true;
  170. }
  171. return assertCollection(this.contents)
  172. ? this.contents.deleteIn(path)
  173. : false;
  174. }
  175. /**
  176. * Returns item at `key`, or `undefined` if not found. By default unwraps
  177. * scalar values from their surrounding node; to disable set `keepScalar` to
  178. * `true` (collections are always returned intact).
  179. */
  180. get(key, keepScalar) {
  181. return isCollection(this.contents)
  182. ? this.contents.get(key, keepScalar)
  183. : undefined;
  184. }
  185. /**
  186. * Returns item at `path`, or `undefined` if not found. By default unwraps
  187. * scalar values from their surrounding node; to disable set `keepScalar` to
  188. * `true` (collections are always returned intact).
  189. */
  190. getIn(path, keepScalar) {
  191. if (isEmptyPath(path))
  192. return !keepScalar && isScalar(this.contents)
  193. ? this.contents.value
  194. : this.contents;
  195. return isCollection(this.contents)
  196. ? this.contents.getIn(path, keepScalar)
  197. : undefined;
  198. }
  199. /**
  200. * Checks if the document includes a value with the key `key`.
  201. */
  202. has(key) {
  203. return isCollection(this.contents) ? this.contents.has(key) : false;
  204. }
  205. /**
  206. * Checks if the document includes a value at `path`.
  207. */
  208. hasIn(path) {
  209. if (isEmptyPath(path))
  210. return this.contents !== undefined;
  211. return isCollection(this.contents) ? this.contents.hasIn(path) : false;
  212. }
  213. /**
  214. * Sets a value in this document. For `!!set`, `value` needs to be a
  215. * boolean to add/remove the item from the set.
  216. */
  217. set(key, value) {
  218. if (this.contents == null) {
  219. // @ts-expect-error We can't really know that this matches Contents.
  220. this.contents = collectionFromPath(this.schema, [key], value);
  221. }
  222. else if (assertCollection(this.contents)) {
  223. this.contents.set(key, value);
  224. }
  225. }
  226. /**
  227. * Sets a value in this document. For `!!set`, `value` needs to be a
  228. * boolean to add/remove the item from the set.
  229. */
  230. setIn(path, value) {
  231. if (isEmptyPath(path)) {
  232. // @ts-expect-error We can't really know that this matches Contents.
  233. this.contents = value;
  234. }
  235. else if (this.contents == null) {
  236. // @ts-expect-error We can't really know that this matches Contents.
  237. this.contents = collectionFromPath(this.schema, Array.from(path), value);
  238. }
  239. else if (assertCollection(this.contents)) {
  240. this.contents.setIn(path, value);
  241. }
  242. }
  243. /**
  244. * Change the YAML version and schema used by the document.
  245. * A `null` version disables support for directives, explicit tags, anchors, and aliases.
  246. * It also requires the `schema` option to be given as a `Schema` instance value.
  247. *
  248. * Overrides all previously set schema options.
  249. */
  250. setSchema(version, options = {}) {
  251. if (typeof version === 'number')
  252. version = String(version);
  253. let opt;
  254. switch (version) {
  255. case '1.1':
  256. if (this.directives)
  257. this.directives.yaml.version = '1.1';
  258. else
  259. this.directives = new Directives({ version: '1.1' });
  260. opt = { merge: true, resolveKnownTags: false, schema: 'yaml-1.1' };
  261. break;
  262. case '1.2':
  263. case 'next':
  264. if (this.directives)
  265. this.directives.yaml.version = version;
  266. else
  267. this.directives = new Directives({ version });
  268. opt = { merge: false, resolveKnownTags: true, schema: 'core' };
  269. break;
  270. case null:
  271. if (this.directives)
  272. delete this.directives;
  273. opt = null;
  274. break;
  275. default: {
  276. const sv = JSON.stringify(version);
  277. throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
  278. }
  279. }
  280. // Not using `instanceof Schema` to allow for duck typing
  281. if (options.schema instanceof Object)
  282. this.schema = options.schema;
  283. else if (opt)
  284. this.schema = new Schema(Object.assign(opt, options));
  285. else
  286. throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
  287. }
  288. // json & jsonArg are only used from toJSON()
  289. toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
  290. const ctx = {
  291. anchors: new Map(),
  292. doc: this,
  293. keep: !json,
  294. mapAsMap: mapAsMap === true,
  295. mapKeyWarned: false,
  296. maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100
  297. };
  298. const res = toJS(this.contents, jsonArg ?? '', ctx);
  299. if (typeof onAnchor === 'function')
  300. for (const { count, res } of ctx.anchors.values())
  301. onAnchor(res, count);
  302. return typeof reviver === 'function'
  303. ? applyReviver(reviver, { '': res }, '', res)
  304. : res;
  305. }
  306. /**
  307. * A JSON representation of the document `contents`.
  308. *
  309. * @param jsonArg Used by `JSON.stringify` to indicate the array index or
  310. * property name.
  311. */
  312. toJSON(jsonArg, onAnchor) {
  313. return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
  314. }
  315. /** A YAML representation of the document. */
  316. toString(options = {}) {
  317. if (this.errors.length > 0)
  318. throw new Error('Document with errors cannot be stringified');
  319. if ('indent' in options &&
  320. (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {
  321. const s = JSON.stringify(options.indent);
  322. throw new Error(`"indent" option must be a positive integer, not ${s}`);
  323. }
  324. return stringifyDocument(this, options);
  325. }
  326. }
  327. function assertCollection(contents) {
  328. if (isCollection(contents))
  329. return true;
  330. throw new Error('Expected a YAML collection as document contents');
  331. }
  332. export { Document };