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

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 (47) hide show
  1. package/README.md +48 -6
  2. package/dist/boot-store-C5vNZJ3i.js +4065 -0
  3. package/dist/{runtime-metrics-DwpDJ8vz.d.ts → bridge-COu0Tg_h.d.ts} +2 -87
  4. package/dist/cli-BrwW4tjO.js +3144 -0
  5. package/dist/client.d.ts +129 -8
  6. package/dist/client.js +6 -5
  7. package/dist/{agent-token-BIboWOU0.js → env-utils-CGNazUNt.js} +31 -2
  8. package/dist/{errors-D4vKuwz8.d.ts → errors-BOllGhVx.d.ts} +15 -2
  9. package/dist/{index-D7mSOFlM.d.ts → index-Cp74OcmS.d.ts} +1 -1
  10. package/dist/node-version-C5FSmwJX.js +26 -0
  11. package/dist/pack.d.ts +2 -2
  12. package/dist/pack.js +1 -1
  13. package/dist/pg-edges-store-BLsbcXkk.js +381 -0
  14. package/dist/{plugin-BuQQEzL-.js → plugin-DIYm2cZE.js} +171 -18
  15. package/dist/proposals-bootstrap.js +6 -4
  16. package/dist/proposals.config.schema.json +5 -0
  17. package/dist/proposals.d.ts +14 -4
  18. package/dist/proposals.default-config.json +2 -1
  19. package/dist/proposals.js +2 -2
  20. package/dist/recall-bootstrap.js +13 -4
  21. package/dist/recall.config.schema.json +12 -0
  22. package/dist/recall.d.ts +53 -9
  23. package/dist/recall.js +2 -2
  24. package/dist/{repl-C52wyfMs.js → repl-B8gy0YM7.js} +63 -30
  25. package/dist/{row-ByLFE2Wx.d.ts → row-DwaDU4b-.d.ts} +58 -9
  26. package/dist/run-B18qtGKc.js +2012 -0
  27. package/dist/{plugin-t2g2wX0b.d.ts → schema-CijHRfuk.d.ts} +957 -16
  28. package/dist/script-C6DSa_Na.js +134 -0
  29. package/dist/sdk.d.ts +104 -16
  30. package/dist/sdk.js +5 -110
  31. package/dist/{src-DuopV8u7.js → src-Br6aDUti.js} +153 -20
  32. package/dist/{src-5hVbeiAu.js → src-D041j6GS.js} +697 -57
  33. package/dist/{src-YXlv_RyL.js → src-DK7VEQT6.js} +4099 -1040
  34. package/dist/{src-C4DzaIQZ.js → src-Dbvuel6w.js} +392 -282
  35. package/dist/{row-DK7lPZVe.js → src-DpPdw2oL.js} +11 -11
  36. package/dist/{src-zcyUofMJ.js → src-DptNGNYQ.js} +39 -15
  37. package/dist/src-gz4I1F29.js +5097 -0
  38. package/dist/substrate-admin.js +17 -781
  39. package/dist/substrate.js +4 -5476
  40. package/dist/testing.d.ts +582 -9
  41. package/dist/testing.js +39 -3
  42. package/dist/{ws-C72iVS5T.d.ts → ws-DC8OhMaV.d.ts} +2 -3
  43. package/package.json +22 -20
  44. package/dist/dataset-DOXGRz50.js +0 -1535
  45. package/dist/env-utils-B7SGmoeJ.js +0 -21
  46. package/dist/schema-g4FQLr0V.d.ts +0 -433
  47. package/dist/src-CjEwiKXw.js +0 -2327
@@ -29,8 +29,44 @@ function formatQualifiedKey(namespace, name) {
29
29
  return `${namespace}/${name}`;
30
30
  }
31
31
 
32
+ //#endregion
33
+ //#region ../../packages/substrate-types/src/schema.ts
34
+ /** Natural order of a type that declares none: newest first. */
35
+ const DEFAULT_ORDERED_BY = Object.freeze({ createdAt: "desc" });
36
+ /** The declared natural order, or {@link DEFAULT_ORDERED_BY}. */
37
+ function naturalOrderOf(schema) {
38
+ return schema.orderedBy ?? DEFAULT_ORDERED_BY;
39
+ }
40
+
32
41
  //#endregion
33
42
  //#region ../../packages/substrate-pack/src/_plan-cache.ts
43
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
44
+ /** The slot for one selection entry, or undefined for a plain field. */
45
+ function walkSlot(name, sel, fieldMap) {
46
+ if (!isObj(sel)) return void 0;
47
+ if (name === "_agg") return {
48
+ kind: "agg",
49
+ names: Object.keys(sel)
50
+ };
51
+ const walk = sel._walk;
52
+ if (!isObj(walk)) return void 0;
53
+ let type;
54
+ if (typeof walk.in === "string") type = /^[^/]+\/([^./]+)\./.exec(walk.in)?.[1];
55
+ else if (typeof walk.out === "string") {
56
+ const def = Object.hasOwn(fieldMap, walk.out) ? fieldMap[walk.out] : void 0;
57
+ if (def?.kind === "crossRef") type = def.type;
58
+ }
59
+ if (type === void 0) return void 0;
60
+ const fields = isObj(sel.fields) ? sel.fields : {};
61
+ return {
62
+ kind: "nested",
63
+ type,
64
+ fields: {
65
+ id: true,
66
+ ...fields
67
+ }
68
+ };
69
+ }
34
70
  /**
35
71
  * Lookup-or-build the per-(fields, fieldMap) plan. O(1) on hit; O(F) on miss
36
72
  * for F selected fields.
@@ -45,14 +81,29 @@ function getRowPlan$2(cache, fields, fieldMap) {
45
81
  if (cached !== void 0) return cached;
46
82
  const entries = Object.entries(fields);
47
83
  const plan = new Array(entries.length);
84
+ let nested = false;
48
85
  for (let i = 0; i < entries.length; i++) {
49
86
  const pair = entries[i];
50
- plan[i] = [
87
+ const def = Object.hasOwn(fieldMap, pair[0]) ? fieldMap[pair[0]] : void 0;
88
+ const slot = def === void 0 ? walkSlot(pair[0], pair[1], fieldMap) : void 0;
89
+ if (slot?.kind === "nested") nested = true;
90
+ plan[i] = slot === void 0 ? [
51
91
  pair[0],
52
92
  pair[1],
53
- Object.hasOwn(fieldMap, pair[0]) ? fieldMap[pair[0]] : void 0
93
+ def
94
+ ] : [
95
+ pair[0],
96
+ pair[1],
97
+ def,
98
+ slot
54
99
  ];
55
100
  }
101
+ if (nested) plan.push([
102
+ "_truncated",
103
+ true,
104
+ void 0,
105
+ { kind: "truncated" }
106
+ ]);
56
107
  perFieldMap.set(fieldMap, plan);
57
108
  return plan;
58
109
  }
@@ -104,70 +155,69 @@ function resolveFieldMap$2(schema, typeName, path, makeError) {
104
155
  }
105
156
 
106
157
  //#endregion
107
- //#region ../../packages/substrate-pack/src/decoder.ts
158
+ //#region ../../packages/substrate-pack/src/encoder.ts
108
159
  /**
109
- * Positional decoder. Spec: §7.0, §7.2.
160
+ * Positional encoder. Spec: §7.0, §7.5.
110
161
  *
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.
162
+ * Strips field names from the wire. For a selected FieldInput, emits a tuple
163
+ * of values in iteration order; the decoder reconstructs the named object
164
+ * using the same FieldInput plus the schema cached at client init. The win is
165
+ * parse time (§7.5) — msgpackr handles named objects fine, but positional
166
+ * arrays skip the key lookup per cell, which compounds across thousand-row
167
+ * responses.
115
168
  *
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.
169
+ * Contract: `encodePositional` is shape-blind. Callers decide single-vs-list
170
+ * via `PackEnvelope.shapes[key]` (§7.2) and pass either a row or an array
171
+ * of rows; the encoder emits the corresponding tuple or array-of-tuples. It does
172
+ * NOT infer list-vs-single from the value shape.
173
+ *
174
+ * Mutation responses use `encodePositionalFromFieldDef` — mutations don't
175
+ * carry a client-sent `FieldInput`, so the FieldDef declared at registration
176
+ * (MutationSchema.returns) drives the encoding directly.
121
177
  */
122
178
  /**
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.
179
+ * @internal — error thrown by the positional encoder on malformed input.
180
+ * Exported, but treat as package-private.
126
181
  */
127
- var PackDecodeError = class extends Error {
128
- name = "PackDecodeError";
182
+ var PackEncodeError = class extends Error {
183
+ name = "PackEncodeError";
129
184
  path;
130
185
  constructor(message, path) {
131
186
  super(`${message} at ${path.length === 0 ? "<root>" : path.join(".")}`);
132
187
  this.path = path.slice();
133
188
  }
134
189
  };
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);
190
+ function encodePositional(value, fields, schema, typeName, ctx) {
191
+ if (value === null || value === void 0) return null;
192
+ const plan = getRowPlan$1(fields, resolveFieldMap$1(schema, typeName, [typeName]));
193
+ if (Array.isArray(value)) return value.map((row) => encodeRowWithPlan(row, plan, schema, [typeName], ctx));
194
+ return encodeRowWithPlan(value, plan, schema, [typeName], ctx);
154
195
  }
155
196
  /**
156
- * Decode a mutation response against its declared `FieldDef`. Symmetric to
157
- * `encodePositionalFromFieldDef`.
197
+ * Encode a mutation response against its declared `FieldDef` (no client-sent
198
+ * FieldInput). Symmetric to `encodePositional` but driven entirely by the
199
+ * schema descriptor.
158
200
  *
159
- * @internal — used by `decodeEnvelope` for mutation returns. Treat as
201
+ * - `scalar` → value passes through (nullable tolerated)
202
+ * - `struct` → positional tuple over `def.fields` iteration order
203
+ * - `list` → value is an array; each element encoded against `def.of`
204
+ * - `crossRef` → value is expected to be an id scalar (eq-on-id; we don't
205
+ * recurse into the target type — mutation returns don't embed sub-rows)
206
+ *
207
+ * @internal — used by `encodeEnvelope` for mutation returns. Treat as
160
208
  * package-private.
161
209
  */
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);
210
+ function encodePositionalFromFieldDef(value, def, schema, ctx, path = []) {
211
+ if (value === null || value === void 0) return null;
212
+ return encodeFieldDef(value, def, schema, path, ctx);
165
213
  }
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);
214
+ function encodeEnvelope(envelope, ctx) {
169
215
  const rewritten = {};
170
- for (const [key, value] of Object.entries(raw.data)) {
216
+ for (const [key, value] of Object.entries(envelope.data)) {
217
+ if (isAggShape(envelope.shapes[key])) {
218
+ rewritten[key] = value;
219
+ continue;
220
+ }
171
221
  const returns = ctx.returnsByKey?.[key];
172
222
  if (returns !== void 0) {
173
223
  const currentNs = ctx.currentNsByKey[key];
@@ -176,7 +226,7 @@ function decodeEnvelope(bytes, ctx) {
176
226
  rewritten[key] = value;
177
227
  continue;
178
228
  }
179
- rewritten[key] = decodeByShapeFromDef(value, returns, schema, raw.shapes[key], {
229
+ rewritten[key] = encodePositionalForShape(value, returns, schema, envelope.shapes[key], {
180
230
  schemas: ctx.schemas,
181
231
  currentNs
182
232
  });
@@ -194,181 +244,199 @@ function decodeEnvelope(bytes, ctx) {
194
244
  rewritten[key] = value;
195
245
  continue;
196
246
  }
197
- const rawShape = raw.shapes[key];
198
- rewritten[key] = decodeByShape(value, fields, schema, typeName, Array.isArray(rawShape) ? void 0 : rawShape, {
247
+ rewritten[key] = encodePositional(value, fields, schema, typeName, {
199
248
  schemas: ctx.schemas,
200
249
  currentNs
201
250
  });
202
251
  }
203
252
  const out = {
204
- schemaVersion: raw.schemaVersion,
253
+ schemaVersion: envelope.schemaVersion,
205
254
  data: rewritten,
206
- shapes: raw.shapes
255
+ shapes: envelope.shapes
207
256
  };
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;
257
+ if (envelope._meta !== void 0) out._meta = envelope._meta;
258
+ if (envelope._pagination !== void 0) out._pagination = envelope._pagination;
259
+ if (envelope._completeness !== void 0) out._completeness = envelope._completeness;
260
+ if (envelope._diagnostics !== void 0) out._diagnostics = envelope._diagnostics;
261
+ if (envelope.errors !== void 0) out.errors = envelope.errors;
262
+ return Buffer.from(pack(out));
213
263
  }
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);
264
+ /** A shape whose value is a `{ count }` or `{ groups }` map, not rows. */
265
+ function isAggShape(shape) {
266
+ return shape === "count" || shape === "groups";
222
267
  }
223
- function decodeByShapeFromDef(value, def, schema, shape, ctx) {
268
+ /**
269
+ * Encode a single envelope value against its declared `returns` FieldDef,
270
+ * honouring the envelope's single-vs-list shape for that key. `single` encodes
271
+ * one row; `list` encodes an array of rows element-by-element.
272
+ *
273
+ * Batched mutate (§5.13): when the shape is `Array<'single' | 'list'>`, the
274
+ * value is itself `Array<unknown>` (one per-frame slot); each slot encodes
275
+ * against the same FieldDef using its own per-frame shape.
276
+ */
277
+ function encodePositionalForShape(value, def, schema, shape, ctx) {
224
278
  if (value === null || value === void 0) return null;
225
279
  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));
280
+ if (!Array.isArray(value)) throw new PackEncodeError("expected array for batched shape", []);
281
+ return value.map((elem, idx) => {
282
+ const perFrameShape = shape[idx];
283
+ return encodePositionalForShape(elem, def, schema, perFrameShape, ctx);
284
+ });
228
285
  }
229
286
  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}]`]));
287
+ if (!Array.isArray(value)) throw new PackEncodeError("expected array for list shape", []);
288
+ return value.map((elem, idx) => encodePositionalFromFieldDef(elem, def, schema, ctx, [`[${idx}]`]));
232
289
  }
233
- return decodePositionalFromFieldDef(value, def, schema, ctx);
290
+ return encodePositionalFromFieldDef(value, def, schema, ctx);
234
291
  }
235
292
  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);
293
+ return resolveFieldMap$2(schema, typeName, path, (message, p) => new PackEncodeError(message, p));
255
294
  }
256
- const DECODE_PLAN_CACHE = /* @__PURE__ */ new WeakMap();
295
+ const ENCODE_PLAN_CACHE = /* @__PURE__ */ new WeakMap();
257
296
  function getRowPlan$1(fields, fieldMap) {
258
- return getRowPlan$2(DECODE_PLAN_CACHE, fields, fieldMap);
297
+ return getRowPlan$2(ENCODE_PLAN_CACHE, fields, fieldMap);
259
298
  }
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 = {};
299
+ function encodeRowWithPlan(row, plan, schema, path, ctx) {
300
+ if (row === null || row === void 0) return null;
301
+ if (typeof row !== "object" || Array.isArray(row)) throw new PackEncodeError(`expected object row, got ${Array.isArray(row) ? "array" : typeof row}`, path);
302
+ const rowObj = row;
264
303
  const len = plan.length;
304
+ const tuple = new Array(len);
265
305
  for (let i = 0; i < len; i++) {
266
306
  const entry = plan[i];
267
307
  const field = entry[0];
268
308
  const selection = entry[1];
269
309
  const def = entry[2];
270
- const cell = tuple[i] ?? null;
310
+ const value = Object.hasOwn(rowObj, field) ? rowObj[field] : void 0;
271
311
  path.push(field);
272
- out[field] = decodeField(cell, selection, def, schema, path, ctx);
312
+ const slot = entry[3];
313
+ tuple[i] = slot === void 0 ? encodeField(value, selection, def, schema, path, ctx) : encodeWalkSlot(value, slot, schema, path, ctx);
273
314
  path.pop();
274
315
  }
275
- return out;
316
+ return tuple;
276
317
  }
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);
318
+ function encodeWalkSlot(value, slot, schema, path, ctx) {
319
+ if (value === null || value === void 0) return null;
320
+ switch (slot.kind) {
321
+ case "truncated": return value;
322
+ case "agg": {
323
+ if (typeof value !== "object" || Array.isArray(value)) throw new PackEncodeError("expected object for _agg", path);
324
+ const aggs = value;
325
+ return slot.names.map((n) => coerceScalar(Object.hasOwn(aggs, n) ? aggs[n] : null));
326
+ }
327
+ case "nested": {
328
+ if (!Array.isArray(value)) throw new PackEncodeError("expected array for nested selection", path);
329
+ const plan = getRowPlan$1(slot.fields, resolveFieldMap$1(schema, slot.type, path));
330
+ return value.map((row, idx) => {
331
+ path.push(`[${idx}]`);
332
+ const out = encodeRowWithPlan(row, plan, schema, path, ctx);
333
+ path.pop();
334
+ return out;
335
+ });
336
+ }
337
+ default: return assertNever(slot);
338
+ }
339
+ }
340
+ function encodeField(value, selection, def, schema, path, ctx) {
341
+ if (value === null || value === void 0) return null;
342
+ if (def === void 0) return selection === true ? coerceScalar(value) : value;
343
+ if (selection === true) return encodeLeaf(value, def, path);
281
344
  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);
345
+ case "scalar": throw new PackEncodeError(`field is a scalar (${def.type}); cannot select sub-fields`, path);
346
+ case "struct": return encodeStruct(value, selection, def, schema, path, ctx);
347
+ case "list": return encodeList(value, selection, def, schema, path, ctx);
348
+ case "crossRef": return encodeCrossRef(value, selection, def, schema, path, ctx);
286
349
  default: return assertNever(def);
287
350
  }
288
351
  }
289
- function decodeLeaf(cell, def, path) {
352
+ function encodeLeaf(value, def, path) {
290
353
  switch (def.kind) {
291
- case "scalar": return cell;
354
+ case "scalar": return coerceScalar(value);
292
355
  case "list":
293
- if (!Array.isArray(cell)) throw new PackDecodeError("expected array for list leaf", path);
294
- return cell;
356
+ if (!Array.isArray(value)) throw new PackEncodeError("expected array for list field", path);
357
+ return value.map((v) => coerceScalar(v));
295
358
  case "struct":
296
- case "crossRef": return cell;
359
+ case "crossRef": return value;
297
360
  default: return assertNever(def);
298
361
  }
299
362
  }
300
- function decodeStruct(cell, selection, def, schema, path, ctx) {
301
- return decodeRowWithPlan(cell, getRowPlan$1(selection, def.fields), schema, path, ctx);
363
+ function encodeStruct(value, selection, def, schema, path, ctx) {
364
+ return encodeRowWithPlan(value, getRowPlan$1(selection, def.fields), schema, path, ctx);
302
365
  }
303
- function decodeList(cell, selection, def, schema, path, ctx) {
304
- if (!Array.isArray(cell)) throw new PackDecodeError("expected array for list field", path);
366
+ function encodeList(value, selection, def, schema, path, ctx) {
367
+ if (!Array.isArray(value)) throw new PackEncodeError("expected array for list field", path);
305
368
  const inner = def.of;
306
369
  const innerPlan = inner.kind === "struct" ? getRowPlan$1(selection, inner.fields) : void 0;
307
370
  const out = [];
308
- for (let idx = 0; idx < cell.length; idx++) {
309
- const elem = cell[idx];
371
+ for (let idx = 0; idx < value.length; idx++) {
372
+ const elem = value[idx];
310
373
  if (elem === null || elem === void 0) {
311
374
  out.push(null);
312
375
  continue;
313
376
  }
314
377
  path.push(`[${idx}]`);
315
- out.push(decodeListElement(elem, selection, inner, schema, path, ctx, innerPlan));
378
+ out.push(encodeListElement(elem, selection, inner, schema, path, ctx, innerPlan));
316
379
  path.pop();
317
380
  }
318
381
  return out;
319
382
  }
320
- function decodeListElement(elem, selection, inner, schema, elemPath, ctx, structPlan) {
383
+ function encodeListElement(elem, selection, inner, schema, elemPath, ctx, structPlan) {
321
384
  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);
385
+ case "scalar": throw new PackEncodeError(`list element is scalar (${inner.type}); cannot select sub-fields`, elemPath);
386
+ case "struct": return encodeRowWithPlan(elem, structPlan ?? getRowPlan$1(selection, inner.fields), schema, elemPath, ctx);
387
+ case "list": return encodeList(elem, selection, inner, schema, elemPath, ctx);
388
+ case "crossRef": return encodeCrossRef(elem, selection, inner, schema, elemPath, ctx);
326
389
  default: return assertNever(inner);
327
390
  }
328
391
  }
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);
392
+ function encodeCrossRef(value, selection, def, schema, path, ctx) {
393
+ if (def.ns === ctx.currentNs) return encodeRowWithPlan(value, getRowPlan$1(selection, resolveFieldMap$1(schema, def.type, path)), schema, path, ctx);
331
394
  const schemas = ctx.schemas;
332
- if (schemas === void 0) throw new PackDecodeError(`cross-namespace crossRef '${def.ns}/${def.type}' requires ctx.schemas`, path);
395
+ if (schemas === void 0) throw new PackEncodeError(`cross-namespace crossRef '${def.ns}/${def.type}' requires ctx.schemas`, path);
333
396
  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, {
397
+ if (targetSchema === void 0) throw new PackEncodeError(`cross-namespace crossRef target namespace '${def.ns}' not in ctx.schemas`, path);
398
+ return encodeRowWithPlan(value, getRowPlan$1(selection, resolveFieldMap$1(targetSchema, def.type, path)), targetSchema, path, {
336
399
  ...ctx,
337
400
  currentNs: def.ns
338
401
  });
339
402
  }
340
- function decodeFieldDef(value, def, schema, path, ctx) {
403
+ function encodeFieldDef(value, def, schema, path, ctx) {
341
404
  if (value === null || value === void 0) return null;
342
405
  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;
406
+ case "scalar": return coerceScalar(value);
407
+ case "struct": return encodeStructFromDef(value, def, schema, path, ctx);
408
+ case "list": return encodeListFromDef(value, def, schema, path, ctx);
409
+ case "crossRef": return coerceScalar(value);
347
410
  default: return assertNever(def);
348
411
  }
349
412
  }
350
- const DECODE_FIELDDEF_PLAN_CACHE = /* @__PURE__ */ new WeakMap();
413
+ const ENCODE_FIELDDEF_PLAN_CACHE = /* @__PURE__ */ new WeakMap();
351
414
  function getFieldDefPlan$1(fields) {
352
- return getFieldDefPlan$2(DECODE_FIELDDEF_PLAN_CACHE, fields);
415
+ return getFieldDefPlan$2(ENCODE_FIELDDEF_PLAN_CACHE, fields);
353
416
  }
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 = {};
417
+ function encodeStructFromDef(value, def, schema, path, ctx) {
418
+ if (typeof value !== "object" || Array.isArray(value)) throw new PackEncodeError(`expected object for struct, got ${Array.isArray(value) ? "array" : typeof value}`, path);
419
+ const rowObj = value;
357
420
  const plan = getFieldDefPlan$1(def.fields);
358
421
  const len = plan.length;
422
+ const tuple = new Array(len);
359
423
  for (let i = 0; i < len; i++) {
360
424
  const entry = plan[i];
361
425
  const fieldName = entry[0];
362
426
  const sub = entry[1];
363
- const cell = value[i] ?? null;
427
+ const cell = Object.hasOwn(rowObj, fieldName) ? rowObj[fieldName] : void 0;
428
+ if (cell === void 0) {
429
+ tuple[i] = null;
430
+ continue;
431
+ }
364
432
  path.push(fieldName);
365
- out[fieldName] = decodeFieldDef(cell, sub, schema, path, ctx);
433
+ tuple[i] = encodeFieldDef(cell, sub, schema, path, ctx);
366
434
  path.pop();
367
435
  }
368
- return out;
436
+ return tuple;
369
437
  }
370
- function decodeListFromDef(value, def, schema, path, ctx) {
371
- if (!Array.isArray(value)) throw new PackDecodeError("expected array for list field", path);
438
+ function encodeListFromDef(value, def, schema, path, ctx) {
439
+ if (!Array.isArray(value)) throw new PackEncodeError("expected array for list field", path);
372
440
  const out = [];
373
441
  for (let idx = 0; idx < value.length; idx++) {
374
442
  const elem = value[idx];
@@ -377,72 +445,88 @@ function decodeListFromDef(value, def, schema, path, ctx) {
377
445
  continue;
378
446
  }
379
447
  path.push(`[${idx}]`);
380
- out.push(decodeFieldDef(elem, def.of, schema, path, ctx));
448
+ out.push(encodeFieldDef(elem, def.of, schema, path, ctx));
381
449
  path.pop();
382
450
  }
383
451
  return out;
384
452
  }
453
+ /**
454
+ * Identity today — msgpackr round-trips Dates natively. Kept as the single
455
+ * choke point for any future scalar normalisation.
456
+ */
457
+ function coerceScalar(value) {
458
+ return value;
459
+ }
385
460
 
386
461
  //#endregion
387
- //#region ../../packages/substrate-pack/src/encoder.ts
462
+ //#region ../../packages/substrate-pack/src/decoder.ts
388
463
  /**
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.
464
+ * Positional decoder. Spec: §7.0, §7.2.
397
465
  *
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.
466
+ * Mirror of `encoder.ts`. Rebuilds named objects from positional tuples using
467
+ * the same `FieldInput` the client originally sent plus the schema cached at
468
+ * init. Single-vs-list dispatch is driven by `PackEnvelope.shapes[key]`
469
+ * (§7.2) — no inference from the tuple shape.
402
470
  *
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.
471
+ * Schema drift (§7.1) is detected here when the caller passes
472
+ * `expectedSchemaVersion`: the decoder throws `SchemaDriftError` before
473
+ * decoding any data value, so drift fails loudly instead of corrupting row
474
+ * shapes. Refetch-and-retry is the caller's job. Without
475
+ * `expectedSchemaVersion` no check is made.
406
476
  */
407
477
  /**
408
- * @internal — error thrown by the positional encoder on malformed input.
409
- * Exported, but treat as package-private.
478
+ * @internal — error thrown by the positional decoder on malformed input.
479
+ * Exported, but treat as package-private; signature may change without a
480
+ * major bump.
410
481
  */
411
- var PackEncodeError = class extends Error {
412
- name = "PackEncodeError";
482
+ var PackDecodeError = class extends Error {
483
+ name = "PackDecodeError";
413
484
  path;
414
485
  constructor(message, path) {
415
486
  super(`${message} at ${path.length === 0 ? "<root>" : path.join(".")}`);
416
487
  this.path = path.slice();
417
488
  }
418
489
  };
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);
490
+ /**
491
+ * §7.1 loud-failure. Thrown by `decodeEnvelope` when the caller supplied an
492
+ * `expectedSchemaVersion` that disagrees with the envelope's declared version.
493
+ * Carries both sides of the mismatch so the caller can decide whether to
494
+ * refetch the federated schema and retry or surface the error.
495
+ */
496
+ var SchemaDriftError = class extends Error {
497
+ envelopeSchemaVersion;
498
+ expectedSchemaVersion;
499
+ name = "SchemaDriftError";
500
+ constructor(envelopeSchemaVersion, expectedSchemaVersion) {
501
+ super(`schema drift: envelope schemaVersion '${envelopeSchemaVersion}' does not match expected '${expectedSchemaVersion}'`);
502
+ this.envelopeSchemaVersion = envelopeSchemaVersion;
503
+ this.expectedSchemaVersion = expectedSchemaVersion;
504
+ }
505
+ };
506
+ function decodePositional(encoded, fields, schema, typeName, ctx) {
507
+ if (encoded === null || encoded === void 0) return null;
508
+ return decodeValueByArity(encoded, fields, resolveFieldMap(schema, typeName, [typeName]), schema, [typeName], ctx);
424
509
  }
425
510
  /**
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)
511
+ * Decode a mutation response against its declared `FieldDef`. Symmetric to
512
+ * `encodePositionalFromFieldDef`.
435
513
  *
436
- * @internal — used by `encodeEnvelope` for mutation returns. Treat as
514
+ * @internal — used by `decodeEnvelope` for mutation returns. Treat as
437
515
  * package-private.
438
516
  */
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);
517
+ function decodePositionalFromFieldDef(encoded, def, schema, ctx, path = []) {
518
+ if (encoded === null || encoded === void 0) return null;
519
+ return decodeFieldDef(encoded, def, schema, path, ctx);
442
520
  }
443
- function encodeEnvelope(envelope, ctx) {
521
+ function decodeEnvelope(bytes, ctx) {
522
+ const raw = unpack(Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes));
523
+ if (ctx.expectedSchemaVersion !== void 0 && raw.schemaVersion !== ctx.expectedSchemaVersion) throw new SchemaDriftError(raw.schemaVersion, ctx.expectedSchemaVersion);
444
524
  const rewritten = {};
445
- for (const [key, value] of Object.entries(envelope.data)) {
525
+ for (const [key, value] of Object.entries(raw.data)) {
526
+ if (isAggShape(raw.shapes[key])) {
527
+ rewritten[key] = value;
528
+ continue;
529
+ }
446
530
  const returns = ctx.returnsByKey?.[key];
447
531
  if (returns !== void 0) {
448
532
  const currentNs = ctx.currentNsByKey[key];
@@ -451,7 +535,7 @@ function encodeEnvelope(envelope, ctx) {
451
535
  rewritten[key] = value;
452
536
  continue;
453
537
  }
454
- rewritten[key] = encodePositionalForShape(value, returns, schema, envelope.shapes[key], {
538
+ rewritten[key] = decodeByShapeFromDef(value, returns, schema, raw.shapes[key], {
455
539
  schemas: ctx.schemas,
456
540
  currentNs
457
541
  });
@@ -469,171 +553,204 @@ function encodeEnvelope(envelope, ctx) {
469
553
  rewritten[key] = value;
470
554
  continue;
471
555
  }
472
- rewritten[key] = encodePositional(value, fields, schema, typeName, {
556
+ const rawShape = raw.shapes[key];
557
+ rewritten[key] = decodeByShape(value, fields, schema, typeName, Array.isArray(rawShape) || isAggShape(rawShape) ? void 0 : rawShape, {
473
558
  schemas: ctx.schemas,
474
559
  currentNs
475
560
  });
476
561
  }
477
562
  const out = {
478
- schemaVersion: envelope.schemaVersion,
563
+ schemaVersion: raw.schemaVersion,
479
564
  data: rewritten,
480
- shapes: envelope.shapes
565
+ shapes: raw.shapes
481
566
  };
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));
567
+ if (raw._meta !== void 0) out._meta = raw._meta;
568
+ if (raw._pagination !== void 0) out._pagination = raw._pagination;
569
+ if (raw._completeness !== void 0) out._completeness = raw._completeness;
570
+ if (raw._diagnostics !== void 0) out._diagnostics = raw._diagnostics;
571
+ if (raw.errors !== void 0) out.errors = raw.errors;
572
+ return out;
487
573
  }
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) {
574
+ function decodeByShape(value, fields, schema, typeName, shape, ctx) {
575
+ if (value === null || value === void 0) return null;
576
+ const plan = getRowPlan(fields, resolveFieldMap(schema, typeName, [typeName]));
577
+ if (shape === "list") {
578
+ if (!Array.isArray(value)) throw new PackDecodeError("expected array for list shape", [typeName]);
579
+ return value.map((elem) => decodeRowWithPlan(elem, plan, schema, [typeName], ctx));
580
+ }
581
+ return decodeRowWithPlan(value, plan, schema, [typeName], ctx);
582
+ }
583
+ function decodeByShapeFromDef(value, def, schema, shape, ctx) {
498
584
  if (value === null || value === void 0) return null;
499
585
  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
- });
586
+ if (!Array.isArray(value)) throw new PackDecodeError("expected array for batched shape", []);
587
+ return value.map((elem, idx) => decodeByShapeFromDef(elem, def, schema, shape[idx], ctx));
505
588
  }
506
589
  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}]`]));
590
+ if (!Array.isArray(value)) throw new PackDecodeError("expected array for list shape", []);
591
+ return value.map((elem, idx) => decodePositionalFromFieldDef(elem, def, schema, ctx, [`[${idx}]`]));
509
592
  }
510
- return encodePositionalFromFieldDef(value, def, schema, ctx);
593
+ return decodePositionalFromFieldDef(value, def, schema, ctx);
511
594
  }
512
595
  function resolveFieldMap(schema, typeName, path) {
513
- return resolveFieldMap$2(schema, typeName, path, (message, p) => new PackEncodeError(message, p));
596
+ return resolveFieldMap$2(schema, typeName, path, (message, p) => new PackDecodeError(message, p));
514
597
  }
515
- const ENCODE_PLAN_CACHE = /* @__PURE__ */ new WeakMap();
598
+ /**
599
+ * Decide whether `value` is a single tuple or a list of tuples based on its
600
+ * shape plus the FieldInput — used only by the top-level `decodePositional`
601
+ * helper (the envelope decoder uses `shapes[key]` directly). Heuristic:
602
+ * - null → null
603
+ * - Array where the first element is itself an array → list of rows
604
+ * - Array otherwise → single row (tuple)
605
+ *
606
+ * This heuristic is the ambiguity §7.2 calls out, so callers SHOULD go through
607
+ * `decodeEnvelope` to use explicit shape metadata.
608
+ */
609
+ function decodeValueByArity(value, fields, fieldMap, schema, path, ctx) {
610
+ if (value === null || value === void 0) return null;
611
+ if (!Array.isArray(value)) throw new PackDecodeError("expected array (tuple) for positional row", path);
612
+ const plan = getRowPlan(fields, fieldMap);
613
+ if (value.length > 0 && Array.isArray(value[0])) return value.map((elem) => decodeRowWithPlan(elem, plan, schema, path, ctx));
614
+ return decodeRowWithPlan(value, plan, schema, path, ctx);
615
+ }
616
+ const DECODE_PLAN_CACHE = /* @__PURE__ */ new WeakMap();
516
617
  function getRowPlan(fields, fieldMap) {
517
- return getRowPlan$2(ENCODE_PLAN_CACHE, fields, fieldMap);
618
+ return getRowPlan$2(DECODE_PLAN_CACHE, fields, fieldMap);
518
619
  }
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;
620
+ function decodeRowWithPlan(tuple, plan, schema, path, ctx) {
621
+ if (tuple === null || tuple === void 0) return null;
622
+ if (!Array.isArray(tuple)) throw new PackDecodeError("expected array (tuple) for row", path);
623
+ const out = {};
523
624
  const len = plan.length;
524
- const tuple = new Array(len);
525
625
  for (let i = 0; i < len; i++) {
526
626
  const entry = plan[i];
527
627
  const field = entry[0];
528
628
  const selection = entry[1];
529
629
  const def = entry[2];
530
- const value = Object.hasOwn(rowObj, field) ? rowObj[field] : void 0;
630
+ const cell = tuple[i] ?? null;
631
+ const slot = entry[3];
632
+ if (slot?.kind === "truncated" && cell === null) continue;
531
633
  path.push(field);
532
- tuple[i] = encodeField(value, selection, def, schema, path, ctx);
634
+ out[field] = slot === void 0 ? decodeField(cell, selection, def, schema, path, ctx) : decodeWalkSlot(cell, slot, schema, path, ctx);
533
635
  path.pop();
534
636
  }
535
- return tuple;
637
+ return out;
536
638
  }
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);
639
+ function decodeWalkSlot(cell, slot, schema, path, ctx) {
640
+ if (cell === null || cell === void 0) return null;
641
+ switch (slot.kind) {
642
+ case "truncated": return cell;
643
+ case "agg":
644
+ if (!Array.isArray(cell)) throw new PackDecodeError("expected array for _agg", path);
645
+ return Object.fromEntries(slot.names.map((n, i) => [n, cell[i] ?? null]));
646
+ case "nested": {
647
+ if (!Array.isArray(cell)) throw new PackDecodeError("expected array for nested selection", path);
648
+ const plan = getRowPlan(slot.fields, resolveFieldMap(schema, slot.type, path));
649
+ return cell.map((tuple, idx) => {
650
+ path.push(`[${idx}]`);
651
+ const out = decodeRowWithPlan(tuple, plan, schema, path, ctx);
652
+ path.pop();
653
+ return out;
654
+ });
655
+ }
656
+ default: return assertNever(slot);
657
+ }
658
+ }
659
+ function decodeField(cell, selection, def, schema, path, ctx) {
660
+ if (cell === null || cell === void 0) return null;
661
+ if (def === void 0) return cell;
662
+ if (selection === true) return decodeLeaf(cell, def, path);
541
663
  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);
664
+ case "scalar": throw new PackDecodeError(`field is a scalar (${def.type}); cannot select sub-fields`, path);
665
+ case "struct": return decodeStruct(cell, selection, def, schema, path, ctx);
666
+ case "list": return decodeList(cell, selection, def, schema, path, ctx);
667
+ case "crossRef": return decodeCrossRef(cell, selection, def, schema, path, ctx);
546
668
  default: return assertNever(def);
547
669
  }
548
670
  }
549
- function encodeLeaf(value, def, path) {
671
+ function decodeLeaf(cell, def, path) {
550
672
  switch (def.kind) {
551
- case "scalar": return coerceScalar(value);
673
+ case "scalar": return cell;
552
674
  case "list":
553
- if (!Array.isArray(value)) throw new PackEncodeError("expected array for list field", path);
554
- return value.map((v) => coerceScalar(v));
675
+ if (!Array.isArray(cell)) throw new PackDecodeError("expected array for list leaf", path);
676
+ return cell;
555
677
  case "struct":
556
- case "crossRef": return value;
678
+ case "crossRef": return cell;
557
679
  default: return assertNever(def);
558
680
  }
559
681
  }
560
- function encodeStruct(value, selection, def, schema, path, ctx) {
561
- return encodeRowWithPlan(value, getRowPlan(selection, def.fields), schema, path, ctx);
682
+ function decodeStruct(cell, selection, def, schema, path, ctx) {
683
+ return decodeRowWithPlan(cell, getRowPlan(selection, def.fields), schema, path, ctx);
562
684
  }
563
- function encodeList(value, selection, def, schema, path, ctx) {
564
- if (!Array.isArray(value)) throw new PackEncodeError("expected array for list field", path);
685
+ function decodeList(cell, selection, def, schema, path, ctx) {
686
+ if (!Array.isArray(cell)) throw new PackDecodeError("expected array for list field", path);
565
687
  const inner = def.of;
566
688
  const innerPlan = inner.kind === "struct" ? getRowPlan(selection, inner.fields) : void 0;
567
689
  const out = [];
568
- for (let idx = 0; idx < value.length; idx++) {
569
- const elem = value[idx];
690
+ for (let idx = 0; idx < cell.length; idx++) {
691
+ const elem = cell[idx];
570
692
  if (elem === null || elem === void 0) {
571
693
  out.push(null);
572
694
  continue;
573
695
  }
574
696
  path.push(`[${idx}]`);
575
- out.push(encodeListElement(elem, selection, inner, schema, path, ctx, innerPlan));
697
+ out.push(decodeListElement(elem, selection, inner, schema, path, ctx, innerPlan));
576
698
  path.pop();
577
699
  }
578
700
  return out;
579
701
  }
580
- function encodeListElement(elem, selection, inner, schema, elemPath, ctx, structPlan) {
702
+ function decodeListElement(elem, selection, inner, schema, elemPath, ctx, structPlan) {
581
703
  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);
704
+ case "scalar": throw new PackDecodeError(`list element is scalar (${inner.type}); cannot select sub-fields`, elemPath);
705
+ case "struct": return decodeRowWithPlan(elem, structPlan ?? getRowPlan(selection, inner.fields), schema, elemPath, ctx);
706
+ case "list": return decodeList(elem, selection, inner, schema, elemPath, ctx);
707
+ case "crossRef": return decodeCrossRef(elem, selection, inner, schema, elemPath, ctx);
586
708
  default: return assertNever(inner);
587
709
  }
588
710
  }
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);
711
+ function decodeCrossRef(cell, selection, def, schema, path, ctx) {
712
+ if (def.ns === ctx.currentNs) return decodeRowWithPlan(cell, getRowPlan(selection, resolveFieldMap(schema, def.type, path)), schema, path, ctx);
591
713
  const schemas = ctx.schemas;
592
- if (schemas === void 0) throw new PackEncodeError(`cross-namespace crossRef '${def.ns}/${def.type}' requires ctx.schemas`, path);
714
+ if (schemas === void 0) throw new PackDecodeError(`cross-namespace crossRef '${def.ns}/${def.type}' requires ctx.schemas`, path);
593
715
  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, {
716
+ if (targetSchema === void 0) throw new PackDecodeError(`cross-namespace crossRef target namespace '${def.ns}' not in ctx.schemas`, path);
717
+ return decodeRowWithPlan(cell, getRowPlan(selection, resolveFieldMap(targetSchema, def.type, path)), targetSchema, path, {
596
718
  ...ctx,
597
719
  currentNs: def.ns
598
720
  });
599
721
  }
600
- function encodeFieldDef(value, def, schema, path, ctx) {
722
+ function decodeFieldDef(value, def, schema, path, ctx) {
601
723
  if (value === null || value === void 0) return null;
602
724
  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);
725
+ case "scalar": return value;
726
+ case "struct": return decodeStructFromDef(value, def, schema, path, ctx);
727
+ case "list": return decodeListFromDef(value, def, schema, path, ctx);
728
+ case "crossRef": return value;
607
729
  default: return assertNever(def);
608
730
  }
609
731
  }
610
- const ENCODE_FIELDDEF_PLAN_CACHE = /* @__PURE__ */ new WeakMap();
732
+ const DECODE_FIELDDEF_PLAN_CACHE = /* @__PURE__ */ new WeakMap();
611
733
  function getFieldDefPlan(fields) {
612
- return getFieldDefPlan$2(ENCODE_FIELDDEF_PLAN_CACHE, fields);
734
+ return getFieldDefPlan$2(DECODE_FIELDDEF_PLAN_CACHE, fields);
613
735
  }
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;
736
+ function decodeStructFromDef(value, def, schema, path, ctx) {
737
+ if (!Array.isArray(value)) throw new PackDecodeError("expected array (tuple) for struct", path);
738
+ const out = {};
617
739
  const plan = getFieldDefPlan(def.fields);
618
740
  const len = plan.length;
619
- const tuple = new Array(len);
620
741
  for (let i = 0; i < len; i++) {
621
742
  const entry = plan[i];
622
743
  const fieldName = entry[0];
623
744
  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
- }
745
+ const cell = value[i] ?? null;
629
746
  path.push(fieldName);
630
- tuple[i] = encodeFieldDef(cell, sub, schema, path, ctx);
747
+ out[fieldName] = decodeFieldDef(cell, sub, schema, path, ctx);
631
748
  path.pop();
632
749
  }
633
- return tuple;
750
+ return out;
634
751
  }
635
- function encodeListFromDef(value, def, schema, path, ctx) {
636
- if (!Array.isArray(value)) throw new PackEncodeError("expected array for list field", path);
752
+ function decodeListFromDef(value, def, schema, path, ctx) {
753
+ if (!Array.isArray(value)) throw new PackDecodeError("expected array for list field", path);
637
754
  const out = [];
638
755
  for (let idx = 0; idx < value.length; idx++) {
639
756
  const elem = value[idx];
@@ -642,18 +759,11 @@ function encodeListFromDef(value, def, schema, path, ctx) {
642
759
  continue;
643
760
  }
644
761
  path.push(`[${idx}]`);
645
- out.push(encodeFieldDef(elem, def.of, schema, path, ctx));
762
+ out.push(decodeFieldDef(elem, def.of, schema, path, ctx));
646
763
  path.pop();
647
764
  }
648
765
  return out;
649
766
  }
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
767
 
658
768
  //#endregion
659
769
  //#region ../../packages/substrate-pack/src/stream-chunk.ts
@@ -834,4 +944,4 @@ function applyDecodePlanInPlace(envelope, plan) {
834
944
  const WS_SUBPROTOCOL_SUBSTRATE_PACK = "substrate-pack";
835
945
 
836
946
  //#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 };
947
+ export { parseQualifiedKey as C, formatQualifiedKey as S, encodeEnvelope as _, buildDecodePlan as a, DEFAULT_ORDERED_BY as b, isPlainRequestData as c, PackDecodeError as d, SchemaDriftError as f, PackEncodeError as g, decodePositionalFromFieldDef as h, applyDecodePlanInPlace as i, decodeStreamChunk as l, decodePositional as m, packFrame as n, decodeWsEnvelope as o, decodeEnvelope as p, unpackFrame as r, encodeWsFrame as s, WS_SUBPROTOCOL_SUBSTRATE_PACK as t, encodeStreamChunk as u, encodePositional as v, assertNever as w, naturalOrderOf as x, encodePositionalFromFieldDef as y };