// JSON 词法、语法与字符串解析交给 jsonc-parser;这里只建立值与执行协议预算。 import { visit } from 'jsonc-parser'; import { once } from 'node:events'; export const MAX_BYTES = 16 * 1024 * 1024; const decoder = new TextDecoder('utf-8', { fatal: true }); export class ProtocolError extends Error {} export function parse(text) { let root; let count = 0; const parents = []; function value(item) { if (++count > 65536 || parents.length > 64) throw new ProtocolError('wire JSON exceeds limit'); const parent = parents.at(-1); if (!parent) root = item; else if (Array.isArray(parent.value)) parent.value.push(item); else Object.defineProperty(parent.value, parent.key, { value: item, enumerable: true, writable: true }); } function container(item) { if (parents.length === 64) throw new ProtocolError('wire JSON exceeds depth limit'); value(item); parents.push({ value: item }); } visit(text, { onObjectBegin: () => container({}), onArrayBegin: () => container([]), onObjectEnd: () => parents.pop(), onArrayEnd: () => parents.pop(), onObjectProperty(key) { const parent = parents.at(-1); if (Object.hasOwn(parent.value, key)) throw new ProtocolError('duplicate JSON field'); parent.key = key; }, onLiteralValue(item, offset, length) { if (typeof item === 'number') { const source = text.slice(offset, offset + length); if (!/[.eE]/.test(source) && !Number.isSafeInteger(item)) item = BigInt(source); else if (/[.eE]/.test(source)) item = JSON.rawJSON(source); } value(item); }, onError: code => { throw new ProtocolError('invalid JSON: ' + code); }, }, { disallowComments: true, allowTrailingComma: false, allowEmptyContent: false }); if (!root || typeof root !== 'object' || Array.isArray(root)) throw new ProtocolError('expected protocol object'); return root; } export function exact(value, names) { if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length !== names.length || names.some(name => !Object.hasOwn(value, name))) { throw new ProtocolError('missing or extra record fields'); } } export class Channel { #input = process.stdin[Symbol.asyncIterator](); #chunk = Buffer.alloc(0); #offset = 0; async #read(size) { const result = Buffer.allocUnsafe(size); let offset = 0; while (offset < size) { if (this.#offset === this.#chunk.length) { const next = await this.#input.next(); if (next.done) throw new ProtocolError('incomplete component frame'); this.#chunk = next.value; this.#offset = 0; } const length = Math.min(size - offset, this.#chunk.length - this.#offset); this.#chunk.copy(result, offset, this.#offset, this.#offset + length); this.#offset += length; offset += length; } return result; } async receive() { const size = (await this.#read(4)).readUInt32BE(); if (size === 0 || size > MAX_BYTES) throw new ProtocolError('component frame exceeds byte limit'); return parse(decoder.decode(await this.#read(size))); } async send(message) { let count = 0; function bounded(value, depth) { if (++count > 65536 || depth > 64) throw new ProtocolError('wire JSON exceeds limit'); if (typeof value === 'number' && !Number.isFinite(value)) throw new ProtocolError('non-finite JSON number'); if (value && typeof value === 'object' && !JSON.isRawJSON(value)) { if (depth === 64) throw new ProtocolError('wire JSON exceeds depth limit'); for (const item of Object.values(value)) bounded(item, depth + 1); } } bounded(message, 0); // 原生 JSON 保留完整 Int,不自写 JSON 编码器。运行时要求 Node 22 以上。 const body = Buffer.from(JSON.stringify(message, (_key, value) => { if (typeof value === 'bigint') return JSON.rawJSON(value.toString()); if (value === undefined || typeof value === 'function' || typeof value === 'symbol') throw new ProtocolError('invalid JSON value'); return value; })); if (body.length > MAX_BYTES) throw new ProtocolError('component frame exceeds byte limit'); const header = Buffer.allocUnsafe(4); header.writeUInt32BE(body.length); if (!process.stdout.write(header)) await once(process.stdout, 'drain'); await new Promise((resolve, reject) => process.stdout.write(body, error => error ? reject(error) : resolve())); } close() { process.stdin.destroy(); } }