UNPKG

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