@mnmal-ai/substrate 0.0.0 → 1.0.0-alpha.1

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.
Files changed (46) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +118 -1
  3. package/dist/agent-token-BIboWOU0.js +200 -0
  4. package/dist/client.d.ts +782 -0
  5. package/dist/client.js +7 -0
  6. package/dist/cluster-worker.js +35 -0
  7. package/dist/content-type-C7T28xNb.js +25 -0
  8. package/dist/dataset-DOXGRz50.js +1535 -0
  9. package/dist/env-utils-B7SGmoeJ.js +21 -0
  10. package/dist/errors-D4vKuwz8.d.ts +130 -0
  11. package/dist/fake-DUVtKVSE.js +36 -0
  12. package/dist/index-D7mSOFlM.d.ts +69 -0
  13. package/dist/pack.d.ts +192 -0
  14. package/dist/pack.js +5 -0
  15. package/dist/plugin-BuQQEzL-.js +3844 -0
  16. package/dist/plugin-t2g2wX0b.d.ts +1568 -0
  17. package/dist/proposals-bootstrap.js +37 -0
  18. package/dist/proposals.config.schema.json +20 -0
  19. package/dist/proposals.d.ts +118 -0
  20. package/dist/proposals.default-config.json +4 -0
  21. package/dist/proposals.js +4 -0
  22. package/dist/recall-bootstrap.js +451 -0
  23. package/dist/recall.config.schema.json +232 -0
  24. package/dist/recall.d.ts +1981 -0
  25. package/dist/recall.default-config.json +4 -0
  26. package/dist/recall.js +5 -0
  27. package/dist/repl-C52wyfMs.js +2213 -0
  28. package/dist/row-ByLFE2Wx.d.ts +719 -0
  29. package/dist/row-DK7lPZVe.js +732 -0
  30. package/dist/runtime-metrics-DwpDJ8vz.d.ts +159 -0
  31. package/dist/schema-g4FQLr0V.d.ts +433 -0
  32. package/dist/sdk.d.ts +694 -0
  33. package/dist/sdk.js +112 -0
  34. package/dist/src-5hVbeiAu.js +1797 -0
  35. package/dist/src-C4DzaIQZ.js +837 -0
  36. package/dist/src-CjEwiKXw.js +2327 -0
  37. package/dist/src-DuopV8u7.js +2408 -0
  38. package/dist/src-YXlv_RyL.js +13524 -0
  39. package/dist/src-zcyUofMJ.js +1015 -0
  40. package/dist/substrate-admin.js +808 -0
  41. package/dist/substrate.js +5482 -0
  42. package/dist/testing.d.ts +1240 -0
  43. package/dist/testing.js +702 -0
  44. package/dist/types-8c0gtnd2.d.ts +35 -0
  45. package/dist/ws-C72iVS5T.d.ts +143 -0
  46. package/package.json +117 -4
@@ -0,0 +1,837 @@
1
+ import { createRequire as __binCreateRequire } from 'node:module'; const require = __binCreateRequire(import.meta.url);
2
+ import { Unpackr, pack, pack as packFrame, unpack, unpack as unpackFrame } from "msgpackr";
3
+
4
+ //#region ../../packages/substrate-types/src/assert-never.ts
5
+ /**
6
+ * Exhaustiveness guard for the `default:` arm of a `switch` over a
7
+ * discriminated union. An unhandled variant makes the call fail to
8
+ * type-check; at runtime it throws rather than returning `undefined`.
9
+ */
10
+ function assertNever(x) {
11
+ throw new Error(`unhandled variant: ${JSON.stringify(x)}`);
12
+ }
13
+
14
+ //#endregion
15
+ //#region ../../packages/substrate-types/src/qualified-key.ts
16
+ function parseQualifiedKey(key) {
17
+ const slash = key.indexOf("/");
18
+ if (slash <= 0 || slash === key.length - 1) return null;
19
+ return {
20
+ ns: key.slice(0, slash),
21
+ name: key.slice(slash + 1)
22
+ };
23
+ }
24
+ /**
25
+ * Companion formatter for `parseQualifiedKey`: returns the
26
+ * `<namespace>/<name>` frame-key string.
27
+ */
28
+ function formatQualifiedKey(namespace, name) {
29
+ return `${namespace}/${name}`;
30
+ }
31
+
32
+ //#endregion
33
+ //#region ../../packages/substrate-pack/src/_plan-cache.ts
34
+ /**
35
+ * Lookup-or-build the per-(fields, fieldMap) plan. O(1) on hit; O(F) on miss
36
+ * for F selected fields.
37
+ */
38
+ function getRowPlan$2(cache, fields, fieldMap) {
39
+ let perFieldMap = cache.get(fields);
40
+ if (perFieldMap === void 0) {
41
+ perFieldMap = /* @__PURE__ */ new WeakMap();
42
+ cache.set(fields, perFieldMap);
43
+ }
44
+ const cached = perFieldMap.get(fieldMap);
45
+ if (cached !== void 0) return cached;
46
+ const entries = Object.entries(fields);
47
+ const plan = new Array(entries.length);
48
+ for (let i = 0; i < entries.length; i++) {
49
+ const pair = entries[i];
50
+ plan[i] = [
51
+ pair[0],
52
+ pair[1],
53
+ Object.hasOwn(fieldMap, pair[0]) ? fieldMap[pair[0]] : void 0
54
+ ];
55
+ }
56
+ perFieldMap.set(fieldMap, plan);
57
+ return plan;
58
+ }
59
+ /**
60
+ * Lookup-or-build the per-fields FieldDefPlan. O(1) on hit; O(F) on miss.
61
+ */
62
+ function getFieldDefPlan$2(cache, fields) {
63
+ const cached = cache.get(fields);
64
+ if (cached !== void 0) return cached;
65
+ const entries = Object.entries(fields);
66
+ const plan = new Array(entries.length);
67
+ for (let i = 0; i < entries.length; i++) {
68
+ const pair = entries[i];
69
+ plan[i] = [pair[0], pair[1]];
70
+ }
71
+ cache.set(fields, plan);
72
+ return plan;
73
+ }
74
+ /**
75
+ * Schema lookup for a type name. Tries the regular type registry first; falls
76
+ * back to mutations whose `returns` is a struct (the natural lookup for
77
+ * nested selection through a mutation-typed frame key). Returns `undefined`
78
+ * when the type is unknown — callers throw their own typed error with the
79
+ * appropriate path context.
80
+ *
81
+ * Non-struct mutation returns (e.g. delete's `{id, deleted}`) intentionally
82
+ * surface as an empty field map rather than undefined — the lookup
83
+ * succeeded; the type has no nested selection. Both codecs treat the empty
84
+ * map as "no fields to project".
85
+ */
86
+ function lookupFieldMap(schema, typeName) {
87
+ const typeEntry = Object.hasOwn(schema.types, typeName) ? schema.types[typeName] : void 0;
88
+ if (typeEntry !== void 0) return typeEntry.fields;
89
+ const mutationEntry = Object.hasOwn(schema.mutations, typeName) ? schema.mutations[typeName] : void 0;
90
+ if (mutationEntry !== void 0) {
91
+ const ret = mutationEntry.returns;
92
+ if (ret.kind === "struct") return ret.fields;
93
+ return {};
94
+ }
95
+ }
96
+ /**
97
+ * Resolve a type's field map, or throw the error `makeError` builds when the
98
+ * type is unknown.
99
+ */
100
+ function resolveFieldMap$2(schema, typeName, path, makeError) {
101
+ const fieldMap = lookupFieldMap(schema, typeName);
102
+ if (fieldMap === void 0) throw makeError(`unknown type '${typeName}' in schema`, path);
103
+ return fieldMap;
104
+ }
105
+
106
+ //#endregion
107
+ //#region ../../packages/substrate-pack/src/decoder.ts
108
+ /**
109
+ * Positional decoder. Spec: §7.0, §7.2.
110
+ *
111
+ * Mirror of `encoder.ts`. Rebuilds named objects from positional tuples using
112
+ * the same `FieldInput` the client originally sent plus the schema cached at
113
+ * init. Single-vs-list dispatch is driven by `PackEnvelope.shapes[key]`
114
+ * (§7.2) — no inference from the tuple shape.
115
+ *
116
+ * Schema drift (§7.1) is detected here when the caller passes
117
+ * `expectedSchemaVersion`: the decoder throws `SchemaDriftError` before
118
+ * decoding any data value, so drift fails loudly instead of corrupting row
119
+ * shapes. Refetch-and-retry is the caller's job. Without
120
+ * `expectedSchemaVersion` no check is made.
121
+ */
122
+ /**
123
+ * @internal — error thrown by the positional decoder on malformed input.
124
+ * Exported, but treat as package-private; signature may change without a
125
+ * major bump.
126
+ */
127
+ var PackDecodeError = class extends Error {
128
+ name = "PackDecodeError";
129
+ path;
130
+ constructor(message, path) {
131
+ super(`${message} at ${path.length === 0 ? "<root>" : path.join(".")}`);
132
+ this.path = path.slice();
133
+ }
134
+ };
135
+ /**
136
+ * §7.1 loud-failure. Thrown by `decodeEnvelope` when the caller supplied an
137
+ * `expectedSchemaVersion` that disagrees with the envelope's declared version.
138
+ * Carries both sides of the mismatch so the caller can decide whether to
139
+ * refetch the federated schema and retry or surface the error.
140
+ */
141
+ var SchemaDriftError = class extends Error {
142
+ envelopeSchemaVersion;
143
+ expectedSchemaVersion;
144
+ name = "SchemaDriftError";
145
+ constructor(envelopeSchemaVersion, expectedSchemaVersion) {
146
+ super(`schema drift: envelope schemaVersion '${envelopeSchemaVersion}' does not match expected '${expectedSchemaVersion}'`);
147
+ this.envelopeSchemaVersion = envelopeSchemaVersion;
148
+ this.expectedSchemaVersion = expectedSchemaVersion;
149
+ }
150
+ };
151
+ function decodePositional(encoded, fields, schema, typeName, ctx) {
152
+ if (encoded === null || encoded === void 0) return null;
153
+ return decodeValueByArity(encoded, fields, resolveFieldMap$1(schema, typeName, [typeName]), schema, [typeName], ctx);
154
+ }
155
+ /**
156
+ * Decode a mutation response against its declared `FieldDef`. Symmetric to
157
+ * `encodePositionalFromFieldDef`.
158
+ *
159
+ * @internal — used by `decodeEnvelope` for mutation returns. Treat as
160
+ * package-private.
161
+ */
162
+ function decodePositionalFromFieldDef(encoded, def, schema, ctx, path = []) {
163
+ if (encoded === null || encoded === void 0) return null;
164
+ return decodeFieldDef(encoded, def, schema, path, ctx);
165
+ }
166
+ function decodeEnvelope(bytes, ctx) {
167
+ const raw = unpack(Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes));
168
+ if (ctx.expectedSchemaVersion !== void 0 && raw.schemaVersion !== ctx.expectedSchemaVersion) throw new SchemaDriftError(raw.schemaVersion, ctx.expectedSchemaVersion);
169
+ const rewritten = {};
170
+ for (const [key, value] of Object.entries(raw.data)) {
171
+ const returns = ctx.returnsByKey?.[key];
172
+ if (returns !== void 0) {
173
+ const currentNs = ctx.currentNsByKey[key];
174
+ const schema = currentNs !== void 0 ? ctx.schemas[currentNs] : void 0;
175
+ if (currentNs === void 0 || schema === void 0) {
176
+ rewritten[key] = value;
177
+ continue;
178
+ }
179
+ rewritten[key] = decodeByShapeFromDef(value, returns, schema, raw.shapes[key], {
180
+ schemas: ctx.schemas,
181
+ currentNs
182
+ });
183
+ continue;
184
+ }
185
+ const fields = ctx.fieldsByKey[key];
186
+ const typeName = ctx.typeByKey[key];
187
+ const currentNs = ctx.currentNsByKey[key];
188
+ if (fields === void 0 || typeName === void 0 || currentNs === void 0) {
189
+ rewritten[key] = value;
190
+ continue;
191
+ }
192
+ const schema = ctx.schemas[currentNs];
193
+ if (schema === void 0) {
194
+ rewritten[key] = value;
195
+ continue;
196
+ }
197
+ const rawShape = raw.shapes[key];
198
+ rewritten[key] = decodeByShape(value, fields, schema, typeName, Array.isArray(rawShape) ? void 0 : rawShape, {
199
+ schemas: ctx.schemas,
200
+ currentNs
201
+ });
202
+ }
203
+ const out = {
204
+ schemaVersion: raw.schemaVersion,
205
+ data: rewritten,
206
+ shapes: raw.shapes
207
+ };
208
+ if (raw._meta !== void 0) out._meta = raw._meta;
209
+ if (raw._pagination !== void 0) out._pagination = raw._pagination;
210
+ if (raw._completeness !== void 0) out._completeness = raw._completeness;
211
+ if (raw.errors !== void 0) out.errors = raw.errors;
212
+ return out;
213
+ }
214
+ function decodeByShape(value, fields, schema, typeName, shape, ctx) {
215
+ if (value === null || value === void 0) return null;
216
+ const plan = getRowPlan$1(fields, resolveFieldMap$1(schema, typeName, [typeName]));
217
+ if (shape === "list") {
218
+ if (!Array.isArray(value)) throw new PackDecodeError("expected array for list shape", [typeName]);
219
+ return value.map((elem) => decodeRowWithPlan(elem, plan, schema, [typeName], ctx));
220
+ }
221
+ return decodeRowWithPlan(value, plan, schema, [typeName], ctx);
222
+ }
223
+ function decodeByShapeFromDef(value, def, schema, shape, ctx) {
224
+ if (value === null || value === void 0) return null;
225
+ if (Array.isArray(shape)) {
226
+ if (!Array.isArray(value)) throw new PackDecodeError("expected array for batched shape", []);
227
+ return value.map((elem, idx) => decodeByShapeFromDef(elem, def, schema, shape[idx], ctx));
228
+ }
229
+ if (shape === "list") {
230
+ if (!Array.isArray(value)) throw new PackDecodeError("expected array for list shape", []);
231
+ return value.map((elem, idx) => decodePositionalFromFieldDef(elem, def, schema, ctx, [`[${idx}]`]));
232
+ }
233
+ return decodePositionalFromFieldDef(value, def, schema, ctx);
234
+ }
235
+ function resolveFieldMap$1(schema, typeName, path) {
236
+ return resolveFieldMap$2(schema, typeName, path, (message, p) => new PackDecodeError(message, p));
237
+ }
238
+ /**
239
+ * Decide whether `value` is a single tuple or a list of tuples based on its
240
+ * shape plus the FieldInput — used only by the top-level `decodePositional`
241
+ * helper (the envelope decoder uses `shapes[key]` directly). Heuristic:
242
+ * - null → null
243
+ * - Array where the first element is itself an array → list of rows
244
+ * - Array otherwise → single row (tuple)
245
+ *
246
+ * This heuristic is the ambiguity §7.2 calls out, so callers SHOULD go through
247
+ * `decodeEnvelope` to use explicit shape metadata.
248
+ */
249
+ function decodeValueByArity(value, fields, fieldMap, schema, path, ctx) {
250
+ if (value === null || value === void 0) return null;
251
+ if (!Array.isArray(value)) throw new PackDecodeError("expected array (tuple) for positional row", path);
252
+ const plan = getRowPlan$1(fields, fieldMap);
253
+ if (value.length > 0 && Array.isArray(value[0])) return value.map((elem) => decodeRowWithPlan(elem, plan, schema, path, ctx));
254
+ return decodeRowWithPlan(value, plan, schema, path, ctx);
255
+ }
256
+ const DECODE_PLAN_CACHE = /* @__PURE__ */ new WeakMap();
257
+ function getRowPlan$1(fields, fieldMap) {
258
+ return getRowPlan$2(DECODE_PLAN_CACHE, fields, fieldMap);
259
+ }
260
+ function decodeRowWithPlan(tuple, plan, schema, path, ctx) {
261
+ if (tuple === null || tuple === void 0) return null;
262
+ if (!Array.isArray(tuple)) throw new PackDecodeError("expected array (tuple) for row", path);
263
+ const out = {};
264
+ const len = plan.length;
265
+ for (let i = 0; i < len; i++) {
266
+ const entry = plan[i];
267
+ const field = entry[0];
268
+ const selection = entry[1];
269
+ const def = entry[2];
270
+ const cell = tuple[i] ?? null;
271
+ path.push(field);
272
+ out[field] = decodeField(cell, selection, def, schema, path, ctx);
273
+ path.pop();
274
+ }
275
+ return out;
276
+ }
277
+ function decodeField(cell, selection, def, schema, path, ctx) {
278
+ if (cell === null || cell === void 0) return null;
279
+ if (def === void 0) return cell;
280
+ if (selection === true) return decodeLeaf(cell, def, path);
281
+ switch (def.kind) {
282
+ case "scalar": throw new PackDecodeError(`field is a scalar (${def.type}); cannot select sub-fields`, path);
283
+ case "struct": return decodeStruct(cell, selection, def, schema, path, ctx);
284
+ case "list": return decodeList(cell, selection, def, schema, path, ctx);
285
+ case "crossRef": return decodeCrossRef(cell, selection, def, schema, path, ctx);
286
+ default: return assertNever(def);
287
+ }
288
+ }
289
+ function decodeLeaf(cell, def, path) {
290
+ switch (def.kind) {
291
+ case "scalar": return cell;
292
+ case "list":
293
+ if (!Array.isArray(cell)) throw new PackDecodeError("expected array for list leaf", path);
294
+ return cell;
295
+ case "struct":
296
+ case "crossRef": return cell;
297
+ default: return assertNever(def);
298
+ }
299
+ }
300
+ function decodeStruct(cell, selection, def, schema, path, ctx) {
301
+ return decodeRowWithPlan(cell, getRowPlan$1(selection, def.fields), schema, path, ctx);
302
+ }
303
+ function decodeList(cell, selection, def, schema, path, ctx) {
304
+ if (!Array.isArray(cell)) throw new PackDecodeError("expected array for list field", path);
305
+ const inner = def.of;
306
+ const innerPlan = inner.kind === "struct" ? getRowPlan$1(selection, inner.fields) : void 0;
307
+ const out = [];
308
+ for (let idx = 0; idx < cell.length; idx++) {
309
+ const elem = cell[idx];
310
+ if (elem === null || elem === void 0) {
311
+ out.push(null);
312
+ continue;
313
+ }
314
+ path.push(`[${idx}]`);
315
+ out.push(decodeListElement(elem, selection, inner, schema, path, ctx, innerPlan));
316
+ path.pop();
317
+ }
318
+ return out;
319
+ }
320
+ function decodeListElement(elem, selection, inner, schema, elemPath, ctx, structPlan) {
321
+ switch (inner.kind) {
322
+ case "scalar": throw new PackDecodeError(`list element is scalar (${inner.type}); cannot select sub-fields`, elemPath);
323
+ case "struct": return decodeRowWithPlan(elem, structPlan ?? getRowPlan$1(selection, inner.fields), schema, elemPath, ctx);
324
+ case "list": return decodeList(elem, selection, inner, schema, elemPath, ctx);
325
+ case "crossRef": return decodeCrossRef(elem, selection, inner, schema, elemPath, ctx);
326
+ default: return assertNever(inner);
327
+ }
328
+ }
329
+ function decodeCrossRef(cell, selection, def, schema, path, ctx) {
330
+ if (def.ns === ctx.currentNs) return decodeRowWithPlan(cell, getRowPlan$1(selection, resolveFieldMap$1(schema, def.type, path)), schema, path, ctx);
331
+ const schemas = ctx.schemas;
332
+ if (schemas === void 0) throw new PackDecodeError(`cross-namespace crossRef '${def.ns}/${def.type}' requires ctx.schemas`, path);
333
+ const targetSchema = schemas[def.ns];
334
+ if (targetSchema === void 0) throw new PackDecodeError(`cross-namespace crossRef target namespace '${def.ns}' not in ctx.schemas`, path);
335
+ return decodeRowWithPlan(cell, getRowPlan$1(selection, resolveFieldMap$1(targetSchema, def.type, path)), targetSchema, path, {
336
+ ...ctx,
337
+ currentNs: def.ns
338
+ });
339
+ }
340
+ function decodeFieldDef(value, def, schema, path, ctx) {
341
+ if (value === null || value === void 0) return null;
342
+ switch (def.kind) {
343
+ case "scalar": return value;
344
+ case "struct": return decodeStructFromDef(value, def, schema, path, ctx);
345
+ case "list": return decodeListFromDef(value, def, schema, path, ctx);
346
+ case "crossRef": return value;
347
+ default: return assertNever(def);
348
+ }
349
+ }
350
+ const DECODE_FIELDDEF_PLAN_CACHE = /* @__PURE__ */ new WeakMap();
351
+ function getFieldDefPlan$1(fields) {
352
+ return getFieldDefPlan$2(DECODE_FIELDDEF_PLAN_CACHE, fields);
353
+ }
354
+ function decodeStructFromDef(value, def, schema, path, ctx) {
355
+ if (!Array.isArray(value)) throw new PackDecodeError("expected array (tuple) for struct", path);
356
+ const out = {};
357
+ const plan = getFieldDefPlan$1(def.fields);
358
+ const len = plan.length;
359
+ for (let i = 0; i < len; i++) {
360
+ const entry = plan[i];
361
+ const fieldName = entry[0];
362
+ const sub = entry[1];
363
+ const cell = value[i] ?? null;
364
+ path.push(fieldName);
365
+ out[fieldName] = decodeFieldDef(cell, sub, schema, path, ctx);
366
+ path.pop();
367
+ }
368
+ return out;
369
+ }
370
+ function decodeListFromDef(value, def, schema, path, ctx) {
371
+ if (!Array.isArray(value)) throw new PackDecodeError("expected array for list field", path);
372
+ const out = [];
373
+ for (let idx = 0; idx < value.length; idx++) {
374
+ const elem = value[idx];
375
+ if (elem === null || elem === void 0) {
376
+ out.push(null);
377
+ continue;
378
+ }
379
+ path.push(`[${idx}]`);
380
+ out.push(decodeFieldDef(elem, def.of, schema, path, ctx));
381
+ path.pop();
382
+ }
383
+ return out;
384
+ }
385
+
386
+ //#endregion
387
+ //#region ../../packages/substrate-pack/src/encoder.ts
388
+ /**
389
+ * Positional encoder. Spec: §7.0, §7.5.
390
+ *
391
+ * Strips field names from the wire. For a selected FieldInput, emits a tuple
392
+ * of values in iteration order; the decoder reconstructs the named object
393
+ * using the same FieldInput plus the schema cached at client init. The win is
394
+ * parse time (§7.5) — msgpackr handles named objects fine, but positional
395
+ * arrays skip the key lookup per cell, which compounds across thousand-row
396
+ * responses.
397
+ *
398
+ * Contract: `encodePositional` is shape-blind. Callers decide single-vs-list
399
+ * via `PackEnvelope.shapes[key]` (§7.2) and pass either a row or an array
400
+ * of rows; the encoder emits the corresponding tuple or array-of-tuples. It does
401
+ * NOT infer list-vs-single from the value shape.
402
+ *
403
+ * Mutation responses use `encodePositionalFromFieldDef` — mutations don't
404
+ * carry a client-sent `FieldInput`, so the FieldDef declared at registration
405
+ * (MutationSchema.returns) drives the encoding directly.
406
+ */
407
+ /**
408
+ * @internal — error thrown by the positional encoder on malformed input.
409
+ * Exported, but treat as package-private.
410
+ */
411
+ var PackEncodeError = class extends Error {
412
+ name = "PackEncodeError";
413
+ path;
414
+ constructor(message, path) {
415
+ super(`${message} at ${path.length === 0 ? "<root>" : path.join(".")}`);
416
+ this.path = path.slice();
417
+ }
418
+ };
419
+ function encodePositional(value, fields, schema, typeName, ctx) {
420
+ if (value === null || value === void 0) return null;
421
+ const plan = getRowPlan(fields, resolveFieldMap(schema, typeName, [typeName]));
422
+ if (Array.isArray(value)) return value.map((row) => encodeRowWithPlan(row, plan, schema, [typeName], ctx));
423
+ return encodeRowWithPlan(value, plan, schema, [typeName], ctx);
424
+ }
425
+ /**
426
+ * Encode a mutation response against its declared `FieldDef` (no client-sent
427
+ * FieldInput). Symmetric to `encodePositional` but driven entirely by the
428
+ * schema descriptor.
429
+ *
430
+ * - `scalar` → value passes through (nullable tolerated)
431
+ * - `struct` → positional tuple over `def.fields` iteration order
432
+ * - `list` → value is an array; each element encoded against `def.of`
433
+ * - `crossRef` → value is expected to be an id scalar (eq-on-id; we don't
434
+ * recurse into the target type — mutation returns don't embed sub-rows)
435
+ *
436
+ * @internal — used by `encodeEnvelope` for mutation returns. Treat as
437
+ * package-private.
438
+ */
439
+ function encodePositionalFromFieldDef(value, def, schema, ctx, path = []) {
440
+ if (value === null || value === void 0) return null;
441
+ return encodeFieldDef(value, def, schema, path, ctx);
442
+ }
443
+ function encodeEnvelope(envelope, ctx) {
444
+ const rewritten = {};
445
+ for (const [key, value] of Object.entries(envelope.data)) {
446
+ const returns = ctx.returnsByKey?.[key];
447
+ if (returns !== void 0) {
448
+ const currentNs = ctx.currentNsByKey[key];
449
+ const schema = currentNs !== void 0 ? ctx.schemas[currentNs] : void 0;
450
+ if (currentNs === void 0 || schema === void 0) {
451
+ rewritten[key] = value;
452
+ continue;
453
+ }
454
+ rewritten[key] = encodePositionalForShape(value, returns, schema, envelope.shapes[key], {
455
+ schemas: ctx.schemas,
456
+ currentNs
457
+ });
458
+ continue;
459
+ }
460
+ const fields = ctx.fieldsByKey[key];
461
+ const typeName = ctx.typeByKey[key];
462
+ const currentNs = ctx.currentNsByKey[key];
463
+ if (fields === void 0 || typeName === void 0 || currentNs === void 0) {
464
+ rewritten[key] = value;
465
+ continue;
466
+ }
467
+ const schema = ctx.schemas[currentNs];
468
+ if (schema === void 0) {
469
+ rewritten[key] = value;
470
+ continue;
471
+ }
472
+ rewritten[key] = encodePositional(value, fields, schema, typeName, {
473
+ schemas: ctx.schemas,
474
+ currentNs
475
+ });
476
+ }
477
+ const out = {
478
+ schemaVersion: envelope.schemaVersion,
479
+ data: rewritten,
480
+ shapes: envelope.shapes
481
+ };
482
+ if (envelope._meta !== void 0) out._meta = envelope._meta;
483
+ if (envelope._pagination !== void 0) out._pagination = envelope._pagination;
484
+ if (envelope._completeness !== void 0) out._completeness = envelope._completeness;
485
+ if (envelope.errors !== void 0) out.errors = envelope.errors;
486
+ return Buffer.from(pack(out));
487
+ }
488
+ /**
489
+ * Encode a single envelope value against its declared `returns` FieldDef,
490
+ * honouring the envelope's single-vs-list shape for that key. `single` encodes
491
+ * one row; `list` encodes an array of rows element-by-element.
492
+ *
493
+ * Batched mutate (§5.13): when the shape is `Array<'single' | 'list'>`, the
494
+ * value is itself `Array<unknown>` (one per-frame slot); each slot encodes
495
+ * against the same FieldDef using its own per-frame shape.
496
+ */
497
+ function encodePositionalForShape(value, def, schema, shape, ctx) {
498
+ if (value === null || value === void 0) return null;
499
+ if (Array.isArray(shape)) {
500
+ if (!Array.isArray(value)) throw new PackEncodeError("expected array for batched shape", []);
501
+ return value.map((elem, idx) => {
502
+ const perFrameShape = shape[idx];
503
+ return encodePositionalForShape(elem, def, schema, perFrameShape, ctx);
504
+ });
505
+ }
506
+ if (shape === "list") {
507
+ if (!Array.isArray(value)) throw new PackEncodeError("expected array for list shape", []);
508
+ return value.map((elem, idx) => encodePositionalFromFieldDef(elem, def, schema, ctx, [`[${idx}]`]));
509
+ }
510
+ return encodePositionalFromFieldDef(value, def, schema, ctx);
511
+ }
512
+ function resolveFieldMap(schema, typeName, path) {
513
+ return resolveFieldMap$2(schema, typeName, path, (message, p) => new PackEncodeError(message, p));
514
+ }
515
+ const ENCODE_PLAN_CACHE = /* @__PURE__ */ new WeakMap();
516
+ function getRowPlan(fields, fieldMap) {
517
+ return getRowPlan$2(ENCODE_PLAN_CACHE, fields, fieldMap);
518
+ }
519
+ function encodeRowWithPlan(row, plan, schema, path, ctx) {
520
+ if (row === null || row === void 0) return null;
521
+ if (typeof row !== "object" || Array.isArray(row)) throw new PackEncodeError(`expected object row, got ${Array.isArray(row) ? "array" : typeof row}`, path);
522
+ const rowObj = row;
523
+ const len = plan.length;
524
+ const tuple = new Array(len);
525
+ for (let i = 0; i < len; i++) {
526
+ const entry = plan[i];
527
+ const field = entry[0];
528
+ const selection = entry[1];
529
+ const def = entry[2];
530
+ const value = Object.hasOwn(rowObj, field) ? rowObj[field] : void 0;
531
+ path.push(field);
532
+ tuple[i] = encodeField(value, selection, def, schema, path, ctx);
533
+ path.pop();
534
+ }
535
+ return tuple;
536
+ }
537
+ function encodeField(value, selection, def, schema, path, ctx) {
538
+ if (value === null || value === void 0) return null;
539
+ if (def === void 0) return selection === true ? coerceScalar(value) : value;
540
+ if (selection === true) return encodeLeaf(value, def, path);
541
+ switch (def.kind) {
542
+ case "scalar": throw new PackEncodeError(`field is a scalar (${def.type}); cannot select sub-fields`, path);
543
+ case "struct": return encodeStruct(value, selection, def, schema, path, ctx);
544
+ case "list": return encodeList(value, selection, def, schema, path, ctx);
545
+ case "crossRef": return encodeCrossRef(value, selection, def, schema, path, ctx);
546
+ default: return assertNever(def);
547
+ }
548
+ }
549
+ function encodeLeaf(value, def, path) {
550
+ switch (def.kind) {
551
+ case "scalar": return coerceScalar(value);
552
+ case "list":
553
+ if (!Array.isArray(value)) throw new PackEncodeError("expected array for list field", path);
554
+ return value.map((v) => coerceScalar(v));
555
+ case "struct":
556
+ case "crossRef": return value;
557
+ default: return assertNever(def);
558
+ }
559
+ }
560
+ function encodeStruct(value, selection, def, schema, path, ctx) {
561
+ return encodeRowWithPlan(value, getRowPlan(selection, def.fields), schema, path, ctx);
562
+ }
563
+ function encodeList(value, selection, def, schema, path, ctx) {
564
+ if (!Array.isArray(value)) throw new PackEncodeError("expected array for list field", path);
565
+ const inner = def.of;
566
+ const innerPlan = inner.kind === "struct" ? getRowPlan(selection, inner.fields) : void 0;
567
+ const out = [];
568
+ for (let idx = 0; idx < value.length; idx++) {
569
+ const elem = value[idx];
570
+ if (elem === null || elem === void 0) {
571
+ out.push(null);
572
+ continue;
573
+ }
574
+ path.push(`[${idx}]`);
575
+ out.push(encodeListElement(elem, selection, inner, schema, path, ctx, innerPlan));
576
+ path.pop();
577
+ }
578
+ return out;
579
+ }
580
+ function encodeListElement(elem, selection, inner, schema, elemPath, ctx, structPlan) {
581
+ switch (inner.kind) {
582
+ case "scalar": throw new PackEncodeError(`list element is scalar (${inner.type}); cannot select sub-fields`, elemPath);
583
+ case "struct": return encodeRowWithPlan(elem, structPlan ?? getRowPlan(selection, inner.fields), schema, elemPath, ctx);
584
+ case "list": return encodeList(elem, selection, inner, schema, elemPath, ctx);
585
+ case "crossRef": return encodeCrossRef(elem, selection, inner, schema, elemPath, ctx);
586
+ default: return assertNever(inner);
587
+ }
588
+ }
589
+ function encodeCrossRef(value, selection, def, schema, path, ctx) {
590
+ if (def.ns === ctx.currentNs) return encodeRowWithPlan(value, getRowPlan(selection, resolveFieldMap(schema, def.type, path)), schema, path, ctx);
591
+ const schemas = ctx.schemas;
592
+ if (schemas === void 0) throw new PackEncodeError(`cross-namespace crossRef '${def.ns}/${def.type}' requires ctx.schemas`, path);
593
+ const targetSchema = schemas[def.ns];
594
+ if (targetSchema === void 0) throw new PackEncodeError(`cross-namespace crossRef target namespace '${def.ns}' not in ctx.schemas`, path);
595
+ return encodeRowWithPlan(value, getRowPlan(selection, resolveFieldMap(targetSchema, def.type, path)), targetSchema, path, {
596
+ ...ctx,
597
+ currentNs: def.ns
598
+ });
599
+ }
600
+ function encodeFieldDef(value, def, schema, path, ctx) {
601
+ if (value === null || value === void 0) return null;
602
+ switch (def.kind) {
603
+ case "scalar": return coerceScalar(value);
604
+ case "struct": return encodeStructFromDef(value, def, schema, path, ctx);
605
+ case "list": return encodeListFromDef(value, def, schema, path, ctx);
606
+ case "crossRef": return coerceScalar(value);
607
+ default: return assertNever(def);
608
+ }
609
+ }
610
+ const ENCODE_FIELDDEF_PLAN_CACHE = /* @__PURE__ */ new WeakMap();
611
+ function getFieldDefPlan(fields) {
612
+ return getFieldDefPlan$2(ENCODE_FIELDDEF_PLAN_CACHE, fields);
613
+ }
614
+ function encodeStructFromDef(value, def, schema, path, ctx) {
615
+ if (typeof value !== "object" || Array.isArray(value)) throw new PackEncodeError(`expected object for struct, got ${Array.isArray(value) ? "array" : typeof value}`, path);
616
+ const rowObj = value;
617
+ const plan = getFieldDefPlan(def.fields);
618
+ const len = plan.length;
619
+ const tuple = new Array(len);
620
+ for (let i = 0; i < len; i++) {
621
+ const entry = plan[i];
622
+ const fieldName = entry[0];
623
+ const sub = entry[1];
624
+ const cell = Object.hasOwn(rowObj, fieldName) ? rowObj[fieldName] : void 0;
625
+ if (cell === void 0) {
626
+ tuple[i] = null;
627
+ continue;
628
+ }
629
+ path.push(fieldName);
630
+ tuple[i] = encodeFieldDef(cell, sub, schema, path, ctx);
631
+ path.pop();
632
+ }
633
+ return tuple;
634
+ }
635
+ function encodeListFromDef(value, def, schema, path, ctx) {
636
+ if (!Array.isArray(value)) throw new PackEncodeError("expected array for list field", path);
637
+ const out = [];
638
+ for (let idx = 0; idx < value.length; idx++) {
639
+ const elem = value[idx];
640
+ if (elem === null || elem === void 0) {
641
+ out.push(null);
642
+ continue;
643
+ }
644
+ path.push(`[${idx}]`);
645
+ out.push(encodeFieldDef(elem, def.of, schema, path, ctx));
646
+ path.pop();
647
+ }
648
+ return out;
649
+ }
650
+ /**
651
+ * Identity today — msgpackr round-trips Dates natively. Kept as the single
652
+ * choke point for any future scalar normalisation.
653
+ */
654
+ function coerceScalar(value) {
655
+ return value;
656
+ }
657
+
658
+ //#endregion
659
+ //#region ../../packages/substrate-pack/src/stream-chunk.ts
660
+ /**
661
+ * Pack a chunk into a msgpack buffer. The row is positionally encoded first,
662
+ * then the whole sub-envelope is serialised in one pass.
663
+ */
664
+ function encodeStreamChunk(input) {
665
+ const encoded = encodePositional(input.row, input.fields, input.schema, input.typeName, {
666
+ currentNs: input.currentNs,
667
+ ...input.schemas !== void 0 ? { schemas: input.schemas } : {}
668
+ });
669
+ const chunk = {
670
+ schemaVersion: input.schemaVersion,
671
+ streamId: input.streamId,
672
+ sequence: input.sequence,
673
+ shape: "single",
674
+ data: encoded
675
+ };
676
+ if (input.final !== void 0) chunk.final = input.final;
677
+ if (input.meta !== void 0) chunk._meta = input.meta;
678
+ return Buffer.from(pack(chunk));
679
+ }
680
+ /**
681
+ * Unpack a chunk and reconstruct the named-object row using the same selection
682
+ * tree + schema the encoder saw. `schemaVersion`, `sequence`, `final`, and
683
+ * `_meta` round-trip unchanged.
684
+ */
685
+ function decodeStreamChunk(bytes, input) {
686
+ const raw = unpack(Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes));
687
+ const decoded = decodePositional(raw.data, input.fields, input.schema, input.typeName, {
688
+ currentNs: input.currentNs,
689
+ ...input.schemas !== void 0 ? { schemas: input.schemas } : {}
690
+ });
691
+ const out = {
692
+ schemaVersion: raw.schemaVersion,
693
+ streamId: raw.streamId,
694
+ sequence: raw.sequence,
695
+ shape: "single",
696
+ data: decoded
697
+ };
698
+ if (raw.final !== void 0) out.final = raw.final;
699
+ if (raw._meta !== void 0) out._meta = raw._meta;
700
+ return out;
701
+ }
702
+
703
+ //#endregion
704
+ //#region ../../packages/substrate-pack/src/wire.ts
705
+ /**
706
+ * WS-frame wire codec. Spec §8.5.
707
+ *
708
+ * Centralizes JSON-vs-pack envelope handling for WebSocket transports plus the
709
+ * precomputed decode plan that turns positional `data` tuples back into named
710
+ * objects. The plan is built once per subscription, so per-frame work is
711
+ * O(plan entries). Shared by substrate-client and the perf harness so both
712
+ * measure the same codepath.
713
+ */
714
+ /**
715
+ * Encode an outbound WS frame. Pack mode returns msgpack bytes; JSON mode
716
+ * returns stringified text. The `mode` argument is the wire-format discriminant
717
+ * — call sites can route the result to the right `WebSocket.send` overload via
718
+ * a typed `typeof wire === 'string'` branch.
719
+ */
720
+ function encodeWsFrame(value, mode) {
721
+ return mode === "pack" ? pack(value) : JSON.stringify(value);
722
+ }
723
+ /**
724
+ * Decode an inbound WS message envelope (the outer `{ id, kind, data?, ... }`
725
+ * shape — positional `data` reconstruction is a separate concern handled by
726
+ * `applyDecodePlanInPlace`).
727
+ *
728
+ * The `mode` discriminant determines how `raw` is interpreted: pack-mode
729
+ * messages arrive as `ArrayBuffer | Uint8Array | Buffer` and are msgpack-
730
+ * decoded; JSON-mode messages arrive as `string` (or, when node-ws hands the
731
+ * payload across as binary, as bytes that we coerce back to text before
732
+ * `JSON.parse`).
733
+ *
734
+ * The runtime narrowing is centralized here so callers don't reach for
735
+ * `raw as string` casts at every call site.
736
+ */
737
+ function decodeWsEnvelope(raw, mode) {
738
+ if (mode === "pack") return inbound.unpack(toBytes(raw));
739
+ if (typeof raw === "string") return JSON.parse(raw);
740
+ return JSON.parse(Buffer.from(toBytes(raw)).toString("utf8"));
741
+ }
742
+ /**
743
+ * Inbound frames come from untrusted peers: structured-clone references (and
744
+ * so cyclic values) are refused. `mapsAsObjects` keeps the default `unpack`'s
745
+ * plain-object maps. msgpackr's other built-in extensions are process-global
746
+ * and still decode, so a server checks a request with `isPlainRequestData`.
747
+ */
748
+ const inbound = new Unpackr({
749
+ structuredClone: false,
750
+ mapsAsObjects: true
751
+ });
752
+ const MAX_REQUEST_DEPTH = 64;
753
+ /**
754
+ * Whether a decoded request holds only JSON-shaped data (plus `Date`, which
755
+ * msgpack timestamps decode to), no deeper than 64 levels. A server refuses
756
+ * anything else: RegExp, Set, Map, BigInt, typed arrays and the like.
757
+ */
758
+ function isPlainRequestData(value, depth = 0) {
759
+ if (depth > MAX_REQUEST_DEPTH) return false;
760
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
761
+ if (typeof value === "number") return Number.isFinite(value);
762
+ if (value instanceof Date) return true;
763
+ if (Array.isArray(value)) return value.every((v) => isPlainRequestData(v, depth + 1));
764
+ if (typeof value !== "object") return false;
765
+ const proto = Object.getPrototypeOf(value);
766
+ if (proto !== Object.prototype && proto !== null) return false;
767
+ return Object.values(value).every((v) => isPlainRequestData(v, depth + 1));
768
+ }
769
+ function toBytes(raw) {
770
+ if (raw instanceof Uint8Array) return raw;
771
+ if (raw instanceof ArrayBuffer) return new Uint8Array(raw);
772
+ return Buffer.from(raw);
773
+ }
774
+ /**
775
+ * Build the decode plan from a frame spec map + federated schemas. Called
776
+ * once per subscription, before the first frame arrives. Keys that are
777
+ * unqualified, have no matching schema, or have no field selection are
778
+ * skipped.
779
+ */
780
+ function buildDecodePlan(frameSpec, schemas) {
781
+ const plan = [];
782
+ for (const qkey of Object.keys(frameSpec)) {
783
+ const parsed = parseQualifiedKey(qkey);
784
+ if (parsed === null) continue;
785
+ const { ns, name } = parsed;
786
+ const schema = schemas[ns];
787
+ if (schema === void 0) continue;
788
+ const spec = frameSpec[qkey];
789
+ if (spec === void 0) continue;
790
+ const fields = spec.fields;
791
+ if (fields === void 0) continue;
792
+ plan.push({
793
+ qkey,
794
+ name,
795
+ schema,
796
+ fields,
797
+ opts: {
798
+ schemas,
799
+ currentNs: ns
800
+ }
801
+ });
802
+ }
803
+ return plan;
804
+ }
805
+ /**
806
+ * Apply a precomputed decode plan to an envelope's `data` map in place.
807
+ * Mutates `envelope.data[qkey]` from positional tuple to named object/list
808
+ * for each plan entry whose qkey is present.
809
+ *
810
+ * Accepts `unknown` so both `WsResponseFrame` and the data-bearing
811
+ * `SubscribeEvent` variants flow through without a parameter-type cast at the
812
+ * call site; remove/end/error frames lack a `data` property and short-circuit
813
+ * here.
814
+ */
815
+ function applyDecodePlanInPlace(envelope, plan) {
816
+ if (envelope === null || typeof envelope !== "object") return;
817
+ const data = envelope.data;
818
+ if (data === null || data === void 0 || typeof data !== "object") return;
819
+ const map = data;
820
+ for (const entry of plan) {
821
+ const value = map[entry.qkey];
822
+ if (value === void 0) continue;
823
+ map[entry.qkey] = decodePositional(value, entry.fields, entry.schema, entry.name, entry.opts);
824
+ }
825
+ }
826
+
827
+ //#endregion
828
+ //#region ../../packages/substrate-pack/src/index.ts
829
+ /**
830
+ * WebSocket subprotocol advertised in `Sec-WebSocket-Protocol` at handshake
831
+ * time. Connections negotiating this subprotocol receive msgpack frames with
832
+ * positionally-encoded `data`; anything else falls back to JSON.
833
+ */
834
+ const WS_SUBPROTOCOL_SUBSTRATE_PACK = "substrate-pack";
835
+
836
+ //#endregion
837
+ export { assertNever as S, decodeEnvelope as _, buildDecodePlan as a, formatQualifiedKey as b, isPlainRequestData as c, PackEncodeError as d, encodeEnvelope as f, SchemaDriftError as g, PackDecodeError as h, applyDecodePlanInPlace as i, decodeStreamChunk as l, encodePositionalFromFieldDef as m, packFrame as n, decodeWsEnvelope as o, encodePositional as p, unpackFrame as r, encodeWsFrame as s, WS_SUBPROTOCOL_SUBSTRATE_PACK as t, encodeStreamChunk as u, decodePositional as v, parseQualifiedKey as x, decodePositionalFromFieldDef as y };