Document.js 13 KB

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