- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/server/src/json-chunk-cursor.ts?format=json
86 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 167, 2 versions changed it
1/** Incremental UTF-16 cursor over canonical log chunks. */
2export class JsonChunkCursor {
3 readonly #input: Iterator<string>;
4 #chunk = "";
5 #offset = 0;
6 constructor(chunks: Iterable<string>) {
7 this.#input = chunks[Symbol.iterator]();
8 }
9 peek(): string | undefined {
10 while (this.#offset === this.#chunk.length) {
11 const next = this.#input.next();
12 if (next.done) return undefined;
13 if (typeof next.value !== "string" || next.value.length > 600000) throw Error("invalid JSON input chunk");
14 this.#chunk = next.value;
15 this.#offset = 0;
16 }
17 return this.#chunk[this.#offset];
18 }
19 take(): string {
20 const char = this.peek();
21 if (char === undefined) throw Error("truncated JSON input");
22 this.#offset++;
23 return char;
24 }
25 /** Consume one quoted JSON string, yielding bounded decoded text. */
26 *stringChunks(): IterableIterator<string> {
27 if (this.take() !== '"') throw Error("expected JSON string");
28 let buffer = "";
29 for (;;) {
30 // Copy ordinary text in bounded slices instead of allocating a string
31 // concatenation for every character of a large canonical field.
32 this.peek();
33 const start = this.#offset;
34 const end = Math.min(this.#chunk.length, start + 16384 - buffer.length);
35 while (this.#offset < end) {
36 const code = this.#chunk.charCodeAt(this.#offset);
37 if (code < 32 || code === 34 || code === 92) break;
38 this.#offset++;
39 }
40 if (this.#offset > start) {
41 buffer += this.#chunk.slice(start, this.#offset);
42 if (buffer.length === 16384) {
43 yield buffer;
44 buffer = "";
45 }
46 continue;
47 }
48 let char = this.take();
49 if (char === '"') {
50 if (buffer) yield buffer;
51 return;
52 }
53 if (char.charCodeAt(0) < 32) throw Error("unescaped JSON control character");
54 if (char === "\\") {
55 const escape = this.take();
56 const simple: Record<string, string> = {
57 '"': '"',
58 "\\": "\\",
59 "/": "/",
60 b: "\b",
61 f: "\f",
62 n: "\n",
63 r: "\r",
64 t: "\t",
65 };
66 if (escape === "u") {
67 let hex = "";
68 for (let i = 0; i < 4; i++) hex += this.take();
69 if (!/^[0-9a-fA-F]{4}$/.test(hex)) throw Error("invalid JSON Unicode escape");
70 char = String.fromCharCode(Number.parseInt(hex, 16));
71 } else {
72 if (!Object.hasOwn(simple, escape)) throw Error("invalid JSON escape");
73 char = simple[escape]!;
74 }
75 }
76 buffer += char;
77 if (buffer.length === 16384) {
78 yield buffer;
79 buffer = "";
80 }
81 }
82 }
83 close(): void {
84 this.#input.return?.();
85 }
86}