uvd-describe-sdk 0.1.0 → 0.2.0

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/dist/index.js CHANGED
@@ -8,7 +8,7 @@ var DEFAULT_JITTER_MS = 400;
8
8
  var TREASURY_EVM = "0xe4dc963c56979E0260fc146b87eE24F18220e545";
9
9
  var PARTNER_CHAIN_ID = 8453;
10
10
  var PARTNER_KEY_ENV = "DESCRIBE_PARTNER_PRIVATE_KEY";
11
- var SDK_VERSION = "0.1.0";
11
+ var SDK_VERSION = "0.2.0";
12
12
  var SDK_NAME = "uvd-describe-sdk-ts";
13
13
  function userAgent(product) {
14
14
  const base = `${SDK_NAME}/${SDK_VERSION}`;
@@ -135,19 +135,41 @@ var DescribeNotFound = class extends DescribeError {
135
135
  }
136
136
  };
137
137
  var DescribeHTTPError = class extends DescribeError {
138
- constructor(status, message) {
138
+ /**
139
+ * What the body SAID, not just the number it said it with — Execution
140
+ * Market's contribution, ported 2026-08-31 from the Python twin
141
+ * (`errors.py::DescribeHTTPError.server_reason` — same field, same
142
+ * `' — the server says: '` text): this class's recovery has promised since
143
+ * day one that *"the body names the field"*, and until today the exception
144
+ * threw that body away and carried the bare status. Whoever caught a 422
145
+ * had to re-request to learn which field was wrong.
146
+ *
147
+ * It arrives ALREADY redacted and truncated by `client.ts::serverReason` —
148
+ * the body is server-written text and a 5xx can echo an upstream URL with
149
+ * an API key in its path — and it is appended to the MESSAGE, never to
150
+ * `recovery`, which stays the frozen literal `recovery.test.ts` pins. The
151
+ * parameter is third and optional so every existing call keeps meaning what
152
+ * it meant — additive, like the twin's keyword-only argument.
153
+ */
154
+ serverReason;
155
+ constructor(status, message, opts = {}) {
139
156
  const server = status >= 500;
140
- super(server ? "http_5xx" : "http_4xx", message, {
141
- // 429 is the one 4xx worth retrying: the 20 rps ceiling is shared with
142
- // every other UVD consumer, so it says "someone else is loud right now",
143
- // not "your request is wrong".
144
- transient: server || status === 429,
145
- // A 4xx is the caller's fault and must NOT vanish into failOpen — except
146
- // 429, which is the shared limit and reads exactly like a brief outage.
147
- serviceFault: server || status === 429,
148
- status
149
- });
157
+ super(
158
+ server ? "http_5xx" : "http_4xx",
159
+ opts.serverReason ? `${message} \u2014 the server says: ${opts.serverReason}` : message,
160
+ {
161
+ // 429 is the one 4xx worth retrying: the 20 rps ceiling is shared with
162
+ // every other UVD consumer, so it says "someone else is loud right now",
163
+ // not "your request is wrong".
164
+ transient: server || status === 429,
165
+ // A 4xx is the caller's fault and must NOT vanish into failOpen — except
166
+ // 429, which is the shared limit and reads exactly like a brief outage.
167
+ serviceFault: server || status === 429,
168
+ status
169
+ }
170
+ );
150
171
  this.name = "DescribeHTTPError";
172
+ this.serverReason = opts.serverReason;
151
173
  }
152
174
  };
153
175
  var DescribePaymentRequired = class extends DescribeError {
@@ -420,6 +442,16 @@ function parseWalletReputation(payload) {
420
442
  if (!isObj(payload) || typeof payload.wallet !== "string") {
421
443
  throw new DescribeUnparseable("wallet-chains response is missing its essential shape (wallet)");
422
444
  }
445
+ if ("globalScore" in payload || "finalScore" in payload || "weightedScore" in payload) {
446
+ throw new DescribeUnparseable(
447
+ "this payload is already parsed (it carries a camelCase score key, which the wire never does): do not parse twice. `client.wallet()` already parses, and the payload as served is in `.raw`."
448
+ );
449
+ }
450
+ if ("final_score" in payload && !("global_score" in payload)) {
451
+ throw new DescribeUnparseable(
452
+ "this is the METERED route's payload (`GET /reputation/wallet/{wallet}` \u2014 it carries a top-level `final_score` and no `global_score`): it goes to parseWalletBreakdown, not parseWalletReputation. Parsing it here would answer nulls for a score the metered route DID serve."
453
+ );
454
+ }
423
455
  const rows = Array.isArray(payload.chains) ? payload.chains : [];
424
456
  const chains = rows.filter(isObj).map((row) => ({
425
457
  network: String(row.network ?? ""),
@@ -450,6 +482,16 @@ function parseWalletBreakdown(payload, payment) {
450
482
  if (!isObj(payload) || typeof payload.wallet !== "string") {
451
483
  throw new DescribeUnparseable("wallet-breakdown response is missing its essential shape (wallet)");
452
484
  }
485
+ if ("finalScore" in payload || "weightedScore" in payload || "globalScore" in payload) {
486
+ throw new DescribeUnparseable(
487
+ "this payload is already parsed (it carries a camelCase score key, which the wire never does \u2014 `globalScore` means it is the OTHER parser's output): do not parse twice. The payload as served is in `.raw`."
488
+ );
489
+ }
490
+ if ("global_score" in payload && !("final_score" in payload)) {
491
+ throw new DescribeUnparseable(
492
+ "this is the FREE route's payload (`GET /wallets/{wallet}/chains` \u2014 it carries `global_score` and no top-level `final_score`): it goes to parseWalletReputation, not parseWalletBreakdown. Parsing it here would answer nulls for scores the free route never served."
493
+ );
494
+ }
453
495
  return {
454
496
  wallet: payload.wallet,
455
497
  finalScore: optNumber(payload.final_score),
@@ -550,6 +592,39 @@ function parseHealth(payload) {
550
592
  }
551
593
 
552
594
  // src/client.ts
595
+ var URL_IN_BODY = /[a-z][a-z0-9+.-]*:\/\/\S+/gi;
596
+ async function serverReason(response) {
597
+ let body;
598
+ try {
599
+ body = await response.json();
600
+ } catch {
601
+ return void 0;
602
+ }
603
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return void 0;
604
+ const record = body;
605
+ const parts = [];
606
+ for (const key of ["error", "code", "message"]) {
607
+ const value = record[key];
608
+ if (value !== null && value !== void 0) parts.push(`${key}=${String(value)}`);
609
+ }
610
+ if (parts.length === 0) return void 0;
611
+ let reason = parts.join(" \xB7 ").replace(URL_IN_BODY, "[url-redacted]");
612
+ if (reason.length > 300) reason = `${reason.slice(0, 300)}\u2026`;
613
+ return reason;
614
+ }
615
+ var KNOWN_CONFIG_KEYS = {
616
+ baseUrl: true,
617
+ timeoutMs: true,
618
+ product: true,
619
+ failOpen: true,
620
+ onFailure: true,
621
+ jitterMs: true,
622
+ payer: true,
623
+ partner: true,
624
+ partnerFallsBackToPaying: true,
625
+ expectedPayTo: true,
626
+ fetchImpl: true
627
+ };
553
628
  var DescribeClient = class {
554
629
  baseUrl;
555
630
  timeoutMs;
@@ -563,6 +638,14 @@ var DescribeClient = class {
563
638
  expectedPayTo;
564
639
  fetchImpl;
565
640
  constructor(config = {}) {
641
+ for (const key of Object.keys(config)) {
642
+ if (!(key in KNOWN_CONFIG_KEYS)) {
643
+ const hint = key === "userAgent" ? " The User-Agent is built for you; name your product with `product` \u2014 it becomes the '(+name)' suffix." : "";
644
+ throw new TypeError(
645
+ `Unknown DescribeClient option '${key}'.${hint} Valid options: ${Object.keys(KNOWN_CONFIG_KEYS).join(", ")}.`
646
+ );
647
+ }
648
+ }
566
649
  this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
567
650
  this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
568
651
  this.ua = userAgent(config.product);
@@ -853,7 +936,9 @@ var DescribeClient = class {
853
936
  throw new DescribeNotFound(`GET ${path} -> HTTP 404`);
854
937
  }
855
938
  if (!response.ok) {
856
- throw new DescribeHTTPError(response.status, `GET ${path} -> HTTP ${response.status}`);
939
+ throw new DescribeHTTPError(response.status, `GET ${path} -> HTTP ${response.status}`, {
940
+ serverReason: await serverReason(response)
941
+ });
857
942
  }
858
943
  return this.readJson(response, path);
859
944
  }
@@ -882,7 +967,9 @@ var DescribeClient = class {
882
967
  throw new DescribeNotFound(`GET ${path} -> HTTP 404`);
883
968
  }
884
969
  if (first.status !== 402) {
885
- throw new DescribeHTTPError(first.status, `GET ${path} -> HTTP ${first.status}`);
970
+ throw new DescribeHTTPError(first.status, `GET ${path} -> HTTP ${first.status}`, {
971
+ serverReason: await serverReason(first)
972
+ });
886
973
  }
887
974
  const challenge = await this.readChallenge(first, path);
888
975
  if (this.partner && !this.partnerFallsBackToPaying) {
@@ -905,10 +992,17 @@ var DescribeClient = class {
905
992
  try {
906
993
  second = await this.request(path, { "X-PAYMENT": header });
907
994
  } catch (error) {
908
- throw attachPayment(error, { settlement: "unknown", receipt: null, reused: null, ...terms });
995
+ throw attachPayment(error, {
996
+ settlement: "unknown",
997
+ receipt: null,
998
+ settlementPending: false,
999
+ reused: null,
1000
+ ...terms
1001
+ });
909
1002
  }
910
1003
  const receipt = second.headers.get("X-Payment-Receipt");
911
1004
  const reused = second.headers.get("X-Payment-Reused");
1005
+ const receiptPending = receipt === SETTLEMENT_PENDING;
912
1006
  const attempt = {
913
1007
  // A receipt is the settlement transaction hash, put there by the seller:
914
1008
  // proof, not inference. Its absence proves nothing — an unhandled 500 is
@@ -916,12 +1010,19 @@ var DescribeClient = class {
916
1010
  //
917
1011
  // ⚠️ Since 2026-08-30 the header must also LOOK like a settlement id (a
918
1012
  // hash, or the `pending` the OpenAPI declares) before it may be called
919
- // proof. `'settled'` means *we hold the hash*, and a string that is not
920
- // one is not one. The value is still carried in `receipt` — on this path
921
- // it is forensic evidence, not a typed field — and `'unknown'` is the
922
- // honest verdict: ask the chain.
1013
+ // proof. `'settled'` means *the seller stated settlement*: we hold the
1014
+ // hash, or the seller answered the literal `pending` and
1015
+ // `settlementPending` says so. A string that is neither is neither, and
1016
+ // `'unknown'` is the honest verdict: ask the chain.
1017
+ //
1018
+ // ⚠️ Since 2026-08-31 the `pending` sentinel never rides in `receipt` —
1019
+ // Execution Market's INC-2026-08-26: a placeholder stored in the column
1020
+ // meant for the hash gets archived as proof. Here `receipt` is null and
1021
+ // the flag carries the state. Garbage, by contrast, IS kept verbatim on
1022
+ // this failure path: there it is forensic evidence, not a typed field.
923
1023
  settlement: receipt !== null && looksLikeSettlementReceipt(receipt) ? "settled" : "unknown",
924
- receipt,
1024
+ receipt: receiptPending ? null : receipt,
1025
+ settlementPending: receiptPending,
925
1026
  reused: reused === null ? null : reused.toLowerCase() === "true",
926
1027
  status: second.status,
927
1028
  ...terms
@@ -930,7 +1031,10 @@ var DescribeClient = class {
930
1031
  throw attachPayment(
931
1032
  new DescribeHTTPError(
932
1033
  second.status,
933
- `GET ${path} -> HTTP ${second.status} AFTER paying (settlement: ${attempt.settlement}${receipt ? `, receipt ${receipt}` : ""}). Read \`error.payment\` before retrying: the same receipt unlocks only this byte-identical resource.`
1034
+ `GET ${path} -> HTTP ${second.status} AFTER paying (settlement: ${attempt.settlement}${receipt ? `, receipt ${receipt}` : ""}). Read \`error.payment\` before retrying: the same receipt unlocks only this byte-identical resource.`,
1035
+ // The most expensive door gets the reason too: a 4xx/5xx AFTER money
1036
+ // moved is exactly where "what did they SAY" matters most.
1037
+ { serverReason: await serverReason(second) }
934
1038
  ),
935
1039
  attempt
936
1040
  );
@@ -945,7 +1049,8 @@ var DescribeClient = class {
945
1049
  return {
946
1050
  body,
947
1051
  payment: {
948
- receipt: receiptOk ? receipt : null,
1052
+ receipt: receiptOk && !receiptPending ? receipt : null,
1053
+ settlementPending: receiptPending,
949
1054
  reused: (reused ?? "").toLowerCase() === "true",
950
1055
  malformedHashes: receipt !== null && !receiptOk ? ["receipt"] : []
951
1056
  },