@discoveryjs/discovery
Version:
Frontend framework for rapid data (JSON) analysis, shareable serverless reports and dashboards
57 lines (56 loc) • 2.23 kB
JavaScript
import { objectToString } from "./object-utils.js";
export { stringifyInfo as jsonStringifyInfo } from "@discoveryjs/json-ext";
function prettyFn(fn, ws, property) {
const src = String(fn);
const [prefix, name] = src.match(/^(?:\S+\s+)?(\S+)\(/) || [];
if (prefix !== "function" && prefix !== "function*" && name === property.trim().slice(0, -1)) {
property = "";
}
if (src.indexOf("\n") === -1) {
return property + src;
}
const lines = src.split(/\n/);
const minOffset = lines[lines.length - 1].match(/^\s*/)?.[0].length || 0;
const stripOffset = new RegExp("^\\s{0," + minOffset + "}");
return property + lines.map((line, idx) => idx && line.length ? line.replace(stripOffset, ws) : line).join("\n");
}
function restoreValue(value, ws, property) {
if (typeof value === "function") {
return prettyFn(value, ws, property);
}
if (value instanceof Date) {
return `${property}new Date("${value.toISOString()}")`;
}
if (Array.isArray(value)) {
return `${property}[${value.join(", ")}]`;
}
return property + String(value);
}
const specialValueTypes = /* @__PURE__ */ new Set([
"[object Function]",
"[object RegExp]",
"[object Date]"
]);
function isNumericArray(value) {
return Array.isArray(value) && value.every((el) => typeof el === "number");
}
export function jsonStringifyAsJavaScript(value, replacer, space = 4) {
const specials = [];
const jsReplacer = function(key, value2) {
if (typeof value2 === "string" && objectToString(this[key]) === "[object Date]") {
value2 = this[key];
}
if (value2 !== null && (specialValueTypes.has(objectToString(value2)) || isNumericArray(value2))) {
specials.push(value2);
return "{{{__placeholder__}}}";
}
return value2;
};
return String(JSON.stringify(value, replacer || jsReplacer, space)).replace(
/"((?:\\.|[^"])*)"(:?)/g,
(_, content, colon) => colon && /^[a-z$_][a-z$_\d]*$/i.test(content) ? content + colon : `'${content.replace(/\\"/g, '"').replace(/'/g, "\\'")}'` + colon
).replace(
/(^|\n)([ \t]*)(.*?)([a-zA-Z$_][a-zA-Z0-9$_]+:\s*)?'{{{__placeholder__}}}'/g,
(_, rn, ws, any, property) => rn + ws + any + restoreValue(specials.shift(), ws, property)
);
}