toJS.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. var identity = require('./identity.js');
  3. /**
  4. * Recursively convert any node or its contents to native JavaScript
  5. *
  6. * @param value - The input value
  7. * @param arg - If `value` defines a `toJSON()` method, use this
  8. * as its first argument
  9. * @param ctx - Conversion context, originally set in Document#toJS(). If
  10. * `{ keep: true }` is not set, output should be suitable for JSON
  11. * stringification.
  12. */
  13. function toJS(value, arg, ctx) {
  14. // eslint-disable-next-line @typescript-eslint/no-unsafe-return
  15. if (Array.isArray(value))
  16. return value.map((v, i) => toJS(v, String(i), ctx));
  17. if (value && typeof value.toJSON === 'function') {
  18. // eslint-disable-next-line @typescript-eslint/no-unsafe-call
  19. if (!ctx || !identity.hasAnchor(value))
  20. return value.toJSON(arg, ctx);
  21. const data = { aliasCount: 0, count: 1, res: undefined };
  22. ctx.anchors.set(value, data);
  23. ctx.onCreate = res => {
  24. data.res = res;
  25. delete ctx.onCreate;
  26. };
  27. const res = value.toJSON(arg, ctx);
  28. if (ctx.onCreate)
  29. ctx.onCreate(res);
  30. return res;
  31. }
  32. if (typeof value === 'bigint' && !ctx?.keep)
  33. return Number(value);
  34. return value;
  35. }
  36. exports.toJS = toJS;