addPairToJSMap.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { warn } from '../log.js';
  2. import { isMergeKey, addMergeToJSMap } from '../schema/yaml-1.1/merge.js';
  3. import { createStringifyContext } from '../stringify/stringify.js';
  4. import { isNode } from './identity.js';
  5. import { toJS } from './toJS.js';
  6. function addPairToJSMap(ctx, map, { key, value }) {
  7. if (isNode(key) && key.addToJSMap)
  8. key.addToJSMap(ctx, map, value);
  9. // TODO: Should drop this special case for bare << handling
  10. else if (isMergeKey(ctx, key))
  11. addMergeToJSMap(ctx, map, value);
  12. else {
  13. const jsKey = toJS(key, '', ctx);
  14. if (map instanceof Map) {
  15. map.set(jsKey, toJS(value, jsKey, ctx));
  16. }
  17. else if (map instanceof Set) {
  18. map.add(jsKey);
  19. }
  20. else {
  21. const stringKey = stringifyKey(key, jsKey, ctx);
  22. const jsValue = toJS(value, stringKey, ctx);
  23. if (stringKey in map)
  24. Object.defineProperty(map, stringKey, {
  25. value: jsValue,
  26. writable: true,
  27. enumerable: true,
  28. configurable: true
  29. });
  30. else
  31. map[stringKey] = jsValue;
  32. }
  33. }
  34. return map;
  35. }
  36. function stringifyKey(key, jsKey, ctx) {
  37. if (jsKey === null)
  38. return '';
  39. if (typeof jsKey !== 'object')
  40. return String(jsKey);
  41. if (isNode(key) && ctx?.doc) {
  42. const strCtx = createStringifyContext(ctx.doc, {});
  43. strCtx.anchors = new Set();
  44. for (const node of ctx.anchors.keys())
  45. strCtx.anchors.add(node.anchor);
  46. strCtx.inFlow = true;
  47. strCtx.inStringifyKey = true;
  48. const strKey = key.toString(strCtx);
  49. if (!ctx.mapKeyWarned) {
  50. let jsonStr = JSON.stringify(strKey);
  51. if (jsonStr.length > 40)
  52. jsonStr = jsonStr.substring(0, 36) + '..."';
  53. warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
  54. ctx.mapKeyWarned = true;
  55. }
  56. return strKey;
  57. }
  58. return JSON.stringify(jsKey);
  59. }
  60. export { addPairToJSMap };