Нет описания

omap.js 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { YAMLSeq } from '../../nodes/YAMLSeq.js';
  2. import { toJS } from '../../nodes/toJS.js';
  3. import { isScalar, isPair } from '../../nodes/Node.js';
  4. import { YAMLMap } from '../../nodes/YAMLMap.js';
  5. import { resolvePairs, createPairs } from './pairs.js';
  6. class YAMLOMap extends YAMLSeq {
  7. constructor() {
  8. super();
  9. this.add = YAMLMap.prototype.add.bind(this);
  10. this.delete = YAMLMap.prototype.delete.bind(this);
  11. this.get = YAMLMap.prototype.get.bind(this);
  12. this.has = YAMLMap.prototype.has.bind(this);
  13. this.set = YAMLMap.prototype.set.bind(this);
  14. this.tag = YAMLOMap.tag;
  15. }
  16. /**
  17. * If `ctx` is given, the return type is actually `Map<unknown, unknown>`,
  18. * but TypeScript won't allow widening the signature of a child method.
  19. */
  20. toJSON(_, ctx) {
  21. if (!ctx)
  22. return super.toJSON(_);
  23. const map = new Map();
  24. if (ctx?.onCreate)
  25. ctx.onCreate(map);
  26. for (const pair of this.items) {
  27. let key, value;
  28. if (isPair(pair)) {
  29. key = toJS(pair.key, '', ctx);
  30. value = toJS(pair.value, key, ctx);
  31. }
  32. else {
  33. key = toJS(pair, '', ctx);
  34. }
  35. if (map.has(key))
  36. throw new Error('Ordered maps must not include duplicate keys');
  37. map.set(key, value);
  38. }
  39. return map;
  40. }
  41. }
  42. YAMLOMap.tag = 'tag:yaml.org,2002:omap';
  43. const omap = {
  44. collection: 'seq',
  45. identify: value => value instanceof Map,
  46. nodeClass: YAMLOMap,
  47. default: false,
  48. tag: 'tag:yaml.org,2002:omap',
  49. resolve(seq, onError) {
  50. const pairs = resolvePairs(seq, onError);
  51. const seenKeys = [];
  52. for (const { key } of pairs.items) {
  53. if (isScalar(key)) {
  54. if (seenKeys.includes(key.value)) {
  55. onError(`Ordered maps must not include duplicate keys: ${key.value}`);
  56. }
  57. else {
  58. seenKeys.push(key.value);
  59. }
  60. }
  61. }
  62. return Object.assign(new YAMLOMap(), pairs);
  63. },
  64. createNode(schema, iterable, ctx) {
  65. const pairs = createPairs(schema, iterable, ctx);
  66. const omap = new YAMLOMap();
  67. omap.items = pairs.items;
  68. return omap;
  69. }
  70. };
  71. export { YAMLOMap, omap };