@mnmal-ai/substrate 1.0.0-alpha.18 → 1.0.0-alpha.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/{boot-store-C8KrACZ5.js → boot-store-DL2Wkzun.js} +191 -268
- package/dist/{bridge-5VHZiH9o.d.ts → bridge-BhiJKwfF.d.ts} +1 -1
- package/dist/{cli-zZ7nHhY5.js → cli-BYyPsfdY.js} +25 -28
- package/dist/client.browser.js +2478 -0
- package/dist/client.d.ts +176 -164
- package/dist/client.js +5 -5
- package/dist/{errors-DHgT7Fa8.d.ts → errors-CYOaWZ8l.d.ts} +1 -1
- package/dist/{index-DKJXQ031.d.ts → index-rW7fu2Af.d.ts} +3 -11
- package/dist/{node-version-CxqcqECU.js → node-version-BlYrbY2I.js} +8 -1
- package/dist/pack.d.ts +59 -11
- package/dist/pack.js +2 -2
- package/dist/{pg-edges-store-D7etFxNK.js → pg-edges-store-B0Krqoac.js} +1 -1
- package/dist/{plugin-DcoJGEMM.js → plugin-Dk9h__NU.js} +2 -2
- package/dist/proposals-bootstrap.js +2 -2
- package/dist/proposals.d.ts +2 -2
- package/dist/proposals.js +1 -1
- package/dist/recall-bootstrap.js +2 -2
- package/dist/recall.d.ts +1 -1
- package/dist/recall.js +2 -2
- package/dist/{repl-SY8cLOZl.js → repl-D6_CBsue.js} +1 -1
- package/dist/{row-DHxnCnhA.d.ts → row-CfsHSEfB.d.ts} +4 -4
- package/dist/{run-Cr-53N3F.js → run-BJMgCcCC.js} +18 -9
- package/dist/{schema-B5WBO8yh.d.ts → schema-laGLMvMC.d.ts} +15 -40
- package/dist/{script-B-32wZGY.js → script-DgXaJY1Y.js} +1 -1
- package/dist/sdk.d.ts +6 -6
- package/dist/sdk.js +3 -3
- package/dist/{src-CdbUzLhB.js → src-B6nsPVmD.js} +201 -25
- package/dist/{src-DV6PcXym.js → src-B_oTGi3X.js} +648 -845
- package/dist/{src-BcuotITf.js → src-BcigMQdR.js} +7 -4
- package/dist/{src-DR_hUj2p.js → src-D3ACIp1y.js} +1 -1
- package/dist/{src-B4dTiEWw.js → src-Dlmuq32R.js} +3 -3
- package/dist/{src-DZfgQ2gR.js → src-DreZjBk7.js} +3 -3
- package/dist/{src-D55T3ZcP.js → src-oO0DtS6y.js} +313 -887
- package/dist/substrate-admin.js +2 -2
- package/dist/substrate.js +2 -2
- package/dist/testing.d.ts +13 -47
- package/dist/testing.js +6 -167
- package/dist/{ws-BL9nSELO.d.ts → ws-BT8kL1IF.d.ts} +4 -4
- package/package.json +21 -23
|
@@ -0,0 +1,2478 @@
|
|
|
1
|
+
import { Unpackr, unpack } from "msgpackr";
|
|
2
|
+
import { signal } from "@preact/signals-core";
|
|
3
|
+
|
|
4
|
+
//#region ../../packages/substrate-client/src/admin/onboard.ts
|
|
5
|
+
const SECOND_ADMIN = "second-admin";
|
|
6
|
+
const FIRST_AGENT = "first-agent";
|
|
7
|
+
const ONBOARD_STEPS = [
|
|
8
|
+
"reachable",
|
|
9
|
+
"auth-enabled",
|
|
10
|
+
"credential",
|
|
11
|
+
"identity",
|
|
12
|
+
"admin-capability",
|
|
13
|
+
"admin-floor",
|
|
14
|
+
SECOND_ADMIN,
|
|
15
|
+
"namespaces",
|
|
16
|
+
"key-directory",
|
|
17
|
+
FIRST_AGENT
|
|
18
|
+
];
|
|
19
|
+
const SKIPPABLE_STEPS = /* @__PURE__ */ new Set([SECOND_ADMIN, FIRST_AGENT]);
|
|
20
|
+
/** The checklist marks every surface draws, so the CLI and the TUI cannot drift. */
|
|
21
|
+
const STEP_MARKS = {
|
|
22
|
+
done: "✓",
|
|
23
|
+
todo: "·",
|
|
24
|
+
blocked: "⊘",
|
|
25
|
+
skipped: "↷"
|
|
26
|
+
};
|
|
27
|
+
/** Marks the step the operator is on: the first `todo`. */
|
|
28
|
+
const CURRENT_MARK = "▶";
|
|
29
|
+
const NO_BOOTSTRAP_FIX = "No admin credential resolves, and `bootstrap` needs SUBSTRATE_DATABASE_URL (a postgres:// URL) — run onboard where the database is reachable, or set SUBSTRATE_ADMIN_TOKEN / SUBSTRATE_ADMIN_KEY_PATH + SUBSTRATE_ADMIN_KEY_ID for an existing admin.";
|
|
30
|
+
function fromCheck(name, check) {
|
|
31
|
+
const base = {
|
|
32
|
+
name,
|
|
33
|
+
optional: false,
|
|
34
|
+
skippable: false
|
|
35
|
+
};
|
|
36
|
+
if (check === void 0) return {
|
|
37
|
+
...base,
|
|
38
|
+
status: "blocked",
|
|
39
|
+
detail: "not reported — an earlier step stopped the run"
|
|
40
|
+
};
|
|
41
|
+
if (check.status === "ok") return {
|
|
42
|
+
...base,
|
|
43
|
+
status: "done",
|
|
44
|
+
detail: check.detail
|
|
45
|
+
};
|
|
46
|
+
if (check.status === "skip") return {
|
|
47
|
+
...base,
|
|
48
|
+
status: "blocked",
|
|
49
|
+
detail: check.detail
|
|
50
|
+
};
|
|
51
|
+
return {
|
|
52
|
+
...base,
|
|
53
|
+
status: "todo",
|
|
54
|
+
detail: check.detail,
|
|
55
|
+
...check.fix !== void 0 ? { fix: check.fix } : {}
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function fromGoal(goal, skipped) {
|
|
59
|
+
const base = {
|
|
60
|
+
name: goal.name,
|
|
61
|
+
optional: goal.optional,
|
|
62
|
+
skippable: true
|
|
63
|
+
};
|
|
64
|
+
if (!goal.measured) return {
|
|
65
|
+
...base,
|
|
66
|
+
status: "blocked",
|
|
67
|
+
detail: goal.detail.blocked
|
|
68
|
+
};
|
|
69
|
+
if (goal.met) return {
|
|
70
|
+
...base,
|
|
71
|
+
status: "done",
|
|
72
|
+
detail: goal.detail.met
|
|
73
|
+
};
|
|
74
|
+
if (skipped.has(goal.name)) return {
|
|
75
|
+
...base,
|
|
76
|
+
status: "skipped",
|
|
77
|
+
detail: goal.detail.unmet
|
|
78
|
+
};
|
|
79
|
+
return {
|
|
80
|
+
...base,
|
|
81
|
+
status: "todo",
|
|
82
|
+
detail: goal.detail.unmet,
|
|
83
|
+
fix: goal.fix,
|
|
84
|
+
action: goal.action
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
function planOnboarding(result, opts) {
|
|
88
|
+
const byName = new Map(result.checks.map((c) => [c.name, c]));
|
|
89
|
+
const { facts } = result;
|
|
90
|
+
const steps = [];
|
|
91
|
+
for (const name of ONBOARD_STEPS) {
|
|
92
|
+
if (name === SECOND_ADMIN) {
|
|
93
|
+
const admins = facts.adminKids;
|
|
94
|
+
steps.push(fromGoal({
|
|
95
|
+
name,
|
|
96
|
+
optional: false,
|
|
97
|
+
measured: byName.get("admin-floor")?.status === "ok" && admins !== void 0,
|
|
98
|
+
met: (admins?.length ?? 0) >= 2,
|
|
99
|
+
detail: {
|
|
100
|
+
met: `${admins?.length ?? 0} admin keys — succession is possible`,
|
|
101
|
+
unmet: "one admin key. Losing it locks this deployment out of its own admin surface, and the floor will refuse to revoke it.",
|
|
102
|
+
blocked: "not measured — admin-floor did not pass"
|
|
103
|
+
},
|
|
104
|
+
fix: "Register a second admin key, held somewhere other than the first.",
|
|
105
|
+
action: { kind: "register-admin" }
|
|
106
|
+
}, opts.skipped));
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
if (name === FIRST_AGENT) {
|
|
110
|
+
const agents = facts.agentKids;
|
|
111
|
+
steps.push(fromGoal({
|
|
112
|
+
name,
|
|
113
|
+
optional: true,
|
|
114
|
+
measured: agents !== void 0,
|
|
115
|
+
met: (agents?.length ?? 0) > 0,
|
|
116
|
+
detail: {
|
|
117
|
+
met: `${agents?.length ?? 0} agent identities with a live key`,
|
|
118
|
+
unmet: "no agent identity yet — register one to exercise the route and directory",
|
|
119
|
+
blocked: "not measured — the directory could not be read"
|
|
120
|
+
},
|
|
121
|
+
fix: "Register a first agent identity.",
|
|
122
|
+
action: { kind: "register-agent" }
|
|
123
|
+
}, opts.skipped));
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
const step = fromCheck(name, byName.get(name));
|
|
127
|
+
if (step.status !== "todo") {
|
|
128
|
+
steps.push(step);
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
if (name === "credential") {
|
|
132
|
+
steps.push(opts.canBootstrap ? {
|
|
133
|
+
...step,
|
|
134
|
+
action: { kind: "bootstrap" }
|
|
135
|
+
} : opts.explainNoBootstrap === false ? step : {
|
|
136
|
+
...step,
|
|
137
|
+
fix: NO_BOOTSTRAP_FIX
|
|
138
|
+
});
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
const retired = facts.retiredWithLiveKey ?? [];
|
|
142
|
+
if (name === "key-directory" && retired.length > 0) {
|
|
143
|
+
steps.push({
|
|
144
|
+
...step,
|
|
145
|
+
action: {
|
|
146
|
+
kind: "revoke",
|
|
147
|
+
kids: retired
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
steps.push(step);
|
|
153
|
+
}
|
|
154
|
+
return steps;
|
|
155
|
+
}
|
|
156
|
+
/** The step the operator is on: the first one still to do. */
|
|
157
|
+
function currentStep(steps) {
|
|
158
|
+
return steps.find((s) => s.status === "todo");
|
|
159
|
+
}
|
|
160
|
+
/** True while any required step is still to do — the `--check` verdict. */
|
|
161
|
+
function requiredOutstanding(steps) {
|
|
162
|
+
return steps.some((s) => s.status === "todo" && !s.optional);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
//#endregion
|
|
166
|
+
//#region ../../packages/substrate-client/src/admin/surgery.ts
|
|
167
|
+
/** Mirrors BACKFILL_MAX_ROWS in substrate-compose; the server enforces it. */
|
|
168
|
+
const BACKFILL_CHUNK = 5e3;
|
|
169
|
+
/**
|
|
170
|
+
* A chunk was refused. `chunksDone` chunks were already sent (and, on apply, WRITTEN); `partial` sums them.
|
|
171
|
+
*
|
|
172
|
+
* `cause` is the real failure and may be an `AuthError` (a rejected admin key) or a
|
|
173
|
+
* `NetworkError` (including one wrapping an `AbortError`). Callers must unwrap `cause`
|
|
174
|
+
* before applying an auth-lock rule or abort handling.
|
|
175
|
+
*
|
|
176
|
+
* `partial.applied` true means at least one chunk was accepted and written; `chunksDone` says how
|
|
177
|
+
* many. `false` does NOT prove nothing was written: a first chunk refused with anything but a 4xx
|
|
178
|
+
* may have partly written (below). A refusal with a 4xx status guarantees the failing chunk wrote nothing;
|
|
179
|
+
* anything else (a 5xx such as `verify_failed`, a dropped connection, an abort) may have
|
|
180
|
+
* partly written the failing chunk, since the route writes in non-transactional 200-row batches.
|
|
181
|
+
*/
|
|
182
|
+
var AdminBackfillError = class extends Error {
|
|
183
|
+
cause;
|
|
184
|
+
chunksDone;
|
|
185
|
+
chunks;
|
|
186
|
+
partial;
|
|
187
|
+
name = "AdminBackfillError";
|
|
188
|
+
constructor(cause, chunksDone, chunks, partial) {
|
|
189
|
+
super(`backfill stopped at chunk ${chunksDone + 1} of ${chunks}: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
190
|
+
this.cause = cause;
|
|
191
|
+
this.chunksDone = chunksDone;
|
|
192
|
+
this.chunks = chunks;
|
|
193
|
+
this.partial = partial;
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
const sig$1 = (o) => o.signal !== void 0 ? { signal: o.signal } : {};
|
|
197
|
+
function createSurgeryApi(t) {
|
|
198
|
+
const post = async (path, body, o) => await (await t.raw(path, {
|
|
199
|
+
method: "POST",
|
|
200
|
+
body,
|
|
201
|
+
...sig$1(o)
|
|
202
|
+
})).json();
|
|
203
|
+
return {
|
|
204
|
+
async backfill(input, o = {}) {
|
|
205
|
+
const entries = Object.entries(input.values);
|
|
206
|
+
const chunks = Math.ceil(entries.length / BACKFILL_CHUNK);
|
|
207
|
+
const apply = input.apply === true;
|
|
208
|
+
let write = 0;
|
|
209
|
+
let kept = 0;
|
|
210
|
+
let unchanged = 0;
|
|
211
|
+
const missing = [];
|
|
212
|
+
const counts = {};
|
|
213
|
+
const summary = (applied = apply) => ({
|
|
214
|
+
requested: entries.length,
|
|
215
|
+
write,
|
|
216
|
+
kept,
|
|
217
|
+
unchanged,
|
|
218
|
+
missing: [...missing],
|
|
219
|
+
counts: { ...counts },
|
|
220
|
+
applied,
|
|
221
|
+
chunks
|
|
222
|
+
});
|
|
223
|
+
for (let index = 0; index < chunks; index++) {
|
|
224
|
+
const slice = entries.slice(index * BACKFILL_CHUNK, (index + 1) * BACKFILL_CHUNK);
|
|
225
|
+
let body;
|
|
226
|
+
try {
|
|
227
|
+
body = await post("/substrate/v1/_system/backfill-field", {
|
|
228
|
+
namespace: input.namespace,
|
|
229
|
+
type: input.type,
|
|
230
|
+
field: input.field,
|
|
231
|
+
apply,
|
|
232
|
+
overwrite: input.overwrite === true,
|
|
233
|
+
values: Object.fromEntries(slice)
|
|
234
|
+
}, o);
|
|
235
|
+
} catch (err) {
|
|
236
|
+
throw new AdminBackfillError(err, index, chunks, summary(apply && index > 0));
|
|
237
|
+
}
|
|
238
|
+
write += Number(body.write ?? 0);
|
|
239
|
+
kept += Number(body.kept ?? 0);
|
|
240
|
+
unchanged += Number(body.unchanged ?? 0);
|
|
241
|
+
if (Array.isArray(body.missing)) missing.push(...body.missing);
|
|
242
|
+
for (const [k, n] of Object.entries(body.counts ?? {})) counts[k] = (counts[k] ?? 0) + n;
|
|
243
|
+
o.onChunk?.({
|
|
244
|
+
index,
|
|
245
|
+
chunks,
|
|
246
|
+
body
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
return summary();
|
|
250
|
+
},
|
|
251
|
+
reindexPage(input, o = {}) {
|
|
252
|
+
const body = {
|
|
253
|
+
namespace: input.namespace,
|
|
254
|
+
type: input.type
|
|
255
|
+
};
|
|
256
|
+
if (input.cursor !== void 0) body.cursor = input.cursor;
|
|
257
|
+
if (input.limit !== void 0) body.limit = input.limit;
|
|
258
|
+
return post("/substrate/v1/embed/reindex", body, o);
|
|
259
|
+
},
|
|
260
|
+
async embedStats(o = {}) {
|
|
261
|
+
return await (await t.raw("/substrate/v1/embed-stats", {
|
|
262
|
+
method: "GET",
|
|
263
|
+
...sig$1(o)
|
|
264
|
+
})).json();
|
|
265
|
+
},
|
|
266
|
+
dropNamespace(input, o = {}) {
|
|
267
|
+
const body = {
|
|
268
|
+
namespace: input.namespace,
|
|
269
|
+
confirm: input.confirm
|
|
270
|
+
};
|
|
271
|
+
if (input.cascade !== void 0) body.cascade = input.cascade;
|
|
272
|
+
if (input.dryRun !== void 0) body.dryRun = input.dryRun;
|
|
273
|
+
return post("/substrate/v1/_system/drop-namespace", body, o);
|
|
274
|
+
},
|
|
275
|
+
dropType(input, o = {}) {
|
|
276
|
+
const body = {
|
|
277
|
+
namespace: input.namespace,
|
|
278
|
+
type: input.type,
|
|
279
|
+
confirm: input.confirm
|
|
280
|
+
};
|
|
281
|
+
if (input.cascade !== void 0) body.cascade = input.cascade;
|
|
282
|
+
if (input.dryRun !== void 0) body.dryRun = input.dryRun;
|
|
283
|
+
return post("/substrate/v1/_system/drop-type", body, o);
|
|
284
|
+
},
|
|
285
|
+
normalise(input, o = {}) {
|
|
286
|
+
const body = {
|
|
287
|
+
namespace: input.namespace,
|
|
288
|
+
type: input.type,
|
|
289
|
+
field: input.field
|
|
290
|
+
};
|
|
291
|
+
if (input.reject !== void 0) body.reject = [...input.reject];
|
|
292
|
+
if (input.apply === true) body.apply = true;
|
|
293
|
+
return post("/substrate/v1/_system/normalise-vocab", body, o);
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
//#endregion
|
|
299
|
+
//#region ../../packages/substrate-types/src/assert-never.ts
|
|
300
|
+
/**
|
|
301
|
+
* Exhaustiveness guard for the `default:` arm of a `switch` over a
|
|
302
|
+
* discriminated union. An unhandled variant makes the call fail to
|
|
303
|
+
* type-check; at runtime it throws rather than returning `undefined`.
|
|
304
|
+
*/
|
|
305
|
+
function assertNever(x) {
|
|
306
|
+
throw new Error(`unhandled variant: ${JSON.stringify(x)}`);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
//#endregion
|
|
310
|
+
//#region ../../packages/substrate-types/src/dataset.ts
|
|
311
|
+
const DEFAULT_FILTER_WRITE_LIMITS = Object.freeze({
|
|
312
|
+
maxMatch: 1e4,
|
|
313
|
+
idsCap: 1e3
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
//#endregion
|
|
317
|
+
//#region ../../packages/substrate-types/src/env-utils.ts
|
|
318
|
+
/**
|
|
319
|
+
* `url` with its trailing slashes removed, for joining a configured base URL
|
|
320
|
+
* to a path. A loop rather than `/\/+$/`, which backtracks quadratically on a
|
|
321
|
+
* long run of slashes that does not end the string.
|
|
322
|
+
*/
|
|
323
|
+
function trimTrailingSlashes(url) {
|
|
324
|
+
let end = url.length;
|
|
325
|
+
while (end > 0 && url.charCodeAt(end - 1) === 47) end--;
|
|
326
|
+
return url.slice(0, end);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
//#endregion
|
|
330
|
+
//#region ../../packages/substrate-types/src/expression.ts
|
|
331
|
+
const sig = (name, args, returns, description) => ({
|
|
332
|
+
name,
|
|
333
|
+
args,
|
|
334
|
+
returns,
|
|
335
|
+
description
|
|
336
|
+
});
|
|
337
|
+
const CMP = "both sides the same type; int64 and number compare as number.";
|
|
338
|
+
const EXPR_FUNCTIONS = [
|
|
339
|
+
sig("add", ["number", "number"], "any", "Sum; int64 when both are int64 (or a safe-integer literal), else number. Errors on overflow."),
|
|
340
|
+
sig("sub", ["number", "number"], "any", "Difference; int64 when both are int64, else number. Errors on overflow."),
|
|
341
|
+
sig("mul", ["number", "number"], "any", "Product; int64 when both are int64, else number. Errors on overflow, and on a nonzero product that underflows to zero."),
|
|
342
|
+
sig("div", ["number", "number"], "number", "Quotient as a number; null when the divisor is zero. Errors on overflow, and on a nonzero quotient that underflows to zero."),
|
|
343
|
+
sig("mod", ["int64", "int64"], "int64", "Remainder of int64 arguments (a safe-integer literal counts); null when the divisor is zero."),
|
|
344
|
+
sig("neg", ["number"], "any", "Arithmetic negation; keeps int64."),
|
|
345
|
+
sig("eq", ["any", "any"], "boolean", `Equal; ${CMP}`),
|
|
346
|
+
sig("neq", ["any", "any"], "boolean", `Not equal; ${CMP}`),
|
|
347
|
+
sig("gt", ["any", "any"], "boolean", `Greater than; ${CMP}`),
|
|
348
|
+
sig("gte", ["any", "any"], "boolean", `Greater than or equal; ${CMP}`),
|
|
349
|
+
sig("lt", ["any", "any"], "boolean", `Less than; ${CMP}`),
|
|
350
|
+
sig("lte", ["any", "any"], "boolean", `Less than or equal; ${CMP}`),
|
|
351
|
+
sig("and", "variadic", "boolean", "True when every boolean argument (one or more) is true."),
|
|
352
|
+
sig("or", "variadic", "boolean", "True when any boolean argument (one or more) is true."),
|
|
353
|
+
sig("not", ["boolean"], "boolean", "Boolean negation."),
|
|
354
|
+
sig("isNull", ["any"], "boolean", "True when its one argument is null; any type."),
|
|
355
|
+
sig("in", "variadic", "boolean", "True when the first argument equals any later one (two or more arguments share a type)."),
|
|
356
|
+
sig("length", ["string"], "number", "Length in characters."),
|
|
357
|
+
sig("lower", ["string"], "string", "Lower-cased text; ASCII letters only, every other character is unchanged."),
|
|
358
|
+
sig("upper", ["string"], "string", "Upper-cased text; ASCII letters only, every other character is unchanged."),
|
|
359
|
+
sig("substring", [
|
|
360
|
+
"string",
|
|
361
|
+
"number",
|
|
362
|
+
"number"
|
|
363
|
+
], "string", "Substring from a 1-based start for a length."),
|
|
364
|
+
sig("concat", "variadic", "string", "Concatenation of one or more string arguments."),
|
|
365
|
+
sig("like", ["string", "likePattern"], "boolean", "SQL LIKE, case-sensitive: % and _ wildcards, backslash escape. The pattern is a lit that does not end in an unescaped backslash."),
|
|
366
|
+
sig("notLike", ["string", "likePattern"], "boolean", "Negated SQL LIKE, case-sensitive."),
|
|
367
|
+
sig("regexpMatch", ["string", "pattern"], "boolean", "True when the portable-subset regex (a lit) matches anywhere."),
|
|
368
|
+
sig("regexpReplace", [
|
|
369
|
+
"string",
|
|
370
|
+
"pattern",
|
|
371
|
+
"string"
|
|
372
|
+
], "string", "Replace the leftmost-longest regex (a lit) match; the replacement may use \\1 to \\9. The pattern may use capturing groups or |, not both."),
|
|
373
|
+
sig("dateTrunc", ["unit", "date"], "date", "Truncate a date (UTC) to a unit given as a lit."),
|
|
374
|
+
sig("extract", ["unit", "date"], "number", "A date part (UTC) as a number; the unit is a lit."),
|
|
375
|
+
sig("case", "variadic", "any", "Pairs [cond, then] then a final else; branches share a type."),
|
|
376
|
+
sig("coalesce", "variadic", "any", "First non-null of one or more arguments sharing a type.")
|
|
377
|
+
];
|
|
378
|
+
|
|
379
|
+
//#endregion
|
|
380
|
+
//#region ../../packages/substrate-types/src/qualified-key.ts
|
|
381
|
+
function parseQualifiedKey(key) {
|
|
382
|
+
const slash = key.indexOf("/");
|
|
383
|
+
if (slash <= 0 || slash === key.length - 1) return null;
|
|
384
|
+
return {
|
|
385
|
+
ns: key.slice(0, slash),
|
|
386
|
+
name: key.slice(slash + 1)
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
//#endregion
|
|
391
|
+
//#region ../../packages/substrate-types/src/schema.ts
|
|
392
|
+
/** Natural order of a type that declares none: newest first. */
|
|
393
|
+
const DEFAULT_ORDERED_BY = Object.freeze({ createdAt: "desc" });
|
|
394
|
+
|
|
395
|
+
//#endregion
|
|
396
|
+
//#region ../../packages/substrate-pack/src/_plan-cache.ts
|
|
397
|
+
const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
398
|
+
/** The slot for one selection entry, or undefined for a plain field. */
|
|
399
|
+
function walkSlot(name, sel, fieldMap) {
|
|
400
|
+
if (!isObj(sel)) return void 0;
|
|
401
|
+
if (name === "_agg") return {
|
|
402
|
+
kind: "agg",
|
|
403
|
+
names: Object.keys(sel)
|
|
404
|
+
};
|
|
405
|
+
const walk = sel._walk;
|
|
406
|
+
if (!isObj(walk)) return void 0;
|
|
407
|
+
let type;
|
|
408
|
+
if (typeof walk.in === "string") type = /^[^/]+\/([^./]+)\./.exec(walk.in)?.[1];
|
|
409
|
+
else if (typeof walk.out === "string") {
|
|
410
|
+
const def = Object.hasOwn(fieldMap, walk.out) ? fieldMap[walk.out] : void 0;
|
|
411
|
+
if (def?.kind === "crossRef") type = def.type;
|
|
412
|
+
}
|
|
413
|
+
if (type === void 0) return void 0;
|
|
414
|
+
const fields = isObj(sel.fields) ? sel.fields : {};
|
|
415
|
+
return {
|
|
416
|
+
kind: "nested",
|
|
417
|
+
type,
|
|
418
|
+
fields: {
|
|
419
|
+
id: true,
|
|
420
|
+
...fields
|
|
421
|
+
}
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Lookup-or-build the per-(fields, fieldMap) plan. O(1) on hit; O(F) on miss
|
|
426
|
+
* for F selected fields.
|
|
427
|
+
*/
|
|
428
|
+
function getRowPlan$1(cache, fields, fieldMap) {
|
|
429
|
+
let perFieldMap = cache.get(fields);
|
|
430
|
+
if (perFieldMap === void 0) {
|
|
431
|
+
perFieldMap = /* @__PURE__ */ new WeakMap();
|
|
432
|
+
cache.set(fields, perFieldMap);
|
|
433
|
+
}
|
|
434
|
+
const cached = perFieldMap.get(fieldMap);
|
|
435
|
+
if (cached !== void 0) return cached;
|
|
436
|
+
const entries = Object.entries(fields);
|
|
437
|
+
const plan = new Array(entries.length);
|
|
438
|
+
let nested = false;
|
|
439
|
+
for (let i = 0; i < entries.length; i++) {
|
|
440
|
+
const pair = entries[i];
|
|
441
|
+
const def = Object.hasOwn(fieldMap, pair[0]) ? fieldMap[pair[0]] : void 0;
|
|
442
|
+
const slot = def === void 0 ? walkSlot(pair[0], pair[1], fieldMap) : void 0;
|
|
443
|
+
if (slot?.kind === "nested") nested = true;
|
|
444
|
+
plan[i] = slot === void 0 ? [
|
|
445
|
+
pair[0],
|
|
446
|
+
pair[1],
|
|
447
|
+
def
|
|
448
|
+
] : [
|
|
449
|
+
pair[0],
|
|
450
|
+
pair[1],
|
|
451
|
+
def,
|
|
452
|
+
slot
|
|
453
|
+
];
|
|
454
|
+
}
|
|
455
|
+
if (nested) plan.push([
|
|
456
|
+
"_truncated",
|
|
457
|
+
true,
|
|
458
|
+
void 0,
|
|
459
|
+
{ kind: "truncated" }
|
|
460
|
+
]);
|
|
461
|
+
perFieldMap.set(fieldMap, plan);
|
|
462
|
+
return plan;
|
|
463
|
+
}
|
|
464
|
+
/**
|
|
465
|
+
* Lookup-or-build the per-fields FieldDefPlan. O(1) on hit; O(F) on miss.
|
|
466
|
+
*/
|
|
467
|
+
function getFieldDefPlan$1(cache, fields) {
|
|
468
|
+
const cached = cache.get(fields);
|
|
469
|
+
if (cached !== void 0) return cached;
|
|
470
|
+
const entries = Object.entries(fields);
|
|
471
|
+
const plan = new Array(entries.length);
|
|
472
|
+
for (let i = 0; i < entries.length; i++) {
|
|
473
|
+
const pair = entries[i];
|
|
474
|
+
plan[i] = [pair[0], pair[1]];
|
|
475
|
+
}
|
|
476
|
+
cache.set(fields, plan);
|
|
477
|
+
return plan;
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* Schema lookup for a type name. Tries the regular type registry first; falls
|
|
481
|
+
* back to mutations whose `returns` is a struct (the natural lookup for
|
|
482
|
+
* nested selection through a mutation-typed frame key). Returns `undefined`
|
|
483
|
+
* when the type is unknown — callers throw their own typed error with the
|
|
484
|
+
* appropriate path context.
|
|
485
|
+
*
|
|
486
|
+
* Non-struct mutation returns (e.g. delete's `{id, deleted}`) intentionally
|
|
487
|
+
* surface as an empty field map rather than undefined — the lookup
|
|
488
|
+
* succeeded; the type has no nested selection. Both codecs treat the empty
|
|
489
|
+
* map as "no fields to project".
|
|
490
|
+
*/
|
|
491
|
+
function lookupFieldMap(schema, typeName) {
|
|
492
|
+
const typeEntry = Object.hasOwn(schema.types, typeName) ? schema.types[typeName] : void 0;
|
|
493
|
+
if (typeEntry !== void 0) return typeEntry.fields;
|
|
494
|
+
const mutationEntry = Object.hasOwn(schema.mutations, typeName) ? schema.mutations[typeName] : void 0;
|
|
495
|
+
if (mutationEntry !== void 0) {
|
|
496
|
+
const ret = mutationEntry.returns;
|
|
497
|
+
if (ret.kind === "struct") return ret.fields;
|
|
498
|
+
return {};
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* Resolve a type's field map, or throw the error `makeError` builds when the
|
|
503
|
+
* type is unknown.
|
|
504
|
+
*/
|
|
505
|
+
function resolveFieldMap$1(schema, typeName, path, makeError) {
|
|
506
|
+
const fieldMap = lookupFieldMap(schema, typeName);
|
|
507
|
+
if (fieldMap === void 0) throw makeError(`unknown type '${typeName}' in schema`, path);
|
|
508
|
+
return fieldMap;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
//#endregion
|
|
512
|
+
//#region ../../packages/substrate-pack/src/encoder.ts
|
|
513
|
+
/**
|
|
514
|
+
* @internal — error thrown by the positional encoder on malformed input.
|
|
515
|
+
* Exported, but treat as package-private.
|
|
516
|
+
*/
|
|
517
|
+
var PackEncodeError = class extends Error {
|
|
518
|
+
name = "PackEncodeError";
|
|
519
|
+
path;
|
|
520
|
+
constructor(message, path) {
|
|
521
|
+
super(`${message} at ${path.length === 0 ? "<root>" : path.join(".")}`);
|
|
522
|
+
this.path = path.slice();
|
|
523
|
+
}
|
|
524
|
+
};
|
|
525
|
+
/** A shape whose value is a `{ count }` or `{ groups }` map, not rows. */
|
|
526
|
+
function isAggShape(shape) {
|
|
527
|
+
return shape === "count" || shape === "groups";
|
|
528
|
+
}
|
|
529
|
+
/** Frame `idx`'s return shape: its own entry for a batched key, else the key's one shape. */
|
|
530
|
+
function frameDef(def, idx) {
|
|
531
|
+
if (!Array.isArray(def)) return def;
|
|
532
|
+
const one = def[idx];
|
|
533
|
+
if (one === void 0) throw new PackEncodeError(`no return shape for frame ${idx}`, []);
|
|
534
|
+
return one;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
//#endregion
|
|
538
|
+
//#region ../../packages/substrate-pack/src/decoder.ts
|
|
539
|
+
/**
|
|
540
|
+
* Positional decoder. Spec: §7.0, §7.2.
|
|
541
|
+
*
|
|
542
|
+
* Mirror of `encoder.ts`. Rebuilds named objects from positional tuples using
|
|
543
|
+
* the same `FieldInput` the client originally sent plus the schema cached at
|
|
544
|
+
* init. Single-vs-list dispatch is driven by `PackEnvelope.shapes[key]`
|
|
545
|
+
* (§7.2) — no inference from the tuple shape.
|
|
546
|
+
*
|
|
547
|
+
* Schema drift (§7.1) is detected here when the caller passes
|
|
548
|
+
* `expectedSchemaVersion`: the decoder throws `SchemaDriftError` before
|
|
549
|
+
* decoding any data value, so drift fails loudly instead of corrupting row
|
|
550
|
+
* shapes. Refetch-and-retry is the caller's job. Without
|
|
551
|
+
* `expectedSchemaVersion` no check is made.
|
|
552
|
+
*/
|
|
553
|
+
/**
|
|
554
|
+
* @internal — error thrown by the positional decoder on malformed input.
|
|
555
|
+
* Exported, but treat as package-private; signature may change without a
|
|
556
|
+
* major bump.
|
|
557
|
+
*/
|
|
558
|
+
var PackDecodeError = class extends Error {
|
|
559
|
+
name = "PackDecodeError";
|
|
560
|
+
path;
|
|
561
|
+
constructor(message, path) {
|
|
562
|
+
super(`${message} at ${path.length === 0 ? "<root>" : path.join(".")}`);
|
|
563
|
+
this.path = path.slice();
|
|
564
|
+
}
|
|
565
|
+
};
|
|
566
|
+
/**
|
|
567
|
+
* §7.1 loud-failure. Thrown by `decodeEnvelope` when the caller supplied an
|
|
568
|
+
* `expectedSchemaVersion` that disagrees with the envelope's declared version.
|
|
569
|
+
* Carries both sides of the mismatch so the caller can decide whether to
|
|
570
|
+
* refetch the federated schema and retry or surface the error.
|
|
571
|
+
*/
|
|
572
|
+
var SchemaDriftError = class extends Error {
|
|
573
|
+
envelopeSchemaVersion;
|
|
574
|
+
expectedSchemaVersion;
|
|
575
|
+
name = "SchemaDriftError";
|
|
576
|
+
constructor(envelopeSchemaVersion, expectedSchemaVersion) {
|
|
577
|
+
super(`schema drift: envelope schemaVersion '${envelopeSchemaVersion}' does not match expected '${expectedSchemaVersion}'`);
|
|
578
|
+
this.envelopeSchemaVersion = envelopeSchemaVersion;
|
|
579
|
+
this.expectedSchemaVersion = expectedSchemaVersion;
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
function decodePositional(encoded, fields, schema, typeName, ctx) {
|
|
583
|
+
if (encoded === null || encoded === void 0) return null;
|
|
584
|
+
return decodeValueByArity(encoded, fields, resolveFieldMap(schema, typeName, [typeName]), schema, [typeName], ctx);
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* Decode a mutation response against its declared `FieldDef`. Symmetric to
|
|
588
|
+
* `encodePositionalFromFieldDef`.
|
|
589
|
+
*
|
|
590
|
+
* @internal — used by `decodeEnvelope` for mutation returns. Treat as
|
|
591
|
+
* package-private.
|
|
592
|
+
*/
|
|
593
|
+
function decodePositionalFromFieldDef(encoded, def, schema, ctx, path = []) {
|
|
594
|
+
if (encoded === null || encoded === void 0) return null;
|
|
595
|
+
return decodeFieldDef(encoded, def, schema, path, ctx);
|
|
596
|
+
}
|
|
597
|
+
function decodeEnvelope(bytes, ctx) {
|
|
598
|
+
const raw = unpack(bytes);
|
|
599
|
+
if (ctx.expectedSchemaVersion !== void 0 && raw.schemaVersion !== ctx.expectedSchemaVersion) throw new SchemaDriftError(raw.schemaVersion, ctx.expectedSchemaVersion);
|
|
600
|
+
const rewritten = {};
|
|
601
|
+
for (const [key, value] of Object.entries(raw.data)) {
|
|
602
|
+
if (isAggShape(raw.shapes[key])) {
|
|
603
|
+
rewritten[key] = value;
|
|
604
|
+
continue;
|
|
605
|
+
}
|
|
606
|
+
const returns = ctx.returnsByKey?.[key];
|
|
607
|
+
if (returns !== void 0) {
|
|
608
|
+
const currentNs = ctx.currentNsByKey[key];
|
|
609
|
+
const schema = currentNs !== void 0 ? ctx.schemas[currentNs] : void 0;
|
|
610
|
+
if (currentNs === void 0 || schema === void 0) {
|
|
611
|
+
rewritten[key] = value;
|
|
612
|
+
continue;
|
|
613
|
+
}
|
|
614
|
+
rewritten[key] = decodeByShapeFromDef(value, returns, schema, raw.shapes[key], {
|
|
615
|
+
schemas: ctx.schemas,
|
|
616
|
+
currentNs
|
|
617
|
+
});
|
|
618
|
+
continue;
|
|
619
|
+
}
|
|
620
|
+
const fields = ctx.fieldsByKey[key];
|
|
621
|
+
const typeName = ctx.typeByKey[key];
|
|
622
|
+
const currentNs = ctx.currentNsByKey[key];
|
|
623
|
+
if (fields === void 0 || typeName === void 0 || currentNs === void 0) {
|
|
624
|
+
rewritten[key] = value;
|
|
625
|
+
continue;
|
|
626
|
+
}
|
|
627
|
+
const schema = ctx.schemas[currentNs];
|
|
628
|
+
if (schema === void 0) {
|
|
629
|
+
rewritten[key] = value;
|
|
630
|
+
continue;
|
|
631
|
+
}
|
|
632
|
+
const rawShape = raw.shapes[key];
|
|
633
|
+
rewritten[key] = decodeByShape(value, fields, schema, typeName, Array.isArray(rawShape) || isAggShape(rawShape) ? void 0 : rawShape, {
|
|
634
|
+
schemas: ctx.schemas,
|
|
635
|
+
currentNs
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
const out = {
|
|
639
|
+
schemaVersion: raw.schemaVersion,
|
|
640
|
+
data: rewritten,
|
|
641
|
+
shapes: raw.shapes
|
|
642
|
+
};
|
|
643
|
+
if (raw._meta !== void 0) out._meta = raw._meta;
|
|
644
|
+
if (raw._pagination !== void 0) out._pagination = raw._pagination;
|
|
645
|
+
if (raw._completeness !== void 0) out._completeness = raw._completeness;
|
|
646
|
+
if (raw._diagnostics !== void 0) out._diagnostics = raw._diagnostics;
|
|
647
|
+
if (raw.errors !== void 0) out.errors = raw.errors;
|
|
648
|
+
return out;
|
|
649
|
+
}
|
|
650
|
+
function decodeByShape(value, fields, schema, typeName, shape, ctx) {
|
|
651
|
+
if (value === null || value === void 0) return null;
|
|
652
|
+
const plan = getRowPlan(fields, resolveFieldMap(schema, typeName, [typeName]));
|
|
653
|
+
if (shape === "list") {
|
|
654
|
+
if (!Array.isArray(value)) throw new PackDecodeError("expected array for list shape", [typeName]);
|
|
655
|
+
return value.map((elem) => decodeRowWithPlan(elem, plan, schema, [typeName], ctx));
|
|
656
|
+
}
|
|
657
|
+
return decodeRowWithPlan(value, plan, schema, [typeName], ctx);
|
|
658
|
+
}
|
|
659
|
+
function decodeByShapeFromDef(value, def, schema, shape, ctx) {
|
|
660
|
+
if (value === null || value === void 0) return null;
|
|
661
|
+
if (Array.isArray(shape)) {
|
|
662
|
+
if (!Array.isArray(value)) throw new PackDecodeError("expected array for batched shape", []);
|
|
663
|
+
return value.map((elem, idx) => decodeByShapeFromDef(elem, frameDef(def, idx), schema, shape[idx], ctx));
|
|
664
|
+
}
|
|
665
|
+
const one = frameDef(def, 0);
|
|
666
|
+
if (shape === "list" && one.kind !== "list") {
|
|
667
|
+
if (!Array.isArray(value)) throw new PackDecodeError("expected array for list shape", []);
|
|
668
|
+
return value.map((elem, idx) => decodePositionalFromFieldDef(elem, one, schema, ctx, [`[${idx}]`]));
|
|
669
|
+
}
|
|
670
|
+
return decodePositionalFromFieldDef(value, one, schema, ctx);
|
|
671
|
+
}
|
|
672
|
+
function resolveFieldMap(schema, typeName, path) {
|
|
673
|
+
return resolveFieldMap$1(schema, typeName, path, (message, p) => new PackDecodeError(message, p));
|
|
674
|
+
}
|
|
675
|
+
/**
|
|
676
|
+
* Decide whether `value` is a single tuple or a list of tuples based on its
|
|
677
|
+
* shape plus the FieldInput — used only by the top-level `decodePositional`
|
|
678
|
+
* helper (the envelope decoder uses `shapes[key]` directly). Heuristic:
|
|
679
|
+
* - null → null
|
|
680
|
+
* - Array where the first element is itself an array → list of rows
|
|
681
|
+
* - Array otherwise → single row (tuple)
|
|
682
|
+
*
|
|
683
|
+
* This heuristic is the ambiguity §7.2 calls out, so callers SHOULD go through
|
|
684
|
+
* `decodeEnvelope` to use explicit shape metadata.
|
|
685
|
+
*/
|
|
686
|
+
function decodeValueByArity(value, fields, fieldMap, schema, path, ctx) {
|
|
687
|
+
if (value === null || value === void 0) return null;
|
|
688
|
+
if (!Array.isArray(value)) throw new PackDecodeError("expected array (tuple) for positional row", path);
|
|
689
|
+
const plan = getRowPlan(fields, fieldMap);
|
|
690
|
+
if (value.length > 0 && Array.isArray(value[0])) return value.map((elem) => decodeRowWithPlan(elem, plan, schema, path, ctx));
|
|
691
|
+
return decodeRowWithPlan(value, plan, schema, path, ctx);
|
|
692
|
+
}
|
|
693
|
+
const DECODE_PLAN_CACHE = /* @__PURE__ */ new WeakMap();
|
|
694
|
+
function getRowPlan(fields, fieldMap) {
|
|
695
|
+
return getRowPlan$1(DECODE_PLAN_CACHE, fields, fieldMap);
|
|
696
|
+
}
|
|
697
|
+
function decodeRowWithPlan(tuple, plan, schema, path, ctx) {
|
|
698
|
+
if (tuple === null || tuple === void 0) return null;
|
|
699
|
+
if (!Array.isArray(tuple)) throw new PackDecodeError("expected array (tuple) for row", path);
|
|
700
|
+
const out = {};
|
|
701
|
+
const len = plan.length;
|
|
702
|
+
for (let i = 0; i < len; i++) {
|
|
703
|
+
const entry = plan[i];
|
|
704
|
+
const field = entry[0];
|
|
705
|
+
const selection = entry[1];
|
|
706
|
+
const def = entry[2];
|
|
707
|
+
const cell = tuple[i] ?? null;
|
|
708
|
+
const slot = entry[3];
|
|
709
|
+
if (slot?.kind === "truncated" && cell === null) continue;
|
|
710
|
+
path.push(field);
|
|
711
|
+
out[field] = slot === void 0 ? decodeField(cell, selection, def, schema, path, ctx) : decodeWalkSlot(cell, slot, schema, path, ctx);
|
|
712
|
+
path.pop();
|
|
713
|
+
}
|
|
714
|
+
return out;
|
|
715
|
+
}
|
|
716
|
+
function decodeWalkSlot(cell, slot, schema, path, ctx) {
|
|
717
|
+
if (cell === null || cell === void 0) return null;
|
|
718
|
+
switch (slot.kind) {
|
|
719
|
+
case "truncated": return cell;
|
|
720
|
+
case "agg":
|
|
721
|
+
if (!Array.isArray(cell)) throw new PackDecodeError("expected array for _agg", path);
|
|
722
|
+
return Object.fromEntries(slot.names.map((n, i) => [n, cell[i] ?? null]));
|
|
723
|
+
case "nested": {
|
|
724
|
+
if (!Array.isArray(cell)) throw new PackDecodeError("expected array for nested selection", path);
|
|
725
|
+
const plan = getRowPlan(slot.fields, resolveFieldMap(schema, slot.type, path));
|
|
726
|
+
return cell.map((tuple, idx) => {
|
|
727
|
+
path.push(`[${idx}]`);
|
|
728
|
+
const out = decodeRowWithPlan(tuple, plan, schema, path, ctx);
|
|
729
|
+
path.pop();
|
|
730
|
+
return out;
|
|
731
|
+
});
|
|
732
|
+
}
|
|
733
|
+
default: return assertNever(slot);
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
function decodeField(cell, selection, def, schema, path, ctx) {
|
|
737
|
+
if (cell === null || cell === void 0) return null;
|
|
738
|
+
if (def === void 0) return cell;
|
|
739
|
+
if (selection === true) return decodeLeaf(cell, def, path);
|
|
740
|
+
switch (def.kind) {
|
|
741
|
+
case "scalar": throw new PackDecodeError(`field is a scalar (${def.type}); cannot select sub-fields`, path);
|
|
742
|
+
case "struct": return decodeStruct(cell, selection, def, schema, path, ctx);
|
|
743
|
+
case "list": return decodeList(cell, selection, def, schema, path, ctx);
|
|
744
|
+
case "crossRef": return decodeCrossRef(cell, selection, def, schema, path, ctx);
|
|
745
|
+
default: return assertNever(def);
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
function decodeLeaf(cell, def, path) {
|
|
749
|
+
switch (def.kind) {
|
|
750
|
+
case "scalar": return cell;
|
|
751
|
+
case "list":
|
|
752
|
+
if (!Array.isArray(cell)) throw new PackDecodeError("expected array for list leaf", path);
|
|
753
|
+
return cell;
|
|
754
|
+
case "struct":
|
|
755
|
+
case "crossRef": return cell;
|
|
756
|
+
default: return assertNever(def);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
function decodeStruct(cell, selection, def, schema, path, ctx) {
|
|
760
|
+
return decodeRowWithPlan(cell, getRowPlan(selection, def.fields), schema, path, ctx);
|
|
761
|
+
}
|
|
762
|
+
function decodeList(cell, selection, def, schema, path, ctx) {
|
|
763
|
+
if (!Array.isArray(cell)) throw new PackDecodeError("expected array for list field", path);
|
|
764
|
+
const inner = def.of;
|
|
765
|
+
const innerPlan = inner.kind === "struct" ? getRowPlan(selection, inner.fields) : void 0;
|
|
766
|
+
const out = [];
|
|
767
|
+
for (let idx = 0; idx < cell.length; idx++) {
|
|
768
|
+
const elem = cell[idx];
|
|
769
|
+
if (elem === null || elem === void 0) {
|
|
770
|
+
out.push(null);
|
|
771
|
+
continue;
|
|
772
|
+
}
|
|
773
|
+
path.push(`[${idx}]`);
|
|
774
|
+
out.push(decodeListElement(elem, selection, inner, schema, path, ctx, innerPlan));
|
|
775
|
+
path.pop();
|
|
776
|
+
}
|
|
777
|
+
return out;
|
|
778
|
+
}
|
|
779
|
+
function decodeListElement(elem, selection, inner, schema, elemPath, ctx, structPlan) {
|
|
780
|
+
switch (inner.kind) {
|
|
781
|
+
case "scalar": throw new PackDecodeError(`list element is scalar (${inner.type}); cannot select sub-fields`, elemPath);
|
|
782
|
+
case "struct": return decodeRowWithPlan(elem, structPlan ?? getRowPlan(selection, inner.fields), schema, elemPath, ctx);
|
|
783
|
+
case "list": return decodeList(elem, selection, inner, schema, elemPath, ctx);
|
|
784
|
+
case "crossRef": return decodeCrossRef(elem, selection, inner, schema, elemPath, ctx);
|
|
785
|
+
default: return assertNever(inner);
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
function decodeCrossRef(cell, selection, def, schema, path, ctx) {
|
|
789
|
+
if (def.ns === ctx.currentNs) return decodeRowWithPlan(cell, getRowPlan(selection, resolveFieldMap(schema, def.type, path)), schema, path, ctx);
|
|
790
|
+
const schemas = ctx.schemas;
|
|
791
|
+
if (schemas === void 0) throw new PackDecodeError(`cross-namespace crossRef '${def.ns}/${def.type}' requires ctx.schemas`, path);
|
|
792
|
+
const targetSchema = schemas[def.ns];
|
|
793
|
+
if (targetSchema === void 0) throw new PackDecodeError(`cross-namespace crossRef target namespace '${def.ns}' not in ctx.schemas`, path);
|
|
794
|
+
return decodeRowWithPlan(cell, getRowPlan(selection, resolveFieldMap(targetSchema, def.type, path)), targetSchema, path, {
|
|
795
|
+
...ctx,
|
|
796
|
+
currentNs: def.ns
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
function decodeFieldDef(value, def, schema, path, ctx) {
|
|
800
|
+
if (value === null || value === void 0) return null;
|
|
801
|
+
switch (def.kind) {
|
|
802
|
+
case "scalar": return value;
|
|
803
|
+
case "struct": return decodeStructFromDef(value, def, schema, path, ctx);
|
|
804
|
+
case "list": return decodeListFromDef(value, def, schema, path, ctx);
|
|
805
|
+
case "crossRef": return value;
|
|
806
|
+
default: return assertNever(def);
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
const DECODE_FIELDDEF_PLAN_CACHE = /* @__PURE__ */ new WeakMap();
|
|
810
|
+
function getFieldDefPlan(fields) {
|
|
811
|
+
return getFieldDefPlan$1(DECODE_FIELDDEF_PLAN_CACHE, fields);
|
|
812
|
+
}
|
|
813
|
+
function decodeStructFromDef(value, def, schema, path, ctx) {
|
|
814
|
+
if (!Array.isArray(value)) throw new PackDecodeError("expected array (tuple) for struct", path);
|
|
815
|
+
const out = {};
|
|
816
|
+
const plan = getFieldDefPlan(def.fields);
|
|
817
|
+
const len = plan.length;
|
|
818
|
+
for (let i = 0; i < len; i++) {
|
|
819
|
+
const entry = plan[i];
|
|
820
|
+
const fieldName = entry[0];
|
|
821
|
+
const sub = entry[1];
|
|
822
|
+
const cell = value[i] ?? null;
|
|
823
|
+
path.push(fieldName);
|
|
824
|
+
out[fieldName] = decodeFieldDef(cell, sub, schema, path, ctx);
|
|
825
|
+
path.pop();
|
|
826
|
+
}
|
|
827
|
+
return out;
|
|
828
|
+
}
|
|
829
|
+
function decodeListFromDef(value, def, schema, path, ctx) {
|
|
830
|
+
if (!Array.isArray(value)) throw new PackDecodeError("expected array for list field", path);
|
|
831
|
+
const out = [];
|
|
832
|
+
for (let idx = 0; idx < value.length; idx++) {
|
|
833
|
+
const elem = value[idx];
|
|
834
|
+
if (elem === null || elem === void 0) {
|
|
835
|
+
out.push(null);
|
|
836
|
+
continue;
|
|
837
|
+
}
|
|
838
|
+
path.push(`[${idx}]`);
|
|
839
|
+
out.push(decodeFieldDef(elem, def.of, schema, path, ctx));
|
|
840
|
+
path.pop();
|
|
841
|
+
}
|
|
842
|
+
return out;
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
//#endregion
|
|
846
|
+
//#region ../../packages/substrate-pack/src/mutation-returns.ts
|
|
847
|
+
/** What a row-writing mutation answers when the frame names no `fields`. */
|
|
848
|
+
const MUTATION_ACK_FIELDS = {
|
|
849
|
+
id: true,
|
|
850
|
+
shortId: true
|
|
851
|
+
};
|
|
852
|
+
/** The `returns` a mutation's result is positioned by, given the frame's `fields` (`true` selects everything). */
|
|
853
|
+
function mutationReturns(mutation, fields) {
|
|
854
|
+
if (fields === true) return mutation.returns;
|
|
855
|
+
const selection = fields ?? (mutation.writesRows === true ? MUTATION_ACK_FIELDS : void 0);
|
|
856
|
+
return selection === void 0 ? mutation.returns : narrow(mutation.returns, selection);
|
|
857
|
+
}
|
|
858
|
+
/**
|
|
859
|
+
* `def` narrowed to the selection, in declared order: a list narrows its
|
|
860
|
+
* element, and a nested selection narrows a nested struct, as the JSON
|
|
861
|
+
* projection recurses. A selected field the struct does not declare is
|
|
862
|
+
* dropped, as the JSON projection drops a field the row does not carry.
|
|
863
|
+
*/
|
|
864
|
+
function narrow(def, selection) {
|
|
865
|
+
if (def.kind === "list") return {
|
|
866
|
+
...def,
|
|
867
|
+
of: narrow(def.of, selection)
|
|
868
|
+
};
|
|
869
|
+
if (def.kind !== "struct") return def;
|
|
870
|
+
const fields = {};
|
|
871
|
+
for (const [name, field] of Object.entries(def.fields)) {
|
|
872
|
+
const sub = selection[name];
|
|
873
|
+
if (sub === void 0) continue;
|
|
874
|
+
fields[name] = typeof sub === "object" && sub !== null ? narrow(field, sub) : field;
|
|
875
|
+
}
|
|
876
|
+
return {
|
|
877
|
+
...def,
|
|
878
|
+
fields
|
|
879
|
+
};
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
//#endregion
|
|
883
|
+
//#region ../../packages/substrate-pack/src/wire.ts
|
|
884
|
+
/**
|
|
885
|
+
* Frame wire codec. Spec §8.5.
|
|
886
|
+
*
|
|
887
|
+
* Centralizes JSON-vs-pack envelope handling for frame streams plus the
|
|
888
|
+
* precomputed decode plan that turns positional `data` tuples back into named
|
|
889
|
+
* objects. The plan is built once per subscription, so per-frame work is
|
|
890
|
+
* O(plan entries). Shared by substrate-client and the perf harness so both
|
|
891
|
+
* measure the same codepath.
|
|
892
|
+
*/
|
|
893
|
+
/**
|
|
894
|
+
* Decode an inbound frame envelope (the outer `{ id, kind, data?, ... }`
|
|
895
|
+
* shape — positional `data` reconstruction is a separate concern handled by
|
|
896
|
+
* `applyDecodePlanInPlace`).
|
|
897
|
+
*
|
|
898
|
+
* The `mode` discriminant determines how `raw` is interpreted: pack-mode
|
|
899
|
+
* messages arrive as `ArrayBuffer | Uint8Array | Buffer` and are msgpack-
|
|
900
|
+
* decoded; JSON-mode messages arrive as `string` (or, when node-ws hands the
|
|
901
|
+
* payload across as binary, as bytes that we coerce back to text before
|
|
902
|
+
* `JSON.parse`).
|
|
903
|
+
*
|
|
904
|
+
* The runtime narrowing is centralized here so callers don't reach for
|
|
905
|
+
* `raw as string` casts at every call site.
|
|
906
|
+
*/
|
|
907
|
+
function decodeWsEnvelope(raw, mode) {
|
|
908
|
+
if (mode === "pack") return inbound.unpack(toBytes(raw));
|
|
909
|
+
if (typeof raw === "string") return JSON.parse(raw);
|
|
910
|
+
return JSON.parse(new TextDecoder().decode(toBytes(raw)));
|
|
911
|
+
}
|
|
912
|
+
/**
|
|
913
|
+
* Inbound frames come from untrusted peers: structured-clone references (and
|
|
914
|
+
* so cyclic values) are refused. `mapsAsObjects` keeps the default `unpack`'s
|
|
915
|
+
* plain-object maps. msgpackr's other built-in extensions are process-global
|
|
916
|
+
* and still decode, so a server checks a request with `isPlainRequestData`.
|
|
917
|
+
*/
|
|
918
|
+
const inbound = new Unpackr({
|
|
919
|
+
structuredClone: false,
|
|
920
|
+
mapsAsObjects: true
|
|
921
|
+
});
|
|
922
|
+
function toBytes(raw) {
|
|
923
|
+
if (raw instanceof Uint8Array) return raw;
|
|
924
|
+
if (raw instanceof ArrayBuffer) return new Uint8Array(raw);
|
|
925
|
+
return new Uint8Array(raw);
|
|
926
|
+
}
|
|
927
|
+
/**
|
|
928
|
+
* Build the decode plan from a frame spec map + federated schemas. Called
|
|
929
|
+
* once per subscription, before the first frame arrives. Keys that are
|
|
930
|
+
* unqualified, have no matching schema, or have no field selection are
|
|
931
|
+
* skipped.
|
|
932
|
+
*/
|
|
933
|
+
function buildDecodePlan(frameSpec, schemas) {
|
|
934
|
+
const plan = [];
|
|
935
|
+
for (const qkey of Object.keys(frameSpec)) {
|
|
936
|
+
const parsed = parseQualifiedKey(qkey);
|
|
937
|
+
if (parsed === null) continue;
|
|
938
|
+
const { ns, name } = parsed;
|
|
939
|
+
const schema = schemas[ns];
|
|
940
|
+
if (schema === void 0) continue;
|
|
941
|
+
const spec = frameSpec[qkey];
|
|
942
|
+
if (spec === void 0) continue;
|
|
943
|
+
const fields = spec.fields;
|
|
944
|
+
if (fields === void 0) continue;
|
|
945
|
+
plan.push({
|
|
946
|
+
qkey,
|
|
947
|
+
name,
|
|
948
|
+
schema,
|
|
949
|
+
fields,
|
|
950
|
+
opts: {
|
|
951
|
+
schemas,
|
|
952
|
+
currentNs: ns
|
|
953
|
+
}
|
|
954
|
+
});
|
|
955
|
+
}
|
|
956
|
+
return plan;
|
|
957
|
+
}
|
|
958
|
+
/**
|
|
959
|
+
* Apply a precomputed decode plan to an envelope's `data` map in place.
|
|
960
|
+
* Mutates `envelope.data[qkey]` from positional tuple to named object/list
|
|
961
|
+
* for each plan entry whose qkey is present.
|
|
962
|
+
*
|
|
963
|
+
* Accepts `unknown` so both `WsResponseFrame` and the data-bearing
|
|
964
|
+
* `SubscribeEvent` variants flow through without a parameter-type cast at the
|
|
965
|
+
* call site; remove/end/error frames lack a `data` property and short-circuit
|
|
966
|
+
* here.
|
|
967
|
+
*/
|
|
968
|
+
function applyDecodePlanInPlace(envelope, plan) {
|
|
969
|
+
if (envelope === null || typeof envelope !== "object") return;
|
|
970
|
+
const data = envelope.data;
|
|
971
|
+
if (data === null || data === void 0 || typeof data !== "object") return;
|
|
972
|
+
const map = data;
|
|
973
|
+
for (const entry of plan) {
|
|
974
|
+
const value = map[entry.qkey];
|
|
975
|
+
if (value === void 0) continue;
|
|
976
|
+
map[entry.qkey] = decodePositional(value, entry.fields, entry.schema, entry.name, entry.opts);
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
//#endregion
|
|
981
|
+
//#region ../../packages/substrate-pack/src/stream-frames.ts
|
|
982
|
+
const FRAMES_JSON_MIME = "application/vnd.substrate.frames+json";
|
|
983
|
+
const FRAMES_PACK_MIME = "application/vnd.substrate.frames+pack";
|
|
984
|
+
/** Largest payload a decoder accepts unless told otherwise. */
|
|
985
|
+
const DEFAULT_MAX_FRAME_BYTES = 16777216;
|
|
986
|
+
var FrameStreamError = class extends Error {
|
|
987
|
+
code;
|
|
988
|
+
constructor(code, message) {
|
|
989
|
+
super(message);
|
|
990
|
+
this.name = "FrameStreamError";
|
|
991
|
+
this.code = code;
|
|
992
|
+
}
|
|
993
|
+
};
|
|
994
|
+
/** A little over three of the server's 20 s heartbeats. */
|
|
995
|
+
const DEFAULT_STREAM_IDLE_MS = 65e3;
|
|
996
|
+
/**
|
|
997
|
+
* `body`, failing with `stream_idle` when a read waits `ms` for bytes,
|
|
998
|
+
* heartbeats included. It times only reads the consumer is waiting on, so a
|
|
999
|
+
* slow consumer never trips it; a connection that died without closing does.
|
|
1000
|
+
* The underlying reader is cancelled on timeout, which settles its pending read.
|
|
1001
|
+
*/
|
|
1002
|
+
function withIdleTimeout(body, ms) {
|
|
1003
|
+
const reader = body.getReader();
|
|
1004
|
+
return new ReadableStream({
|
|
1005
|
+
async pull(controller) {
|
|
1006
|
+
let timer;
|
|
1007
|
+
const idle = new Promise((_, reject) => {
|
|
1008
|
+
timer = setTimeout(() => reject(new FrameStreamError("stream_idle", `the stream sent nothing for ${ms} ms`)), ms);
|
|
1009
|
+
});
|
|
1010
|
+
try {
|
|
1011
|
+
const r = await Promise.race([reader.read(), idle]);
|
|
1012
|
+
if (r.done) controller.close();
|
|
1013
|
+
else controller.enqueue(r.value);
|
|
1014
|
+
} catch (err) {
|
|
1015
|
+
reader.cancel().catch(() => {});
|
|
1016
|
+
controller.error(err);
|
|
1017
|
+
} finally {
|
|
1018
|
+
clearTimeout(timer);
|
|
1019
|
+
}
|
|
1020
|
+
},
|
|
1021
|
+
cancel(reason) {
|
|
1022
|
+
return reader.cancel(reason);
|
|
1023
|
+
}
|
|
1024
|
+
}, { highWaterMark: 0 });
|
|
1025
|
+
}
|
|
1026
|
+
const utf8 = new TextEncoder();
|
|
1027
|
+
/**
|
|
1028
|
+
* The payloads of a frame stream, in order, heartbeats skipped. A length above
|
|
1029
|
+
* `maxFrameBytes` throws `frame_too_large` before any of that payload is read
|
|
1030
|
+
* or allocated; a body that ends inside a frame throws `truncated_frame`.
|
|
1031
|
+
*/
|
|
1032
|
+
async function* decodeStreamFrames(body, opts = {}) {
|
|
1033
|
+
const max = opts.maxFrameBytes ?? 16777216;
|
|
1034
|
+
if (!Number.isInteger(max) || max < 0) throw new RangeError(`maxFrameBytes must be a non-negative integer, got ${max}`);
|
|
1035
|
+
let buf = /* @__PURE__ */ new Uint8Array(4096);
|
|
1036
|
+
let start = 0;
|
|
1037
|
+
let end = 0;
|
|
1038
|
+
const append = (chunk) => {
|
|
1039
|
+
if (end + chunk.length > buf.length) {
|
|
1040
|
+
const live = end - start;
|
|
1041
|
+
if (live + chunk.length > buf.length) {
|
|
1042
|
+
const grown = new Uint8Array(Math.max(buf.length * 2, live + chunk.length));
|
|
1043
|
+
grown.set(buf.subarray(start, end), 0);
|
|
1044
|
+
buf = grown;
|
|
1045
|
+
} else buf.copyWithin(0, start, end);
|
|
1046
|
+
start = 0;
|
|
1047
|
+
end = live;
|
|
1048
|
+
}
|
|
1049
|
+
buf.set(chunk, end);
|
|
1050
|
+
end += chunk.length;
|
|
1051
|
+
};
|
|
1052
|
+
const source = typeof body[Symbol.asyncIterator] === "function" ? body : readableToIterable(body);
|
|
1053
|
+
for await (const chunk of source) {
|
|
1054
|
+
append(chunk);
|
|
1055
|
+
while (end - start >= 4) {
|
|
1056
|
+
const len = new DataView(buf.buffer, buf.byteOffset + start, 4).getUint32(0, false);
|
|
1057
|
+
if (len > max) throw new FrameStreamError("frame_too_large", `frame of ${len} bytes exceeds the ${max}-byte limit`);
|
|
1058
|
+
if (end - start < 4 + len) break;
|
|
1059
|
+
if (len > 0) yield buf.slice(start + 4, start + 4 + len);
|
|
1060
|
+
start += 4 + len;
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
if (end - start > 0) throw new FrameStreamError("truncated_frame", `stream ended inside a frame (${end - start} bytes left over)`);
|
|
1064
|
+
}
|
|
1065
|
+
/** A ReadableStream without async iteration (Safari), cancelled when the consumer stops early. */
|
|
1066
|
+
async function* readableToIterable(stream) {
|
|
1067
|
+
const reader = stream.getReader();
|
|
1068
|
+
let finished = false;
|
|
1069
|
+
try {
|
|
1070
|
+
for (;;) {
|
|
1071
|
+
const { done, value } = await reader.read();
|
|
1072
|
+
if (done) {
|
|
1073
|
+
finished = true;
|
|
1074
|
+
return;
|
|
1075
|
+
}
|
|
1076
|
+
yield value;
|
|
1077
|
+
}
|
|
1078
|
+
} finally {
|
|
1079
|
+
if (!finished) await reader.cancel().catch(() => {});
|
|
1080
|
+
reader.releaseLock();
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
//#endregion
|
|
1085
|
+
//#region ../../packages/substrate-client/src/admin/api.ts
|
|
1086
|
+
function createAdminApi(t) {
|
|
1087
|
+
return {
|
|
1088
|
+
...createSurgeryApi(t),
|
|
1089
|
+
async keys(opts = {}) {
|
|
1090
|
+
const out = [];
|
|
1091
|
+
let cursor;
|
|
1092
|
+
for (;;) {
|
|
1093
|
+
const qs = cursor === void 0 ? "" : `?cursor=${encodeURIComponent(cursor)}`;
|
|
1094
|
+
const page = await (await t.raw(`/substrate/v1/_system/keys${qs}`, {
|
|
1095
|
+
method: "GET",
|
|
1096
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
1097
|
+
})).json();
|
|
1098
|
+
out.push(...page.keys);
|
|
1099
|
+
if (page.hasMore !== true) return out;
|
|
1100
|
+
if (typeof page.nextCursor !== "string") throw new Error("server reported hasMore with no nextCursor — refusing to report a partial key table as complete");
|
|
1101
|
+
cursor = page.nextCursor;
|
|
1102
|
+
}
|
|
1103
|
+
},
|
|
1104
|
+
async update(change, opts = {}) {
|
|
1105
|
+
const body = {
|
|
1106
|
+
kid: change.kid,
|
|
1107
|
+
namespaces: [...change.namespaces],
|
|
1108
|
+
capabilities: [...change.capabilities]
|
|
1109
|
+
};
|
|
1110
|
+
if (change.widen === true) body.widen = true;
|
|
1111
|
+
if (change.allowAdmin === true) body.allowAdmin = true;
|
|
1112
|
+
if (change.allowUnknownNs === true) body.allowUnknownNs = true;
|
|
1113
|
+
return await (await t.raw("/substrate/v1/_system/keys", {
|
|
1114
|
+
method: "PATCH",
|
|
1115
|
+
body,
|
|
1116
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
1117
|
+
})).json();
|
|
1118
|
+
},
|
|
1119
|
+
async revoke(kid, opts = {}) {
|
|
1120
|
+
return await (await t.raw("/substrate/v1/_system/keys", {
|
|
1121
|
+
method: "PATCH",
|
|
1122
|
+
body: {
|
|
1123
|
+
kid,
|
|
1124
|
+
revoke: true
|
|
1125
|
+
},
|
|
1126
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
1127
|
+
})).json();
|
|
1128
|
+
},
|
|
1129
|
+
async register(input, opts = {}) {
|
|
1130
|
+
const body = {
|
|
1131
|
+
kid: input.kid,
|
|
1132
|
+
publicKey: input.publicKey,
|
|
1133
|
+
algorithm: input.algorithm,
|
|
1134
|
+
namespaces: [...input.namespaces],
|
|
1135
|
+
capabilities: [...input.capabilities]
|
|
1136
|
+
};
|
|
1137
|
+
if (input.name !== void 0) body.name = input.name;
|
|
1138
|
+
if (input.directory !== void 0) body.directory = { create: input.directory };
|
|
1139
|
+
if (input.allowAdmin === true) body.allowAdmin = true;
|
|
1140
|
+
if (input.allowUnknownNs === true) body.allowUnknownNs = true;
|
|
1141
|
+
return await (await t.raw("/substrate/v1/_system/keys", {
|
|
1142
|
+
method: "POST",
|
|
1143
|
+
body,
|
|
1144
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
1145
|
+
})).json();
|
|
1146
|
+
},
|
|
1147
|
+
async invite(input, opts = {}) {
|
|
1148
|
+
const body = {
|
|
1149
|
+
namespaces: [...input.namespaces],
|
|
1150
|
+
capabilities: [...input.capabilities]
|
|
1151
|
+
};
|
|
1152
|
+
if (input.ttlMs !== void 0) body.ttlMs = input.ttlMs;
|
|
1153
|
+
return await (await t.raw("/substrate/v1/_system/invites", {
|
|
1154
|
+
method: "POST",
|
|
1155
|
+
body,
|
|
1156
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
1157
|
+
})).json();
|
|
1158
|
+
}
|
|
1159
|
+
};
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
//#endregion
|
|
1163
|
+
//#region ../../packages/substrate-client/src/errors.ts
|
|
1164
|
+
var NetworkError = class extends Error {
|
|
1165
|
+
cause;
|
|
1166
|
+
name = "NetworkError";
|
|
1167
|
+
/** HTTP status of the response, when the failure was one. */
|
|
1168
|
+
status;
|
|
1169
|
+
/** The server's JSON error `code`, when its body carried one. */
|
|
1170
|
+
code;
|
|
1171
|
+
/** The server's JSON `error` text, when its body carried one. */
|
|
1172
|
+
serverMessage;
|
|
1173
|
+
/** The refusal's parsed JSON object, verbatim. */
|
|
1174
|
+
body;
|
|
1175
|
+
constructor(message, cause, info = {}) {
|
|
1176
|
+
super(message);
|
|
1177
|
+
this.cause = cause;
|
|
1178
|
+
if (info.status !== void 0) this.status = info.status;
|
|
1179
|
+
if (info.code !== void 0) this.code = info.code;
|
|
1180
|
+
if (info.serverMessage !== void 0) this.serverMessage = info.serverMessage;
|
|
1181
|
+
if (info.body !== void 0) this.body = info.body;
|
|
1182
|
+
}
|
|
1183
|
+
};
|
|
1184
|
+
/**
|
|
1185
|
+
* Thrown on Substrate auth failures — 401 (unauthenticated) or 403 (authenticated but
|
|
1186
|
+
* not authorised). Proxy-level failures (407, 511) fall through to NetworkError.
|
|
1187
|
+
*/
|
|
1188
|
+
var AuthError = class extends Error {
|
|
1189
|
+
status;
|
|
1190
|
+
name = "AuthError";
|
|
1191
|
+
/** The server's JSON error `code`, when its body carried one: the auth gate says `forbidden`. */
|
|
1192
|
+
code;
|
|
1193
|
+
/** The server's JSON `error` or `message` text, when its body carried one. */
|
|
1194
|
+
serverMessage;
|
|
1195
|
+
/** The refusal's parsed JSON object, verbatim. */
|
|
1196
|
+
body;
|
|
1197
|
+
constructor(message, status, info = {}) {
|
|
1198
|
+
super(message);
|
|
1199
|
+
this.status = status;
|
|
1200
|
+
if (info.code !== void 0) this.code = info.code;
|
|
1201
|
+
if (info.serverMessage !== void 0) this.serverMessage = info.serverMessage;
|
|
1202
|
+
if (info.body !== void 0) this.body = info.body;
|
|
1203
|
+
}
|
|
1204
|
+
};
|
|
1205
|
+
var SubscribeError = class extends Error {
|
|
1206
|
+
code;
|
|
1207
|
+
name = "SubscribeError";
|
|
1208
|
+
constructor(message, code) {
|
|
1209
|
+
super(message);
|
|
1210
|
+
this.code = code;
|
|
1211
|
+
}
|
|
1212
|
+
};
|
|
1213
|
+
|
|
1214
|
+
//#endregion
|
|
1215
|
+
//#region ../../packages/substrate-client/src/subscribe-rows.ts
|
|
1216
|
+
/**
|
|
1217
|
+
* Pure subscribe-event → typed-row-set fold, shared by `SubstrateClient.watch` and
|
|
1218
|
+
* the cache store.
|
|
1219
|
+
*
|
|
1220
|
+
* The `data` envelope shape per event kind:
|
|
1221
|
+
* - snapshot : data = { '<ns>/<Type>': Row[] } — the full current set
|
|
1222
|
+
* - add : data = { '<ns>/<Type>': Row } — one newly-matching row
|
|
1223
|
+
* - update : data = { '<ns>/<Type>': Row } — one changed row (by id)
|
|
1224
|
+
* - remove : { removedId: string } — no data envelope
|
|
1225
|
+
* - end / error / chunk : no row change (terminal / streaming kinds)
|
|
1226
|
+
*
|
|
1227
|
+
* Rows are correlated by their `id` field (string-coerced), so any frame fed to
|
|
1228
|
+
* the fold must select `id` — `SubstrateClient.watch` injects it via
|
|
1229
|
+
* `augmentFramesWithId`. `add` appends (no de-dup) and ignores the query's
|
|
1230
|
+
* `orderBy`.
|
|
1231
|
+
*/
|
|
1232
|
+
function rowSlot(data, qualifiedKey) {
|
|
1233
|
+
if (data === null || typeof data !== "object") return void 0;
|
|
1234
|
+
return data[qualifiedKey];
|
|
1235
|
+
}
|
|
1236
|
+
function rowId(row) {
|
|
1237
|
+
return String(row.id);
|
|
1238
|
+
}
|
|
1239
|
+
/**
|
|
1240
|
+
* Fold one subscribe event into `current`, returning the next row list. Pure:
|
|
1241
|
+
* the caller owns terminal-kind delivery and the "select id" contract.
|
|
1242
|
+
*
|
|
1243
|
+
* Returns the SAME array reference when the event does not change the set (an
|
|
1244
|
+
* `update` whose row carries no `id`, or a non-row kind), so callers can cheaply
|
|
1245
|
+
* skip redundant writes / yields by identity.
|
|
1246
|
+
*/
|
|
1247
|
+
function reduceSubscribeRows(current, qualifiedKey, event) {
|
|
1248
|
+
switch (event.kind) {
|
|
1249
|
+
case "snapshot": {
|
|
1250
|
+
const slot = rowSlot(event.data, qualifiedKey);
|
|
1251
|
+
if (Array.isArray(slot)) return [...slot];
|
|
1252
|
+
return slot === void 0 || slot === null ? [] : [slot];
|
|
1253
|
+
}
|
|
1254
|
+
case "add": return [...current, rowSlot(event.data, qualifiedKey)];
|
|
1255
|
+
case "update": {
|
|
1256
|
+
const row = rowSlot(event.data, qualifiedKey);
|
|
1257
|
+
if (row === void 0 || row.id === void 0) return current;
|
|
1258
|
+
const targetId = String(row.id);
|
|
1259
|
+
return current.map((r) => rowId(r) === targetId ? row : r);
|
|
1260
|
+
}
|
|
1261
|
+
case "remove": return current.filter((r) => rowId(r) !== String(event.removedId));
|
|
1262
|
+
default: return current;
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
/** End reasons after which the transport resubscribes rather than finishing. */
|
|
1266
|
+
const SURVIVABLE_END_REASONS = /* @__PURE__ */ new Set([
|
|
1267
|
+
"server_restart",
|
|
1268
|
+
"credential_expired",
|
|
1269
|
+
"credential_changed"
|
|
1270
|
+
]);
|
|
1271
|
+
/**
|
|
1272
|
+
* Fold a single-key subscription's event stream into a live row-set: yields the
|
|
1273
|
+
* current `T[]` after every snapshot / add / update / remove. Completes on `end`
|
|
1274
|
+
* (or when the source iterator completes); throws `SubscribeError` on an `error`
|
|
1275
|
+
* event — matching the raw `subscribe` contract, where the transport throws on
|
|
1276
|
+
* error frames.
|
|
1277
|
+
*
|
|
1278
|
+
* A delta that does not change the set (e.g. an `update` whose row has no id) is
|
|
1279
|
+
* not re-yielded. Cancellation: breaking the consuming `for await` (or calling
|
|
1280
|
+
* `.return()`) propagates to the source iterable's `return()` through the inner
|
|
1281
|
+
* `for await`, cancelling the underlying subscription.
|
|
1282
|
+
*/
|
|
1283
|
+
async function* watchRows(events, qualifiedKey) {
|
|
1284
|
+
let rows = [];
|
|
1285
|
+
for await (const event of events) {
|
|
1286
|
+
if (event.kind === "end" && !SURVIVABLE_END_REASONS.has(event.reason ?? "")) return;
|
|
1287
|
+
if (event.kind === "end") continue;
|
|
1288
|
+
if (event.kind === "error") {
|
|
1289
|
+
const first = event.errors[0];
|
|
1290
|
+
throw new SubscribeError(first?.message ?? "subscribe error", first?.code ?? "unknown");
|
|
1291
|
+
}
|
|
1292
|
+
const next = reduceSubscribeRows(rows, qualifiedKey, event);
|
|
1293
|
+
if (next === rows) continue;
|
|
1294
|
+
rows = next;
|
|
1295
|
+
yield rows;
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
//#endregion
|
|
1300
|
+
//#region ../../packages/substrate-client/src/cache/store.ts
|
|
1301
|
+
/**
|
|
1302
|
+
* Signals-backed reactive cache. Keyed by canonicalised frame key (same shape
|
|
1303
|
+
* as `canonicaliseFrameKey`). Each entry holds signals for `data`, `loading`,
|
|
1304
|
+
* `error`, plus refCount + invalidatedAt for lifecycle and drift management.
|
|
1305
|
+
*
|
|
1306
|
+
* Lifecycle:
|
|
1307
|
+
* - subscribe(key) → increment refCount, return an unsubscribe that decrements.
|
|
1308
|
+
* - When refCount → 0, schedule GC after `idleGcMs`; cancel if a new subscribe
|
|
1309
|
+
* arrives in that window.
|
|
1310
|
+
* - invalidate(keyPrefix): if any entry under that prefix has refCount > 0,
|
|
1311
|
+
* stamp `invalidatedAt` (callers observe and re-fetch). Entries with
|
|
1312
|
+
* refCount === 0 are dropped.
|
|
1313
|
+
*/
|
|
1314
|
+
var CacheStore = class {
|
|
1315
|
+
#entries = /* @__PURE__ */ new Map();
|
|
1316
|
+
#idleGcMs;
|
|
1317
|
+
constructor(opts) {
|
|
1318
|
+
this.#idleGcMs = opts.idleGcMs;
|
|
1319
|
+
}
|
|
1320
|
+
get(key) {
|
|
1321
|
+
const existing = this.#entries.get(key);
|
|
1322
|
+
if (existing !== void 0) return existing;
|
|
1323
|
+
const entry = {
|
|
1324
|
+
data: signal(void 0),
|
|
1325
|
+
loading: signal(false),
|
|
1326
|
+
error: signal(null),
|
|
1327
|
+
diagnostics: signal([]),
|
|
1328
|
+
invalidatedSignal: signal(0),
|
|
1329
|
+
refCount: 0,
|
|
1330
|
+
invalidatedAt: null,
|
|
1331
|
+
lastFetched: 0,
|
|
1332
|
+
gcTimer: null
|
|
1333
|
+
};
|
|
1334
|
+
this.#entries.set(key, entry);
|
|
1335
|
+
return entry;
|
|
1336
|
+
}
|
|
1337
|
+
peek(key) {
|
|
1338
|
+
return this.#entries.get(key);
|
|
1339
|
+
}
|
|
1340
|
+
subscribe(key) {
|
|
1341
|
+
const entry = this.get(key);
|
|
1342
|
+
entry.refCount += 1;
|
|
1343
|
+
if (entry.gcTimer !== null) {
|
|
1344
|
+
clearTimeout(entry.gcTimer);
|
|
1345
|
+
entry.gcTimer = null;
|
|
1346
|
+
}
|
|
1347
|
+
let unsubscribed = false;
|
|
1348
|
+
return () => {
|
|
1349
|
+
if (unsubscribed) return;
|
|
1350
|
+
unsubscribed = true;
|
|
1351
|
+
entry.refCount -= 1;
|
|
1352
|
+
if (entry.refCount === 0) this.#scheduleGc(key, entry);
|
|
1353
|
+
};
|
|
1354
|
+
}
|
|
1355
|
+
set(key, data, diagnostics = []) {
|
|
1356
|
+
const entry = this.get(key);
|
|
1357
|
+
entry.data.value = data;
|
|
1358
|
+
entry.loading.value = false;
|
|
1359
|
+
entry.error.value = null;
|
|
1360
|
+
if (diagnostics.length > 0 || entry.diagnostics.value.length > 0) entry.diagnostics.value = diagnostics;
|
|
1361
|
+
entry.invalidatedAt = null;
|
|
1362
|
+
entry.invalidatedSignal.value = 0;
|
|
1363
|
+
entry.lastFetched = Date.now();
|
|
1364
|
+
}
|
|
1365
|
+
setLoading(key, loading) {
|
|
1366
|
+
const entry = this.get(key);
|
|
1367
|
+
entry.loading.value = loading;
|
|
1368
|
+
}
|
|
1369
|
+
setError(key, err) {
|
|
1370
|
+
const entry = this.get(key);
|
|
1371
|
+
entry.error.value = err;
|
|
1372
|
+
entry.loading.value = false;
|
|
1373
|
+
}
|
|
1374
|
+
invalidate(keyPrefix) {
|
|
1375
|
+
const now = Date.now();
|
|
1376
|
+
for (const [key, entry] of this.#entries) {
|
|
1377
|
+
if (!key.startsWith(keyPrefix)) continue;
|
|
1378
|
+
if (entry.refCount > 0) {
|
|
1379
|
+
entry.invalidatedAt = now;
|
|
1380
|
+
entry.invalidatedSignal.value = now;
|
|
1381
|
+
} else {
|
|
1382
|
+
if (entry.gcTimer !== null) clearTimeout(entry.gcTimer);
|
|
1383
|
+
this.#entries.delete(key);
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
/**
|
|
1388
|
+
* Apply a subscribe event to the entry at `cacheKey`, patching the row slot
|
|
1389
|
+
* under `qualifiedKey` in the entry's `data` envelope.
|
|
1390
|
+
*
|
|
1391
|
+
* - snapshot → replace the entire envelope via `set()`
|
|
1392
|
+
* - add → append the single row to the list at data[qualifiedKey]
|
|
1393
|
+
* - update → replace row by id in the list at data[qualifiedKey]
|
|
1394
|
+
* - remove → drop row by removedId from the list at data[qualifiedKey]
|
|
1395
|
+
* - end / error / chunk → no cache change (the hook surfaces these)
|
|
1396
|
+
*
|
|
1397
|
+
* `update` / `remove` on an entry without data are no-ops — the server always
|
|
1398
|
+
* emits `snapshot` first.
|
|
1399
|
+
*/
|
|
1400
|
+
applySubscribeEvent(cacheKey, qualifiedKey, event) {
|
|
1401
|
+
if (event.kind === "snapshot") {
|
|
1402
|
+
this.set(cacheKey, event.data);
|
|
1403
|
+
return;
|
|
1404
|
+
}
|
|
1405
|
+
if (event.kind !== "add" && event.kind !== "update" && event.kind !== "remove") return;
|
|
1406
|
+
const entry = this.get(cacheKey);
|
|
1407
|
+
const current = entry.data.value;
|
|
1408
|
+
if (event.kind !== "add" && (current === void 0 || !Array.isArray(current[qualifiedKey]))) return;
|
|
1409
|
+
const list = Array.isArray(current?.[qualifiedKey]) ? current[qualifiedKey] : [];
|
|
1410
|
+
const next = reduceSubscribeRows(list, qualifiedKey, event);
|
|
1411
|
+
if (next === list) return;
|
|
1412
|
+
entry.data.value = {
|
|
1413
|
+
...current ?? {},
|
|
1414
|
+
[qualifiedKey]: next
|
|
1415
|
+
};
|
|
1416
|
+
}
|
|
1417
|
+
#scheduleGc(key, entry) {
|
|
1418
|
+
if (entry.gcTimer !== null) clearTimeout(entry.gcTimer);
|
|
1419
|
+
entry.gcTimer = setTimeout(() => {
|
|
1420
|
+
entry.gcTimer = null;
|
|
1421
|
+
if (entry.refCount === 0) this.#entries.delete(key);
|
|
1422
|
+
}, this.#idleGcMs);
|
|
1423
|
+
}
|
|
1424
|
+
};
|
|
1425
|
+
|
|
1426
|
+
//#endregion
|
|
1427
|
+
//#region ../../packages/substrate-client/src/diagnostics.ts
|
|
1428
|
+
const HANDLED = /* @__PURE__ */ new Set([
|
|
1429
|
+
"unknownProjectionFields",
|
|
1430
|
+
"filterValidationSkipped",
|
|
1431
|
+
"plan"
|
|
1432
|
+
]);
|
|
1433
|
+
/**
|
|
1434
|
+
* Reduce one envelope entry to a diagnostic, or `undefined` when it holds
|
|
1435
|
+
* nothing worth reporting — an entry present but empty, or one whose only
|
|
1436
|
+
* unknown-field list is empty. Without that, the default sink emits a warning
|
|
1437
|
+
* naming no observation at all.
|
|
1438
|
+
*/
|
|
1439
|
+
function describeEntry(opKey, entry) {
|
|
1440
|
+
const unknownProjectionFields = [...entry.unknownProjectionFields ?? []];
|
|
1441
|
+
const { filterValidationSkipped } = entry;
|
|
1442
|
+
const unrecognizedKeys = Object.keys(entry).filter((k) => !HANDLED.has(k) && entry[k] !== void 0).sort();
|
|
1443
|
+
if (unknownProjectionFields.length === 0 && filterValidationSkipped === void 0 && unrecognizedKeys.length === 0) return;
|
|
1444
|
+
const diagnostic = {
|
|
1445
|
+
opKey,
|
|
1446
|
+
unknownProjectionFields
|
|
1447
|
+
};
|
|
1448
|
+
if (filterValidationSkipped !== void 0) diagnostic.filterValidationSkipped = filterValidationSkipped;
|
|
1449
|
+
if (unrecognizedKeys.length > 0) diagnostic.unrecognizedKeys = unrecognizedKeys;
|
|
1450
|
+
return diagnostic;
|
|
1451
|
+
}
|
|
1452
|
+
/**
|
|
1453
|
+
* Extract diagnostics from a decoded envelope and hand each one to `sink`.
|
|
1454
|
+
* Returns the flattened list so callers can also attach it to a mapped result.
|
|
1455
|
+
*
|
|
1456
|
+
* An envelope with no `_diagnostics` returns `[]` without the sink firing.
|
|
1457
|
+
*/
|
|
1458
|
+
function collectDiagnostics(envDiagnostics, sink) {
|
|
1459
|
+
if (envDiagnostics === void 0) return [];
|
|
1460
|
+
const out = [];
|
|
1461
|
+
for (const [opKey, entry] of Object.entries(envDiagnostics)) {
|
|
1462
|
+
if (entry === null || entry === void 0) continue;
|
|
1463
|
+
const diagnostic = describeEntry(opKey, entry);
|
|
1464
|
+
if (diagnostic === void 0) continue;
|
|
1465
|
+
out.push(diagnostic);
|
|
1466
|
+
sink?.(diagnostic);
|
|
1467
|
+
}
|
|
1468
|
+
return out;
|
|
1469
|
+
}
|
|
1470
|
+
/**
|
|
1471
|
+
* Default sink: one `console.warn` per distinct observation set, naming the
|
|
1472
|
+
* frame key and everything observed about it, plus the reason the reader should
|
|
1473
|
+
* care in each case.
|
|
1474
|
+
*
|
|
1475
|
+
* ONE warning per diagnostic rather than one per observation. An entry carrying
|
|
1476
|
+
* both an unknown projection and a skipped filter validation describes a single
|
|
1477
|
+
* read, and splitting it reads as two independent defects.
|
|
1478
|
+
*
|
|
1479
|
+
* Deduping state is per-sink, so per-client: `new SubstrateClient(...)` starts
|
|
1480
|
+
* fresh.
|
|
1481
|
+
*/
|
|
1482
|
+
function createDefaultDiagnosticsSink() {
|
|
1483
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1484
|
+
return (diagnostic) => {
|
|
1485
|
+
const { opKey, filterValidationSkipped } = diagnostic;
|
|
1486
|
+
const fields = [...diagnostic.unknownProjectionFields].sort();
|
|
1487
|
+
const unrecognized = [...diagnostic.unrecognizedKeys ?? []].sort();
|
|
1488
|
+
const dedupeKey = [
|
|
1489
|
+
opKey,
|
|
1490
|
+
fields.join(","),
|
|
1491
|
+
filterValidationSkipped ?? "",
|
|
1492
|
+
unrecognized.join(",")
|
|
1493
|
+
].join("\0");
|
|
1494
|
+
if (seen.has(dedupeKey)) return;
|
|
1495
|
+
seen.add(dedupeKey);
|
|
1496
|
+
const parts = [];
|
|
1497
|
+
if (fields.length > 0) parts.push(`projected field(s) the type does not declare: ${fields.join(", ")}. The read succeeded — these are null on EVERY row, which is indistinguishable from a declared field that is always null. Check for a typo, or a substrate that has not restarted with your schema yet.`);
|
|
1498
|
+
if (filterValidationSkipped !== void 0) parts.push(`the where-clause was not schema-validated (${filterValidationSkipped}), so its operators and operands were never checked against the field kinds. Results are still correct — the substrate refuses a predicate it cannot honour — but a malformed filter fails later and less clearly.`);
|
|
1499
|
+
if (unrecognized.length > 0) parts.push(`the substrate reported diagnostic(s) this client cannot read: ${unrecognized.join(", ")}. Upgrade @mnmal-ai/substrate-client to surface them.`);
|
|
1500
|
+
console.warn(`[substrate-client] ${opKey}: ${parts.join(" Also, ")} (Pass \`onDiagnostics\` to SubstrateClient to route this elsewhere.)`);
|
|
1501
|
+
};
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
//#endregion
|
|
1505
|
+
//#region ../../packages/substrate-client/src/reconnect.ts
|
|
1506
|
+
var ReconnectScheduler = class {
|
|
1507
|
+
#base;
|
|
1508
|
+
#max;
|
|
1509
|
+
#jitter;
|
|
1510
|
+
#attempt = 0;
|
|
1511
|
+
constructor(opts) {
|
|
1512
|
+
this.#base = opts.baseDelayMs;
|
|
1513
|
+
this.#max = opts.maxDelayMs;
|
|
1514
|
+
this.#jitter = opts.jitter;
|
|
1515
|
+
}
|
|
1516
|
+
nextDelay() {
|
|
1517
|
+
const raw = Math.min(this.#base * 2 ** this.#attempt, this.#max);
|
|
1518
|
+
this.#attempt += 1;
|
|
1519
|
+
if (this.#jitter === 0) return raw;
|
|
1520
|
+
const spread = raw * this.#jitter;
|
|
1521
|
+
return raw + (Math.random() * 2 - 1) * spread;
|
|
1522
|
+
}
|
|
1523
|
+
reset() {
|
|
1524
|
+
this.#attempt = 0;
|
|
1525
|
+
}
|
|
1526
|
+
/**
|
|
1527
|
+
* Resolve after `nextDelay()` ms. Callers must use this serially — the
|
|
1528
|
+
* `#attempt` counter is shared across calls, so overlapping `schedule()`
|
|
1529
|
+
* invocations will produce incorrect delays. The stream reconnect loop awaits
|
|
1530
|
+
* each `schedule()` before firing the next attempt.
|
|
1531
|
+
*/
|
|
1532
|
+
async schedule() {
|
|
1533
|
+
const d = this.nextDelay();
|
|
1534
|
+
await new Promise((resolve) => setTimeout(resolve, d));
|
|
1535
|
+
}
|
|
1536
|
+
};
|
|
1537
|
+
|
|
1538
|
+
//#endregion
|
|
1539
|
+
//#region ../../packages/substrate-client/src/transport/frame-event.ts
|
|
1540
|
+
/** Server response frames as the subscribe and stream iterables yield them. */
|
|
1541
|
+
const DEFAULT_RECONNECT = {
|
|
1542
|
+
baseDelayMs: 1e3,
|
|
1543
|
+
maxDelayMs: 3e4,
|
|
1544
|
+
jitter: .1
|
|
1545
|
+
};
|
|
1546
|
+
const DEFAULT_OVERLOAD_RESUBSCRIBE = {
|
|
1547
|
+
enabled: true,
|
|
1548
|
+
maxAttempts: 3,
|
|
1549
|
+
baseDelayMs: 1e3,
|
|
1550
|
+
maxDelayMs: 3e4,
|
|
1551
|
+
jitter: .1,
|
|
1552
|
+
healthyResetMs: 6e4
|
|
1553
|
+
};
|
|
1554
|
+
/** Convert a server frame to a SubscribeEvent, or null if unrecognised. */
|
|
1555
|
+
function msgToEvent(msg) {
|
|
1556
|
+
switch (msg.kind) {
|
|
1557
|
+
case "snapshot":
|
|
1558
|
+
case "add":
|
|
1559
|
+
case "update": return {
|
|
1560
|
+
kind: msg.kind,
|
|
1561
|
+
data: msg.data,
|
|
1562
|
+
...msg.shapes !== void 0 ? { shapes: msg.shapes } : {}
|
|
1563
|
+
};
|
|
1564
|
+
case "chunk": return {
|
|
1565
|
+
kind: "chunk",
|
|
1566
|
+
data: msg.data,
|
|
1567
|
+
...msg.shapes !== void 0 ? { shapes: msg.shapes } : {},
|
|
1568
|
+
...msg.sequence !== void 0 ? { sequence: msg.sequence } : {}
|
|
1569
|
+
};
|
|
1570
|
+
case "remove": return {
|
|
1571
|
+
kind: "remove",
|
|
1572
|
+
removedId: msg.removedId ?? ""
|
|
1573
|
+
};
|
|
1574
|
+
case "end": return {
|
|
1575
|
+
kind: "end",
|
|
1576
|
+
...msg.final !== void 0 ? { final: msg.final } : {},
|
|
1577
|
+
...msg.reason !== void 0 ? { reason: msg.reason } : {}
|
|
1578
|
+
};
|
|
1579
|
+
case "error": {
|
|
1580
|
+
const first = (msg.errors ?? [{
|
|
1581
|
+
message: "unknown error",
|
|
1582
|
+
code: "unknown"
|
|
1583
|
+
}])[0] ?? {
|
|
1584
|
+
message: "unknown error",
|
|
1585
|
+
code: "unknown"
|
|
1586
|
+
};
|
|
1587
|
+
throw new SubscribeError(first.message, first.code ?? "unknown");
|
|
1588
|
+
}
|
|
1589
|
+
default: return null;
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
//#endregion
|
|
1594
|
+
//#region ../../packages/substrate-client/src/transport/frames.ts
|
|
1595
|
+
/**
|
|
1596
|
+
* Subscribe and stream over length-prefixed frame streams: one POST per
|
|
1597
|
+
* subscription, its response body a sequence of frames (substrate-pack's
|
|
1598
|
+
* stream-frames codec). Each subscription owns its request, so cancelling one
|
|
1599
|
+
* aborts only that request.
|
|
1600
|
+
*
|
|
1601
|
+
* A subscription survives the following, re-subscribing for a fresh
|
|
1602
|
+
* snapshot: a dropped connection (after backoff), `end { server_restart }`
|
|
1603
|
+
* (at once), `subscription_overloaded` (after the overload delay, within its
|
|
1604
|
+
* budget) and a lapsed credential when `getToken` can mint a new one. A 401 or
|
|
1605
|
+
* 403 is terminal. A stream is never re-sent, since that would replay its chunks.
|
|
1606
|
+
*/
|
|
1607
|
+
/** `NetworkError.code` when the server does not answer with frame streams. */
|
|
1608
|
+
const FRAMES_UNSUPPORTED = "frames_unsupported";
|
|
1609
|
+
/** `NetworkError.code` when a stream was cut short by a server restart. */
|
|
1610
|
+
const STREAM_INTERRUPTED = "stream_interrupted";
|
|
1611
|
+
const OVERLOADED = "subscription_overloaded";
|
|
1612
|
+
const SERVER_RESTART = "server_restart";
|
|
1613
|
+
const LAPSES = /* @__PURE__ */ new Set(["credential_expired", "credential_changed"]);
|
|
1614
|
+
function openFrameStream(http, path, frame, opts) {
|
|
1615
|
+
return { [Symbol.asyncIterator]: () => {
|
|
1616
|
+
const ctrl = new AbortController();
|
|
1617
|
+
const gen = run(http, path, frame, opts, opts.signal === void 0 ? ctrl.signal : anySignal([ctrl.signal, opts.signal]));
|
|
1618
|
+
return {
|
|
1619
|
+
next: () => gen.next(),
|
|
1620
|
+
return: async () => {
|
|
1621
|
+
ctrl.abort();
|
|
1622
|
+
await gen.return(void 0);
|
|
1623
|
+
return {
|
|
1624
|
+
value: void 0,
|
|
1625
|
+
done: true
|
|
1626
|
+
};
|
|
1627
|
+
}
|
|
1628
|
+
};
|
|
1629
|
+
} };
|
|
1630
|
+
}
|
|
1631
|
+
async function* run(http, path, frame, opts, signal) {
|
|
1632
|
+
const subscribe = path === "/substrate/v1/subscribe";
|
|
1633
|
+
const reconnect = {
|
|
1634
|
+
...DEFAULT_RECONNECT,
|
|
1635
|
+
...opts.reconnect
|
|
1636
|
+
};
|
|
1637
|
+
const backoff = new ReconnectScheduler(reconnect);
|
|
1638
|
+
const overload = {
|
|
1639
|
+
...DEFAULT_OVERLOAD_RESUBSCRIBE,
|
|
1640
|
+
...opts.overload
|
|
1641
|
+
};
|
|
1642
|
+
let overloadAttempts = 0;
|
|
1643
|
+
let lastOverloadAt = null;
|
|
1644
|
+
let opened = false;
|
|
1645
|
+
let busyRetries = 0;
|
|
1646
|
+
const accept = opts.wire === "pack" ? FRAMES_PACK_MIME : FRAMES_JSON_MIME;
|
|
1647
|
+
for (;;) {
|
|
1648
|
+
let body;
|
|
1649
|
+
try {
|
|
1650
|
+
const res = await http.raw(path, {
|
|
1651
|
+
method: "POST",
|
|
1652
|
+
body: frame,
|
|
1653
|
+
accept,
|
|
1654
|
+
signal
|
|
1655
|
+
});
|
|
1656
|
+
const type = res.headers.get("content-type") ?? "";
|
|
1657
|
+
if (!type.startsWith(accept)) {
|
|
1658
|
+
await res.body?.cancel();
|
|
1659
|
+
throw new NetworkError(`POST ${path} answered '${type}', not ${accept}: the server predates frame streams`, null, {
|
|
1660
|
+
status: res.status,
|
|
1661
|
+
code: FRAMES_UNSUPPORTED
|
|
1662
|
+
});
|
|
1663
|
+
}
|
|
1664
|
+
if (res.body === null) throw new NetworkError(`POST ${path}: response has no body`, null);
|
|
1665
|
+
body = res.body;
|
|
1666
|
+
} catch (err) {
|
|
1667
|
+
if (signal.aborted) return;
|
|
1668
|
+
if (!opened && isBusy(err) && busyRetries < BUSY_RETRIES) {
|
|
1669
|
+
busyRetries++;
|
|
1670
|
+
if (!await sleep(backoff.nextDelay(), signal)) return;
|
|
1671
|
+
continue;
|
|
1672
|
+
}
|
|
1673
|
+
if (err instanceof AuthError || !opened || !subscribe || refused(err)) throw err;
|
|
1674
|
+
if (!await sleep(backoff.nextDelay(), signal)) return;
|
|
1675
|
+
continue;
|
|
1676
|
+
}
|
|
1677
|
+
opened = true;
|
|
1678
|
+
const openedAt = Date.now();
|
|
1679
|
+
let next;
|
|
1680
|
+
try {
|
|
1681
|
+
const idleMs = opts.idleMs ?? 65e3;
|
|
1682
|
+
for await (const payload of decodeStreamFrames(idleMs > 0 ? withIdleTimeout(body, idleMs) : body)) {
|
|
1683
|
+
const msg = decodeFrame(payload, opts.wire);
|
|
1684
|
+
if (Date.now() - openedAt >= reconnect.maxDelayMs) backoff.reset();
|
|
1685
|
+
if (subscribe && msg.kind === "error" && msg.errors?.[0]?.code === OVERLOADED && overload.enabled) {
|
|
1686
|
+
const now = Date.now();
|
|
1687
|
+
if (lastOverloadAt !== null && now - lastOverloadAt > overload.healthyResetMs) overloadAttempts = 0;
|
|
1688
|
+
lastOverloadAt = now;
|
|
1689
|
+
if (overloadAttempts < overload.maxAttempts) {
|
|
1690
|
+
overloadAttempts += 1;
|
|
1691
|
+
next = { delayMs: jittered(overload, overloadAttempts) };
|
|
1692
|
+
break;
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
if (!subscribe && msg.kind === "end" && msg.reason === SERVER_RESTART) throw new NetworkError(`POST ${path}: the server restarted mid-stream`, null, { code: STREAM_INTERRUPTED });
|
|
1696
|
+
const event = msgToEvent(msg);
|
|
1697
|
+
if (event === null) continue;
|
|
1698
|
+
yield event;
|
|
1699
|
+
if (msg.kind === "end") {
|
|
1700
|
+
next = subscribe && (msg.reason === SERVER_RESTART || msg.reason !== void 0 && LAPSES.has(msg.reason) && opts.canRefreshToken) ? { delayMs: 0 } : "stop";
|
|
1701
|
+
break;
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
} catch (err) {
|
|
1705
|
+
if (signal.aborted) return;
|
|
1706
|
+
if (err instanceof SubscribeError || err instanceof NetworkError && err.code === "stream_interrupted") throw err;
|
|
1707
|
+
if (!subscribe) throw err instanceof NetworkError ? err : new NetworkError(`POST ${path}: the stream broke before its end frame`, err);
|
|
1708
|
+
}
|
|
1709
|
+
if (next === "stop") return;
|
|
1710
|
+
if (next === void 0) {
|
|
1711
|
+
if (signal.aborted) return;
|
|
1712
|
+
if (!subscribe) throw new NetworkError(`POST ${path}: stream ended without an end frame`, null);
|
|
1713
|
+
next = { delayMs: backoff.nextDelay() };
|
|
1714
|
+
}
|
|
1715
|
+
if (!await sleep(next.delayMs, signal)) return;
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
/** Retries of a 429 before the first response, after which it surfaces. */
|
|
1719
|
+
const BUSY_RETRIES = 3;
|
|
1720
|
+
function isBusy(err) {
|
|
1721
|
+
return err instanceof NetworkError && err.status === 429;
|
|
1722
|
+
}
|
|
1723
|
+
/**
|
|
1724
|
+
* A refusal that retrying will not change: a server without frame streams, or a
|
|
1725
|
+
* 4xx other than 408 and 429 (the frame no longer validates, say).
|
|
1726
|
+
*/
|
|
1727
|
+
function refused(err) {
|
|
1728
|
+
if (!(err instanceof NetworkError)) return false;
|
|
1729
|
+
if (err.code === "frames_unsupported") return true;
|
|
1730
|
+
const status = err.status;
|
|
1731
|
+
return status !== void 0 && status >= 400 && status < 500 && status !== 408 && status !== 429;
|
|
1732
|
+
}
|
|
1733
|
+
/**
|
|
1734
|
+
* Aborts when any of `signals` does. `AbortSignal.any` holds no listener on its
|
|
1735
|
+
* sources, so finished subscriptions leave nothing behind on a shared signal; the
|
|
1736
|
+
* fallback, for browsers before 2024, does.
|
|
1737
|
+
*/
|
|
1738
|
+
function anySignal(signals) {
|
|
1739
|
+
if (typeof AbortSignal.any === "function") return AbortSignal.any(signals);
|
|
1740
|
+
const ctrl = new AbortController();
|
|
1741
|
+
for (const s of signals) {
|
|
1742
|
+
if (s.aborted) {
|
|
1743
|
+
ctrl.abort(s.reason);
|
|
1744
|
+
break;
|
|
1745
|
+
}
|
|
1746
|
+
s.addEventListener("abort", () => ctrl.abort(s.reason), { once: true });
|
|
1747
|
+
}
|
|
1748
|
+
return ctrl.signal;
|
|
1749
|
+
}
|
|
1750
|
+
function decodeFrame(payload, wire) {
|
|
1751
|
+
const value = wire === "pack" ? decodeWsEnvelope(payload, "pack") : JSON.parse(new TextDecoder().decode(payload));
|
|
1752
|
+
if (value === null || typeof value !== "object" || typeof value.kind !== "string") throw new NetworkError("malformed frame in subscription stream", null);
|
|
1753
|
+
return value;
|
|
1754
|
+
}
|
|
1755
|
+
function jittered(cfg, attempt) {
|
|
1756
|
+
const raw = Math.min(cfg.baseDelayMs * 2 ** (attempt - 1), cfg.maxDelayMs);
|
|
1757
|
+
return cfg.jitter === 0 ? raw : raw + (Math.random() * 2 - 1) * raw * cfg.jitter;
|
|
1758
|
+
}
|
|
1759
|
+
/** Resolves true after `ms`, or false as soon as `signal` aborts. */
|
|
1760
|
+
function sleep(ms, signal) {
|
|
1761
|
+
if (signal.aborted) return Promise.resolve(false);
|
|
1762
|
+
return new Promise((resolve) => {
|
|
1763
|
+
const timer = setTimeout(() => {
|
|
1764
|
+
signal.removeEventListener("abort", onAbort);
|
|
1765
|
+
resolve(true);
|
|
1766
|
+
}, ms);
|
|
1767
|
+
const onAbort = () => {
|
|
1768
|
+
clearTimeout(timer);
|
|
1769
|
+
resolve(false);
|
|
1770
|
+
};
|
|
1771
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1772
|
+
});
|
|
1773
|
+
}
|
|
1774
|
+
|
|
1775
|
+
//#endregion
|
|
1776
|
+
//#region ../../packages/substrate-client/src/nl.ts
|
|
1777
|
+
function createNlApi(t) {
|
|
1778
|
+
const packs = /* @__PURE__ */ new Map();
|
|
1779
|
+
return {
|
|
1780
|
+
async *ask(req, opts = {}) {
|
|
1781
|
+
const res = await t.raw("/substrate/v1/nl", {
|
|
1782
|
+
method: "POST",
|
|
1783
|
+
body: req,
|
|
1784
|
+
accept: FRAMES_JSON_MIME,
|
|
1785
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
1786
|
+
});
|
|
1787
|
+
const type = res.headers.get("content-type") ?? "";
|
|
1788
|
+
if (!type.startsWith("application/vnd.substrate.frames+json") || res.body === null) {
|
|
1789
|
+
await res.body?.cancel();
|
|
1790
|
+
throw new NetworkError(`POST /substrate/v1/nl answered '${type}', not ${FRAMES_JSON_MIME}: the server predates frame streams`, null, {
|
|
1791
|
+
status: res.status,
|
|
1792
|
+
code: FRAMES_UNSUPPORTED
|
|
1793
|
+
});
|
|
1794
|
+
}
|
|
1795
|
+
const utf8 = new TextDecoder();
|
|
1796
|
+
for await (const payload of decodeStreamFrames(res.body)) {
|
|
1797
|
+
let ev;
|
|
1798
|
+
try {
|
|
1799
|
+
ev = JSON.parse(utf8.decode(payload));
|
|
1800
|
+
} catch (err) {
|
|
1801
|
+
throw new NetworkError("malformed frame in the NL stream", err);
|
|
1802
|
+
}
|
|
1803
|
+
if (ev.event === "error") {
|
|
1804
|
+
const e = ev.data;
|
|
1805
|
+
throw new NetworkError(`${e.code ?? "error"}: ${e.message ?? ""}`, ev.data);
|
|
1806
|
+
}
|
|
1807
|
+
yield ev;
|
|
1808
|
+
}
|
|
1809
|
+
},
|
|
1810
|
+
async askJson(req, opts = {}) {
|
|
1811
|
+
return await (await t.raw("/substrate/v1/nl", {
|
|
1812
|
+
method: "POST",
|
|
1813
|
+
body: req,
|
|
1814
|
+
accept: "application/json",
|
|
1815
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
1816
|
+
})).json();
|
|
1817
|
+
},
|
|
1818
|
+
async pack(namespace, opts = {}) {
|
|
1819
|
+
const prior = packs.get(namespace);
|
|
1820
|
+
const url = `/substrate/v1/nl/pack/${encodeURIComponent(namespace)}`;
|
|
1821
|
+
const res = await t.raw(url, {
|
|
1822
|
+
method: "GET",
|
|
1823
|
+
allow304: true,
|
|
1824
|
+
...prior !== void 0 ? { headers: { "if-none-match": prior.etag } } : {},
|
|
1825
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
1826
|
+
});
|
|
1827
|
+
if (res.status === 304) {
|
|
1828
|
+
if (prior !== void 0) return structuredClone(prior.body);
|
|
1829
|
+
throw new NetworkError(`GET ${url} returned 304 with no cached pack to reuse`, null);
|
|
1830
|
+
}
|
|
1831
|
+
const body = await res.json();
|
|
1832
|
+
const etag = res.headers.get("etag");
|
|
1833
|
+
if (etag !== null) packs.set(namespace, {
|
|
1834
|
+
etag,
|
|
1835
|
+
body: structuredClone(body)
|
|
1836
|
+
});
|
|
1837
|
+
return structuredClone(body);
|
|
1838
|
+
}
|
|
1839
|
+
};
|
|
1840
|
+
}
|
|
1841
|
+
|
|
1842
|
+
//#endregion
|
|
1843
|
+
//#region ../../packages/substrate-client/src/subscribe-util.ts
|
|
1844
|
+
/**
|
|
1845
|
+
* Produce a copy of `frame` where every qualified key's `fields` selection has
|
|
1846
|
+
* `id: true` injected. `update` and `remove` subscribe events are correlated by
|
|
1847
|
+
* row id, so without an `id` in the selection a live consumer would have nothing
|
|
1848
|
+
* to patch against.
|
|
1849
|
+
*
|
|
1850
|
+
* The input frame is never mutated. Callers still use the original frame for
|
|
1851
|
+
* cache-key canonicalisation so query + subscribe on the same frame resolve to
|
|
1852
|
+
* the same cache entry.
|
|
1853
|
+
*/
|
|
1854
|
+
function augmentFramesWithId(frame) {
|
|
1855
|
+
const out = {};
|
|
1856
|
+
for (const [key, entry] of Object.entries(frame)) if (Array.isArray(entry)) out[key] = entry.map((e) => ({
|
|
1857
|
+
params: e.params ?? {},
|
|
1858
|
+
fields: {
|
|
1859
|
+
id: true,
|
|
1860
|
+
...e.fields ?? {}
|
|
1861
|
+
}
|
|
1862
|
+
}));
|
|
1863
|
+
else if (entry !== void 0) out[key] = {
|
|
1864
|
+
params: entry.params ?? {},
|
|
1865
|
+
fields: {
|
|
1866
|
+
id: true,
|
|
1867
|
+
...entry.fields ?? {}
|
|
1868
|
+
}
|
|
1869
|
+
};
|
|
1870
|
+
return out;
|
|
1871
|
+
}
|
|
1872
|
+
/**
|
|
1873
|
+
* Validate that `frame` has exactly one qualified key and return it. Throws with
|
|
1874
|
+
* a descriptive error for zero- or multi-key frames.
|
|
1875
|
+
*/
|
|
1876
|
+
function assertSingleKey(frame) {
|
|
1877
|
+
const keys = Object.keys(frame);
|
|
1878
|
+
if (keys.length !== 1) {
|
|
1879
|
+
if (keys.length === 0) throw new Error("Live subscribe surfaces require exactly one key in the frame.");
|
|
1880
|
+
throw new Error(`Live subscribe surfaces require a single qualified key. Got: ${keys.join(", ")}`);
|
|
1881
|
+
}
|
|
1882
|
+
return keys[0];
|
|
1883
|
+
}
|
|
1884
|
+
|
|
1885
|
+
//#endregion
|
|
1886
|
+
//#region ../../packages/substrate-client/src/transport/default-fetch.ts
|
|
1887
|
+
let current = (input, init) => globalThis.fetch(input, init);
|
|
1888
|
+
const substrateFetch = (input, init) => current(input, init);
|
|
1889
|
+
|
|
1890
|
+
//#endregion
|
|
1891
|
+
//#region ../../packages/substrate-client/src/transport/http.ts
|
|
1892
|
+
var HttpTransport = class {
|
|
1893
|
+
#endpoint;
|
|
1894
|
+
#fetch;
|
|
1895
|
+
#token;
|
|
1896
|
+
#getToken;
|
|
1897
|
+
constructor(opts) {
|
|
1898
|
+
if (opts.token !== void 0 && opts.getToken !== void 0) throw new Error("HttpTransport: provide `token` OR `getToken`, not both");
|
|
1899
|
+
this.#endpoint = trimTrailingSlashes(opts.endpoint);
|
|
1900
|
+
this.#fetch = (opts.fetch ?? substrateFetch).bind(globalThis);
|
|
1901
|
+
this.#token = opts.token;
|
|
1902
|
+
this.#getToken = opts.getToken;
|
|
1903
|
+
}
|
|
1904
|
+
async query(frame, opts) {
|
|
1905
|
+
return this.#postEnvelope(`${this.#endpoint}/substrate/v1/query`, frame, opts);
|
|
1906
|
+
}
|
|
1907
|
+
async mutate(frame, opts) {
|
|
1908
|
+
return this.#postEnvelope(`${this.#endpoint}/substrate/v1/mutate`, frame, opts);
|
|
1909
|
+
}
|
|
1910
|
+
async federatedSchema(opts = {}) {
|
|
1911
|
+
const url = `${this.#endpoint}/substrate/v1/federated-schema`;
|
|
1912
|
+
const headers = await this.#headers("json", opts.headers);
|
|
1913
|
+
let res;
|
|
1914
|
+
try {
|
|
1915
|
+
res = await this.#fetch(url, {
|
|
1916
|
+
method: "GET",
|
|
1917
|
+
headers,
|
|
1918
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
1919
|
+
});
|
|
1920
|
+
} catch (err) {
|
|
1921
|
+
throw new NetworkError(`GET ${url} failed`, err);
|
|
1922
|
+
}
|
|
1923
|
+
await this.#assertOk(res, url);
|
|
1924
|
+
return await res.json();
|
|
1925
|
+
}
|
|
1926
|
+
/** A request to an arbitrary /substrate path with the client's auth; asserts ok (a 304 passes only with allow304). */
|
|
1927
|
+
async raw(path, init) {
|
|
1928
|
+
const url = `${this.#endpoint}${path}`;
|
|
1929
|
+
const extra = init.accept !== void 0 ? { accept: init.accept } : {};
|
|
1930
|
+
for (const [k, v] of Object.entries(init.headers ?? {})) extra[k.toLowerCase()] = v;
|
|
1931
|
+
const headers = await this.#headers("json", extra);
|
|
1932
|
+
if (init.body === void 0) delete headers["content-type"];
|
|
1933
|
+
let res;
|
|
1934
|
+
try {
|
|
1935
|
+
res = await this.#fetch(url, {
|
|
1936
|
+
method: init.method,
|
|
1937
|
+
headers,
|
|
1938
|
+
...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {},
|
|
1939
|
+
...init.signal !== void 0 ? { signal: init.signal } : {}
|
|
1940
|
+
});
|
|
1941
|
+
} catch (err) {
|
|
1942
|
+
throw new NetworkError(`${init.method} ${url} failed`, err);
|
|
1943
|
+
}
|
|
1944
|
+
if (!(init.allow304 === true && res.status === 304)) await this.#assertOk(res, url);
|
|
1945
|
+
return res;
|
|
1946
|
+
}
|
|
1947
|
+
async #postEnvelope(url, body, opts) {
|
|
1948
|
+
const wire = opts.wire ?? "json";
|
|
1949
|
+
const headers = await this.#headers(wire, opts.headers);
|
|
1950
|
+
let res;
|
|
1951
|
+
try {
|
|
1952
|
+
res = await this.#fetch(url, {
|
|
1953
|
+
method: "POST",
|
|
1954
|
+
headers,
|
|
1955
|
+
body: JSON.stringify(body),
|
|
1956
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
1957
|
+
});
|
|
1958
|
+
} catch (err) {
|
|
1959
|
+
throw new NetworkError(`POST ${url} failed`, err);
|
|
1960
|
+
}
|
|
1961
|
+
await this.#assertOk(res, url);
|
|
1962
|
+
if (wire === "pack") {
|
|
1963
|
+
const buf = await res.arrayBuffer();
|
|
1964
|
+
return { __packBytes: new Uint8Array(buf) };
|
|
1965
|
+
}
|
|
1966
|
+
return await res.json();
|
|
1967
|
+
}
|
|
1968
|
+
async #headers(wire, extra) {
|
|
1969
|
+
const headers = {
|
|
1970
|
+
"content-type": "application/json",
|
|
1971
|
+
accept: wire === "pack" ? "application/vnd.substrate.pack" : "application/json"
|
|
1972
|
+
};
|
|
1973
|
+
const tok = this.#token ?? (this.#getToken ? await this.#getToken() : void 0);
|
|
1974
|
+
if (tok !== void 0) headers.authorization = `Bearer ${tok}`;
|
|
1975
|
+
return {
|
|
1976
|
+
...headers,
|
|
1977
|
+
...extra
|
|
1978
|
+
};
|
|
1979
|
+
}
|
|
1980
|
+
async #assertOk(res, url) {
|
|
1981
|
+
if (res.ok) return;
|
|
1982
|
+
if (res.status === 401 || res.status === 403) {
|
|
1983
|
+
const { code, serverMessage, body } = await errorInfo(res);
|
|
1984
|
+
const info = {
|
|
1985
|
+
...code !== void 0 ? { code } : {},
|
|
1986
|
+
...serverMessage !== void 0 ? { serverMessage } : {},
|
|
1987
|
+
...body !== void 0 ? { body } : {}
|
|
1988
|
+
};
|
|
1989
|
+
throw new AuthError(`${res.status === 401 ? "Unauthorised" : "Forbidden"}: ${url}`, res.status, info);
|
|
1990
|
+
}
|
|
1991
|
+
throw new NetworkError(`${res.status} from ${url}`, null, await errorInfo(res));
|
|
1992
|
+
}
|
|
1993
|
+
};
|
|
1994
|
+
/** The status plus whatever a JSON body says: the whole object as `body`, the first string of `error.message` (the recall plugin's nested shape), `error`, `message` as the message, and the first string of `error.code`, `code` as the code. Non-JSON bodies leave the status alone. */
|
|
1995
|
+
async function errorInfo(res) {
|
|
1996
|
+
const info = { status: res.status };
|
|
1997
|
+
try {
|
|
1998
|
+
const body = JSON.parse(await res.text());
|
|
1999
|
+
if (body !== null && typeof body === "object" && !Array.isArray(body)) {
|
|
2000
|
+
const b = body;
|
|
2001
|
+
info.body = b;
|
|
2002
|
+
const nested = b.error !== null && typeof b.error === "object" ? b.error : void 0;
|
|
2003
|
+
const message = [
|
|
2004
|
+
nested?.message,
|
|
2005
|
+
b.error,
|
|
2006
|
+
b.message
|
|
2007
|
+
].find((v) => typeof v === "string");
|
|
2008
|
+
const code = [nested?.code, b.code].find((v) => typeof v === "string");
|
|
2009
|
+
if (typeof message === "string") info.serverMessage = message;
|
|
2010
|
+
if (typeof code === "string") info.code = code;
|
|
2011
|
+
}
|
|
2012
|
+
} catch {}
|
|
2013
|
+
return info;
|
|
2014
|
+
}
|
|
2015
|
+
|
|
2016
|
+
//#endregion
|
|
2017
|
+
//#region ../../packages/substrate-client/src/wire/pack.ts
|
|
2018
|
+
function isPackMarker(v) {
|
|
2019
|
+
return typeof v === "object" && v !== null && "__packBytes" in v;
|
|
2020
|
+
}
|
|
2021
|
+
|
|
2022
|
+
//#endregion
|
|
2023
|
+
//#region ../../packages/substrate-client/src/wire/json.ts
|
|
2024
|
+
function decodeJsonEnvelope(env) {
|
|
2025
|
+
if (typeof env.schemaVersion !== "string") throw new Error("Malformed envelope: missing schemaVersion");
|
|
2026
|
+
return env;
|
|
2027
|
+
}
|
|
2028
|
+
|
|
2029
|
+
//#endregion
|
|
2030
|
+
//#region ../../packages/substrate-client/src/client.ts
|
|
2031
|
+
/**
|
|
2032
|
+
* SubstrateClient — the public facade over the HTTP and frame-stream transports, wire
|
|
2033
|
+
* decoding and schema-drift handling.
|
|
2034
|
+
*
|
|
2035
|
+
* Routing is protocol-mandated: query and mutate are plain HTTP requests;
|
|
2036
|
+
* subscribe and stream are frame streams (one POST each, response held open).
|
|
2037
|
+
*
|
|
2038
|
+
* Drift detection is lazy-seeded: the client cannot replicate the server's
|
|
2039
|
+
* federated schema-version hash, so the first envelope's `schemaVersion` seeds
|
|
2040
|
+
* the cache and any later mismatch refetches the schema and accepts the new
|
|
2041
|
+
* version as authoritative.
|
|
2042
|
+
*/
|
|
2043
|
+
var SubstrateClient = class {
|
|
2044
|
+
#http;
|
|
2045
|
+
#nl;
|
|
2046
|
+
#admin;
|
|
2047
|
+
#streamWire;
|
|
2048
|
+
#canRefreshToken;
|
|
2049
|
+
/** Aborted by close(), ending every open subscription and stream. */
|
|
2050
|
+
#closing = new AbortController();
|
|
2051
|
+
#reconnectOpts;
|
|
2052
|
+
#streamIdleMs;
|
|
2053
|
+
#overloadResubscribeOpts;
|
|
2054
|
+
#schemaCache = null;
|
|
2055
|
+
#schemaFetch = null;
|
|
2056
|
+
#driftCachedVersion = null;
|
|
2057
|
+
#closed = false;
|
|
2058
|
+
#cache;
|
|
2059
|
+
#onDiagnostics;
|
|
2060
|
+
constructor(opts) {
|
|
2061
|
+
if (opts.token !== void 0 && opts.getToken !== void 0) throw new Error("SubstrateClient: provide `token` OR `getToken`, not both");
|
|
2062
|
+
this.#http = new HttpTransport({
|
|
2063
|
+
endpoint: opts.endpoint,
|
|
2064
|
+
...opts.token !== void 0 ? { token: opts.token } : {},
|
|
2065
|
+
...opts.getToken !== void 0 ? { getToken: opts.getToken } : {},
|
|
2066
|
+
...opts.fetch !== void 0 ? { fetch: opts.fetch } : {}
|
|
2067
|
+
});
|
|
2068
|
+
this.#streamWire = opts.streamWire ?? "json";
|
|
2069
|
+
this.#canRefreshToken = opts.token === void 0 && opts.getToken !== void 0;
|
|
2070
|
+
this.#reconnectOpts = opts.reconnect;
|
|
2071
|
+
this.#streamIdleMs = opts.streamIdleMs;
|
|
2072
|
+
this.#overloadResubscribeOpts = opts.overloadResubscribe;
|
|
2073
|
+
this.#onDiagnostics = opts.onDiagnostics ?? createDefaultDiagnosticsSink();
|
|
2074
|
+
this.#cache = new CacheStore({ idleGcMs: 5e3 });
|
|
2075
|
+
}
|
|
2076
|
+
/** Natural-language ask (frame stream or JSON) and the served namespace pack. Requires the substrate-nl plugin. */
|
|
2077
|
+
get nl() {
|
|
2078
|
+
this.#nl ??= createNlApi(this.#http);
|
|
2079
|
+
return this.#nl;
|
|
2080
|
+
}
|
|
2081
|
+
/** The admin-gated routes. Needs an identity whose grant confers `admin`. */
|
|
2082
|
+
get admin() {
|
|
2083
|
+
this.#admin ??= createAdminApi(this.#http);
|
|
2084
|
+
return this.#admin;
|
|
2085
|
+
}
|
|
2086
|
+
#ensureOpen() {
|
|
2087
|
+
if (this.#closed) throw new Error("SubstrateClient: already closed");
|
|
2088
|
+
}
|
|
2089
|
+
async federatedSchema() {
|
|
2090
|
+
this.#ensureOpen();
|
|
2091
|
+
if (this.#schemaCache !== null) return this.#schemaCache;
|
|
2092
|
+
if (this.#schemaFetch === null) this.#schemaFetch = this.#http.federatedSchema().then((schema) => {
|
|
2093
|
+
this.#schemaCache = schema;
|
|
2094
|
+
this.#schemaFetch = null;
|
|
2095
|
+
return schema;
|
|
2096
|
+
}, (err) => {
|
|
2097
|
+
this.#schemaFetch = null;
|
|
2098
|
+
throw err;
|
|
2099
|
+
});
|
|
2100
|
+
return this.#schemaFetch;
|
|
2101
|
+
}
|
|
2102
|
+
async query(frame, opts = {}) {
|
|
2103
|
+
this.#ensureOpen();
|
|
2104
|
+
await this.federatedSchema();
|
|
2105
|
+
const wire = opts.wire ?? "json";
|
|
2106
|
+
const raw = await this.#http.query(frame, {
|
|
2107
|
+
wire,
|
|
2108
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {},
|
|
2109
|
+
...opts.headers !== void 0 ? { headers: opts.headers } : {}
|
|
2110
|
+
});
|
|
2111
|
+
return this.#decode(raw, frame, wire);
|
|
2112
|
+
}
|
|
2113
|
+
async mutate(frame, opts = {}) {
|
|
2114
|
+
this.#ensureOpen();
|
|
2115
|
+
await this.federatedSchema();
|
|
2116
|
+
const wire = opts.wire ?? "json";
|
|
2117
|
+
const raw = await this.#http.mutate(frame, {
|
|
2118
|
+
wire,
|
|
2119
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {},
|
|
2120
|
+
...opts.headers !== void 0 ? { headers: opts.headers } : {}
|
|
2121
|
+
});
|
|
2122
|
+
return this.#decode(raw, frame, wire);
|
|
2123
|
+
}
|
|
2124
|
+
/** A live query: a snapshot, then deltas. `opts.wire` and `opts.signal` apply. */
|
|
2125
|
+
subscribe(frame, opts = {}) {
|
|
2126
|
+
return this.#frameStream("/substrate/v1/subscribe", frame, opts);
|
|
2127
|
+
}
|
|
2128
|
+
/** A one-shot streamed resolver: chunks, then `end`. `opts.wire` and `opts.signal` apply. */
|
|
2129
|
+
stream(frame, opts = {}) {
|
|
2130
|
+
return this.#frameStream("/substrate/v1/stream", frame, opts);
|
|
2131
|
+
}
|
|
2132
|
+
#frameStream(path, frame, opts) {
|
|
2133
|
+
this.#ensureOpen();
|
|
2134
|
+
const body = flatFrame(frame);
|
|
2135
|
+
const wire = opts.wire ?? this.#streamWire;
|
|
2136
|
+
const signal = opts.signal === void 0 ? this.#closing.signal : anySignal([this.#closing.signal, opts.signal]);
|
|
2137
|
+
const inner = openFrameStream(this.#http, path, body, {
|
|
2138
|
+
wire,
|
|
2139
|
+
canRefreshToken: this.#canRefreshToken,
|
|
2140
|
+
signal,
|
|
2141
|
+
...this.#reconnectOpts !== void 0 ? { reconnect: this.#reconnectOpts } : {},
|
|
2142
|
+
...this.#streamIdleMs !== void 0 ? { idleMs: this.#streamIdleMs } : {},
|
|
2143
|
+
...this.#overloadResubscribeOpts !== void 0 ? { overload: this.#overloadResubscribeOpts } : {}
|
|
2144
|
+
});
|
|
2145
|
+
return wire === "pack" ? this.#wrapPackDecode(inner, body) : inner;
|
|
2146
|
+
}
|
|
2147
|
+
/**
|
|
2148
|
+
* Live typed-row view over a single-key subscription. Subscribes under the
|
|
2149
|
+
* hood, folds snapshot/add/update/remove into the current row-set, and yields
|
|
2150
|
+
* the maintained `T[]` after each delta — hiding the raw `SubscribeEvent`
|
|
2151
|
+
* protocol. `id` is force-selected (via `augmentFramesWithId`) so
|
|
2152
|
+
* update/remove can correlate rows by id.
|
|
2153
|
+
*
|
|
2154
|
+
* Completes when the subscription ends; throws on an error frame — the same
|
|
2155
|
+
* contract as `subscribe`. Breaking the consuming `for await` cancels the
|
|
2156
|
+
* underlying subscription. Reconnect / overload-resubscribe are handled by
|
|
2157
|
+
* `subscribe`; each fresh snapshot atomically replaces the row-set.
|
|
2158
|
+
*
|
|
2159
|
+
* Single-qualified-key only: multi-key frames throw; use `subscribe` for
|
|
2160
|
+
* those or for raw events.
|
|
2161
|
+
*/
|
|
2162
|
+
watch(frame) {
|
|
2163
|
+
this.#ensureOpen();
|
|
2164
|
+
const qualifiedKey = assertSingleKey(frame);
|
|
2165
|
+
return watchRows(this.subscribe(augmentFramesWithId(frame)), qualifiedKey);
|
|
2166
|
+
}
|
|
2167
|
+
/**
|
|
2168
|
+
* @internal — not part of the stable public surface.
|
|
2169
|
+
*/
|
|
2170
|
+
get cache() {
|
|
2171
|
+
return this.#cache;
|
|
2172
|
+
}
|
|
2173
|
+
invalidate(keyPrefix) {
|
|
2174
|
+
this.#ensureOpen();
|
|
2175
|
+
this.#cache.invalidate(keyPrefix);
|
|
2176
|
+
}
|
|
2177
|
+
/** Runtime metrics: op totals, per-key latency, process health, slowest requests. Needs `read`. */
|
|
2178
|
+
async metrics(opts = {}) {
|
|
2179
|
+
this.#ensureOpen();
|
|
2180
|
+
return await (await this.#http.raw("/substrate/v1/metrics", {
|
|
2181
|
+
method: "GET",
|
|
2182
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
2183
|
+
})).json();
|
|
2184
|
+
}
|
|
2185
|
+
/** The recent error log. Needs `admin`. */
|
|
2186
|
+
async errors(opts = {}) {
|
|
2187
|
+
this.#ensureOpen();
|
|
2188
|
+
return await (await this.#http.raw("/substrate/v1/errors", {
|
|
2189
|
+
method: "GET",
|
|
2190
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
2191
|
+
})).json();
|
|
2192
|
+
}
|
|
2193
|
+
async close() {
|
|
2194
|
+
if (this.#closed) return;
|
|
2195
|
+
this.#closed = true;
|
|
2196
|
+
this.#closing.abort();
|
|
2197
|
+
}
|
|
2198
|
+
async #refetchSchema() {
|
|
2199
|
+
const schema = await this.#http.federatedSchema();
|
|
2200
|
+
this.#schemaCache = schema;
|
|
2201
|
+
}
|
|
2202
|
+
async #decode(raw, frame, wire) {
|
|
2203
|
+
let env;
|
|
2204
|
+
if (wire === "pack" && isPackMarker(raw)) {
|
|
2205
|
+
const bytes = raw.__packBytes;
|
|
2206
|
+
const decode = (expectedSchemaVersion) => decodeEnvelope(bytes, {
|
|
2207
|
+
...this.#buildDecodeCtx(frame, this.#schemaCache ?? {}),
|
|
2208
|
+
...expectedSchemaVersion !== void 0 ? { expectedSchemaVersion } : {}
|
|
2209
|
+
});
|
|
2210
|
+
try {
|
|
2211
|
+
env = decode(this.#driftCachedVersion ?? void 0);
|
|
2212
|
+
} catch (err) {
|
|
2213
|
+
if (!(err instanceof SchemaDriftError)) throw err;
|
|
2214
|
+
await this.#refetchSchema();
|
|
2215
|
+
this.#driftCachedVersion = err.envelopeSchemaVersion;
|
|
2216
|
+
env = decode();
|
|
2217
|
+
}
|
|
2218
|
+
} else env = decodeJsonEnvelope(raw);
|
|
2219
|
+
if (this.#driftCachedVersion === null) this.#driftCachedVersion = env.schemaVersion;
|
|
2220
|
+
else if (this.#driftCachedVersion !== env.schemaVersion) {
|
|
2221
|
+
await this.#refetchSchema();
|
|
2222
|
+
this.#driftCachedVersion = env.schemaVersion;
|
|
2223
|
+
}
|
|
2224
|
+
collectDiagnostics(env._diagnostics, this.#onDiagnostics);
|
|
2225
|
+
return env;
|
|
2226
|
+
}
|
|
2227
|
+
/**
|
|
2228
|
+
* Wrap a frame event stream so each `data`-bearing frame (snapshot/add/update/
|
|
2229
|
+
* chunk) gets its positional tuple values reconstructed into named-object
|
|
2230
|
+
* rows using the cached federated schema. Errors from the inner stream
|
|
2231
|
+
* (transport drop, server error frame) propagate untouched.
|
|
2232
|
+
*
|
|
2233
|
+
* The decode plan is built once, after the schema resolves, and reused for
|
|
2234
|
+
* every frame of the subscription.
|
|
2235
|
+
*
|
|
2236
|
+
* Hand-rolled iterator, NOT a native async generator: the generator form
|
|
2237
|
+
* queues return() behind an in-flight next(), which on a quiet connection
|
|
2238
|
+
* never resolves, so close() would hang. return() here forwards immediately.
|
|
2239
|
+
*/
|
|
2240
|
+
#wrapPackDecode(inner, frameSpec) {
|
|
2241
|
+
const buildPlan = async () => {
|
|
2242
|
+
const schemas = await this.federatedSchema();
|
|
2243
|
+
return buildDecodePlan(frameSpec, schemas);
|
|
2244
|
+
};
|
|
2245
|
+
return { [Symbol.asyncIterator]: () => {
|
|
2246
|
+
const innerIt = inner[Symbol.asyncIterator]();
|
|
2247
|
+
let planPromise = null;
|
|
2248
|
+
return {
|
|
2249
|
+
async next() {
|
|
2250
|
+
planPromise ??= buildPlan();
|
|
2251
|
+
const plan = await planPromise;
|
|
2252
|
+
const result = await innerIt.next();
|
|
2253
|
+
if (!result.done) applyDecodePlanInPlace(result.value, plan);
|
|
2254
|
+
return result;
|
|
2255
|
+
},
|
|
2256
|
+
async return() {
|
|
2257
|
+
await innerIt.return?.();
|
|
2258
|
+
return {
|
|
2259
|
+
value: void 0,
|
|
2260
|
+
done: true
|
|
2261
|
+
};
|
|
2262
|
+
}
|
|
2263
|
+
};
|
|
2264
|
+
} };
|
|
2265
|
+
}
|
|
2266
|
+
#buildDecodeCtx(frame, schemas) {
|
|
2267
|
+
const fieldsByKey = {};
|
|
2268
|
+
const returnsByKey = {};
|
|
2269
|
+
const typeByKey = {};
|
|
2270
|
+
const currentNsByKey = {};
|
|
2271
|
+
for (const key of Object.keys(frame)) {
|
|
2272
|
+
const frameEntry = frame[key];
|
|
2273
|
+
const entry = Array.isArray(frameEntry) ? frameEntry[0] : frameEntry;
|
|
2274
|
+
const parsed = parseQualifiedKey(key);
|
|
2275
|
+
if (parsed === null) continue;
|
|
2276
|
+
const { ns, name } = parsed;
|
|
2277
|
+
currentNsByKey[key] = ns;
|
|
2278
|
+
typeByKey[key] = name;
|
|
2279
|
+
const mutation = schemas[ns]?.mutations[name];
|
|
2280
|
+
if (mutation !== void 0) {
|
|
2281
|
+
const shapeOf = (fields) => mutationReturns(mutation, fields);
|
|
2282
|
+
returnsByKey[key] = Array.isArray(frameEntry) ? frameEntry.map((f) => shapeOf(f.fields)) : shapeOf(entry?.fields);
|
|
2283
|
+
} else fieldsByKey[key] = entry?.fields ?? {};
|
|
2284
|
+
}
|
|
2285
|
+
return {
|
|
2286
|
+
fieldsByKey,
|
|
2287
|
+
returnsByKey,
|
|
2288
|
+
typeByKey,
|
|
2289
|
+
schemas,
|
|
2290
|
+
currentNsByKey
|
|
2291
|
+
};
|
|
2292
|
+
}
|
|
2293
|
+
};
|
|
2294
|
+
function flatFrame(frame) {
|
|
2295
|
+
const flat = {};
|
|
2296
|
+
for (const [key, entry] of Object.entries(frame)) {
|
|
2297
|
+
const single = Array.isArray(entry) ? entry[0] : entry;
|
|
2298
|
+
flat[key] = {
|
|
2299
|
+
params: single?.params ?? {},
|
|
2300
|
+
fields: single?.fields ?? {}
|
|
2301
|
+
};
|
|
2302
|
+
}
|
|
2303
|
+
return flat;
|
|
2304
|
+
}
|
|
2305
|
+
|
|
2306
|
+
//#endregion
|
|
2307
|
+
//#region ../../packages/substrate-client/src/script.ts
|
|
2308
|
+
const DEFAULT_MAX_WRITES = 50;
|
|
2309
|
+
const DEFAULT_MAX_PAGES = 200;
|
|
2310
|
+
/** Counts the frames in a mutate payload: an array under an op-key is one frame per element. */
|
|
2311
|
+
function frameCount(frame) {
|
|
2312
|
+
return Object.values(frame).reduce((n, v) => n + (Array.isArray(v) ? v.length : 1), 0);
|
|
2313
|
+
}
|
|
2314
|
+
function assertKeys(frame, env, verb) {
|
|
2315
|
+
const missing = Object.keys(frame).filter((k) => !(k in env.data));
|
|
2316
|
+
if (missing.length > 0 || verb === "mutate" && (env.errors?.length ?? 0) > 0) {
|
|
2317
|
+
const errs = (env.errors ?? []).map((e) => `${e.code ?? "error"}: ${e.message}`).join("; ");
|
|
2318
|
+
throw new Error(`${verb} refused${missing.length > 0 ? ` for ${missing.join(", ")}` : ""}${errs !== "" ? ` (${errs})` : ""}`);
|
|
2319
|
+
}
|
|
2320
|
+
}
|
|
2321
|
+
/**
|
|
2322
|
+
* Runs `script` against a guarded context and reports everything it did,
|
|
2323
|
+
* including the mutations applied before any failure.
|
|
2324
|
+
*/
|
|
2325
|
+
async function runScript(script, opts) {
|
|
2326
|
+
const { client, kid, mode = "read", args = {}, maxWrites = 50, maxPages = DEFAULT_MAX_PAGES } = opts;
|
|
2327
|
+
const log = opts.log ?? ((line) => console.error(line));
|
|
2328
|
+
const mutations = [];
|
|
2329
|
+
const warnings = [];
|
|
2330
|
+
const stats = {
|
|
2331
|
+
queries: 0,
|
|
2332
|
+
writes: 0,
|
|
2333
|
+
ms: 0
|
|
2334
|
+
};
|
|
2335
|
+
const started = Date.now();
|
|
2336
|
+
const query = async (frame) => {
|
|
2337
|
+
stats.queries++;
|
|
2338
|
+
const env = await client.query(frame);
|
|
2339
|
+
assertKeys(frame, env, "query");
|
|
2340
|
+
for (const [key, page] of Object.entries(env._pagination ?? {})) if (page.hasMore) warnings.push(`${key}: result truncated (hasMore); use queryAll for a complete read`);
|
|
2341
|
+
return env;
|
|
2342
|
+
};
|
|
2343
|
+
const ctx = {
|
|
2344
|
+
kid,
|
|
2345
|
+
mode,
|
|
2346
|
+
args: Object.freeze({ ...args }),
|
|
2347
|
+
query,
|
|
2348
|
+
async queryAll(key, frame) {
|
|
2349
|
+
const rows = [];
|
|
2350
|
+
let cursor;
|
|
2351
|
+
for (let page = 0; page < maxPages; page++) {
|
|
2352
|
+
const params = {
|
|
2353
|
+
...frame.params,
|
|
2354
|
+
...cursor !== void 0 ? { cursor } : {}
|
|
2355
|
+
};
|
|
2356
|
+
stats.queries++;
|
|
2357
|
+
const env = await client.query({ [key]: {
|
|
2358
|
+
...frame,
|
|
2359
|
+
params
|
|
2360
|
+
} });
|
|
2361
|
+
assertKeys({ [key]: frame }, env, "query");
|
|
2362
|
+
const data = env.data[key];
|
|
2363
|
+
rows.push(...Array.isArray(data) ? data : [data]);
|
|
2364
|
+
const p = env._pagination?.[key];
|
|
2365
|
+
if (p?.hasMore !== true) return rows;
|
|
2366
|
+
if (p.nextCursor === void 0) throw new Error(`${key}: hasMore with no nextCursor`);
|
|
2367
|
+
cursor = p.nextCursor;
|
|
2368
|
+
}
|
|
2369
|
+
throw new Error(`${key}: still hasMore after ${maxPages} pages`);
|
|
2370
|
+
},
|
|
2371
|
+
async recall({ query: to, row, ...params }) {
|
|
2372
|
+
const fields = row === void 0 ? {} : { fields: {
|
|
2373
|
+
id: true,
|
|
2374
|
+
namespace: true,
|
|
2375
|
+
type: true,
|
|
2376
|
+
score: true,
|
|
2377
|
+
kind: true,
|
|
2378
|
+
expandedFrom: true,
|
|
2379
|
+
row
|
|
2380
|
+
} };
|
|
2381
|
+
return (await query({ "recall/Hit": {
|
|
2382
|
+
params: {
|
|
2383
|
+
to,
|
|
2384
|
+
...params
|
|
2385
|
+
},
|
|
2386
|
+
...fields
|
|
2387
|
+
} })).data["recall/Hit"];
|
|
2388
|
+
},
|
|
2389
|
+
async schema(namespace, type) {
|
|
2390
|
+
const all = await client.federatedSchema();
|
|
2391
|
+
if (namespace === void 0) return all;
|
|
2392
|
+
const ns = all[namespace];
|
|
2393
|
+
if (ns === void 0) throw new Error(`schema: unknown namespace '${namespace}'`);
|
|
2394
|
+
if (type === void 0) return ns;
|
|
2395
|
+
const t = ns.types[type];
|
|
2396
|
+
if (t === void 0) throw new Error(`schema: unknown type '${namespace}/${type}'`);
|
|
2397
|
+
return t;
|
|
2398
|
+
},
|
|
2399
|
+
async mutate(frame) {
|
|
2400
|
+
if (mode === "read") throw new Error("mutate refused: read mode (run in dry-run or write mode)");
|
|
2401
|
+
if (mode === "dry-run") {
|
|
2402
|
+
mutations.push({
|
|
2403
|
+
frame,
|
|
2404
|
+
applied: false
|
|
2405
|
+
});
|
|
2406
|
+
return null;
|
|
2407
|
+
}
|
|
2408
|
+
const n = frameCount(frame);
|
|
2409
|
+
if (stats.writes + n > maxWrites) throw new Error(`mutate refused: ${stats.writes + n} frames would exceed --max-writes ${maxWrites}`);
|
|
2410
|
+
const env = await client.mutate(frame);
|
|
2411
|
+
const applied = Object.keys(frame).some((k) => k in env.data);
|
|
2412
|
+
if (applied) stats.writes += n;
|
|
2413
|
+
mutations.push({
|
|
2414
|
+
frame,
|
|
2415
|
+
applied,
|
|
2416
|
+
...env.errors !== void 0 ? { errors: env.errors } : {}
|
|
2417
|
+
});
|
|
2418
|
+
assertKeys(frame, env, "mutate");
|
|
2419
|
+
return env;
|
|
2420
|
+
},
|
|
2421
|
+
log: (...args) => log(args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" "))
|
|
2422
|
+
};
|
|
2423
|
+
const report = (extra) => {
|
|
2424
|
+
stats.ms = Date.now() - started;
|
|
2425
|
+
return {
|
|
2426
|
+
...extra,
|
|
2427
|
+
kid,
|
|
2428
|
+
mode,
|
|
2429
|
+
args,
|
|
2430
|
+
mutations,
|
|
2431
|
+
warnings,
|
|
2432
|
+
stats
|
|
2433
|
+
};
|
|
2434
|
+
};
|
|
2435
|
+
try {
|
|
2436
|
+
return report({
|
|
2437
|
+
ok: true,
|
|
2438
|
+
result: await script(ctx)
|
|
2439
|
+
});
|
|
2440
|
+
} catch (err) {
|
|
2441
|
+
return report({
|
|
2442
|
+
ok: false,
|
|
2443
|
+
error: err instanceof Error ? err.message : String(err)
|
|
2444
|
+
});
|
|
2445
|
+
}
|
|
2446
|
+
}
|
|
2447
|
+
|
|
2448
|
+
//#endregion
|
|
2449
|
+
//#region ../../packages/substrate-client/src/token-target.ts
|
|
2450
|
+
/**
|
|
2451
|
+
* Where a freshly minted credential may be sent: an https origin, or plain
|
|
2452
|
+
* http only to a loopback host, where nothing on the network can read it.
|
|
2453
|
+
*/
|
|
2454
|
+
const LOOPBACK = /^(localhost|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[::1\])$/;
|
|
2455
|
+
/**
|
|
2456
|
+
* @returns the origin of `baseUrl`, which a token for it names as its `aud`.
|
|
2457
|
+
* @throws Error when `baseUrl` is not a URL, or is plain http to a non-loopback host.
|
|
2458
|
+
*/
|
|
2459
|
+
function tokenAudience(baseUrl) {
|
|
2460
|
+
let url;
|
|
2461
|
+
try {
|
|
2462
|
+
url = new URL(baseUrl);
|
|
2463
|
+
} catch {
|
|
2464
|
+
throw new Error(`'${baseUrl}' is not a URL`);
|
|
2465
|
+
}
|
|
2466
|
+
if (url.protocol === "https:" || url.protocol === "http:" && LOOPBACK.test(url.hostname)) return url.origin;
|
|
2467
|
+
throw new Error(`refusing to send a credential to ${url.origin}: use https, or plain http only to a loopback host`);
|
|
2468
|
+
}
|
|
2469
|
+
/** `fetchImpl` with redirects refused: a redirect would carry the credential to wherever it points. */
|
|
2470
|
+
function noRedirectFetch(fetchImpl = substrateFetch) {
|
|
2471
|
+
return (input, init) => fetchImpl(input, {
|
|
2472
|
+
...init,
|
|
2473
|
+
redirect: "error"
|
|
2474
|
+
});
|
|
2475
|
+
}
|
|
2476
|
+
|
|
2477
|
+
//#endregion
|
|
2478
|
+
export { AdminBackfillError, AuthError, BACKFILL_CHUNK, CURRENT_MARK, DEFAULT_MAX_WRITES, NetworkError, ONBOARD_STEPS, SKIPPABLE_STEPS, STEP_MARKS, SchemaDriftError, SubscribeError, SubstrateClient, collectDiagnostics, createDefaultDiagnosticsSink, currentStep, noRedirectFetch, planOnboarding, reduceSubscribeRows, requiredOutstanding, runScript, substrateFetch, tokenAudience, watchRows };
|