addPairToJSMap.js 2.2 KB

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