@silverprotocol/core 0.6.6 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +54 -6
- package/dist/agjson.d.ts +29 -8
- package/dist/agjson.d.ts.map +1 -1
- package/dist/agjson.js +28 -7
- package/dist/agjson.js.map +1 -1
- package/dist/atomic-push.d.ts +51 -0
- package/dist/atomic-push.d.ts.map +1 -0
- package/dist/atomic-push.js +188 -0
- package/dist/atomic-push.js.map +1 -0
- package/dist/copy-json.d.ts +12 -0
- package/dist/copy-json.d.ts.map +1 -0
- package/dist/copy-json.js +21 -0
- package/dist/copy-json.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +41 -5
- package/dist/ingest.d.ts.map +1 -1
- package/dist/ingest.js +53 -30
- package/dist/ingest.js.map +1 -1
- package/dist/input-check.d.ts +51 -0
- package/dist/input-check.d.ts.map +1 -0
- package/dist/input-check.js +113 -0
- package/dist/input-check.js.map +1 -0
- package/dist/record.d.ts +68 -0
- package/dist/record.d.ts.map +1 -0
- package/dist/record.js +112 -0
- package/dist/record.js.map +1 -0
- package/dist/reduce.d.ts +0 -14
- package/dist/reduce.d.ts.map +1 -1
- package/dist/reduce.js +270 -68
- package/dist/reduce.js.map +1 -1
- package/dist/stream-assembler.d.ts +47 -4
- package/dist/stream-assembler.d.ts.map +1 -1
- package/dist/stream-assembler.js +55 -4
- package/dist/stream-assembler.js.map +1 -1
- package/dist/wire.d.ts +96 -0
- package/dist/wire.d.ts.map +1 -1
- package/dist/wire.js +309 -0
- package/dist/wire.js.map +1 -1
- package/package.json +1 -1
- package/src/agjson.ts +33 -10
- package/src/atomic-push.ts +217 -0
- package/src/copy-json.ts +27 -0
- package/src/index.ts +3 -0
- package/src/ingest.ts +71 -26
- package/src/input-check.ts +124 -0
- package/src/record.ts +132 -0
- package/src/reduce.ts +234 -56
- package/src/stream-assembler.ts +74 -8
- package/src/wire.ts +303 -0
package/src/stream-assembler.ts
CHANGED
|
@@ -104,6 +104,19 @@ const RESERVED_EXT_KEYS = new Set<string>([
|
|
|
104
104
|
"_meta",
|
|
105
105
|
]);
|
|
106
106
|
|
|
107
|
+
/** An opaque {@link StreamAssembler.checkpoint} value: restore it with {@link StreamAssembler.rollback}. */
|
|
108
|
+
export interface AssemblerCheckpoint {
|
|
109
|
+
readonly seq: number;
|
|
110
|
+
readonly seenTurns: ReadonlySet<string>;
|
|
111
|
+
readonly openTurns: ReadonlySet<string>;
|
|
112
|
+
readonly openMessages: ReadonlyMap<string, { turnId: string }>;
|
|
113
|
+
readonly msgTurn: ReadonlyMap<string, string>;
|
|
114
|
+
readonly lastTurn: string | undefined;
|
|
115
|
+
readonly turnStack: readonly (string | undefined)[];
|
|
116
|
+
readonly cumulative: ReadonlyMap<string, string>;
|
|
117
|
+
readonly bufferLength: number;
|
|
118
|
+
}
|
|
119
|
+
|
|
107
120
|
export class StreamAssembler {
|
|
108
121
|
// Turn-scoped monotonic sequence counter (never calls Date.now/Math.random).
|
|
109
122
|
#seq = 0;
|
|
@@ -345,7 +358,7 @@ export class StreamAssembler {
|
|
|
345
358
|
textStart(
|
|
346
359
|
id: string,
|
|
347
360
|
messageId: string,
|
|
348
|
-
fields?: { role?: "assistant"; providerMetadata?: AgProviderMeta },
|
|
361
|
+
fields?: { role?: "assistant"; providerMetadata?: AgProviderMeta; phase?: string },
|
|
349
362
|
): void {
|
|
350
363
|
const turnId = this.#resolveTurnId(undefined, messageId);
|
|
351
364
|
const ev: TextStartEvent = {
|
|
@@ -355,6 +368,7 @@ export class StreamAssembler {
|
|
|
355
368
|
messageId,
|
|
356
369
|
...(turnId !== undefined ? { turnId } : {}),
|
|
357
370
|
...(fields?.role !== undefined ? { role: fields.role } : {}),
|
|
371
|
+
...(fields?.phase !== undefined ? { phase: fields.phase } : {}), // draft.4 open-string label
|
|
358
372
|
...(fields?.providerMetadata !== undefined ? { providerMetadata: fields.providerMetadata } : {}),
|
|
359
373
|
};
|
|
360
374
|
this.#emit(ev);
|
|
@@ -384,7 +398,7 @@ export class StreamAssembler {
|
|
|
384
398
|
textEnd(
|
|
385
399
|
id: string,
|
|
386
400
|
messageId: string,
|
|
387
|
-
fields?: { providerMetadata?: AgProviderMeta; citations?: AgCitation[] },
|
|
401
|
+
fields?: { providerMetadata?: AgProviderMeta; citations?: AgCitation[]; phase?: string },
|
|
388
402
|
): void {
|
|
389
403
|
const turnId = this.#resolveTurnId(undefined, messageId);
|
|
390
404
|
const ev: TextEndEvent = {
|
|
@@ -393,6 +407,7 @@ export class StreamAssembler {
|
|
|
393
407
|
id,
|
|
394
408
|
messageId,
|
|
395
409
|
...(turnId !== undefined ? { turnId } : {}),
|
|
410
|
+
...(fields?.phase !== undefined ? { phase: fields.phase } : {}), // draft.4: replaces the start value
|
|
396
411
|
...(fields?.providerMetadata !== undefined ? { providerMetadata: fields.providerMetadata } : {}),
|
|
397
412
|
...(fields?.citations !== undefined ? { citations: fields.citations } : {}),
|
|
398
413
|
};
|
|
@@ -402,7 +417,7 @@ export class StreamAssembler {
|
|
|
402
417
|
// ── REASONING primitives ────────────────────────────────────────────────────
|
|
403
418
|
|
|
404
419
|
/** Emit `reasoning.start` for a new reasoning stream. */
|
|
405
|
-
reasoningStart(id: string, messageId: string, opts?: { mode?: "summarized" | "full" }): void {
|
|
420
|
+
reasoningStart(id: string, messageId: string, opts?: { mode?: "summarized" | "full"; phase?: string }): void {
|
|
406
421
|
const turnId = this.#resolveTurnId(undefined, messageId);
|
|
407
422
|
const ev: ReasoningStartEvent = {
|
|
408
423
|
type: "reasoning.start",
|
|
@@ -411,6 +426,7 @@ export class StreamAssembler {
|
|
|
411
426
|
messageId,
|
|
412
427
|
...(turnId !== undefined ? { turnId } : {}),
|
|
413
428
|
...(opts?.mode !== undefined ? { mode: opts.mode } : {}),
|
|
429
|
+
...(opts?.phase !== undefined ? { phase: opts.phase } : {}), // draft.4 open-string label
|
|
414
430
|
};
|
|
415
431
|
this.#emit(ev);
|
|
416
432
|
}
|
|
@@ -418,10 +434,10 @@ export class StreamAssembler {
|
|
|
418
434
|
/**
|
|
419
435
|
* Emit `reasoning.delta`. With `{cumulative:true}` de-cumulates against the
|
|
420
436
|
* prior buffer. `opts.providerMetadata` rides the delta verbatim — the home
|
|
421
|
-
* for a provider's per-chunk reasoning
|
|
422
|
-
*
|
|
423
|
-
*
|
|
424
|
-
*
|
|
437
|
+
* for a provider's per-chunk, replay-load-bearing reasoning metadata; absent
|
|
438
|
+
* ⇒ no key. Host-only telemetry does NOT belong here: e.g. the Claude CLI's
|
|
439
|
+
* per-delta `estimated_tokens` rides `_meta` (X5). This sugar has no `_meta`
|
|
440
|
+
* option, so a facet raw-emits the delta for that case.
|
|
425
441
|
*/
|
|
426
442
|
reasoningDelta(
|
|
427
443
|
id: string,
|
|
@@ -444,7 +460,7 @@ export class StreamAssembler {
|
|
|
444
460
|
}
|
|
445
461
|
|
|
446
462
|
/** Emit `reasoning.end` for a finished reasoning stream. */
|
|
447
|
-
reasoningEnd(id: string, messageId: string, opts?: { provider?: string }): void {
|
|
463
|
+
reasoningEnd(id: string, messageId: string, opts?: { provider?: string; phase?: string }): void {
|
|
448
464
|
const turnId = this.#resolveTurnId(undefined, messageId);
|
|
449
465
|
const ev: ReasoningEndEvent = {
|
|
450
466
|
type: "reasoning.end",
|
|
@@ -453,6 +469,7 @@ export class StreamAssembler {
|
|
|
453
469
|
messageId,
|
|
454
470
|
...(turnId !== undefined ? { turnId } : {}),
|
|
455
471
|
...(opts?.provider !== undefined ? { provider: opts.provider } : {}),
|
|
472
|
+
...(opts?.phase !== undefined ? { phase: opts.phase } : {}), // draft.4: replaces the start value
|
|
456
473
|
};
|
|
457
474
|
this.#emit(ev);
|
|
458
475
|
}
|
|
@@ -636,6 +653,55 @@ export class StreamAssembler {
|
|
|
636
653
|
} as AgClosedEventType);
|
|
637
654
|
}
|
|
638
655
|
|
|
656
|
+
/**
|
|
657
|
+
* A restorable snapshot of this assembler's whole state: the seq counter,
|
|
658
|
+
* the turn / message trackers, the turn stack, the cumulative-delta
|
|
659
|
+
* buffers and how many events sit undrained. It exists for a facet's
|
|
660
|
+
* per-native transaction (the fleet guard ruling, 2026-09-24): take a
|
|
661
|
+
* checkpoint before driving one native, and {@link rollback} to it if
|
|
662
|
+
* driving throws. The discarded partial batch then consumes no seq
|
|
663
|
+
* (INV-SEQ), and no turn, message or block it half-opened survives.
|
|
664
|
+
* Treat the value as opaque.
|
|
665
|
+
*
|
|
666
|
+
* Cost: O(state) per call. The message→turn map and the seen-turn set keep
|
|
667
|
+
* every message and turn of the invoke, so a facet that checkpoints per
|
|
668
|
+
* native pays O(natives × messages) per invoke. Measured 2026-09-24 on
|
|
669
|
+
* vercel-ai (the cost over a constant-size checkpoint, per invoke):
|
|
670
|
+
* 0.006 ms for the largest corpus native (50 parts), 1.6 ms for a synthetic
|
|
671
|
+
* 100-step run (702 parts), 41 ms for 500 steps (3,502 parts). Copy-on-write
|
|
672
|
+
* is the fix if that ever matters.
|
|
673
|
+
*/
|
|
674
|
+
checkpoint(): AssemblerCheckpoint {
|
|
675
|
+
return {
|
|
676
|
+
seq: this.#seq,
|
|
677
|
+
seenTurns: new Set(this.#seenTurns),
|
|
678
|
+
openTurns: new Set(this.#openTurns),
|
|
679
|
+
openMessages: new Map([...this.#openMessages].map(([k, v]) => [k, { ...v }])),
|
|
680
|
+
msgTurn: new Map(this.#msgTurn),
|
|
681
|
+
lastTurn: this.#lastTurn,
|
|
682
|
+
turnStack: [...this.#turnStack],
|
|
683
|
+
cumulative: new Map(this.#cumulative),
|
|
684
|
+
bufferLength: this.#buffer.length,
|
|
685
|
+
};
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
/**
|
|
689
|
+
* Restore a {@link checkpoint}: every event emitted since it is discarded,
|
|
690
|
+
* and the seq counter and trackers return to their state at that moment.
|
|
691
|
+
* The checkpoint stays valid, so it can be rolled back to again.
|
|
692
|
+
*/
|
|
693
|
+
rollback(cp: AssemblerCheckpoint): void {
|
|
694
|
+
this.#seq = cp.seq;
|
|
695
|
+
this.#seenTurns = new Set(cp.seenTurns);
|
|
696
|
+
this.#openTurns = new Set(cp.openTurns);
|
|
697
|
+
this.#openMessages = new Map([...cp.openMessages].map(([k, v]) => [k, { ...v }]));
|
|
698
|
+
this.#msgTurn = new Map(cp.msgTurn);
|
|
699
|
+
this.#lastTurn = cp.lastTurn;
|
|
700
|
+
this.#turnStack = [...cp.turnStack];
|
|
701
|
+
this.#cumulative = new Map(cp.cumulative);
|
|
702
|
+
this.#buffer = this.#buffer.slice(0, cp.bufferLength);
|
|
703
|
+
}
|
|
704
|
+
|
|
639
705
|
/**
|
|
640
706
|
* Drain the buffer and return all buffered events. Clears the buffer.
|
|
641
707
|
*/
|
package/src/wire.ts
CHANGED
|
@@ -17,3 +17,306 @@ export function toJsonValue(v: unknown): JsonValue {
|
|
|
17
17
|
const w: JsonValue = JSON.parse(JSON.stringify(v));
|
|
18
18
|
return w;
|
|
19
19
|
}
|
|
20
|
+
|
|
21
|
+
/** The value a cycle is replaced with by {@link toJsonValueSafe} (at the repeated node only). */
|
|
22
|
+
export const JSON_SAFE_CIRCULAR = "[Circular]";
|
|
23
|
+
/** The value a node nested deeper than {@link JSON_SAFE_MAX_DEPTH} is replaced with. */
|
|
24
|
+
export const JSON_SAFE_MAX_DEPTH_MARK = "[MaxDepth]";
|
|
25
|
+
/** The nesting depth past which the helpers stop descending (never reached by real data). */
|
|
26
|
+
export const JSON_SAFE_MAX_DEPTH = 1000;
|
|
27
|
+
|
|
28
|
+
/** Why {@link toJsonValueSafe} had to degrade a node that `JSON.stringify` would have thrown on. */
|
|
29
|
+
export type JsonSafeIssueKind =
|
|
30
|
+
| "bigint" // converted to its decimal string
|
|
31
|
+
| "circular" // replaced with JSON_SAFE_CIRCULAR
|
|
32
|
+
| "throwing-toJSON" // member omitted (null in an array / at the top)
|
|
33
|
+
| "throwing-getter" // member omitted (null in an array)
|
|
34
|
+
| "throwing-keys" // the node's keys could not be enumerated: node omitted
|
|
35
|
+
| "max-depth"; // replaced with JSON_SAFE_MAX_DEPTH_MARK
|
|
36
|
+
|
|
37
|
+
/** One degraded node: `path` is `$` for the top, then `.key` / `[index]` segments. */
|
|
38
|
+
export interface JsonSafeIssue {
|
|
39
|
+
path: string;
|
|
40
|
+
kind: JsonSafeIssueKind;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* True when `v` is ALREADY a plain JSON value, i.e. exactly what a JSON
|
|
45
|
+
* round-trip of it would produce: `null`, a string, a boolean, a finite
|
|
46
|
+
* number other than `-0`, an array with no holes, or a plain object (prototype
|
|
47
|
+
* `Object.prototype` or `null`, no own `toJSON`) of such values, acyclic and
|
|
48
|
+
* shallower than {@link JSON_SAFE_MAX_DEPTH}. Never throws (a throwing getter
|
|
49
|
+
* or proxy trap answers `false`). The walk allocates nothing per node beyond
|
|
50
|
+
* an ancestor stack, so a facet can afford it on every native event.
|
|
51
|
+
*/
|
|
52
|
+
export function isJsonValue(v: unknown): v is JsonValue {
|
|
53
|
+
const ancestors: object[] = [];
|
|
54
|
+
const walk = (x: unknown, depth: number): boolean => {
|
|
55
|
+
if (x === null) return true;
|
|
56
|
+
switch (typeof x) {
|
|
57
|
+
case "string":
|
|
58
|
+
case "boolean":
|
|
59
|
+
return true;
|
|
60
|
+
case "number":
|
|
61
|
+
return Number.isFinite(x) && !Object.is(x, -0);
|
|
62
|
+
case "object":
|
|
63
|
+
break;
|
|
64
|
+
default:
|
|
65
|
+
return false; // undefined, function, symbol, bigint
|
|
66
|
+
}
|
|
67
|
+
const o = x as object;
|
|
68
|
+
if (depth >= JSON_SAFE_MAX_DEPTH || ancestors.includes(o)) return false;
|
|
69
|
+
ancestors.push(o);
|
|
70
|
+
try {
|
|
71
|
+
if (Array.isArray(o)) {
|
|
72
|
+
for (let i = 0; i < o.length; i++) {
|
|
73
|
+
if (!(i in o) || !walk(o[i], depth + 1)) return false;
|
|
74
|
+
}
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
const proto: unknown = Object.getPrototypeOf(o);
|
|
78
|
+
if (proto !== Object.prototype && proto !== null) return false;
|
|
79
|
+
if (typeof (o as { toJSON?: unknown }).toJSON === "function") return false;
|
|
80
|
+
for (const k in o) {
|
|
81
|
+
if (!Object.prototype.hasOwnProperty.call(o, k)) continue;
|
|
82
|
+
if (!walk((o as Record<string, unknown>)[k], depth + 1)) return false;
|
|
83
|
+
}
|
|
84
|
+
return true;
|
|
85
|
+
} finally {
|
|
86
|
+
ancestors.pop();
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
try {
|
|
90
|
+
return walk(v, 0);
|
|
91
|
+
} catch {
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Materialize ANY live value as a `JsonValue`, and never throw.
|
|
98
|
+
*
|
|
99
|
+
* TOTAL by contract: for every input it returns a `JsonValue`. It never
|
|
100
|
+
* throws and never returns anything that is not JSON; the degraded forms below
|
|
101
|
+
* are themselves JSON (a string, or an omitted member).
|
|
102
|
+
*
|
|
103
|
+
* For a facet at a LIVE boundary (in practice once, on the whole native, at
|
|
104
|
+
* `push()` entry): a framework hands over in-process objects that may hold
|
|
105
|
+
* `undefined`, a `Date`, `NaN`, a `BigInt`, a function, a cycle or a throwing
|
|
106
|
+
* getter. `JsonValue.parse` is a validator, and it throws on those;
|
|
107
|
+
* `toJsonValue` (a JSON round-trip) throws on a BigInt or a cycle. A
|
|
108
|
+
* Normalizer MUST NOT throw out of `push()` (SPEC.md §8.0). Keep
|
|
109
|
+
* `JsonValue.parse` for validating data that is already JSON.
|
|
110
|
+
*
|
|
111
|
+
* Plain JSON input (see {@link isJsonValue}) is returned UNCHANGED, as the same
|
|
112
|
+
* reference, with no copy. Anything else is rebuilt as a fresh value that
|
|
113
|
+
* applies `JSON.stringify`'s own rules per node, so for JSON-able input the
|
|
114
|
+
* result serializes identically to `toJsonValue(v)`:
|
|
115
|
+
* - `toJSON` is honoured once per node, with the member key (a `Date` becomes
|
|
116
|
+
* its ISO string; a class instance defining `toJSON` becomes its result);
|
|
117
|
+
* - boxed `Number` / `String` / `Boolean` / `BigInt` are unwrapped;
|
|
118
|
+
* - `NaN` and ±`Infinity` become `null`, and `-0` becomes `0`;
|
|
119
|
+
* - an `undefined`, function or symbol member is omitted from an object, and
|
|
120
|
+
* becomes `null` in an array (a hole too);
|
|
121
|
+
* - an object contributes its own enumerable string keys, in `Object.keys`
|
|
122
|
+
* order (a `Map` or `Set` therefore becomes `{}`, as in JSON).
|
|
123
|
+
*
|
|
124
|
+
* Where `JSON.stringify` would throw, it degrades per node instead and keeps
|
|
125
|
+
* every JSON-able sibling:
|
|
126
|
+
* - a `BigInt` becomes its decimal string;
|
|
127
|
+
* - a cycle becomes {@link JSON_SAFE_CIRCULAR} at the node that repeats an
|
|
128
|
+
* ancestor. A value shared by two branches but not its own ancestor is
|
|
129
|
+
* serialized in full each time, as JSON does;
|
|
130
|
+
* - a throwing `toJSON` or getter omits that member (`null` in an array and
|
|
131
|
+
* for the top-level value);
|
|
132
|
+
* - a node whose keys cannot be enumerated (e.g. a proxy trap throws) is
|
|
133
|
+
* omitted likewise;
|
|
134
|
+
* - nesting past {@link JSON_SAFE_MAX_DEPTH} levels becomes
|
|
135
|
+
* {@link JSON_SAFE_MAX_DEPTH_MARK}, so a pathological structure cannot
|
|
136
|
+
* overflow the stack.
|
|
137
|
+
*
|
|
138
|
+
* One deliberate extension beyond JSON: an `Error` instance (whose `name` and
|
|
139
|
+
* `message` are not enumerable, so JSON would reduce it to its enumerable
|
|
140
|
+
* props) becomes `{name, message, …own enumerable props}`, recursively
|
|
141
|
+
* converted, and NEVER `stack`, which holds local file paths. The rule is the
|
|
142
|
+
* google-adk 0.6.x facet's (c6ecc1c) exactly, so 0.6.7 and 0.7.0 map an Error
|
|
143
|
+
* the same way: detection is `instanceof Error`, and `cause` or
|
|
144
|
+
* AggregateError `errors` ride only when a host made them enumerable.
|
|
145
|
+
*
|
|
146
|
+
* A `__proto__` key is kept as an ordinary own data member on BOTH paths (as
|
|
147
|
+
* `JSON.parse` does), never as a prototype. The helper does not strip it: a
|
|
148
|
+
* consumer that must drop it does so downstream (ingest's copy does, and the
|
|
149
|
+
* facets' scrub/allowlist paths skip it explicitly). A top-level value that
|
|
150
|
+
* JSON would drop (`undefined`, a function, a symbol) returns `null`. To learn
|
|
151
|
+
* WHICH nodes degraded, use {@link toJsonValueSafeWithIssues}.
|
|
152
|
+
*
|
|
153
|
+
* ALIASING: unlike `toJsonValue` (which always deep-copies through a JSON
|
|
154
|
+
* round-trip), plain input is returned BY REFERENCE, so its nodes can end up
|
|
155
|
+
* inside emitted events. A caller that needs isolation copies the result
|
|
156
|
+
* ({@link isJsonValue} is the cheap check). A facet must neither mutate the
|
|
157
|
+
* returned value nor retain it past the `push()` that produced it.
|
|
158
|
+
*/
|
|
159
|
+
export function toJsonValueSafe(v: unknown): JsonValue {
|
|
160
|
+
return toJsonValueSafeWithIssues(v).value;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** `instanceof Error`, exactly as the google-adk 0.6.x facet decides it
|
|
164
|
+
* (c6ecc1c), so 0.6.7 and 0.7.0 map the same values. An Error from another
|
|
165
|
+
* realm is not one, and converts as a plain object. */
|
|
166
|
+
function isErrorObject(o: object): boolean {
|
|
167
|
+
try {
|
|
168
|
+
return o instanceof Error;
|
|
169
|
+
} catch {
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* {@link toJsonValueSafe}, plus the list of nodes it had to degrade (empty when
|
|
176
|
+
* the input was JSON-able). A consumer that must not forward an invented value
|
|
177
|
+
* can branch on `issues.length > 0` instead of using `value`.
|
|
178
|
+
*/
|
|
179
|
+
export function toJsonValueSafeWithIssues(v: unknown): { value: JsonValue; issues: readonly JsonSafeIssue[] } {
|
|
180
|
+
if (isJsonValue(v)) return { value: v, issues: [] };
|
|
181
|
+
const issues: JsonSafeIssue[] = [];
|
|
182
|
+
const ancestors: object[] = [];
|
|
183
|
+
const OMIT = Symbol("omit");
|
|
184
|
+
const child = (path: string, key: string, inArray: boolean): string => (inArray ? `${path}[${key}]` : `${path}.${key}`);
|
|
185
|
+
|
|
186
|
+
const convert = (value: unknown, key: string, path: string, depth: number): JsonValue | typeof OMIT => {
|
|
187
|
+
let x = value;
|
|
188
|
+
try {
|
|
189
|
+
if (x !== null && (typeof x === "object" || typeof x === "bigint") && typeof (x as { toJSON?: unknown }).toJSON === "function") {
|
|
190
|
+
x = (x as { toJSON: (k: string) => unknown }).toJSON(key);
|
|
191
|
+
}
|
|
192
|
+
} catch {
|
|
193
|
+
issues.push({ path, kind: "throwing-toJSON" });
|
|
194
|
+
return OMIT;
|
|
195
|
+
}
|
|
196
|
+
if (typeof x === "object" && x !== null) {
|
|
197
|
+
if (x instanceof Number) x = Number(x);
|
|
198
|
+
else if (x instanceof String) x = String(x);
|
|
199
|
+
else if (x instanceof Boolean) x = x.valueOf();
|
|
200
|
+
else if (Object.prototype.toString.call(x) === "[object BigInt]") x = (x as { valueOf(): unknown }).valueOf();
|
|
201
|
+
}
|
|
202
|
+
if (x === null) return null;
|
|
203
|
+
switch (typeof x) {
|
|
204
|
+
case "string":
|
|
205
|
+
case "boolean":
|
|
206
|
+
return x;
|
|
207
|
+
case "number":
|
|
208
|
+
return Number.isFinite(x) ? (Object.is(x, -0) ? 0 : x) : null;
|
|
209
|
+
case "bigint":
|
|
210
|
+
issues.push({ path, kind: "bigint" });
|
|
211
|
+
return x.toString();
|
|
212
|
+
case "undefined":
|
|
213
|
+
case "function":
|
|
214
|
+
case "symbol":
|
|
215
|
+
return OMIT;
|
|
216
|
+
default:
|
|
217
|
+
break;
|
|
218
|
+
}
|
|
219
|
+
const obj = x as object;
|
|
220
|
+
if (ancestors.includes(obj)) {
|
|
221
|
+
issues.push({ path, kind: "circular" });
|
|
222
|
+
return JSON_SAFE_CIRCULAR;
|
|
223
|
+
}
|
|
224
|
+
if (depth >= JSON_SAFE_MAX_DEPTH) {
|
|
225
|
+
issues.push({ path, kind: "max-depth" });
|
|
226
|
+
return JSON_SAFE_MAX_DEPTH_MARK;
|
|
227
|
+
}
|
|
228
|
+
if (isErrorObject(obj)) {
|
|
229
|
+
// Deliberate extension beyond JSON (sp-main, 2026-09-24): an Error's
|
|
230
|
+
// `name` and `message` are not enumerable own data, so JSON drops them
|
|
231
|
+
// and a live error part loses its text. Map it to {name, message, …own
|
|
232
|
+
// enumerable props}, and NEVER `stack` (it holds local file paths).
|
|
233
|
+
ancestors.push(obj);
|
|
234
|
+
try {
|
|
235
|
+
const out: { [k: string]: JsonValue } = {};
|
|
236
|
+
const put = (k: string, read: () => unknown): void => {
|
|
237
|
+
let item: unknown;
|
|
238
|
+
try {
|
|
239
|
+
item = read();
|
|
240
|
+
} catch {
|
|
241
|
+
issues.push({ path: child(path, k, false), kind: "throwing-getter" });
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
const c = convert(item, k, child(path, k, false), depth + 1);
|
|
245
|
+
if (c !== OMIT) Object.defineProperty(out, k, { value: c, enumerable: true, writable: true, configurable: true });
|
|
246
|
+
};
|
|
247
|
+
put("name", () => (obj as Error).name);
|
|
248
|
+
put("message", () => (obj as Error).message);
|
|
249
|
+
let keys: string[] = [];
|
|
250
|
+
try {
|
|
251
|
+
keys = Object.keys(obj);
|
|
252
|
+
} catch {
|
|
253
|
+
issues.push({ path, kind: "throwing-keys" });
|
|
254
|
+
}
|
|
255
|
+
for (const k of keys) {
|
|
256
|
+
// As c6ecc1c: an own enumerable name/message is read again here and
|
|
257
|
+
// that read wins, keeping its first position.
|
|
258
|
+
if (k === "stack") continue;
|
|
259
|
+
put(k, () => (obj as Record<string, unknown>)[k]);
|
|
260
|
+
}
|
|
261
|
+
return out;
|
|
262
|
+
} finally {
|
|
263
|
+
ancestors.pop();
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
ancestors.push(obj);
|
|
267
|
+
try {
|
|
268
|
+
if (Array.isArray(obj)) {
|
|
269
|
+
let length: number;
|
|
270
|
+
try {
|
|
271
|
+
length = obj.length;
|
|
272
|
+
} catch {
|
|
273
|
+
issues.push({ path, kind: "throwing-keys" });
|
|
274
|
+
return OMIT;
|
|
275
|
+
}
|
|
276
|
+
const out: JsonValue[] = [];
|
|
277
|
+
for (let i = 0; i < length; i++) {
|
|
278
|
+
const p = child(path, String(i), true);
|
|
279
|
+
let item: unknown;
|
|
280
|
+
try {
|
|
281
|
+
item = obj[i];
|
|
282
|
+
} catch {
|
|
283
|
+
issues.push({ path: p, kind: "throwing-getter" });
|
|
284
|
+
out.push(null);
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
const c = convert(item, String(i), p, depth + 1);
|
|
288
|
+
out.push(c === OMIT ? null : c);
|
|
289
|
+
}
|
|
290
|
+
return out;
|
|
291
|
+
}
|
|
292
|
+
let keys: string[];
|
|
293
|
+
try {
|
|
294
|
+
keys = Object.keys(obj);
|
|
295
|
+
} catch {
|
|
296
|
+
issues.push({ path, kind: "throwing-keys" });
|
|
297
|
+
return OMIT;
|
|
298
|
+
}
|
|
299
|
+
const out: { [k: string]: JsonValue } = {};
|
|
300
|
+
for (const k of keys) {
|
|
301
|
+
const p = child(path, k, false);
|
|
302
|
+
let item: unknown;
|
|
303
|
+
try {
|
|
304
|
+
item = (obj as Record<string, unknown>)[k];
|
|
305
|
+
} catch {
|
|
306
|
+
issues.push({ path: p, kind: "throwing-getter" });
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
const c = convert(item, k, p, depth + 1);
|
|
310
|
+
if (c === OMIT) continue;
|
|
311
|
+
// A data property, never a prototype write, even for "__proto__".
|
|
312
|
+
Object.defineProperty(out, k, { value: c, enumerable: true, writable: true, configurable: true });
|
|
313
|
+
}
|
|
314
|
+
return out;
|
|
315
|
+
} finally {
|
|
316
|
+
ancestors.pop();
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
const top = convert(v, "", "$", 0);
|
|
321
|
+
return { value: top === OMIT ? null : top, issues };
|
|
322
|
+
}
|