Нет описания

Document.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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/Node.js';
  4. import { Pair } from '../nodes/Pair.js';
  5. import { toJS } from '../nodes/toJS.js';
  6. import { Schema } from '../schema/Schema.js';
  7. import { stringify } from '../stringify/stringify.js';
  8. import { stringifyDocument } from '../stringify/stringifyDocument.js';
  9. import { anchorNames, findNewAnchor, createNodeAnchors } from './anchors.js';
  10. import { applyReviver } from './applyReviver.js';
  11. import { createNode } from './createNode.js';
  12. import { Directives } from './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, NODE_TYPE, { value: 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. uniqueKeys: true,
  39. version: '1.2'
  40. }, options);
  41. this.options = opt;
  42. let { version } = opt;
  43. if (options?._directives) {
  44. this.directives = options._directives.atDocument();
  45. if (this.directives.yaml.explicit)
  46. version = this.directives.yaml.version;
  47. }
  48. else
  49. this.directives = new Directives({ version });
  50. this.setSchema(version, options);
  51. if (value === undefined)
  52. this.contents = null;
  53. else {
  54. this.contents = this.createNode(value, _replacer, options);
  55. }
  56. }
  57. /**
  58. * Create a deep copy of this Document and its contents.
  59. *
  60. * Custom Node values that inherit from `Object` still refer to their original instances.
  61. */
  62. clone() {
  63. const copy = Object.create(Document.prototype, {
  64. [NODE_TYPE]: { value: DOC }
  65. });
  66. copy.commentBefore = this.commentBefore;
  67. copy.comment = this.comment;
  68. copy.errors = this.errors.slice();
  69. copy.warnings = this.warnings.slice();
  70. copy.options = Object.assign({}, this.options);
  71. if (this.directives)
  72. copy.directives = this.directives.clone();
  73. copy.schema = this.schema.clone();
  74. copy.contents = 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 = anchorNames(this);
  103. node.anchor =
  104. // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
  105. !name || prev.has(name) ? findNewAnchor(name || 'a', prev) : name;
  106. }
  107. return new 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 } = 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(value, tag, ctx);
  140. if (flow && 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(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 (isEmptyPath(path)) {
  167. if (this.contents == null)
  168. return false;
  169. this.contents = null;
  170. return true;
  171. }
  172. return assertCollection(this.contents)
  173. ? this.contents.deleteIn(path)
  174. : false;
  175. }
  176. /**
  177. * Returns item at `key`, or `undefined` if not found. By default unwraps
  178. * scalar values from their surrounding node; to disable set `keepScalar` to
  179. * `true` (collections are always returned intact).
  180. */
  181. get(key, keepScalar) {
  182. return isCollection(this.contents)
  183. ? this.contents.get(key, keepScalar)
  184. : undefined;
  185. }
  186. /**
  187. * Returns item at `path`, or `undefined` if not found. By default unwraps
  188. * scalar values from their surrounding node; to disable set `keepScalar` to
  189. * `true` (collections are always returned intact).
  190. */
  191. getIn(path, keepScalar) {
  192. if (isEmptyPath(path))
  193. return !keepScalar && isScalar(this.contents)
  194. ? this.contents.value
  195. : this.contents;
  196. return isCollection(this.contents)
  197. ? this.contents.getIn(path, keepScalar)
  198. : undefined;
  199. }
  200. /**
  201. * Checks if the document includes a value with the key `key`.
  202. */
  203. has(key) {
  204. return isCollection(this.contents) ? this.contents.has(key) : false;
  205. }
  206. /**
  207. * Checks if the document includes a value at `path`.
  208. */
  209. hasIn(path) {
  210. if (isEmptyPath(path))
  211. return this.contents !== undefined;
  212. return isCollection(this.contents) ? this.contents.hasIn(path) : false;
  213. }
  214. /**
  215. * Sets a value in this document. For `!!set`, `value` needs to be a
  216. * boolean to add/remove the item from the set.
  217. */
  218. set(key, value) {
  219. if (this.contents == null) {
  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. this.contents = value;
  233. else if (this.contents == null) {
  234. this.contents = collectionFromPath(this.schema, Array.from(path), value);
  235. }
  236. else if (assertCollection(this.contents)) {
  237. this.contents.setIn(path, value);
  238. }
  239. }
  240. /**
  241. * Change the YAML version and schema used by the document.
  242. * A `null` version disables support for directives, explicit tags, anchors, and aliases.
  243. * It also requires the `schema` option to be given as a `Schema` instance value.
  244. *
  245. * Overrides all previously set schema options.
  246. */
  247. setSchema(version, options = {}) {
  248. if (typeof version === 'number')
  249. version = String(version);
  250. let opt;
  251. switch (version) {
  252. case '1.1':
  253. if (this.directives)
  254. this.directives.yaml.version = '1.1';
  255. else
  256. this.directives = new Directives({ version: '1.1' });
  257. opt = { merge: true, resolveKnownTags: false, schema: 'yaml-1.1' };
  258. break;
  259. case '1.2':
  260. case 'next':
  261. if (this.directives)
  262. this.directives.yaml.version = version;
  263. else
  264. this.directives = new Directives({ version });
  265. opt = { merge: false, resolveKnownTags: true, schema: 'core' };
  266. break;
  267. case null:
  268. if (this.directives)
  269. delete this.directives;
  270. opt = null;
  271. break;
  272. default: {
  273. const sv = JSON.stringify(version);
  274. throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
  275. }
  276. }
  277. // Not using `instanceof Schema` to allow for duck typing
  278. if (options.schema instanceof Object)
  279. this.schema = options.schema;
  280. else if (opt)
  281. this.schema = new Schema(Object.assign(opt, options));
  282. else
  283. throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
  284. }
  285. // json & jsonArg are only used from toJSON()
  286. toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
  287. const ctx = {
  288. anchors: new Map(),
  289. doc: this,
  290. keep: !json,
  291. mapAsMap: mapAsMap === true,
  292. mapKeyWarned: false,
  293. maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100,
  294. stringify
  295. };
  296. const res = toJS(this.contents, jsonArg ?? '', ctx);
  297. if (typeof onAnchor === 'function')
  298. for (const { count, res } of ctx.anchors.values())
  299. onAnchor(res, count);
  300. return typeof reviver === 'function'
  301. ? applyReviver(reviver, { '': res }, '', res)
  302. : res;
  303. }
  304. /**
  305. * A JSON representation of the document `contents`.
  306. *
  307. * @param jsonArg Used by `JSON.stringify` to indicate the array index or
  308. * property name.
  309. */
  310. toJSON(jsonArg, onAnchor) {
  311. return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
  312. }
  313. /** A YAML representation of the document. */
  314. toString(options = {}) {
  315. if (this.errors.length > 0)
  316. throw new Error('Document with errors cannot be stringified');
  317. if ('indent' in options &&
  318. (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {
  319. const s = JSON.stringify(options.indent);
  320. throw new Error(`"indent" option must be a positive integer, not ${s}`);
  321. }
  322. return stringifyDocument(this, options);
  323. }
  324. }
  325. function assertCollection(contents) {
  326. if (isCollection(contents))
  327. return true;
  328. throw new Error('Expected a YAML collection as document contents');
  329. }
  330. export { Document };