fix(mcp): retain complete application results across response limits
Retain complete authenticated application Evidence when the repeated MCP representation exceeds the default receive frame or Node string limit. Return a typed transport constraint, keep useful followup queries available, and stream full canonical bundles to atomic destinations. Verify complete Notion and Obsidian workflows on Linux and native Windows, full CLI/Evidence parity, and real large Chrome screenshot recovery. Preserve complete success contracts and caller-selected evidence paths. Refs #1065, #1053.
This commit is contained in:
@@ -17,13 +17,13 @@ export class AnalysisUnsupportedTargetError extends AnalysisError {
|
||||
}
|
||||
}
|
||||
|
||||
/** Provider reported a resource failure, distinct from malformed input or unsupported coverage. */
|
||||
/** An analysis or transport resource failure, distinct from malformed input or unsupported coverage. */
|
||||
export class AnalysisResourceConstraintError extends AnalysisError {
|
||||
readonly _tag = "AnalysisResourceConstraintError";
|
||||
|
||||
constructor(
|
||||
readonly operation: string,
|
||||
readonly resource: "memory" | "cpu" | "file-size",
|
||||
readonly resource: "memory" | "cpu" | "file-size" | "transport",
|
||||
readonly reason: string,
|
||||
readonly reportedLimits: Readonly<Record<string, JsonValue>> | null,
|
||||
options?: AnalysisErrorOptions,
|
||||
|
||||
@@ -37,11 +37,13 @@ export const analysisErrorRemediationAction = (
|
||||
if (error instanceof AnalysisUnsupportedTargetError)
|
||||
return "Select a target supported by this operation or choose an operation supporting the reported target format.";
|
||||
if (error instanceof AnalysisResourceConstraintError)
|
||||
return error.resource === "cpu"
|
||||
? "Review the reported worker CPU limits and observed signal. Retry with sufficient CPU time or a smaller artifact; REA retains tighter inherited limits."
|
||||
: error.resource === "file-size"
|
||||
? "Review the reported worker file-size limits and write failure. Retry with a sufficient file-size allowance for the evidence reply; REA retains tighter inherited limits."
|
||||
: "Review the reported worker memory limits and available host memory. Retry with sufficient memory or a smaller artifact; REA retains tighter inherited limits.";
|
||||
return error.resource === "transport"
|
||||
? "Use the reported Evidence reference with a focused analysis tool when retained in this session, or export the session through export_evidence_bundle to a caller-selected path. Complete CLI JSON output is also available. The connection remains usable."
|
||||
: error.resource === "cpu"
|
||||
? "Review the reported worker CPU limits and observed signal. Retry with sufficient CPU time or a smaller artifact; REA retains tighter inherited limits."
|
||||
: error.resource === "file-size"
|
||||
? "Review the reported worker file-size limits and write failure. Retry with a sufficient file-size allowance for the evidence reply; REA retains tighter inherited limits."
|
||||
: "Review the reported worker memory limits and available host memory. Retry with sufficient memory or a smaller artifact; REA retains tighter inherited limits.";
|
||||
if (error instanceof HopperTimeoutError)
|
||||
return error.providerState === "busy"
|
||||
? "Check binary_session.analysis_activity, wait for the active Hopper request to finish, then retry."
|
||||
|
||||
@@ -62,6 +62,7 @@ it.each([
|
||||
["cpu", { cpu_seconds: 1 }],
|
||||
["file-size", null],
|
||||
["file-size", { file_size_bytes: 1024 }],
|
||||
["transport", { result_budget_bytes: 10485760 }],
|
||||
] as const)(
|
||||
"projects reported %s constraints with observed or unknown limits: %j",
|
||||
(resource, limits) => {
|
||||
@@ -89,9 +90,11 @@ it.each([
|
||||
expect(projected.remediation.action).toContain(
|
||||
resource === "cpu"
|
||||
? "CPU"
|
||||
: resource === "file-size"
|
||||
? "file-size"
|
||||
: "memory",
|
||||
: resource === "transport"
|
||||
? "Evidence reference"
|
||||
: resource === "file-size"
|
||||
? "file-size"
|
||||
: "memory",
|
||||
);
|
||||
expect(projected.remediation.action).not.toContain("doctor");
|
||||
expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(
|
||||
|
||||
@@ -3,9 +3,15 @@ import { describe, expect } from "vitest";
|
||||
|
||||
import { createAnalysisProfile } from "./analysisProfile.js";
|
||||
import type { BinaryTarget } from "./binaryTarget.js";
|
||||
import { createEvidence, evidenceSchema, parseEvidence } from "./evidence.js";
|
||||
import { MAX_JSON_DEPTH } from "./jsonValue.js";
|
||||
import {
|
||||
createEvidence,
|
||||
evidenceRecordSchema,
|
||||
evidenceSchema,
|
||||
parseEvidence,
|
||||
} from "./evidence.js";
|
||||
import { MAX_JSON_DEPTH, type JsonValue } from "./jsonValue.js";
|
||||
import { createEvidenceBundle } from "./evidenceBundle.js";
|
||||
import { freezeJsonSnapshot } from "./immutableJson.js";
|
||||
|
||||
const TARGET: BinaryTarget = {
|
||||
path: "/tmp/fixture",
|
||||
@@ -18,6 +24,90 @@ const TARGET: BinaryTarget = {
|
||||
const PROVIDER = { id: "fixture", name: "Fixture provider", version: "1" };
|
||||
const PROFILE = createAnalysisProfile(PROVIDER, { loader: "default" });
|
||||
|
||||
it("preserves identity and bytes when reusing an owned immutable result", () => {
|
||||
const value = { nested: { values: ["observed", 1] } };
|
||||
const mutable = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "inspect",
|
||||
parameters: {},
|
||||
result: value,
|
||||
});
|
||||
const frozen = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "inspect",
|
||||
parameters: {},
|
||||
result: freezeJsonSnapshot(value),
|
||||
});
|
||||
expect(JSON.stringify(frozen)).toBe(JSON.stringify(mutable));
|
||||
expect(frozen.normalized_result).toBe(value);
|
||||
expect(Object.isFrozen(frozen)).toBe(true);
|
||||
expect(parseEvidence(frozen)).toEqual(mutable);
|
||||
const wire: unknown = JSON.parse(JSON.stringify(frozen));
|
||||
expect(parseEvidence(wire)).toEqual(mutable);
|
||||
expect(() =>
|
||||
parseEvidence({ ...frozen, normalized_result: { changed: true } }),
|
||||
).toThrow("semantic identifier");
|
||||
});
|
||||
|
||||
it("applies the JSON depth boundary to owned immutable results", () => {
|
||||
let result: JsonValue = 1;
|
||||
for (let index = 0; index <= MAX_JSON_DEPTH; index += 1)
|
||||
result = { nested: result };
|
||||
const observe = () =>
|
||||
createEvidence(TARGET, PROVIDER, {
|
||||
operation: "inspect",
|
||||
parameters: {},
|
||||
result,
|
||||
});
|
||||
expect(observe).toThrow("maximum nesting depth");
|
||||
freezeJsonSnapshot(result);
|
||||
expect(observe).toThrow("maximum nesting depth");
|
||||
});
|
||||
|
||||
it("preserves prototype-named own members when reusing an owned result", () => {
|
||||
const result = { ["__proto__"]: { preserved: 7 }, constructor: "ordinary" };
|
||||
const observation = { operation: "inspect", parameters: {}, result };
|
||||
const ordinary = createEvidence(TARGET, PROVIDER, observation);
|
||||
const owned = createEvidence(TARGET, PROVIDER, {
|
||||
...observation,
|
||||
result: freezeJsonSnapshot(result),
|
||||
});
|
||||
expect(owned.normalized_result).toBe(result);
|
||||
expect(owned).toEqual(ordinary);
|
||||
expect(parseEvidence(JSON.parse(JSON.stringify(owned)))).toEqual(owned);
|
||||
expect(Object.getPrototypeOf(owned.normalized_result)).toBe(Object.prototype);
|
||||
expect(Reflect.get(Object.prototype, "preserved")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("preserves producer envelope admission and profile validation", () => {
|
||||
const legacy = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "inspect",
|
||||
parameters: {},
|
||||
result: { observed: [1, 2, 3] },
|
||||
});
|
||||
const profiled = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "inspect",
|
||||
parameters: {},
|
||||
result: { observed: [1, 2, 3] },
|
||||
analysisProfile: PROFILE,
|
||||
});
|
||||
const candidates: unknown[] = [
|
||||
legacy,
|
||||
profiled,
|
||||
{ ...legacy, analysis_profile: undefined },
|
||||
{ ...legacy, analysis_profile: null },
|
||||
{
|
||||
...profiled,
|
||||
analysis_profile: { ...PROFILE, provider: { ...PROVIDER, id: "other" } },
|
||||
},
|
||||
{ ...legacy, unexpected: true },
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
const canonical = evidenceRecordSchema.safeParse(candidate);
|
||||
if (canonical.success)
|
||||
expect(parseEvidence(candidate)).toEqual(canonical.data);
|
||||
else expect(() => parseEvidence(candidate)).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it("snapshots caller-owned payloads before deriving their identity", () => {
|
||||
const result = { nested: { values: ["observed"] } };
|
||||
const rawResult = { entries: [{ value: "raw" }] };
|
||||
|
||||
+50
-3
@@ -10,8 +10,13 @@ import type { BinaryTarget } from "./binaryTarget.js";
|
||||
import {
|
||||
jsonObjectSchema,
|
||||
jsonValueSchema,
|
||||
jsonValueValidationIssue,
|
||||
type JsonValue,
|
||||
} from "./jsonValue.js";
|
||||
import {
|
||||
freezeJsonSnapshot,
|
||||
isImmutableJsonSnapshot,
|
||||
} from "./immutableJson.js";
|
||||
import { digestSchema } from "./../domain/digests.js";
|
||||
import { prefixedDigestSchema } from "./../domain/digests.js";
|
||||
|
||||
@@ -144,6 +149,14 @@ export const evidenceRecordSchema = z.union([
|
||||
]);
|
||||
|
||||
export type Evidence = z.infer<typeof evidenceRecordSchema>;
|
||||
const immutableEvidenceSnapshots = new WeakMap<object, Evidence>();
|
||||
const immutableResultSchema = z
|
||||
.custom<JsonValue>(isImmutableJsonSnapshot)
|
||||
.superRefine((value, context) => {
|
||||
const issue = jsonValueValidationIssue(value);
|
||||
if (issue !== undefined)
|
||||
context.addIssue({ code: "custom", message: issue });
|
||||
});
|
||||
export type EvidenceLocation = z.infer<typeof evidenceLocationSchema>;
|
||||
|
||||
/** Minimal immutable local artifact identity accepted by Evidence. */
|
||||
@@ -216,7 +229,19 @@ const computeEvidenceId = (evidence: EvidenceWithoutId): string =>
|
||||
|
||||
/** Parse evidence and reject a syntactically valid but tampered semantic ID. */
|
||||
export const parseEvidence = (input: unknown): Evidence => {
|
||||
const evidence = evidenceRecordSchema.parse(input);
|
||||
const immutable =
|
||||
typeof input === "object" && input !== null
|
||||
? immutableEvidenceSnapshots.get(input)
|
||||
: undefined;
|
||||
if (immutable !== undefined) return immutable;
|
||||
// Select the producer's envelope before traversing its payload. A legacy
|
||||
// record cannot satisfy the required-profile branch, whose failed parse
|
||||
// would otherwise clone the entire normalized result before trying legacy.
|
||||
const schema =
|
||||
typeof input === "object" && input !== null && "analysis_profile" in input
|
||||
? profiledEvidenceSchema
|
||||
: evidenceBaseSchema;
|
||||
const evidence = schema.parse(input);
|
||||
const { evidence_id: evidenceId, ...withoutId } = evidence;
|
||||
if (computeEvidenceId(withoutId) !== evidenceId)
|
||||
throw new TypeError(
|
||||
@@ -225,6 +250,20 @@ export const parseEvidence = (input: unknown): Evidence => {
|
||||
return evidence;
|
||||
};
|
||||
|
||||
/** Authenticate and seal a ledger-owned snapshot; external mutable values are copied first. */
|
||||
export const immutableEvidence = (input: unknown): Evidence =>
|
||||
rememberImmutableEvidence(parseEvidence(input));
|
||||
|
||||
/** Recognize authenticated Evidence whose complete reachable JSON data is immutable. */
|
||||
export const isImmutableEvidence = (evidence: Evidence): boolean =>
|
||||
immutableEvidenceSnapshots.has(evidence);
|
||||
|
||||
const rememberImmutableEvidence = (evidence: Evidence): Evidence => {
|
||||
freezeJsonSnapshot(evidence);
|
||||
immutableEvidenceSnapshots.set(evidence, evidence);
|
||||
return evidence;
|
||||
};
|
||||
|
||||
/** Build deterministic Evidence from an immutable artifact subject. */
|
||||
export const createEvidence = (
|
||||
target: EvidenceSubjectTarget | BinaryTarget | undefined,
|
||||
@@ -285,7 +324,14 @@ export const createEvidence = (
|
||||
observation.analysisProfile === undefined
|
||||
? evidenceBaseSchema
|
||||
: profiledEvidenceSchema;
|
||||
const normalized = schema.parse({
|
||||
const sharedResult =
|
||||
typeof observation.result === "object" &&
|
||||
observation.result !== null &&
|
||||
isImmutableJsonSnapshot(observation.result);
|
||||
const selectedSchema = sharedResult
|
||||
? schema.safeExtend({ normalized_result: immutableResultSchema })
|
||||
: schema;
|
||||
const normalized = selectedSchema.parse({
|
||||
...semantic,
|
||||
evidence_id: `ev_${"0".repeat(64)}`,
|
||||
subject,
|
||||
@@ -293,8 +339,9 @@ export const createEvidence = (
|
||||
// The envelope has already been parsed into an independent snapshot. Only
|
||||
// its derived identifier changes here; parsing again clones the full payload
|
||||
// and recomputes the same digest while the previous snapshot is still live.
|
||||
return {
|
||||
const evidence = {
|
||||
...normalized,
|
||||
evidence_id: computeEvidenceId(normalized),
|
||||
};
|
||||
return sharedResult ? rememberImmutableEvidence(evidence) : evidence;
|
||||
};
|
||||
|
||||
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { createEvidence } from "./evidence.js";
|
||||
import {
|
||||
createEvidenceBundle,
|
||||
createImmutableEvidenceBundle,
|
||||
evidenceBundleForTarget,
|
||||
parseEvidenceBundle,
|
||||
} from "./evidenceBundle.js";
|
||||
@@ -118,3 +119,26 @@ describe("evidenceBundleForTarget", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("immutable serialization bundles", () => {
|
||||
it("authenticates sealed records while revalidating detached and malformed input", () => {
|
||||
const evidence = createEvidence(undefined, provider, {
|
||||
operation: "health",
|
||||
parameters: {},
|
||||
result: { nested: [true] },
|
||||
});
|
||||
const bundle = createImmutableEvidenceBundle([evidence]);
|
||||
expect(parseEvidenceBundle(bundle)).toBe(bundle);
|
||||
expect(Object.isFrozen(bundle.records[0]?.normalized_result)).toBe(true);
|
||||
const detached: unknown = JSON.parse(JSON.stringify(bundle));
|
||||
expect(parseEvidenceBundle(detached)).toEqual(bundle);
|
||||
expect(parseEvidenceBundle(detached)).not.toBe(bundle);
|
||||
const tampered = {
|
||||
...bundle,
|
||||
records: [{ ...evidence, normalized_result: false }],
|
||||
};
|
||||
expect(() => parseEvidenceBundle(Object.freeze(tampered))).toThrow();
|
||||
expect(() => createImmutableEvidenceBundle(tampered.records)).toThrow();
|
||||
expect(() => createImmutableEvidenceBundle([evidence, evidence])).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,6 +4,7 @@ import canonicalize from "canonicalize";
|
||||
import {
|
||||
evidenceEnvelopeSchema,
|
||||
evidenceRecordSchema,
|
||||
immutableEvidence,
|
||||
parseEvidence,
|
||||
providerSchema,
|
||||
type Evidence,
|
||||
@@ -12,6 +13,7 @@ import {
|
||||
residualUnknownSchema,
|
||||
type ResidualUnknown,
|
||||
} from "./residualUnknown.js";
|
||||
import { freezeJsonSnapshot } from "./immutableJson.js";
|
||||
|
||||
const artifactManifestSchema = evidenceEnvelopeSchema.shape.subject
|
||||
.unwrap()
|
||||
@@ -44,6 +46,29 @@ export const evidenceBundleSchema = z.object({
|
||||
});
|
||||
|
||||
export type EvidenceBundle = z.infer<typeof evidenceBundleSchema>;
|
||||
const immutableBundles = new WeakMap<object, EvidenceBundle>();
|
||||
|
||||
/** Build and authenticate a sealed bundle while reusing immutable Evidence records. */
|
||||
export const createImmutableEvidenceBundle = (
|
||||
records: readonly Evidence[],
|
||||
unknowns: readonly ResidualUnknown[] = [],
|
||||
): EvidenceBundle => {
|
||||
const checkedRecords = records.map(immutableEvidence);
|
||||
if (
|
||||
new Set(checkedRecords.map(({ evidence_id }) => evidence_id)).size !==
|
||||
checkedRecords.length
|
||||
)
|
||||
throw new TypeError("Evidence bundle contains duplicate record IDs");
|
||||
const checkedUnknowns = unknowns.map((unknown) =>
|
||||
residualUnknownSchema.parse(unknown),
|
||||
);
|
||||
validateUnknownGraph(checkedUnknowns, checkedRecords);
|
||||
const bundle = freezeJsonSnapshot(
|
||||
createEvidenceBundle(checkedRecords, checkedUnknowns),
|
||||
);
|
||||
immutableBundles.set(bundle, bundle);
|
||||
return bundle;
|
||||
};
|
||||
|
||||
/** Project records into a deterministic bundle whose order has no semantics. */
|
||||
export const createEvidenceBundle = (
|
||||
@@ -212,6 +237,10 @@ export const describeValidationFailure = (cause: unknown): string => {
|
||||
|
||||
/** Parse records, verify semantic IDs, and reject inconsistent manifests. */
|
||||
export const parseEvidenceBundle = (input: unknown): EvidenceBundle => {
|
||||
if (typeof input === "object" && input !== null) {
|
||||
const owned = immutableBundles.get(input);
|
||||
if (owned !== undefined) return owned;
|
||||
}
|
||||
const parsed = evidenceBundleSchema.parse(input);
|
||||
const recordIds = parsed.records.map(({ evidence_id: id }) => id);
|
||||
if (new Set(recordIds).size !== recordIds.length)
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
import {
|
||||
freezeJsonSnapshot,
|
||||
isImmutableJsonSnapshot,
|
||||
} from "./immutableJson.js";
|
||||
|
||||
describe("owned immutable JSON snapshots", () => {
|
||||
it("seals reachable data and preserves repeated references", () => {
|
||||
const shared = { values: [1, "observed"] };
|
||||
const value = { left: shared, right: shared };
|
||||
const encoded = JSON.stringify(value);
|
||||
expect(freezeJsonSnapshot(value)).toBe(value);
|
||||
expect(value.left).toBe(value.right);
|
||||
expect(Object.isFrozen(value)).toBe(true);
|
||||
expect(Object.isFrozen(shared.values)).toBe(true);
|
||||
expect(Reflect.set(shared.values, 0, 9)).toBe(false);
|
||||
expect(JSON.stringify(value)).toBe(encoded);
|
||||
expect(isImmutableJsonSnapshot(value)).toBe(true);
|
||||
});
|
||||
|
||||
it("does not mistake a shallow freeze for validated immutable data", () => {
|
||||
const value = Object.freeze({ nested: { value: 1 } });
|
||||
expect(isImmutableJsonSnapshot(value)).toBe(false);
|
||||
freezeJsonSnapshot(value);
|
||||
expect(Object.isFrozen(value.nested)).toBe(true);
|
||||
expect(isImmutableJsonSnapshot(value)).toBe(true);
|
||||
});
|
||||
|
||||
it("composes sealed roots without changing the nested data or authenticating a shallow freeze", () => {
|
||||
const nested = freezeJsonSnapshot({ values: [1, "observed"] });
|
||||
const outer = freezeJsonSnapshot({ nested });
|
||||
expect(outer.nested).toBe(nested);
|
||||
expect(Object.isFrozen(outer)).toBe(true);
|
||||
expect(Object.isFrozen(nested.values)).toBe(true);
|
||||
expect(isImmutableJsonSnapshot(outer)).toBe(true);
|
||||
expect(isImmutableJsonSnapshot(nested)).toBe(true);
|
||||
const unowned = Object.freeze({ nested: { value: 1 } });
|
||||
expect(isImmutableJsonSnapshot(unowned)).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects cycles without registering or partially freezing the snapshot", () => {
|
||||
const value: Record<string, JsonValue> = {};
|
||||
value.self = value;
|
||||
expect(() => freezeJsonSnapshot(value)).toThrow("circular");
|
||||
expect(isImmutableJsonSnapshot(value)).toBe(false);
|
||||
expect(Object.isFrozen(value)).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects mutable accessor behavior and sparse arrays", () => {
|
||||
const accessor = {
|
||||
get value() {
|
||||
return 1;
|
||||
},
|
||||
};
|
||||
expect(() => freezeJsonSnapshot(accessor)).toThrow("accessors");
|
||||
expect(isImmutableJsonSnapshot(accessor)).toBe(false);
|
||||
expect(() => freezeJsonSnapshot(new Array<number>(2))).toThrow("sparse");
|
||||
expect(() => freezeJsonSnapshot({ number: Number.NaN })).toThrow(
|
||||
"JSON values",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
|
||||
const immutableSnapshots = new WeakSet<object>();
|
||||
|
||||
/** Recognize an owned JSON snapshot sealed by this module, or an immutable scalar. */
|
||||
export const isImmutableJsonSnapshot = (value: unknown): value is JsonValue =>
|
||||
value === null ||
|
||||
typeof value === "string" ||
|
||||
typeof value === "boolean" ||
|
||||
(typeof value === "number" && Number.isFinite(value)) ||
|
||||
(typeof value === "object" && immutableSnapshots.has(value));
|
||||
|
||||
/** Seal an already parsed, owned JSON snapshot for immutable zero-copy reuse. */
|
||||
export const freezeJsonSnapshot = <T extends JsonValue>(value: T): T => {
|
||||
const pending: { value: unknown; exiting: boolean }[] = [
|
||||
{ value, exiting: false },
|
||||
];
|
||||
// These sets exist only during traversal, while the owned root already
|
||||
// retains every child. Strong sets avoid per-node ephemeron GC work.
|
||||
const visited = new Set<object>();
|
||||
const ancestors = new Set<object>();
|
||||
const objects: object[] = [];
|
||||
while (pending.length > 0) {
|
||||
const entry = pending.pop();
|
||||
if (entry === undefined) break;
|
||||
const item = entry.value;
|
||||
if (entry.exiting && typeof item === "object" && item !== null) {
|
||||
ancestors.delete(item);
|
||||
visited.add(item);
|
||||
objects.push(item);
|
||||
continue;
|
||||
}
|
||||
if (isImmutableJsonSnapshot(item)) continue;
|
||||
if (typeof item !== "object" || item === null)
|
||||
throw new TypeError("Immutable JSON snapshots require JSON values");
|
||||
const prototype: unknown = Object.getPrototypeOf(item);
|
||||
if (
|
||||
!Array.isArray(item) &&
|
||||
prototype !== Object.prototype &&
|
||||
prototype !== null
|
||||
)
|
||||
throw new TypeError("Immutable JSON snapshots require ordinary objects");
|
||||
if (ancestors.has(item))
|
||||
throw new TypeError(
|
||||
"Immutable JSON snapshots cannot contain circular references",
|
||||
);
|
||||
if (visited.has(item)) continue;
|
||||
ancestors.add(item);
|
||||
pending.push({ value: item, exiting: true });
|
||||
if (Array.isArray(item))
|
||||
for (let index = 0; index < item.length; index += 1)
|
||||
if (!Object.hasOwn(item, index))
|
||||
throw new TypeError(
|
||||
"Immutable JSON snapshots cannot contain sparse arrays",
|
||||
);
|
||||
for (const key of Object.getOwnPropertyNames(item)) {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(item, key);
|
||||
if (descriptor === undefined || !Object.hasOwn(descriptor, "value"))
|
||||
throw new TypeError(
|
||||
"Immutable JSON snapshots cannot contain accessors",
|
||||
);
|
||||
const child: unknown = descriptor.value;
|
||||
pending.push({ value: child, exiting: false });
|
||||
}
|
||||
}
|
||||
// Register only after every value is checked and every object is frozen.
|
||||
// An arbitrary Object.freeze call cannot forge this snapshot identity.
|
||||
for (const item of objects) Object.freeze(item);
|
||||
// Register the requested root, rather than retaining weak entries for every
|
||||
// nested object. Sealing an Evidence or bundle skips previously sealed roots.
|
||||
if (typeof value === "object" && value !== null)
|
||||
immutableSnapshots.add(value);
|
||||
return value;
|
||||
};
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
import {
|
||||
bufferedJsonParts,
|
||||
canonicalJsonParts,
|
||||
jsonParts,
|
||||
} from "./jsonSerialization.js";
|
||||
|
||||
describe("streamed JSON representation", () => {
|
||||
it.each([
|
||||
null,
|
||||
true,
|
||||
-0,
|
||||
[1, false, null, 'quotes: " / slash: \\ / newline: \n'],
|
||||
{ nested: { value: "中文 😀 \ud800" }, items: [1, 2] },
|
||||
JSON.parse('{"__proto__":{"value":1},"constructor":2,"10":3,"2":4}'),
|
||||
])("matches native JSON for ordinary values: %j", (value: unknown) => {
|
||||
expect([...bufferedJsonParts(jsonParts(value))].join("")).toBe(
|
||||
JSON.stringify(value),
|
||||
);
|
||||
expect([...jsonParts(value, true)].join("")).toBe(
|
||||
JSON.stringify(value, null, 2),
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves surrogate pairs across string and buffer boundaries", () => {
|
||||
const value = { text: `${"x".repeat(8190)}😀${'中文\n"'.repeat(20000)}` };
|
||||
const parts = [...bufferedJsonParts(jsonParts(value))];
|
||||
expect(
|
||||
Buffer.concat(parts.map((part) => Buffer.from(part))).toString(),
|
||||
).toBe(JSON.stringify(value));
|
||||
expect(JSON.parse(parts.join(""))).toEqual(value);
|
||||
});
|
||||
|
||||
it("rejects a cycle while allowing repeated references", () => {
|
||||
const shared = { value: 1 };
|
||||
expect([...jsonParts({ left: shared, right: shared })].join("")).toBe(
|
||||
JSON.stringify({ left: shared, right: shared }),
|
||||
);
|
||||
const cycle: { self?: unknown } = {};
|
||||
cycle.self = cycle;
|
||||
expect(() => [...jsonParts(cycle)]).toThrow("circular reference");
|
||||
});
|
||||
|
||||
it("matches existing canonical bytes for numeric keys, Unicode, and shared values", () => {
|
||||
const shared = { z: -0, a: [1e-7, 1e30, "雪😀\ud800"] };
|
||||
const ownKeys: unknown = JSON.parse(
|
||||
'{"__proto__":1,"constructor":2,"10":3,"2":4}',
|
||||
);
|
||||
const value = {
|
||||
z: shared,
|
||||
a: shared,
|
||||
keys: ownKeys,
|
||||
long: '雪😀"'.repeat(20000),
|
||||
};
|
||||
expect([...bufferedJsonParts(canonicalJsonParts(value))].join("")).toBe(
|
||||
canonicalize(value),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
/** Encode ordinary JSON as bounded string parts without a document-sized allocation. */
|
||||
export function* jsonParts(value: unknown, pretty = false): Generator<string> {
|
||||
yield* encodeValue(value, pretty, 0, new Set(), false);
|
||||
}
|
||||
|
||||
/** Encode validated JSON with canonical key ordering without allocating the whole document. */
|
||||
export function* canonicalJsonParts(value: unknown): Generator<string> {
|
||||
yield* encodeValue(value, false, 0, new Set(), true);
|
||||
}
|
||||
|
||||
/** Buffer JSON parts while preserving complete UTF-16 surrogate pairs. */
|
||||
export function* bufferedJsonParts(parts: Iterable<string>): Generator<string> {
|
||||
let buffer = "";
|
||||
for (const part of parts) {
|
||||
if (buffer.length + part.length > 64 * 1024 && buffer !== "") {
|
||||
yield buffer;
|
||||
buffer = "";
|
||||
}
|
||||
buffer += part;
|
||||
}
|
||||
if (buffer !== "") yield buffer;
|
||||
}
|
||||
|
||||
function* encodeString(value: string): Generator<string> {
|
||||
if (value.length <= 8192) {
|
||||
yield JSON.stringify(value);
|
||||
return;
|
||||
}
|
||||
yield '"';
|
||||
for (let start = 0; start < value.length;) {
|
||||
let end = Math.min(start + 8192, value.length);
|
||||
const last = value.charCodeAt(end - 1);
|
||||
const next = value.charCodeAt(end);
|
||||
// Keep a surrogate pair in the same JSON.stringify and UTF-8 write.
|
||||
if (
|
||||
end < value.length &&
|
||||
last >= 0xd800 &&
|
||||
last <= 0xdbff &&
|
||||
next >= 0xdc00 &&
|
||||
next <= 0xdfff
|
||||
)
|
||||
end -= 1;
|
||||
yield JSON.stringify(value.slice(start, end)).slice(1, -1);
|
||||
start = end;
|
||||
}
|
||||
yield '"';
|
||||
}
|
||||
|
||||
function* encodeValue(
|
||||
value: unknown,
|
||||
pretty: boolean,
|
||||
depth: number,
|
||||
ancestors: Set<object>,
|
||||
canonical: boolean,
|
||||
): Generator<string> {
|
||||
if (typeof value === "string") {
|
||||
yield* encodeString(value);
|
||||
return;
|
||||
}
|
||||
if (value === null || typeof value === "boolean") {
|
||||
yield value === null ? "null" : String(value);
|
||||
return;
|
||||
}
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
yield String(value);
|
||||
return;
|
||||
}
|
||||
if (typeof value !== "object" || value === null)
|
||||
throw new TypeError("JSON output requires ordinary JSON values");
|
||||
if (ancestors.has(value))
|
||||
throw new TypeError("JSON output contains a circular reference");
|
||||
if (
|
||||
!Array.isArray(value) &&
|
||||
Object.prototype.toString.call(value) !== "[object Object]"
|
||||
)
|
||||
throw new TypeError("JSON output requires ordinary JSON objects");
|
||||
ancestors.add(value);
|
||||
try {
|
||||
const array = Array.isArray(value);
|
||||
const keys = array ? undefined : Object.keys(value);
|
||||
if (canonical) keys?.sort();
|
||||
const count = array ? value.length : (keys?.length ?? 0);
|
||||
let written = 0;
|
||||
yield array ? "[" : "{";
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
let item: unknown;
|
||||
let key: string | undefined;
|
||||
if (array) {
|
||||
item = value[index];
|
||||
} else {
|
||||
key = keys?.[index];
|
||||
if (key === undefined)
|
||||
throw new TypeError("JSON object changed during serialization");
|
||||
item = Reflect.get(value, key);
|
||||
// Incur's filter can select inherited methods. Match native JSON's
|
||||
// omission without eagerly reading the rest of a bounded result.
|
||||
if (
|
||||
item === undefined ||
|
||||
typeof item === "function" ||
|
||||
typeof item === "symbol"
|
||||
)
|
||||
continue;
|
||||
}
|
||||
if (written > 0) yield ",";
|
||||
if (pretty) yield `\n${" ".repeat(depth + 1)}`;
|
||||
if (key !== undefined) {
|
||||
yield* encodeString(key);
|
||||
yield pretty ? ": " : ":";
|
||||
}
|
||||
yield* encodeValue(item, pretty, depth + 1, ancestors, canonical);
|
||||
written += 1;
|
||||
}
|
||||
if (pretty && written > 0) yield `\n${" ".repeat(depth)}`;
|
||||
yield array ? "]" : "}";
|
||||
} finally {
|
||||
ancestors.delete(value);
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,8 @@ const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
const recordShape = z.record(z.string(), z.unknown());
|
||||
|
||||
const jsonValidationIssue = (root: unknown): string | undefined => {
|
||||
/** Validate JSON meaning and nesting without cloning a trusted immutable value. */
|
||||
export const jsonValueValidationIssue = (root: unknown): string | undefined => {
|
||||
const pending: { value: unknown; depth: number }[] = [
|
||||
{ value: root, depth: 0 },
|
||||
];
|
||||
@@ -59,9 +60,10 @@ const preserveJsonValue = (value: JsonValue): JsonValue => {
|
||||
};
|
||||
|
||||
const validatedJsonValue = z.custom<JsonValue>(
|
||||
(value) => jsonValidationIssue(value) === undefined,
|
||||
(value) => jsonValueValidationIssue(value) === undefined,
|
||||
{
|
||||
error: (issue) => jsonValidationIssue(issue.input) ?? "Invalid JSON value",
|
||||
error: (issue) =>
|
||||
jsonValueValidationIssue(issue.input) ?? "Invalid JSON value",
|
||||
},
|
||||
);
|
||||
// Keep both stages nonrecursive in public and Standard Schema projections.
|
||||
|
||||
Reference in New Issue
Block a user