@mnmal-ai/substrate 0.0.0 → 1.0.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +118 -1
- package/dist/agent-token-BIboWOU0.js +200 -0
- package/dist/client.d.ts +782 -0
- package/dist/client.js +7 -0
- package/dist/cluster-worker.js +35 -0
- package/dist/content-type-C7T28xNb.js +25 -0
- package/dist/dataset-DOXGRz50.js +1535 -0
- package/dist/env-utils-B7SGmoeJ.js +21 -0
- package/dist/errors-D4vKuwz8.d.ts +130 -0
- package/dist/fake-DUVtKVSE.js +36 -0
- package/dist/index-D7mSOFlM.d.ts +69 -0
- package/dist/pack.d.ts +192 -0
- package/dist/pack.js +5 -0
- package/dist/plugin-BuQQEzL-.js +3844 -0
- package/dist/plugin-t2g2wX0b.d.ts +1568 -0
- package/dist/proposals-bootstrap.js +37 -0
- package/dist/proposals.config.schema.json +20 -0
- package/dist/proposals.d.ts +118 -0
- package/dist/proposals.default-config.json +4 -0
- package/dist/proposals.js +4 -0
- package/dist/recall-bootstrap.js +451 -0
- package/dist/recall.config.schema.json +232 -0
- package/dist/recall.d.ts +1981 -0
- package/dist/recall.default-config.json +4 -0
- package/dist/recall.js +5 -0
- package/dist/repl-C52wyfMs.js +2213 -0
- package/dist/row-ByLFE2Wx.d.ts +719 -0
- package/dist/row-DK7lPZVe.js +732 -0
- package/dist/runtime-metrics-DwpDJ8vz.d.ts +159 -0
- package/dist/schema-g4FQLr0V.d.ts +433 -0
- package/dist/sdk.d.ts +694 -0
- package/dist/sdk.js +112 -0
- package/dist/src-5hVbeiAu.js +1797 -0
- package/dist/src-C4DzaIQZ.js +837 -0
- package/dist/src-CjEwiKXw.js +2327 -0
- package/dist/src-DuopV8u7.js +2408 -0
- package/dist/src-YXlv_RyL.js +13524 -0
- package/dist/src-zcyUofMJ.js +1015 -0
- package/dist/substrate-admin.js +808 -0
- package/dist/substrate.js +5482 -0
- package/dist/testing.d.ts +1240 -0
- package/dist/testing.js +702 -0
- package/dist/types-8c0gtnd2.d.ts +35 -0
- package/dist/ws-C72iVS5T.d.ts +143 -0
- package/package.json +117 -4
|
@@ -0,0 +1,2408 @@
|
|
|
1
|
+
import { createRequire as __binCreateRequire } from 'node:module'; const require = __binCreateRequire(import.meta.url);
|
|
2
|
+
import { D as isActiveAdminKeyRow, O as capabilitiesFor, T as SYSTEM_NAMESPACE } from "./row-DK7lPZVe.js";
|
|
3
|
+
import { _ as decodeEnvelope, a as buildDecodePlan, i as applyDecodePlanInPlace, o as decodeWsEnvelope, s as encodeWsFrame, t as WS_SUBPROTOCOL_SUBSTRATE_PACK, x as parseQualifiedKey } from "./src-C4DzaIQZ.js";
|
|
4
|
+
import { signal } from "@preact/signals-core";
|
|
5
|
+
import { WebSocket } from "ws";
|
|
6
|
+
|
|
7
|
+
//#region ../../packages/substrate-client/src/admin/diagnose.ts
|
|
8
|
+
/**
|
|
9
|
+
* The library behind `substrate-admin doctor` and substrate-tui's `/doctor` — diagnoses
|
|
10
|
+
* a deployment, and the identity presented to it, through checks that can each
|
|
11
|
+
* answer NO.
|
|
12
|
+
*
|
|
13
|
+
* 1. **Route-only.** Every auth claim is checked through the running server;
|
|
14
|
+
* a direct postgres read never authenticates, so it cannot test auth.
|
|
15
|
+
* 2. **A SKIP is not an OK.** A check whose precondition failed renders as
|
|
16
|
+
* `skip` with the reason — never as a pass, and never omitted.
|
|
17
|
+
* 3. **Shared classifiers.** Admin checks use `isActiveAdminKeyRow` and
|
|
18
|
+
* `capabilitiesFor`, the same predicates the server's guards use, so the
|
|
19
|
+
* doctor cannot agree with a copy that has drifted from the guard.
|
|
20
|
+
*/
|
|
21
|
+
const CHECK_REACHABLE = "reachable";
|
|
22
|
+
const CHECK_AUTH_ENABLED = "auth-enabled";
|
|
23
|
+
const CHECK_CREDENTIAL = "credential";
|
|
24
|
+
const CHECK_IDENTITY = "identity";
|
|
25
|
+
const CHECK_ADMIN = "admin-capability";
|
|
26
|
+
const CHECK_FLOOR = "admin-floor";
|
|
27
|
+
const CHECK_NAMESPACES = "namespaces";
|
|
28
|
+
const CHECK_DIR = "key-directory";
|
|
29
|
+
/** Every check downstream of a failure, so a skip is never silent. */
|
|
30
|
+
const DOWNSTREAM = {
|
|
31
|
+
[CHECK_REACHABLE]: [
|
|
32
|
+
CHECK_AUTH_ENABLED,
|
|
33
|
+
CHECK_CREDENTIAL,
|
|
34
|
+
CHECK_IDENTITY,
|
|
35
|
+
CHECK_ADMIN,
|
|
36
|
+
CHECK_FLOOR,
|
|
37
|
+
CHECK_NAMESPACES,
|
|
38
|
+
CHECK_DIR
|
|
39
|
+
],
|
|
40
|
+
[CHECK_CREDENTIAL]: [
|
|
41
|
+
CHECK_IDENTITY,
|
|
42
|
+
CHECK_ADMIN,
|
|
43
|
+
CHECK_FLOOR,
|
|
44
|
+
CHECK_NAMESPACES,
|
|
45
|
+
CHECK_DIR
|
|
46
|
+
],
|
|
47
|
+
[CHECK_IDENTITY]: [
|
|
48
|
+
CHECK_ADMIN,
|
|
49
|
+
CHECK_FLOOR,
|
|
50
|
+
CHECK_DIR
|
|
51
|
+
],
|
|
52
|
+
[CHECK_ADMIN]: [CHECK_FLOOR, CHECK_DIR],
|
|
53
|
+
[CHECK_FLOOR]: [CHECK_DIR]
|
|
54
|
+
};
|
|
55
|
+
var Checks = class {
|
|
56
|
+
rows = [];
|
|
57
|
+
ok(name, detail) {
|
|
58
|
+
this.rows.push({
|
|
59
|
+
name,
|
|
60
|
+
status: "ok",
|
|
61
|
+
detail
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
/** Asked and unanswerable — recorded explicitly so absence never reads as health. */
|
|
65
|
+
skip(name, detail) {
|
|
66
|
+
this.rows.push({
|
|
67
|
+
name,
|
|
68
|
+
status: "skip",
|
|
69
|
+
detail
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
/** Record a failure AND every check it makes unanswerable. */
|
|
73
|
+
no(name, detail, fix, httpStatus) {
|
|
74
|
+
this.rows.push({
|
|
75
|
+
name,
|
|
76
|
+
status: "no",
|
|
77
|
+
detail,
|
|
78
|
+
fix,
|
|
79
|
+
...httpStatus !== void 0 ? { httpStatus } : {}
|
|
80
|
+
});
|
|
81
|
+
for (const dep of DOWNSTREAM[name] ?? []) this.rows.push({
|
|
82
|
+
name: dep,
|
|
83
|
+
status: "skip",
|
|
84
|
+
detail: `not asked — ${name} answered no`
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
has(name) {
|
|
88
|
+
return this.rows.some((c) => c.name === name);
|
|
89
|
+
}
|
|
90
|
+
done() {
|
|
91
|
+
return {
|
|
92
|
+
checks: this.rows,
|
|
93
|
+
exitCode: this.rows.some((c) => c.status === "no") ? 1 : 0
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
/** The `grants` block `GET /substrate/v1/whoami` returns, resolved back into a Grant. */
|
|
98
|
+
function grantFromWhoami(grants) {
|
|
99
|
+
if (grants === null || typeof grants !== "object" || Array.isArray(grants)) return null;
|
|
100
|
+
const out = /* @__PURE__ */ new Map();
|
|
101
|
+
for (const [ns, caps] of Object.entries(grants)) {
|
|
102
|
+
if (!Array.isArray(caps)) return null;
|
|
103
|
+
out.set(ns, new Set(caps.filter((c) => typeof c === "string")));
|
|
104
|
+
}
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
async function getJson(url, fetchImpl, headers = {}) {
|
|
108
|
+
let res;
|
|
109
|
+
try {
|
|
110
|
+
res = await fetchImpl(url, { headers });
|
|
111
|
+
} catch (err) {
|
|
112
|
+
return { error: err instanceof Error ? err.message : String(err) };
|
|
113
|
+
}
|
|
114
|
+
const body = await res.json().catch(() => ({}));
|
|
115
|
+
return {
|
|
116
|
+
status: res.status,
|
|
117
|
+
body
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Pages every live (non-revoked) Key row. Paged to completion because an
|
|
122
|
+
* admin floor computed off one page is wrong.
|
|
123
|
+
*
|
|
124
|
+
* Rows are returned raw — callers classify with `isActiveAdminKeyRow`, not by
|
|
125
|
+
* reading `capabilities`: a key stored `namespaces: '*:read+mutate+admin'`
|
|
126
|
+
* carries no `admin` in `capabilities` and is nonetheless an admin.
|
|
127
|
+
*/
|
|
128
|
+
async function listLiveKeys(baseUrl, authorization, fetchImpl) {
|
|
129
|
+
const frameKey = `${SYSTEM_NAMESPACE}/Key`;
|
|
130
|
+
const rows = [];
|
|
131
|
+
let cursor = null;
|
|
132
|
+
for (;;) {
|
|
133
|
+
const params = {
|
|
134
|
+
where: { revokedAt: { eq: null } },
|
|
135
|
+
limit: 200,
|
|
136
|
+
...cursor !== null ? { cursor } : {}
|
|
137
|
+
};
|
|
138
|
+
let res;
|
|
139
|
+
try {
|
|
140
|
+
res = await fetchImpl(`${baseUrl}/substrate/v1/query`, {
|
|
141
|
+
method: "POST",
|
|
142
|
+
headers: {
|
|
143
|
+
"content-type": "application/json",
|
|
144
|
+
authorization
|
|
145
|
+
},
|
|
146
|
+
body: JSON.stringify({ [frameKey]: {
|
|
147
|
+
params,
|
|
148
|
+
fields: {
|
|
149
|
+
kid: true,
|
|
150
|
+
namespaces: true,
|
|
151
|
+
capabilities: true,
|
|
152
|
+
revokedAt: true
|
|
153
|
+
}
|
|
154
|
+
} })
|
|
155
|
+
});
|
|
156
|
+
} catch (err) {
|
|
157
|
+
return { error: err instanceof Error ? err.message : String(err) };
|
|
158
|
+
}
|
|
159
|
+
const payload = await res.json().catch(() => ({}));
|
|
160
|
+
const data = payload.data;
|
|
161
|
+
if (data === void 0 || !(frameKey in data)) {
|
|
162
|
+
const errors = JSON.stringify(payload.errors ?? payload);
|
|
163
|
+
return { error: `HTTP ${res.status}, frame absent: ${errors}` };
|
|
164
|
+
}
|
|
165
|
+
const page = data[frameKey];
|
|
166
|
+
if (!Array.isArray(page)) return { error: `unexpected shape for ${frameKey}` };
|
|
167
|
+
rows.push(...page);
|
|
168
|
+
const pagination = payload._pagination?.[frameKey];
|
|
169
|
+
if (pagination?.hasMore !== true) break;
|
|
170
|
+
if (typeof pagination.nextCursor !== "string") return { error: `${frameKey}: server reported hasMore with no nextCursor` };
|
|
171
|
+
cursor = pagination.nextCursor;
|
|
172
|
+
}
|
|
173
|
+
return { rows };
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Page the AgentIdentity directory. Returns `{ absent }` — NOT an empty list —
|
|
177
|
+
* when the frame never came back: this credential may simply lack read on
|
|
178
|
+
* `cortext` (an `_system`-scoped admin does), and an empty directory reads as
|
|
179
|
+
* "every live key is orphaned", which is the opposite of what was measured.
|
|
180
|
+
*/
|
|
181
|
+
async function listDirectoryIdentities(baseUrl, authorization, fetchImpl) {
|
|
182
|
+
const frameKey = "cortext/AgentIdentity";
|
|
183
|
+
const rows = [];
|
|
184
|
+
let cursor = null;
|
|
185
|
+
for (;;) {
|
|
186
|
+
const params = {
|
|
187
|
+
limit: 200,
|
|
188
|
+
...cursor !== null ? { cursor } : {}
|
|
189
|
+
};
|
|
190
|
+
let res;
|
|
191
|
+
try {
|
|
192
|
+
res = await fetchImpl(`${baseUrl}/substrate/v1/query`, {
|
|
193
|
+
method: "POST",
|
|
194
|
+
headers: {
|
|
195
|
+
"content-type": "application/json",
|
|
196
|
+
authorization
|
|
197
|
+
},
|
|
198
|
+
body: JSON.stringify({ [frameKey]: {
|
|
199
|
+
params,
|
|
200
|
+
fields: {
|
|
201
|
+
kid: true,
|
|
202
|
+
host: true,
|
|
203
|
+
active: true
|
|
204
|
+
}
|
|
205
|
+
} })
|
|
206
|
+
});
|
|
207
|
+
} catch (err) {
|
|
208
|
+
return { error: err instanceof Error ? err.message : String(err) };
|
|
209
|
+
}
|
|
210
|
+
const payload = await res.json().catch(() => ({}));
|
|
211
|
+
const data = payload.data;
|
|
212
|
+
if (data === void 0 || !(frameKey in data)) {
|
|
213
|
+
const errors = JSON.stringify(payload.errors ?? payload);
|
|
214
|
+
return { absent: `HTTP ${res.status}, frame absent: ${errors}` };
|
|
215
|
+
}
|
|
216
|
+
const page = data[frameKey];
|
|
217
|
+
if (!Array.isArray(page)) return { error: `unexpected shape for ${frameKey}` };
|
|
218
|
+
rows.push(...page);
|
|
219
|
+
const pagination = payload._pagination?.[frameKey];
|
|
220
|
+
if (pagination?.hasMore !== true) break;
|
|
221
|
+
if (typeof pagination.nextCursor !== "string") return { error: `${frameKey}: server reported hasMore with no nextCursor` };
|
|
222
|
+
cursor = pagination.nextCursor;
|
|
223
|
+
}
|
|
224
|
+
return { rows };
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Reconciles live Key rows against AgentIdentity rows, returning retired
|
|
228
|
+
* identities that still hold a live key and live keys with no directory row.
|
|
229
|
+
*
|
|
230
|
+
* Admin keys are exempt from the second list by CAPABILITY, never by kid: the
|
|
231
|
+
* bootstrap root of trust has no directory row by design.
|
|
232
|
+
*
|
|
233
|
+
* A row whose `active` is absent counts as ACTIVE — only an explicit `false`
|
|
234
|
+
* deactivates. Rows predating the field must not read as decommissioned.
|
|
235
|
+
* A key row with no string kid is unmatchable and ignored (doctor is not a
|
|
236
|
+
* corruption scanner).
|
|
237
|
+
*/
|
|
238
|
+
function reconcileIdentities(keys, identities, adminCapability) {
|
|
239
|
+
const liveByKid = /* @__PURE__ */ new Map();
|
|
240
|
+
for (const key of keys) {
|
|
241
|
+
if (typeof key.kid !== "string" || key.kid.length === 0) continue;
|
|
242
|
+
if (!liveByKid.has(key.kid)) liveByKid.set(key.kid, key);
|
|
243
|
+
}
|
|
244
|
+
const activeByKid = /* @__PURE__ */ new Map();
|
|
245
|
+
for (const identity of identities) {
|
|
246
|
+
if (typeof identity.kid !== "string" || identity.kid.length === 0) continue;
|
|
247
|
+
if (!activeByKid.has(identity.kid)) activeByKid.set(identity.kid, identity.active !== false);
|
|
248
|
+
}
|
|
249
|
+
const retiredWithLiveKey = [];
|
|
250
|
+
const liveKeyWithoutRow = [];
|
|
251
|
+
const agentKids = [];
|
|
252
|
+
for (const [kid, key] of liveByKid) {
|
|
253
|
+
const active = activeByKid.get(kid);
|
|
254
|
+
const admin = isActiveAdminKeyRow(key, adminCapability);
|
|
255
|
+
if (active === false) retiredWithLiveKey.push(kid);
|
|
256
|
+
else if (active === void 0 && !admin) liveKeyWithoutRow.push(kid);
|
|
257
|
+
else if (active === true && !admin) agentKids.push(kid);
|
|
258
|
+
}
|
|
259
|
+
retiredWithLiveKey.sort();
|
|
260
|
+
liveKeyWithoutRow.sort();
|
|
261
|
+
agentKids.sort();
|
|
262
|
+
return {
|
|
263
|
+
retiredWithLiveKey,
|
|
264
|
+
liveKeyWithoutRow,
|
|
265
|
+
agentKids
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
/** Every check `diagnose` can emit, in dependency order: what a caller marks NOT ASKED when it
|
|
269
|
+
* cannot run diagnose at all (the CLI's direct-to-postgres target). */
|
|
270
|
+
const DIAGNOSE_CHECKS = [
|
|
271
|
+
CHECK_REACHABLE,
|
|
272
|
+
CHECK_AUTH_ENABLED,
|
|
273
|
+
CHECK_CREDENTIAL,
|
|
274
|
+
CHECK_IDENTITY,
|
|
275
|
+
CHECK_ADMIN,
|
|
276
|
+
CHECK_FLOOR,
|
|
277
|
+
CHECK_NAMESPACES,
|
|
278
|
+
CHECK_DIR
|
|
279
|
+
];
|
|
280
|
+
/**
|
|
281
|
+
* Runs every check against `opts.baseUrl`, in dependency order. A failure
|
|
282
|
+
* short-circuits its dependants into explicit skips.
|
|
283
|
+
*/
|
|
284
|
+
async function diagnose(opts) {
|
|
285
|
+
const checks = new Checks();
|
|
286
|
+
const fetchImpl = opts.fetch ?? fetch;
|
|
287
|
+
const adminCapability = opts.adminCapability ?? "admin";
|
|
288
|
+
const baseUrl = opts.baseUrl.replace(/\/+$/, "");
|
|
289
|
+
let identityId = null;
|
|
290
|
+
let facts = {};
|
|
291
|
+
const done = () => ({
|
|
292
|
+
...checks.done(),
|
|
293
|
+
identity: identityId,
|
|
294
|
+
facts
|
|
295
|
+
});
|
|
296
|
+
const health = await getJson(`${baseUrl}/health`, fetchImpl);
|
|
297
|
+
if ("error" in health) {
|
|
298
|
+
checks.no(CHECK_REACHABLE, `${baseUrl}/health could not be reached: ${health.error}`, "Check the URL, that the service is up (`systemctl status substrate-binary`), and that TLS trusts the certificate.");
|
|
299
|
+
return done();
|
|
300
|
+
}
|
|
301
|
+
if (health.status !== 200) {
|
|
302
|
+
checks.no(CHECK_REACHABLE, `${baseUrl}/health answered HTTP ${health.status}`, "The server is answering but unhealthy — read `journalctl -u substrate-binary`.", health.status);
|
|
303
|
+
return done();
|
|
304
|
+
}
|
|
305
|
+
checks.ok(CHECK_REACHABLE, `${baseUrl} is up, version ${String(health.body.version ?? "?")}`);
|
|
306
|
+
const posture = await getJson(`${baseUrl}/substrate/v1/whoami`, fetchImpl);
|
|
307
|
+
const authEnabled = "error" in posture ? void 0 : posture.body.authEnabled;
|
|
308
|
+
if (authEnabled === false) checks.no(CHECK_AUTH_ENABLED, "the deployment has auth DISABLED — it verifies nothing, and every caller is anonymous. An admin credential cannot resolve here no matter how correct it is, and `policy_denied: no identity` is what that looks like from three layers up.", "Set SUBSTRATE_AUTH_MODE on the server (attribute or required) and restart it — the setting is read at boot, so an edit alone changes nothing.");
|
|
309
|
+
else if (authEnabled === true) checks.ok(CHECK_AUTH_ENABLED, "the server verifies credentials (authEnabled true)");
|
|
310
|
+
else checks.ok(CHECK_AUTH_ENABLED, "could not read authEnabled from /substrate/v1/whoami — treating as unknown, not as on");
|
|
311
|
+
const cred = opts.credential;
|
|
312
|
+
if ("error" in cred) {
|
|
313
|
+
checks.no(CHECK_CREDENTIAL, cred.error, cred.fix ?? "Set SUBSTRATE_ADMIN_TOKEN, or SUBSTRATE_ADMIN_KEY_PATH + SUBSTRATE_ADMIN_KEY_ID, or run `substrate-admin bootstrap` on a deployment that has no admin yet.");
|
|
314
|
+
return done();
|
|
315
|
+
}
|
|
316
|
+
checks.ok(CHECK_CREDENTIAL, `a token was minted from ${cred.label}`);
|
|
317
|
+
const authorization = cred.authorization();
|
|
318
|
+
const onboard = await getJson(`${baseUrl}/substrate/v1/onboard`, fetchImpl, { authorization });
|
|
319
|
+
const onboardFix = "The server is up but could not say what it hosts — read `journalctl -u substrate-binary`.";
|
|
320
|
+
const binary = "error" in onboard ? void 0 : onboard.body.binary;
|
|
321
|
+
if ("error" in onboard) checks.no(CHECK_NAMESPACES, `${baseUrl}/substrate/v1/onboard could not be reached: ${onboard.error}`, onboardFix);
|
|
322
|
+
else if (onboard.status === 401 || onboard.status === 403) checks.skip(CHECK_NAMESPACES, `not asked — /substrate/v1/onboard refused the credential (HTTP ${onboard.status}); see identity`);
|
|
323
|
+
else if (onboard.status !== 200) checks.no(CHECK_NAMESPACES, `${baseUrl}/substrate/v1/onboard answered HTTP ${onboard.status}`, onboardFix, onboard.status);
|
|
324
|
+
else if (binary === void 0) checks.no(CHECK_NAMESPACES, "/substrate/v1/onboard answered 200 with no `binary` block, so the hosted namespaces are unknown", onboardFix, onboard.status);
|
|
325
|
+
else {
|
|
326
|
+
const coordinators = Array.isArray(binary.coordinators) ? binary.coordinators : [];
|
|
327
|
+
const hosted = /* @__PURE__ */ new Set([SYSTEM_NAMESPACE]);
|
|
328
|
+
for (const c of coordinators) for (const ns of Array.isArray(c.namespaces) ? c.namespaces : []) if (typeof ns === "string") hosted.add(ns);
|
|
329
|
+
for (const ns of Array.isArray(binary.virtualNamespaces) ? binary.virtualNamespaces : []) if (typeof ns === "string") hosted.add(ns);
|
|
330
|
+
checks.ok(CHECK_NAMESPACES, `hosted: ${[...hosted].sort().join(", ")}`);
|
|
331
|
+
}
|
|
332
|
+
const whoami = await getJson(`${baseUrl}/substrate/v1/whoami`, fetchImpl, { authorization });
|
|
333
|
+
if ("error" in whoami) {
|
|
334
|
+
checks.no(CHECK_IDENTITY, `${baseUrl}/substrate/v1/whoami could not be reached: ${whoami.error}`, "The health check passed, so this is likely a proxy or path problem rather than a down server.");
|
|
335
|
+
return done();
|
|
336
|
+
}
|
|
337
|
+
const identity = whoami.body.identity;
|
|
338
|
+
if (whoami.status === 401) {
|
|
339
|
+
checks.no(CHECK_IDENTITY, "the server REJECTED the credential (401). It arrived and did not verify — a wrong key/kid pair, or a kid with no live Key row.", "Confirm the kid names a live row (`substrate-admin list`) and that the private key beside it is the pair for that row's public key.", whoami.status);
|
|
340
|
+
return done();
|
|
341
|
+
}
|
|
342
|
+
if (identity === null || identity === void 0) {
|
|
343
|
+
checks.no(CHECK_IDENTITY, "the server saw NO identity on the request. The credential never arrived — this is not a rejection (that would be a 401), it is an absence.", "Check the token is being sent as `Authorization: Bearer …` and that no proxy is stripping the header.", whoami.status);
|
|
344
|
+
return done();
|
|
345
|
+
}
|
|
346
|
+
checks.ok(CHECK_IDENTITY, `the server resolved this credential as ${String(identity.id)}`);
|
|
347
|
+
identityId = String(identity.id);
|
|
348
|
+
if (opts.expectAdmin === false) {
|
|
349
|
+
for (const name of [
|
|
350
|
+
CHECK_ADMIN,
|
|
351
|
+
CHECK_FLOOR,
|
|
352
|
+
CHECK_DIR
|
|
353
|
+
]) checks.skip(name, "not asked — this identity was not expected to be an admin");
|
|
354
|
+
return done();
|
|
355
|
+
}
|
|
356
|
+
const grant = grantFromWhoami(identity.grants);
|
|
357
|
+
if (grant === null) {
|
|
358
|
+
checks.no(CHECK_ADMIN, "the whoami response carried no readable `grants` block, so what this identity may do cannot be established from here.", "Check `version` above against the client you are running: a server older than this client may not send `grants`.");
|
|
359
|
+
return done();
|
|
360
|
+
}
|
|
361
|
+
if (!capabilitiesFor(grant, "_system").has(adminCapability)) {
|
|
362
|
+
checks.no(CHECK_ADMIN, `the identity authenticates but its grant does not confer '${adminCapability}' on ${SYSTEM_NAMESPACE} — it has ${JSON.stringify(identity.grants)}. Every admin route will answer policy_denied, which names the missing capability but not that the credential itself is fine.`, `Widen the grant: substrate-admin update ${String(identity.id)} --ns '${SYSTEM_NAMESPACE}:read+mutate+${adminCapability}' --widen --allow-admin`);
|
|
363
|
+
return done();
|
|
364
|
+
}
|
|
365
|
+
checks.ok(CHECK_ADMIN, `the grant confers '${adminCapability}' on ${SYSTEM_NAMESPACE} — this identity can administer`);
|
|
366
|
+
const floor = await listLiveKeys(baseUrl, authorization, fetchImpl);
|
|
367
|
+
if ("error" in floor) {
|
|
368
|
+
checks.no(CHECK_FLOOR, `could not read ${SYSTEM_NAMESPACE}/Key: ${floor.error}`, "The identity is admin, so this is a route or store problem rather than a permission one — read `journalctl -u substrate-binary`.");
|
|
369
|
+
return done();
|
|
370
|
+
}
|
|
371
|
+
const admins = floor.rows.filter((row) => isActiveAdminKeyRow(row, adminCapability)).map((row) => String(row.kid));
|
|
372
|
+
facts = {
|
|
373
|
+
...facts,
|
|
374
|
+
adminKids: admins,
|
|
375
|
+
liveKeyCount: floor.rows.length
|
|
376
|
+
};
|
|
377
|
+
if (admins.length === 0) {
|
|
378
|
+
checks.no(CHECK_FLOOR, `${floor.rows.length} live keys and NONE of them classifies as admin — yet the credential above just authenticated as one. The two answers disagree, which means the classifier and the policy have diverged.`, "Report it — do not revoke anything until it is understood.");
|
|
379
|
+
return done();
|
|
380
|
+
}
|
|
381
|
+
const roster = admins.join(", ");
|
|
382
|
+
checks.ok(CHECK_FLOOR, admins.length === 1 ? `1 admin key of ${floor.rows.length} live: ${roster}. NOTE: it is the last one — the floor will refuse to revoke it, and losing it locks the deployment out of its own admin surface. Register a second before you need one.` : `${admins.length} admin keys of ${floor.rows.length} live: ${roster}. Succession is possible — either can be rotated out while the other administers.`);
|
|
383
|
+
const directory = await listDirectoryIdentities(baseUrl, authorization, fetchImpl);
|
|
384
|
+
if ("error" in directory) {
|
|
385
|
+
checks.no(CHECK_DIR, `could not read cortext/AgentIdentity: ${directory.error}`, "The identity is admin, so this is a route or store problem rather than a permission one — read `journalctl -u substrate-binary`.");
|
|
386
|
+
return done();
|
|
387
|
+
}
|
|
388
|
+
if ("absent" in directory) {
|
|
389
|
+
checks.skip(CHECK_DIR, `not asked — the directory frame never came back. This credential cannot read cortext/AgentIdentity (${directory.absent}), so there is no directory to reconcile against, and an empty one would read as "every live key is orphaned". Re-run with an identity granted read on cortext to get this check.`);
|
|
390
|
+
return done();
|
|
391
|
+
}
|
|
392
|
+
const { retiredWithLiveKey, liveKeyWithoutRow, agentKids } = reconcileIdentities(floor.rows, directory.rows, adminCapability);
|
|
393
|
+
facts = {
|
|
394
|
+
...facts,
|
|
395
|
+
retiredWithLiveKey,
|
|
396
|
+
liveKeyWithoutRow,
|
|
397
|
+
agentKids
|
|
398
|
+
};
|
|
399
|
+
if (retiredWithLiveKey.length > 0) {
|
|
400
|
+
const kids = retiredWithLiveKey.join(", ");
|
|
401
|
+
checks.no(CHECK_DIR, `decommissioned ${retiredWithLiveKey.length === 1 ? "agent" : "agents"} with a LIVE signing credential: ${kids}. The directory says retired; the key table still verifies — and the table is what the server checks.`, `Revoke ${retiredWithLiveKey.length === 1 ? "it" : "them"} if the decommission stands (\`substrate-admin revoke ${kids}\`), or re-activate the directory row if it does not.`);
|
|
402
|
+
return done();
|
|
403
|
+
}
|
|
404
|
+
if (liveKeyWithoutRow.length > 0) {
|
|
405
|
+
const kids = liveKeyWithoutRow.join(", ");
|
|
406
|
+
checks.no(CHECK_DIR, `live ${liveKeyWithoutRow.length === 1 ? "credential" : "credentials"} with no directory row: ${kids}. Nothing references these identities, so no other surface will ever surface them (admin-capable keys are exempt — the bootstrap root of trust has no row by design).`, `If the identity is real, register its directory row; if it is unattended machinery nobody owns, revoke the key (\`substrate-admin revoke ${kids}\`).`);
|
|
407
|
+
return done();
|
|
408
|
+
}
|
|
409
|
+
checks.ok(CHECK_DIR, `credential table and directory agree: ${floor.rows.length} live keys, ${directory.rows.length} directory rows, no retired row holding a live key and no live key without a row (admin roots exempt by capability, not by name).`);
|
|
410
|
+
return done();
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
//#endregion
|
|
414
|
+
//#region ../../packages/substrate-client/src/admin/onboard.ts
|
|
415
|
+
const SECOND_ADMIN = "second-admin";
|
|
416
|
+
const FIRST_AGENT = "first-agent";
|
|
417
|
+
const ONBOARD_STEPS = [
|
|
418
|
+
"reachable",
|
|
419
|
+
"auth-enabled",
|
|
420
|
+
"credential",
|
|
421
|
+
"identity",
|
|
422
|
+
"admin-capability",
|
|
423
|
+
"admin-floor",
|
|
424
|
+
SECOND_ADMIN,
|
|
425
|
+
"namespaces",
|
|
426
|
+
"key-directory",
|
|
427
|
+
FIRST_AGENT
|
|
428
|
+
];
|
|
429
|
+
const SKIPPABLE_STEPS = /* @__PURE__ */ new Set([SECOND_ADMIN, FIRST_AGENT]);
|
|
430
|
+
/** The checklist marks every surface draws, so the CLI and the TUI cannot drift. */
|
|
431
|
+
const STEP_MARKS = {
|
|
432
|
+
done: "✓",
|
|
433
|
+
todo: "·",
|
|
434
|
+
blocked: "⊘",
|
|
435
|
+
skipped: "↷"
|
|
436
|
+
};
|
|
437
|
+
/** Marks the step the operator is on: the first `todo`. */
|
|
438
|
+
const CURRENT_MARK = "▶";
|
|
439
|
+
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.";
|
|
440
|
+
function fromCheck(name, check) {
|
|
441
|
+
const base = {
|
|
442
|
+
name,
|
|
443
|
+
optional: false,
|
|
444
|
+
skippable: false
|
|
445
|
+
};
|
|
446
|
+
if (check === void 0) return {
|
|
447
|
+
...base,
|
|
448
|
+
status: "blocked",
|
|
449
|
+
detail: "not reported — an earlier step stopped the run"
|
|
450
|
+
};
|
|
451
|
+
if (check.status === "ok") return {
|
|
452
|
+
...base,
|
|
453
|
+
status: "done",
|
|
454
|
+
detail: check.detail
|
|
455
|
+
};
|
|
456
|
+
if (check.status === "skip") return {
|
|
457
|
+
...base,
|
|
458
|
+
status: "blocked",
|
|
459
|
+
detail: check.detail
|
|
460
|
+
};
|
|
461
|
+
return {
|
|
462
|
+
...base,
|
|
463
|
+
status: "todo",
|
|
464
|
+
detail: check.detail,
|
|
465
|
+
...check.fix !== void 0 ? { fix: check.fix } : {}
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
function fromGoal(goal, skipped) {
|
|
469
|
+
const base = {
|
|
470
|
+
name: goal.name,
|
|
471
|
+
optional: goal.optional,
|
|
472
|
+
skippable: true
|
|
473
|
+
};
|
|
474
|
+
if (!goal.measured) return {
|
|
475
|
+
...base,
|
|
476
|
+
status: "blocked",
|
|
477
|
+
detail: goal.detail.blocked
|
|
478
|
+
};
|
|
479
|
+
if (goal.met) return {
|
|
480
|
+
...base,
|
|
481
|
+
status: "done",
|
|
482
|
+
detail: goal.detail.met
|
|
483
|
+
};
|
|
484
|
+
if (skipped.has(goal.name)) return {
|
|
485
|
+
...base,
|
|
486
|
+
status: "skipped",
|
|
487
|
+
detail: goal.detail.unmet
|
|
488
|
+
};
|
|
489
|
+
return {
|
|
490
|
+
...base,
|
|
491
|
+
status: "todo",
|
|
492
|
+
detail: goal.detail.unmet,
|
|
493
|
+
fix: goal.fix,
|
|
494
|
+
action: goal.action
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
function planOnboarding(result, opts) {
|
|
498
|
+
const byName = new Map(result.checks.map((c) => [c.name, c]));
|
|
499
|
+
const { facts } = result;
|
|
500
|
+
const steps = [];
|
|
501
|
+
for (const name of ONBOARD_STEPS) {
|
|
502
|
+
if (name === SECOND_ADMIN) {
|
|
503
|
+
const admins = facts.adminKids;
|
|
504
|
+
steps.push(fromGoal({
|
|
505
|
+
name,
|
|
506
|
+
optional: false,
|
|
507
|
+
measured: byName.get("admin-floor")?.status === "ok" && admins !== void 0,
|
|
508
|
+
met: (admins?.length ?? 0) >= 2,
|
|
509
|
+
detail: {
|
|
510
|
+
met: `${admins?.length ?? 0} admin keys — succession is possible`,
|
|
511
|
+
unmet: "one admin key. Losing it locks this deployment out of its own admin surface, and the floor will refuse to revoke it.",
|
|
512
|
+
blocked: "not measured — admin-floor did not pass"
|
|
513
|
+
},
|
|
514
|
+
fix: "Register a second admin key, held somewhere other than the first.",
|
|
515
|
+
action: { kind: "register-admin" }
|
|
516
|
+
}, opts.skipped));
|
|
517
|
+
continue;
|
|
518
|
+
}
|
|
519
|
+
if (name === FIRST_AGENT) {
|
|
520
|
+
const agents = facts.agentKids;
|
|
521
|
+
steps.push(fromGoal({
|
|
522
|
+
name,
|
|
523
|
+
optional: true,
|
|
524
|
+
measured: agents !== void 0,
|
|
525
|
+
met: (agents?.length ?? 0) > 0,
|
|
526
|
+
detail: {
|
|
527
|
+
met: `${agents?.length ?? 0} agent identities with a live key`,
|
|
528
|
+
unmet: "no agent identity yet — register one to exercise the route and directory",
|
|
529
|
+
blocked: "not measured — the directory could not be read"
|
|
530
|
+
},
|
|
531
|
+
fix: "Register a first agent identity.",
|
|
532
|
+
action: { kind: "register-agent" }
|
|
533
|
+
}, opts.skipped));
|
|
534
|
+
continue;
|
|
535
|
+
}
|
|
536
|
+
const step = fromCheck(name, byName.get(name));
|
|
537
|
+
if (step.status !== "todo") {
|
|
538
|
+
steps.push(step);
|
|
539
|
+
continue;
|
|
540
|
+
}
|
|
541
|
+
if (name === "credential") {
|
|
542
|
+
steps.push(opts.canBootstrap ? {
|
|
543
|
+
...step,
|
|
544
|
+
action: { kind: "bootstrap" }
|
|
545
|
+
} : opts.explainNoBootstrap === false ? step : {
|
|
546
|
+
...step,
|
|
547
|
+
fix: NO_BOOTSTRAP_FIX
|
|
548
|
+
});
|
|
549
|
+
continue;
|
|
550
|
+
}
|
|
551
|
+
const retired = facts.retiredWithLiveKey ?? [];
|
|
552
|
+
if (name === "key-directory" && retired.length > 0) {
|
|
553
|
+
steps.push({
|
|
554
|
+
...step,
|
|
555
|
+
action: {
|
|
556
|
+
kind: "revoke",
|
|
557
|
+
kids: retired
|
|
558
|
+
}
|
|
559
|
+
});
|
|
560
|
+
continue;
|
|
561
|
+
}
|
|
562
|
+
steps.push(step);
|
|
563
|
+
}
|
|
564
|
+
return steps;
|
|
565
|
+
}
|
|
566
|
+
/** The step the operator is on: the first one still to do. */
|
|
567
|
+
function currentStep(steps) {
|
|
568
|
+
return steps.find((s) => s.status === "todo");
|
|
569
|
+
}
|
|
570
|
+
/** True while any required step is still to do — the `--check` verdict. */
|
|
571
|
+
function requiredOutstanding(steps) {
|
|
572
|
+
return steps.some((s) => s.status === "todo" && !s.optional);
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
//#endregion
|
|
576
|
+
//#region ../../packages/substrate-client/src/admin/surgery.ts
|
|
577
|
+
/** Mirrors BACKFILL_MAX_ROWS in substrate-compose; the server enforces it. */
|
|
578
|
+
const BACKFILL_CHUNK = 5e3;
|
|
579
|
+
/**
|
|
580
|
+
* A chunk was refused. `chunksDone` chunks were already sent (and, on apply, WRITTEN); `partial` sums them.
|
|
581
|
+
*
|
|
582
|
+
* `cause` is the real failure and may be an `AuthError` (a rejected admin key) or a
|
|
583
|
+
* `NetworkError` (including one wrapping an `AbortError`). Callers must unwrap `cause`
|
|
584
|
+
* before applying an auth-lock rule or abort handling.
|
|
585
|
+
*
|
|
586
|
+
* `partial.applied` true means at least one chunk was accepted and written; `chunksDone` says how
|
|
587
|
+
* many. `false` does NOT prove nothing was written: a first chunk refused with anything but a 4xx
|
|
588
|
+
* may have partly written (below). A refusal with a 4xx status guarantees the failing chunk wrote nothing;
|
|
589
|
+
* anything else (a 5xx such as `verify_failed`, a dropped connection, an abort) may have
|
|
590
|
+
* partly written the failing chunk, since the route writes in non-transactional 200-row batches.
|
|
591
|
+
*/
|
|
592
|
+
var AdminBackfillError = class extends Error {
|
|
593
|
+
cause;
|
|
594
|
+
chunksDone;
|
|
595
|
+
chunks;
|
|
596
|
+
partial;
|
|
597
|
+
name = "AdminBackfillError";
|
|
598
|
+
constructor(cause, chunksDone, chunks, partial) {
|
|
599
|
+
super(`backfill stopped at chunk ${chunksDone + 1} of ${chunks}: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
600
|
+
this.cause = cause;
|
|
601
|
+
this.chunksDone = chunksDone;
|
|
602
|
+
this.chunks = chunks;
|
|
603
|
+
this.partial = partial;
|
|
604
|
+
}
|
|
605
|
+
};
|
|
606
|
+
const sig = (o) => o.signal !== void 0 ? { signal: o.signal } : {};
|
|
607
|
+
function createSurgeryApi(t) {
|
|
608
|
+
const post = async (path, body, o) => await (await t.raw(path, {
|
|
609
|
+
method: "POST",
|
|
610
|
+
body,
|
|
611
|
+
...sig(o)
|
|
612
|
+
})).json();
|
|
613
|
+
return {
|
|
614
|
+
async backfill(input, o = {}) {
|
|
615
|
+
const entries = Object.entries(input.values);
|
|
616
|
+
const chunks = Math.ceil(entries.length / BACKFILL_CHUNK);
|
|
617
|
+
const apply = input.apply === true;
|
|
618
|
+
let write = 0;
|
|
619
|
+
let kept = 0;
|
|
620
|
+
let unchanged = 0;
|
|
621
|
+
const missing = [];
|
|
622
|
+
const counts = {};
|
|
623
|
+
const summary = (applied = apply) => ({
|
|
624
|
+
requested: entries.length,
|
|
625
|
+
write,
|
|
626
|
+
kept,
|
|
627
|
+
unchanged,
|
|
628
|
+
missing: [...missing],
|
|
629
|
+
counts: { ...counts },
|
|
630
|
+
applied,
|
|
631
|
+
chunks
|
|
632
|
+
});
|
|
633
|
+
for (let index = 0; index < chunks; index++) {
|
|
634
|
+
const slice = entries.slice(index * BACKFILL_CHUNK, (index + 1) * BACKFILL_CHUNK);
|
|
635
|
+
let body;
|
|
636
|
+
try {
|
|
637
|
+
body = await post("/substrate/v1/_system/backfill-field", {
|
|
638
|
+
namespace: input.namespace,
|
|
639
|
+
type: input.type,
|
|
640
|
+
field: input.field,
|
|
641
|
+
apply,
|
|
642
|
+
overwrite: input.overwrite === true,
|
|
643
|
+
values: Object.fromEntries(slice)
|
|
644
|
+
}, o);
|
|
645
|
+
} catch (err) {
|
|
646
|
+
throw new AdminBackfillError(err, index, chunks, summary(apply && index > 0));
|
|
647
|
+
}
|
|
648
|
+
write += Number(body.write ?? 0);
|
|
649
|
+
kept += Number(body.kept ?? 0);
|
|
650
|
+
unchanged += Number(body.unchanged ?? 0);
|
|
651
|
+
if (Array.isArray(body.missing)) missing.push(...body.missing);
|
|
652
|
+
for (const [k, n] of Object.entries(body.counts ?? {})) counts[k] = (counts[k] ?? 0) + n;
|
|
653
|
+
o.onChunk?.({
|
|
654
|
+
index,
|
|
655
|
+
chunks,
|
|
656
|
+
body
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
return summary();
|
|
660
|
+
},
|
|
661
|
+
reindexPage(input, o = {}) {
|
|
662
|
+
const body = {
|
|
663
|
+
namespace: input.namespace,
|
|
664
|
+
type: input.type
|
|
665
|
+
};
|
|
666
|
+
if (input.cursor !== void 0) body.cursor = input.cursor;
|
|
667
|
+
if (input.limit !== void 0) body.limit = input.limit;
|
|
668
|
+
return post("/substrate/v1/embed/reindex", body, o);
|
|
669
|
+
},
|
|
670
|
+
async embedStats(o = {}) {
|
|
671
|
+
return await (await t.raw("/substrate/v1/embed-stats", {
|
|
672
|
+
method: "GET",
|
|
673
|
+
...sig(o)
|
|
674
|
+
})).json();
|
|
675
|
+
},
|
|
676
|
+
dropNamespace(input, o = {}) {
|
|
677
|
+
const body = {
|
|
678
|
+
namespace: input.namespace,
|
|
679
|
+
confirm: input.confirm
|
|
680
|
+
};
|
|
681
|
+
if (input.cascade !== void 0) body.cascade = input.cascade;
|
|
682
|
+
if (input.dryRun !== void 0) body.dryRun = input.dryRun;
|
|
683
|
+
return post("/substrate/v1/_system/drop-namespace", body, o);
|
|
684
|
+
},
|
|
685
|
+
dropType(input, o = {}) {
|
|
686
|
+
const body = {
|
|
687
|
+
namespace: input.namespace,
|
|
688
|
+
type: input.type,
|
|
689
|
+
confirm: input.confirm
|
|
690
|
+
};
|
|
691
|
+
if (input.cascade !== void 0) body.cascade = input.cascade;
|
|
692
|
+
if (input.dryRun !== void 0) body.dryRun = input.dryRun;
|
|
693
|
+
return post("/substrate/v1/_system/drop-type", body, o);
|
|
694
|
+
},
|
|
695
|
+
normalise(input, o = {}) {
|
|
696
|
+
const body = {
|
|
697
|
+
namespace: input.namespace,
|
|
698
|
+
type: input.type,
|
|
699
|
+
field: input.field
|
|
700
|
+
};
|
|
701
|
+
if (input.reject !== void 0) body.reject = [...input.reject];
|
|
702
|
+
if (input.apply === true) body.apply = true;
|
|
703
|
+
return post("/substrate/v1/_system/normalise-vocab", body, o);
|
|
704
|
+
}
|
|
705
|
+
};
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
//#endregion
|
|
709
|
+
//#region ../../packages/substrate-client/src/admin/api.ts
|
|
710
|
+
function createAdminApi(t) {
|
|
711
|
+
return {
|
|
712
|
+
...createSurgeryApi(t),
|
|
713
|
+
async keys(opts = {}) {
|
|
714
|
+
const out = [];
|
|
715
|
+
let cursor;
|
|
716
|
+
for (;;) {
|
|
717
|
+
const qs = cursor === void 0 ? "" : `?cursor=${encodeURIComponent(cursor)}`;
|
|
718
|
+
const page = await (await t.raw(`/substrate/v1/_system/keys${qs}`, {
|
|
719
|
+
method: "GET",
|
|
720
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
721
|
+
})).json();
|
|
722
|
+
out.push(...page.keys);
|
|
723
|
+
if (page.hasMore !== true) return out;
|
|
724
|
+
if (typeof page.nextCursor !== "string") throw new Error("server reported hasMore with no nextCursor — refusing to report a partial key table as complete");
|
|
725
|
+
cursor = page.nextCursor;
|
|
726
|
+
}
|
|
727
|
+
},
|
|
728
|
+
async update(change, opts = {}) {
|
|
729
|
+
const body = {
|
|
730
|
+
kid: change.kid,
|
|
731
|
+
namespaces: [...change.namespaces],
|
|
732
|
+
capabilities: [...change.capabilities]
|
|
733
|
+
};
|
|
734
|
+
if (change.widen === true) body.widen = true;
|
|
735
|
+
if (change.allowAdmin === true) body.allowAdmin = true;
|
|
736
|
+
if (change.allowUnknownNs === true) body.allowUnknownNs = true;
|
|
737
|
+
return await (await t.raw("/substrate/v1/_system/keys", {
|
|
738
|
+
method: "PATCH",
|
|
739
|
+
body,
|
|
740
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
741
|
+
})).json();
|
|
742
|
+
},
|
|
743
|
+
async revoke(kid, opts = {}) {
|
|
744
|
+
return await (await t.raw("/substrate/v1/_system/keys", {
|
|
745
|
+
method: "PATCH",
|
|
746
|
+
body: {
|
|
747
|
+
kid,
|
|
748
|
+
revoke: true
|
|
749
|
+
},
|
|
750
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
751
|
+
})).json();
|
|
752
|
+
},
|
|
753
|
+
async register(input, opts = {}) {
|
|
754
|
+
const body = {
|
|
755
|
+
kid: input.kid,
|
|
756
|
+
publicKey: input.publicKey,
|
|
757
|
+
algorithm: input.algorithm,
|
|
758
|
+
namespaces: [...input.namespaces],
|
|
759
|
+
capabilities: [...input.capabilities]
|
|
760
|
+
};
|
|
761
|
+
if (input.name !== void 0) body.name = input.name;
|
|
762
|
+
if (input.directory !== void 0) body.directory = { create: input.directory };
|
|
763
|
+
if (input.allowAdmin === true) body.allowAdmin = true;
|
|
764
|
+
if (input.allowUnknownNs === true) body.allowUnknownNs = true;
|
|
765
|
+
return await (await t.raw("/substrate/v1/_system/keys", {
|
|
766
|
+
method: "POST",
|
|
767
|
+
body,
|
|
768
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
769
|
+
})).json();
|
|
770
|
+
},
|
|
771
|
+
async invite(input, opts = {}) {
|
|
772
|
+
const body = {
|
|
773
|
+
namespaces: [...input.namespaces],
|
|
774
|
+
capabilities: [...input.capabilities]
|
|
775
|
+
};
|
|
776
|
+
if (input.ttlMs !== void 0) body.ttlMs = input.ttlMs;
|
|
777
|
+
return await (await t.raw("/substrate/v1/_system/invites", {
|
|
778
|
+
method: "POST",
|
|
779
|
+
body,
|
|
780
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
781
|
+
})).json();
|
|
782
|
+
}
|
|
783
|
+
};
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
//#endregion
|
|
787
|
+
//#region ../../packages/substrate-client/src/errors.ts
|
|
788
|
+
var NetworkError = class extends Error {
|
|
789
|
+
cause;
|
|
790
|
+
name = "NetworkError";
|
|
791
|
+
/** HTTP status of the response, when the failure was one. */
|
|
792
|
+
status;
|
|
793
|
+
/** The server's JSON error `code`, when its body carried one. */
|
|
794
|
+
code;
|
|
795
|
+
/** The server's JSON `error` text, when its body carried one. */
|
|
796
|
+
serverMessage;
|
|
797
|
+
/** The refusal's parsed JSON object, verbatim. */
|
|
798
|
+
body;
|
|
799
|
+
constructor(message, cause, info = {}) {
|
|
800
|
+
super(message);
|
|
801
|
+
this.cause = cause;
|
|
802
|
+
if (info.status !== void 0) this.status = info.status;
|
|
803
|
+
if (info.code !== void 0) this.code = info.code;
|
|
804
|
+
if (info.serverMessage !== void 0) this.serverMessage = info.serverMessage;
|
|
805
|
+
if (info.body !== void 0) this.body = info.body;
|
|
806
|
+
}
|
|
807
|
+
};
|
|
808
|
+
/**
|
|
809
|
+
* Thrown on Substrate auth failures — 401 (unauthenticated) or 403 (authenticated but
|
|
810
|
+
* not authorised). Proxy-level failures (407, 511) fall through to NetworkError.
|
|
811
|
+
*/
|
|
812
|
+
var AuthError = class extends Error {
|
|
813
|
+
status;
|
|
814
|
+
name = "AuthError";
|
|
815
|
+
/** The server's JSON error `code`, when its body carried one: the auth gate says `forbidden`. */
|
|
816
|
+
code;
|
|
817
|
+
/** The server's JSON `error` or `message` text, when its body carried one. */
|
|
818
|
+
serverMessage;
|
|
819
|
+
/** The refusal's parsed JSON object, verbatim. */
|
|
820
|
+
body;
|
|
821
|
+
constructor(message, status, info = {}) {
|
|
822
|
+
super(message);
|
|
823
|
+
this.status = status;
|
|
824
|
+
if (info.code !== void 0) this.code = info.code;
|
|
825
|
+
if (info.serverMessage !== void 0) this.serverMessage = info.serverMessage;
|
|
826
|
+
if (info.body !== void 0) this.body = info.body;
|
|
827
|
+
}
|
|
828
|
+
};
|
|
829
|
+
var SubscribeError = class extends Error {
|
|
830
|
+
code;
|
|
831
|
+
name = "SubscribeError";
|
|
832
|
+
constructor(message, code) {
|
|
833
|
+
super(message);
|
|
834
|
+
this.code = code;
|
|
835
|
+
}
|
|
836
|
+
};
|
|
837
|
+
|
|
838
|
+
//#endregion
|
|
839
|
+
//#region ../../packages/substrate-client/src/subscribe-rows.ts
|
|
840
|
+
/**
|
|
841
|
+
* Pure subscribe-event → typed-row-set fold, shared by `SubstrateClient.watch` and
|
|
842
|
+
* the cache store.
|
|
843
|
+
*
|
|
844
|
+
* The `data` envelope shape per event kind:
|
|
845
|
+
* - snapshot : data = { '<ns>/<Type>': Row[] } — the full current set
|
|
846
|
+
* - add : data = { '<ns>/<Type>': Row } — one newly-matching row
|
|
847
|
+
* - update : data = { '<ns>/<Type>': Row } — one changed row (by id)
|
|
848
|
+
* - remove : { removedId: string } — no data envelope
|
|
849
|
+
* - end / error / chunk : no row change (terminal / streaming kinds)
|
|
850
|
+
*
|
|
851
|
+
* Rows are correlated by their `id` field (string-coerced), so any frame fed to
|
|
852
|
+
* the fold must select `id` — `SubstrateClient.watch` injects it via
|
|
853
|
+
* `augmentFramesWithId`. `add` appends (no de-dup) and ignores the query's
|
|
854
|
+
* `orderBy`.
|
|
855
|
+
*/
|
|
856
|
+
function rowSlot(data, qualifiedKey) {
|
|
857
|
+
if (data === null || typeof data !== "object") return void 0;
|
|
858
|
+
return data[qualifiedKey];
|
|
859
|
+
}
|
|
860
|
+
function rowId(row) {
|
|
861
|
+
return String(row.id);
|
|
862
|
+
}
|
|
863
|
+
/**
|
|
864
|
+
* Fold one subscribe event into `current`, returning the next row list. Pure:
|
|
865
|
+
* the caller owns terminal-kind delivery and the "select id" contract.
|
|
866
|
+
*
|
|
867
|
+
* Returns the SAME array reference when the event does not change the set (an
|
|
868
|
+
* `update` whose row carries no `id`, or a non-row kind), so callers can cheaply
|
|
869
|
+
* skip redundant writes / yields by identity.
|
|
870
|
+
*/
|
|
871
|
+
function reduceSubscribeRows(current, qualifiedKey, event) {
|
|
872
|
+
switch (event.kind) {
|
|
873
|
+
case "snapshot": {
|
|
874
|
+
const slot = rowSlot(event.data, qualifiedKey);
|
|
875
|
+
if (Array.isArray(slot)) return [...slot];
|
|
876
|
+
return slot === void 0 || slot === null ? [] : [slot];
|
|
877
|
+
}
|
|
878
|
+
case "add": return [...current, rowSlot(event.data, qualifiedKey)];
|
|
879
|
+
case "update": {
|
|
880
|
+
const row = rowSlot(event.data, qualifiedKey);
|
|
881
|
+
if (row === void 0 || row.id === void 0) return current;
|
|
882
|
+
const targetId = String(row.id);
|
|
883
|
+
return current.map((r) => rowId(r) === targetId ? row : r);
|
|
884
|
+
}
|
|
885
|
+
case "remove": return current.filter((r) => rowId(r) !== String(event.removedId));
|
|
886
|
+
default: return current;
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
/**
|
|
890
|
+
* Fold a single-key subscription's event stream into a live row-set: yields the
|
|
891
|
+
* current `T[]` after every snapshot / add / update / remove. Completes on `end`
|
|
892
|
+
* (or when the source iterator completes); throws `SubscribeError` on an `error`
|
|
893
|
+
* event — matching the raw `subscribe` contract, where the transport throws on
|
|
894
|
+
* error frames.
|
|
895
|
+
*
|
|
896
|
+
* A delta that does not change the set (e.g. an `update` whose row has no id) is
|
|
897
|
+
* not re-yielded. Cancellation: breaking the consuming `for await` (or calling
|
|
898
|
+
* `.return()`) propagates to the source iterable's `return()` through the inner
|
|
899
|
+
* `for await`, cancelling the underlying WS subscription.
|
|
900
|
+
*/
|
|
901
|
+
async function* watchRows(events, qualifiedKey) {
|
|
902
|
+
let rows = [];
|
|
903
|
+
for await (const event of events) {
|
|
904
|
+
if (event.kind === "end") return;
|
|
905
|
+
if (event.kind === "error") {
|
|
906
|
+
const first = event.errors[0];
|
|
907
|
+
throw new SubscribeError(first?.message ?? "subscribe error", first?.code ?? "unknown");
|
|
908
|
+
}
|
|
909
|
+
const next = reduceSubscribeRows(rows, qualifiedKey, event);
|
|
910
|
+
if (next === rows) continue;
|
|
911
|
+
rows = next;
|
|
912
|
+
yield rows;
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
//#endregion
|
|
917
|
+
//#region ../../packages/substrate-client/src/cache/store.ts
|
|
918
|
+
/**
|
|
919
|
+
* Signals-backed reactive cache. Keyed by canonicalised frame key (same shape
|
|
920
|
+
* as `canonicaliseFrameKey`). Each entry holds signals for `data`, `loading`,
|
|
921
|
+
* `error`, plus refCount + invalidatedAt for lifecycle and drift management.
|
|
922
|
+
*
|
|
923
|
+
* Lifecycle:
|
|
924
|
+
* - subscribe(key) → increment refCount, return an unsubscribe that decrements.
|
|
925
|
+
* - When refCount → 0, schedule GC after `idleGcMs`; cancel if a new subscribe
|
|
926
|
+
* arrives in that window.
|
|
927
|
+
* - invalidate(keyPrefix): if any entry under that prefix has refCount > 0,
|
|
928
|
+
* stamp `invalidatedAt` (callers observe and re-fetch). Entries with
|
|
929
|
+
* refCount === 0 are dropped.
|
|
930
|
+
*/
|
|
931
|
+
var CacheStore = class {
|
|
932
|
+
#entries = /* @__PURE__ */ new Map();
|
|
933
|
+
#idleGcMs;
|
|
934
|
+
constructor(opts) {
|
|
935
|
+
this.#idleGcMs = opts.idleGcMs;
|
|
936
|
+
}
|
|
937
|
+
get(key) {
|
|
938
|
+
const existing = this.#entries.get(key);
|
|
939
|
+
if (existing !== void 0) return existing;
|
|
940
|
+
const entry = {
|
|
941
|
+
data: signal(void 0),
|
|
942
|
+
loading: signal(false),
|
|
943
|
+
error: signal(null),
|
|
944
|
+
diagnostics: signal([]),
|
|
945
|
+
invalidatedSignal: signal(0),
|
|
946
|
+
refCount: 0,
|
|
947
|
+
invalidatedAt: null,
|
|
948
|
+
lastFetched: 0,
|
|
949
|
+
gcTimer: null
|
|
950
|
+
};
|
|
951
|
+
this.#entries.set(key, entry);
|
|
952
|
+
return entry;
|
|
953
|
+
}
|
|
954
|
+
peek(key) {
|
|
955
|
+
return this.#entries.get(key);
|
|
956
|
+
}
|
|
957
|
+
subscribe(key) {
|
|
958
|
+
const entry = this.get(key);
|
|
959
|
+
entry.refCount += 1;
|
|
960
|
+
if (entry.gcTimer !== null) {
|
|
961
|
+
clearTimeout(entry.gcTimer);
|
|
962
|
+
entry.gcTimer = null;
|
|
963
|
+
}
|
|
964
|
+
let unsubscribed = false;
|
|
965
|
+
return () => {
|
|
966
|
+
if (unsubscribed) return;
|
|
967
|
+
unsubscribed = true;
|
|
968
|
+
entry.refCount -= 1;
|
|
969
|
+
if (entry.refCount === 0) this.#scheduleGc(key, entry);
|
|
970
|
+
};
|
|
971
|
+
}
|
|
972
|
+
set(key, data, diagnostics = []) {
|
|
973
|
+
const entry = this.get(key);
|
|
974
|
+
entry.data.value = data;
|
|
975
|
+
entry.loading.value = false;
|
|
976
|
+
entry.error.value = null;
|
|
977
|
+
if (diagnostics.length > 0 || entry.diagnostics.value.length > 0) entry.diagnostics.value = diagnostics;
|
|
978
|
+
entry.invalidatedAt = null;
|
|
979
|
+
entry.invalidatedSignal.value = 0;
|
|
980
|
+
entry.lastFetched = Date.now();
|
|
981
|
+
}
|
|
982
|
+
setLoading(key, loading) {
|
|
983
|
+
const entry = this.get(key);
|
|
984
|
+
entry.loading.value = loading;
|
|
985
|
+
}
|
|
986
|
+
setError(key, err) {
|
|
987
|
+
const entry = this.get(key);
|
|
988
|
+
entry.error.value = err;
|
|
989
|
+
entry.loading.value = false;
|
|
990
|
+
}
|
|
991
|
+
invalidate(keyPrefix) {
|
|
992
|
+
const now = Date.now();
|
|
993
|
+
for (const [key, entry] of this.#entries) {
|
|
994
|
+
if (!key.startsWith(keyPrefix)) continue;
|
|
995
|
+
if (entry.refCount > 0) {
|
|
996
|
+
entry.invalidatedAt = now;
|
|
997
|
+
entry.invalidatedSignal.value = now;
|
|
998
|
+
} else {
|
|
999
|
+
if (entry.gcTimer !== null) clearTimeout(entry.gcTimer);
|
|
1000
|
+
this.#entries.delete(key);
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
/**
|
|
1005
|
+
* Apply a subscribe event to the entry at `cacheKey`, patching the row slot
|
|
1006
|
+
* under `qualifiedKey` in the entry's `data` envelope.
|
|
1007
|
+
*
|
|
1008
|
+
* - snapshot → replace the entire envelope via `set()`
|
|
1009
|
+
* - add → append the single row to the list at data[qualifiedKey]
|
|
1010
|
+
* - update → replace row by id in the list at data[qualifiedKey]
|
|
1011
|
+
* - remove → drop row by removedId from the list at data[qualifiedKey]
|
|
1012
|
+
* - end / error / chunk → no cache change (the hook surfaces these)
|
|
1013
|
+
*
|
|
1014
|
+
* `update` / `remove` on an entry without data are no-ops — the server always
|
|
1015
|
+
* emits `snapshot` first.
|
|
1016
|
+
*/
|
|
1017
|
+
applySubscribeEvent(cacheKey, qualifiedKey, event) {
|
|
1018
|
+
if (event.kind === "snapshot") {
|
|
1019
|
+
this.set(cacheKey, event.data);
|
|
1020
|
+
return;
|
|
1021
|
+
}
|
|
1022
|
+
if (event.kind !== "add" && event.kind !== "update" && event.kind !== "remove") return;
|
|
1023
|
+
const entry = this.get(cacheKey);
|
|
1024
|
+
const current = entry.data.value;
|
|
1025
|
+
if (event.kind !== "add" && (current === void 0 || !Array.isArray(current[qualifiedKey]))) return;
|
|
1026
|
+
const list = Array.isArray(current?.[qualifiedKey]) ? current[qualifiedKey] : [];
|
|
1027
|
+
const next = reduceSubscribeRows(list, qualifiedKey, event);
|
|
1028
|
+
if (next === list) return;
|
|
1029
|
+
entry.data.value = {
|
|
1030
|
+
...current ?? {},
|
|
1031
|
+
[qualifiedKey]: next
|
|
1032
|
+
};
|
|
1033
|
+
}
|
|
1034
|
+
#scheduleGc(key, entry) {
|
|
1035
|
+
if (entry.gcTimer !== null) clearTimeout(entry.gcTimer);
|
|
1036
|
+
entry.gcTimer = setTimeout(() => {
|
|
1037
|
+
entry.gcTimer = null;
|
|
1038
|
+
if (entry.refCount === 0) this.#entries.delete(key);
|
|
1039
|
+
}, this.#idleGcMs);
|
|
1040
|
+
}
|
|
1041
|
+
};
|
|
1042
|
+
|
|
1043
|
+
//#endregion
|
|
1044
|
+
//#region ../../packages/substrate-client/src/diagnostics.ts
|
|
1045
|
+
const HANDLED = /* @__PURE__ */ new Set(["unknownProjectionFields", "filterValidationSkipped"]);
|
|
1046
|
+
/**
|
|
1047
|
+
* Reduce one envelope entry to a diagnostic, or `undefined` when it holds
|
|
1048
|
+
* nothing worth reporting — an entry present but empty, or one whose only
|
|
1049
|
+
* unknown-field list is empty. Without that, the default sink emits a warning
|
|
1050
|
+
* naming no observation at all.
|
|
1051
|
+
*/
|
|
1052
|
+
function describeEntry(opKey, entry) {
|
|
1053
|
+
const unknownProjectionFields = [...entry.unknownProjectionFields ?? []];
|
|
1054
|
+
const { filterValidationSkipped } = entry;
|
|
1055
|
+
const unrecognizedKeys = Object.keys(entry).filter((k) => !HANDLED.has(k) && entry[k] !== void 0).sort();
|
|
1056
|
+
if (unknownProjectionFields.length === 0 && filterValidationSkipped === void 0 && unrecognizedKeys.length === 0) return;
|
|
1057
|
+
const diagnostic = {
|
|
1058
|
+
opKey,
|
|
1059
|
+
unknownProjectionFields
|
|
1060
|
+
};
|
|
1061
|
+
if (filterValidationSkipped !== void 0) diagnostic.filterValidationSkipped = filterValidationSkipped;
|
|
1062
|
+
if (unrecognizedKeys.length > 0) diagnostic.unrecognizedKeys = unrecognizedKeys;
|
|
1063
|
+
return diagnostic;
|
|
1064
|
+
}
|
|
1065
|
+
/**
|
|
1066
|
+
* Extract diagnostics from a decoded envelope and hand each one to `sink`.
|
|
1067
|
+
* Returns the flattened list so callers can also attach it to a mapped result.
|
|
1068
|
+
*
|
|
1069
|
+
* An envelope with no `_diagnostics` returns `[]` without the sink firing.
|
|
1070
|
+
*/
|
|
1071
|
+
function collectDiagnostics(envDiagnostics, sink) {
|
|
1072
|
+
if (envDiagnostics === void 0) return [];
|
|
1073
|
+
const out = [];
|
|
1074
|
+
for (const [opKey, entry] of Object.entries(envDiagnostics)) {
|
|
1075
|
+
if (entry === null || entry === void 0) continue;
|
|
1076
|
+
const diagnostic = describeEntry(opKey, entry);
|
|
1077
|
+
if (diagnostic === void 0) continue;
|
|
1078
|
+
out.push(diagnostic);
|
|
1079
|
+
sink?.(diagnostic);
|
|
1080
|
+
}
|
|
1081
|
+
return out;
|
|
1082
|
+
}
|
|
1083
|
+
/**
|
|
1084
|
+
* Default sink: one `console.warn` per distinct observation set, naming the
|
|
1085
|
+
* frame key and everything observed about it, plus the reason the reader should
|
|
1086
|
+
* care in each case.
|
|
1087
|
+
*
|
|
1088
|
+
* ONE warning per diagnostic rather than one per observation. An entry carrying
|
|
1089
|
+
* both an unknown projection and a skipped filter validation describes a single
|
|
1090
|
+
* read, and splitting it reads as two independent defects.
|
|
1091
|
+
*
|
|
1092
|
+
* Deduping state is per-sink, so per-client: `new SubstrateClient(...)` starts
|
|
1093
|
+
* fresh.
|
|
1094
|
+
*/
|
|
1095
|
+
function createDefaultDiagnosticsSink() {
|
|
1096
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1097
|
+
return (diagnostic) => {
|
|
1098
|
+
const { opKey, filterValidationSkipped } = diagnostic;
|
|
1099
|
+
const fields = [...diagnostic.unknownProjectionFields].sort();
|
|
1100
|
+
const unrecognized = [...diagnostic.unrecognizedKeys ?? []].sort();
|
|
1101
|
+
const dedupeKey = [
|
|
1102
|
+
opKey,
|
|
1103
|
+
fields.join(","),
|
|
1104
|
+
filterValidationSkipped ?? "",
|
|
1105
|
+
unrecognized.join(",")
|
|
1106
|
+
].join("\0");
|
|
1107
|
+
if (seen.has(dedupeKey)) return;
|
|
1108
|
+
seen.add(dedupeKey);
|
|
1109
|
+
const parts = [];
|
|
1110
|
+
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.`);
|
|
1111
|
+
if (filterValidationSkipped !== void 0) parts.push(`the where-clause was not schema-validated (${filterValidationSkipped}), so an unindexed filter SCANNED rather than being rejected. Results are still correct — the substrate refuses a predicate it cannot honour — but the cost is unbounded on a large table.`);
|
|
1112
|
+
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.`);
|
|
1113
|
+
console.warn(`[substrate-client] ${opKey}: ${parts.join(" Also, ")} (Pass \`onDiagnostics\` to SubstrateClient to route this elsewhere.)`);
|
|
1114
|
+
};
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
//#endregion
|
|
1118
|
+
//#region ../../packages/substrate-client/src/transport/sse.ts
|
|
1119
|
+
/** Parse one SSE block; null when it carries no data (comment-only or empty). Throws on an in-band `error` event. */
|
|
1120
|
+
function parseBlock(block) {
|
|
1121
|
+
let event = "message";
|
|
1122
|
+
const data = [];
|
|
1123
|
+
for (const line of block.split("\n")) {
|
|
1124
|
+
if (line.startsWith(":")) continue;
|
|
1125
|
+
if (line.startsWith("event:")) event = line.slice(6).trim();
|
|
1126
|
+
else if (line.startsWith("data:")) data.push(line.slice(5).startsWith(" ") ? line.slice(6) : line.slice(5));
|
|
1127
|
+
}
|
|
1128
|
+
if (data.length === 0) return null;
|
|
1129
|
+
const raw = data.join("\n");
|
|
1130
|
+
let parsed;
|
|
1131
|
+
try {
|
|
1132
|
+
parsed = JSON.parse(raw);
|
|
1133
|
+
} catch (err) {
|
|
1134
|
+
throw new NetworkError(`malformed SSE data for event '${event}': ${raw.slice(0, 100)}`, err);
|
|
1135
|
+
}
|
|
1136
|
+
if (event === "error") {
|
|
1137
|
+
const e = parsed;
|
|
1138
|
+
throw new NetworkError(`${e.code ?? "error"}: ${e.message ?? ""}`, parsed);
|
|
1139
|
+
}
|
|
1140
|
+
return {
|
|
1141
|
+
event,
|
|
1142
|
+
data: parsed
|
|
1143
|
+
};
|
|
1144
|
+
}
|
|
1145
|
+
async function* readSse(body) {
|
|
1146
|
+
const reader = body.getReader();
|
|
1147
|
+
const decoder = new TextDecoder();
|
|
1148
|
+
let buf = "";
|
|
1149
|
+
try {
|
|
1150
|
+
for (;;) {
|
|
1151
|
+
const { value, done } = await reader.read();
|
|
1152
|
+
if (done) break;
|
|
1153
|
+
buf = (buf + decoder.decode(value, { stream: true })).replace(/\r\n/g, "\n");
|
|
1154
|
+
let sep = buf.indexOf("\n\n");
|
|
1155
|
+
while (sep >= 0) {
|
|
1156
|
+
const block = buf.slice(0, sep);
|
|
1157
|
+
buf = buf.slice(sep + 2);
|
|
1158
|
+
sep = buf.indexOf("\n\n");
|
|
1159
|
+
const evt = parseBlock(block);
|
|
1160
|
+
if (evt !== null) yield evt;
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
buf += decoder.decode();
|
|
1164
|
+
const tail = buf.replace(/\r\n?/g, "\n").trim();
|
|
1165
|
+
if (tail !== "") {
|
|
1166
|
+
const evt = parseBlock(tail);
|
|
1167
|
+
if (evt !== null) yield evt;
|
|
1168
|
+
}
|
|
1169
|
+
} finally {
|
|
1170
|
+
await reader.cancel().catch(() => {});
|
|
1171
|
+
reader.releaseLock();
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
//#endregion
|
|
1176
|
+
//#region ../../packages/substrate-client/src/nl.ts
|
|
1177
|
+
function createNlApi(t) {
|
|
1178
|
+
const packs = /* @__PURE__ */ new Map();
|
|
1179
|
+
return {
|
|
1180
|
+
async *ask(req, opts = {}) {
|
|
1181
|
+
const res = await t.raw("/substrate/v1/nl", {
|
|
1182
|
+
method: "POST",
|
|
1183
|
+
body: req,
|
|
1184
|
+
accept: "text/event-stream",
|
|
1185
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
1186
|
+
});
|
|
1187
|
+
if (res.body === null) throw new NetworkError("empty SSE body", null);
|
|
1188
|
+
yield* readSse(res.body);
|
|
1189
|
+
},
|
|
1190
|
+
async askJson(req, opts = {}) {
|
|
1191
|
+
return await (await t.raw("/substrate/v1/nl", {
|
|
1192
|
+
method: "POST",
|
|
1193
|
+
body: req,
|
|
1194
|
+
accept: "application/json",
|
|
1195
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
1196
|
+
})).json();
|
|
1197
|
+
},
|
|
1198
|
+
async pack(namespace, opts = {}) {
|
|
1199
|
+
const prior = packs.get(namespace);
|
|
1200
|
+
const url = `/substrate/v1/nl/pack/${encodeURIComponent(namespace)}`;
|
|
1201
|
+
const res = await t.raw(url, {
|
|
1202
|
+
method: "GET",
|
|
1203
|
+
allow304: true,
|
|
1204
|
+
...prior !== void 0 ? { headers: { "if-none-match": prior.etag } } : {},
|
|
1205
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
1206
|
+
});
|
|
1207
|
+
if (res.status === 304) {
|
|
1208
|
+
if (prior !== void 0) return structuredClone(prior.body);
|
|
1209
|
+
throw new NetworkError(`GET ${url} returned 304 with no cached pack to reuse`, null);
|
|
1210
|
+
}
|
|
1211
|
+
const body = await res.json();
|
|
1212
|
+
const etag = res.headers.get("etag");
|
|
1213
|
+
if (etag !== null) packs.set(namespace, {
|
|
1214
|
+
etag,
|
|
1215
|
+
body: structuredClone(body)
|
|
1216
|
+
});
|
|
1217
|
+
return structuredClone(body);
|
|
1218
|
+
}
|
|
1219
|
+
};
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
//#endregion
|
|
1223
|
+
//#region ../../packages/substrate-client/src/subscribe-util.ts
|
|
1224
|
+
/**
|
|
1225
|
+
* Produce a copy of `frame` where every qualified key's `fields` selection has
|
|
1226
|
+
* `id: true` injected. `update` and `remove` subscribe events are correlated by
|
|
1227
|
+
* row id, so without an `id` in the selection a live consumer would have nothing
|
|
1228
|
+
* to patch against.
|
|
1229
|
+
*
|
|
1230
|
+
* The input frame is never mutated. Callers still use the original frame for
|
|
1231
|
+
* cache-key canonicalisation so query + subscribe on the same frame resolve to
|
|
1232
|
+
* the same cache entry.
|
|
1233
|
+
*/
|
|
1234
|
+
function augmentFramesWithId(frame) {
|
|
1235
|
+
const out = {};
|
|
1236
|
+
for (const [key, entry] of Object.entries(frame)) if (Array.isArray(entry)) out[key] = entry.map((e) => ({
|
|
1237
|
+
params: e.params ?? {},
|
|
1238
|
+
fields: {
|
|
1239
|
+
id: true,
|
|
1240
|
+
...e.fields ?? {}
|
|
1241
|
+
}
|
|
1242
|
+
}));
|
|
1243
|
+
else if (entry !== void 0) out[key] = {
|
|
1244
|
+
params: entry.params ?? {},
|
|
1245
|
+
fields: {
|
|
1246
|
+
id: true,
|
|
1247
|
+
...entry.fields ?? {}
|
|
1248
|
+
}
|
|
1249
|
+
};
|
|
1250
|
+
return out;
|
|
1251
|
+
}
|
|
1252
|
+
/**
|
|
1253
|
+
* Validate that `frame` has exactly one qualified key and return it. Throws with
|
|
1254
|
+
* a descriptive error for zero- or multi-key frames.
|
|
1255
|
+
*/
|
|
1256
|
+
function assertSingleKey(frame) {
|
|
1257
|
+
const keys = Object.keys(frame);
|
|
1258
|
+
if (keys.length !== 1) {
|
|
1259
|
+
if (keys.length === 0) throw new Error("Live subscribe surfaces require exactly one key in the frame.");
|
|
1260
|
+
throw new Error(`Live subscribe surfaces require a single qualified key. Got: ${keys.join(", ")}`);
|
|
1261
|
+
}
|
|
1262
|
+
return keys[0];
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
//#endregion
|
|
1266
|
+
//#region ../../packages/substrate-client/src/transport/http.ts
|
|
1267
|
+
var HttpTransport = class {
|
|
1268
|
+
#endpoint;
|
|
1269
|
+
#fetch;
|
|
1270
|
+
#token;
|
|
1271
|
+
#getToken;
|
|
1272
|
+
constructor(opts) {
|
|
1273
|
+
if (opts.token !== void 0 && opts.getToken !== void 0) throw new Error("HttpTransport: provide `token` OR `getToken`, not both");
|
|
1274
|
+
this.#endpoint = opts.endpoint.replace(/\/+$/, "");
|
|
1275
|
+
this.#fetch = (opts.fetch ?? globalThis.fetch).bind(globalThis);
|
|
1276
|
+
this.#token = opts.token;
|
|
1277
|
+
this.#getToken = opts.getToken;
|
|
1278
|
+
}
|
|
1279
|
+
async query(frame, opts) {
|
|
1280
|
+
return this.#postEnvelope(`${this.#endpoint}/substrate/v1/query`, frame, opts);
|
|
1281
|
+
}
|
|
1282
|
+
async mutate(frame, opts) {
|
|
1283
|
+
return this.#postEnvelope(`${this.#endpoint}/substrate/v1/mutate`, frame, opts);
|
|
1284
|
+
}
|
|
1285
|
+
async federatedSchema(opts = {}) {
|
|
1286
|
+
const url = `${this.#endpoint}/substrate/v1/federated-schema`;
|
|
1287
|
+
const headers = await this.#headers("json", opts.headers);
|
|
1288
|
+
let res;
|
|
1289
|
+
try {
|
|
1290
|
+
res = await this.#fetch(url, {
|
|
1291
|
+
method: "GET",
|
|
1292
|
+
headers,
|
|
1293
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
1294
|
+
});
|
|
1295
|
+
} catch (err) {
|
|
1296
|
+
throw new NetworkError(`GET ${url} failed`, err);
|
|
1297
|
+
}
|
|
1298
|
+
await this.#assertOk(res, url);
|
|
1299
|
+
return await res.json();
|
|
1300
|
+
}
|
|
1301
|
+
/** A request to an arbitrary /substrate path with the client's auth; asserts ok (a 304 passes only with allow304). */
|
|
1302
|
+
async raw(path, init) {
|
|
1303
|
+
const url = `${this.#endpoint}${path}`;
|
|
1304
|
+
const extra = init.accept !== void 0 ? { accept: init.accept } : {};
|
|
1305
|
+
for (const [k, v] of Object.entries(init.headers ?? {})) extra[k.toLowerCase()] = v;
|
|
1306
|
+
const headers = await this.#headers("json", extra);
|
|
1307
|
+
if (init.body === void 0) delete headers["content-type"];
|
|
1308
|
+
let res;
|
|
1309
|
+
try {
|
|
1310
|
+
res = await this.#fetch(url, {
|
|
1311
|
+
method: init.method,
|
|
1312
|
+
headers,
|
|
1313
|
+
...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {},
|
|
1314
|
+
...init.signal !== void 0 ? { signal: init.signal } : {}
|
|
1315
|
+
});
|
|
1316
|
+
} catch (err) {
|
|
1317
|
+
throw new NetworkError(`${init.method} ${url} failed`, err);
|
|
1318
|
+
}
|
|
1319
|
+
if (!(init.allow304 === true && res.status === 304)) await this.#assertOk(res, url);
|
|
1320
|
+
return res;
|
|
1321
|
+
}
|
|
1322
|
+
async #postEnvelope(url, body, opts) {
|
|
1323
|
+
const wire = opts.wire ?? "json";
|
|
1324
|
+
const headers = await this.#headers(wire, opts.headers);
|
|
1325
|
+
let res;
|
|
1326
|
+
try {
|
|
1327
|
+
res = await this.#fetch(url, {
|
|
1328
|
+
method: "POST",
|
|
1329
|
+
headers,
|
|
1330
|
+
body: JSON.stringify(body),
|
|
1331
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
1332
|
+
});
|
|
1333
|
+
} catch (err) {
|
|
1334
|
+
throw new NetworkError(`POST ${url} failed`, err);
|
|
1335
|
+
}
|
|
1336
|
+
await this.#assertOk(res, url);
|
|
1337
|
+
if (wire === "pack") {
|
|
1338
|
+
const buf = await res.arrayBuffer();
|
|
1339
|
+
return { __packBytes: new Uint8Array(buf) };
|
|
1340
|
+
}
|
|
1341
|
+
return await res.json();
|
|
1342
|
+
}
|
|
1343
|
+
async #headers(wire, extra) {
|
|
1344
|
+
const headers = {
|
|
1345
|
+
"content-type": "application/json",
|
|
1346
|
+
accept: wire === "pack" ? "application/vnd.substrate.pack" : "application/json"
|
|
1347
|
+
};
|
|
1348
|
+
const tok = this.#token ?? (this.#getToken ? await this.#getToken() : void 0);
|
|
1349
|
+
if (tok !== void 0) headers.authorization = `Bearer ${tok}`;
|
|
1350
|
+
return {
|
|
1351
|
+
...headers,
|
|
1352
|
+
...extra
|
|
1353
|
+
};
|
|
1354
|
+
}
|
|
1355
|
+
async #assertOk(res, url) {
|
|
1356
|
+
if (res.ok) return;
|
|
1357
|
+
if (res.status === 401 || res.status === 403) {
|
|
1358
|
+
const { code, serverMessage, body } = await errorInfo(res);
|
|
1359
|
+
const info = {
|
|
1360
|
+
...code !== void 0 ? { code } : {},
|
|
1361
|
+
...serverMessage !== void 0 ? { serverMessage } : {},
|
|
1362
|
+
...body !== void 0 ? { body } : {}
|
|
1363
|
+
};
|
|
1364
|
+
throw new AuthError(`${res.status === 401 ? "Unauthorised" : "Forbidden"}: ${url}`, res.status, info);
|
|
1365
|
+
}
|
|
1366
|
+
throw new NetworkError(`${res.status} from ${url}`, null, await errorInfo(res));
|
|
1367
|
+
}
|
|
1368
|
+
};
|
|
1369
|
+
/** 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. */
|
|
1370
|
+
async function errorInfo(res) {
|
|
1371
|
+
const info = { status: res.status };
|
|
1372
|
+
try {
|
|
1373
|
+
const body = JSON.parse(await res.text());
|
|
1374
|
+
if (body !== null && typeof body === "object" && !Array.isArray(body)) {
|
|
1375
|
+
const b = body;
|
|
1376
|
+
info.body = b;
|
|
1377
|
+
const nested = b.error !== null && typeof b.error === "object" ? b.error : void 0;
|
|
1378
|
+
const message = [
|
|
1379
|
+
nested?.message,
|
|
1380
|
+
b.error,
|
|
1381
|
+
b.message
|
|
1382
|
+
].find((v) => typeof v === "string");
|
|
1383
|
+
const code = [nested?.code, b.code].find((v) => typeof v === "string");
|
|
1384
|
+
if (typeof message === "string") info.serverMessage = message;
|
|
1385
|
+
if (typeof code === "string") info.code = code;
|
|
1386
|
+
}
|
|
1387
|
+
} catch {}
|
|
1388
|
+
return info;
|
|
1389
|
+
}
|
|
1390
|
+
|
|
1391
|
+
//#endregion
|
|
1392
|
+
//#region ../../packages/substrate-client/src/reconnect.ts
|
|
1393
|
+
var ReconnectScheduler = class {
|
|
1394
|
+
#base;
|
|
1395
|
+
#max;
|
|
1396
|
+
#jitter;
|
|
1397
|
+
#attempt = 0;
|
|
1398
|
+
constructor(opts) {
|
|
1399
|
+
this.#base = opts.baseDelayMs;
|
|
1400
|
+
this.#max = opts.maxDelayMs;
|
|
1401
|
+
this.#jitter = opts.jitter;
|
|
1402
|
+
}
|
|
1403
|
+
nextDelay() {
|
|
1404
|
+
const raw = Math.min(this.#base * 2 ** this.#attempt, this.#max);
|
|
1405
|
+
this.#attempt += 1;
|
|
1406
|
+
if (this.#jitter === 0) return raw;
|
|
1407
|
+
const spread = raw * this.#jitter;
|
|
1408
|
+
return raw + (Math.random() * 2 - 1) * spread;
|
|
1409
|
+
}
|
|
1410
|
+
reset() {
|
|
1411
|
+
this.#attempt = 0;
|
|
1412
|
+
}
|
|
1413
|
+
/**
|
|
1414
|
+
* Resolve after `nextDelay()` ms. Callers must use this serially — the
|
|
1415
|
+
* `#attempt` counter is shared across calls, so overlapping `schedule()`
|
|
1416
|
+
* invocations will produce incorrect delays. The WS reconnect loop awaits
|
|
1417
|
+
* each `schedule()` before firing the next attempt.
|
|
1418
|
+
*/
|
|
1419
|
+
async schedule() {
|
|
1420
|
+
const d = this.nextDelay();
|
|
1421
|
+
await new Promise((resolve) => setTimeout(resolve, d));
|
|
1422
|
+
}
|
|
1423
|
+
};
|
|
1424
|
+
|
|
1425
|
+
//#endregion
|
|
1426
|
+
//#region ../../packages/substrate-client/src/transport/multiplex.ts
|
|
1427
|
+
/**
|
|
1428
|
+
* MultiplexedSocket — low-level WS multiplexer.
|
|
1429
|
+
*
|
|
1430
|
+
* One raw WebSocket; outbound frames get a client-generated `id`; inbound
|
|
1431
|
+
* frames with a matching `id` route to the right pending handler.
|
|
1432
|
+
*
|
|
1433
|
+
* Subscribe/stream ops stay pending across multiple messages (they receive
|
|
1434
|
+
* snapshot/add/update/remove/chunk/end/error frames). Query/mutate are not
|
|
1435
|
+
* handled here — those go via HTTP.
|
|
1436
|
+
*
|
|
1437
|
+
* Encoding: JSON-over-WS by default. Pass `usePack: true` to send/receive
|
|
1438
|
+
* msgpack-encoded frames matching the `substrate-pack` subprotocol negotiated
|
|
1439
|
+
* one level up by `WsTransport`. Under pack, `data` values arrive as
|
|
1440
|
+
* positional tuples — the higher layer (`SubstrateClient`) is responsible for
|
|
1441
|
+
* the schema-driven positional → named decode; the multiplexer only
|
|
1442
|
+
* handles wire-format framing.
|
|
1443
|
+
*
|
|
1444
|
+
* Works with both node-ws WebSocket and browser native WebSocket via the
|
|
1445
|
+
* shared `addEventListener` interface (node-ws v8+ supports it).
|
|
1446
|
+
*/
|
|
1447
|
+
/** Terminal response kinds — once received the pending entry is cleared. */
|
|
1448
|
+
const TERMINAL_KINDS = /* @__PURE__ */ new Set(["end", "error"]);
|
|
1449
|
+
var MultiplexedSocket = class {
|
|
1450
|
+
#ws;
|
|
1451
|
+
#mode;
|
|
1452
|
+
#pending = /* @__PURE__ */ new Map();
|
|
1453
|
+
#seq = 0;
|
|
1454
|
+
#closing = false;
|
|
1455
|
+
/**
|
|
1456
|
+
* Accept either a node `ws` WebSocket or a browser WebSocket — both expose
|
|
1457
|
+
* `addEventListener`. The constructor wires up message and close handling.
|
|
1458
|
+
*
|
|
1459
|
+
* `usePack` is set by `WsTransport` after the `substrate-pack` subprotocol
|
|
1460
|
+
* has been negotiated at handshake; once true the socket exclusively
|
|
1461
|
+
* speaks msgpack frames.
|
|
1462
|
+
*/
|
|
1463
|
+
constructor(ws, opts = {}) {
|
|
1464
|
+
this.#ws = ws;
|
|
1465
|
+
this.#mode = opts.usePack === true ? "pack" : "json";
|
|
1466
|
+
ws.addEventListener("message", (ev) => this.#onMessage(ev));
|
|
1467
|
+
ws.addEventListener("close", (ev) => this.#onClose(ev));
|
|
1468
|
+
}
|
|
1469
|
+
nextId() {
|
|
1470
|
+
this.#seq += 1;
|
|
1471
|
+
return `c${this.#seq}`;
|
|
1472
|
+
}
|
|
1473
|
+
/**
|
|
1474
|
+
* Serialise + send `frame` (which must already include an `id` field) and
|
|
1475
|
+
* register `pending` as the handler for responses bearing that id.
|
|
1476
|
+
* Returns the frame id for caller bookkeeping.
|
|
1477
|
+
*/
|
|
1478
|
+
send(frame, pending) {
|
|
1479
|
+
const id = frame.id ?? this.nextId();
|
|
1480
|
+
const frameWithId = id === frame.id ? frame : {
|
|
1481
|
+
...frame,
|
|
1482
|
+
id
|
|
1483
|
+
};
|
|
1484
|
+
this.#pending.set(id, pending);
|
|
1485
|
+
try {
|
|
1486
|
+
this.#sendWire(encodeWsFrame(frameWithId, this.#mode));
|
|
1487
|
+
} catch (_err) {
|
|
1488
|
+
this.#pending.delete(id);
|
|
1489
|
+
pending.onClose("send failed");
|
|
1490
|
+
}
|
|
1491
|
+
return id;
|
|
1492
|
+
}
|
|
1493
|
+
/**
|
|
1494
|
+
* Send a cancel frame for a given subscription id and remove the pending
|
|
1495
|
+
* handler. The server will emit a terminal `end` frame; since we delete the
|
|
1496
|
+
* pending entry here, that frame is silently dropped.
|
|
1497
|
+
*/
|
|
1498
|
+
cancel(id) {
|
|
1499
|
+
this.#pending.delete(id);
|
|
1500
|
+
try {
|
|
1501
|
+
this.#sendWire(encodeWsFrame({
|
|
1502
|
+
id,
|
|
1503
|
+
op: "cancel"
|
|
1504
|
+
}, this.#mode));
|
|
1505
|
+
} catch {}
|
|
1506
|
+
}
|
|
1507
|
+
/**
|
|
1508
|
+
* Push wire bytes to the socket. The branch exists because `WebSocket.send`'s
|
|
1509
|
+
* overloads don't accept the union. Binary frames are copied into a fresh
|
|
1510
|
+
* `Uint8Array` so the backing buffer is an `ArrayBuffer`, not the
|
|
1511
|
+
* `ArrayBufferLike` msgpackr's `Buffer` is typed with — avoiding a cast.
|
|
1512
|
+
*/
|
|
1513
|
+
#sendWire(wire) {
|
|
1514
|
+
if (typeof wire === "string") this.#ws.send(wire);
|
|
1515
|
+
else this.#ws.send(new Uint8Array(wire));
|
|
1516
|
+
}
|
|
1517
|
+
close() {
|
|
1518
|
+
if (this.#closing) return;
|
|
1519
|
+
this.#closing = true;
|
|
1520
|
+
try {
|
|
1521
|
+
this.#ws.close();
|
|
1522
|
+
} catch {}
|
|
1523
|
+
}
|
|
1524
|
+
#onMessage(ev) {
|
|
1525
|
+
let msg;
|
|
1526
|
+
try {
|
|
1527
|
+
msg = decodeWsEnvelope(ev.data, this.#mode);
|
|
1528
|
+
} catch {
|
|
1529
|
+
return;
|
|
1530
|
+
}
|
|
1531
|
+
const pending = this.#pending.get(msg.id);
|
|
1532
|
+
if (!pending) return;
|
|
1533
|
+
if (TERMINAL_KINDS.has(msg.kind)) this.#pending.delete(msg.id);
|
|
1534
|
+
pending.onMessage(msg);
|
|
1535
|
+
}
|
|
1536
|
+
#onClose(ev) {
|
|
1537
|
+
const reason = this.#closing ? "transport_closed" : ev.code === 1012 ? "server_restart" : `ws closed (code ${ev.code})`;
|
|
1538
|
+
const snapshot = [...this.#pending.entries()];
|
|
1539
|
+
this.#pending.clear();
|
|
1540
|
+
for (const [, pending] of snapshot) pending.onClose(reason);
|
|
1541
|
+
}
|
|
1542
|
+
};
|
|
1543
|
+
|
|
1544
|
+
//#endregion
|
|
1545
|
+
//#region ../../packages/substrate-client/src/transport/ws.ts
|
|
1546
|
+
/**
|
|
1547
|
+
* WsTransport — high-level WebSocket transport for Substrate subscriptions.
|
|
1548
|
+
*
|
|
1549
|
+
* Manages one raw socket per `(endpoint, auth)` pair via MultiplexedSocket.
|
|
1550
|
+
* Exposes `subscribe` and `stream` as AsyncIterables; `cancel` is handled
|
|
1551
|
+
* transparently via the iterator's `return()` method.
|
|
1552
|
+
*
|
|
1553
|
+
* Protocol:
|
|
1554
|
+
* - No hello/handshake: send subscribe/stream frames immediately on open.
|
|
1555
|
+
* - WS handles: subscribe, stream, cancel only. Query/mutate use HTTP.
|
|
1556
|
+
* - Auth: Bearer token in Authorization header on the HTTP upgrade request.
|
|
1557
|
+
* Node-ws supports custom headers; the WHATWG/browser WebSocket does not,
|
|
1558
|
+
* so under Node node-ws is always preferred even when a global WebSocket
|
|
1559
|
+
* exists. True browsers cannot authenticate the WS without a
|
|
1560
|
+
* header-capable `webSocket` implementation.
|
|
1561
|
+
* - Response kinds: snapshot / add / update / remove / chunk / end / error.
|
|
1562
|
+
* - Terminal kinds for cleanup: 'end' and 'error'.
|
|
1563
|
+
*
|
|
1564
|
+
* Reconnect: when the socket closes unexpectedly, ReconnectScheduler backs
|
|
1565
|
+
* off and re-opens. Active subscriptions are resubscribed on the new socket —
|
|
1566
|
+
* the consumer's AsyncIterable keeps flowing (snapshot arrives again from the
|
|
1567
|
+
* server's perspective; the consumer sees it as a new event). A transport that
|
|
1568
|
+
* has never connected does not retry: its first failure rejects `next()`.
|
|
1569
|
+
*/
|
|
1570
|
+
/**
|
|
1571
|
+
* Terminal-cause tokens from the WS teardown contract
|
|
1572
|
+
* (docs/ws-subscription-contract.md). Local literals, not substrate-types
|
|
1573
|
+
* imports: they are stable wire contract, like the 1012 close code.
|
|
1574
|
+
*/
|
|
1575
|
+
const REASON_SUBSCRIPTION_OVERLOADED = "subscription_overloaded";
|
|
1576
|
+
const REASON_SERVER_RESTART = "server_restart";
|
|
1577
|
+
/**
|
|
1578
|
+
* Pick the WebSocket implementation for a connection.
|
|
1579
|
+
*
|
|
1580
|
+
* Priority: injected > node-ws under Node > global (browser). Node ≥22 ships
|
|
1581
|
+
* a global WebSocket that cannot carry headers, so preferring it would
|
|
1582
|
+
* silently drop the bearer.
|
|
1583
|
+
*
|
|
1584
|
+
* Throws when a token is configured but the only available implementation
|
|
1585
|
+
* cannot carry headers (a true browser): connecting anonymously to an
|
|
1586
|
+
* auth-gated server would loop on 4001 instead.
|
|
1587
|
+
*/
|
|
1588
|
+
function selectWebSocketImpl(opts) {
|
|
1589
|
+
if (opts.injected !== void 0) return {
|
|
1590
|
+
impl: opts.injected,
|
|
1591
|
+
supportsHeaders: true
|
|
1592
|
+
};
|
|
1593
|
+
if (opts.isNode) return {
|
|
1594
|
+
impl: opts.nodeWs,
|
|
1595
|
+
supportsHeaders: true
|
|
1596
|
+
};
|
|
1597
|
+
if (opts.globalWs !== void 0) {
|
|
1598
|
+
if (opts.hasToken) throw new NetworkError("WsTransport: a bearer token is configured but the only available WebSocket implementation (the WHATWG/browser global) cannot carry the Authorization header. Supply a header-capable implementation via the `webSocket` option.", null);
|
|
1599
|
+
return {
|
|
1600
|
+
impl: opts.globalWs,
|
|
1601
|
+
supportsHeaders: false
|
|
1602
|
+
};
|
|
1603
|
+
}
|
|
1604
|
+
throw new NetworkError("WsTransport: no WebSocket implementation available", null);
|
|
1605
|
+
}
|
|
1606
|
+
const DEFAULT_RECONNECT = {
|
|
1607
|
+
baseDelayMs: 1e3,
|
|
1608
|
+
maxDelayMs: 3e4,
|
|
1609
|
+
jitter: .1
|
|
1610
|
+
};
|
|
1611
|
+
const DEFAULT_OVERLOAD_RESUBSCRIBE = {
|
|
1612
|
+
enabled: true,
|
|
1613
|
+
maxAttempts: 3,
|
|
1614
|
+
baseDelayMs: 1e3,
|
|
1615
|
+
maxDelayMs: 3e4,
|
|
1616
|
+
jitter: .1,
|
|
1617
|
+
healthyResetMs: 6e4
|
|
1618
|
+
};
|
|
1619
|
+
var WsTransport = class {
|
|
1620
|
+
#endpoint;
|
|
1621
|
+
#token;
|
|
1622
|
+
#getToken;
|
|
1623
|
+
#webSocket;
|
|
1624
|
+
#reconnectOpts;
|
|
1625
|
+
#encoding;
|
|
1626
|
+
#overloadResubscribe;
|
|
1627
|
+
/** Current multiplexed socket, or null if not yet opened / closed. */
|
|
1628
|
+
#mux = null;
|
|
1629
|
+
/** Promise that resolves when the socket is open and ready. */
|
|
1630
|
+
#openPromise = null;
|
|
1631
|
+
/** Set when close() is called — no more reconnects. */
|
|
1632
|
+
#destroyed = false;
|
|
1633
|
+
/** Active subscriptions keyed by their logical frame id. */
|
|
1634
|
+
#activeSubs = /* @__PURE__ */ new Map();
|
|
1635
|
+
/** Guard: prevents multiple concurrent #reconnectActiveSubs invocations. */
|
|
1636
|
+
#reconnecting = false;
|
|
1637
|
+
/**
|
|
1638
|
+
* Close code captured from the most recent unintentional socket close.
|
|
1639
|
+
* Read once by the next `#openLoop` and cleared. When it equals 1012
|
|
1640
|
+
* (W3C "Service Restart") the loop skips its first scheduled backoff —
|
|
1641
|
+
* the server is intentionally bouncing and we'd rather pay one wasted
|
|
1642
|
+
* connect attempt than 1+s of jittered delay.
|
|
1643
|
+
*/
|
|
1644
|
+
#lastCloseCode = null;
|
|
1645
|
+
/**
|
|
1646
|
+
* Retry forever only once a socket has opened. Before that, a failure is
|
|
1647
|
+
* most likely a wrong endpoint or a broken token, so it surfaces instead.
|
|
1648
|
+
*/
|
|
1649
|
+
#hasOpened = false;
|
|
1650
|
+
constructor(opts) {
|
|
1651
|
+
if (opts.token !== void 0 && opts.getToken !== void 0) throw new Error("WsTransport: provide `token` OR `getToken`, not both");
|
|
1652
|
+
this.#endpoint = opts.endpoint;
|
|
1653
|
+
this.#token = opts.token;
|
|
1654
|
+
this.#getToken = opts.getToken;
|
|
1655
|
+
this.#webSocket = opts.webSocket;
|
|
1656
|
+
this.#reconnectOpts = {
|
|
1657
|
+
...DEFAULT_RECONNECT,
|
|
1658
|
+
...opts.reconnect
|
|
1659
|
+
};
|
|
1660
|
+
this.#encoding = opts.encoding ?? "json";
|
|
1661
|
+
this.#overloadResubscribe = {
|
|
1662
|
+
...DEFAULT_OVERLOAD_RESUBSCRIBE,
|
|
1663
|
+
...opts.overloadResubscribe
|
|
1664
|
+
};
|
|
1665
|
+
}
|
|
1666
|
+
/**
|
|
1667
|
+
* Subscribe to a live query. Returns an AsyncIterable of SubscribeEvents.
|
|
1668
|
+
* Calling `break` or `return()` on the iterator sends a cancel frame.
|
|
1669
|
+
*/
|
|
1670
|
+
subscribe(req) {
|
|
1671
|
+
return this.#makeIterable({
|
|
1672
|
+
...req,
|
|
1673
|
+
op: "subscribe"
|
|
1674
|
+
});
|
|
1675
|
+
}
|
|
1676
|
+
/** Stream a one-shot resolver. Returns chunk events followed by an end event. */
|
|
1677
|
+
stream(req) {
|
|
1678
|
+
return this.#makeIterable({
|
|
1679
|
+
...req,
|
|
1680
|
+
op: "stream"
|
|
1681
|
+
});
|
|
1682
|
+
}
|
|
1683
|
+
/** Gracefully shut down. Cancels all active subscriptions and closes the socket. */
|
|
1684
|
+
async close() {
|
|
1685
|
+
this.#destroyed = true;
|
|
1686
|
+
for (const [, sub] of this.#activeSubs) {
|
|
1687
|
+
sub.done = true;
|
|
1688
|
+
if (sub.retryTimer !== null) {
|
|
1689
|
+
clearTimeout(sub.retryTimer);
|
|
1690
|
+
sub.retryTimer = null;
|
|
1691
|
+
}
|
|
1692
|
+
if (sub.waiter) {
|
|
1693
|
+
sub.waiter(null);
|
|
1694
|
+
sub.waiter = null;
|
|
1695
|
+
}
|
|
1696
|
+
}
|
|
1697
|
+
this.#activeSubs.clear();
|
|
1698
|
+
if (this.#mux) {
|
|
1699
|
+
this.#mux.close();
|
|
1700
|
+
this.#mux = null;
|
|
1701
|
+
}
|
|
1702
|
+
this.#openPromise = null;
|
|
1703
|
+
}
|
|
1704
|
+
/** Ensure a connected MultiplexedSocket is available. */
|
|
1705
|
+
async #ensureOpen() {
|
|
1706
|
+
if (this.#mux !== null) return this.#mux;
|
|
1707
|
+
if (this.#openPromise !== null) return this.#openPromise;
|
|
1708
|
+
this.#openPromise = this.#openLoop();
|
|
1709
|
+
return this.#openPromise;
|
|
1710
|
+
}
|
|
1711
|
+
/**
|
|
1712
|
+
* Open loop: try to open a socket; on failure, backoff and retry.
|
|
1713
|
+
* Runs until connected or #destroyed.
|
|
1714
|
+
*/
|
|
1715
|
+
async #openLoop() {
|
|
1716
|
+
const scheduler = new ReconnectScheduler(this.#reconnectOpts);
|
|
1717
|
+
const wasGracefulRestart = this.#lastCloseCode === 1012;
|
|
1718
|
+
this.#lastCloseCode = null;
|
|
1719
|
+
let firstFailure = true;
|
|
1720
|
+
while (true) {
|
|
1721
|
+
if (this.#destroyed) throw new NetworkError("WsTransport destroyed", null);
|
|
1722
|
+
try {
|
|
1723
|
+
const mux = await this.#openOnce();
|
|
1724
|
+
scheduler.reset();
|
|
1725
|
+
this.#hasOpened = true;
|
|
1726
|
+
this.#mux = mux;
|
|
1727
|
+
this.#openPromise = null;
|
|
1728
|
+
return mux;
|
|
1729
|
+
} catch (err) {
|
|
1730
|
+
if (this.#destroyed) throw new NetworkError("WsTransport destroyed", err);
|
|
1731
|
+
if (!this.#hasOpened) {
|
|
1732
|
+
this.#openPromise = null;
|
|
1733
|
+
throw err;
|
|
1734
|
+
}
|
|
1735
|
+
if (wasGracefulRestart && firstFailure) {
|
|
1736
|
+
firstFailure = false;
|
|
1737
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
1738
|
+
} else {
|
|
1739
|
+
firstFailure = false;
|
|
1740
|
+
await scheduler.schedule();
|
|
1741
|
+
}
|
|
1742
|
+
if (this.#destroyed) throw new NetworkError("WsTransport destroyed", null);
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
/** Open one WebSocket connection and resolve when it's ready. */
|
|
1747
|
+
async #openOnce() {
|
|
1748
|
+
const token = this.#token ?? (this.#getToken ? await this.#getToken() : void 0);
|
|
1749
|
+
const subprotocols = this.#encoding === "pack" ? [WS_SUBPROTOCOL_SUBSTRATE_PACK] : void 0;
|
|
1750
|
+
const ws = await new Promise((resolve, reject) => {
|
|
1751
|
+
let rawWs;
|
|
1752
|
+
const { impl, supportsHeaders } = selectWebSocketImpl({
|
|
1753
|
+
injected: this.#webSocket,
|
|
1754
|
+
isNode: typeof process !== "undefined" && process.versions?.node !== void 0,
|
|
1755
|
+
globalWs: globalThis.WebSocket,
|
|
1756
|
+
nodeWs: WebSocket,
|
|
1757
|
+
hasToken: token !== void 0
|
|
1758
|
+
});
|
|
1759
|
+
if (supportsHeaders) {
|
|
1760
|
+
const headers = {};
|
|
1761
|
+
if (token !== void 0) headers.authorization = `Bearer ${token}`;
|
|
1762
|
+
rawWs = new impl(this.#endpoint, subprotocols, { headers });
|
|
1763
|
+
} else rawWs = subprotocols !== void 0 ? new impl(this.#endpoint, subprotocols) : new impl(this.#endpoint);
|
|
1764
|
+
if (this.#encoding === "pack") try {
|
|
1765
|
+
rawWs.binaryType = "arraybuffer";
|
|
1766
|
+
} catch {}
|
|
1767
|
+
const onOpen = () => {
|
|
1768
|
+
rawWs.removeEventListener("error", onError);
|
|
1769
|
+
resolve(rawWs);
|
|
1770
|
+
};
|
|
1771
|
+
const onError = (ev) => {
|
|
1772
|
+
rawWs.removeEventListener("open", onOpen);
|
|
1773
|
+
reject(new NetworkError(`WS connect failed: ${this.#endpoint}`, ev));
|
|
1774
|
+
};
|
|
1775
|
+
rawWs.addEventListener("open", onOpen);
|
|
1776
|
+
rawWs.addEventListener("error", onError);
|
|
1777
|
+
});
|
|
1778
|
+
const mux = new MultiplexedSocket(ws, { usePack: this.#encoding === "pack" });
|
|
1779
|
+
ws.addEventListener("close", (ev) => {
|
|
1780
|
+
if (this.#destroyed) return;
|
|
1781
|
+
if (ev.code === 4001) {
|
|
1782
|
+
if (this.#mux === mux) this.#mux = null;
|
|
1783
|
+
this.#failActiveSubs(new NetworkError(`WS closed 4001 unauthorized by ${this.#endpoint} — bearer rejected (wrong/expired token, or none configured against an auth-gated server)`, ev));
|
|
1784
|
+
return;
|
|
1785
|
+
}
|
|
1786
|
+
if (this.#mux === mux) {
|
|
1787
|
+
this.#mux = null;
|
|
1788
|
+
this.#lastCloseCode = ev.code;
|
|
1789
|
+
}
|
|
1790
|
+
this.#reconnectActiveSubs().catch(() => {});
|
|
1791
|
+
});
|
|
1792
|
+
return mux;
|
|
1793
|
+
}
|
|
1794
|
+
/** Terminate every active sub with `err` — delivered so next() throws. */
|
|
1795
|
+
#failActiveSubs(err) {
|
|
1796
|
+
for (const [, sub] of this.#activeSubs) {
|
|
1797
|
+
if (sub.done) continue;
|
|
1798
|
+
sub.done = true;
|
|
1799
|
+
if (sub.retryTimer !== null) {
|
|
1800
|
+
clearTimeout(sub.retryTimer);
|
|
1801
|
+
sub.retryTimer = null;
|
|
1802
|
+
}
|
|
1803
|
+
const payload = {
|
|
1804
|
+
ok: false,
|
|
1805
|
+
err
|
|
1806
|
+
};
|
|
1807
|
+
if (sub.waiter) {
|
|
1808
|
+
const w = sub.waiter;
|
|
1809
|
+
sub.waiter = null;
|
|
1810
|
+
w(payload);
|
|
1811
|
+
} else sub.queue.push(payload);
|
|
1812
|
+
}
|
|
1813
|
+
this.#activeSubs.clear();
|
|
1814
|
+
}
|
|
1815
|
+
/** Re-subscribe all active subs after a reconnect. */
|
|
1816
|
+
async #reconnectActiveSubs() {
|
|
1817
|
+
if (this.#reconnecting) return;
|
|
1818
|
+
if (this.#destroyed) return;
|
|
1819
|
+
this.#reconnecting = true;
|
|
1820
|
+
try {
|
|
1821
|
+
if (this.#activeSubs.size === 0) return;
|
|
1822
|
+
let mux;
|
|
1823
|
+
try {
|
|
1824
|
+
mux = await this.#ensureOpen();
|
|
1825
|
+
} catch {
|
|
1826
|
+
for (const [, sub] of this.#activeSubs) {
|
|
1827
|
+
sub.done = true;
|
|
1828
|
+
if (sub.retryTimer !== null) {
|
|
1829
|
+
clearTimeout(sub.retryTimer);
|
|
1830
|
+
sub.retryTimer = null;
|
|
1831
|
+
}
|
|
1832
|
+
if (sub.waiter) {
|
|
1833
|
+
sub.waiter(null);
|
|
1834
|
+
sub.waiter = null;
|
|
1835
|
+
}
|
|
1836
|
+
}
|
|
1837
|
+
this.#activeSubs.clear();
|
|
1838
|
+
return;
|
|
1839
|
+
}
|
|
1840
|
+
for (const [, sub] of this.#activeSubs) {
|
|
1841
|
+
if (sub.done) continue;
|
|
1842
|
+
if (sub.retryTimer !== null) {
|
|
1843
|
+
clearTimeout(sub.retryTimer);
|
|
1844
|
+
sub.retryTimer = null;
|
|
1845
|
+
}
|
|
1846
|
+
this.#doSubscribe(mux, sub);
|
|
1847
|
+
}
|
|
1848
|
+
} finally {
|
|
1849
|
+
this.#reconnecting = false;
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1852
|
+
/** Send a subscribe/stream frame on the mux and wire up the Pending handler. */
|
|
1853
|
+
#doSubscribe(mux, sub) {
|
|
1854
|
+
const pending = {
|
|
1855
|
+
onMessage: (msg) => {
|
|
1856
|
+
if (sub.done) return;
|
|
1857
|
+
const action = this.#classifyTerminal(msg, sub);
|
|
1858
|
+
if (action === "suppress") return;
|
|
1859
|
+
let payload;
|
|
1860
|
+
try {
|
|
1861
|
+
if (msgToEvent(msg) === null) return;
|
|
1862
|
+
payload = {
|
|
1863
|
+
ok: true,
|
|
1864
|
+
msg
|
|
1865
|
+
};
|
|
1866
|
+
} catch (err) {
|
|
1867
|
+
payload = {
|
|
1868
|
+
ok: false,
|
|
1869
|
+
err: err instanceof Error ? err : new Error(String(err))
|
|
1870
|
+
};
|
|
1871
|
+
sub.done = true;
|
|
1872
|
+
}
|
|
1873
|
+
if (action === "terminal" && (msg.kind === "end" || msg.kind === "error")) sub.done = true;
|
|
1874
|
+
if (sub.waiter) {
|
|
1875
|
+
const w = sub.waiter;
|
|
1876
|
+
sub.waiter = null;
|
|
1877
|
+
w(payload);
|
|
1878
|
+
} else sub.queue.push(payload);
|
|
1879
|
+
},
|
|
1880
|
+
onClose: (_reason) => {
|
|
1881
|
+
if (sub.done) return;
|
|
1882
|
+
if (this.#destroyed) {
|
|
1883
|
+
sub.done = true;
|
|
1884
|
+
if (sub.waiter) {
|
|
1885
|
+
sub.waiter(null);
|
|
1886
|
+
sub.waiter = null;
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
};
|
|
1891
|
+
const outFrame = {
|
|
1892
|
+
id: sub.socketId,
|
|
1893
|
+
op: sub.frame.op,
|
|
1894
|
+
frame: sub.frame.frame
|
|
1895
|
+
};
|
|
1896
|
+
mux.send(outFrame, pending);
|
|
1897
|
+
}
|
|
1898
|
+
/**
|
|
1899
|
+
* Classify a frame per the teardown contract (substrate repo
|
|
1900
|
+
* docs/ws-subscription-contract.md) BEFORE msgToEvent, which throws on
|
|
1901
|
+
* error frames.
|
|
1902
|
+
*
|
|
1903
|
+
* - 'suppress': consumed by the retry machinery; never reaches the consumer.
|
|
1904
|
+
* Overload error frames with budget left schedule a resubscribe here; the
|
|
1905
|
+
* trailing `end { reason: 'subscription_overloaded' }` of a suppressed
|
|
1906
|
+
* teardown is swallowed too.
|
|
1907
|
+
* - 'survive': delivered to the consumer but NOT terminal — server_restart
|
|
1908
|
+
* end frames; the sub stays live so the socket-close reconnect path
|
|
1909
|
+
* resubscribes it.
|
|
1910
|
+
* - 'terminal': mark done on delivery.
|
|
1911
|
+
* - 'data': everything else.
|
|
1912
|
+
*/
|
|
1913
|
+
#classifyTerminal(msg, sub) {
|
|
1914
|
+
const cfg = this.#overloadResubscribe;
|
|
1915
|
+
if (msg.kind === "error") {
|
|
1916
|
+
if (msg.errors?.[0]?.code !== REASON_SUBSCRIPTION_OVERLOADED || !cfg.enabled) return "terminal";
|
|
1917
|
+
const now = Date.now();
|
|
1918
|
+
if (sub.lastOverloadAt !== null && now - sub.lastOverloadAt > cfg.healthyResetMs) sub.overloadAttempts = 0;
|
|
1919
|
+
sub.lastOverloadAt = now;
|
|
1920
|
+
if (sub.overloadAttempts >= cfg.maxAttempts) return "terminal";
|
|
1921
|
+
sub.overloadAttempts += 1;
|
|
1922
|
+
this.#scheduleOverloadRetry(sub);
|
|
1923
|
+
return "suppress";
|
|
1924
|
+
}
|
|
1925
|
+
if (msg.kind === "end") {
|
|
1926
|
+
if (msg.reason === REASON_SUBSCRIPTION_OVERLOADED && cfg.enabled && sub.retryTimer !== null) return "suppress";
|
|
1927
|
+
if (msg.reason === REASON_SERVER_RESTART) return "survive";
|
|
1928
|
+
return "terminal";
|
|
1929
|
+
}
|
|
1930
|
+
return "data";
|
|
1931
|
+
}
|
|
1932
|
+
/** Backoff then re-send the subscribe frame for `sub` on the live socket. */
|
|
1933
|
+
#scheduleOverloadRetry(sub) {
|
|
1934
|
+
const cfg = this.#overloadResubscribe;
|
|
1935
|
+
const raw = Math.min(cfg.baseDelayMs * 2 ** (sub.overloadAttempts - 1), cfg.maxDelayMs);
|
|
1936
|
+
const delay = cfg.jitter === 0 ? raw : raw + (Math.random() * 2 - 1) * raw * cfg.jitter;
|
|
1937
|
+
sub.retryTimer = setTimeout(() => {
|
|
1938
|
+
sub.retryTimer = null;
|
|
1939
|
+
if (sub.done || this.#destroyed) return;
|
|
1940
|
+
this.#ensureOpen().then((mux) => {
|
|
1941
|
+
if (!sub.done) this.#doSubscribe(mux, sub);
|
|
1942
|
+
}).catch(() => {});
|
|
1943
|
+
}, delay);
|
|
1944
|
+
}
|
|
1945
|
+
#makeIterable(frame) {
|
|
1946
|
+
const logicalId = frame.id;
|
|
1947
|
+
const transport = this;
|
|
1948
|
+
return { [Symbol.asyncIterator]() {
|
|
1949
|
+
const sub = {
|
|
1950
|
+
frame,
|
|
1951
|
+
socketId: logicalId,
|
|
1952
|
+
queue: [],
|
|
1953
|
+
waiter: null,
|
|
1954
|
+
done: false,
|
|
1955
|
+
overloadAttempts: 0,
|
|
1956
|
+
lastOverloadAt: null,
|
|
1957
|
+
retryTimer: null
|
|
1958
|
+
};
|
|
1959
|
+
transport.#activeSubs.set(logicalId, sub);
|
|
1960
|
+
transport.#ensureOpen().then((mux) => {
|
|
1961
|
+
if (!sub.done) transport.#doSubscribe(mux, sub);
|
|
1962
|
+
}).catch((err) => {
|
|
1963
|
+
if (sub.done) return;
|
|
1964
|
+
sub.done = true;
|
|
1965
|
+
transport.#activeSubs.delete(logicalId);
|
|
1966
|
+
const payload = {
|
|
1967
|
+
ok: false,
|
|
1968
|
+
err: err instanceof Error ? err : new NetworkError(String(err), err)
|
|
1969
|
+
};
|
|
1970
|
+
if (sub.waiter) {
|
|
1971
|
+
const w = sub.waiter;
|
|
1972
|
+
sub.waiter = null;
|
|
1973
|
+
w(payload);
|
|
1974
|
+
} else sub.queue.push(payload);
|
|
1975
|
+
});
|
|
1976
|
+
return {
|
|
1977
|
+
async next() {
|
|
1978
|
+
while (true) {
|
|
1979
|
+
if (sub.queue.length > 0) {
|
|
1980
|
+
const payload = sub.queue.shift();
|
|
1981
|
+
if (!payload.ok) {
|
|
1982
|
+
sub.done = true;
|
|
1983
|
+
transport.#activeSubs.delete(logicalId);
|
|
1984
|
+
throw payload.err;
|
|
1985
|
+
}
|
|
1986
|
+
const ev = msgToEvent(payload.msg);
|
|
1987
|
+
if (ev === null) continue;
|
|
1988
|
+
return {
|
|
1989
|
+
value: ev,
|
|
1990
|
+
done: false
|
|
1991
|
+
};
|
|
1992
|
+
}
|
|
1993
|
+
if (sub.done) return {
|
|
1994
|
+
value: void 0,
|
|
1995
|
+
done: true
|
|
1996
|
+
};
|
|
1997
|
+
const payload = await new Promise((resolve) => {
|
|
1998
|
+
sub.waiter = resolve;
|
|
1999
|
+
});
|
|
2000
|
+
if (payload === null) return {
|
|
2001
|
+
value: void 0,
|
|
2002
|
+
done: true
|
|
2003
|
+
};
|
|
2004
|
+
if (!payload.ok) {
|
|
2005
|
+
sub.done = true;
|
|
2006
|
+
transport.#activeSubs.delete(logicalId);
|
|
2007
|
+
throw payload.err;
|
|
2008
|
+
}
|
|
2009
|
+
const ev = msgToEvent(payload.msg);
|
|
2010
|
+
if (ev !== null) return {
|
|
2011
|
+
value: ev,
|
|
2012
|
+
done: false
|
|
2013
|
+
};
|
|
2014
|
+
}
|
|
2015
|
+
},
|
|
2016
|
+
async return() {
|
|
2017
|
+
if (!sub.done) {
|
|
2018
|
+
sub.done = true;
|
|
2019
|
+
if (sub.retryTimer !== null) {
|
|
2020
|
+
clearTimeout(sub.retryTimer);
|
|
2021
|
+
sub.retryTimer = null;
|
|
2022
|
+
}
|
|
2023
|
+
transport.#activeSubs.delete(logicalId);
|
|
2024
|
+
if (transport.#mux) transport.#mux.cancel(sub.socketId);
|
|
2025
|
+
if (sub.waiter) {
|
|
2026
|
+
sub.waiter(null);
|
|
2027
|
+
sub.waiter = null;
|
|
2028
|
+
}
|
|
2029
|
+
}
|
|
2030
|
+
return {
|
|
2031
|
+
value: void 0,
|
|
2032
|
+
done: true
|
|
2033
|
+
};
|
|
2034
|
+
}
|
|
2035
|
+
};
|
|
2036
|
+
} };
|
|
2037
|
+
}
|
|
2038
|
+
};
|
|
2039
|
+
/** Convert an InboundMessage to a SubscribeEvent, or null if unrecognised. */
|
|
2040
|
+
function msgToEvent(msg) {
|
|
2041
|
+
switch (msg.kind) {
|
|
2042
|
+
case "snapshot":
|
|
2043
|
+
case "add":
|
|
2044
|
+
case "update": return {
|
|
2045
|
+
kind: msg.kind,
|
|
2046
|
+
data: msg.data,
|
|
2047
|
+
...msg.shapes !== void 0 ? { shapes: msg.shapes } : {}
|
|
2048
|
+
};
|
|
2049
|
+
case "chunk": return {
|
|
2050
|
+
kind: "chunk",
|
|
2051
|
+
data: msg.data,
|
|
2052
|
+
...msg.shapes !== void 0 ? { shapes: msg.shapes } : {},
|
|
2053
|
+
...msg.sequence !== void 0 ? { sequence: msg.sequence } : {}
|
|
2054
|
+
};
|
|
2055
|
+
case "remove": return {
|
|
2056
|
+
kind: "remove",
|
|
2057
|
+
removedId: msg.removedId ?? ""
|
|
2058
|
+
};
|
|
2059
|
+
case "end": return {
|
|
2060
|
+
kind: "end",
|
|
2061
|
+
...msg.final !== void 0 ? { final: msg.final } : {},
|
|
2062
|
+
...msg.reason !== void 0 ? { reason: msg.reason } : {}
|
|
2063
|
+
};
|
|
2064
|
+
case "error": {
|
|
2065
|
+
const first = (msg.errors ?? [{
|
|
2066
|
+
message: "unknown error",
|
|
2067
|
+
code: "unknown"
|
|
2068
|
+
}])[0] ?? {
|
|
2069
|
+
message: "unknown error",
|
|
2070
|
+
code: "unknown"
|
|
2071
|
+
};
|
|
2072
|
+
throw new SubscribeError(first.message, first.code ?? "unknown");
|
|
2073
|
+
}
|
|
2074
|
+
default: return null;
|
|
2075
|
+
}
|
|
2076
|
+
}
|
|
2077
|
+
|
|
2078
|
+
//#endregion
|
|
2079
|
+
//#region ../../packages/substrate-client/src/wire/pack.ts
|
|
2080
|
+
function isPackMarker(v) {
|
|
2081
|
+
return typeof v === "object" && v !== null && "__packBytes" in v;
|
|
2082
|
+
}
|
|
2083
|
+
|
|
2084
|
+
//#endregion
|
|
2085
|
+
//#region ../../packages/substrate-client/src/wire/json.ts
|
|
2086
|
+
function decodeJsonEnvelope(env) {
|
|
2087
|
+
if (typeof env.schemaVersion !== "string") throw new Error("Malformed envelope: missing schemaVersion");
|
|
2088
|
+
return env;
|
|
2089
|
+
}
|
|
2090
|
+
|
|
2091
|
+
//#endregion
|
|
2092
|
+
//#region ../../packages/substrate-client/src/client.ts
|
|
2093
|
+
/**
|
|
2094
|
+
* SubstrateClient — the public facade over the HTTP and WS transports, wire
|
|
2095
|
+
* decoding and schema-drift handling.
|
|
2096
|
+
*
|
|
2097
|
+
* Routing is protocol-mandated: query and mutate go over HTTP only (WS does
|
|
2098
|
+
* not accept them); subscribe and stream go over WS only.
|
|
2099
|
+
*
|
|
2100
|
+
* Drift detection is lazy-seeded: the client cannot replicate the server's
|
|
2101
|
+
* federated schema-version hash, so the first envelope's `schemaVersion` seeds
|
|
2102
|
+
* the cache and any later mismatch refetches the schema and accepts the new
|
|
2103
|
+
* version as authoritative.
|
|
2104
|
+
*/
|
|
2105
|
+
var SubstrateClient = class {
|
|
2106
|
+
#http;
|
|
2107
|
+
#ws = null;
|
|
2108
|
+
#nl;
|
|
2109
|
+
#admin;
|
|
2110
|
+
#wsEndpoint;
|
|
2111
|
+
#wsToken;
|
|
2112
|
+
#wsGetToken;
|
|
2113
|
+
#wsEncoding;
|
|
2114
|
+
#reconnectOpts;
|
|
2115
|
+
#overloadResubscribeOpts;
|
|
2116
|
+
#webSocketImpl;
|
|
2117
|
+
#schemaCache = null;
|
|
2118
|
+
#schemaFetch = null;
|
|
2119
|
+
#driftCachedVersion = null;
|
|
2120
|
+
#closed = false;
|
|
2121
|
+
#wsReqSeq = 0;
|
|
2122
|
+
#cache;
|
|
2123
|
+
#onDiagnostics;
|
|
2124
|
+
constructor(opts) {
|
|
2125
|
+
if (opts.token !== void 0 && opts.getToken !== void 0) throw new Error("SubstrateClient: provide `token` OR `getToken`, not both");
|
|
2126
|
+
this.#http = new HttpTransport({
|
|
2127
|
+
endpoint: opts.endpoint,
|
|
2128
|
+
...opts.token !== void 0 ? { token: opts.token } : {},
|
|
2129
|
+
...opts.getToken !== void 0 ? { getToken: opts.getToken } : {},
|
|
2130
|
+
...opts.fetch !== void 0 ? { fetch: opts.fetch } : {}
|
|
2131
|
+
});
|
|
2132
|
+
this.#wsEndpoint = `${opts.endpoint.replace(/^http/, "ws").replace(/\/+$/, "")}/substrate/v1/ws`;
|
|
2133
|
+
this.#wsToken = opts.token;
|
|
2134
|
+
this.#wsGetToken = opts.getToken;
|
|
2135
|
+
this.#wsEncoding = opts.wsEncoding ?? "json";
|
|
2136
|
+
this.#reconnectOpts = opts.reconnect;
|
|
2137
|
+
this.#overloadResubscribeOpts = opts.overloadResubscribe;
|
|
2138
|
+
this.#webSocketImpl = opts.webSocket;
|
|
2139
|
+
this.#onDiagnostics = opts.onDiagnostics ?? createDefaultDiagnosticsSink();
|
|
2140
|
+
this.#cache = new CacheStore({ idleGcMs: 5e3 });
|
|
2141
|
+
}
|
|
2142
|
+
/** Natural-language ask (SSE or JSON) and the served namespace pack. Requires the substrate-nl plugin. */
|
|
2143
|
+
get nl() {
|
|
2144
|
+
this.#nl ??= createNlApi(this.#http);
|
|
2145
|
+
return this.#nl;
|
|
2146
|
+
}
|
|
2147
|
+
/** The admin-gated routes. Needs an identity whose grant confers `admin`. */
|
|
2148
|
+
get admin() {
|
|
2149
|
+
this.#admin ??= createAdminApi(this.#http);
|
|
2150
|
+
return this.#admin;
|
|
2151
|
+
}
|
|
2152
|
+
#ensureOpen() {
|
|
2153
|
+
if (this.#closed) throw new Error("SubstrateClient: already closed");
|
|
2154
|
+
}
|
|
2155
|
+
async federatedSchema() {
|
|
2156
|
+
this.#ensureOpen();
|
|
2157
|
+
if (this.#schemaCache !== null) return this.#schemaCache;
|
|
2158
|
+
if (this.#schemaFetch === null) this.#schemaFetch = this.#http.federatedSchema().then((schema) => {
|
|
2159
|
+
this.#schemaCache = schema;
|
|
2160
|
+
this.#schemaFetch = null;
|
|
2161
|
+
return schema;
|
|
2162
|
+
}, (err) => {
|
|
2163
|
+
this.#schemaFetch = null;
|
|
2164
|
+
throw err;
|
|
2165
|
+
});
|
|
2166
|
+
return this.#schemaFetch;
|
|
2167
|
+
}
|
|
2168
|
+
async query(frame, opts = {}) {
|
|
2169
|
+
this.#ensureOpen();
|
|
2170
|
+
await this.federatedSchema();
|
|
2171
|
+
const wire = opts.wire ?? "json";
|
|
2172
|
+
const raw = await this.#http.query(frame, {
|
|
2173
|
+
wire,
|
|
2174
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {},
|
|
2175
|
+
...opts.headers !== void 0 ? { headers: opts.headers } : {}
|
|
2176
|
+
});
|
|
2177
|
+
return this.#decode(raw, frame, wire);
|
|
2178
|
+
}
|
|
2179
|
+
async mutate(frame, opts = {}) {
|
|
2180
|
+
this.#ensureOpen();
|
|
2181
|
+
await this.federatedSchema();
|
|
2182
|
+
const wire = opts.wire ?? "json";
|
|
2183
|
+
const raw = await this.#http.mutate(frame, {
|
|
2184
|
+
wire,
|
|
2185
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {},
|
|
2186
|
+
...opts.headers !== void 0 ? { headers: opts.headers } : {}
|
|
2187
|
+
});
|
|
2188
|
+
return this.#decode(raw, frame, wire);
|
|
2189
|
+
}
|
|
2190
|
+
subscribe(frame, _opts = {}) {
|
|
2191
|
+
this.#ensureOpen();
|
|
2192
|
+
const req = this.#frameToWsRequest(frame);
|
|
2193
|
+
const inner = this.#getWs().subscribe(req);
|
|
2194
|
+
return this.#wsEncoding === "pack" ? this.#wrapPackDecode(inner, req.frame) : inner;
|
|
2195
|
+
}
|
|
2196
|
+
stream(frame, _opts = {}) {
|
|
2197
|
+
this.#ensureOpen();
|
|
2198
|
+
const req = this.#frameToWsRequest(frame);
|
|
2199
|
+
const inner = this.#getWs().stream(req);
|
|
2200
|
+
return this.#wsEncoding === "pack" ? this.#wrapPackDecode(inner, req.frame) : inner;
|
|
2201
|
+
}
|
|
2202
|
+
/**
|
|
2203
|
+
* Live typed-row view over a single-key subscription. Subscribes under the
|
|
2204
|
+
* hood, folds snapshot/add/update/remove into the current row-set, and yields
|
|
2205
|
+
* the maintained `T[]` after each delta — hiding the raw `SubscribeEvent`
|
|
2206
|
+
* protocol. `id` is force-selected (via `augmentFramesWithId`) so
|
|
2207
|
+
* update/remove can correlate rows by id.
|
|
2208
|
+
*
|
|
2209
|
+
* Completes when the subscription ends; throws on an error frame — the same
|
|
2210
|
+
* contract as `subscribe`. Breaking the consuming `for await` cancels the
|
|
2211
|
+
* underlying WS subscription. Reconnect / overload-resubscribe are handled by
|
|
2212
|
+
* `subscribe`; each fresh snapshot atomically replaces the row-set.
|
|
2213
|
+
*
|
|
2214
|
+
* Single-qualified-key only: multi-key frames throw; use `subscribe` for
|
|
2215
|
+
* those or for raw events.
|
|
2216
|
+
*/
|
|
2217
|
+
watch(frame) {
|
|
2218
|
+
this.#ensureOpen();
|
|
2219
|
+
const qualifiedKey = assertSingleKey(frame);
|
|
2220
|
+
return watchRows(this.subscribe(augmentFramesWithId(frame)), qualifiedKey);
|
|
2221
|
+
}
|
|
2222
|
+
/**
|
|
2223
|
+
* @internal — not part of the stable public surface.
|
|
2224
|
+
*/
|
|
2225
|
+
get cache() {
|
|
2226
|
+
return this.#cache;
|
|
2227
|
+
}
|
|
2228
|
+
invalidate(keyPrefix) {
|
|
2229
|
+
this.#ensureOpen();
|
|
2230
|
+
this.#cache.invalidate(keyPrefix);
|
|
2231
|
+
}
|
|
2232
|
+
/** Runtime metrics: op totals, per-key latency, process health, slowest requests. Needs `read`. */
|
|
2233
|
+
async metrics(opts = {}) {
|
|
2234
|
+
this.#ensureOpen();
|
|
2235
|
+
return await (await this.#http.raw("/substrate/v1/metrics", {
|
|
2236
|
+
method: "GET",
|
|
2237
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
2238
|
+
})).json();
|
|
2239
|
+
}
|
|
2240
|
+
/** The recent error log. Needs `admin`. */
|
|
2241
|
+
async errors(opts = {}) {
|
|
2242
|
+
this.#ensureOpen();
|
|
2243
|
+
return await (await this.#http.raw("/substrate/v1/errors", {
|
|
2244
|
+
method: "GET",
|
|
2245
|
+
...opts.signal !== void 0 ? { signal: opts.signal } : {}
|
|
2246
|
+
})).json();
|
|
2247
|
+
}
|
|
2248
|
+
async close() {
|
|
2249
|
+
if (this.#closed) return;
|
|
2250
|
+
this.#closed = true;
|
|
2251
|
+
if (this.#ws !== null) {
|
|
2252
|
+
await this.#ws.close();
|
|
2253
|
+
this.#ws = null;
|
|
2254
|
+
}
|
|
2255
|
+
}
|
|
2256
|
+
#getWs() {
|
|
2257
|
+
if (this.#ws === null) this.#ws = new WsTransport({
|
|
2258
|
+
endpoint: this.#wsEndpoint,
|
|
2259
|
+
encoding: this.#wsEncoding,
|
|
2260
|
+
...this.#wsToken !== void 0 ? { token: this.#wsToken } : {},
|
|
2261
|
+
...this.#wsGetToken !== void 0 ? { getToken: this.#wsGetToken } : {},
|
|
2262
|
+
...this.#reconnectOpts !== void 0 ? { reconnect: this.#reconnectOpts } : {},
|
|
2263
|
+
...this.#overloadResubscribeOpts !== void 0 ? { overloadResubscribe: this.#overloadResubscribeOpts } : {},
|
|
2264
|
+
...this.#webSocketImpl !== void 0 ? { webSocket: this.#webSocketImpl } : {}
|
|
2265
|
+
});
|
|
2266
|
+
return this.#ws;
|
|
2267
|
+
}
|
|
2268
|
+
async #refetchSchema() {
|
|
2269
|
+
const schema = await this.#http.federatedSchema();
|
|
2270
|
+
this.#schemaCache = schema;
|
|
2271
|
+
}
|
|
2272
|
+
async #decode(raw, frame, wire) {
|
|
2273
|
+
let env;
|
|
2274
|
+
if (wire === "pack" && isPackMarker(raw)) {
|
|
2275
|
+
const schema = this.#schemaCache ?? {};
|
|
2276
|
+
const marker = raw;
|
|
2277
|
+
const ctx = this.#buildDecodeCtx(frame, schema);
|
|
2278
|
+
env = decodeEnvelope(marker.__packBytes, ctx);
|
|
2279
|
+
} else env = decodeJsonEnvelope(raw);
|
|
2280
|
+
if (this.#driftCachedVersion === null) this.#driftCachedVersion = env.schemaVersion;
|
|
2281
|
+
else if (this.#driftCachedVersion !== env.schemaVersion) {
|
|
2282
|
+
await this.#refetchSchema();
|
|
2283
|
+
this.#driftCachedVersion = env.schemaVersion;
|
|
2284
|
+
}
|
|
2285
|
+
collectDiagnostics(env._diagnostics, this.#onDiagnostics);
|
|
2286
|
+
return env;
|
|
2287
|
+
}
|
|
2288
|
+
/**
|
|
2289
|
+
* Convert a `QualifiedFrame` into a `WsFrameRequest` for the WsTransport.
|
|
2290
|
+
*
|
|
2291
|
+
* The id MUST be unique per call: a key-derived id lets a re-subscribe race
|
|
2292
|
+
* the old sub's terminal frame and silently kill the new one. The type-key
|
|
2293
|
+
* prefix is only for readable logs. WsTransport reuses the id verbatim on
|
|
2294
|
+
* reconnect, so it is stable for the subscription's lifetime.
|
|
2295
|
+
*/
|
|
2296
|
+
#frameToWsRequest(frame) {
|
|
2297
|
+
this.#wsReqSeq += 1;
|
|
2298
|
+
const id = `${Object.keys(frame).sort().join("|")}#${this.#wsReqSeq}`;
|
|
2299
|
+
const wsFrame = {};
|
|
2300
|
+
for (const [key, entry] of Object.entries(frame)) {
|
|
2301
|
+
const single = Array.isArray(entry) ? entry[0] : entry;
|
|
2302
|
+
wsFrame[key] = {
|
|
2303
|
+
params: single?.params ?? {},
|
|
2304
|
+
fields: single?.fields ?? {}
|
|
2305
|
+
};
|
|
2306
|
+
}
|
|
2307
|
+
return {
|
|
2308
|
+
id,
|
|
2309
|
+
frame: wsFrame
|
|
2310
|
+
};
|
|
2311
|
+
}
|
|
2312
|
+
/**
|
|
2313
|
+
* Wrap a WS event stream so each `data`-bearing frame (snapshot/add/update/
|
|
2314
|
+
* chunk) gets its positional tuple values reconstructed into named-object
|
|
2315
|
+
* rows using the cached federated schema. Errors from the inner stream
|
|
2316
|
+
* (transport drop, server error frame) propagate untouched.
|
|
2317
|
+
*
|
|
2318
|
+
* The decode plan is built once, after the schema resolves, and reused for
|
|
2319
|
+
* every frame of the subscription.
|
|
2320
|
+
*
|
|
2321
|
+
* Hand-rolled iterator, NOT a native async generator: the generator form
|
|
2322
|
+
* queues return() behind an in-flight next(), which on a quiet connection
|
|
2323
|
+
* never resolves, so close() would hang. return() here forwards immediately.
|
|
2324
|
+
*/
|
|
2325
|
+
#wrapPackDecode(inner, frameSpec) {
|
|
2326
|
+
const buildPlan = async () => {
|
|
2327
|
+
const schemas = await this.federatedSchema();
|
|
2328
|
+
return buildDecodePlan(frameSpec, schemas);
|
|
2329
|
+
};
|
|
2330
|
+
return { [Symbol.asyncIterator]: () => {
|
|
2331
|
+
const innerIt = inner[Symbol.asyncIterator]();
|
|
2332
|
+
let planPromise = null;
|
|
2333
|
+
return {
|
|
2334
|
+
async next() {
|
|
2335
|
+
planPromise ??= buildPlan();
|
|
2336
|
+
const plan = await planPromise;
|
|
2337
|
+
const result = await innerIt.next();
|
|
2338
|
+
if (!result.done) applyDecodePlanInPlace(result.value, plan);
|
|
2339
|
+
return result;
|
|
2340
|
+
},
|
|
2341
|
+
async return() {
|
|
2342
|
+
await innerIt.return?.();
|
|
2343
|
+
return {
|
|
2344
|
+
value: void 0,
|
|
2345
|
+
done: true
|
|
2346
|
+
};
|
|
2347
|
+
}
|
|
2348
|
+
};
|
|
2349
|
+
} };
|
|
2350
|
+
}
|
|
2351
|
+
#buildDecodeCtx(frame, schemas) {
|
|
2352
|
+
const fieldsByKey = {};
|
|
2353
|
+
const returnsByKey = {};
|
|
2354
|
+
const typeByKey = {};
|
|
2355
|
+
const currentNsByKey = {};
|
|
2356
|
+
for (const key of Object.keys(frame)) {
|
|
2357
|
+
const frameEntry = frame[key];
|
|
2358
|
+
const entry = Array.isArray(frameEntry) ? frameEntry[0] : frameEntry;
|
|
2359
|
+
const parsed = parseQualifiedKey(key);
|
|
2360
|
+
if (parsed === null) continue;
|
|
2361
|
+
const { ns, name } = parsed;
|
|
2362
|
+
currentNsByKey[key] = ns;
|
|
2363
|
+
typeByKey[key] = name;
|
|
2364
|
+
const nsSchema = schemas[ns];
|
|
2365
|
+
if (nsSchema !== void 0 && nsSchema.mutations[name] !== void 0) returnsByKey[key] = nsSchema.mutations[name].returns;
|
|
2366
|
+
else fieldsByKey[key] = entry?.fields ?? {};
|
|
2367
|
+
}
|
|
2368
|
+
return {
|
|
2369
|
+
fieldsByKey,
|
|
2370
|
+
returnsByKey,
|
|
2371
|
+
typeByKey,
|
|
2372
|
+
schemas,
|
|
2373
|
+
currentNsByKey
|
|
2374
|
+
};
|
|
2375
|
+
}
|
|
2376
|
+
};
|
|
2377
|
+
|
|
2378
|
+
//#endregion
|
|
2379
|
+
//#region ../../packages/substrate-client/src/token-target.ts
|
|
2380
|
+
/**
|
|
2381
|
+
* Where a freshly minted credential may be sent: an https origin, or plain
|
|
2382
|
+
* http only to a loopback host, where nothing on the network can read it.
|
|
2383
|
+
*/
|
|
2384
|
+
const LOOPBACK = /^(localhost|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[::1\])$/;
|
|
2385
|
+
/**
|
|
2386
|
+
* @returns the origin of `baseUrl`, which a token for it names as its `aud`.
|
|
2387
|
+
* @throws Error when `baseUrl` is not a URL, or is plain http to a non-loopback host.
|
|
2388
|
+
*/
|
|
2389
|
+
function tokenAudience(baseUrl) {
|
|
2390
|
+
let url;
|
|
2391
|
+
try {
|
|
2392
|
+
url = new URL(baseUrl);
|
|
2393
|
+
} catch {
|
|
2394
|
+
throw new Error(`'${baseUrl}' is not a URL`);
|
|
2395
|
+
}
|
|
2396
|
+
if (url.protocol === "https:" || url.protocol === "http:" && LOOPBACK.test(url.hostname)) return url.origin;
|
|
2397
|
+
throw new Error(`refusing to send a credential to ${url.origin}: use https, or plain http only to a loopback host`);
|
|
2398
|
+
}
|
|
2399
|
+
/** `fetchImpl` with redirects refused: a redirect would carry the credential to wherever it points. */
|
|
2400
|
+
function noRedirectFetch(fetchImpl = fetch) {
|
|
2401
|
+
return (input, init) => fetchImpl(input, {
|
|
2402
|
+
...init,
|
|
2403
|
+
redirect: "error"
|
|
2404
|
+
});
|
|
2405
|
+
}
|
|
2406
|
+
|
|
2407
|
+
//#endregion
|
|
2408
|
+
export { reconcileIdentities as S, currentStep as _, createDefaultDiagnosticsSink as a, DIAGNOSE_CHECKS as b, AuthError as c, AdminBackfillError as d, BACKFILL_CHUNK as f, STEP_MARKS as g, SKIPPABLE_STEPS as h, collectDiagnostics as i, NetworkError as l, ONBOARD_STEPS as m, tokenAudience as n, reduceSubscribeRows as o, CURRENT_MARK as p, SubstrateClient as r, watchRows as s, noRedirectFetch as t, SubscribeError as u, planOnboarding as v, diagnose as x, requiredOutstanding as y };
|