@mnmal-ai/substrate 1.0.0-alpha.8 → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +32 -14
  2. package/dist/boot-store-BMQUbHKv.js +4086 -0
  3. package/dist/{runtime-metrics-DwpDJ8vz.d.ts → bridge-DnToJedN.d.ts} +2 -87
  4. package/dist/cli-DModIbnN.js +3390 -0
  5. package/dist/client.browser.js +2507 -0
  6. package/dist/client.d.ts +222 -171
  7. package/dist/client.js +6 -7
  8. package/dist/cluster-worker.js +0 -1
  9. package/dist/{content-type-C7T28xNb.js → content-type-wLljot5M.js} +0 -1
  10. package/dist/{env-utils-CGNazUNt.js → env-utils-s25Z1YSA.js} +0 -1
  11. package/dist/{errors-D4vKuwz8.d.ts → errors-Cmkp1qxf.d.ts} +44 -4
  12. package/dist/{fake-DUVtKVSE.js → fake-DdXtb-m8.js} +0 -1
  13. package/dist/{index-D7mSOFlM.d.ts → index-BI4KqFiR.d.ts} +7 -11
  14. package/dist/msgpackr-Dq18g6Ds.js +16 -0
  15. package/dist/node-version-BtK_Nq6z.js +32 -0
  16. package/dist/pack.d.ts +75 -11
  17. package/dist/pack.js +4 -4
  18. package/dist/{plugin-B3NxUCVn.js → plugin-CEOhrEme.js} +149 -6
  19. package/dist/proposals-bootstrap.js +6 -5
  20. package/dist/proposals.config.schema.json +5 -0
  21. package/dist/proposals.d.ts +17 -5
  22. package/dist/proposals.default-config.json +2 -1
  23. package/dist/proposals.js +2 -3
  24. package/dist/recall-bootstrap.js +5 -4
  25. package/dist/recall.config.schema.json +6 -0
  26. package/dist/recall.d.ts +27 -6
  27. package/dist/recall.js +2 -3
  28. package/dist/{repl-DeKzfvNV.js → repl-BvDZy-Ut.js} +52 -26
  29. package/dist/{row-ByLFE2Wx.d.ts → row-D0If4qif.d.ts} +92 -12
  30. package/dist/run-BT123RV1.js +2443 -0
  31. package/dist/{plugin-t2g2wX0b.d.ts → schema-aIkY8sR3.d.ts} +1293 -63
  32. package/dist/{script-C6DSa_Na.js → script-ByQ9pzhC.js} +54 -26
  33. package/dist/script-runner.js +78 -0
  34. package/dist/sdk.d.ts +236 -38
  35. package/dist/sdk.js +5 -110
  36. package/dist/semver-D_zdq0hi.js +17 -0
  37. package/dist/src-BMD2OE--.js +8289 -0
  38. package/dist/{src-BLgbLq2k.js → src-B_kHkbsr.js} +780 -330
  39. package/dist/{src-DjIuRjzF.js → src-CKSJ13p8.js} +10231 -4237
  40. package/dist/{src-CkZw6xVD.js → src-CW7eRDss.js} +188 -87
  41. package/dist/{row-DZ0Fnpc6.js → src-DmiUWOLp.js} +2 -1
  42. package/dist/{src-DCy7Iy2l.js → src-DmjwFMu8.js} +900 -77
  43. package/dist/{src-DiNTSaFk.js → src-FXO5JPyk.js} +686 -856
  44. package/dist/substrate-admin.js +17 -782
  45. package/dist/substrate.js +4 -5206
  46. package/dist/testing.d.ts +473 -96
  47. package/dist/testing.js +19 -165
  48. package/dist/{ws-C72iVS5T.d.ts → ws-DW8ng02H.d.ts} +4 -5
  49. package/package.json +26 -26
  50. package/dist/dataset-jZS_4ci4.js +0 -1535
  51. package/dist/pg-edges-store-KH_FQCxx.js +0 -381
  52. package/dist/schema-g4FQLr0V.d.ts +0 -433
  53. package/dist/src-BD27zeGF.js +0 -2339
@@ -1,10 +1,315 @@
1
- import { createRequire as __binCreateRequire } from 'node:module'; const require = __binCreateRequire(import.meta.url);
2
- import { c as makeTokenProvider, i as DEFAULT_CAPABILITIES, n as trimTrailingSlashes } from "./env-utils-CGNazUNt.js";
3
- import { D as isActiveAdminKeyRow, O as capabilitiesFor, T as SYSTEM_NAMESPACE } from "./row-DZ0Fnpc6.js";
4
- import { _ as decodeEnvelope, a as buildDecodePlan, g as SchemaDriftError, i as applyDecodePlanInPlace, o as decodeWsEnvelope, s as encodeWsFrame, t as WS_SUBPROTOCOL_SUBSTRATE_PACK, x as parseQualifiedKey } from "./src-BLgbLq2k.js";
1
+ import { c as makeTokenProvider, i as DEFAULT_CAPABILITIES, n as trimTrailingSlashes } from "./env-utils-s25Z1YSA.js";
2
+ import { D as isActiveAdminKeyRow, O as capabilitiesFor, T as SYSTEM_NAMESPACE } from "./src-DmiUWOLp.js";
3
+ import { N as parseQualifiedKey, S as decodeEnvelope, d as applyDecodePlanInPlace, f as buildDecodePlan, i as FRAMES_PACK_MIME, n as DEFAULT_STREAM_IDLE_MS, p as decodeWsEnvelope, r as FRAMES_JSON_MIME, s as decodeStreamFrames, u as withIdleTimeout, x as SchemaDriftError, y as mutationReturns } from "./src-B_kHkbsr.js";
4
+ import http2 from "node:http2";
5
5
  import { signal } from "@preact/signals-core";
6
- import { WebSocket } from "ws";
7
6
 
7
+ //#region ../../packages/substrate-client/src/transport/h2-fetch.ts
8
+ /**
9
+ * A fetch-shaped function over `node:http2`: the transport seam's HTTP/2
10
+ * adapter for Node and Bun (Todo #1850, Decision #625).
11
+ *
12
+ * One `ClientHttp2Session` per origin, opened on first use and shared by every
13
+ * request to it; concurrent first calls share the pending connect. A session is
14
+ * dropped on GOAWAY, close or error, and the next request opens a new one. An
15
+ * idle session is unref'd, so a short-lived process exits without `close()`.
16
+ * `http:` origins use HTTP/2 with prior knowledge (h2c); `https:` origins verify
17
+ * the server against `ca`, or the process's default trust (which includes
18
+ * NODE_EXTRA_CA_CERTS). Certificate checks are never turned off.
19
+ *
20
+ * Imports node builtins only.
21
+ */
22
+ const DEFAULT_CONNECT_TIMEOUT_MS = 1e4;
23
+ /** Request headers HTTP/2 forbids (RFC 9113 §8.2.2); fetch callers may still set them. */
24
+ const CONNECTION_HEADERS = /* @__PURE__ */ new Set([
25
+ "connection",
26
+ "keep-alive",
27
+ "transfer-encoding",
28
+ "upgrade",
29
+ "proxy-connection",
30
+ "host"
31
+ ]);
32
+ function abortError(signal) {
33
+ const reason = signal.reason;
34
+ if (reason instanceof Error && reason.name === "AbortError") return reason;
35
+ return new DOMException("This operation was aborted", "AbortError");
36
+ }
37
+ function toHeaderRecord(init) {
38
+ const out = {};
39
+ new Headers(init).forEach((value, name) => {
40
+ if (!CONNECTION_HEADERS.has(name)) out[name] = value;
41
+ });
42
+ return out;
43
+ }
44
+ function toBodyBytes(body) {
45
+ if (body === void 0 || body === null) return void 0;
46
+ if (typeof body === "string" || body instanceof Uint8Array) return body;
47
+ if (body instanceof ArrayBuffer) return new Uint8Array(body);
48
+ if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
49
+ throw new TypeError("createH2Fetch: only string, ArrayBuffer and typed-array bodies are supported");
50
+ }
51
+ function createH2Fetch(opts = {}) {
52
+ const connectTimeoutMs = opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
53
+ const pool = /* @__PURE__ */ new Map();
54
+ /** Every session opened, connected or not, so close() can end them all. */
55
+ const sessions = /* @__PURE__ */ new Set();
56
+ function connect(origin) {
57
+ const existing = pool.get(origin);
58
+ if (existing !== void 0) return existing;
59
+ const pending = new Promise((resolve, reject) => {
60
+ const session = http2.connect(origin, origin.startsWith("https:") && opts.ca !== void 0 ? { ca: opts.ca } : {});
61
+ sessions.add(session);
62
+ session.once("close", () => sessions.delete(session));
63
+ const pooled = {
64
+ session,
65
+ holds: 0
66
+ };
67
+ let connected = false;
68
+ const drop = () => {
69
+ if (pool.get(origin) === pending) pool.delete(origin);
70
+ };
71
+ const fail = (err) => {
72
+ clearTimeout(timer);
73
+ drop();
74
+ if (!connected) reject(err);
75
+ };
76
+ const timer = setTimeout(() => {
77
+ session.destroy();
78
+ fail(/* @__PURE__ */ new Error(`connect to ${origin} timed out after ${connectTimeoutMs} ms`));
79
+ }, connectTimeoutMs);
80
+ timer.unref();
81
+ session.once("connect", () => {
82
+ clearTimeout(timer);
83
+ connected = true;
84
+ session.unref();
85
+ resolve(pooled);
86
+ });
87
+ session.on("error", fail);
88
+ session.on("goaway", drop);
89
+ session.on("close", () => fail(/* @__PURE__ */ new Error(`connection to ${origin} closed before it opened`)));
90
+ });
91
+ pending.catch(() => {});
92
+ pool.set(origin, pending);
93
+ return pending;
94
+ }
95
+ /** Forget `pooled` if it is still the origin's session, so the next request opens a new one. */
96
+ function forget(origin, pooled) {
97
+ const current = pool.get(origin);
98
+ if (current === void 0) return;
99
+ current.then((p) => {
100
+ if (p === pooled && pool.get(origin) === current) pool.delete(origin);
101
+ }, () => {});
102
+ }
103
+ const fetchH2 = async (input, init = {}) => {
104
+ const signal = init.signal ?? void 0;
105
+ if (signal?.aborted) throw abortError(signal);
106
+ const url = new URL(input);
107
+ const body = toBodyBytes(init.body);
108
+ const headers = {
109
+ ...toHeaderRecord(init.headers),
110
+ ":method": (init.method ?? "GET").toUpperCase(),
111
+ ":path": `${url.pathname}${url.search}`
112
+ };
113
+ for (let attempt = 0;; attempt++) {
114
+ const pooled = await untilAborted(connect(url.origin), signal);
115
+ const outcome = await send(pooled, headers, body, init, signal);
116
+ if (outcome.kind === "response") return outcome.response;
117
+ forget(url.origin, pooled);
118
+ if (outcome.kind === "retry" && attempt === 0) continue;
119
+ throw outcome.error;
120
+ }
121
+ };
122
+ return Object.assign(fetchH2, { async close() {
123
+ pool.clear();
124
+ await Promise.all([...sessions].map((session) => {
125
+ if (session.connecting) {
126
+ session.destroy();
127
+ return;
128
+ }
129
+ return session.closed ? void 0 : new Promise((r) => session.close(() => r()));
130
+ }));
131
+ } });
132
+ }
133
+ /** Keep the session ref'd while anyone waits on it; an idle or unread one lets the process exit. */
134
+ function hold(p) {
135
+ if (p.holds++ === 0) p.session.ref();
136
+ }
137
+ function release(p) {
138
+ if (--p.holds === 0 && !p.session.destroyed) p.session.unref();
139
+ }
140
+ function untilAborted(p, signal) {
141
+ if (signal === void 0) return p;
142
+ return new Promise((resolve, reject) => {
143
+ const onAbort = () => reject(abortError(signal));
144
+ signal.addEventListener("abort", onAbort, { once: true });
145
+ p.then((v) => {
146
+ signal.removeEventListener("abort", onAbort);
147
+ resolve(v);
148
+ }, (e) => {
149
+ signal.removeEventListener("abort", onAbort);
150
+ reject(e);
151
+ });
152
+ });
153
+ }
154
+ const RETRYABLE_CODES = /* @__PURE__ */ new Set(["ERR_HTTP2_GOAWAY_SESSION", "ERR_HTTP2_INVALID_SESSION"]);
155
+ function send(pooled, headers, body, init, signal) {
156
+ return new Promise((resolve) => {
157
+ let stream;
158
+ try {
159
+ stream = pooled.session.request(headers, { endStream: body === void 0 });
160
+ } catch (err) {
161
+ const code = err.code;
162
+ resolve({
163
+ kind: code !== void 0 && RETRYABLE_CODES.has(code) ? "retry" : "error",
164
+ error: err
165
+ });
166
+ return;
167
+ }
168
+ hold(pooled);
169
+ let settled = false;
170
+ const settle = (o) => {
171
+ if (settled) return;
172
+ settled = true;
173
+ release(pooled);
174
+ resolve(o);
175
+ };
176
+ const onAbort = () => {
177
+ stream.close(http2.constants.NGHTTP2_CANCEL);
178
+ settle({
179
+ kind: "error",
180
+ error: abortError(signal)
181
+ });
182
+ };
183
+ signal?.addEventListener("abort", onAbort, { once: true });
184
+ stream.once("close", () => {
185
+ signal?.removeEventListener("abort", onAbort);
186
+ const refused = stream.rstCode === http2.constants.NGHTTP2_REFUSED_STREAM;
187
+ settle({
188
+ kind: refused ? "retry" : "error",
189
+ error: /* @__PURE__ */ new Error(`stream closed before a response (code ${stream.rstCode})`)
190
+ });
191
+ });
192
+ stream.once("error", (err) => settle({
193
+ kind: "error",
194
+ error: err
195
+ }));
196
+ stream.once("response", (h) => {
197
+ const status = Number(h[":status"]);
198
+ const responseHeaders = new Headers();
199
+ for (const [name, value] of Object.entries(h)) {
200
+ if (name.startsWith(":") || value === void 0) continue;
201
+ for (const v of Array.isArray(value) ? value : [String(value)]) responseHeaders.append(name, v);
202
+ }
203
+ if (status >= 300 && status < 400 && responseHeaders.has("location") && init.redirect !== "manual") {
204
+ stream.close(http2.constants.NGHTTP2_CANCEL);
205
+ settle({
206
+ kind: "error",
207
+ error: /* @__PURE__ */ new TypeError(`redirect refused: ${status} to ${responseHeaders.get("location")}`)
208
+ });
209
+ return;
210
+ }
211
+ const nullBody = status === 204 || status === 205 || status === 304 || headers[":method"] === "HEAD";
212
+ let response;
213
+ try {
214
+ response = new Response(nullBody ? null : webBody(stream, pooled, signal), {
215
+ status,
216
+ headers: responseHeaders
217
+ });
218
+ } catch (err) {
219
+ stream.close(http2.constants.NGHTTP2_CANCEL);
220
+ settle({
221
+ kind: "error",
222
+ error: err
223
+ });
224
+ return;
225
+ }
226
+ if (nullBody) stream.resume();
227
+ settle({
228
+ kind: "response",
229
+ response
230
+ });
231
+ });
232
+ if (body !== void 0) stream.end(body);
233
+ });
234
+ }
235
+ /**
236
+ * The response body as a web stream with backpressure. The session stays ref'd
237
+ * only while the reader is waiting for data, so a body nobody reads lets the
238
+ * process exit. An unread body still holds its HTTP/2 stream open until the
239
+ * server finishes it: read or cancel every body. Cancelling resets the stream.
240
+ * Built by hand rather than with `Readable.toWeb`, which aborts h2 bodies early under Bun.
241
+ */
242
+ function webBody(stream, pooled, signal) {
243
+ let done = false;
244
+ let holding = false;
245
+ const setHold = (on) => {
246
+ if (on === holding) return;
247
+ holding = on;
248
+ if (on) hold(pooled);
249
+ else release(pooled);
250
+ };
251
+ const finish = () => {
252
+ done = true;
253
+ setHold(false);
254
+ };
255
+ return new ReadableStream({
256
+ start(controller) {
257
+ stream.on("data", (chunk) => {
258
+ if (done) return;
259
+ controller.enqueue(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength));
260
+ if ((controller.desiredSize ?? 1) <= 0) {
261
+ stream.pause();
262
+ setHold(false);
263
+ }
264
+ });
265
+ stream.once("end", () => {
266
+ if (done) return;
267
+ finish();
268
+ if (signal?.aborted) controller.error(abortError(signal));
269
+ else controller.close();
270
+ });
271
+ stream.once("error", (err) => {
272
+ if (done) return;
273
+ finish();
274
+ controller.error(signal?.aborted ? abortError(signal) : err);
275
+ });
276
+ stream.once("close", () => {
277
+ if (done) return;
278
+ finish();
279
+ controller.error(signal?.aborted ? abortError(signal) : /* @__PURE__ */ new Error(`stream closed before its end (code ${stream.rstCode})`));
280
+ });
281
+ },
282
+ pull() {
283
+ if (done) return;
284
+ setHold(true);
285
+ stream.resume();
286
+ },
287
+ cancel() {
288
+ finish();
289
+ stream.close(http2.constants.NGHTTP2_CANCEL);
290
+ }
291
+ });
292
+ }
293
+
294
+ //#endregion
295
+ //#region ../../packages/substrate-client/src/transport/platform-fetch.ts
296
+ /**
297
+ * The default behind `substrateFetch` in Node and Bun: one process-wide HTTP/2
298
+ * session pool, opened on first use. Browser builds swap in
299
+ * `platform-fetch.browser.ts`.
300
+ */
301
+ let pool;
302
+ const platformFetch = (input, init) => {
303
+ pool ??= createH2Fetch();
304
+ return pool(input, init);
305
+ };
306
+
307
+ //#endregion
308
+ //#region ../../packages/substrate-client/src/transport/default-fetch.ts
309
+ let current = platformFetch;
310
+ const substrateFetch = (input, init) => current(input, init);
311
+
312
+ //#endregion
8
313
  //#region ../../packages/substrate-client/src/admin/diagnose.ts
9
314
  /**
10
315
  * The library behind `substrate-admin doctor` and substrate-tui's `/doctor` — diagnoses
@@ -27,6 +332,7 @@ const CHECK_ADMIN = "admin-capability";
27
332
  const CHECK_FLOOR = "admin-floor";
28
333
  const CHECK_NAMESPACES = "namespaces";
29
334
  const CHECK_DIR = "key-directory";
335
+ const CHECK_STORAGE = "storage";
30
336
  /** Every check downstream of a failure, so a skip is never silent. */
31
337
  const DOWNSTREAM = {
32
338
  [CHECK_REACHABLE]: [
@@ -36,21 +342,28 @@ const DOWNSTREAM = {
36
342
  CHECK_ADMIN,
37
343
  CHECK_FLOOR,
38
344
  CHECK_NAMESPACES,
39
- CHECK_DIR
345
+ CHECK_DIR,
346
+ CHECK_STORAGE
40
347
  ],
41
348
  [CHECK_CREDENTIAL]: [
42
349
  CHECK_IDENTITY,
43
350
  CHECK_ADMIN,
44
351
  CHECK_FLOOR,
45
352
  CHECK_NAMESPACES,
46
- CHECK_DIR
353
+ CHECK_DIR,
354
+ CHECK_STORAGE
47
355
  ],
48
356
  [CHECK_IDENTITY]: [
49
357
  CHECK_ADMIN,
50
358
  CHECK_FLOOR,
51
- CHECK_DIR
359
+ CHECK_DIR,
360
+ CHECK_STORAGE
361
+ ],
362
+ [CHECK_ADMIN]: [
363
+ CHECK_FLOOR,
364
+ CHECK_DIR,
365
+ CHECK_STORAGE
52
366
  ],
53
- [CHECK_ADMIN]: [CHECK_FLOOR, CHECK_DIR],
54
367
  [CHECK_FLOOR]: [CHECK_DIR]
55
368
  };
56
369
  var Checks = class {
@@ -276,7 +589,8 @@ const DIAGNOSE_CHECKS = [
276
589
  CHECK_ADMIN,
277
590
  CHECK_FLOOR,
278
591
  CHECK_NAMESPACES,
279
- CHECK_DIR
592
+ CHECK_DIR,
593
+ CHECK_STORAGE
280
594
  ];
281
595
  /**
282
596
  * Runs every check against `opts.baseUrl`, in dependency order. A failure
@@ -284,7 +598,7 @@ const DIAGNOSE_CHECKS = [
284
598
  */
285
599
  async function diagnose(opts) {
286
600
  const checks = new Checks();
287
- const fetchImpl = opts.fetch ?? fetch;
601
+ const fetchImpl = opts.fetch ?? substrateFetch;
288
602
  const adminCapability = opts.adminCapability ?? "admin";
289
603
  const baseUrl = trimTrailingSlashes(opts.baseUrl);
290
604
  let identityId = null;
@@ -350,7 +664,8 @@ async function diagnose(opts) {
350
664
  for (const name of [
351
665
  CHECK_ADMIN,
352
666
  CHECK_FLOOR,
353
- CHECK_DIR
667
+ CHECK_DIR,
668
+ CHECK_STORAGE
354
669
  ]) checks.skip(name, "not asked — this identity was not expected to be an admin");
355
670
  return done();
356
671
  }
@@ -364,6 +679,16 @@ async function diagnose(opts) {
364
679
  return done();
365
680
  }
366
681
  checks.ok(CHECK_ADMIN, `the grant confers '${adminCapability}' on ${SYSTEM_NAMESPACE} — this identity can administer`);
682
+ const config = await getJson(`${baseUrl}/substrate/v1/config`, fetchImpl, { authorization });
683
+ const storage = "error" in config ? void 0 : config.body.storage;
684
+ if ("error" in config || config.status !== 200) checks.skip(CHECK_STORAGE, `not asked — /substrate/v1/config ${"error" in config ? `could not be reached: ${config.error}` : `answered HTTP ${config.status}`}`);
685
+ else if (storage === void 0) checks.skip(CHECK_STORAGE, "not asked — the server reports no storage section (memory store)");
686
+ else {
687
+ const warnings = Array.isArray(storage.warnings) ? storage.warnings.map(String) : [];
688
+ const info = Array.isArray(storage.info) ? storage.info.map((l) => `\n${String(l)}`).join("") : "";
689
+ if (warnings.length === 0) checks.ok(CHECK_STORAGE, `${String(storage.layout)} layout, no warnings${info}`);
690
+ else checks.no(CHECK_STORAGE, `${String(storage.layout)} layout, ${warnings.length} warning(s):\n${warnings.join("\n")}${info}`, "Each warning names what to move or drop; indexes are never dropped automatically.");
691
+ }
367
692
  const floor = await listLiveKeys(baseUrl, authorization, fetchImpl);
368
693
  if ("error" in floor) {
369
694
  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`.");
@@ -715,7 +1040,10 @@ function createAdminApi(t) {
715
1040
  const out = [];
716
1041
  let cursor;
717
1042
  for (;;) {
718
- const qs = cursor === void 0 ? "" : `?cursor=${encodeURIComponent(cursor)}`;
1043
+ const q = new URLSearchParams();
1044
+ if (opts.filter === "all") q.set("filter", "all");
1045
+ if (cursor !== void 0) q.set("cursor", cursor);
1046
+ const qs = q.toString() === "" ? "" : `?${q.toString()}`;
719
1047
  const page = await (await t.raw(`/substrate/v1/_system/keys${qs}`, {
720
1048
  method: "GET",
721
1049
  ...opts.signal !== void 0 ? { signal: opts.signal } : {}
@@ -903,7 +1231,7 @@ const SURVIVABLE_END_REASONS = /* @__PURE__ */ new Set([
903
1231
  * A delta that does not change the set (e.g. an `update` whose row has no id) is
904
1232
  * not re-yielded. Cancellation: breaking the consuming `for await` (or calling
905
1233
  * `.return()`) propagates to the source iterable's `return()` through the inner
906
- * `for await`, cancelling the underlying WS subscription.
1234
+ * `for await`, cancelling the underlying subscription.
907
1235
  */
908
1236
  async function* watchRows(events, qualifiedKey) {
909
1237
  let rows = [];
@@ -1050,7 +1378,11 @@ var CacheStore = class {
1050
1378
 
1051
1379
  //#endregion
1052
1380
  //#region ../../packages/substrate-client/src/diagnostics.ts
1053
- const HANDLED = /* @__PURE__ */ new Set(["unknownProjectionFields", "filterValidationSkipped"]);
1381
+ const HANDLED = /* @__PURE__ */ new Set([
1382
+ "unknownProjectionFields",
1383
+ "filterValidationSkipped",
1384
+ "plan"
1385
+ ]);
1054
1386
  /**
1055
1387
  * Reduce one envelope entry to a diagnostic, or `undefined` when it holds
1056
1388
  * nothing worth reporting — an entry present but empty, or one whose only
@@ -1116,68 +1448,281 @@ function createDefaultDiagnosticsSink() {
1116
1448
  seen.add(dedupeKey);
1117
1449
  const parts = [];
1118
1450
  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.`);
1119
- 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.`);
1451
+ if (filterValidationSkipped !== void 0) parts.push(`the where-clause was not schema-validated (${filterValidationSkipped}), so its operators and operands were never checked against the field kinds. Results are still correct — the substrate refuses a predicate it cannot honour — but a malformed filter fails later and less clearly.`);
1120
1452
  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.`);
1121
1453
  console.warn(`[substrate-client] ${opKey}: ${parts.join(" Also, ")} (Pass \`onDiagnostics\` to SubstrateClient to route this elsewhere.)`);
1122
1454
  };
1123
1455
  }
1124
1456
 
1125
1457
  //#endregion
1126
- //#region ../../packages/substrate-client/src/transport/sse.ts
1127
- /** Parse one SSE block; null when it carries no data (comment-only or empty). Throws on an in-band `error` event. */
1128
- function parseBlock(block) {
1129
- let event = "message";
1130
- const data = [];
1131
- for (const line of block.split("\n")) {
1132
- if (line.startsWith(":")) continue;
1133
- if (line.startsWith("event:")) event = line.slice(6).trim();
1134
- else if (line.startsWith("data:")) data.push(line.slice(5).startsWith(" ") ? line.slice(6) : line.slice(5));
1135
- }
1136
- if (data.length === 0) return null;
1137
- const raw = data.join("\n");
1138
- let parsed;
1139
- try {
1140
- parsed = JSON.parse(raw);
1141
- } catch (err) {
1142
- throw new NetworkError(`malformed SSE data for event '${event}': ${raw.slice(0, 100)}`, err);
1458
+ //#region ../../packages/substrate-client/src/reconnect.ts
1459
+ var ReconnectScheduler = class {
1460
+ #base;
1461
+ #max;
1462
+ #jitter;
1463
+ #attempt = 0;
1464
+ constructor(opts) {
1465
+ this.#base = opts.baseDelayMs;
1466
+ this.#max = opts.maxDelayMs;
1467
+ this.#jitter = opts.jitter;
1143
1468
  }
1144
- if (event === "error") {
1145
- const e = parsed;
1146
- throw new NetworkError(`${e.code ?? "error"}: ${e.message ?? ""}`, parsed);
1469
+ nextDelay() {
1470
+ const raw = Math.min(this.#base * 2 ** this.#attempt, this.#max);
1471
+ this.#attempt += 1;
1472
+ if (this.#jitter === 0) return raw;
1473
+ const spread = raw * this.#jitter;
1474
+ return raw + (Math.random() * 2 - 1) * spread;
1475
+ }
1476
+ reset() {
1477
+ this.#attempt = 0;
1478
+ }
1479
+ /**
1480
+ * Resolve after `nextDelay()` ms. Callers must use this serially — the
1481
+ * `#attempt` counter is shared across calls, so overlapping `schedule()`
1482
+ * invocations will produce incorrect delays. The stream reconnect loop awaits
1483
+ * each `schedule()` before firing the next attempt.
1484
+ */
1485
+ async schedule() {
1486
+ const d = this.nextDelay();
1487
+ await new Promise((resolve) => setTimeout(resolve, d));
1488
+ }
1489
+ };
1490
+
1491
+ //#endregion
1492
+ //#region ../../packages/substrate-client/src/transport/frame-event.ts
1493
+ /** Server response frames as the subscribe and stream iterables yield them. */
1494
+ const DEFAULT_RECONNECT = {
1495
+ baseDelayMs: 1e3,
1496
+ maxDelayMs: 3e4,
1497
+ jitter: .1
1498
+ };
1499
+ const DEFAULT_OVERLOAD_RESUBSCRIBE = {
1500
+ enabled: true,
1501
+ maxAttempts: 3,
1502
+ baseDelayMs: 1e3,
1503
+ maxDelayMs: 3e4,
1504
+ jitter: .1,
1505
+ healthyResetMs: 6e4
1506
+ };
1507
+ /** Convert a server frame to a SubscribeEvent, or null if unrecognised. */
1508
+ function msgToEvent(msg) {
1509
+ switch (msg.kind) {
1510
+ case "snapshot":
1511
+ case "add":
1512
+ case "update": return {
1513
+ kind: msg.kind,
1514
+ data: msg.data,
1515
+ ...msg.shapes !== void 0 ? { shapes: msg.shapes } : {}
1516
+ };
1517
+ case "chunk": return {
1518
+ kind: "chunk",
1519
+ data: msg.data,
1520
+ ...msg.shapes !== void 0 ? { shapes: msg.shapes } : {},
1521
+ ...msg.sequence !== void 0 ? { sequence: msg.sequence } : {}
1522
+ };
1523
+ case "remove": return {
1524
+ kind: "remove",
1525
+ removedId: msg.removedId ?? ""
1526
+ };
1527
+ case "end": return {
1528
+ kind: "end",
1529
+ ...msg.final !== void 0 ? { final: msg.final } : {},
1530
+ ...msg.reason !== void 0 ? { reason: msg.reason } : {}
1531
+ };
1532
+ case "error": {
1533
+ const first = (msg.errors ?? [{
1534
+ message: "unknown error",
1535
+ code: "unknown"
1536
+ }])[0] ?? {
1537
+ message: "unknown error",
1538
+ code: "unknown"
1539
+ };
1540
+ throw new SubscribeError(first.message, first.code ?? "unknown");
1541
+ }
1542
+ default: return null;
1147
1543
  }
1148
- return {
1149
- event,
1150
- data: parsed
1151
- };
1152
1544
  }
1153
- async function* readSse(body) {
1154
- const reader = body.getReader();
1155
- const decoder = new TextDecoder();
1156
- let buf = "";
1157
- try {
1158
- for (;;) {
1159
- const { value, done } = await reader.read();
1160
- if (done) break;
1161
- buf = (buf + decoder.decode(value, { stream: true })).replace(/\r\n/g, "\n");
1162
- let sep = buf.indexOf("\n\n");
1163
- while (sep >= 0) {
1164
- const block = buf.slice(0, sep);
1165
- buf = buf.slice(sep + 2);
1166
- sep = buf.indexOf("\n\n");
1167
- const evt = parseBlock(block);
1168
- if (evt !== null) yield evt;
1545
+
1546
+ //#endregion
1547
+ //#region ../../packages/substrate-client/src/transport/frames.ts
1548
+ /**
1549
+ * Subscribe and stream over length-prefixed frame streams: one POST per
1550
+ * subscription, its response body a sequence of frames (substrate-pack's
1551
+ * stream-frames codec). Each subscription owns its request, so cancelling one
1552
+ * aborts only that request.
1553
+ *
1554
+ * A subscription survives the following, re-subscribing for a fresh
1555
+ * snapshot: a dropped connection (after backoff), `end { server_restart }`
1556
+ * (at once), `subscription_overloaded` (after the overload delay, within its
1557
+ * budget) and a lapsed credential when `getToken` can mint a new one. A 401 or
1558
+ * 403 is terminal. A stream is never re-sent, since that would replay its chunks.
1559
+ */
1560
+ /** `NetworkError.code` when the server does not answer with frame streams. */
1561
+ const FRAMES_UNSUPPORTED = "frames_unsupported";
1562
+ /** `NetworkError.code` when a stream was cut short by a server restart. */
1563
+ const STREAM_INTERRUPTED = "stream_interrupted";
1564
+ const OVERLOADED = "subscription_overloaded";
1565
+ const SERVER_RESTART = "server_restart";
1566
+ const LAPSES = /* @__PURE__ */ new Set(["credential_expired", "credential_changed"]);
1567
+ function openFrameStream(http, path, frame, opts) {
1568
+ return { [Symbol.asyncIterator]: () => {
1569
+ const ctrl = new AbortController();
1570
+ const gen = run(http, path, frame, opts, opts.signal === void 0 ? ctrl.signal : anySignal([ctrl.signal, opts.signal]));
1571
+ return {
1572
+ next: () => gen.next(),
1573
+ return: async () => {
1574
+ ctrl.abort();
1575
+ await gen.return(void 0);
1576
+ return {
1577
+ value: void 0,
1578
+ done: true
1579
+ };
1169
1580
  }
1581
+ };
1582
+ } };
1583
+ }
1584
+ async function* run(http, path, frame, opts, signal) {
1585
+ const subscribe = path === "/substrate/v1/subscribe";
1586
+ const reconnect = {
1587
+ ...DEFAULT_RECONNECT,
1588
+ ...opts.reconnect
1589
+ };
1590
+ const backoff = new ReconnectScheduler(reconnect);
1591
+ const overload = {
1592
+ ...DEFAULT_OVERLOAD_RESUBSCRIBE,
1593
+ ...opts.overload
1594
+ };
1595
+ let overloadAttempts = 0;
1596
+ let lastOverloadAt = null;
1597
+ let opened = false;
1598
+ let busyRetries = 0;
1599
+ const accept = opts.wire === "pack" ? FRAMES_PACK_MIME : FRAMES_JSON_MIME;
1600
+ for (;;) {
1601
+ let body;
1602
+ try {
1603
+ const res = await http.raw(path, {
1604
+ method: "POST",
1605
+ body: frame,
1606
+ accept,
1607
+ signal
1608
+ });
1609
+ const type = res.headers.get("content-type") ?? "";
1610
+ if (!type.startsWith(accept)) {
1611
+ await res.body?.cancel();
1612
+ throw new NetworkError(`POST ${path} answered '${type}', not ${accept}: the server predates frame streams`, null, {
1613
+ status: res.status,
1614
+ code: FRAMES_UNSUPPORTED
1615
+ });
1616
+ }
1617
+ if (res.body === null) throw new NetworkError(`POST ${path}: response has no body`, null);
1618
+ body = res.body;
1619
+ } catch (err) {
1620
+ if (signal.aborted) return;
1621
+ if (!opened && isBusy(err) && busyRetries < BUSY_RETRIES) {
1622
+ busyRetries++;
1623
+ if (!await sleep(backoff.nextDelay(), signal)) return;
1624
+ continue;
1625
+ }
1626
+ if (err instanceof AuthError || !opened || !subscribe || refused(err)) throw err;
1627
+ if (!await sleep(backoff.nextDelay(), signal)) return;
1628
+ continue;
1170
1629
  }
1171
- buf += decoder.decode();
1172
- const tail = buf.replace(/\r\n?/g, "\n").trim();
1173
- if (tail !== "") {
1174
- const evt = parseBlock(tail);
1175
- if (evt !== null) yield evt;
1630
+ opened = true;
1631
+ const openedAt = Date.now();
1632
+ let next;
1633
+ try {
1634
+ const idleMs = opts.idleMs ?? 65e3;
1635
+ for await (const payload of decodeStreamFrames(idleMs > 0 ? withIdleTimeout(body, idleMs) : body)) {
1636
+ const msg = decodeFrame(payload, opts.wire);
1637
+ if (Date.now() - openedAt >= reconnect.maxDelayMs) backoff.reset();
1638
+ if (subscribe && msg.kind === "error" && msg.errors?.[0]?.code === OVERLOADED && overload.enabled) {
1639
+ const now = Date.now();
1640
+ if (lastOverloadAt !== null && now - lastOverloadAt > overload.healthyResetMs) overloadAttempts = 0;
1641
+ lastOverloadAt = now;
1642
+ if (overloadAttempts < overload.maxAttempts) {
1643
+ overloadAttempts += 1;
1644
+ next = { delayMs: jittered(overload, overloadAttempts) };
1645
+ break;
1646
+ }
1647
+ }
1648
+ if (!subscribe && msg.kind === "end" && msg.reason === SERVER_RESTART) throw new NetworkError(`POST ${path}: the server restarted mid-stream`, null, { code: STREAM_INTERRUPTED });
1649
+ const event = msgToEvent(msg);
1650
+ if (event === null) continue;
1651
+ yield event;
1652
+ if (msg.kind === "end") {
1653
+ next = subscribe && (msg.reason === SERVER_RESTART || msg.reason !== void 0 && LAPSES.has(msg.reason) && opts.canRefreshToken) ? { delayMs: 0 } : "stop";
1654
+ break;
1655
+ }
1656
+ }
1657
+ } catch (err) {
1658
+ if (signal.aborted) return;
1659
+ if (err instanceof SubscribeError || err instanceof NetworkError && err.code === "stream_interrupted") throw err;
1660
+ if (!subscribe) throw err instanceof NetworkError ? err : new NetworkError(`POST ${path}: the stream broke before its end frame`, err);
1661
+ }
1662
+ if (next === "stop") return;
1663
+ if (next === void 0) {
1664
+ if (signal.aborted) return;
1665
+ if (!subscribe) throw new NetworkError(`POST ${path}: stream ended without an end frame`, null);
1666
+ next = { delayMs: backoff.nextDelay() };
1667
+ }
1668
+ if (!await sleep(next.delayMs, signal)) return;
1669
+ }
1670
+ }
1671
+ /** Retries of a 429 before the first response, after which it surfaces. */
1672
+ const BUSY_RETRIES = 3;
1673
+ function isBusy(err) {
1674
+ return err instanceof NetworkError && err.status === 429;
1675
+ }
1676
+ /**
1677
+ * A refusal that retrying will not change: a server without frame streams, or a
1678
+ * 4xx other than 408 and 429 (the frame no longer validates, say).
1679
+ */
1680
+ function refused(err) {
1681
+ if (!(err instanceof NetworkError)) return false;
1682
+ if (err.code === "frames_unsupported") return true;
1683
+ const status = err.status;
1684
+ return status !== void 0 && status >= 400 && status < 500 && status !== 408 && status !== 429;
1685
+ }
1686
+ /**
1687
+ * Aborts when any of `signals` does. `AbortSignal.any` holds no listener on its
1688
+ * sources, so finished subscriptions leave nothing behind on a shared signal; the
1689
+ * fallback, for browsers before 2024, does.
1690
+ */
1691
+ function anySignal(signals) {
1692
+ if (typeof AbortSignal.any === "function") return AbortSignal.any(signals);
1693
+ const ctrl = new AbortController();
1694
+ for (const s of signals) {
1695
+ if (s.aborted) {
1696
+ ctrl.abort(s.reason);
1697
+ break;
1176
1698
  }
1177
- } finally {
1178
- await reader.cancel().catch(() => {});
1179
- reader.releaseLock();
1699
+ s.addEventListener("abort", () => ctrl.abort(s.reason), { once: true });
1180
1700
  }
1701
+ return ctrl.signal;
1702
+ }
1703
+ function decodeFrame(payload, wire) {
1704
+ const value = wire === "pack" ? decodeWsEnvelope(payload, "pack") : JSON.parse(new TextDecoder().decode(payload));
1705
+ if (value === null || typeof value !== "object" || typeof value.kind !== "string") throw new NetworkError("malformed frame in subscription stream", null);
1706
+ return value;
1707
+ }
1708
+ function jittered(cfg, attempt) {
1709
+ const raw = Math.min(cfg.baseDelayMs * 2 ** (attempt - 1), cfg.maxDelayMs);
1710
+ return cfg.jitter === 0 ? raw : raw + (Math.random() * 2 - 1) * raw * cfg.jitter;
1711
+ }
1712
+ /** Resolves true after `ms`, or false as soon as `signal` aborts. */
1713
+ function sleep(ms, signal) {
1714
+ if (signal.aborted) return Promise.resolve(false);
1715
+ return new Promise((resolve) => {
1716
+ const timer = setTimeout(() => {
1717
+ signal.removeEventListener("abort", onAbort);
1718
+ resolve(true);
1719
+ }, ms);
1720
+ const onAbort = () => {
1721
+ clearTimeout(timer);
1722
+ resolve(false);
1723
+ };
1724
+ signal.addEventListener("abort", onAbort, { once: true });
1725
+ });
1181
1726
  }
1182
1727
 
1183
1728
  //#endregion
@@ -1189,11 +1734,31 @@ function createNlApi(t) {
1189
1734
  const res = await t.raw("/substrate/v1/nl", {
1190
1735
  method: "POST",
1191
1736
  body: req,
1192
- accept: "text/event-stream",
1737
+ accept: FRAMES_JSON_MIME,
1193
1738
  ...opts.signal !== void 0 ? { signal: opts.signal } : {}
1194
1739
  });
1195
- if (res.body === null) throw new NetworkError("empty SSE body", null);
1196
- yield* readSse(res.body);
1740
+ const type = res.headers.get("content-type") ?? "";
1741
+ if (!type.startsWith("application/vnd.substrate.frames+json") || res.body === null) {
1742
+ await res.body?.cancel();
1743
+ throw new NetworkError(`POST /substrate/v1/nl answered '${type}', not ${FRAMES_JSON_MIME}: the server predates frame streams`, null, {
1744
+ status: res.status,
1745
+ code: FRAMES_UNSUPPORTED
1746
+ });
1747
+ }
1748
+ const utf8 = new TextDecoder();
1749
+ for await (const payload of decodeStreamFrames(res.body)) {
1750
+ let ev;
1751
+ try {
1752
+ ev = JSON.parse(utf8.decode(payload));
1753
+ } catch (err) {
1754
+ throw new NetworkError("malformed frame in the NL stream", err);
1755
+ }
1756
+ if (ev.event === "error") {
1757
+ const e = ev.data;
1758
+ throw new NetworkError(`${e.code ?? "error"}: ${e.message ?? ""}`, ev.data);
1759
+ }
1760
+ yield ev;
1761
+ }
1197
1762
  },
1198
1763
  async askJson(req, opts = {}) {
1199
1764
  return await (await t.raw("/substrate/v1/nl", {
@@ -1280,7 +1845,7 @@ var HttpTransport = class {
1280
1845
  constructor(opts) {
1281
1846
  if (opts.token !== void 0 && opts.getToken !== void 0) throw new Error("HttpTransport: provide `token` OR `getToken`, not both");
1282
1847
  this.#endpoint = trimTrailingSlashes(opts.endpoint);
1283
- this.#fetch = (opts.fetch ?? globalThis.fetch).bind(globalThis);
1848
+ this.#fetch = (opts.fetch ?? substrateFetch).bind(globalThis);
1284
1849
  this.#token = opts.token;
1285
1850
  this.#getToken = opts.getToken;
1286
1851
  }
@@ -1396,722 +1961,6 @@ async function errorInfo(res) {
1396
1961
  return info;
1397
1962
  }
1398
1963
 
1399
- //#endregion
1400
- //#region ../../packages/substrate-client/src/reconnect.ts
1401
- var ReconnectScheduler = class {
1402
- #base;
1403
- #max;
1404
- #jitter;
1405
- #attempt = 0;
1406
- constructor(opts) {
1407
- this.#base = opts.baseDelayMs;
1408
- this.#max = opts.maxDelayMs;
1409
- this.#jitter = opts.jitter;
1410
- }
1411
- nextDelay() {
1412
- const raw = Math.min(this.#base * 2 ** this.#attempt, this.#max);
1413
- this.#attempt += 1;
1414
- if (this.#jitter === 0) return raw;
1415
- const spread = raw * this.#jitter;
1416
- return raw + (Math.random() * 2 - 1) * spread;
1417
- }
1418
- reset() {
1419
- this.#attempt = 0;
1420
- }
1421
- /**
1422
- * Resolve after `nextDelay()` ms. Callers must use this serially — the
1423
- * `#attempt` counter is shared across calls, so overlapping `schedule()`
1424
- * invocations will produce incorrect delays. The WS reconnect loop awaits
1425
- * each `schedule()` before firing the next attempt.
1426
- */
1427
- async schedule() {
1428
- const d = this.nextDelay();
1429
- await new Promise((resolve) => setTimeout(resolve, d));
1430
- }
1431
- };
1432
-
1433
- //#endregion
1434
- //#region ../../packages/substrate-client/src/transport/multiplex.ts
1435
- /**
1436
- * MultiplexedSocket — low-level WS multiplexer.
1437
- *
1438
- * One raw WebSocket; outbound frames get a client-generated `id`; inbound
1439
- * frames with a matching `id` route to the right pending handler.
1440
- *
1441
- * Subscribe/stream ops stay pending across multiple messages (they receive
1442
- * snapshot/add/update/remove/chunk/end/error frames). Query/mutate are not
1443
- * handled here — those go via HTTP.
1444
- *
1445
- * Encoding: JSON-over-WS by default. Pass `usePack: true` to send/receive
1446
- * msgpack-encoded frames matching the `substrate-pack` subprotocol negotiated
1447
- * one level up by `WsTransport`. Under pack, `data` values arrive as
1448
- * positional tuples — the higher layer (`SubstrateClient`) is responsible for
1449
- * the schema-driven positional → named decode; the multiplexer only
1450
- * handles wire-format framing.
1451
- *
1452
- * Works with both node-ws WebSocket and browser native WebSocket via the
1453
- * shared `addEventListener` interface (node-ws v8+ supports it).
1454
- */
1455
- /** Terminal response kinds — once received the pending entry is cleared. */
1456
- const TERMINAL_KINDS = /* @__PURE__ */ new Set(["end", "error"]);
1457
- var MultiplexedSocket = class {
1458
- #ws;
1459
- #mode;
1460
- #pending = /* @__PURE__ */ new Map();
1461
- #seq = 0;
1462
- #closing = false;
1463
- /**
1464
- * Accept either a node `ws` WebSocket or a browser WebSocket — both expose
1465
- * `addEventListener`. The constructor wires up message and close handling.
1466
- *
1467
- * `usePack` is set by `WsTransport` after the `substrate-pack` subprotocol
1468
- * has been negotiated at handshake; once true the socket exclusively
1469
- * speaks msgpack frames.
1470
- */
1471
- constructor(ws, opts = {}) {
1472
- this.#ws = ws;
1473
- this.#mode = opts.usePack === true ? "pack" : "json";
1474
- ws.addEventListener("message", (ev) => this.#onMessage(ev));
1475
- ws.addEventListener("close", (ev) => this.#onClose(ev));
1476
- }
1477
- nextId() {
1478
- this.#seq += 1;
1479
- return `c${this.#seq}`;
1480
- }
1481
- /**
1482
- * Serialise + send `frame` (which must already include an `id` field) and
1483
- * register `pending` as the handler for responses bearing that id.
1484
- * Returns the frame id for caller bookkeeping.
1485
- */
1486
- send(frame, pending) {
1487
- const id = frame.id ?? this.nextId();
1488
- const frameWithId = id === frame.id ? frame : {
1489
- ...frame,
1490
- id
1491
- };
1492
- this.#pending.set(id, pending);
1493
- try {
1494
- this.#sendWire(encodeWsFrame(frameWithId, this.#mode));
1495
- } catch (_err) {
1496
- this.#pending.delete(id);
1497
- pending.onClose("send failed");
1498
- }
1499
- return id;
1500
- }
1501
- /**
1502
- * Send a cancel frame for a given subscription id and remove the pending
1503
- * handler. The server will emit a terminal `end` frame; since we delete the
1504
- * pending entry here, that frame is silently dropped.
1505
- */
1506
- cancel(id) {
1507
- this.#pending.delete(id);
1508
- try {
1509
- this.#sendWire(encodeWsFrame({
1510
- id,
1511
- op: "cancel"
1512
- }, this.#mode));
1513
- } catch {}
1514
- }
1515
- /**
1516
- * Push wire bytes to the socket. The branch exists because `WebSocket.send`'s
1517
- * overloads don't accept the union. Binary frames are copied into a fresh
1518
- * `Uint8Array` so the backing buffer is an `ArrayBuffer`, not the
1519
- * `ArrayBufferLike` msgpackr's `Buffer` is typed with — avoiding a cast.
1520
- */
1521
- #sendWire(wire) {
1522
- if (typeof wire === "string") this.#ws.send(wire);
1523
- else this.#ws.send(new Uint8Array(wire));
1524
- }
1525
- close() {
1526
- if (this.#closing) return;
1527
- this.#closing = true;
1528
- try {
1529
- this.#ws.close();
1530
- } catch {}
1531
- }
1532
- #onMessage(ev) {
1533
- let msg;
1534
- try {
1535
- msg = decodeWsEnvelope(ev.data, this.#mode);
1536
- } catch {
1537
- return;
1538
- }
1539
- const pending = this.#pending.get(msg.id);
1540
- if (!pending) return;
1541
- if (TERMINAL_KINDS.has(msg.kind)) this.#pending.delete(msg.id);
1542
- pending.onMessage(msg);
1543
- }
1544
- #onClose(ev) {
1545
- const reason = this.#closing ? "transport_closed" : ev.code === 1012 ? "server_restart" : `ws closed (code ${ev.code})`;
1546
- const snapshot = [...this.#pending.entries()];
1547
- this.#pending.clear();
1548
- for (const [, pending] of snapshot) pending.onClose(reason);
1549
- }
1550
- };
1551
-
1552
- //#endregion
1553
- //#region ../../packages/substrate-client/src/transport/ws.ts
1554
- /**
1555
- * WsTransport — high-level WebSocket transport for Substrate subscriptions.
1556
- *
1557
- * Manages one raw socket per `(endpoint, auth)` pair via MultiplexedSocket.
1558
- * Exposes `subscribe` and `stream` as AsyncIterables; `cancel` is handled
1559
- * transparently via the iterator's `return()` method.
1560
- *
1561
- * Protocol:
1562
- * - No hello/handshake: send subscribe/stream frames immediately on open.
1563
- * - WS handles: subscribe, stream, cancel only. Query/mutate use HTTP.
1564
- * - Auth: Bearer token in Authorization header on the HTTP upgrade request.
1565
- * Node-ws supports custom headers; the WHATWG/browser WebSocket does not,
1566
- * so under Node node-ws is always preferred even when a global WebSocket
1567
- * exists. True browsers cannot authenticate the WS without a
1568
- * header-capable `webSocket` implementation.
1569
- * - Response kinds: snapshot / add / update / remove / chunk / end / error.
1570
- * - Terminal kinds for cleanup: 'end' and 'error'.
1571
- *
1572
- * Reconnect: when the socket closes unexpectedly, ReconnectScheduler backs
1573
- * off and re-opens. Active subscriptions are resubscribed on the new socket —
1574
- * the consumer's AsyncIterable keeps flowing (snapshot arrives again from the
1575
- * server's perspective; the consumer sees it as a new event). A transport that
1576
- * has never connected does not retry: its first failure rejects `next()`.
1577
- */
1578
- /**
1579
- * Terminal-cause tokens from the WS teardown contract
1580
- * (docs/ws-subscription-contract.md). Local literals, not substrate-types
1581
- * imports: they are stable wire contract, like the 1012 close code.
1582
- */
1583
- const REASON_SUBSCRIPTION_OVERLOADED = "subscription_overloaded";
1584
- const REASON_SERVER_RESTART = "server_restart";
1585
- /**
1586
- * Pick the WebSocket implementation for a connection.
1587
- *
1588
- * Priority: injected > node-ws under Node > global (browser). Node ≥22 ships
1589
- * a global WebSocket that cannot carry headers, so preferring it would
1590
- * silently drop the bearer.
1591
- *
1592
- * Throws when a token is configured but the only available implementation
1593
- * cannot carry headers (a true browser): connecting anonymously to an
1594
- * auth-gated server would loop on 4001 instead.
1595
- */
1596
- function selectWebSocketImpl(opts) {
1597
- if (opts.injected !== void 0) return {
1598
- impl: opts.injected,
1599
- supportsHeaders: true
1600
- };
1601
- if (opts.isNode) return {
1602
- impl: opts.nodeWs,
1603
- supportsHeaders: true
1604
- };
1605
- if (opts.globalWs !== void 0) {
1606
- 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);
1607
- return {
1608
- impl: opts.globalWs,
1609
- supportsHeaders: false
1610
- };
1611
- }
1612
- throw new NetworkError("WsTransport: no WebSocket implementation available", null);
1613
- }
1614
- const DEFAULT_RECONNECT = {
1615
- baseDelayMs: 1e3,
1616
- maxDelayMs: 3e4,
1617
- jitter: .1
1618
- };
1619
- const DEFAULT_OVERLOAD_RESUBSCRIBE = {
1620
- enabled: true,
1621
- maxAttempts: 3,
1622
- baseDelayMs: 1e3,
1623
- maxDelayMs: 3e4,
1624
- jitter: .1,
1625
- healthyResetMs: 6e4
1626
- };
1627
- var WsTransport = class {
1628
- #endpoint;
1629
- #token;
1630
- #getToken;
1631
- #webSocket;
1632
- #reconnectOpts;
1633
- #encoding;
1634
- #overloadResubscribe;
1635
- /** Current multiplexed socket, or null if not yet opened / closed. */
1636
- #mux = null;
1637
- /** Promise that resolves when the socket is open and ready. */
1638
- #openPromise = null;
1639
- /** Set when close() is called — no more reconnects. */
1640
- #destroyed = false;
1641
- /** Active subscriptions keyed by their logical frame id. */
1642
- #activeSubs = /* @__PURE__ */ new Map();
1643
- /** Guard: prevents multiple concurrent #reconnectActiveSubs invocations. */
1644
- #reconnecting = false;
1645
- /**
1646
- * Close code captured from the most recent unintentional socket close.
1647
- * Read once by the next `#openLoop` and cleared. When it equals 1012
1648
- * (W3C "Service Restart") the loop skips its first scheduled backoff —
1649
- * the server is intentionally bouncing and we'd rather pay one wasted
1650
- * connect attempt than 1+s of jittered delay.
1651
- */
1652
- #lastCloseCode = null;
1653
- /**
1654
- * Backoff for closes that come AFTER an accepted upgrade (1013 overload,
1655
- * 4001 on a lapsed credential). It lives on the transport, not the open
1656
- * loop, so repeated churn grows the delay; a socket that delivers a frame
1657
- * and outlives `maxDelayMs` proves healthy and resets it.
1658
- */
1659
- #churn;
1660
- /**
1661
- * Retry forever only once a socket has opened. Before that, a failure is
1662
- * most likely a wrong endpoint or a broken token, so it surfaces instead.
1663
- */
1664
- #hasOpened = false;
1665
- constructor(opts) {
1666
- if (opts.token !== void 0 && opts.getToken !== void 0) throw new Error("WsTransport: provide `token` OR `getToken`, not both");
1667
- this.#endpoint = opts.endpoint;
1668
- this.#token = opts.token;
1669
- this.#getToken = opts.getToken;
1670
- this.#webSocket = opts.webSocket;
1671
- this.#reconnectOpts = {
1672
- ...DEFAULT_RECONNECT,
1673
- ...opts.reconnect
1674
- };
1675
- this.#churn = new ReconnectScheduler(this.#reconnectOpts);
1676
- this.#encoding = opts.encoding ?? "json";
1677
- this.#overloadResubscribe = {
1678
- ...DEFAULT_OVERLOAD_RESUBSCRIBE,
1679
- ...opts.overloadResubscribe
1680
- };
1681
- }
1682
- /**
1683
- * Subscribe to a live query. Returns an AsyncIterable of SubscribeEvents.
1684
- * Calling `break` or `return()` on the iterator sends a cancel frame.
1685
- */
1686
- subscribe(req) {
1687
- return this.#makeIterable({
1688
- ...req,
1689
- op: "subscribe"
1690
- });
1691
- }
1692
- /** Stream a one-shot resolver. Returns chunk events followed by an end event. */
1693
- stream(req) {
1694
- return this.#makeIterable({
1695
- ...req,
1696
- op: "stream"
1697
- });
1698
- }
1699
- /** Gracefully shut down. Cancels all active subscriptions and closes the socket. */
1700
- async close() {
1701
- this.#destroyed = true;
1702
- for (const [, sub] of this.#activeSubs) {
1703
- sub.done = true;
1704
- if (sub.retryTimer !== null) {
1705
- clearTimeout(sub.retryTimer);
1706
- sub.retryTimer = null;
1707
- }
1708
- if (sub.waiter) {
1709
- sub.waiter(null);
1710
- sub.waiter = null;
1711
- }
1712
- }
1713
- this.#activeSubs.clear();
1714
- if (this.#mux) {
1715
- this.#mux.close();
1716
- this.#mux = null;
1717
- }
1718
- this.#openPromise = null;
1719
- }
1720
- /** Ensure a connected MultiplexedSocket is available. */
1721
- async #ensureOpen() {
1722
- if (this.#mux !== null) return this.#mux;
1723
- if (this.#openPromise !== null) return this.#openPromise;
1724
- this.#openPromise = this.#openLoop();
1725
- return this.#openPromise;
1726
- }
1727
- /**
1728
- * Open loop: try to open a socket; on failure, backoff and retry.
1729
- * Runs until connected or #destroyed.
1730
- */
1731
- async #openLoop() {
1732
- const scheduler = new ReconnectScheduler(this.#reconnectOpts);
1733
- const wasGracefulRestart = this.#lastCloseCode === 1012;
1734
- const churned = this.#lastCloseCode === 1013 || this.#lastCloseCode === 4001;
1735
- this.#lastCloseCode = null;
1736
- if (churned) {
1737
- await this.#churn.schedule();
1738
- if (this.#destroyed) throw new NetworkError("WsTransport destroyed", null);
1739
- }
1740
- let firstFailure = true;
1741
- while (true) {
1742
- if (this.#destroyed) throw new NetworkError("WsTransport destroyed", null);
1743
- try {
1744
- const mux = await this.#openOnce();
1745
- if (this.#destroyed) {
1746
- mux.close();
1747
- throw new NetworkError("WsTransport destroyed", null);
1748
- }
1749
- scheduler.reset();
1750
- this.#hasOpened = true;
1751
- this.#mux = mux;
1752
- this.#openPromise = null;
1753
- return mux;
1754
- } catch (err) {
1755
- if (this.#destroyed) throw new NetworkError("WsTransport destroyed", err);
1756
- if (!this.#hasOpened) {
1757
- this.#openPromise = null;
1758
- throw err;
1759
- }
1760
- if (wasGracefulRestart && firstFailure) {
1761
- firstFailure = false;
1762
- await new Promise((resolve) => setTimeout(resolve, 0));
1763
- } else {
1764
- firstFailure = false;
1765
- await scheduler.schedule();
1766
- }
1767
- if (this.#destroyed) throw new NetworkError("WsTransport destroyed", null);
1768
- }
1769
- }
1770
- }
1771
- /** Open one WebSocket connection and resolve when it's ready. */
1772
- async #openOnce() {
1773
- const token = this.#token ?? (this.#getToken ? await this.#getToken() : void 0);
1774
- const subprotocols = this.#encoding === "pack" ? [WS_SUBPROTOCOL_SUBSTRATE_PACK] : void 0;
1775
- const ws = await new Promise((resolve, reject) => {
1776
- let rawWs;
1777
- const { impl, supportsHeaders } = selectWebSocketImpl({
1778
- injected: this.#webSocket,
1779
- isNode: typeof process !== "undefined" && process.versions?.node !== void 0,
1780
- globalWs: globalThis.WebSocket,
1781
- nodeWs: WebSocket,
1782
- hasToken: token !== void 0
1783
- });
1784
- if (supportsHeaders) {
1785
- const headers = {};
1786
- if (token !== void 0) headers.authorization = `Bearer ${token}`;
1787
- rawWs = new impl(this.#endpoint, subprotocols, { headers });
1788
- } else rawWs = subprotocols !== void 0 ? new impl(this.#endpoint, subprotocols) : new impl(this.#endpoint);
1789
- if (this.#encoding === "pack") try {
1790
- rawWs.binaryType = "arraybuffer";
1791
- } catch {}
1792
- const onOpen = () => {
1793
- rawWs.removeEventListener("error", onError);
1794
- resolve(rawWs);
1795
- };
1796
- const onError = (ev) => {
1797
- rawWs.removeEventListener("open", onOpen);
1798
- reject(new NetworkError(`WS connect failed: ${this.#endpoint}`, ev));
1799
- };
1800
- rawWs.addEventListener("open", onOpen);
1801
- rawWs.addEventListener("error", onError);
1802
- });
1803
- const mux = new MultiplexedSocket(ws, { usePack: this.#encoding === "pack" });
1804
- const openedAt = Date.now();
1805
- let delivered = false;
1806
- ws.addEventListener("message", () => {
1807
- delivered = true;
1808
- }, { once: true });
1809
- ws.addEventListener("close", (ev) => {
1810
- if (this.#destroyed) return;
1811
- const healthy = delivered && Date.now() - openedAt >= this.#reconnectOpts.maxDelayMs;
1812
- if (healthy) this.#churn.reset();
1813
- if (ev.code === 4001 && !(healthy && this.#canRefreshToken())) {
1814
- if (this.#mux === mux) this.#mux = null;
1815
- 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));
1816
- return;
1817
- }
1818
- if (this.#mux === mux) {
1819
- this.#mux = null;
1820
- this.#lastCloseCode = ev.code;
1821
- }
1822
- this.#reconnectActiveSubs().catch(() => {});
1823
- });
1824
- return mux;
1825
- }
1826
- /** Only a provider can mint a fresh token; a fixed `token` would be refused again. */
1827
- #canRefreshToken() {
1828
- return this.#token === void 0 && this.#getToken !== void 0;
1829
- }
1830
- /** Terminate every active sub with `err` — delivered so next() throws. */
1831
- #failActiveSubs(err) {
1832
- for (const [, sub] of this.#activeSubs) {
1833
- if (sub.done) continue;
1834
- sub.done = true;
1835
- if (sub.retryTimer !== null) {
1836
- clearTimeout(sub.retryTimer);
1837
- sub.retryTimer = null;
1838
- }
1839
- const payload = {
1840
- ok: false,
1841
- err
1842
- };
1843
- if (sub.waiter) {
1844
- const w = sub.waiter;
1845
- sub.waiter = null;
1846
- w(payload);
1847
- } else sub.queue.push(payload);
1848
- }
1849
- this.#activeSubs.clear();
1850
- }
1851
- /** Re-subscribe all active subs after a reconnect. */
1852
- async #reconnectActiveSubs() {
1853
- if (this.#reconnecting) return;
1854
- if (this.#destroyed) return;
1855
- this.#reconnecting = true;
1856
- try {
1857
- if (this.#activeSubs.size === 0) return;
1858
- let mux;
1859
- try {
1860
- mux = await this.#ensureOpen();
1861
- } catch {
1862
- for (const [, sub] of this.#activeSubs) {
1863
- sub.done = true;
1864
- if (sub.retryTimer !== null) {
1865
- clearTimeout(sub.retryTimer);
1866
- sub.retryTimer = null;
1867
- }
1868
- if (sub.waiter) {
1869
- sub.waiter(null);
1870
- sub.waiter = null;
1871
- }
1872
- }
1873
- this.#activeSubs.clear();
1874
- return;
1875
- }
1876
- for (const [, sub] of this.#activeSubs) {
1877
- if (sub.done) continue;
1878
- if (sub.retryTimer !== null) {
1879
- clearTimeout(sub.retryTimer);
1880
- sub.retryTimer = null;
1881
- }
1882
- this.#doSubscribe(mux, sub);
1883
- }
1884
- } finally {
1885
- this.#reconnecting = false;
1886
- }
1887
- }
1888
- /** Send a subscribe/stream frame on the mux and wire up the Pending handler. */
1889
- #doSubscribe(mux, sub) {
1890
- const pending = {
1891
- onMessage: (msg) => {
1892
- if (sub.done) return;
1893
- const action = this.#classifyTerminal(msg, sub);
1894
- if (action === "suppress") return;
1895
- let payload;
1896
- try {
1897
- if (msgToEvent(msg) === null) return;
1898
- payload = {
1899
- ok: true,
1900
- msg
1901
- };
1902
- } catch (err) {
1903
- payload = {
1904
- ok: false,
1905
- err: err instanceof Error ? err : new Error(String(err))
1906
- };
1907
- sub.done = true;
1908
- }
1909
- if (action === "terminal" && (msg.kind === "end" || msg.kind === "error")) sub.done = true;
1910
- if (sub.waiter) {
1911
- const w = sub.waiter;
1912
- sub.waiter = null;
1913
- w(payload);
1914
- } else sub.queue.push(payload);
1915
- },
1916
- onClose: (_reason) => {
1917
- if (sub.done) return;
1918
- if (this.#destroyed) {
1919
- sub.done = true;
1920
- if (sub.waiter) {
1921
- sub.waiter(null);
1922
- sub.waiter = null;
1923
- }
1924
- }
1925
- }
1926
- };
1927
- const outFrame = {
1928
- id: sub.socketId,
1929
- op: sub.frame.op,
1930
- frame: sub.frame.frame
1931
- };
1932
- mux.send(outFrame, pending);
1933
- }
1934
- /**
1935
- * Classify a frame per the teardown contract (substrate repo
1936
- * docs/ws-subscription-contract.md) BEFORE msgToEvent, which throws on
1937
- * error frames.
1938
- *
1939
- * - 'suppress': consumed by the retry machinery; never reaches the consumer.
1940
- * Overload error frames with budget left schedule a resubscribe here; the
1941
- * trailing `end { reason: 'subscription_overloaded' }` of a suppressed
1942
- * teardown is swallowed too.
1943
- * - 'survive': delivered to the consumer but NOT terminal — server_restart
1944
- * end frames; the sub stays live so the socket-close reconnect path
1945
- * resubscribes it.
1946
- * - 'terminal': mark done on delivery.
1947
- * - 'data': everything else.
1948
- */
1949
- #classifyTerminal(msg, sub) {
1950
- const cfg = this.#overloadResubscribe;
1951
- if (msg.kind === "error") {
1952
- if (msg.errors?.[0]?.code !== REASON_SUBSCRIPTION_OVERLOADED || !cfg.enabled) return "terminal";
1953
- const now = Date.now();
1954
- if (sub.lastOverloadAt !== null && now - sub.lastOverloadAt > cfg.healthyResetMs) sub.overloadAttempts = 0;
1955
- sub.lastOverloadAt = now;
1956
- if (sub.overloadAttempts >= cfg.maxAttempts) return "terminal";
1957
- sub.overloadAttempts += 1;
1958
- this.#scheduleOverloadRetry(sub);
1959
- return "suppress";
1960
- }
1961
- if (msg.kind === "end") {
1962
- if (msg.reason === REASON_SUBSCRIPTION_OVERLOADED && cfg.enabled && sub.retryTimer !== null) return "suppress";
1963
- if (msg.reason === REASON_SERVER_RESTART) return "survive";
1964
- if ((msg.reason === "credential_expired" || msg.reason === "credential_changed") && this.#canRefreshToken()) return "survive";
1965
- return "terminal";
1966
- }
1967
- return "data";
1968
- }
1969
- /** Backoff then re-send the subscribe frame for `sub` on the live socket. */
1970
- #scheduleOverloadRetry(sub) {
1971
- const cfg = this.#overloadResubscribe;
1972
- const raw = Math.min(cfg.baseDelayMs * 2 ** (sub.overloadAttempts - 1), cfg.maxDelayMs);
1973
- const delay = cfg.jitter === 0 ? raw : raw + (Math.random() * 2 - 1) * raw * cfg.jitter;
1974
- sub.retryTimer = setTimeout(() => {
1975
- sub.retryTimer = null;
1976
- if (sub.done || this.#destroyed) return;
1977
- this.#ensureOpen().then((mux) => {
1978
- if (!sub.done) this.#doSubscribe(mux, sub);
1979
- }).catch(() => {});
1980
- }, delay);
1981
- }
1982
- #makeIterable(frame) {
1983
- const logicalId = frame.id;
1984
- const transport = this;
1985
- return { [Symbol.asyncIterator]() {
1986
- const sub = {
1987
- frame,
1988
- socketId: logicalId,
1989
- queue: [],
1990
- waiter: null,
1991
- done: false,
1992
- overloadAttempts: 0,
1993
- lastOverloadAt: null,
1994
- retryTimer: null
1995
- };
1996
- transport.#activeSubs.set(logicalId, sub);
1997
- transport.#ensureOpen().then((mux) => {
1998
- if (!sub.done) transport.#doSubscribe(mux, sub);
1999
- }).catch((err) => {
2000
- if (sub.done) return;
2001
- sub.done = true;
2002
- transport.#activeSubs.delete(logicalId);
2003
- const payload = {
2004
- ok: false,
2005
- err: err instanceof Error ? err : new NetworkError(String(err), err)
2006
- };
2007
- if (sub.waiter) {
2008
- const w = sub.waiter;
2009
- sub.waiter = null;
2010
- w(payload);
2011
- } else sub.queue.push(payload);
2012
- });
2013
- return {
2014
- async next() {
2015
- while (true) {
2016
- if (sub.queue.length > 0) {
2017
- const payload = sub.queue.shift();
2018
- if (!payload.ok) {
2019
- sub.done = true;
2020
- transport.#activeSubs.delete(logicalId);
2021
- throw payload.err;
2022
- }
2023
- const ev = msgToEvent(payload.msg);
2024
- if (ev === null) continue;
2025
- return {
2026
- value: ev,
2027
- done: false
2028
- };
2029
- }
2030
- if (sub.done) return {
2031
- value: void 0,
2032
- done: true
2033
- };
2034
- const payload = await new Promise((resolve) => {
2035
- sub.waiter = resolve;
2036
- });
2037
- if (payload === null) return {
2038
- value: void 0,
2039
- done: true
2040
- };
2041
- if (!payload.ok) {
2042
- sub.done = true;
2043
- transport.#activeSubs.delete(logicalId);
2044
- throw payload.err;
2045
- }
2046
- const ev = msgToEvent(payload.msg);
2047
- if (ev !== null) return {
2048
- value: ev,
2049
- done: false
2050
- };
2051
- }
2052
- },
2053
- async return() {
2054
- if (!sub.done) {
2055
- sub.done = true;
2056
- if (sub.retryTimer !== null) {
2057
- clearTimeout(sub.retryTimer);
2058
- sub.retryTimer = null;
2059
- }
2060
- transport.#activeSubs.delete(logicalId);
2061
- if (transport.#mux) transport.#mux.cancel(sub.socketId);
2062
- if (sub.waiter) {
2063
- sub.waiter(null);
2064
- sub.waiter = null;
2065
- }
2066
- }
2067
- return {
2068
- value: void 0,
2069
- done: true
2070
- };
2071
- }
2072
- };
2073
- } };
2074
- }
2075
- };
2076
- /** Convert an InboundMessage to a SubscribeEvent, or null if unrecognised. */
2077
- function msgToEvent(msg) {
2078
- switch (msg.kind) {
2079
- case "snapshot":
2080
- case "add":
2081
- case "update": return {
2082
- kind: msg.kind,
2083
- data: msg.data,
2084
- ...msg.shapes !== void 0 ? { shapes: msg.shapes } : {}
2085
- };
2086
- case "chunk": return {
2087
- kind: "chunk",
2088
- data: msg.data,
2089
- ...msg.shapes !== void 0 ? { shapes: msg.shapes } : {},
2090
- ...msg.sequence !== void 0 ? { sequence: msg.sequence } : {}
2091
- };
2092
- case "remove": return {
2093
- kind: "remove",
2094
- removedId: msg.removedId ?? ""
2095
- };
2096
- case "end": return {
2097
- kind: "end",
2098
- ...msg.final !== void 0 ? { final: msg.final } : {},
2099
- ...msg.reason !== void 0 ? { reason: msg.reason } : {}
2100
- };
2101
- case "error": {
2102
- const first = (msg.errors ?? [{
2103
- message: "unknown error",
2104
- code: "unknown"
2105
- }])[0] ?? {
2106
- message: "unknown error",
2107
- code: "unknown"
2108
- };
2109
- throw new SubscribeError(first.message, first.code ?? "unknown");
2110
- }
2111
- default: return null;
2112
- }
2113
- }
2114
-
2115
1964
  //#endregion
2116
1965
  //#region ../../packages/substrate-client/src/wire/pack.ts
2117
1966
  function isPackMarker(v) {
@@ -2128,11 +1977,11 @@ function decodeJsonEnvelope(env) {
2128
1977
  //#endregion
2129
1978
  //#region ../../packages/substrate-client/src/client.ts
2130
1979
  /**
2131
- * SubstrateClient — the public facade over the HTTP and WS transports, wire
1980
+ * SubstrateClient — the public facade over the HTTP and frame-stream transports, wire
2132
1981
  * decoding and schema-drift handling.
2133
1982
  *
2134
- * Routing is protocol-mandated: query and mutate go over HTTP only (WS does
2135
- * not accept them); subscribe and stream go over WS only.
1983
+ * Routing is protocol-mandated: query and mutate are plain HTTP requests;
1984
+ * subscribe and stream are frame streams (one POST each, response held open).
2136
1985
  *
2137
1986
  * Drift detection is lazy-seeded: the client cannot replicate the server's
2138
1987
  * federated schema-version hash, so the first envelope's `schemaVersion` seeds
@@ -2141,21 +1990,19 @@ function decodeJsonEnvelope(env) {
2141
1990
  */
2142
1991
  var SubstrateClient = class {
2143
1992
  #http;
2144
- #ws = null;
2145
1993
  #nl;
2146
1994
  #admin;
2147
- #wsEndpoint;
2148
- #wsToken;
2149
- #wsGetToken;
2150
- #wsEncoding;
1995
+ #streamWire;
1996
+ #canRefreshToken;
1997
+ /** Aborted by close(), ending every open subscription and stream. */
1998
+ #closing = new AbortController();
2151
1999
  #reconnectOpts;
2000
+ #streamIdleMs;
2152
2001
  #overloadResubscribeOpts;
2153
- #webSocketImpl;
2154
2002
  #schemaCache = null;
2155
2003
  #schemaFetch = null;
2156
2004
  #driftCachedVersion = null;
2157
2005
  #closed = false;
2158
- #wsReqSeq = 0;
2159
2006
  #cache;
2160
2007
  #onDiagnostics;
2161
2008
  constructor(opts) {
@@ -2166,17 +2013,15 @@ var SubstrateClient = class {
2166
2013
  ...opts.getToken !== void 0 ? { getToken: opts.getToken } : {},
2167
2014
  ...opts.fetch !== void 0 ? { fetch: opts.fetch } : {}
2168
2015
  });
2169
- this.#wsEndpoint = `${trimTrailingSlashes(opts.endpoint.replace(/^http/, "ws"))}/substrate/v1/ws`;
2170
- this.#wsToken = opts.token;
2171
- this.#wsGetToken = opts.getToken;
2172
- this.#wsEncoding = opts.wsEncoding ?? "json";
2016
+ this.#streamWire = opts.streamWire ?? "json";
2017
+ this.#canRefreshToken = opts.token === void 0 && opts.getToken !== void 0;
2173
2018
  this.#reconnectOpts = opts.reconnect;
2019
+ this.#streamIdleMs = opts.streamIdleMs;
2174
2020
  this.#overloadResubscribeOpts = opts.overloadResubscribe;
2175
- this.#webSocketImpl = opts.webSocket;
2176
2021
  this.#onDiagnostics = opts.onDiagnostics ?? createDefaultDiagnosticsSink();
2177
2022
  this.#cache = new CacheStore({ idleGcMs: 5e3 });
2178
2023
  }
2179
- /** Natural-language ask (SSE or JSON) and the served namespace pack. Requires the substrate-nl plugin. */
2024
+ /** Natural-language ask (frame stream or JSON) and the served namespace pack. Requires the substrate-nl plugin. */
2180
2025
  get nl() {
2181
2026
  this.#nl ??= createNlApi(this.#http);
2182
2027
  return this.#nl;
@@ -2224,17 +2069,28 @@ var SubstrateClient = class {
2224
2069
  });
2225
2070
  return this.#decode(raw, frame, wire);
2226
2071
  }
2227
- subscribe(frame, _opts = {}) {
2228
- this.#ensureOpen();
2229
- const req = this.#frameToWsRequest(frame);
2230
- const inner = this.#getWs().subscribe(req);
2231
- return this.#wsEncoding === "pack" ? this.#wrapPackDecode(inner, req.frame) : inner;
2072
+ /** A live query: a snapshot, then deltas. `opts.wire` and `opts.signal` apply. */
2073
+ subscribe(frame, opts = {}) {
2074
+ return this.#frameStream("/substrate/v1/subscribe", frame, opts);
2232
2075
  }
2233
- stream(frame, _opts = {}) {
2076
+ /** A one-shot streamed resolver: chunks, then `end`. `opts.wire` and `opts.signal` apply. */
2077
+ stream(frame, opts = {}) {
2078
+ return this.#frameStream("/substrate/v1/stream", frame, opts);
2079
+ }
2080
+ #frameStream(path, frame, opts) {
2234
2081
  this.#ensureOpen();
2235
- const req = this.#frameToWsRequest(frame);
2236
- const inner = this.#getWs().stream(req);
2237
- return this.#wsEncoding === "pack" ? this.#wrapPackDecode(inner, req.frame) : inner;
2082
+ const body = flatFrame(frame);
2083
+ const wire = opts.wire ?? this.#streamWire;
2084
+ const signal = opts.signal === void 0 ? this.#closing.signal : anySignal([this.#closing.signal, opts.signal]);
2085
+ const inner = openFrameStream(this.#http, path, body, {
2086
+ wire,
2087
+ canRefreshToken: this.#canRefreshToken,
2088
+ signal,
2089
+ ...this.#reconnectOpts !== void 0 ? { reconnect: this.#reconnectOpts } : {},
2090
+ ...this.#streamIdleMs !== void 0 ? { idleMs: this.#streamIdleMs } : {},
2091
+ ...this.#overloadResubscribeOpts !== void 0 ? { overload: this.#overloadResubscribeOpts } : {}
2092
+ });
2093
+ return wire === "pack" ? this.#wrapPackDecode(inner, body) : inner;
2238
2094
  }
2239
2095
  /**
2240
2096
  * Live typed-row view over a single-key subscription. Subscribes under the
@@ -2245,7 +2101,7 @@ var SubstrateClient = class {
2245
2101
  *
2246
2102
  * Completes when the subscription ends; throws on an error frame — the same
2247
2103
  * contract as `subscribe`. Breaking the consuming `for await` cancels the
2248
- * underlying WS subscription. Reconnect / overload-resubscribe are handled by
2104
+ * underlying subscription. Reconnect / overload-resubscribe are handled by
2249
2105
  * `subscribe`; each fresh snapshot atomically replaces the row-set.
2250
2106
  *
2251
2107
  * Single-qualified-key only: multi-key frames throw; use `subscribe` for
@@ -2285,22 +2141,7 @@ var SubstrateClient = class {
2285
2141
  async close() {
2286
2142
  if (this.#closed) return;
2287
2143
  this.#closed = true;
2288
- if (this.#ws !== null) {
2289
- await this.#ws.close();
2290
- this.#ws = null;
2291
- }
2292
- }
2293
- #getWs() {
2294
- if (this.#ws === null) this.#ws = new WsTransport({
2295
- endpoint: this.#wsEndpoint,
2296
- encoding: this.#wsEncoding,
2297
- ...this.#wsToken !== void 0 ? { token: this.#wsToken } : {},
2298
- ...this.#wsGetToken !== void 0 ? { getToken: this.#wsGetToken } : {},
2299
- ...this.#reconnectOpts !== void 0 ? { reconnect: this.#reconnectOpts } : {},
2300
- ...this.#overloadResubscribeOpts !== void 0 ? { overloadResubscribe: this.#overloadResubscribeOpts } : {},
2301
- ...this.#webSocketImpl !== void 0 ? { webSocket: this.#webSocketImpl } : {}
2302
- });
2303
- return this.#ws;
2144
+ this.#closing.abort();
2304
2145
  }
2305
2146
  async #refetchSchema() {
2306
2147
  const schema = await this.#http.federatedSchema();
@@ -2332,31 +2173,7 @@ var SubstrateClient = class {
2332
2173
  return env;
2333
2174
  }
2334
2175
  /**
2335
- * Convert a `QualifiedFrame` into a `WsFrameRequest` for the WsTransport.
2336
- *
2337
- * The id MUST be unique per call: a key-derived id lets a re-subscribe race
2338
- * the old sub's terminal frame and silently kill the new one. The type-key
2339
- * prefix is only for readable logs. WsTransport reuses the id verbatim on
2340
- * reconnect, so it is stable for the subscription's lifetime.
2341
- */
2342
- #frameToWsRequest(frame) {
2343
- this.#wsReqSeq += 1;
2344
- const id = `${Object.keys(frame).sort().join("|")}#${this.#wsReqSeq}`;
2345
- const wsFrame = {};
2346
- for (const [key, entry] of Object.entries(frame)) {
2347
- const single = Array.isArray(entry) ? entry[0] : entry;
2348
- wsFrame[key] = {
2349
- params: single?.params ?? {},
2350
- fields: single?.fields ?? {}
2351
- };
2352
- }
2353
- return {
2354
- id,
2355
- frame: wsFrame
2356
- };
2357
- }
2358
- /**
2359
- * Wrap a WS event stream so each `data`-bearing frame (snapshot/add/update/
2176
+ * Wrap a frame event stream so each `data`-bearing frame (snapshot/add/update/
2360
2177
  * chunk) gets its positional tuple values reconstructed into named-object
2361
2178
  * rows using the cached federated schema. Errors from the inner stream
2362
2179
  * (transport drop, server error frame) propagate untouched.
@@ -2407,9 +2224,11 @@ var SubstrateClient = class {
2407
2224
  const { ns, name } = parsed;
2408
2225
  currentNsByKey[key] = ns;
2409
2226
  typeByKey[key] = name;
2410
- const nsSchema = schemas[ns];
2411
- if (nsSchema !== void 0 && nsSchema.mutations[name] !== void 0) returnsByKey[key] = nsSchema.mutations[name].returns;
2412
- else fieldsByKey[key] = entry?.fields ?? {};
2227
+ const mutation = schemas[ns]?.mutations[name];
2228
+ if (mutation !== void 0) {
2229
+ const shapeOf = (fields) => mutationReturns(mutation, fields);
2230
+ returnsByKey[key] = Array.isArray(frameEntry) ? frameEntry.map((f) => shapeOf(f.fields)) : shapeOf(entry?.fields);
2231
+ } else fieldsByKey[key] = entry?.fields ?? {};
2413
2232
  }
2414
2233
  return {
2415
2234
  fieldsByKey,
@@ -2420,6 +2239,17 @@ var SubstrateClient = class {
2420
2239
  };
2421
2240
  }
2422
2241
  };
2242
+ function flatFrame(frame) {
2243
+ const flat = {};
2244
+ for (const [key, entry] of Object.entries(frame)) {
2245
+ const single = Array.isArray(entry) ? entry[0] : entry;
2246
+ flat[key] = {
2247
+ params: single?.params ?? {},
2248
+ fields: single?.fields ?? {}
2249
+ };
2250
+ }
2251
+ return flat;
2252
+ }
2423
2253
 
2424
2254
  //#endregion
2425
2255
  //#region ../../packages/substrate-client/src/token-target.ts
@@ -2443,7 +2273,7 @@ function tokenAudience(baseUrl) {
2443
2273
  throw new Error(`refusing to send a credential to ${url.origin}: use https, or plain http only to a loopback host`);
2444
2274
  }
2445
2275
  /** `fetchImpl` with redirects refused: a redirect would carry the credential to wherever it points. */
2446
- function noRedirectFetch(fetchImpl = fetch) {
2276
+ function noRedirectFetch(fetchImpl = substrateFetch) {
2447
2277
  return (input, init) => fetchImpl(input, {
2448
2278
  ...init,
2449
2279
  redirect: "error"
@@ -2514,4 +2344,4 @@ function createClientFromEnv(opts = {}) {
2514
2344
  }
2515
2345
 
2516
2346
  //#endregion
2517
- export { diagnose as C, DIAGNOSE_CHECKS as S, SKIPPABLE_STEPS as _, SubstrateClient as a, planOnboarding as b, reduceSubscribeRows as c, NetworkError as d, SubscribeError as f, ONBOARD_STEPS as g, CURRENT_MARK as h, tokenAudience as i, watchRows as l, BACKFILL_CHUNK as m, resolveAgentCapabilities as n, collectDiagnostics as o, AdminBackfillError as p, noRedirectFetch as r, createDefaultDiagnosticsSink as s, createClientFromEnv as t, AuthError as u, STEP_MARKS as v, reconcileIdentities as w, requiredOutstanding as x, currentStep as y };
2347
+ export { diagnose as C, createH2Fetch as E, DIAGNOSE_CHECKS as S, substrateFetch as T, SKIPPABLE_STEPS as _, SubstrateClient as a, planOnboarding as b, reduceSubscribeRows as c, NetworkError as d, SubscribeError as f, ONBOARD_STEPS as g, CURRENT_MARK as h, tokenAudience as i, watchRows as l, BACKFILL_CHUNK as m, resolveAgentCapabilities as n, collectDiagnostics as o, AdminBackfillError as p, noRedirectFetch as r, createDefaultDiagnosticsSink as s, createClientFromEnv as t, AuthError as u, STEP_MARKS as v, reconcileIdentities as w, requiredOutstanding as x, currentStep as y };