Project Files
src / json.ts
// Source-preserving JSON parser. Numeric tokens are never converted to Number,
// so large identifiers keep their exact digits. Offsets use decoded UTF-16 text.
export type JsonType = "object" | "array" | "string" | "number" | "boolean" | "null";
export interface JsonNode {
id: number; parent: number | null; key: string; type: JsonType; recordId: number;
start: number; end: number; line: number; column: number; endLine: number; childCount: number;
}
export interface JsonIndex { version: 1; nodes: JsonNode[]; }
const MAX_NODES = 200_000, MAX_DEPTH = 128, MAX_POINTER = 8192;
const encode = (key: string) => key.replace(/~/g, "~0").replace(/\//g, "~1");
export function parseJson(text: string): JsonIndex {
const nodes: JsonNode[] = [];
let pos = 0, line = 1, lineStart = 0;
const fail = (message: string): never => { throw new Error(`Invalid JSON at line ${line}, column ${pos - lineStart + 1}: ${message}`); };
const whitespace = () => {
while (pos < text.length && /[\x20\t\r\n]/.test(text[pos])) {
if (text[pos] === "\n") { line++; lineStart = pos + 1; }
pos++;
}
};
const string = (): string => {
const start = pos++;
while (pos < text.length) {
const char = text.charCodeAt(pos++);
if (char === 34) {
try { return JSON.parse(text.slice(start, pos)) as string; }
catch { return fail("Invalid string escape."); }
}
if (char < 32) return fail("Unescaped control character in string.");
if (char === 92) pos++; // JSON.parse validates escape syntax, including \u.
}
return fail("Unterminated string.");
};
const number = /-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/y;
const value = (parent: number | null, key: string, depth: number, pathLength: number,
recordId: number | undefined, inArrayRecord: boolean): void => {
whitespace();
if (depth > MAX_DEPTH) fail(`Nesting exceeds ${MAX_DEPTH} levels.`);
if (nodes.length >= MAX_NODES) fail(`Node count exceeds ${MAX_NODES}. Split the file.`);
if (pathLength > MAX_POINTER) fail(`JSON pointer exceeds ${MAX_POINTER} characters.`);
const char = text[pos];
const type: JsonType = char === "{" ? "object" : char === "[" ? "array" : char === '"' ? "string"
: char === "t" || char === "f" ? "boolean" : char === "n" ? "null" : "number";
const id = nodes.length;
const node: JsonNode = { id, parent, key, type, recordId: recordId ?? id,
start: pos, end: pos, line, column: pos - lineStart + 1, endLine: line, childCount: 0 };
nodes.push(node);
if (parent !== null) nodes[parent].childCount++;
if (char === "{" || char === "[") {
const object = char === "{", close = object ? "}" : "]";
pos++; whitespace();
if (text[pos] !== close) {
let index = 0;
while (true) {
whitespace();
let childKey: string;
if (object) {
if (text[pos] !== '"') fail("Expected an object key.");
childKey = string(); whitespace();
if (text[pos++] !== ":") fail("Expected ':' after an object key.");
} else childKey = String(index++);
const arrayRecord = !object && !inArrayRecord;
value(id, childKey, depth + 1, pathLength + 1 + encode(childKey).length,
arrayRecord ? undefined : node.recordId, inArrayRecord || arrayRecord);
whitespace();
if (text[pos] === close) break;
if (text[pos++] !== ",") fail(`Expected ',' or '${close}'.`);
}
}
pos++;
} else if (char === '"') string();
else if (char === "t" && text.startsWith("true", pos)) pos += 4;
else if (char === "f" && text.startsWith("false", pos)) pos += 5;
else if (char === "n" && text.startsWith("null", pos)) pos += 4;
else {
number.lastIndex = pos;
const match = number.exec(text);
if (!match) fail("Expected a JSON value.");
pos = number.lastIndex;
}
node.end = pos; node.endLine = line;
};
value(null, "", 0, 0, undefined, false);
whitespace();
if (pos !== text.length) fail("Unexpected trailing content.");
return { version: 1, nodes };
}
export function jsonPointer(index: JsonIndex, node: JsonNode): string {
const segments: string[] = [];
for (let current = node; current.parent !== null; current = index.nodes[current.parent]) segments.push(encode(current.key));
return segments.length ? `/${segments.reverse().join("/")}` : "";
}
export function jsonValue(text: string, node: JsonNode): string {
const source = text.slice(node.start, node.end);
return node.type === "string" ? JSON.parse(source) as string : source;
}
export function isBinaryValue(value: string, node: JsonNode): boolean {
if (node.type !== "string") return false;
return /^data:[^,]*;base64,/i.test(value) || /^base64:/i.test(value)
|| (value.length > 4096 && /^(?:base64|data|contentBase64|image_data)$/i.test(node.key) && /^[A-Za-z0-9+/=\r\n]+$/.test(value));
}