@inversealtruism/csd-client 0.1.20 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,4 +8,15 @@ Part of the [Compute Substrate SDK](https://github.com/InverseAltruism/csd-sdk)
8
8
  npm i @inversealtruism/csd-client
9
9
  ```
10
10
 
11
+ A non-2xx answer throws an `Error` whose message names the method, the path and the status, as before, and which
12
+ carries `status` and, when the body arrives within 1 second (or the request's remaining time, if less), `body`
13
+ (`HttpErrorFields`): the first `ERROR_BODY_MAX_BYTES` (4,096) bytes as text, decoded as UTF-8, never parsed and never
14
+ logged, so a caller can tell why a node or a proxy refused a request. A body that is late or cannot be read is not
15
+ waited for further, and the error has no `body`. A 4xx is not retried, `submit` never is, and a 5xx retried within
16
+ `retries` is retried without reading its body.
17
+
18
+ Node 22 or later (`engines`). `parseJsonExact`, the default body parser, keeps an integer above 2^53 - 1 exact only
19
+ where `JSON.parse` hands its reviver the source text, which Node 18 and 20 lack; there such a value (a Propose's
20
+ `expires_epoch`, which the node does not bound) comes back as a rounded number, and a txid recomputed from it fails.
21
+
11
22
  See the [repo README](https://github.com/InverseAltruism/csd-sdk#readme) and [examples/quickstart.mjs](https://github.com/InverseAltruism/csd-sdk/blob/master/examples/quickstart.mjs) for usage. MIT.
package/dist/index.cjs CHANGED
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  CsdClient: () => CsdClient,
24
+ ERROR_BODY_MAX_BYTES: () => ERROR_BODY_MAX_BYTES,
24
25
  parseJsonExact: () => parseJsonExact,
25
26
  rpcHeaderToHeader: () => rpcHeaderToHeader,
26
27
  rpcTxToTx: () => rpcTxToTx,
@@ -33,8 +34,57 @@ function parseJsonExact(text) {
33
34
  return JSON.parse(text, exactIntReviver);
34
35
  }
35
36
  var DEFAULT_MAX_RESPONSE_BYTES = 16 * 1024 * 1024;
37
+ var ERROR_BODY_MAX_BYTES = 4096;
38
+ var ERROR_BODY_WAIT_MS = 1e3;
39
+ var LATE = /* @__PURE__ */ Symbol("late");
36
40
  var DEFAULT_RETRIES = 0;
37
41
  var finiteOr = (v, dflt) => v !== void 0 && Number.isFinite(v) ? v : dflt;
42
+ async function errorBody(r, ms) {
43
+ if (!(ms > 0)) return void 0;
44
+ let timer;
45
+ const late = new Promise((res) => {
46
+ timer = setTimeout(() => res(LATE), ms);
47
+ });
48
+ const within = (p) => {
49
+ p.catch(() => void 0);
50
+ return Promise.race([p, late]);
51
+ };
52
+ const cut = (b) => new TextDecoder().decode(b.subarray(0, ERROR_BODY_MAX_BYTES));
53
+ try {
54
+ const body = r.body;
55
+ if (!body || typeof body.getReader !== "function") {
56
+ const t = await within(r.text());
57
+ return t === LATE ? void 0 : cut(new TextEncoder().encode(t));
58
+ }
59
+ const reader = body.getReader();
60
+ const chunks = [];
61
+ let total = 0;
62
+ while (total < ERROR_BODY_MAX_BYTES) {
63
+ const step = await within(reader.read());
64
+ if (step === LATE) {
65
+ reader.cancel().catch(() => void 0);
66
+ return void 0;
67
+ }
68
+ if (step.done) break;
69
+ if (step.value) {
70
+ chunks.push(step.value);
71
+ total += step.value.length;
72
+ }
73
+ }
74
+ if (total >= ERROR_BODY_MAX_BYTES) reader.cancel().catch(() => void 0);
75
+ const buf = new Uint8Array(total);
76
+ let off = 0;
77
+ for (const c of chunks) {
78
+ buf.set(c, off);
79
+ off += c.length;
80
+ }
81
+ return cut(buf);
82
+ } catch {
83
+ return void 0;
84
+ } finally {
85
+ clearTimeout(timer);
86
+ }
87
+ }
38
88
  var CsdClient = class {
39
89
  base;
40
90
  f;
@@ -57,11 +107,15 @@ var CsdClient = class {
57
107
  let lastErr;
58
108
  for (let attempt = 0; ; attempt++) {
59
109
  try {
110
+ const sent = Date.now();
60
111
  const r = await this.f(`${this.base}${path}`, { ...init, signal: AbortSignal.timeout(this.timeoutMs) });
61
112
  if (r.status >= 500 && attempt < maxRetries) {
62
113
  lastErr = new Error(`HTTP ${r.status}`);
63
- } else if (!r.ok) throw Object.assign(new Error(`${init?.method ?? "GET"} ${path} \u2192 HTTP ${r.status}`), { terminal: r.status < 500 });
64
- else return await this.readCapped(r, path);
114
+ } else if (!r.ok) {
115
+ const body = await errorBody(r, Math.min(ERROR_BODY_WAIT_MS, this.timeoutMs - (Date.now() - sent)));
116
+ const fields = body === void 0 ? { status: r.status } : { status: r.status, body };
117
+ throw Object.assign(new Error(`${init?.method ?? "GET"} ${path} \u2192 HTTP ${r.status}`), { terminal: r.status < 500 }, fields);
118
+ } else return await this.readCapped(r, path);
65
119
  } catch (e) {
66
120
  if (attempt >= maxRetries || e?.terminal) throw e;
67
121
  lastErr = e;
@@ -74,7 +128,7 @@ var CsdClient = class {
74
128
  /**
75
129
  * Read a response body as JSON with a hard byte ceiling (`maxResponseBytes`). Rejects an
76
130
  * oversized `Content-Length` up front, and otherwise streams the body and aborts the moment
77
- * it exceeds the cap — so a malicious node cannot make us buffer a giant body and OOM before
131
+ * it exceeds the cap: so a malicious node cannot make us buffer a giant body and OOM before
78
132
  * we ever validate it (audit M2). Falls back to a size-checked `text()` on runtimes without a
79
133
  * streaming body (older MV3/Node), preserving the cap as a best effort.
80
134
  */
@@ -123,7 +177,7 @@ var CsdClient = class {
123
177
  }
124
178
  // The node returns application errors as `{ok:false, err}` with HTTP **200**, so a bare `get()`
125
179
  // can't see them. For endpoints whose `{ok:false}` result is useless to the caller (a missing
126
- // block), surface it as a thrown error — otherwise a beyond-tip/not-found block flows downstream
180
+ // block), surface it as a thrown error: otherwise a beyond-tip/not-found block flows downstream
127
181
  // as a malformed object and crashes opaquely (e.g. the light client reading `header.prev`).
128
182
  async getOk(path) {
129
183
  const j = await this.get(path);
@@ -152,7 +206,7 @@ var CsdClient = class {
152
206
  return this.get(`/utxos/${addr}${opts.available === false ? "" : "?available=true"}`);
153
207
  }
154
208
  // getOk: a not-found proposal returns {ok:false}@200; without this the caller reads .domain/.uri off a
155
- // malformed object instead of seeing the error (audit M6). (tx() deliberately keeps its bare get — its
209
+ // malformed object instead of seeing the error (audit M6). (tx() deliberately keeps its bare get: its
156
210
  // {ok:false} is a documented VALID "not yet in a block" state that waitForTx/verifyInputValues handle.)
157
211
  proposal(id) {
158
212
  return this.getOk(`/proposal/${id}`);
@@ -170,11 +224,11 @@ var CsdClient = class {
170
224
  return this.get("/mempool");
171
225
  }
172
226
  /**
173
- * Await a txid reaching `confirmations` (default 1) — the submit-then-confirm flow every
227
+ * Await a txid reaching `confirmations` (default 1): the submit-then-confirm flow every
174
228
  * consumer was hand-rolling. Polls /tx + /tip; resolves {txid, height, confirmations};
175
- * rejects on timeout (default 10 min — CSD blocks are ~2 min but the live miner is lumpy).
229
+ * rejects on timeout (default 10 min: CSD blocks are ~2 min but the live miner is lumpy).
176
230
  * A tx that drops OUT of the chain mid-wait (reorg) keeps polling until it re-confirms or
177
- * times out — never resolves on a stale sighting.
231
+ * times out: never resolves on a stale sighting.
178
232
  * The count is `tip.height - tx.height + 1` from the RPC's own /tx and /tip answers, with no PoW
179
233
  * or inclusion check, so a lying RPC can over-state it. Gate funds on csd-light, not on this.
180
234
  */
@@ -198,7 +252,7 @@ var CsdClient = class {
198
252
  }
199
253
  /**
200
254
  * Broadcast a node-JSON tx (from @inversealtruism/csd-tx `txToNodeJson`).
201
- * ⚠ The node returns `{ok:false, err}` with HTTP 200 on REJECTION — and **`txid` is populated even
255
+ * ⚠ The node returns `{ok:false, err}` with HTTP 200 on REJECTION, and **`txid` is populated even
202
256
  * then** (it's the computed id of the rejected tx). Callers MUST check `.ok`; reading `.txid`
203
257
  * alone mistakes a rejected tx for a broadcast one. Use `submitOrThrow` if you want a hard failure.
204
258
  */
@@ -263,6 +317,7 @@ function rpcHeaderToHeader(h) {
263
317
  // Annotate the CommonJS export names for ESM import in node:
264
318
  0 && (module.exports = {
265
319
  CsdClient,
320
+ ERROR_BODY_MAX_BYTES,
266
321
  parseJsonExact,
267
322
  rpcHeaderToHeader,
268
323
  rpcTxToTx,
package/dist/index.d.cts CHANGED
@@ -158,12 +158,12 @@ interface ClientOptions {
158
158
  fetch?: typeof fetch;
159
159
  timeoutMs?: number;
160
160
  /** retry NETWORK failures (timeouts, refused, 5xx) this many times with jittered backoff.
161
- * NEVER retries an application result (`ok:false`) or 4xx — those are answers, not outages. */
161
+ * NEVER retries an application result (`ok:false`) or 4xx: those are answers, not outages. */
162
162
  retries?: number;
163
163
  /**
164
164
  * Hard ceiling (bytes) on a response body before it is parsed. A lying/malicious node can
165
165
  * otherwise stream a multi-hundred-MB body that the verifier buffers (`await r.json()`) and
166
- * OOM-crashes BEFORE any PoW/merkle/LWMA check runs — a remote DoS of the trusted light-client
166
+ * OOM-crashes BEFORE any PoW/merkle/LWMA check runs: a remote DoS of the trusted light-client
167
167
  * path (audit M2). Default 16 MiB ≫ any real block; raise it for an unusually large block source.
168
168
  */
169
169
  maxResponseBytes?: number;
@@ -172,6 +172,16 @@ interface ClientOptions {
172
172
  }
173
173
  /** JSON.parse, except that an integer literal outside the safe JS range is returned as an exact bigint. */
174
174
  declare function parseJsonExact(text: string): unknown;
175
+ /** The most bytes of a non-2xx body an HTTP error carries. The node's refusal texts run to a few hundred bytes (its
176
+ * longest error format, with 66-character arguments, is under 200 characters); a proxy's short HTML page fits too. */
177
+ declare const ERROR_BODY_MAX_BYTES = 4096;
178
+ /** What the error a request throws for a non-2xx answer carries besides its message: the HTTP status, and the first
179
+ * ERROR_BODY_MAX_BYTES bytes of the body, decoded as UTF-8 (an invalid byte reads as U+FFFD), never parsed, when the
180
+ * body arrives within ERROR_BODY_WAIT_MS (or the request's remaining time, if less); else no `body`. */
181
+ interface HttpErrorFields {
182
+ status: number;
183
+ body?: string;
184
+ }
175
185
  declare class CsdClient {
176
186
  private readonly base;
177
187
  private readonly f;
@@ -184,7 +194,7 @@ declare class CsdClient {
184
194
  /**
185
195
  * Read a response body as JSON with a hard byte ceiling (`maxResponseBytes`). Rejects an
186
196
  * oversized `Content-Length` up front, and otherwise streams the body and aborts the moment
187
- * it exceeds the cap — so a malicious node cannot make us buffer a giant body and OOM before
197
+ * it exceeds the cap: so a malicious node cannot make us buffer a giant body and OOM before
188
198
  * we ever validate it (audit M2). Falls back to a size-checked `text()` on runtimes without a
189
199
  * streaming body (older MV3/Node), preserving the cap as a best effort.
190
200
  */
@@ -206,11 +216,11 @@ declare class CsdClient {
206
216
  domains(): Promise<RpcDomains>;
207
217
  mempool(): Promise<unknown>;
208
218
  /**
209
- * Await a txid reaching `confirmations` (default 1) — the submit-then-confirm flow every
219
+ * Await a txid reaching `confirmations` (default 1): the submit-then-confirm flow every
210
220
  * consumer was hand-rolling. Polls /tx + /tip; resolves {txid, height, confirmations};
211
- * rejects on timeout (default 10 min — CSD blocks are ~2 min but the live miner is lumpy).
221
+ * rejects on timeout (default 10 min: CSD blocks are ~2 min but the live miner is lumpy).
212
222
  * A tx that drops OUT of the chain mid-wait (reorg) keeps polling until it re-confirms or
213
- * times out — never resolves on a stale sighting.
223
+ * times out: never resolves on a stale sighting.
214
224
  * The count is `tip.height - tx.height + 1` from the RPC's own /tx and /tip answers, with no PoW
215
225
  * or inclusion check, so a lying RPC can over-state it. Gate funds on csd-light, not on this.
216
226
  */
@@ -221,7 +231,7 @@ declare class CsdClient {
221
231
  }): Promise<WaitForTxResult>;
222
232
  /**
223
233
  * Broadcast a node-JSON tx (from @inversealtruism/csd-tx `txToNodeJson`).
224
- * ⚠ The node returns `{ok:false, err}` with HTTP 200 on REJECTION — and **`txid` is populated even
234
+ * ⚠ The node returns `{ok:false, err}` with HTTP 200 on REJECTION, and **`txid` is populated even
225
235
  * then** (it's the computed id of the rejected tx). Callers MUST check `.ok`; reading `.txid`
226
236
  * alone mistakes a rejected tx for a broadcast one. Use `submitOrThrow` if you want a hard failure.
227
237
  */
@@ -236,7 +246,7 @@ declare function rpcTxToTx(j: RpcTxJson): Tx;
236
246
  /** UTXO-VALUE-1 cure (audit). A CSD fee is implicit (Σin − Σout) and uncapped by consensus, so a
237
247
  * builder that trusts a hostile RPC's /utxos `value` can compute too-small a change and silently
238
248
  * BURN the difference as fee. This confirms each selected input's REAL value by fetching its source
239
- * tx and RECOMPUTING its txid with the consensus codec — the txid commits to the output values, so
249
+ * tx and RECOMPUTING its txid with the consensus codec: the txid commits to the output values, so
240
250
  * a forged body whose recomputed txid still matches the prevout is impossible. Fail-CLOSED: any
241
251
  * unreachable/forged/missing source aborts. Returns the verified input total (use it to compute
242
252
  * change from REAL values, not the reported ones). RPC-facing builders (wallet, cairn-sdk) should
@@ -257,4 +267,4 @@ declare function verifyInputValues(client: {
257
267
  /** Convert a node /block header JSON into the codec's BlockHeader. */
258
268
  declare function rpcHeaderToHeader(h: RpcHeaderJson): BlockHeader;
259
269
 
260
- export { type ClientOptions, CsdClient, type RpcBlock, type RpcDomain, type RpcDomains, type RpcHeaderJson, type RpcHealth, type RpcProposal, type RpcProposalItem, type RpcProposalRecord, type RpcProposals, type RpcSubmit, type RpcTip, type RpcTxInfo, type RpcTxJson, type RpcUtxo, type RpcUtxos, type WaitForTxResult, parseJsonExact, rpcHeaderToHeader, rpcTxToTx, verifyInputValues };
270
+ export { type ClientOptions, CsdClient, ERROR_BODY_MAX_BYTES, type HttpErrorFields, type RpcBlock, type RpcDomain, type RpcDomains, type RpcHeaderJson, type RpcHealth, type RpcProposal, type RpcProposalItem, type RpcProposalRecord, type RpcProposals, type RpcSubmit, type RpcTip, type RpcTxInfo, type RpcTxJson, type RpcUtxo, type RpcUtxos, type WaitForTxResult, parseJsonExact, rpcHeaderToHeader, rpcTxToTx, verifyInputValues };
package/dist/index.d.ts CHANGED
@@ -158,12 +158,12 @@ interface ClientOptions {
158
158
  fetch?: typeof fetch;
159
159
  timeoutMs?: number;
160
160
  /** retry NETWORK failures (timeouts, refused, 5xx) this many times with jittered backoff.
161
- * NEVER retries an application result (`ok:false`) or 4xx — those are answers, not outages. */
161
+ * NEVER retries an application result (`ok:false`) or 4xx: those are answers, not outages. */
162
162
  retries?: number;
163
163
  /**
164
164
  * Hard ceiling (bytes) on a response body before it is parsed. A lying/malicious node can
165
165
  * otherwise stream a multi-hundred-MB body that the verifier buffers (`await r.json()`) and
166
- * OOM-crashes BEFORE any PoW/merkle/LWMA check runs — a remote DoS of the trusted light-client
166
+ * OOM-crashes BEFORE any PoW/merkle/LWMA check runs: a remote DoS of the trusted light-client
167
167
  * path (audit M2). Default 16 MiB ≫ any real block; raise it for an unusually large block source.
168
168
  */
169
169
  maxResponseBytes?: number;
@@ -172,6 +172,16 @@ interface ClientOptions {
172
172
  }
173
173
  /** JSON.parse, except that an integer literal outside the safe JS range is returned as an exact bigint. */
174
174
  declare function parseJsonExact(text: string): unknown;
175
+ /** The most bytes of a non-2xx body an HTTP error carries. The node's refusal texts run to a few hundred bytes (its
176
+ * longest error format, with 66-character arguments, is under 200 characters); a proxy's short HTML page fits too. */
177
+ declare const ERROR_BODY_MAX_BYTES = 4096;
178
+ /** What the error a request throws for a non-2xx answer carries besides its message: the HTTP status, and the first
179
+ * ERROR_BODY_MAX_BYTES bytes of the body, decoded as UTF-8 (an invalid byte reads as U+FFFD), never parsed, when the
180
+ * body arrives within ERROR_BODY_WAIT_MS (or the request's remaining time, if less); else no `body`. */
181
+ interface HttpErrorFields {
182
+ status: number;
183
+ body?: string;
184
+ }
175
185
  declare class CsdClient {
176
186
  private readonly base;
177
187
  private readonly f;
@@ -184,7 +194,7 @@ declare class CsdClient {
184
194
  /**
185
195
  * Read a response body as JSON with a hard byte ceiling (`maxResponseBytes`). Rejects an
186
196
  * oversized `Content-Length` up front, and otherwise streams the body and aborts the moment
187
- * it exceeds the cap — so a malicious node cannot make us buffer a giant body and OOM before
197
+ * it exceeds the cap: so a malicious node cannot make us buffer a giant body and OOM before
188
198
  * we ever validate it (audit M2). Falls back to a size-checked `text()` on runtimes without a
189
199
  * streaming body (older MV3/Node), preserving the cap as a best effort.
190
200
  */
@@ -206,11 +216,11 @@ declare class CsdClient {
206
216
  domains(): Promise<RpcDomains>;
207
217
  mempool(): Promise<unknown>;
208
218
  /**
209
- * Await a txid reaching `confirmations` (default 1) — the submit-then-confirm flow every
219
+ * Await a txid reaching `confirmations` (default 1): the submit-then-confirm flow every
210
220
  * consumer was hand-rolling. Polls /tx + /tip; resolves {txid, height, confirmations};
211
- * rejects on timeout (default 10 min — CSD blocks are ~2 min but the live miner is lumpy).
221
+ * rejects on timeout (default 10 min: CSD blocks are ~2 min but the live miner is lumpy).
212
222
  * A tx that drops OUT of the chain mid-wait (reorg) keeps polling until it re-confirms or
213
- * times out — never resolves on a stale sighting.
223
+ * times out: never resolves on a stale sighting.
214
224
  * The count is `tip.height - tx.height + 1` from the RPC's own /tx and /tip answers, with no PoW
215
225
  * or inclusion check, so a lying RPC can over-state it. Gate funds on csd-light, not on this.
216
226
  */
@@ -221,7 +231,7 @@ declare class CsdClient {
221
231
  }): Promise<WaitForTxResult>;
222
232
  /**
223
233
  * Broadcast a node-JSON tx (from @inversealtruism/csd-tx `txToNodeJson`).
224
- * ⚠ The node returns `{ok:false, err}` with HTTP 200 on REJECTION — and **`txid` is populated even
234
+ * ⚠ The node returns `{ok:false, err}` with HTTP 200 on REJECTION, and **`txid` is populated even
225
235
  * then** (it's the computed id of the rejected tx). Callers MUST check `.ok`; reading `.txid`
226
236
  * alone mistakes a rejected tx for a broadcast one. Use `submitOrThrow` if you want a hard failure.
227
237
  */
@@ -236,7 +246,7 @@ declare function rpcTxToTx(j: RpcTxJson): Tx;
236
246
  /** UTXO-VALUE-1 cure (audit). A CSD fee is implicit (Σin − Σout) and uncapped by consensus, so a
237
247
  * builder that trusts a hostile RPC's /utxos `value` can compute too-small a change and silently
238
248
  * BURN the difference as fee. This confirms each selected input's REAL value by fetching its source
239
- * tx and RECOMPUTING its txid with the consensus codec — the txid commits to the output values, so
249
+ * tx and RECOMPUTING its txid with the consensus codec: the txid commits to the output values, so
240
250
  * a forged body whose recomputed txid still matches the prevout is impossible. Fail-CLOSED: any
241
251
  * unreachable/forged/missing source aborts. Returns the verified input total (use it to compute
242
252
  * change from REAL values, not the reported ones). RPC-facing builders (wallet, cairn-sdk) should
@@ -257,4 +267,4 @@ declare function verifyInputValues(client: {
257
267
  /** Convert a node /block header JSON into the codec's BlockHeader. */
258
268
  declare function rpcHeaderToHeader(h: RpcHeaderJson): BlockHeader;
259
269
 
260
- export { type ClientOptions, CsdClient, type RpcBlock, type RpcDomain, type RpcDomains, type RpcHeaderJson, type RpcHealth, type RpcProposal, type RpcProposalItem, type RpcProposalRecord, type RpcProposals, type RpcSubmit, type RpcTip, type RpcTxInfo, type RpcTxJson, type RpcUtxo, type RpcUtxos, type WaitForTxResult, parseJsonExact, rpcHeaderToHeader, rpcTxToTx, verifyInputValues };
270
+ export { type ClientOptions, CsdClient, ERROR_BODY_MAX_BYTES, type HttpErrorFields, type RpcBlock, type RpcDomain, type RpcDomains, type RpcHeaderJson, type RpcHealth, type RpcProposal, type RpcProposalItem, type RpcProposalRecord, type RpcProposals, type RpcSubmit, type RpcTip, type RpcTxInfo, type RpcTxJson, type RpcUtxo, type RpcUtxos, type WaitForTxResult, parseJsonExact, rpcHeaderToHeader, rpcTxToTx, verifyInputValues };
package/dist/index.js CHANGED
@@ -5,8 +5,57 @@ function parseJsonExact(text) {
5
5
  return JSON.parse(text, exactIntReviver);
6
6
  }
7
7
  var DEFAULT_MAX_RESPONSE_BYTES = 16 * 1024 * 1024;
8
+ var ERROR_BODY_MAX_BYTES = 4096;
9
+ var ERROR_BODY_WAIT_MS = 1e3;
10
+ var LATE = /* @__PURE__ */ Symbol("late");
8
11
  var DEFAULT_RETRIES = 0;
9
12
  var finiteOr = (v, dflt) => v !== void 0 && Number.isFinite(v) ? v : dflt;
13
+ async function errorBody(r, ms) {
14
+ if (!(ms > 0)) return void 0;
15
+ let timer;
16
+ const late = new Promise((res) => {
17
+ timer = setTimeout(() => res(LATE), ms);
18
+ });
19
+ const within = (p) => {
20
+ p.catch(() => void 0);
21
+ return Promise.race([p, late]);
22
+ };
23
+ const cut = (b) => new TextDecoder().decode(b.subarray(0, ERROR_BODY_MAX_BYTES));
24
+ try {
25
+ const body = r.body;
26
+ if (!body || typeof body.getReader !== "function") {
27
+ const t = await within(r.text());
28
+ return t === LATE ? void 0 : cut(new TextEncoder().encode(t));
29
+ }
30
+ const reader = body.getReader();
31
+ const chunks = [];
32
+ let total = 0;
33
+ while (total < ERROR_BODY_MAX_BYTES) {
34
+ const step = await within(reader.read());
35
+ if (step === LATE) {
36
+ reader.cancel().catch(() => void 0);
37
+ return void 0;
38
+ }
39
+ if (step.done) break;
40
+ if (step.value) {
41
+ chunks.push(step.value);
42
+ total += step.value.length;
43
+ }
44
+ }
45
+ if (total >= ERROR_BODY_MAX_BYTES) reader.cancel().catch(() => void 0);
46
+ const buf = new Uint8Array(total);
47
+ let off = 0;
48
+ for (const c of chunks) {
49
+ buf.set(c, off);
50
+ off += c.length;
51
+ }
52
+ return cut(buf);
53
+ } catch {
54
+ return void 0;
55
+ } finally {
56
+ clearTimeout(timer);
57
+ }
58
+ }
10
59
  var CsdClient = class {
11
60
  base;
12
61
  f;
@@ -29,11 +78,15 @@ var CsdClient = class {
29
78
  let lastErr;
30
79
  for (let attempt = 0; ; attempt++) {
31
80
  try {
81
+ const sent = Date.now();
32
82
  const r = await this.f(`${this.base}${path}`, { ...init, signal: AbortSignal.timeout(this.timeoutMs) });
33
83
  if (r.status >= 500 && attempt < maxRetries) {
34
84
  lastErr = new Error(`HTTP ${r.status}`);
35
- } else if (!r.ok) throw Object.assign(new Error(`${init?.method ?? "GET"} ${path} \u2192 HTTP ${r.status}`), { terminal: r.status < 500 });
36
- else return await this.readCapped(r, path);
85
+ } else if (!r.ok) {
86
+ const body = await errorBody(r, Math.min(ERROR_BODY_WAIT_MS, this.timeoutMs - (Date.now() - sent)));
87
+ const fields = body === void 0 ? { status: r.status } : { status: r.status, body };
88
+ throw Object.assign(new Error(`${init?.method ?? "GET"} ${path} \u2192 HTTP ${r.status}`), { terminal: r.status < 500 }, fields);
89
+ } else return await this.readCapped(r, path);
37
90
  } catch (e) {
38
91
  if (attempt >= maxRetries || e?.terminal) throw e;
39
92
  lastErr = e;
@@ -46,7 +99,7 @@ var CsdClient = class {
46
99
  /**
47
100
  * Read a response body as JSON with a hard byte ceiling (`maxResponseBytes`). Rejects an
48
101
  * oversized `Content-Length` up front, and otherwise streams the body and aborts the moment
49
- * it exceeds the cap — so a malicious node cannot make us buffer a giant body and OOM before
102
+ * it exceeds the cap: so a malicious node cannot make us buffer a giant body and OOM before
50
103
  * we ever validate it (audit M2). Falls back to a size-checked `text()` on runtimes without a
51
104
  * streaming body (older MV3/Node), preserving the cap as a best effort.
52
105
  */
@@ -95,7 +148,7 @@ var CsdClient = class {
95
148
  }
96
149
  // The node returns application errors as `{ok:false, err}` with HTTP **200**, so a bare `get()`
97
150
  // can't see them. For endpoints whose `{ok:false}` result is useless to the caller (a missing
98
- // block), surface it as a thrown error — otherwise a beyond-tip/not-found block flows downstream
151
+ // block), surface it as a thrown error: otherwise a beyond-tip/not-found block flows downstream
99
152
  // as a malformed object and crashes opaquely (e.g. the light client reading `header.prev`).
100
153
  async getOk(path) {
101
154
  const j = await this.get(path);
@@ -124,7 +177,7 @@ var CsdClient = class {
124
177
  return this.get(`/utxos/${addr}${opts.available === false ? "" : "?available=true"}`);
125
178
  }
126
179
  // getOk: a not-found proposal returns {ok:false}@200; without this the caller reads .domain/.uri off a
127
- // malformed object instead of seeing the error (audit M6). (tx() deliberately keeps its bare get — its
180
+ // malformed object instead of seeing the error (audit M6). (tx() deliberately keeps its bare get: its
128
181
  // {ok:false} is a documented VALID "not yet in a block" state that waitForTx/verifyInputValues handle.)
129
182
  proposal(id) {
130
183
  return this.getOk(`/proposal/${id}`);
@@ -142,11 +195,11 @@ var CsdClient = class {
142
195
  return this.get("/mempool");
143
196
  }
144
197
  /**
145
- * Await a txid reaching `confirmations` (default 1) — the submit-then-confirm flow every
198
+ * Await a txid reaching `confirmations` (default 1): the submit-then-confirm flow every
146
199
  * consumer was hand-rolling. Polls /tx + /tip; resolves {txid, height, confirmations};
147
- * rejects on timeout (default 10 min — CSD blocks are ~2 min but the live miner is lumpy).
200
+ * rejects on timeout (default 10 min: CSD blocks are ~2 min but the live miner is lumpy).
148
201
  * A tx that drops OUT of the chain mid-wait (reorg) keeps polling until it re-confirms or
149
- * times out — never resolves on a stale sighting.
202
+ * times out: never resolves on a stale sighting.
150
203
  * The count is `tip.height - tx.height + 1` from the RPC's own /tx and /tip answers, with no PoW
151
204
  * or inclusion check, so a lying RPC can over-state it. Gate funds on csd-light, not on this.
152
205
  */
@@ -170,7 +223,7 @@ var CsdClient = class {
170
223
  }
171
224
  /**
172
225
  * Broadcast a node-JSON tx (from @inversealtruism/csd-tx `txToNodeJson`).
173
- * ⚠ The node returns `{ok:false, err}` with HTTP 200 on REJECTION — and **`txid` is populated even
226
+ * ⚠ The node returns `{ok:false, err}` with HTTP 200 on REJECTION, and **`txid` is populated even
174
227
  * then** (it's the computed id of the rejected tx). Callers MUST check `.ok`; reading `.txid`
175
228
  * alone mistakes a rejected tx for a broadcast one. Use `submitOrThrow` if you want a hard failure.
176
229
  */
@@ -234,6 +287,7 @@ function rpcHeaderToHeader(h) {
234
287
  }
235
288
  export {
236
289
  CsdClient,
290
+ ERROR_BODY_MAX_BYTES,
237
291
  parseJsonExact,
238
292
  rpcHeaderToHeader,
239
293
  rpcTxToTx,
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@inversealtruism/csd-client",
3
- "version": "0.1.20",
3
+ "version": "0.1.21",
4
4
  "engines": {
5
- "node": ">=18"
5
+ "node": ">=22"
6
6
  },
7
7
  "description": "Typed HTTP RPC client for a Compute Substrate node (or the Cairn proxy / a discovered gateway): tip/block/tx/utxos/proposals/top/domains/mempool/submit/templates.",
8
8
  "type": "module",
@@ -27,12 +27,12 @@
27
27
  "README.md"
28
28
  ],
29
29
  "dependencies": {
30
- "@inversealtruism/csd-codec": "0.1.18"
30
+ "@inversealtruism/csd-codec": "0.1.19"
31
31
  },
32
32
  "license": "MIT",
33
33
  "sideEffects": false,
34
34
  "devDependencies": {
35
- "@inversealtruism/csd-vectors": "0.1.16"
35
+ "@inversealtruism/csd-vectors": "0.1.17"
36
36
  },
37
37
  "publishConfig": {
38
38
  "access": "public"