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