@seedprotocol/arweave 0.8.2-next.1774.gc97b5ba → 0.8.2-next.1818.gac40edf
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 +6 -1
- package/dist/{ArweaveClient-BsqZ1E90.js → ArweaveClient-wX1uYRvQ.js} +72 -42
- package/dist/ArweaveClient-wX1uYRvQ.js.map +1 -0
- package/dist/gateway/readBaseUrls.d.ts +27 -5
- package/dist/gateway/readBaseUrls.d.ts.map +1 -1
- package/dist/index.js +74 -74
- package/dist/index.js.map +1 -1
- package/dist/node.js +1 -1
- package/package.json +1 -1
- package/dist/ArweaveClient-BsqZ1E90.js.map +0 -1
package/README.md
CHANGED
|
@@ -44,6 +44,11 @@ import { fetchArweaveRawTextAcrossGateways } from '@seedprotocol/arweave'
|
|
|
44
44
|
const body = await fetchArweaveRawTextAcrossGateways(txId)
|
|
45
45
|
```
|
|
46
46
|
|
|
47
|
+
`readArweaveRawAcrossGateways(txId)` asks the same gateways once each and returns `{ bytes, attempts }`,
|
|
48
|
+
where each attempt is `{ baseUrl, outcome }` and `outcome` is the HTTP status, `'timeout'`, `'network'`
|
|
49
|
+
(the request threw; in a browser this includes an answer blocked by CORS), `'empty'` or `'unreadable'`.
|
|
50
|
+
Use it to say why a read missed.
|
|
51
|
+
|
|
47
52
|
Override the fallback list with `ARWEAVE_READ_GATEWAYS` or `NEXT_PUBLIC_ARWEAVE_READ_GATEWAYS` (comma-separated hosts).
|
|
48
53
|
|
|
49
54
|
### Gateway endpoint resolution
|
|
@@ -68,7 +73,7 @@ See [GATEWAY_HYPER.md](https://github.com/JournoLabs/seed-protocol-sdk/blob/main
|
|
|
68
73
|
|-------|--------------|
|
|
69
74
|
| `@seedprotocol/arweave` | `ArweaveClient` (alias of `BaseArweaveClient`), `IArweaveClient` |
|
|
70
75
|
| | Gateway constants and env helpers: `DEFAULT_ARWEAVE_HOST`, `DEFAULT_ARWEAVE_GATEWAYS`, `ARWEAVE_HOST_ENV_KEYS`, `resolveArweaveHostFromEnv`, `getArweaveReadGatewayHostsForPrimary` |
|
|
71
|
-
| | Read gateways: `ensureReadGatewaySelected`, `selectFirstHealthyReadGateway`, `probeGateway`, `getArweaveReadBaseUrls`, `fetchArweaveRawFromBaseUrl`, `fetchArweaveRawTextAcrossGateways`, `setPreferredArweaveReadBaseUrls` |
|
|
76
|
+
| | Read gateways: `ensureReadGatewaySelected`, `selectFirstHealthyReadGateway`, `probeGateway`, `getArweaveReadBaseUrls`, `fetchArweaveRawFromBaseUrl`, `readArweaveRawAcrossGateways`, `fetchArweaveRawTextAcrossGateways`, `setPreferredArweaveReadBaseUrls` |
|
|
72
77
|
| | Circuit breaker: `configureGatewayCircuitBreaker`, `isGatewayHostCircuitOpen`, `recordGatewayHostSuccess` / `recordGatewayHostFailure` |
|
|
73
78
|
| | Gateway config: `resolveSeedGatewayEndpoints`, `resolveSidecarOrigin`, `seedGatewayConfigFromSeedConfig`, `seedGatewayConfigFromClientContext`, `SeedGatewayConfig`, `ResolvedSeedGatewayEndpoints` |
|
|
74
79
|
| | Upload pipeline status: `getArweaveUploadStatus`, `isArweaveL1AnchoringComplete`, `getUploadPipelineTransactionStatus`, `queryArweaveGatewayTransactionWithFallback` |
|
|
@@ -626,41 +626,71 @@ async function Xe() {
|
|
|
626
626
|
} catch {}
|
|
627
627
|
}
|
|
628
628
|
async function Z(e, t, n) {
|
|
629
|
-
let r = new AbortController(),
|
|
629
|
+
let r = e.replace(/\/$/, ""), i = new AbortController(), a = setTimeout(() => i.abort(), n?.timeoutMs ?? 1e4);
|
|
630
630
|
try {
|
|
631
|
-
let
|
|
631
|
+
let e = await fetch(`${r}/raw/${encodeURIComponent(t)}`, {
|
|
632
632
|
method: "GET",
|
|
633
633
|
credentials: "omit",
|
|
634
|
-
signal:
|
|
634
|
+
signal: i.signal
|
|
635
635
|
});
|
|
636
|
-
return
|
|
636
|
+
return e.ok ? {
|
|
637
|
+
baseUrl: r,
|
|
638
|
+
outcome: e.status,
|
|
639
|
+
response: e
|
|
640
|
+
} : {
|
|
641
|
+
baseUrl: r,
|
|
642
|
+
outcome: e.status
|
|
643
|
+
};
|
|
637
644
|
} catch {
|
|
638
|
-
return
|
|
645
|
+
return {
|
|
646
|
+
baseUrl: r,
|
|
647
|
+
outcome: i.signal.aborted ? "timeout" : "network"
|
|
648
|
+
};
|
|
639
649
|
} finally {
|
|
640
|
-
clearTimeout(
|
|
650
|
+
clearTimeout(a);
|
|
641
651
|
}
|
|
642
652
|
}
|
|
643
653
|
async function Ze(e, t) {
|
|
644
|
-
let n = /* @__PURE__ */ new Set(),
|
|
645
|
-
for (let
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
654
|
+
let n = [], r = /* @__PURE__ */ new Set(), i = async (i) => {
|
|
655
|
+
for (let a of i) {
|
|
656
|
+
let i = a.trim().replace(/\/$/, "");
|
|
657
|
+
if (!i || r.has(i)) continue;
|
|
658
|
+
r.add(i);
|
|
659
|
+
let { response: o, ...s } = await Z(i, e, t);
|
|
660
|
+
if (!o) n.push(s);
|
|
661
|
+
else try {
|
|
662
|
+
let r = t?.decode === !1 ? new Uint8Array(await o.arrayBuffer()) : (await ue(o, { transactionId: e })).bytes;
|
|
663
|
+
if (r.byteLength > 0) return n.push(s), r;
|
|
664
|
+
n.push({
|
|
665
|
+
baseUrl: i,
|
|
666
|
+
outcome: "empty"
|
|
667
|
+
});
|
|
668
|
+
} catch {
|
|
669
|
+
n.push({
|
|
670
|
+
baseUrl: i,
|
|
671
|
+
outcome: "unreadable"
|
|
672
|
+
});
|
|
673
|
+
}
|
|
653
674
|
}
|
|
654
|
-
};
|
|
655
|
-
return
|
|
675
|
+
}, a = await i(J());
|
|
676
|
+
return a ? {
|
|
677
|
+
bytes: a,
|
|
678
|
+
attempts: n
|
|
679
|
+
} : (await Xe(), {
|
|
680
|
+
bytes: await i([...X(t), w.getBaseUrl()]),
|
|
681
|
+
attempts: n
|
|
682
|
+
});
|
|
656
683
|
}
|
|
657
684
|
async function Qe(e, t) {
|
|
658
|
-
|
|
685
|
+
return (await Ze(e, t)).bytes;
|
|
686
|
+
}
|
|
687
|
+
async function $e(e, t) {
|
|
688
|
+
let n = await Qe(e, t);
|
|
659
689
|
if (n && !ce(n)) return new TextDecoder().decode(n) || void 0;
|
|
660
690
|
}
|
|
661
691
|
//#endregion
|
|
662
692
|
//#region src/graphql/gql/gql.ts
|
|
663
|
-
var
|
|
693
|
+
var et = {
|
|
664
694
|
"\n query GetTransactionTags($transactionId: ID!) {\n tags: transaction(id: $transactionId) {\n id\n tags {\n name\n value\n }\n }\n }\n": {
|
|
665
695
|
kind: "Document",
|
|
666
696
|
definitions: [{
|
|
@@ -1014,13 +1044,13 @@ var $e = {
|
|
|
1014
1044
|
}]
|
|
1015
1045
|
}
|
|
1016
1046
|
};
|
|
1017
|
-
function
|
|
1018
|
-
return
|
|
1047
|
+
function tt(e) {
|
|
1048
|
+
return et[e] ?? {};
|
|
1019
1049
|
}
|
|
1020
1050
|
//#endregion
|
|
1021
1051
|
//#region src/ArweaveClient/queries.ts
|
|
1022
|
-
var
|
|
1023
|
-
async function
|
|
1052
|
+
var nt = tt("\n query GetTransactionTags($transactionId: ID!) {\n tags: transaction(id: $transactionId) {\n id\n tags {\n name\n value\n }\n }\n }\n"), rt = tt("\n query GetArweaveTransactions(\n $owners: [String!]\n $first: Int\n $after: String\n ) {\n transactions(owners: $owners, first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n anchor\n signature\n block {\n id\n height\n }\n data {\n size\n type\n }\n tags {\n name\n value\n }\n }\n }\n pageInfo {\n hasNextPage\n }\n }\n }\n"), it = 1e4, at = 2e4, ot = 1e3, st = (e) => e >= 500 || e === 429;
|
|
1053
|
+
async function ct(e, t, n) {
|
|
1024
1054
|
let r = new AbortController(), i = setTimeout(() => r.abort(), n);
|
|
1025
1055
|
try {
|
|
1026
1056
|
let n = await fetch(`${e.replace(/\/$/, "")}/${encodeURIComponent(t)}`, {
|
|
@@ -1028,7 +1058,7 @@ async function st(e, t, n) {
|
|
|
1028
1058
|
credentials: "omit",
|
|
1029
1059
|
signal: r.signal
|
|
1030
1060
|
});
|
|
1031
|
-
return await n.body?.cancel().catch(() => {}),
|
|
1061
|
+
return await n.body?.cancel().catch(() => {}), st(n.status) ? {
|
|
1032
1062
|
kind: "retry",
|
|
1033
1063
|
status: n.status
|
|
1034
1064
|
} : {
|
|
@@ -1044,18 +1074,18 @@ async function st(e, t, n) {
|
|
|
1044
1074
|
clearTimeout(i);
|
|
1045
1075
|
}
|
|
1046
1076
|
}
|
|
1047
|
-
function
|
|
1077
|
+
function lt() {
|
|
1048
1078
|
let e = Ye(), t = q();
|
|
1049
1079
|
if (t?.activePath !== "hyper-sidecar" && t?.activePath !== "http-proxy") return e;
|
|
1050
1080
|
let n = /* @__PURE__ */ new Set([...J(), t.arweaveBaseUrl.replace(/\/$/, "")]);
|
|
1051
1081
|
return e.filter((e) => n.has(e));
|
|
1052
1082
|
}
|
|
1053
|
-
async function
|
|
1054
|
-
let n = t.timeoutMs ?? 1e4, r = performance.now() + (t.totalTimeoutMs ?? 2e4), i = t.baseUrls ??
|
|
1083
|
+
async function ut(e, t = {}) {
|
|
1084
|
+
let n = t.timeoutMs ?? 1e4, r = performance.now() + (t.totalTimeoutMs ?? 2e4), i = t.baseUrls ?? lt(), a = i.filter((e) => !A(e)), o = a.length > 0 ? a : i, s = 500;
|
|
1055
1085
|
for (let [t, i] of o.entries()) {
|
|
1056
1086
|
let a = r - performance.now();
|
|
1057
1087
|
if (a <= 0 || t > 0 && a < Math.min(n, 1e3)) break;
|
|
1058
|
-
let o = await
|
|
1088
|
+
let o = await ct(i, e, Math.min(n, a));
|
|
1059
1089
|
if (o.kind === "answer") return N(i), {
|
|
1060
1090
|
status: o.status >= 200 && o.status < 300 ? 200 : o.status,
|
|
1061
1091
|
confirmed: null
|
|
@@ -1069,8 +1099,8 @@ async function lt(e, t = {}) {
|
|
|
1069
1099
|
}
|
|
1070
1100
|
//#endregion
|
|
1071
1101
|
//#region src/default/ArweaveClient.ts
|
|
1072
|
-
var Q = t("seedArweave:ArweaveClient"),
|
|
1073
|
-
function
|
|
1102
|
+
var Q = t("seedArweave:ArweaveClient"), dt = 3e4;
|
|
1103
|
+
function ft(e) {
|
|
1074
1104
|
return (t, n) => {
|
|
1075
1105
|
if (typeof AbortController > "u") return fetch(t, n);
|
|
1076
1106
|
let r = new AbortController(), i = n?.signal ?? void 0, a = setTimeout(() => r.abort(/* @__PURE__ */ Error(`Arweave GraphQL request timed out after ${e} ms`)), e), o = () => r.abort(i?.reason);
|
|
@@ -1082,22 +1112,22 @@ function dt(e) {
|
|
|
1082
1112
|
});
|
|
1083
1113
|
};
|
|
1084
1114
|
}
|
|
1085
|
-
var $ = null,
|
|
1115
|
+
var $ = null, pt = null, mt = async () => {
|
|
1086
1116
|
let e = `${w.getProtocol()}://${w.getHost()}`;
|
|
1087
|
-
if ($ &&
|
|
1117
|
+
if ($ && pt === e) return $;
|
|
1088
1118
|
let t = await import("arweave"), n = t.default ?? t;
|
|
1089
|
-
return typeof n.init != "function" && typeof n.default?.init == "function" && (n = n.default),
|
|
1090
|
-
},
|
|
1119
|
+
return typeof n.init != "function" && typeof n.default?.init == "function" && (n = n.default), pt = e, $ = n.init(w.getArweaveJsApiConfig()), $;
|
|
1120
|
+
}, ht = class {
|
|
1091
1121
|
getArweaveClient() {
|
|
1092
|
-
return new e(w.getEndpoint(), { fetch: dt
|
|
1122
|
+
return new e(w.getEndpoint(), { fetch: ft(dt) });
|
|
1093
1123
|
}
|
|
1094
1124
|
async getTransactionStatus(e) {
|
|
1095
|
-
return
|
|
1125
|
+
return ut(e);
|
|
1096
1126
|
}
|
|
1097
1127
|
async getTransactionData(e, t) {
|
|
1098
1128
|
let n = t?.decode === !1 ? [] : J();
|
|
1099
1129
|
for (let r of n) {
|
|
1100
|
-
let n = await Z(r, e);
|
|
1130
|
+
let { response: n } = await Z(r, e);
|
|
1101
1131
|
if (n) try {
|
|
1102
1132
|
return t?.string ? await n.text() : new Uint8Array(await n.arrayBuffer());
|
|
1103
1133
|
} catch (e) {
|
|
@@ -1109,7 +1139,7 @@ var $ = null, ft = null, pt = async () => {
|
|
|
1109
1139
|
if (!n.ok) throw Error(`Failed to fetch transaction data: HTTP ${n.status}`);
|
|
1110
1140
|
return t?.string ? n.text() : new Uint8Array(await n.arrayBuffer());
|
|
1111
1141
|
}
|
|
1112
|
-
let r = await
|
|
1142
|
+
let r = await mt();
|
|
1113
1143
|
try {
|
|
1114
1144
|
let n = await r.transactions.getData(e, {
|
|
1115
1145
|
decode: t?.decode ?? !0,
|
|
@@ -1123,7 +1153,7 @@ var $ = null, ft = null, pt = async () => {
|
|
|
1123
1153
|
async getTransactionTags(e) {
|
|
1124
1154
|
let t = this.getArweaveClient();
|
|
1125
1155
|
try {
|
|
1126
|
-
let n = await t.request(
|
|
1156
|
+
let n = await t.request(nt, { transactionId: e });
|
|
1127
1157
|
return n.tags?.tags ? n.tags.tags.map((e) => ({
|
|
1128
1158
|
name: e.name,
|
|
1129
1159
|
value: e.value
|
|
@@ -1133,7 +1163,7 @@ var $ = null, ft = null, pt = async () => {
|
|
|
1133
1163
|
}
|
|
1134
1164
|
}
|
|
1135
1165
|
async createTransaction(e, t) {
|
|
1136
|
-
let n = await (await
|
|
1166
|
+
let n = await (await mt()).createTransaction({ data: e });
|
|
1137
1167
|
if (t?.tags) for (let e of t.tags) n.addTag(e.name, e.value);
|
|
1138
1168
|
return n;
|
|
1139
1169
|
}
|
|
@@ -1167,6 +1197,6 @@ var $ = null, ft = null, pt = async () => {
|
|
|
1167
1197
|
}
|
|
1168
1198
|
};
|
|
1169
1199
|
//#endregion
|
|
1170
|
-
export {
|
|
1200
|
+
export { f as $, B as A, P as B, G as C, Te as D, De as E, _e as F, fe as G, ve as H, ye as I, oe as J, pe as K, A as L, V as M, j as N, z as O, M as P, h as Q, be as R, Ae as S, W as T, w as U, N as V, v as W, ue as X, ce as Y, ae as Z, J as _, ot as a, r as at, Ge as b, nt as c, p as ct, Qe as d, re as dt, c as et, Z as f, te as ft, Ze as g, X as h, at as i, o as it, Ce as j, we as k, Je as l, ne as lt, Ye as m, ht as n, n as nt, ut as o, i as ot, $e as p, le as q, it as r, a as rt, rt as s, u as st, dt as t, s as tt, Xe as u, ie as ut, q as v, Ve as w, Ue as x, qe as y, O as z };
|
|
1171
1201
|
|
|
1172
|
-
//# sourceMappingURL=ArweaveClient-
|
|
1202
|
+
//# sourceMappingURL=ArweaveClient-wX1uYRvQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ArweaveClient-wX1uYRvQ.js","names":["g","types.GetTransactionTagsDocument","types.GetArweaveTransactionsDocument","debug","DEFAULT_ARWEAVE_HOST","DEFAULT_SEED_FEED_HYPER_KEY","DEFAULT_SEED_GATEWAY_HYPER_KEY","DEFAULT_GATEWAY_SIDECAR_HOST","DEFAULT_GATEWAY_SIDECAR_PORT","DEFAULT_ARWEAVE_GRAPHQL_URL","DEFAULT_ARWEAVE_GATEWAYS","RETIRED_ARWEAVE_GATEWAYS","KNOWN_ARWEAVE_GATEWAYS","READ_GATEWAYS_ENV_KEYS","ARWEAVE_HOST_ENV_KEYS","normalizeGatewayHostInput","input","resolveArweaveHostFromEnv","key","raw","getArweaveReadGatewayHostsForPrimary","mergePrimaryHostWithDefaults","primary","getDefaultArweaveReadGatewayHostsOrdered","s","seen","out","keyOf","h","add","k","d","defaults","isKnownArweaveGatewayHostname","hostname","g","gl","readTransform","setArweaveContentReadTransform","transform","hasArweaveContentReadTransform","transformArweaveContent","content","context","ENVELOPE_VERSION_LINE","isEncryptedArweaveContent","bytes","i","getResponseMediaType","response","readArweaveContentResponse","OWNER_KEY","thisCopy","markArweaveClientOwner","DuplicateArweaveModuleError","assertSingleArweaveModule","owner","resetArweaveClientOwnerForTests","parseGateway","_host","_protocol","_hostExplicitlySet","_suppressEnvGatewayOverride","BaseArweaveClient","impl","envHost","host","slash","protocol","defaultPort","url","parsed","transactionId","data","options","isString","params","DEFAULT_FAILURE_THRESHOLD","DEFAULT_OPEN_MS","failureThreshold","openDurationMs","circuits","normalizeGatewayHostKey","hostOrUrl","getOrCreate","c","resolveState","now","configureGatewayCircuitBreaker","resetGatewayCircuitBreakerForTests","isGatewayHostCircuitOpen","state","getGatewayHostCircuitState","beginGatewayHostHalfOpenProbe","cancelGatewayHostHalfOpenProbe","recordGatewayHostSuccess","recordGatewayHostFailure","listOpenGatewayCircuitHosts","READ_GATEWAY_CACHE_TTL_MS","READ_GATEWAY_UNHEALTHY_CACHE_TTL_MS","PROBE_TIMEOUT_MS","readGatewayCache","ensureInFlight","lastHealthyReadGatewayHost","invalidateReadGatewayCache","resetArweaveReadGatewayForTests","isReadGatewayKnownHealthy","getLastHealthyReadGatewayHost","probeGateway","baseUrl","hostKey","recordCircuit","record","healthy","callerAborted","signal","controller","timer","timeoutMs","onAbort","text","json","selectFirstHealthyReadGateway","hosts","buildOrderedHostsForProbe","ensureReadGatewaySelected","picked","fallback","PROBE_TTL_MS","PROBE_FAILURE_TTL_MS","sidecarProbeCache","proxyProbeCache","invalidateSidecarProbeCache","parseGatewayHost","publicArweaveBaseUrl","config","resolveSidecarOrigin","port","browserOrigin","origin","resolveProxyBaseUrl","proxyBaseUrl","probeUrlHealthy","cached","cacheKey","entry","buildHttpEndpoints","uploadApiBaseUrl","buildHyperEndpoints","sidecar","buildProxyEndpoints","absoluteProxyBaseUrl","path","hostWithPath","shouldProbeProxy","LOOPBACK_HOSTNAME","sidecarReachableFromHere","browserWindow","pageOrigin","tryProxyEndpoints","absolute","resolveSeedGatewayEndpoints","resolveEndpoints","budget","callerSignal","mode","shouldProbe","proxy","hyperEndpoints","getReadGatewayHostsForConfig","resolved","publicBase","publicHosts","index","resolvedGatewayEndpoints","getResolvedSeedGatewayEndpoints","setResolvedSeedGatewayEndpoints","value","preferredReadBaseUrls","getPreferredArweaveReadBaseUrls","setPreferredArweaveReadBaseUrls","urls","trimmed","DEFAULT_ARWEAVE_RAW_READ_TIMEOUT_MS","pushUnique","u","getResolvedArweaveReadBaseUrls","getArweaveReadBaseUrls","ensureArweaveReadGatewayForFallback","fetchArweaveRawFromBaseUrl","base","res","readArweaveRawAcrossGateways","attempts","tried","tryUrls","attempt","preferred","fetchArweaveRawBytesAcrossGateways","fetchArweaveRawTextAcrossGateways","documents","\"kind\"","\"definitions\"","\"operation\"","\"name\"","\"value\"","\"variableDefinitions\"","\"variable\"","\"type\"","\"selectionSet\"","\"selections\"","\"alias\"","\"arguments\"","graphql","source","GET_TRANSACTION_TAGS","GET_ARWEAVE_TRANSACTIONS","DEFAULT_TRANSACTION_STATUS_TIMEOUT_MS","DEFAULT_TRANSACTION_STATUS_TOTAL_TIMEOUT_MS","MIN_TRANSACTION_STATUS_ATTEMPT_MS","isGatewayFailure","status","fetchStatusFromBaseUrl","transactionStatusBaseUrls","local","fetchTransactionStatusAcrossGateways","deadline","baseUrls","open","candidates","lastStatus","remaining","logger","ARWEAVE_GRAPHQL_TIMEOUT_MS","fetchWithTimeout","init","onCallerAbort","_arweaveInstance","_arweaveGatewayKey","getArweaveInstance","gatewayKey","mod","ArweaveClass","DefaultArweaveClient","GraphQLClient","error","arweave","client","result","tag","tx","results","transactionIds","contentType"],"sources":["../src/constants.ts","../src/content/arweaveContent.ts","../src/moduleOwner.ts","../src/ArweaveClient/BaseArweaveClient.ts","../src/gateway/gatewayCircuitBreaker.ts","../src/ArweaveClient/selectReadGateway.ts","../src/gateway/resolveSeedGatewayEndpoints.ts","../src/gateway/gatewayState.ts","../src/gateway/readBaseUrls.ts","../src/graphql/gql/graphql.ts","../src/graphql/gql/gql.ts","../src/ArweaveClient/queries.ts","../src/gateway/transactionStatus.ts","../src/default/ArweaveClient.ts"],"sourcesContent":["/**\n * Default Arweave gateway host used across all packages (first in {@link DEFAULT_ARWEAVE_GATEWAYS}),\n * and the host publish writes into Html links unless `arweaveDomain` names another (ADR 0025).\n */\nexport const DEFAULT_ARWEAVE_HOST = 'arweave.net'\n\n/**\n * Official Seed Protocol public feed Hyperdrive key (z32).\n * Empty until the first official publisher keypair is generated and backed up by ops.\n */\nexport const DEFAULT_SEED_FEED_HYPER_KEY = ''\n\n/**\n * Official Seed Protocol gateway Hyper tunnel operator key (z32).\n * Empty until ops generate and back up the first operator keypair.\n * Also defined in packages/gateway-hyper/src/constants.ts; keep both equal (gateway-hyper __tests__/constants.test.ts checks).\n */\nexport const DEFAULT_SEED_GATEWAY_HYPER_KEY = ''\n\n/** Default localhost sidecar bind for Gateway Hyper client mode. */\nexport const DEFAULT_GATEWAY_SIDECAR_HOST = '127.0.0.1'\nexport const DEFAULT_GATEWAY_SIDECAR_PORT = 1984\n\n/** Default Arweave gateway GraphQL endpoint (transaction / block queries). */\nexport const DEFAULT_ARWEAVE_GRAPHQL_URL = `https://${DEFAULT_ARWEAVE_HOST}/graphql`\n\n/**\n * Default Arweave gateways for read fallback / metadata fetching (ordered by preference).\n * Override order with `ARWEAVE_READ_GATEWAYS` or `NEXT_PUBLIC_ARWEAVE_READ_GATEWAYS` (comma-separated hosts).\n */\nexport const DEFAULT_ARWEAVE_GATEWAYS = [\n 'arweave.net',\n 'zigza.xyz',\n 'ar.seedprotocol.io',\n] as const\n\n/**\n * Gateways recognized in stored links but never read from: their `/<id>` URLs still parse as\n * Arweave links and get re-hosted onto a read gateway. `permagate.io` was a default until it went\n * down (404 \"Application not found\" on `/info`, `/raw/<id>` and `/graphql`, 2026-10-27).\n */\nconst RETIRED_ARWEAVE_GATEWAYS = ['permagate.io'] as const\n\n/** {@link DEFAULT_ARWEAVE_GATEWAYS} and the retired gateways: hosts whose `/<id>` paths are Arweave links. */\nexport const KNOWN_ARWEAVE_GATEWAYS: readonly string[] = [...DEFAULT_ARWEAVE_GATEWAYS, ...RETIRED_ARWEAVE_GATEWAYS]\n\nconst READ_GATEWAYS_ENV_KEYS = ['ARWEAVE_READ_GATEWAYS', 'NEXT_PUBLIC_ARWEAVE_READ_GATEWAYS'] as const\n\n/** Env keys checked for primary Arweave gateway host (first match wins). */\nexport const ARWEAVE_HOST_ENV_KEYS = [\n 'NEXT_PUBLIC_ARWEAVE_HOST',\n 'ARWEAVE_HOST',\n 'VITE_ARWEAVE_HOST',\n] as const\n\nfunction normalizeGatewayHostInput(input: string): string {\n const t = input.trim()\n if (t.startsWith('http://')) return t.slice(7).replace(/\\/$/, '')\n if (t.startsWith('https://')) return t.slice(8).replace(/\\/$/, '')\n return t.replace(/\\/$/, '')\n}\n\n/**\n * Primary gateway host from env (`NEXT_PUBLIC_ARWEAVE_HOST`, `ARWEAVE_HOST`, or `VITE_ARWEAVE_HOST`).\n * Scheme prefixes (`http://`, `https://`) are stripped.\n */\nexport function resolveArweaveHostFromEnv(): string | undefined {\n if (typeof process === 'undefined' || !process.env) return undefined\n for (const key of ARWEAVE_HOST_ENV_KEYS) {\n const raw = process.env[key]?.trim()\n if (raw) return normalizeGatewayHostInput(raw)\n }\n return undefined\n}\n\n/** Ordered read gateways: `primary` first, then the defaults (or the env list) not already in it. */\nexport function getArweaveReadGatewayHostsForPrimary(primary: string): string[] {\n return mergePrimaryHostWithDefaults(primary, getDefaultArweaveReadGatewayHostsOrdered())\n}\n\n/** Ordered gateway hostnames for reads: env list if set, otherwise {@link DEFAULT_ARWEAVE_GATEWAYS}. */\nexport function getDefaultArweaveReadGatewayHostsOrdered(): string[] {\n if (typeof process === 'undefined' || !process.env) {\n return [...DEFAULT_ARWEAVE_GATEWAYS]\n }\n for (const key of READ_GATEWAYS_ENV_KEYS) {\n const raw = process.env[key]?.trim()\n if (raw) {\n return raw.split(',').map((s) => s.trim()).filter(Boolean)\n }\n }\n return [...DEFAULT_ARWEAVE_GATEWAYS]\n}\n\n/**\n * Deduped host list: primary first, then each default not already present (case-insensitive).\n */\nexport function mergePrimaryHostWithDefaults(\n primary: string,\n defaults: readonly string[],\n): string[] {\n const seen = new Set<string>()\n const out: string[] = []\n const keyOf = (h: string) => h.trim().toLowerCase().replace(/\\/$/, '')\n const add = (h: string) => {\n const t = h.trim().replace(/\\/$/, '')\n if (!t) return\n const k = keyOf(t)\n if (seen.has(k)) return\n seen.add(k)\n out.push(t)\n }\n add(primary)\n for (const d of defaults) add(d)\n return out\n}\n\n/**\n * True if `hostname` looks like a public Arweave gateway used in stored URLs (hydration / RSS).\n */\nexport function isKnownArweaveGatewayHostname(hostname: string): boolean {\n const h = hostname.trim().toLowerCase()\n if (!h) return false\n if (h.endsWith('arweave.net')) return true\n if (h.endsWith('ar-io.net')) return true\n for (const g of KNOWN_ARWEAVE_GATEWAYS) {\n const gl = g.toLowerCase()\n if (h === gl || h.endsWith(`.${gl}`)) return true\n }\n return false\n}\n","/**\n * Read-side seam for Arweave content: every place the SDK packages read an upload's bytes from a\n * gateway passes them through {@link transformArweaveContent} before using them. Today nothing is\n * registered and content is used as fetched (public publishing). A future private-publish option\n * would register a transform here (e.g. decrypt using keys from the client config) instead of\n * patching each reader.\n *\n * Readers routed through it:\n * - {@link fetchArweaveRawTextAcrossGateways} (`readBaseUrls.ts`): the SDK's Html storage-seed\n * fallback (`readHtmlBodyForStorageSeed`, which also passes blob-source bytes through) and other\n * text reads.\n * - `BaseArweaveClient.getTransactionData` (every platform client; `decode: false` reads are left\n * alone, they are not content bytes).\n * - `@seedprotocol/query`'s `hydrateArweaveRichTextInItems` (also re-exported by `@seedprotocol/feed`).\n *\n * Not routed (they cannot be, as things stand):\n * - The SDK's OPFS download worker runs from a string and cannot import this module; it has its own\n * `transformDownloadedContent` hook.\n * Text readers return nothing for bytes that are still an encrypted envelope after the transform\n * ({@link isEncryptedArweaveContent}).\n *\n * - Places that hand a gateway URL straight to the browser (`SeedImage` / `useEnsureLocalImage`'s\n * progressive `gatewayHref`, `mediaRef` hrefs, feed image URLs). Encrypted content would need\n * those to fetch, transform and use a blob URL instead.\n */\n\nexport type ArweaveContent = {\n bytes: Uint8Array\n /** Media type without parameters, lowercased (from the response, i.e. the upload's Content-Type tag). */\n contentType?: string\n}\n\nexport type ArweaveContentReadContext = {\n transactionId: string\n}\n\n/** @experimental Signature may change when private publishing lands. */\nexport type ArweaveContentReadTransform = (\n content: ArweaveContent,\n context: ArweaveContentReadContext,\n) => ArweaveContent | Promise<ArweaveContent>\n\nlet readTransform: ArweaveContentReadTransform | undefined\n\n/**\n * Register (or clear, with `undefined`) the transform applied to Arweave content after it is\n * fetched. @experimental Groundwork for private publishing; nothing in the SDK registers one yet.\n */\nexport function setArweaveContentReadTransform(transform: ArweaveContentReadTransform | undefined): void {\n readTransform = transform\n}\n\n/** True when a read transform is registered. Lets readers skip work on the common, public path. */\nexport function hasArweaveContentReadTransform(): boolean {\n return readTransform !== undefined\n}\n\n/** Content as the app should see it: the registered transform's result, or `content` unchanged. */\nexport async function transformArweaveContent(\n content: ArweaveContent,\n context: ArweaveContentReadContext,\n): Promise<ArweaveContent> {\n return readTransform ? readTransform(content, context) : content\n}\n\n/** First line of a `seed-private/v1` envelope (`packages/encryption/SPEC.md`, ADR 0033). */\nconst ENVELOPE_VERSION_LINE = 'seed-private/v1\\n'\n\n/**\n * True when `bytes` are a private Version's encrypted envelope that no transform decrypted. Readers\n * that want text or media skip such bytes instead of decoding ciphertext.\n */\nexport function isEncryptedArweaveContent(bytes: Uint8Array): boolean {\n if (bytes.length < ENVELOPE_VERSION_LINE.length) return false\n for (let i = 0; i < ENVELOPE_VERSION_LINE.length; i++) {\n if (bytes[i] !== ENVELOPE_VERSION_LINE.charCodeAt(i)) return false\n }\n return true\n}\n\n/** `Content-Type` header without parameters, lowercased; undefined when absent. */\nexport function getResponseMediaType(response: Response): string | undefined {\n const raw = response.headers?.get('content-type')\n const mediaType = raw?.split(';')[0]?.trim().toLowerCase()\n return mediaType || undefined\n}\n\n/** Read a gateway response's body through {@link transformArweaveContent}. */\nexport async function readArweaveContentResponse(\n response: Response,\n context: ArweaveContentReadContext,\n): Promise<ArweaveContent> {\n const bytes = new Uint8Array(await response.arrayBuffer())\n return transformArweaveContent({ bytes, contentType: getResponseMediaType(response) }, context)\n}\n","/**\n * Detects a second copy of this package in one page or process. Each copy has its own\n * BaseArweaveClient slot and gateway state, so code reading through one copy would quietly\n * miss the client and gateway registered on the other.\n *\n * Whichever copy last registered a client records itself under a global key that every copy\n * shares; {@link assertSingleArweaveModule} throws when that is not the caller's copy.\n */\nconst OWNER_KEY = Symbol.for('@seedprotocol/arweave:clientOwner')\n\n/** Identity of this copy of the module. */\nconst thisCopy = Object.freeze({ package: '@seedprotocol/arweave' })\n\ntype GlobalWithOwner = typeof globalThis & { [OWNER_KEY]?: object }\n\n/** @internal Called by BaseArweaveClient when a client is registered. */\nexport function markArweaveClientOwner(): void {\n ;(globalThis as GlobalWithOwner)[OWNER_KEY] = thisCopy\n}\n\nexport class DuplicateArweaveModuleError extends Error {\n constructor() {\n super(\n 'Two copies of @seedprotocol/arweave are loaded, and the Arweave client was registered on the other copy ' +\n '(e.g. by SeedClient). Reads through this copy would use a different client and gateway. ' +\n 'Make sure every @seedprotocol/* package is the same version and installed once (`npm ls @seedprotocol/arweave`). ' +\n 'With Vite, keep @seedprotocol/* packages out of optimizeDeps.exclude so they are pre-bundled together, ' +\n 'and dedupe them (seedVitePlugin does) when they are linked into the app.',\n )\n this.name = 'DuplicateArweaveModuleError'\n }\n}\n\n/** Throws {@link DuplicateArweaveModuleError} when another copy of this package registered the Arweave client. */\nexport function assertSingleArweaveModule(): void {\n const owner = (globalThis as GlobalWithOwner)[OWNER_KEY]\n if (owner !== undefined && owner !== thisCopy) throw new DuplicateArweaveModuleError()\n}\n\n/** @internal Tests that load fresh module copies (vi.resetModules) clear the shared marker. */\nexport function resetArweaveClientOwnerForTests(): void {\n delete (globalThis as GlobalWithOwner)[OWNER_KEY]\n}\n","import { GraphQLClient } from 'graphql-request'\nimport type {\n TransactionStatus,\n TransactionTag,\n GetDataOptions,\n DownloadFilesParams,\n DownloadResult,\n CreateTransactionOptions,\n ArweaveTransaction,\n} from '../types/arweave.js'\nimport { DEFAULT_ARWEAVE_HOST, resolveArweaveHostFromEnv } from '../constants.js'\nimport type { IArweaveClient } from './IArweaveClient.js'\nimport { hasArweaveContentReadTransform, transformArweaveContent } from '../content/arweaveContent.js'\nimport { markArweaveClientOwner } from '../moduleOwner.js'\n\nfunction parseGateway(input: string): { protocol: 'http' | 'https'; host: string } {\n const t = input.trim()\n if (t.startsWith('http://')) {\n return { protocol: 'http', host: t.slice(7).replace(/\\/$/, '') }\n }\n if (t.startsWith('https://')) {\n return { protocol: 'https', host: t.slice(8).replace(/\\/$/, '') }\n }\n return { protocol: 'https', host: t.replace(/\\/$/, '') }\n}\n\n// Internal gateway state (process-wide; stays on the facade)\nlet _host = DEFAULT_ARWEAVE_HOST\nlet _protocol: 'http' | 'https' = 'https'\nlet _hostExplicitlySet = false\n/** When true, env gateway host does not override `_host` (after a successful read-gateway probe). */\nlet _suppressEnvGatewayOverride = false\n\nexport abstract class BaseArweaveClient {\n private static _impl: IArweaveClient | null = null\n\n static configure(impl: IArweaveClient): void {\n if (!impl) {\n throw new Error(\n 'Cannot configure ArweaveClient with undefined or null. Ensure the platform-specific ArweaveClient is properly created.',\n )\n }\n BaseArweaveClient._impl = impl\n markArweaveClientOwner()\n }\n\n /** True once a platform (SDK, Node bootstrap, host app) has registered an implementation. */\n static isConfigured(): boolean {\n return BaseArweaveClient._impl != null\n }\n\n private static requireImpl(): IArweaveClient {\n if (!BaseArweaveClient._impl) {\n throw new Error(\n 'ArweaveClient not configured. Import from @seedprotocol/arweave/node to register the Node.js implementation, or ensure SDK platform init has run.',\n )\n }\n return BaseArweaveClient._impl\n }\n\n /**\n * Resolved gateway host (no scheme) and protocol from env override or setHost().\n */\n static resolveGateway(): { protocol: 'http' | 'https'; host: string } {\n const envHost = resolveArweaveHostFromEnv()\n if (envHost && !_hostExplicitlySet && !_suppressEnvGatewayOverride) {\n return parseGateway(envHost)\n }\n return { protocol: _protocol, host: _host }\n }\n\n // ============================================\n // Configuration Methods (facade / process-wide)\n // ============================================\n\n /**\n * Get the current Arweave host (hostname, optionally with port and path prefix — no URL scheme)\n * @returns The Arweave host (e.g. 'arweave.net', 'localhost:1984', or 'app.example.com/api/seed-gateway')\n */\n static getHost(): string {\n return this.resolveGateway().host\n }\n\n /**\n * Hostname (+ optional port) without a path prefix — safe for the `arweave` npm client's `init({ host })`.\n */\n static getArweaveSdkHost(): string {\n const host = this.getHost()\n const slash = host.indexOf('/')\n return slash === -1 ? host : host.slice(0, slash)\n }\n\n /**\n * `{ host, port, protocol }` for the `arweave` npm client's `init()`. The port is always set: the\n * web build of `arweave` otherwise falls back to the page's own port (`https://arweave.net:5173`),\n * and a `host:port` passed as `host` becomes `host:port:443`. Path prefixes are dropped — the\n * `arweave` client cannot address a gateway mounted under a path.\n */\n static getArweaveJsApiConfig(): { host: string; port: number; protocol: 'http' | 'https' } {\n const protocol = this.getProtocol()\n const defaultPort = protocol === 'https' ? 443 : 80\n try {\n const url = new URL(`${protocol}://${this.getArweaveSdkHost()}`)\n return { host: url.hostname, port: url.port ? Number(url.port) : defaultPort, protocol }\n } catch {\n return { host: this.getArweaveSdkHost(), port: defaultPort, protocol }\n }\n }\n\n /**\n * Path prefix on the gateway origin (e.g. `/api/seed-gateway`), or empty.\n */\n static getGatewayPath(): string {\n const host = this.getHost()\n const slash = host.indexOf('/')\n if (slash === -1) return ''\n return host.slice(slash).replace(/\\/$/, '') || ''\n }\n\n /**\n * Get whether requests use http or https\n */\n static getProtocol(): 'http' | 'https' {\n return this.resolveGateway().protocol\n }\n\n /**\n * Base URL for the configured gateway (e.g. https://arweave.net, http://localhost:1984,\n * or https://app.example.com/api/seed-gateway)\n */\n static getBaseUrl(): string {\n const { protocol, host } = this.resolveGateway()\n return `${protocol}://${host}`\n }\n\n /**\n * Set the Arweave gateway. Plain host defaults to https; prefix with http:// for local HTTP gateways.\n * @param host - e.g. 'arweave.net', 'https://arweave.net', or 'http://localhost:1984'\n */\n static setHost(host: string): void {\n const parsed = parseGateway(host)\n _host = parsed.host\n _protocol = parsed.protocol\n _hostExplicitlySet = true\n _suppressEnvGatewayOverride = false\n }\n\n /**\n * When true, read-path gateway probing does not change the host ({@link setHost}).\n */\n static isReadGatewayLocked(): boolean {\n return _hostExplicitlySet\n }\n\n /**\n * @internal Clears env override suppression after probing (for test isolation).\n */\n static resetReadGatewaySelectionStateForTests(): void {\n _suppressEnvGatewayOverride = false\n }\n\n /**\n * Sets the preferred read gateway without locking. Env host still takes precedence until a probe applies a host.\n * Used for seed `arweaveDomain`.\n */\n static setPreferredReadGateway(host: string): void {\n const parsed = parseGateway(host)\n _host = parsed.host\n _protocol = parsed.protocol\n _hostExplicitlySet = false\n }\n\n /**\n * Applies a gateway chosen by read-path health probing so {@link getHost} uses it instead of env override.\n */\n static applyProbedReadGateway(host: string): void {\n const parsed = parseGateway(host)\n _host = parsed.host\n _protocol = parsed.protocol\n _hostExplicitlySet = false\n _suppressEnvGatewayOverride = true\n }\n\n /**\n * Get the GraphQL endpoint URL\n * @returns The full GraphQL endpoint URL\n */\n static getEndpoint(): string {\n return `${this.getBaseUrl()}/graphql`\n }\n\n /**\n * Get the raw data URL for a transaction\n * @param transactionId - The Arweave transaction ID\n * @returns The full URL to access raw transaction data\n */\n static getRawUrl(transactionId: string): string {\n return `${this.getBaseUrl()}/raw/${transactionId}`\n }\n\n /**\n * URL used to verify that a transaction is available on the gateway (HTTP 200 = present).\n * @param transactionId - The Arweave transaction ID\n */\n static getStatusUrl(transactionId: string): string {\n return `${this.getBaseUrl()}/${transactionId}`\n }\n\n // ============================================\n // Delegated to platform instance\n // ============================================\n\n static getArweaveClient(): GraphQLClient {\n return BaseArweaveClient.requireImpl().getArweaveClient()\n }\n\n static getTransactionStatus(transactionId: string): Promise<TransactionStatus> {\n return BaseArweaveClient.requireImpl().getTransactionStatus(transactionId)\n }\n\n /**\n * Transaction data from the platform client. Decoded data goes through `transformArweaveContent`\n * when a read transform is registered (see `content/arweaveContent.ts`); `decode: false` returns\n * the encoded data as is.\n */\n static async getTransactionData(\n transactionId: string,\n options?: GetDataOptions\n ): Promise<Uint8Array | string> {\n const data = await BaseArweaveClient.requireImpl().getTransactionData(transactionId, options)\n if (options?.decode === false || !hasArweaveContentReadTransform()) {\n return data\n }\n const isString = typeof data === 'string'\n const { bytes } = await transformArweaveContent(\n { bytes: isString ? new TextEncoder().encode(data) : data },\n { transactionId },\n )\n return isString ? new TextDecoder().decode(bytes) : bytes\n }\n\n static getTransactionTags(transactionId: string): Promise<TransactionTag[]> {\n return BaseArweaveClient.requireImpl().getTransactionTags(transactionId)\n }\n\n static createTransaction(\n data: string | Uint8Array,\n options?: CreateTransactionOptions\n ): Promise<ArweaveTransaction> {\n return BaseArweaveClient.requireImpl().createTransaction(data, options)\n }\n\n static downloadFiles(params: DownloadFilesParams): Promise<DownloadResult[]> {\n return BaseArweaveClient.requireImpl().downloadFiles(params)\n }\n}\n","/**\n * Process-wide circuit breaker for Arweave gateway hosts.\n *\n * After consecutive failures, a host is \"open\" for a cooldown and skipped by\n * probes / metadata fetches. After the cooldown it becomes half-open (one probe\n * allowed). Success closes the circuit.\n */\n\nexport type GatewayCircuitState = 'closed' | 'open' | 'half-open'\n\ntype HostCircuit = {\n failures: number\n openedAt: number | null\n /** When half-open, only one probe may run at a time. */\n halfOpenProbeInFlight: boolean\n}\n\nconst DEFAULT_FAILURE_THRESHOLD = 1\nconst DEFAULT_OPEN_MS = 60_000\n\nlet failureThreshold = DEFAULT_FAILURE_THRESHOLD\nlet openDurationMs = DEFAULT_OPEN_MS\nconst circuits = new Map<string, HostCircuit>()\n\n/** Strip scheme / trailing slash; lowercase host (+ optional port/path). */\nexport function normalizeGatewayHostKey(hostOrUrl: string): string {\n let t = hostOrUrl.trim()\n if (!t) return ''\n if (t.startsWith('http://')) t = t.slice(7)\n else if (t.startsWith('https://')) t = t.slice(8)\n return t.replace(/\\/$/, '').toLowerCase()\n}\n\nfunction getOrCreate(key: string): HostCircuit {\n let c = circuits.get(key)\n if (!c) {\n c = { failures: 0, openedAt: null, halfOpenProbeInFlight: false }\n circuits.set(key, c)\n }\n return c\n}\n\nfunction resolveState(c: HostCircuit, now: number): GatewayCircuitState {\n if (c.openedAt == null) return 'closed'\n if (now - c.openedAt >= openDurationMs) return 'half-open'\n return 'open'\n}\n\n/**\n * Configure failure threshold and open-state duration (mainly for tests).\n */\nexport function configureGatewayCircuitBreaker(options: {\n failureThreshold?: number\n openDurationMs?: number\n}): void {\n if (options.failureThreshold != null && options.failureThreshold >= 1) {\n failureThreshold = options.failureThreshold\n }\n if (options.openDurationMs != null && options.openDurationMs >= 0) {\n openDurationMs = options.openDurationMs\n }\n}\n\n/** Clears all host circuits and restores default thresholds (for tests). */\nexport function resetGatewayCircuitBreakerForTests(): void {\n circuits.clear()\n failureThreshold = DEFAULT_FAILURE_THRESHOLD\n openDurationMs = DEFAULT_OPEN_MS\n}\n\n/**\n * True when the host should not receive new requests (open), or a half-open\n * probe is already in flight.\n */\nexport function isGatewayHostCircuitOpen(hostOrUrl: string, now = Date.now()): boolean {\n const key = normalizeGatewayHostKey(hostOrUrl)\n if (!key) return false\n const c = circuits.get(key)\n if (!c) return false\n const state = resolveState(c, now)\n if (state === 'open') return true\n if (state === 'half-open' && c.halfOpenProbeInFlight) return true\n return false\n}\n\nexport function getGatewayHostCircuitState(\n hostOrUrl: string,\n now = Date.now(),\n): GatewayCircuitState {\n const key = normalizeGatewayHostKey(hostOrUrl)\n if (!key) return 'closed'\n const c = circuits.get(key)\n if (!c) return 'closed'\n return resolveState(c, now)\n}\n\n/**\n * Mark that a probe/request is starting against a half-open host so concurrent\n * callers skip it. No-op when closed or fully open.\n */\nexport function beginGatewayHostHalfOpenProbe(hostOrUrl: string, now = Date.now()): void {\n const key = normalizeGatewayHostKey(hostOrUrl)\n if (!key) return\n const c = getOrCreate(key)\n if (resolveState(c, now) === 'half-open') {\n c.halfOpenProbeInFlight = true\n }\n}\n\n/**\n * End a half-open probe that gave no answer (the caller aborted it) without recording a result, so\n * the next caller may probe the host.\n */\nexport function cancelGatewayHostHalfOpenProbe(hostOrUrl: string): void {\n const key = normalizeGatewayHostKey(hostOrUrl)\n const c = key ? circuits.get(key) : undefined\n if (c) c.halfOpenProbeInFlight = false\n}\n\nexport function recordGatewayHostSuccess(hostOrUrl: string): void {\n const key = normalizeGatewayHostKey(hostOrUrl)\n if (!key) return\n circuits.set(key, { failures: 0, openedAt: null, halfOpenProbeInFlight: false })\n}\n\nexport function recordGatewayHostFailure(hostOrUrl: string, now = Date.now()): void {\n const key = normalizeGatewayHostKey(hostOrUrl)\n if (!key) return\n const c = getOrCreate(key)\n c.failures += 1\n c.halfOpenProbeInFlight = false\n if (c.failures >= failureThreshold) {\n c.openedAt = now\n }\n}\n\n/** Hosts currently in open (or half-open with in-flight) state. */\nexport function listOpenGatewayCircuitHosts(now = Date.now()): string[] {\n const out: string[] = []\n for (const key of circuits.keys()) {\n if (isGatewayHostCircuitOpen(key, now)) out.push(key)\n }\n return out\n}\n","import { BaseArweaveClient } from './BaseArweaveClient.js'\nimport {\n DEFAULT_ARWEAVE_HOST,\n getArweaveReadGatewayHostsForPrimary,\n} from '../constants.js'\nimport {\n beginGatewayHostHalfOpenProbe,\n cancelGatewayHostHalfOpenProbe,\n isGatewayHostCircuitOpen,\n recordGatewayHostFailure,\n recordGatewayHostSuccess,\n resetGatewayCircuitBreakerForTests,\n} from '../gateway/gatewayCircuitBreaker.js'\n\nconst READ_GATEWAY_CACHE_TTL_MS = 3 * 60 * 1000\n/** Shorter TTL when no gateway passed the probe — avoid hammering while still recovering sooner. */\nconst READ_GATEWAY_UNHEALTHY_CACHE_TTL_MS = 60 * 1000\nconst PROBE_TIMEOUT_MS = 5000\n\ntype ReadGatewayCache = {\n host: string\n /** False when the last probe found no healthy gateway. */\n healthy: boolean\n expiresAt: number\n}\n\nlet readGatewayCache: ReadGatewayCache | null = null\nlet ensureInFlight: Promise<string> | null = null\n/** Last host that successfully passed /info (survives an all-fail probe cycle). */\nlet lastHealthyReadGatewayHost: string | null = null\n\n/** Clears cached read gateway (e.g. after tests or to force a fresh probe). */\nexport function invalidateReadGatewayCache(): void {\n readGatewayCache = null\n ensureInFlight = null\n}\n\n/** Clears probe cache, env override suppression, and preferred host (for tests). */\nexport function resetArweaveReadGatewayForTests(): void {\n invalidateReadGatewayCache()\n lastHealthyReadGatewayHost = null\n resetGatewayCircuitBreakerForTests()\n BaseArweaveClient.resetReadGatewaySelectionStateForTests()\n if (!BaseArweaveClient.isReadGatewayLocked()) {\n BaseArweaveClient.setPreferredReadGateway(DEFAULT_ARWEAVE_HOST)\n }\n}\n\n/**\n * True when the last {@link ensureReadGatewaySelected} probe found a healthy host\n * (or the cache still says so). False after an all-fail probe until the next success.\n */\nexport function isReadGatewayKnownHealthy(): boolean {\n if (BaseArweaveClient.isReadGatewayLocked()) return true\n if (readGatewayCache && Date.now() < readGatewayCache.expiresAt) {\n return readGatewayCache.healthy\n }\n return lastHealthyReadGatewayHost != null\n}\n\n/** Last gateway host that passed /info, if any. */\nexport function getLastHealthyReadGatewayHost(): string | null {\n return lastHealthyReadGatewayHost\n}\n\nexport type ProbeGatewayOptions = {\n /** Aborts the probe. A probe the caller aborts resolves false and isn't counted as a failure. */\n signal?: AbortSignal\n /** Gives up (and counts a failure) after this long, with or without `signal`. Default 5 s. */\n timeoutMs?: number\n /**\n * Record the result in the gateway circuit breaker, and skip a host whose circuit is open.\n * Default true. Pass false for a status check that shouldn't change which gateways reads use.\n */\n recordCircuit?: boolean\n}\n\n/** GET /info. Healthy when it answers 2xx with a JSON object. */\nexport async function probeGateway(\n baseUrl: string,\n options: ProbeGatewayOptions = {},\n): Promise<boolean> {\n if (options instanceof AbortSignal) {\n throw new TypeError('probeGateway takes options: pass { signal }, not an AbortSignal')\n }\n const { signal, timeoutMs = PROBE_TIMEOUT_MS, recordCircuit = true } = options\n const url = `${baseUrl.replace(/\\/$/, '')}/info`\n let hostKey = baseUrl\n try {\n hostKey = new URL(baseUrl.includes('://') ? baseUrl : `https://${baseUrl}`).host\n } catch {\n hostKey = baseUrl.replace(/^https?:\\/\\//, '').replace(/\\/$/, '')\n }\n\n if (recordCircuit) {\n if (isGatewayHostCircuitOpen(hostKey)) return false\n beginGatewayHostHalfOpenProbe(hostKey)\n }\n const record = (healthy: boolean): boolean => {\n if (recordCircuit) {\n if (healthy) recordGatewayHostSuccess(hostKey)\n else recordGatewayHostFailure(hostKey)\n }\n return healthy\n }\n const callerAborted = (): boolean => {\n if (recordCircuit) cancelGatewayHostHalfOpenProbe(hostKey)\n return false\n }\n if (signal?.aborted) return callerAborted()\n\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n const onAbort = () => controller.abort(signal?.reason)\n signal?.addEventListener('abort', onAbort, { once: true })\n try {\n const response = await fetch(url, {\n method: 'GET',\n signal: controller.signal,\n headers: { Accept: 'application/json' },\n })\n if (!response.ok) return record(false)\n const text = await response.text()\n if (!text.trim()) return record(false)\n try {\n const json = JSON.parse(text) as unknown\n return record(typeof json === 'object' && json !== null)\n } catch {\n return record(false)\n }\n } catch {\n if (signal?.aborted) return callerAborted()\n return record(false)\n } finally {\n clearTimeout(timer)\n signal?.removeEventListener('abort', onAbort)\n }\n}\n\nexport async function selectFirstHealthyReadGateway(\n hosts: string[],\n protocol: 'http' | 'https' = 'https',\n signal?: AbortSignal,\n): Promise<string | null> {\n for (const host of hosts) {\n const h = host.trim().replace(/\\/$/, '')\n if (!h) continue\n if (isGatewayHostCircuitOpen(h)) continue\n const baseUrl = `${protocol}://${h}`\n if (await probeGateway(baseUrl, { signal })) {\n return h\n }\n }\n return null\n}\n\nfunction buildOrderedHostsForProbe(): string[] {\n return getArweaveReadGatewayHostsForPrimary(BaseArweaveClient.getHost())\n}\n\n/**\n * Probes gateways in order and applies the first healthy host via {@link BaseArweaveClient.applyProbedReadGateway}.\n * No-op when the read gateway is locked ({@link BaseArweaveClient.setHost}).\n * Uses a short TTL cache to avoid probing on every read.\n *\n * When every probe fails, keeps the last known healthy host (if any) instead of\n * treating the preferred-but-unreachable host as selected, and caches\n * `healthy: false` so {@link isReadGatewayKnownHealthy} reflects that. When `signal` aborts before a\n * host passes, nothing is cached and it returns the last healthy host (else the current one).\n */\nexport async function ensureReadGatewaySelected(signal?: AbortSignal): Promise<string> {\n if (BaseArweaveClient.isReadGatewayLocked()) {\n return BaseArweaveClient.getHost()\n }\n\n const now = Date.now()\n if (readGatewayCache && now < readGatewayCache.expiresAt) {\n return readGatewayCache.host\n }\n\n if (ensureInFlight) {\n return ensureInFlight\n }\n\n ensureInFlight = (async () => {\n const ordered = buildOrderedHostsForProbe()\n const protocol = BaseArweaveClient.getProtocol()\n const picked = await selectFirstHealthyReadGateway(ordered, protocol, signal)\n\n // An aborted probe says nothing about the gateways: keep the cache and host as they were.\n if (!picked && signal?.aborted) {\n return lastHealthyReadGatewayHost ?? BaseArweaveClient.getHost()\n }\n\n if (!BaseArweaveClient.isReadGatewayLocked()) {\n if (picked) {\n BaseArweaveClient.applyProbedReadGateway(picked)\n lastHealthyReadGatewayHost = picked\n readGatewayCache = {\n host: picked,\n healthy: true,\n expiresAt: Date.now() + READ_GATEWAY_CACHE_TTL_MS,\n }\n } else {\n const fallback = lastHealthyReadGatewayHost ?? BaseArweaveClient.getHost()\n if (\n lastHealthyReadGatewayHost &&\n BaseArweaveClient.getHost() !== lastHealthyReadGatewayHost\n ) {\n BaseArweaveClient.applyProbedReadGateway(lastHealthyReadGatewayHost)\n }\n readGatewayCache = {\n host: fallback,\n healthy: false,\n expiresAt: Date.now() + READ_GATEWAY_UNHEALTHY_CACHE_TTL_MS,\n }\n }\n } else {\n readGatewayCache = {\n host: BaseArweaveClient.getHost(),\n healthy: true,\n expiresAt: Date.now() + READ_GATEWAY_CACHE_TTL_MS,\n }\n }\n\n return readGatewayCache.host\n })()\n\n try {\n return await ensureInFlight\n } finally {\n ensureInFlight = null\n }\n}\n","import { probeGateway } from '../ArweaveClient/selectReadGateway.js'\nimport {\n DEFAULT_ARWEAVE_HOST,\n DEFAULT_GATEWAY_SIDECAR_HOST,\n DEFAULT_GATEWAY_SIDECAR_PORT,\n getArweaveReadGatewayHostsForPrimary,\n} from '../constants.js'\nimport type {\n ResolvedSeedGatewayEndpoints,\n SeedGatewayConfig,\n SeedGatewayTransportMode,\n} from '../types/gateway.js'\n\nconst PROBE_TTL_MS = 3 * 60 * 1000\n/** A failed probe is retried sooner, like the read gateway selector's unhealthy result. */\nconst PROBE_FAILURE_TTL_MS = 60 * 1000\n\nlet sidecarProbeCache: { healthy: boolean; expiresAt: number } | null = null\nconst proxyProbeCache = new Map<string, { healthy: boolean; expiresAt: number }>()\n\n/** Clears cached sidecar / proxy probes (tests / forced re-probe). */\nexport function invalidateSidecarProbeCache(): void {\n sidecarProbeCache = null\n proxyProbeCache.clear()\n}\n\nfunction parseGatewayHost(input: string | undefined): { host: string; protocol: 'http' | 'https' } {\n // An empty arweaveDomain means the default, not `https://`\n const raw = input?.trim() || DEFAULT_ARWEAVE_HOST\n if (raw.startsWith('http://')) {\n return { protocol: 'http', host: raw.slice(7).replace(/\\/$/, '') }\n }\n if (raw.startsWith('https://')) {\n return { protocol: 'https', host: raw.slice(8).replace(/\\/$/, '') }\n }\n return { protocol: 'https', host: raw.replace(/\\/$/, '') }\n}\n\nfunction publicArweaveBaseUrl(config: SeedGatewayConfig): string {\n const { host, protocol } = parseGatewayHost(config.arweaveDomain)\n return `${protocol}://${host}`\n}\n\n/**\n * The local Hyper sidecar's address from `hyper.localSidecarHost` and `hyper.localSidecarPort`,\n * else the defaults. `host` leaves out port 80 and 443; `baseUrl` always has the port.\n */\nexport function resolveSidecarOrigin(config: SeedGatewayConfig): {\n host: string\n port: number\n baseUrl: string\n} {\n const host = config.hyper?.localSidecarHost?.trim() || DEFAULT_GATEWAY_SIDECAR_HOST\n const port = config.hyper?.localSidecarPort ?? DEFAULT_GATEWAY_SIDECAR_PORT\n const hostWithPort = port === 80 || port === 443 ? host : `${host}:${port}`\n return {\n host: hostWithPort,\n port,\n baseUrl: `http://${host}:${port}`,\n }\n}\n\nfunction browserOrigin(): string | undefined {\n try {\n const g = globalThis as { window?: { location?: { origin?: string } } }\n const origin = g.window?.location?.origin\n return typeof origin === 'string' && origin.length > 0 ? origin.replace(/\\/$/, '') : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Resolve `proxyBaseUrl` to an absolute origin+path (no trailing slash).\n * Relative paths require a browser `window.location.origin` or {@link ResolveSeedGatewayEndpointsOptions.origin}.\n */\nexport function resolveProxyBaseUrl(\n proxyBaseUrl: string,\n options?: { origin?: string },\n): string {\n const raw = proxyBaseUrl.trim()\n if (!raw) {\n throw new Error('proxyBaseUrl is empty')\n }\n if (raw.startsWith('http://') || raw.startsWith('https://')) {\n return raw.replace(/\\/$/, '')\n }\n if (raw.startsWith('/')) {\n const origin = (options?.origin?.trim() || browserOrigin() || '').replace(/\\/$/, '')\n if (!origin) {\n throw new Error(\n `Relative proxyBaseUrl \"${proxyBaseUrl}\" requires a browser origin or resolve options.origin`,\n )\n }\n return `${origin}${raw.replace(/\\/$/, '')}`\n }\n return `https://${raw.replace(/\\/$/, '')}`\n}\n\n/**\n * Probes `baseUrl`, cached per `cacheKey`: a healthy result for 3 minutes, a failure for 60 s. A\n * probe cut short by `signal` (the caller or the resolve's `timeoutMs`) is not cached.\n */\nasync function probeUrlHealthy(\n baseUrl: string,\n cacheKey: 'sidecar' | string,\n signal?: AbortSignal,\n): Promise<boolean> {\n const now = Date.now()\n const cached = cacheKey === 'sidecar' ? sidecarProbeCache : proxyProbeCache.get(cacheKey)\n if (cached && now < cached.expiresAt) {\n return cached.healthy\n }\n const healthy = await probeGateway(baseUrl, { signal })\n if (!healthy && signal?.aborted) return false\n const entry = { healthy, expiresAt: now + (healthy ? PROBE_TTL_MS : PROBE_FAILURE_TTL_MS) }\n if (cacheKey === 'sidecar') sidecarProbeCache = entry\n else proxyProbeCache.set(cacheKey, entry)\n return healthy\n}\n\nfunction buildHttpEndpoints(config: SeedGatewayConfig): ResolvedSeedGatewayEndpoints {\n const { host, protocol } = parseGatewayHost(config.arweaveDomain)\n const baseUrl = `${protocol}://${host}`\n // A public gateway doesn't serve the upload API: unset stays unset (''), not the gateway's URL.\n const uploadApiBaseUrl = config.uploadApiBaseUrl?.trim() ?? ''\n return {\n mode: config.transport ?? 'http-gateway',\n arweaveHost: host,\n arweaveProtocol: protocol,\n arweaveBaseUrl: baseUrl,\n arweaveGraphqlUrl: `${protocol}://${host}/graphql`,\n uploadApiBaseUrl,\n activePath: 'http',\n gatewayHyperKey: config.hyper?.gatewayHyperKey?.trim() || undefined,\n publicArweaveBaseUrl: baseUrl,\n }\n}\n\nfunction buildHyperEndpoints(config: SeedGatewayConfig): ResolvedSeedGatewayEndpoints {\n const sidecar = resolveSidecarOrigin(config)\n const key = config.hyper?.gatewayHyperKey?.trim()\n return {\n mode: 'hyper',\n arweaveHost: sidecar.host,\n arweaveProtocol: 'http',\n arweaveBaseUrl: sidecar.baseUrl,\n arweaveGraphqlUrl: `${sidecar.baseUrl}/graphql`,\n uploadApiBaseUrl: sidecar.baseUrl,\n activePath: 'hyper-sidecar',\n gatewayHyperKey: key || undefined,\n publicArweaveBaseUrl: publicArweaveBaseUrl(config),\n }\n}\n\nfunction buildProxyEndpoints(\n config: SeedGatewayConfig,\n absoluteProxyBaseUrl: string,\n): ResolvedSeedGatewayEndpoints {\n const parsed = new URL(absoluteProxyBaseUrl)\n const protocol: 'http' | 'https' = parsed.protocol === 'http:' ? 'http' : 'https'\n const path = parsed.pathname.replace(/\\/$/, '')\n const hostWithPath = path ? `${parsed.host}${path}` : parsed.host\n const baseUrl = `${protocol}://${hostWithPath}`\n return {\n mode: config.transport ?? 'http-gateway',\n arweaveHost: hostWithPath,\n arweaveProtocol: protocol,\n arweaveBaseUrl: baseUrl,\n arweaveGraphqlUrl: `${baseUrl}/graphql`,\n uploadApiBaseUrl: baseUrl,\n activePath: 'http-proxy',\n gatewayHyperKey: config.hyper?.gatewayHyperKey?.trim() || undefined,\n proxyBaseUrl: absoluteProxyBaseUrl,\n publicArweaveBaseUrl: publicArweaveBaseUrl(config),\n }\n}\n\nfunction shouldProbeProxy(config: SeedGatewayConfig): boolean {\n return (config.hyper?.probeProxy ?? config.hyper?.probeSidecar) !== false\n}\n\nconst LOOPBACK_HOSTNAME = /^(localhost|127(?:\\.\\d{1,3}){3}|\\[::1\\]|::1)$|\\.localhost$/i\n\n/**\n * Whether `hybrid` may try the local sidecar here: outside a browser, from a loopback page, or\n * with `hyper.probeSidecarFromBrowser`.\n */\nfunction sidecarReachableFromHere(config: SeedGatewayConfig, origin: string | undefined): boolean {\n if (config.hyper?.probeSidecarFromBrowser) return true\n const browserWindow = (globalThis as { window?: { location?: { origin?: string } } }).window\n if (!browserWindow) return true\n const pageOrigin = origin ?? browserWindow.location?.origin\n if (!pageOrigin) return true\n try {\n return LOOPBACK_HOSTNAME.test(new URL(pageOrigin).hostname)\n } catch {\n return false\n }\n}\n\nexport type ResolveSeedGatewayEndpointsOptions = {\n signal?: AbortSignal\n /**\n * Time allowed for all of this resolve's probes together. A probe still running when it runs out\n * counts as unreachable for this resolve only: it isn't cached or recorded in the circuit breaker.\n * Each probe also times out on its own after 5 s.\n */\n timeoutMs?: number\n /** Skip cache and probe sidecar / proxy again. */\n forceSidecarProbe?: boolean\n /**\n * Origin used to resolve relative `proxyBaseUrl` (e.g. `https://app.example.com`).\n * Defaults to `window.location.origin` in browsers.\n */\n origin?: string\n}\n\nasync function tryProxyEndpoints(\n config: SeedGatewayConfig,\n options?: ResolveSeedGatewayEndpointsOptions,\n): Promise<ResolvedSeedGatewayEndpoints | null> {\n const raw = config.proxyBaseUrl?.trim()\n if (!raw) return null\n\n const absolute = resolveProxyBaseUrl(raw, { origin: options?.origin })\n if (shouldProbeProxy(config)) {\n const ok = await probeUrlHealthy(absolute, `proxy:${absolute}`, options?.signal)\n if (!ok) return null\n }\n return buildProxyEndpoints(config, absolute)\n}\n\n/**\n * Resolve effective gateway + upload API URLs for the configured transport mode.\n *\n * Preference when a proxy and/or sidecar may apply:\n * configured + healthy `proxyBaseUrl` → local Hyper sidecar → public HTTP gateway.\n */\nexport async function resolveSeedGatewayEndpoints(\n config: SeedGatewayConfig,\n options?: ResolveSeedGatewayEndpointsOptions,\n): Promise<ResolvedSeedGatewayEndpoints> {\n if (options?.forceSidecarProbe) {\n invalidateSidecarProbeCache()\n }\n if (options?.timeoutMs === undefined) return resolveEndpoints(config, options)\n\n const budget = new AbortController()\n const timer = setTimeout(() => budget.abort(), options.timeoutMs)\n const callerSignal = options.signal\n const onAbort = () => budget.abort(callerSignal?.reason)\n if (callerSignal?.aborted) onAbort()\n else callerSignal?.addEventListener('abort', onAbort, { once: true })\n try {\n return await resolveEndpoints(config, { ...options, signal: budget.signal })\n } finally {\n clearTimeout(timer)\n callerSignal?.removeEventListener('abort', onAbort)\n }\n}\n\nasync function resolveEndpoints(\n config: SeedGatewayConfig,\n options?: ResolveSeedGatewayEndpointsOptions,\n): Promise<ResolvedSeedGatewayEndpoints> {\n\n const mode: SeedGatewayTransportMode = config.transport ?? 'http-gateway'\n const shouldProbe = config.hyper?.probeSidecar !== false\n\n if (mode === 'http-gateway') {\n if (config.proxyBaseUrl?.trim()) {\n const absolute = resolveProxyBaseUrl(config.proxyBaseUrl, { origin: options?.origin })\n if (shouldProbeProxy(config)) {\n const ok = await probeUrlHealthy(absolute, `proxy:${absolute}`, options?.signal)\n if (!ok) {\n throw new Error(\n `Gateway HTTP proxy not reachable at ${absolute}. ` +\n 'Ensure your Node route runs createGatewayProxy (or equivalent) and mounts at proxyBaseUrl.',\n )\n }\n }\n return buildProxyEndpoints({ ...config, transport: mode }, absolute)\n }\n return buildHttpEndpoints({ ...config, transport: mode })\n }\n\n if (mode === 'hyper') {\n const proxy = await tryProxyEndpoints({ ...config, transport: mode }, options)\n if (proxy) return proxy\n\n const hyperEndpoints = buildHyperEndpoints({ ...config, transport: mode })\n if (shouldProbe) {\n const ok = await probeUrlHealthy(hyperEndpoints.arweaveBaseUrl, 'sidecar', options?.signal)\n if (!ok) {\n throw new Error(\n `Gateway Hyper sidecar not reachable at ${hyperEndpoints.arweaveBaseUrl}. ` +\n 'Run: seed-gateway connect <operator-z32-key> — or configure gateway.proxyBaseUrl for an app-server proxy.',\n )\n }\n }\n return hyperEndpoints\n }\n\n // hybrid: proxy → sidecar → public HTTP. The sidecar is skipped on a public web page.\n const proxy = await tryProxyEndpoints({ ...config, transport: mode }, options)\n if (proxy) return proxy\n\n const sidecar = resolveSidecarOrigin(config)\n if (\n shouldProbe &&\n sidecarReachableFromHere(config, options?.origin) &&\n (await probeUrlHealthy(sidecar.baseUrl, 'sidecar', options?.signal))\n ) {\n return buildHyperEndpoints({ ...config, transport: 'hyper' })\n }\n\n const http = buildHttpEndpoints({ ...config, transport: 'http-gateway' })\n return {\n ...http,\n mode: 'hybrid',\n activePath: 'hybrid-fallback-http',\n }\n}\n\n/**\n * Ordered read gateways. With a sidecar or proxy active it comes first, as its base URL, followed by\n * the public gateway and the default list as `https://` URLs, so reads (and links re-hosted for\n * this reader, ADR 0025) still have public fallbacks when it is down. Otherwise hosts without a\n * scheme, the active one first.\n */\nexport function getReadGatewayHostsForConfig(\n resolved: ResolvedSeedGatewayEndpoints,\n _defaults?: readonly string[],\n): string[] {\n if (resolved.activePath === 'hyper-sidecar' || resolved.activePath === 'http-proxy') {\n const publicBase = new URL(resolved.publicArweaveBaseUrl)\n const publicHosts = getArweaveReadGatewayHostsForPrimary(publicBase.host).map((host, index) =>\n index === 0 ? `${publicBase.protocol}//${host}` : `https://${host}`,\n )\n return [resolved.arweaveBaseUrl, ...publicHosts]\n }\n return getArweaveReadGatewayHostsForPrimary(resolved.arweaveHost)\n}\n","import type { ResolvedSeedGatewayEndpoints } from '../types/gateway.js'\nimport { resolveProxyBaseUrl } from './resolveSeedGatewayEndpoints.js'\n\nlet resolvedGatewayEndpoints: ResolvedSeedGatewayEndpoints | null = null\n\n/** Last endpoints applied during client init (for read-path helpers). */\nexport function getResolvedSeedGatewayEndpoints(): ResolvedSeedGatewayEndpoints | null {\n return resolvedGatewayEndpoints\n}\n\nexport function setResolvedSeedGatewayEndpoints(\n value: ResolvedSeedGatewayEndpoints | null,\n): void {\n resolvedGatewayEndpoints = value\n}\n\nlet preferredReadBaseUrls: string[] = []\n\n/**\n * Gateways tried before the resolved / public hosts for `/raw/{id}` reads — typically the gateway\n * the app uploads through (Hyper sidecar or app-server proxy), which serves data items before they\n * reach L1 or the public gateways. Does not affect upload, GraphQL or {@link BaseArweaveClient} host.\n */\nexport function getPreferredArweaveReadBaseUrls(): string[] {\n return preferredReadBaseUrls\n}\n\n/**\n * Replace the preferred read gateways. Each entry is a base URL with scheme and any path prefix\n * (`https://app.example.com/api/seed-gateway`); same-origin relative paths (`/api/seed-gateway`)\n * resolve against `window.location.origin` and are dropped when there is no origin. Pass `[]` to clear.\n */\nexport function setPreferredArweaveReadBaseUrls(urls: readonly string[]): void {\n const out: string[] = []\n const seen = new Set<string>()\n for (const raw of urls) {\n const trimmed = raw?.trim()\n if (!trimmed) continue\n let url: string\n try {\n // URL lowercases scheme and host; the path stays case-sensitive.\n const parsed = new URL(/^https?:\\/\\//i.test(trimmed) ? trimmed : resolveProxyBaseUrl(trimmed))\n url = `${parsed.origin}${parsed.pathname.replace(/\\/+$/, '')}`\n } catch {\n continue\n }\n if (seen.has(url)) continue\n seen.add(url)\n out.push(url)\n }\n preferredReadBaseUrls = out\n}\n","import { BaseArweaveClient } from '../ArweaveClient/BaseArweaveClient.js'\nimport { ensureReadGatewaySelected } from '../ArweaveClient/selectReadGateway.js'\nimport { getArweaveReadGatewayHostsForPrimary } from '../constants.js'\nimport { getPreferredArweaveReadBaseUrls, getResolvedSeedGatewayEndpoints } from './gatewayState.js'\nimport { getReadGatewayHostsForConfig } from './resolveSeedGatewayEndpoints.js'\nimport { isEncryptedArweaveContent, readArweaveContentResponse } from '../content/arweaveContent.js'\n\n/** Per-gateway timeout for {@link fetchArweaveRawFromBaseUrl}; a hung gateway must not block the next one. */\nexport const DEFAULT_ARWEAVE_RAW_READ_TIMEOUT_MS = 10_000\n\nexport type ArweaveReadBaseUrlOptions = {\n /** Hosts (no scheme) used when no gateway endpoints have been resolved, e.g. a feed's own list. */\n fallbackHosts?: readonly string[]\n}\n\nfunction pushUnique(out: string[], seen: Set<string>, url: string): void {\n const u = url.trim().replace(/\\/$/, '')\n if (!u || seen.has(u)) return\n seen.add(u)\n out.push(u)\n}\n\n/**\n * Resolved / public read gateways as base URLs (scheme + host + any path prefix), without the\n * preferred ones. Does not probe.\n */\nexport function getResolvedArweaveReadBaseUrls(options?: ArweaveReadBaseUrlOptions): string[] {\n const resolved = getResolvedSeedGatewayEndpoints()\n const protocol = BaseArweaveClient.getProtocol()\n const hosts = resolved\n ? getReadGatewayHostsForConfig(resolved)\n : options?.fallbackHosts?.length\n ? [...options.fallbackHosts]\n : getArweaveReadGatewayHostsForPrimary(BaseArweaveClient.getHost())\n\n const out: string[] = []\n const seen = new Set<string>()\n for (const host of hosts) {\n const h = host.trim()\n if (!h) continue\n pushUnique(out, seen, /^https?:\\/\\//i.test(h) ? h : `${protocol}://${h}`)\n }\n return out\n}\n\n/**\n * Ordered base URLs for `/raw/{id}` (and `/{id}`) reads: preferred gateways\n * ({@link setPreferredArweaveReadBaseUrls}) first, then the resolved / public gateways. Does not probe.\n */\nexport function getArweaveReadBaseUrls(options?: ArweaveReadBaseUrlOptions): string[] {\n const out: string[] = []\n const seen = new Set<string>()\n for (const url of getPreferredArweaveReadBaseUrls()) pushUnique(out, seen, url)\n for (const url of getResolvedArweaveReadBaseUrls(options)) pushUnique(out, seen, url)\n return out\n}\n\n/** Run the read-gateway probe unless a sidecar / proxy is already the active path. Never throws. */\nexport async function ensureArweaveReadGatewayForFallback(): Promise<void> {\n try {\n const resolved = getResolvedSeedGatewayEndpoints()\n if (resolved && (resolved.activePath === 'hyper-sidecar' || resolved.activePath === 'http-proxy')) {\n return\n }\n await ensureReadGatewaySelected()\n } catch {\n /* optional — fall through to the current host */\n }\n}\n\n/**\n * What one gateway answered to `/raw/{id}`: the HTTP status, `'timeout'` (our abort fired),\n * `'network'` (fetch threw; a browser reports a CORS-blocked answer this way, without its status),\n * `'empty'` (2xx with no bytes) or `'unreadable'` (2xx whose body or read transform failed).\n */\nexport type ArweaveRawReadOutcome = number | 'timeout' | 'network' | 'empty' | 'unreadable'\n\nexport type ArweaveRawReadAttempt = { baseUrl: string; outcome: ArweaveRawReadOutcome }\n\n/** GET `{baseUrl}/raw/{id}`. `response` is set only for a 2xx answer. */\nexport async function fetchArweaveRawFromBaseUrl(\n baseUrl: string,\n transactionId: string,\n options?: { timeoutMs?: number },\n): Promise<ArweaveRawReadAttempt & { response?: Response }> {\n const base = baseUrl.replace(/\\/$/, '')\n const controller = new AbortController()\n const timer = setTimeout(\n () => controller.abort(),\n options?.timeoutMs ?? DEFAULT_ARWEAVE_RAW_READ_TIMEOUT_MS,\n )\n try {\n const res = await fetch(`${base}/raw/${encodeURIComponent(transactionId)}`, {\n method: 'GET',\n credentials: 'omit',\n signal: controller.signal,\n })\n return res.ok\n ? { baseUrl: base, outcome: res.status, response: res }\n : { baseUrl: base, outcome: res.status }\n } catch {\n return { baseUrl: base, outcome: controller.signal.aborted ? 'timeout' : 'network' }\n } finally {\n clearTimeout(timer)\n }\n}\n\n/**\n * GET `/raw/{id}` across read gateways, asking each at most once, and return the first non-empty\n * body with what each gateway asked answered. Preferred gateways go first and are tried before any\n * read-gateway probe; a just-published item is served by the gateway it was uploaded through well\n * before it reaches L1 or the public hosts. The configured host (`BaseArweaveClient.getBaseUrl()`)\n * goes last when the resolved list leaves it out.\n * The body goes through `transformArweaveContent` (see `content/arweaveContent.ts`); `decode: false`\n * returns the transaction's bytes as stored, as `getTransactionData` does.\n */\nexport async function readArweaveRawAcrossGateways(\n transactionId: string,\n options?: ArweaveReadBaseUrlOptions & { timeoutMs?: number; decode?: boolean },\n): Promise<{ bytes?: Uint8Array; attempts: ArweaveRawReadAttempt[] }> {\n const attempts: ArweaveRawReadAttempt[] = []\n const tried = new Set<string>()\n const tryUrls = async (urls: string[]): Promise<Uint8Array | undefined> => {\n for (const url of urls) {\n const base = url.trim().replace(/\\/$/, '')\n if (!base || tried.has(base)) continue\n tried.add(base)\n const { response, ...attempt } = await fetchArweaveRawFromBaseUrl(base, transactionId, options)\n if (!response) {\n attempts.push(attempt)\n continue\n }\n try {\n const bytes =\n options?.decode === false\n ? new Uint8Array(await response.arrayBuffer())\n : (await readArweaveContentResponse(response, { transactionId })).bytes\n if (bytes.byteLength > 0) {\n attempts.push(attempt)\n return bytes\n }\n attempts.push({ baseUrl: base, outcome: 'empty' })\n } catch {\n attempts.push({ baseUrl: base, outcome: 'unreadable' })\n }\n }\n return undefined\n }\n\n const preferred = await tryUrls(getPreferredArweaveReadBaseUrls())\n if (preferred) return { bytes: preferred, attempts }\n\n await ensureArweaveReadGatewayForFallback()\n const bytes = await tryUrls([...getResolvedArweaveReadBaseUrls(options), BaseArweaveClient.getBaseUrl()])\n return { bytes, attempts }\n}\n\n/** {@link readArweaveRawAcrossGateways}'s bytes; undefined when no gateway served any. */\nexport async function fetchArweaveRawBytesAcrossGateways(\n transactionId: string,\n options?: ArweaveReadBaseUrlOptions & { timeoutMs?: number; decode?: boolean },\n): Promise<Uint8Array | undefined> {\n return (await readArweaveRawAcrossGateways(transactionId, options)).bytes\n}\n\n/** {@link fetchArweaveRawBytesAcrossGateways} as text; undefined for an encrypted envelope no transform opened. */\nexport async function fetchArweaveRawTextAcrossGateways(\n transactionId: string,\n options?: ArweaveReadBaseUrlOptions & { timeoutMs?: number },\n): Promise<string | undefined> {\n const bytes = await fetchArweaveRawBytesAcrossGateways(transactionId, options)\n if (!bytes || isEncryptedArweaveContent(bytes)) return undefined\n return new TextDecoder().decode(bytes) || undefined\n}\n","/* eslint-disable */\nimport type { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/core';\nexport type Maybe<T> = T | null;\nexport type InputMaybe<T> = T | null | undefined;\nexport type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };\nexport type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };\nexport type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };\nexport type MakeEmpty<T extends { [key: string]: unknown }, K extends keyof T> = { [_ in K]?: never };\nexport type Incremental<T> = T | { [P in keyof T]?: P extends ' $fragmentName' | '__typename' ? T[P] : never };\n/** All built-in and custom scalars, mapped to their actual values */\nexport type Scalars = {\n ID: { input: string; output: string; }\n String: { input: string; output: string; }\n Boolean: { input: boolean; output: boolean; }\n Int: { input: number; output: number; }\n Float: { input: number; output: number; }\n};\n\n/** Representation of a value transfer between wallets, in both winson and ar. */\nexport type Amount = {\n __typename?: 'Amount';\n /** Amount as an AR string e.g. \\`\"0.000000000001\"\\`. */\n ar: Scalars['String']['output'];\n /** Amount as a winston string e.g. \\`\"1000000000000\"\\`. */\n winston: Scalars['String']['output'];\n};\n\n/** Block Schema */\nexport type Block = {\n __typename?: 'Block';\n /** The block height. */\n height: Scalars['Int']['output'];\n /** The block ID. */\n id?: Maybe<Scalars['ID']['output']>;\n /** The previous block ID. */\n previous?: Maybe<Scalars['ID']['output']>;\n /** The block timestamp (UTC). */\n timestamp?: Maybe<Scalars['Int']['output']>;\n};\n\n/**\n * Paginated result set using the GraphQL cursor spec,\n * see: https://relay.dev/graphql/connections.htm.\n */\nexport type BlockConnection = {\n __typename?: 'BlockConnection';\n edges: Array<BlockEdge>;\n pageInfo: PageInfo;\n};\n\n/** Paginated result set using the GraphQL cursor spec. */\nexport type BlockEdge = {\n __typename?: 'BlockEdge';\n /**\n * The cursor value for fetching the next page.\n *\n * Pass this to the after parameter in blocks(after: $cursor), the next page will start from the next item after this.\n */\n cursor: Scalars['String']['output'];\n /** A block object. */\n node: Block;\n};\n\n/**\n * The data bundle containing the current data item.\n * See: https://github.com/ArweaveTeam/arweave-standards/blob/master/ans/ANS-104.md.\n */\nexport type Bundle = {\n __typename?: 'Bundle';\n /** ID of the containing data bundle. */\n id: Scalars['ID']['output'];\n};\n\nexport enum CacheControlScope {\n Private = 'PRIVATE',\n Public = 'PUBLIC'\n}\n\n/** Basic metadata about the transaction data payload. */\nexport type MetaData = {\n __typename?: 'MetaData';\n /** Size of the associated data in bytes. */\n size: Scalars['String']['output'];\n /** Type is derived from the \\`content-type\\` tag on a transaction. */\n type?: Maybe<Scalars['String']['output']>;\n};\n\n/** Representation of a transaction owner. */\nexport type Owner = {\n __typename?: 'Owner';\n /** The owner's wallet address. */\n address: Scalars['String']['output'];\n /** The owner's public key as a base64url encoded string. */\n key: Scalars['String']['output'];\n};\n\n/** Paginated page info using the GraphQL cursor spec. */\nexport type PageInfo = {\n __typename?: 'PageInfo';\n hasNextPage: Scalars['Boolean']['output'];\n};\n\n/**\n * The parent transaction for bundled transactions,\n * see: https://github.com/ArweaveTeam/arweave-standards/blob/master/ans/ANS-102.md.\n */\nexport type Parent = {\n __typename?: 'Parent';\n id: Scalars['ID']['output'];\n};\n\nexport type Query = {\n __typename?: 'Query';\n block?: Maybe<Block>;\n blocks: BlockConnection;\n /** Get a transaction by its id */\n transaction?: Maybe<Transaction>;\n /** Get a paginated set of matching transactions using filters. */\n transactions: TransactionConnection;\n};\n\n\nexport type QueryBlockArgs = {\n id?: InputMaybe<Scalars['String']['input']>;\n};\n\n\nexport type QueryBlocksArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n height?: InputMaybe<RangeFilter>;\n ids?: InputMaybe<Array<Scalars['ID']['input']>>;\n sort?: InputMaybe<SortOrder>;\n};\n\n\nexport type QueryTransactionArgs = {\n id: Scalars['ID']['input'];\n};\n\n\nexport type QueryTransactionsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n block?: InputMaybe<RangeFilter>;\n bundledIn?: InputMaybe<Array<Scalars['ID']['input']>>;\n first?: InputMaybe<Scalars['Int']['input']>;\n ids?: InputMaybe<Array<Scalars['ID']['input']>>;\n ingested_at?: InputMaybe<RangeFilter>;\n owners?: InputMaybe<Array<Scalars['String']['input']>>;\n recipients?: InputMaybe<Array<Scalars['String']['input']>>;\n sort?: InputMaybe<SortOrder>;\n tags?: InputMaybe<Array<TagFilter>>;\n};\n\n/** Filter with a min and max */\nexport type RangeFilter = {\n /** Maximum integer to filter to */\n max?: InputMaybe<Scalars['Int']['input']>;\n /** Minimum integer to filter from */\n min?: InputMaybe<Scalars['Int']['input']>;\n};\n\n/** Optionally reverse the result sort order from `HEIGHT_DESC` (default) to `HEIGHT_ASC`. */\nexport enum SortOrder {\n /** Results are sorted by the transaction block height in ascending order, with the oldest transactions appearing first, and the most recent and pending/unconfirmed appearing last. */\n HeightAsc = 'HEIGHT_ASC',\n /** Results are sorted by the transaction block height in descending order, with the most recent and unconfirmed/pending transactions appearing first. */\n HeightDesc = 'HEIGHT_DESC',\n /** Results are sorted by the transaction ingestion time in ascending order, with the oldest ingested transactions appearing first. */\n IngestedAtAsc = 'INGESTED_AT_ASC',\n /** Results are sorted by the transaction ingestion time in descending order, with the most recently ingested transactions appearing first. */\n IngestedAtDesc = 'INGESTED_AT_DESC'\n}\n\n/** Tag Schema */\nexport type Tag = {\n __typename?: 'Tag';\n /** UTF-8 tag name */\n name: Scalars['String']['output'];\n /** UTF-8 tag value */\n value: Scalars['String']['output'];\n};\n\n/** Find transactions with the following tag name and value */\nexport type TagFilter = {\n /** How tag names and values are matched. Defaults to EXACT. */\n match?: TagMatch;\n /** The tag name */\n name?: InputMaybe<Scalars['String']['input']>;\n /** The operator to apply to to the tag filter. Defaults to EQ (equal). */\n op?: TagOperator;\n /**\n * An array of values to match against. If multiple values are passed then transactions with _any_ matching tag value from the set will be returned.\n *\n * e.g.\n *\n * `{name: \"app-name\", values: [\"app-1\"]}`\n *\n * Returns all transactions where the `app-name` tag has a value of `app-1`.\n *\n * `{name: \"app-name\", values: [\"app-1\", \"app-2\", \"app-3\"]}`\n *\n * Returns all transactions where the `app-name` tag has a value of either `app-1` _or_ `app-2` _or_ `app-3`.\n */\n values?: InputMaybe<Array<Scalars['String']['input']>>;\n};\n\n/** The method used to determine if tags match. */\nexport enum TagMatch {\n /** An exact match */\n Exact = 'EXACT',\n /** Fuzzy match containing all search terms */\n FuzzyAnd = 'FUZZY_AND',\n /** Fuzzy match containing at least one search term */\n FuzzyOr = 'FUZZY_OR',\n /** A wildcard match */\n Wildcard = 'WILDCARD'\n}\n\n/** The operator to apply to a tag value. */\nexport enum TagOperator {\n /** Equal */\n Eq = 'EQ',\n /** Not equal */\n Neq = 'NEQ'\n}\n\n/** Transaction Structure */\nexport type Transaction = {\n __typename?: 'Transaction';\n anchor: Scalars['String']['output'];\n /** Transactions with a null block are recent and unconfirmed, if they aren't mined into a block within 60 minutes they will be removed from results. */\n block?: Maybe<Block>;\n /**\n * For bundled data items this references the containing bundle ID.\n * See: https://github.com/ArweaveTeam/arweave-standards/blob/master/ans/ANS-104.md\n */\n bundledIn?: Maybe<Bundle>;\n data: MetaData;\n fee: Amount;\n id: Scalars['ID']['output'];\n /** When this transaction was made available for querying */\n ingested_at?: Maybe<Scalars['Int']['output']>;\n owner: Owner;\n /**\n * @deprecated Don't use, kept for backwards compatability only!\n * @deprecated Use `bundledIn`\n */\n parent?: Maybe<Parent>;\n quantity: Amount;\n recipient: Scalars['String']['output'];\n signature: Scalars['String']['output'];\n tags: Array<Tag>;\n};\n\n/**\n * Paginated result set using the GraphQL cursor spec,\n * see: https://relay.dev/graphql/connections.htm.\n */\nexport type TransactionConnection = {\n __typename?: 'TransactionConnection';\n /** The number of transactions that match this query. */\n count?: Maybe<Scalars['String']['output']>;\n edges: Array<TransactionEdge>;\n pageInfo: PageInfo;\n};\n\n/** Paginated result set using the GraphQL cursor spec. */\nexport type TransactionEdge = {\n __typename?: 'TransactionEdge';\n /**\n * The cursor value for fetching the next page.\n *\n * Pass this to the `after` parameter in ` transactions(after: $cursor)`, the next page will start from the next item after this.\n */\n cursor: Scalars['String']['output'];\n /** A transaction object. */\n node: Transaction;\n};\n\nexport type GetTransactionTagsQueryVariables = Exact<{\n transactionId: Scalars['ID']['input'];\n}>;\n\n\nexport type GetTransactionTagsQuery = { __typename?: 'Query', tags?: { __typename?: 'Transaction', id: string, tags: Array<{ __typename?: 'Tag', name: string, value: string }> } | null };\n\nexport type GetArweaveTransactionsQueryVariables = Exact<{\n owners?: InputMaybe<Array<Scalars['String']['input']> | Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n after?: InputMaybe<Scalars['String']['input']>;\n}>;\n\n\nexport type GetArweaveTransactionsQuery = { __typename?: 'Query', transactions: { __typename?: 'TransactionConnection', edges: Array<{ __typename?: 'TransactionEdge', cursor: string, node: { __typename?: 'Transaction', id: string, anchor: string, signature: string, block?: { __typename?: 'Block', id?: string | null, height: number } | null, data: { __typename?: 'MetaData', size: string, type?: string | null }, tags: Array<{ __typename?: 'Tag', name: string, value: string }> } }>, pageInfo: { __typename?: 'PageInfo', hasNextPage: boolean } } };\n\n\nexport const GetTransactionTagsDocument = {\"kind\":\"Document\",\"definitions\":[{\"kind\":\"OperationDefinition\",\"operation\":\"query\",\"name\":{\"kind\":\"Name\",\"value\":\"GetTransactionTags\"},\"variableDefinitions\":[{\"kind\":\"VariableDefinition\",\"variable\":{\"kind\":\"Variable\",\"name\":{\"kind\":\"Name\",\"value\":\"transactionId\"}},\"type\":{\"kind\":\"NonNullType\",\"type\":{\"kind\":\"NamedType\",\"name\":{\"kind\":\"Name\",\"value\":\"ID\"}}}}],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"alias\":{\"kind\":\"Name\",\"value\":\"tags\"},\"name\":{\"kind\":\"Name\",\"value\":\"transaction\"},\"arguments\":[{\"kind\":\"Argument\",\"name\":{\"kind\":\"Name\",\"value\":\"id\"},\"value\":{\"kind\":\"Variable\",\"name\":{\"kind\":\"Name\",\"value\":\"transactionId\"}}}],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"id\"}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"tags\"},\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"name\"}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"value\"}}]}}]}}]}}]} as unknown as DocumentNode<GetTransactionTagsQuery, GetTransactionTagsQueryVariables>;\nexport const GetArweaveTransactionsDocument = {\"kind\":\"Document\",\"definitions\":[{\"kind\":\"OperationDefinition\",\"operation\":\"query\",\"name\":{\"kind\":\"Name\",\"value\":\"GetArweaveTransactions\"},\"variableDefinitions\":[{\"kind\":\"VariableDefinition\",\"variable\":{\"kind\":\"Variable\",\"name\":{\"kind\":\"Name\",\"value\":\"owners\"}},\"type\":{\"kind\":\"ListType\",\"type\":{\"kind\":\"NonNullType\",\"type\":{\"kind\":\"NamedType\",\"name\":{\"kind\":\"Name\",\"value\":\"String\"}}}}},{\"kind\":\"VariableDefinition\",\"variable\":{\"kind\":\"Variable\",\"name\":{\"kind\":\"Name\",\"value\":\"first\"}},\"type\":{\"kind\":\"NamedType\",\"name\":{\"kind\":\"Name\",\"value\":\"Int\"}}},{\"kind\":\"VariableDefinition\",\"variable\":{\"kind\":\"Variable\",\"name\":{\"kind\":\"Name\",\"value\":\"after\"}},\"type\":{\"kind\":\"NamedType\",\"name\":{\"kind\":\"Name\",\"value\":\"String\"}}}],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"transactions\"},\"arguments\":[{\"kind\":\"Argument\",\"name\":{\"kind\":\"Name\",\"value\":\"owners\"},\"value\":{\"kind\":\"Variable\",\"name\":{\"kind\":\"Name\",\"value\":\"owners\"}}},{\"kind\":\"Argument\",\"name\":{\"kind\":\"Name\",\"value\":\"first\"},\"value\":{\"kind\":\"Variable\",\"name\":{\"kind\":\"Name\",\"value\":\"first\"}}},{\"kind\":\"Argument\",\"name\":{\"kind\":\"Name\",\"value\":\"after\"},\"value\":{\"kind\":\"Variable\",\"name\":{\"kind\":\"Name\",\"value\":\"after\"}}}],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"edges\"},\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"cursor\"}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"node\"},\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"id\"}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"anchor\"}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"signature\"}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"block\"},\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"id\"}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"height\"}}]}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"data\"},\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"size\"}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"type\"}}]}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"tags\"},\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"name\"}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"value\"}}]}}]}}]}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"pageInfo\"},\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"hasNextPage\"}}]}}]}}]}}]} as unknown as DocumentNode<GetArweaveTransactionsQuery, GetArweaveTransactionsQueryVariables>;","/* eslint-disable */\nimport * as types from './graphql';\nimport type { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/core';\n\n/**\n * Map of all GraphQL operations in the project.\n *\n * This map has several performance disadvantages:\n * 1. It is not tree-shakeable, so it will include all operations in the project.\n * 2. It is not minifiable, so the string of a GraphQL query will be multiple times inside the bundle.\n * 3. It does not support dead code elimination, so it will add unused operations.\n *\n * Therefore it is highly recommended to use the babel or swc plugin for production.\n * Learn more about it here: https://the-guild.dev/graphql/codegen/plugins/presets/preset-client#reducing-bundle-size\n */\ntype Documents = {\n \"\\n query GetTransactionTags($transactionId: ID!) {\\n tags: transaction(id: $transactionId) {\\n id\\n tags {\\n name\\n value\\n }\\n }\\n }\\n\": typeof types.GetTransactionTagsDocument,\n \"\\n query GetArweaveTransactions(\\n $owners: [String!]\\n $first: Int\\n $after: String\\n ) {\\n transactions(owners: $owners, first: $first, after: $after) {\\n edges {\\n cursor\\n node {\\n id\\n anchor\\n signature\\n block {\\n id\\n height\\n }\\n data {\\n size\\n type\\n }\\n tags {\\n name\\n value\\n }\\n }\\n }\\n pageInfo {\\n hasNextPage\\n }\\n }\\n }\\n\": typeof types.GetArweaveTransactionsDocument,\n};\nconst documents: Documents = {\n \"\\n query GetTransactionTags($transactionId: ID!) {\\n tags: transaction(id: $transactionId) {\\n id\\n tags {\\n name\\n value\\n }\\n }\\n }\\n\": types.GetTransactionTagsDocument,\n \"\\n query GetArweaveTransactions(\\n $owners: [String!]\\n $first: Int\\n $after: String\\n ) {\\n transactions(owners: $owners, first: $first, after: $after) {\\n edges {\\n cursor\\n node {\\n id\\n anchor\\n signature\\n block {\\n id\\n height\\n }\\n data {\\n size\\n type\\n }\\n tags {\\n name\\n value\\n }\\n }\\n }\\n pageInfo {\\n hasNextPage\\n }\\n }\\n }\\n\": types.GetArweaveTransactionsDocument,\n};\n\n/**\n * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.\n *\n *\n * @example\n * ```ts\n * const query = graphql(`query GetUser($id: ID!) { user(id: $id) { name } }`);\n * ```\n *\n * The query argument is unknown!\n * Please regenerate the types.\n */\nexport function graphql(source: string): unknown;\n\n/**\n * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.\n */\nexport function graphql(source: \"\\n query GetTransactionTags($transactionId: ID!) {\\n tags: transaction(id: $transactionId) {\\n id\\n tags {\\n name\\n value\\n }\\n }\\n }\\n\"): (typeof documents)[\"\\n query GetTransactionTags($transactionId: ID!) {\\n tags: transaction(id: $transactionId) {\\n id\\n tags {\\n name\\n value\\n }\\n }\\n }\\n\"];\n/**\n * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.\n */\nexport function graphql(source: \"\\n query GetArweaveTransactions(\\n $owners: [String!]\\n $first: Int\\n $after: String\\n ) {\\n transactions(owners: $owners, first: $first, after: $after) {\\n edges {\\n cursor\\n node {\\n id\\n anchor\\n signature\\n block {\\n id\\n height\\n }\\n data {\\n size\\n type\\n }\\n tags {\\n name\\n value\\n }\\n }\\n }\\n pageInfo {\\n hasNextPage\\n }\\n }\\n }\\n\"): (typeof documents)[\"\\n query GetArweaveTransactions(\\n $owners: [String!]\\n $first: Int\\n $after: String\\n ) {\\n transactions(owners: $owners, first: $first, after: $after) {\\n edges {\\n cursor\\n node {\\n id\\n anchor\\n signature\\n block {\\n id\\n height\\n }\\n data {\\n size\\n type\\n }\\n tags {\\n name\\n value\\n }\\n }\\n }\\n pageInfo {\\n hasNextPage\\n }\\n }\\n }\\n\"];\n\nexport function graphql(source: string) {\n return (documents as any)[source] ?? {};\n}\n\nexport type DocumentType<TDocumentNode extends DocumentNode<any, any>> = TDocumentNode extends DocumentNode< infer TType, any> ? TType : never;","import { graphql } from '../graphql/gql/index.js'\nimport type { TypedDocumentNode } from '@graphql-typed-document-node/core'\n\nexport const GET_TRANSACTION_TAGS = graphql(/* GraphQL */ `\n query GetTransactionTags($transactionId: ID!) {\n tags: transaction(id: $transactionId) {\n id\n tags {\n name\n value\n }\n }\n }\n`) as unknown as TypedDocumentNode<{ tags: { id: string; tags: { name: string; value: string }[] } | null }, { transactionId: string }>\n\nexport const GET_ARWEAVE_TRANSACTIONS = graphql(/* GraphQL */ `\n query GetArweaveTransactions(\n $owners: [String!]\n $first: Int\n $after: String\n ) {\n transactions(owners: $owners, first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n anchor\n signature\n block {\n id\n height\n }\n data {\n size\n type\n }\n tags {\n name\n value\n }\n }\n }\n pageInfo {\n hasNextPage\n }\n }\n }\n`) as unknown as TypedDocumentNode<\n {\n transactions: {\n edges: Array<{\n cursor: string\n node: {\n id: string\n anchor: string\n signature: string\n block: { id: string; height: number }\n data: { size: number; type: string }\n tags: Array<{ name: string; value: string }>\n }\n }>\n pageInfo: { hasNextPage: boolean }\n }\n },\n { owners?: string[]; first?: number; after?: string }\n>\n","import type { TransactionStatus } from '../types/arweave.js'\nimport {\n isGatewayHostCircuitOpen,\n recordGatewayHostFailure,\n recordGatewayHostSuccess,\n} from './gatewayCircuitBreaker.js'\nimport { getPreferredArweaveReadBaseUrls, getResolvedSeedGatewayEndpoints } from './gatewayState.js'\nimport { getArweaveReadBaseUrls } from './readBaseUrls.js'\n\n/** Per-gateway timeout for a status check. A gateway can take minutes on an id it doesn't have. */\nexport const DEFAULT_TRANSACTION_STATUS_TIMEOUT_MS = 10_000\n\n/** Time budget for a status check across all gateways. */\nexport const DEFAULT_TRANSACTION_STATUS_TOTAL_TIMEOUT_MS = 20_000\n\n/** Least budget worth starting another gateway attempt with (capped at the per-gateway timeout). */\nexport const MIN_TRANSACTION_STATUS_ATTEMPT_MS = 1_000\n\nexport type TransactionStatusFetchOptions = {\n timeoutMs?: number\n totalTimeoutMs?: number\n /** Base URLs to try in order. Defaults to {@link getArweaveReadBaseUrls}, without public gateways while a sidecar or proxy is active. */\n baseUrls?: readonly string[]\n}\n\ntype Attempt = { kind: 'answer'; status: number } | { kind: 'retry'; status: number }\n\n/** 5xx and 429 say nothing about the transaction; another gateway may answer. */\nconst isGatewayFailure = (status: number) => status >= 500 || status === 429\n\nasync function fetchStatusFromBaseUrl(baseUrl: string, transactionId: string, timeoutMs: number): Promise<Attempt> {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n try {\n const response = await fetch(`${baseUrl.replace(/\\/$/, '')}/${encodeURIComponent(transactionId)}`, {\n method: 'GET',\n credentials: 'omit',\n signal: controller.signal,\n })\n // Presence only: don't download the body.\n await response.body?.cancel().catch(() => {})\n return isGatewayFailure(response.status)\n ? { kind: 'retry', status: response.status }\n : { kind: 'answer', status: response.status }\n } catch {\n return { kind: 'retry', status: controller.signal.aborted ? 504 : 500 }\n } finally {\n clearTimeout(timer)\n }\n}\n\n/**\n * Read gateways for a status check. While a sidecar or proxy is the active path, only it and the\n * preferred gateways are asked: a data item it just accepted isn't on the public gateways yet, and\n * their 404 would read as missing.\n */\nfunction transactionStatusBaseUrls(): string[] {\n const urls = getArweaveReadBaseUrls()\n const resolved = getResolvedSeedGatewayEndpoints()\n if (resolved?.activePath !== 'hyper-sidecar' && resolved?.activePath !== 'http-proxy') return urls\n const local = new Set([...getPreferredArweaveReadBaseUrls(), resolved.arweaveBaseUrl.replace(/\\/$/, '')])\n return urls.filter((url) => local.has(url))\n}\n\n/**\n * HTTP status of `GET {gateway}/{id}`, trying read gateways in order\n * ({@link getArweaveReadBaseUrls}: preferred, then the configured host, then public fallbacks; only\n * the proxy or sidecar when one is the active path). A gateway's 2xx-4xx answer is returned as is\n * (a 404 isn't retried elsewhere). A timeout, network error, 5xx or 429 moves on to the next\n * gateway, and gateways whose circuit is open are skipped. When none answers within the total\n * budget the status is 504 if the last attempt timed out, otherwise that attempt's status. A\n * gateway after the first is only asked while the budget left covers its timeout or\n * {@link MIN_TRANSACTION_STATUS_ATTEMPT_MS}, whichever is shorter.\n */\nexport async function fetchTransactionStatusAcrossGateways(\n transactionId: string,\n options: TransactionStatusFetchOptions = {},\n): Promise<TransactionStatus> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_TRANSACTION_STATUS_TIMEOUT_MS\n const deadline = performance.now() + (options.totalTimeoutMs ?? DEFAULT_TRANSACTION_STATUS_TOTAL_TIMEOUT_MS)\n const baseUrls = options.baseUrls ?? transactionStatusBaseUrls()\n const open = baseUrls.filter((url) => !isGatewayHostCircuitOpen(url))\n // Every circuit open: try them anyway rather than answer without asking.\n const candidates = open.length > 0 ? open : baseUrls\n\n let lastStatus = 500\n for (const [index, baseUrl] of candidates.entries()) {\n const remaining = deadline - performance.now()\n if (remaining <= 0) break\n // A timer can fire a little before the clock reaches the deadline; don't spend the sliver\n // that leaves on an attempt that can't succeed (and would count against the gateway's circuit).\n if (index > 0 && remaining < Math.min(timeoutMs, MIN_TRANSACTION_STATUS_ATTEMPT_MS)) break\n const attempt = await fetchStatusFromBaseUrl(baseUrl, transactionId, Math.min(timeoutMs, remaining))\n if (attempt.kind === 'answer') {\n recordGatewayHostSuccess(baseUrl)\n // Callers test for 200 (present); any 2xx means the gateway has it.\n const status = attempt.status >= 200 && attempt.status < 300 ? 200 : attempt.status\n return { status, confirmed: null }\n }\n recordGatewayHostFailure(baseUrl)\n lastStatus = attempt.status\n }\n return { status: lastStatus, confirmed: null }\n}\n","import { BaseArweaveClient } from '../ArweaveClient/BaseArweaveClient.js'\nimport type { IArweaveClient } from '../ArweaveClient/IArweaveClient.js'\nimport { GraphQLClient } from 'graphql-request'\nimport type Arweave from 'arweave'\nimport type {\n TransactionStatus,\n TransactionTag,\n GetDataOptions,\n DownloadFilesParams,\n DownloadResult,\n CreateTransactionOptions,\n ArweaveTransaction,\n} from '../types/arweave.js'\nimport { GET_TRANSACTION_TAGS } from '../ArweaveClient/queries.js'\nimport { fetchTransactionStatusAcrossGateways } from '../gateway/transactionStatus.js'\nimport { getPreferredArweaveReadBaseUrls } from '../gateway/gatewayState.js'\nimport { fetchArweaveRawFromBaseUrl } from '../gateway/readBaseUrls.js'\nimport debug from 'debug'\n\nconst logger = debug('seedArweave:ArweaveClient')\n\n/**\n * How long one Arweave GraphQL request may take before it is aborted, so a stalled gateway doesn't\n * hold every caller that awaits it.\n */\nexport const ARWEAVE_GRAPHQL_TIMEOUT_MS = 30_000\n\ntype FetchInit = Parameters<typeof fetch>[1]\n\n/** `fetch` that aborts after `timeoutMs`, or when the caller's signal does. */\nfunction fetchWithTimeout(timeoutMs: number) {\n return (input: Parameters<typeof fetch>[0], init?: FetchInit): Promise<Response> => {\n if (typeof AbortController === 'undefined') return fetch(input, init)\n const controller = new AbortController()\n const callerSignal = init?.signal ?? undefined\n const timer = setTimeout(\n () => controller.abort(new Error(`Arweave GraphQL request timed out after ${timeoutMs} ms`)),\n timeoutMs,\n )\n const onCallerAbort = () => controller.abort(callerSignal?.reason)\n if (callerSignal?.aborted) onCallerAbort()\n else callerSignal?.addEventListener('abort', onCallerAbort, { once: true })\n return fetch(input, { ...init, signal: controller.signal }).finally(() => {\n clearTimeout(timer)\n callerSignal?.removeEventListener('abort', onCallerAbort)\n })\n }\n}\n\n// Cached Arweave instance (keyed by gateway so setHost / protocol changes apply)\nlet _arweaveInstance: Arweave | null = null\nlet _arweaveGatewayKey: string | null = null\n\n/**\n * arweave-js instance for the configured gateway. Loaded on first use, so importing this package\n * does not load arweave-js; only the data fallback and createTransaction need it.\n */\nconst getArweaveInstance = async (): Promise<Arweave> => {\n const gatewayKey = `${BaseArweaveClient.getProtocol()}://${BaseArweaveClient.getHost()}`\n if (_arweaveInstance && _arweaveGatewayKey === gatewayKey) {\n return _arweaveInstance\n }\n\n const mod = (await import('arweave')) as unknown as { default?: unknown }\n // ESM and CJS builds of arweave-js nest the class differently.\n let ArweaveClass = (mod.default ?? mod) as { init?: unknown; default?: { init?: unknown } }\n if (typeof ArweaveClass.init !== 'function' && typeof ArweaveClass.default?.init === 'function') {\n ArweaveClass = ArweaveClass.default\n }\n\n _arweaveGatewayKey = gatewayKey\n _arweaveInstance = (ArweaveClass as typeof Arweave).init(BaseArweaveClient.getArweaveJsApiConfig())\n return _arweaveInstance\n}\n\n/**\n * Fetch-based Arweave client; works in Node and browsers. Registering it is up to the caller.\n * Data reads try the preferred read gateways first (usually the one the item was uploaded through),\n * which serve data items before they reach L1.\n */\nexport class DefaultArweaveClient implements IArweaveClient {\n getArweaveClient(): GraphQLClient {\n return new GraphQLClient(BaseArweaveClient.getEndpoint(), {\n fetch: fetchWithTimeout(ARWEAVE_GRAPHQL_TIMEOUT_MS),\n })\n }\n\n async getTransactionStatus(transactionId: string): Promise<TransactionStatus> {\n return fetchTransactionStatusAcrossGateways(transactionId)\n }\n\n async getTransactionData(\n transactionId: string,\n options?: GetDataOptions,\n ): Promise<Uint8Array | string> {\n // `/raw` is already decoded, so skip the preferred gateways when the caller asked for undecoded data.\n const preferred = options?.decode === false ? [] : getPreferredArweaveReadBaseUrls()\n for (const base of preferred) {\n const { response } = await fetchArweaveRawFromBaseUrl(base, transactionId)\n if (!response) continue\n try {\n if (options?.string) {\n return await response.text()\n }\n return new Uint8Array(await response.arrayBuffer())\n } catch (error) {\n logger('Error reading preferred gateway response:', error)\n }\n }\n\n // Path-prefixed proxies (app-server Hyper proxy) are not supported by arweave.init host;\n // fetch via getRawUrl so /api/seed-gateway/... works.\n if (BaseArweaveClient.getGatewayPath()) {\n const response = await fetch(BaseArweaveClient.getRawUrl(transactionId))\n if (!response.ok) {\n throw new Error(`Failed to fetch transaction data: HTTP ${response.status}`)\n }\n if (options?.string) {\n return response.text()\n }\n return new Uint8Array(await response.arrayBuffer())\n }\n\n const arweave = await getArweaveInstance()\n\n try {\n const data = await arweave.transactions.getData(transactionId, {\n decode: options?.decode ?? true,\n string: options?.string ?? false,\n })\n\n if (options?.string && typeof data === 'string') {\n return data\n }\n\n if (data instanceof Uint8Array) {\n return data\n }\n\n // Handle string data when not requesting string\n if (typeof data === 'string') {\n return new TextEncoder().encode(data)\n }\n\n return data as Uint8Array\n } catch (error) {\n logger('Error fetching transaction data:', error)\n throw error\n }\n }\n\n async getTransactionTags(transactionId: string): Promise<TransactionTag[]> {\n const client = this.getArweaveClient()\n\n try {\n const result = await client.request(GET_TRANSACTION_TAGS, { transactionId })\n\n if (!result.tags?.tags) {\n return []\n }\n\n return result.tags.tags.map((tag: { name: string; value: string }) => ({\n name: tag.name,\n value: tag.value,\n }))\n } catch (error) {\n logger('Error fetching transaction tags:', error)\n return []\n }\n }\n\n async createTransaction(\n data: string | Uint8Array,\n options?: CreateTransactionOptions,\n ): Promise<ArweaveTransaction> {\n const arweave = await getArweaveInstance()\n\n const tx = await arweave.createTransaction({\n data,\n })\n\n if (options?.tags) {\n for (const tag of options.tags) {\n tx.addTag(tag.name, tag.value)\n }\n }\n\n return tx\n }\n\n async downloadFiles(params: DownloadFilesParams): Promise<DownloadResult[]> {\n const { transactionIds, excludedTransactions } = params\n const results: DownloadResult[] = []\n const baseUrl = BaseArweaveClient.getBaseUrl()\n\n for (const transactionId of transactionIds) {\n if (excludedTransactions?.has(transactionId)) {\n continue\n }\n\n try {\n const url = `${baseUrl}/raw/${transactionId}`\n const response = await fetch(url)\n\n if (!response.ok) {\n results.push({\n transactionId,\n success: false,\n error: `HTTP ${response.status}: ${response.statusText}`,\n })\n continue\n }\n\n const data = new Uint8Array(await response.arrayBuffer())\n const contentType = response.headers.get('content-type') || undefined\n\n results.push({\n transactionId,\n success: true,\n contentType,\n data,\n })\n } catch (error) {\n logger(`Error downloading transaction ${transactionId}:`, error)\n results.push({\n transactionId,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n\n return results\n }\n}\n"],"mappings":";;;AAIA,IAAaI,IAAuB,eAMvBC,IAA8B,IAO9BC,IAAiC,IAGjCC,IAA+B,aAC/BC,IAA+B,MAG/BC,IAA8B,WAAWL,EAAqB,WAM9DM,IAA2B;CACtC;CACA;CACA;AACF,GAOMC,I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,IAAI;GACF,IAAMF,IAAM,GAAGuC,EAAQ,OAAOrC,KACxBvB,IAAW,MAAM,MAAMqB,CAAG;GAEhC,IAAI,CAACrB,EAAS,IAAI;IAChB,EAAQ,KAAK;KACX;KACA,SAAS;KACT,OAAO,QAAQA,EAAS,OAAO,IAAIA,EAAS;IAC9C,CAAC;IACD;GACF;GAEA,IAAMwB,IAAO,IAAI,WAAW,MAAMxB,EAAS,YAAY,CAAC,GAClD4M,IAAc5M,EAAS,QAAQ,IAAI,cAAc,KAAK,KAAA;GAE5D,EAAQ,KAAK;IACX;IACA,SAAS;IACT;IACA;GACF,CAAC;EACH,SAASoM,GAAO;GAEd,AADAb,EAAO,iCAAiChK,EAAc,IAAI6K,CAAK,GAC/DM,EAAQ,KAAK;IACX;IACA,SAAS;IACT,OAAON,aAAiB,QAAQA,EAAM,UAAU,OAAOA,CAAK;GAC9D,CAAC;EACH;EAGF,OAAOM;CACT;AACF"}
|
|
@@ -16,17 +16,39 @@ export declare function getResolvedArweaveReadBaseUrls(options?: ArweaveReadBase
|
|
|
16
16
|
export declare function getArweaveReadBaseUrls(options?: ArweaveReadBaseUrlOptions): string[];
|
|
17
17
|
/** Run the read-gateway probe unless a sidecar / proxy is already the active path. Never throws. */
|
|
18
18
|
export declare function ensureArweaveReadGatewayForFallback(): Promise<void>;
|
|
19
|
-
/**
|
|
19
|
+
/**
|
|
20
|
+
* What one gateway answered to `/raw/{id}`: the HTTP status, `'timeout'` (our abort fired),
|
|
21
|
+
* `'network'` (fetch threw; a browser reports a CORS-blocked answer this way, without its status),
|
|
22
|
+
* `'empty'` (2xx with no bytes) or `'unreadable'` (2xx whose body or read transform failed).
|
|
23
|
+
*/
|
|
24
|
+
export type ArweaveRawReadOutcome = number | 'timeout' | 'network' | 'empty' | 'unreadable';
|
|
25
|
+
export type ArweaveRawReadAttempt = {
|
|
26
|
+
baseUrl: string;
|
|
27
|
+
outcome: ArweaveRawReadOutcome;
|
|
28
|
+
};
|
|
29
|
+
/** GET `{baseUrl}/raw/{id}`. `response` is set only for a 2xx answer. */
|
|
20
30
|
export declare function fetchArweaveRawFromBaseUrl(baseUrl: string, transactionId: string, options?: {
|
|
21
31
|
timeoutMs?: number;
|
|
22
|
-
}): Promise<
|
|
32
|
+
}): Promise<ArweaveRawReadAttempt & {
|
|
33
|
+
response?: Response;
|
|
34
|
+
}>;
|
|
23
35
|
/**
|
|
24
|
-
* GET `/raw/{id}` across read gateways and return the first non-empty
|
|
25
|
-
*
|
|
26
|
-
* gateway
|
|
36
|
+
* GET `/raw/{id}` across read gateways, asking each at most once, and return the first non-empty
|
|
37
|
+
* body with what each gateway asked answered. Preferred gateways go first and are tried before any
|
|
38
|
+
* read-gateway probe; a just-published item is served by the gateway it was uploaded through well
|
|
39
|
+
* before it reaches L1 or the public hosts. The configured host (`BaseArweaveClient.getBaseUrl()`)
|
|
40
|
+
* goes last when the resolved list leaves it out.
|
|
27
41
|
* The body goes through `transformArweaveContent` (see `content/arweaveContent.ts`); `decode: false`
|
|
28
42
|
* returns the transaction's bytes as stored, as `getTransactionData` does.
|
|
29
43
|
*/
|
|
44
|
+
export declare function readArweaveRawAcrossGateways(transactionId: string, options?: ArweaveReadBaseUrlOptions & {
|
|
45
|
+
timeoutMs?: number;
|
|
46
|
+
decode?: boolean;
|
|
47
|
+
}): Promise<{
|
|
48
|
+
bytes?: Uint8Array;
|
|
49
|
+
attempts: ArweaveRawReadAttempt[];
|
|
50
|
+
}>;
|
|
51
|
+
/** {@link readArweaveRawAcrossGateways}'s bytes; undefined when no gateway served any. */
|
|
30
52
|
export declare function fetchArweaveRawBytesAcrossGateways(transactionId: string, options?: ArweaveReadBaseUrlOptions & {
|
|
31
53
|
timeoutMs?: number;
|
|
32
54
|
decode?: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readBaseUrls.d.ts","sourceRoot":"","sources":["../../src/gateway/readBaseUrls.ts"],"names":[],"mappings":"AAOA,8GAA8G;AAC9G,eAAO,MAAM,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