@zama-fhe/sdk 3.3.0 → 3.3.1-alpha.2
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 +0 -2
- package/dist/cjs/base-signer.cjs +1 -1
- package/dist/cjs/base-signer.cjs.map +1 -1
- package/dist/cjs/chains.cjs +1 -1
- package/dist/cjs/chains.cjs.map +1 -1
- package/dist/cjs/cleartext/index.cjs +1 -1
- package/dist/cjs/cleartext.cjs +2 -0
- package/dist/cjs/cleartext.cjs.map +1 -0
- package/dist/cjs/ethers/index.cjs.map +1 -1
- package/dist/cjs/fhevm-relayer.cjs +2 -0
- package/dist/cjs/fhevm-relayer.cjs.map +1 -0
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/node/index.cjs +2 -0
- package/dist/cjs/node/index.cjs.map +1 -0
- package/dist/cjs/query/index.cjs +1 -1
- package/dist/cjs/query/index.cjs.map +1 -1
- package/dist/cjs/relayer.cjs +1 -1
- package/dist/cjs/relayer.cjs.map +1 -1
- package/dist/cjs/token.cjs +1 -1
- package/dist/cjs/token.cjs.map +1 -1
- package/dist/cjs/viem/index.cjs +1 -1
- package/dist/cjs/viem/index.cjs.map +1 -1
- package/dist/cjs/web/index.cjs +1 -590
- package/dist/cjs/web/index.cjs.map +1 -1
- package/dist/cjs/wrappers-registry.cjs.map +1 -1
- package/dist/esm/base-signer-CI-FYai2.js +2 -0
- package/dist/esm/base-signer-CI-FYai2.js.map +1 -0
- package/dist/esm/{base-signer-C3Wc5oi9.d.ts → base-signer-Q2EJECrc.d.ts} +2 -2
- package/dist/esm/chains/index.d.ts +2 -3
- package/dist/esm/chains/index.js +1 -1
- package/dist/esm/chains-CLv9HEJ_.js +2 -0
- package/dist/esm/chains-CLv9HEJ_.js.map +1 -0
- package/dist/esm/cleartext/index.d.ts +3 -2
- package/dist/esm/cleartext/index.js +1 -1
- package/dist/esm/cleartext-BfXTVQu-.js +2 -0
- package/dist/esm/cleartext-BfXTVQu-.js.map +1 -0
- package/dist/esm/cleartext-U6sPs_Kd.d.ts +19 -0
- package/dist/esm/ethers/index.d.ts +4 -5
- package/dist/esm/ethers/index.js +1 -1
- package/dist/esm/ethers/index.js.map +1 -1
- package/dist/esm/fhevm-relayer-B-lEKfPQ.js +2 -0
- package/dist/esm/fhevm-relayer-B-lEKfPQ.js.map +1 -0
- package/dist/esm/index-BnIp_-Ak.d.ts +328 -0
- package/dist/esm/{index-CYBH0nyo.d.ts → index-D66eC3G7.d.ts} +60 -13
- package/dist/esm/index.d.ts +8 -11
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/node/index.d.ts +5 -194
- package/dist/esm/node/index.js +1 -1
- package/dist/esm/node/index.js.map +1 -1
- package/dist/esm/query/index.d.ts +3 -380
- package/dist/esm/query/index.js +1 -1
- package/dist/esm/query/index.js.map +1 -1
- package/dist/esm/relayer-BYq9bLh8.js +2 -0
- package/dist/esm/relayer-BYq9bLh8.js.map +1 -0
- package/dist/esm/token-CmHTAAWW.js +2 -0
- package/dist/esm/token-CmHTAAWW.js.map +1 -0
- package/dist/esm/{types-piBsdTIP.d.ts → types-Bov8XY36.d.ts} +3 -3
- package/dist/esm/{types-OHIaPwCy.d.ts → types-BpvL50qX.d.ts} +3 -3
- package/dist/esm/types-C-WTLcHZ.d.ts +988 -0
- package/dist/esm/viem/index.d.ts +4 -5
- package/dist/esm/viem/index.js +1 -1
- package/dist/esm/viem/index.js.map +1 -1
- package/dist/esm/web/index.d.ts +6 -9
- package/dist/esm/web/index.js +1 -590
- package/dist/esm/web/index.js.map +1 -1
- package/dist/esm/{wrappers-registry-C1oK8Bi6.js → wrappers-registry-xZWzyAi4.js} +2 -2
- package/dist/esm/wrappers-registry-xZWzyAi4.js.map +1 -0
- package/dist/esm/{index-C1Mtc8Rw.d.ts → zama-sdk-q4_qt64Q.d.ts} +1471 -1102
- package/package.json +6 -2
- package/dist/cjs/assertions.cjs +0 -2
- package/dist/cjs/assertions.cjs.map +0 -1
- package/dist/cjs/encryption.cjs +0 -2
- package/dist/cjs/encryption.cjs.map +0 -1
- package/dist/cjs/relayer-cleartext.cjs +0 -2
- package/dist/cjs/relayer-cleartext.cjs.map +0 -1
- package/dist/cjs/relayer-sdk.worker.js +0 -589
- package/dist/cjs/timeout.cjs +0 -2
- package/dist/cjs/timeout.cjs.map +0 -1
- package/dist/cjs/validation.cjs +0 -2
- package/dist/cjs/validation.cjs.map +0 -1
- package/dist/esm/assertions-zYseN5Xz.js +0 -2
- package/dist/esm/assertions-zYseN5Xz.js.map +0 -1
- package/dist/esm/base-signer-DjytqPkd.js +0 -2
- package/dist/esm/base-signer-DjytqPkd.js.map +0 -1
- package/dist/esm/chains-CXcO1DBP.js +0 -2
- package/dist/esm/chains-CXcO1DBP.js.map +0 -1
- package/dist/esm/cleartext-DAkOTlrE.d.ts +0 -19
- package/dist/esm/cleartext-rTWFctyd.js +0 -2
- package/dist/esm/cleartext-rTWFctyd.js.map +0 -1
- package/dist/esm/encryption-x4Z_Icqk.js +0 -2
- package/dist/esm/encryption-x4Z_Icqk.js.map +0 -1
- package/dist/esm/hex-A72GrTf9.js +0 -2
- package/dist/esm/hex-A72GrTf9.js.map +0 -1
- package/dist/esm/indexeddb-storage-Mi-fCWN3.js +0 -2
- package/dist/esm/indexeddb-storage-Mi-fCWN3.js.map +0 -1
- package/dist/esm/memory-storage-fp9RY5BQ.js +0 -2
- package/dist/esm/memory-storage-fp9RY5BQ.js.map +0 -1
- package/dist/esm/node/relayer-sdk.node-worker.d.ts +0 -1
- package/dist/esm/node/relayer-sdk.node-worker.js +0 -2
- package/dist/esm/node/relayer-sdk.node-worker.js.map +0 -1
- package/dist/esm/relayer-cleartext-Bp6jtxDd.js +0 -2
- package/dist/esm/relayer-cleartext-Bp6jtxDd.js.map +0 -1
- package/dist/esm/relayer-cleartext-CSeMlmGO.d.ts +0 -844
- package/dist/esm/relayer-eavK5bfZ.js +0 -2
- package/dist/esm/relayer-eavK5bfZ.js.map +0 -1
- package/dist/esm/relayer-sdk.worker.js +0 -589
- package/dist/esm/timeout-CNVfiaJD.js +0 -2
- package/dist/esm/timeout-CNVfiaJD.js.map +0 -1
- package/dist/esm/token-Bt33g0zQ.js +0 -2
- package/dist/esm/token-Bt33g0zQ.js.map +0 -1
- package/dist/esm/types-BgczXqW2.d.ts +0 -49
- package/dist/esm/types-Gn5MeDsr.d.ts +0 -669
- package/dist/esm/validation-DLszOweh.js +0 -2
- package/dist/esm/validation-DLszOweh.js.map +0 -1
- package/dist/esm/worker.base-client-BVnT4yJa.js +0 -2
- package/dist/esm/worker.base-client-BVnT4yJa.js.map +0 -1
- package/dist/esm/wrappers-registry-C1oK8Bi6.js.map +0 -1
|
@@ -1,589 +0,0 @@
|
|
|
1
|
-
(function() {
|
|
2
|
-
//#region src/utils/error.ts
|
|
3
|
-
/** Coerce an unknown caught value to an Error instance. */
|
|
4
|
-
function toError(error) {
|
|
5
|
-
if (error instanceof Error) return error;
|
|
6
|
-
if (typeof error === "object" && error !== null && "message" in error) return new Error(String(error.message));
|
|
7
|
-
return new Error(String(error));
|
|
8
|
-
}
|
|
9
|
-
/** Properties that may nest a lower-level cause across viem / ethers / fetch. */
|
|
10
|
-
const NESTED_ERROR_KEYS = [
|
|
11
|
-
"cause",
|
|
12
|
-
"error",
|
|
13
|
-
"info"
|
|
14
|
-
];
|
|
15
|
-
/**
|
|
16
|
-
* ethers reports its HTTP status only as a string on `info.responseStatus`
|
|
17
|
-
* (e.g. `"429 Too Many Requests"`). Read it directly off the node — not via the
|
|
18
|
-
* cause-chain flattening, which descends a single branch — so it survives even
|
|
19
|
-
* when the error also carries an `error` link that would be walked first.
|
|
20
|
-
*/
|
|
21
|
-
function responseStatusFromNode(node) {
|
|
22
|
-
const info = node.info;
|
|
23
|
-
if (info !== null && typeof info === "object") {
|
|
24
|
-
const responseStatus = info.responseStatus;
|
|
25
|
-
if (typeof responseStatus === "string") return responseStatus;
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
/**
|
|
29
|
-
* Copy the scalar signal fields the classifier keys on from a raw error node
|
|
30
|
-
* onto the envelope, only where not already set — so a shallower node keeps
|
|
31
|
-
* priority. Also lifts ethers' string `info.responseStatus` and the relayer's
|
|
32
|
-
* `Retry-After` header (both destroyed by structured clone: the header lives on
|
|
33
|
-
* a non-cloneable `Headers`, the status on a nested `info` the flattening skips).
|
|
34
|
-
*/
|
|
35
|
-
function captureNodeSignals(node, into) {
|
|
36
|
-
if (into.code === void 0 && (typeof node.code === "string" || typeof node.code === "number")) into.code = node.code;
|
|
37
|
-
if (into.status === void 0 && typeof node.status === "number") into.status = node.status;
|
|
38
|
-
if (into.statusCode === void 0 && typeof node.statusCode === "number") into.statusCode = node.statusCode;
|
|
39
|
-
if (into.responseStatus === void 0) {
|
|
40
|
-
const responseStatus = responseStatusFromNode(node);
|
|
41
|
-
if (responseStatus !== void 0) into.responseStatus = responseStatus;
|
|
42
|
-
}
|
|
43
|
-
if (into.retryAfter === void 0) if (typeof node.retryAfter === "number") into.retryAfter = node.retryAfter;
|
|
44
|
-
else {
|
|
45
|
-
const fromHeader = retryAfterFromHeader(node);
|
|
46
|
-
if (fromHeader !== void 0) into.retryAfter = fromHeader;
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
/** Lift any still-missing scalar signal from an already-serialized child up. */
|
|
50
|
-
function hoistMissingSignals(from, into) {
|
|
51
|
-
if (into.code === void 0 && from.code !== void 0) into.code = from.code;
|
|
52
|
-
if (into.status === void 0 && from.status !== void 0) into.status = from.status;
|
|
53
|
-
if (into.statusCode === void 0 && from.statusCode !== void 0) into.statusCode = from.statusCode;
|
|
54
|
-
if (into.responseStatus === void 0 && from.responseStatus !== void 0) into.responseStatus = from.responseStatus;
|
|
55
|
-
if (into.retryAfter === void 0 && from.retryAfter !== void 0) into.retryAfter = from.retryAfter;
|
|
56
|
-
}
|
|
57
|
-
/**
|
|
58
|
-
* Flatten an error (and its `cause` / `error` / `info` chain) into a
|
|
59
|
-
* structured-clone-safe {@link SerializedError}. Depth-bounded to mirror
|
|
60
|
-
* {@link findInErrorChain} and guard against cyclic structures.
|
|
61
|
-
*/
|
|
62
|
-
function serializeError(error, depth = 6) {
|
|
63
|
-
const coerced = toError(error);
|
|
64
|
-
const node = typeof error === "object" && error !== null ? error : coerced;
|
|
65
|
-
const serialized = {
|
|
66
|
-
name: coerced.name,
|
|
67
|
-
message: coerced.message
|
|
68
|
-
};
|
|
69
|
-
captureNodeSignals(node, serialized);
|
|
70
|
-
if (depth > 0) for (const key of NESTED_ERROR_KEYS) {
|
|
71
|
-
const next = node[key];
|
|
72
|
-
if (next !== void 0 && next !== null && typeof next === "object") {
|
|
73
|
-
const child = serializeError(next, depth - 1);
|
|
74
|
-
if (serialized.cause === void 0) serialized.cause = child;
|
|
75
|
-
hoistMissingSignals(child, serialized);
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
return serialized;
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
|
-
* Parse an HTTP `Retry-After` header value into **seconds** (the SDK's duration
|
|
82
|
-
* unit and the header's own unit), or `undefined` when absent/unparseable. Per
|
|
83
|
-
* RFC 9110 the value is either a non-negative number of seconds (`"120"`) or an
|
|
84
|
-
* HTTP-date; a past date floors to `0`.
|
|
85
|
-
*/
|
|
86
|
-
function parseRetryAfterHeader(value) {
|
|
87
|
-
if (value === null || value === void 0) return;
|
|
88
|
-
const trimmed = value.trim();
|
|
89
|
-
if (trimmed === "") return;
|
|
90
|
-
if (/^\d+$/.test(trimmed)) return Number(trimmed);
|
|
91
|
-
if (/[a-zA-Z]/.test(trimmed)) {
|
|
92
|
-
const dateMs = Date.parse(trimmed);
|
|
93
|
-
if (!Number.isNaN(dateMs)) return Math.max(0, Math.round((dateMs - Date.now()) / 1e3));
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
/** Read a `Retry-After` header (→ seconds) off a `Headers`-like object, if present. */
|
|
97
|
-
function readRetryAfterHeader(headers) {
|
|
98
|
-
if (headers === null || typeof headers !== "object") return;
|
|
99
|
-
const get = headers.get;
|
|
100
|
-
if (typeof get !== "function") return;
|
|
101
|
-
return parseRetryAfterHeader(get.call(headers, "Retry-After"));
|
|
102
|
-
}
|
|
103
|
-
/**
|
|
104
|
-
* A node's **relayer** `Retry-After` header (seconds), read from a wrapped fetch
|
|
105
|
-
* `Response` (the relayer SDK's `cause.response.headers`). The SDK owns the
|
|
106
|
-
* relayer fetch, so parsing the header there is legitimate.
|
|
107
|
-
*
|
|
108
|
-
* The viem/chain side (`HttpRequestError.headers`) is deliberately **not** read:
|
|
109
|
-
* for consumer RPC the integrator's viem/ethers transport already honors
|
|
110
|
-
* `Retry-After` in its own retry loop (and retries) before the error ever
|
|
111
|
-
* surfaces, so re-reading it here would re-implement a transport concern.
|
|
112
|
-
* Chain-RPC backoff is configured on the consumer's transport (`chain.network`).
|
|
113
|
-
*/
|
|
114
|
-
function retryAfterFromHeader(node) {
|
|
115
|
-
const response = node.response;
|
|
116
|
-
if (response !== null && typeof response === "object") return readRetryAfterHeader(response.headers);
|
|
117
|
-
}
|
|
118
|
-
//#endregion
|
|
119
|
-
//#region src/utils/assertions.ts
|
|
120
|
-
function assertObject(value, context) {
|
|
121
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`${context} must be an object, got ${typeof value}`);
|
|
122
|
-
}
|
|
123
|
-
function assertString(value, context) {
|
|
124
|
-
if (typeof value !== "string") throw new TypeError(`${context} must be a string, got ${typeof value}`);
|
|
125
|
-
}
|
|
126
|
-
function assertFunction(value, context) {
|
|
127
|
-
if (typeof value !== "function") throw new TypeError(`${context} must be a function, got ${typeof value}`);
|
|
128
|
-
}
|
|
129
|
-
/** Assert that `obj[key]` is a string. Narrows `obj` to include `{ [key]: string }`. */
|
|
130
|
-
function assertStringProp(obj, key, context) {
|
|
131
|
-
assertString(obj[key], context);
|
|
132
|
-
}
|
|
133
|
-
/** Assert that `obj[key]` is a function. Narrows `obj` to include `{ [key]: F }`. */
|
|
134
|
-
function assertFunctionProp(obj, key, context) {
|
|
135
|
-
assertFunction(obj[key], context);
|
|
136
|
-
}
|
|
137
|
-
function assertCondition(condition, message) {
|
|
138
|
-
if (!condition) throw new TypeError(message);
|
|
139
|
-
}
|
|
140
|
-
//#endregion
|
|
141
|
-
//#region src/utils/hex.ts
|
|
142
|
-
/** Normalize a un-prefixed hex payload to a 0x-prefixed `Hex` value. */
|
|
143
|
-
function prefixHex(value) {
|
|
144
|
-
return value.startsWith("0x") ? value : `0x${value}`;
|
|
145
|
-
}
|
|
146
|
-
/** Convert a public `Hex` value back an unprefixed format. */
|
|
147
|
-
function unprefixHex(value) {
|
|
148
|
-
assertCondition(value.startsWith("0x"), `Expected 0x-prefixed hex, got: ${value}`);
|
|
149
|
-
return value.slice(2);
|
|
150
|
-
}
|
|
151
|
-
//#endregion
|
|
152
|
-
//#region src/worker/browser-extension.ts
|
|
153
|
-
function isValidRuntime(runtime) {
|
|
154
|
-
try {
|
|
155
|
-
assertObject(runtime, "runtime");
|
|
156
|
-
assertStringProp(runtime, "id", "runtime.id");
|
|
157
|
-
assertFunctionProp(runtime, "getURL", "runtime.getURL");
|
|
158
|
-
return true;
|
|
159
|
-
} catch {
|
|
160
|
-
return false;
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
/**
|
|
164
|
-
* Return the browser extension runtime object, or `undefined` outside extensions.
|
|
165
|
-
* Works across Chrome/Edge (`chrome.runtime`) and Firefox/Safari (`browser.runtime`).
|
|
166
|
-
* Extensions have restricted CSP that blocks `blob:` URLs, so callers use
|
|
167
|
-
* this to detect the environment and resolve file URLs via `runtime.getURL`.
|
|
168
|
-
*/
|
|
169
|
-
function getBrowserExtensionRuntime() {
|
|
170
|
-
const g = globalThis;
|
|
171
|
-
for (const ns of [g.chrome, g.browser]) try {
|
|
172
|
-
assertObject(ns, "ns");
|
|
173
|
-
if (isValidRuntime(ns.runtime)) return ns.runtime;
|
|
174
|
-
} catch {
|
|
175
|
-
continue;
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
//#endregion
|
|
179
|
-
//#region src/worker/relayer-sdk.worker.ts
|
|
180
|
-
const instances = /* @__PURE__ */ new Map();
|
|
181
|
-
const pending = /* @__PURE__ */ new Map();
|
|
182
|
-
const configs = /* @__PURE__ */ new Map();
|
|
183
|
-
/** Convert an FheChain to the FhevmInstanceConfig shape expected by createInstance. */
|
|
184
|
-
function toInstanceConfig(chain) {
|
|
185
|
-
return {
|
|
186
|
-
...chain,
|
|
187
|
-
chainId: chain.id
|
|
188
|
-
};
|
|
189
|
-
}
|
|
190
|
-
let sdkGlobal = null;
|
|
191
|
-
/**
|
|
192
|
-
* Get or lazily create an FhevmInstance for the given chain.
|
|
193
|
-
*/
|
|
194
|
-
async function getInstance(chainId) {
|
|
195
|
-
const existing = instances.get(chainId);
|
|
196
|
-
if (existing) return existing;
|
|
197
|
-
const inflight = pending.get(chainId);
|
|
198
|
-
if (inflight) return inflight;
|
|
199
|
-
const config = configs.get(chainId);
|
|
200
|
-
if (!config) throw new Error(`No config for chain ${chainId}. Available: [${[...configs.keys()].join(", ")}]`);
|
|
201
|
-
if (!sdkGlobal) throw new Error("Relayer SDK is not initialized. Call INIT first.");
|
|
202
|
-
const promise = sdkGlobal.createInstance({
|
|
203
|
-
...toInstanceConfig(config),
|
|
204
|
-
batchRpcCalls: false
|
|
205
|
-
}).then((instance) => {
|
|
206
|
-
instances.set(chainId, instance);
|
|
207
|
-
pending.delete(chainId);
|
|
208
|
-
return instance;
|
|
209
|
-
}).catch((err) => {
|
|
210
|
-
pending.delete(chainId);
|
|
211
|
-
throw err;
|
|
212
|
-
});
|
|
213
|
-
pending.set(chainId, promise);
|
|
214
|
-
return promise;
|
|
215
|
-
}
|
|
216
|
-
function unreachableFheType(_) {
|
|
217
|
-
throw new Error("Unsupported FHE type");
|
|
218
|
-
}
|
|
219
|
-
const relayerUrls = /* @__PURE__ */ new Set();
|
|
220
|
-
let csrfTokenBase = "";
|
|
221
|
-
const CSRF_HEADER_NAME = "x-csrf-token";
|
|
222
|
-
const MUTATING_METHODS = /* @__PURE__ */ new Set([
|
|
223
|
-
"POST",
|
|
224
|
-
"PUT",
|
|
225
|
-
"DELETE",
|
|
226
|
-
"PATCH"
|
|
227
|
-
]);
|
|
228
|
-
/**
|
|
229
|
-
* Register relayer URLs from chain configs for fetch interception.
|
|
230
|
-
*/
|
|
231
|
-
function registerRelayerUrls(chainConfigs) {
|
|
232
|
-
for (const c of chainConfigs) if (c.relayerUrl) relayerUrls.add(c.relayerUrl);
|
|
233
|
-
}
|
|
234
|
-
/**
|
|
235
|
-
* Send a success response back to the main thread.
|
|
236
|
-
* Optionally transfers ArrayBuffers for zero-copy performance.
|
|
237
|
-
*/
|
|
238
|
-
function sendSuccess(id, type, data, transfer) {
|
|
239
|
-
const response = {
|
|
240
|
-
id,
|
|
241
|
-
type,
|
|
242
|
-
success: true,
|
|
243
|
-
data
|
|
244
|
-
};
|
|
245
|
-
return transfer ? self.postMessage(response, transfer) : self.postMessage(response);
|
|
246
|
-
}
|
|
247
|
-
/**
|
|
248
|
-
* Send an error response back to the main thread.
|
|
249
|
-
*/
|
|
250
|
-
function sendError(id, type, error) {
|
|
251
|
-
self.postMessage({
|
|
252
|
-
id,
|
|
253
|
-
type,
|
|
254
|
-
success: false,
|
|
255
|
-
error: error instanceof Error ? error.message : String(error),
|
|
256
|
-
serialized: serializeError(error)
|
|
257
|
-
});
|
|
258
|
-
}
|
|
259
|
-
const originalFetch = fetch;
|
|
260
|
-
/** Allowed CDN hostnames for loading the relayer SDK script. */
|
|
261
|
-
const ALLOWED_CDN_HOSTS = /* @__PURE__ */ new Set(["cdn.zama.org"]);
|
|
262
|
-
/**
|
|
263
|
-
* Validate the CDN URL supplied by the caller.
|
|
264
|
-
* Ensures only HTTPS URLs from approved hosts are used when loading
|
|
265
|
-
* SDK code into the worker.
|
|
266
|
-
*/
|
|
267
|
-
function validateCdnUrl(rawUrl) {
|
|
268
|
-
let url;
|
|
269
|
-
try {
|
|
270
|
-
url = new URL(rawUrl);
|
|
271
|
-
} catch {
|
|
272
|
-
throw new Error("Invalid CDN URL");
|
|
273
|
-
}
|
|
274
|
-
if (url.protocol !== "https:") throw new Error("CDN URL must use https");
|
|
275
|
-
if (!ALLOWED_CDN_HOSTS.has(url.hostname)) throw new Error(`CDN URL host is not allowed: ${url.hostname}`);
|
|
276
|
-
return url.toString();
|
|
277
|
-
}
|
|
278
|
-
/**
|
|
279
|
-
* Set up fetch interceptor to add credentials and CSRF token for relayer requests.
|
|
280
|
-
* Workers don't automatically include cookies, so we intercept fetch calls
|
|
281
|
-
* targeting our relayer proxy to inject credentials and CSRF headers.
|
|
282
|
-
*/
|
|
283
|
-
function setupFetchInterceptor() {
|
|
284
|
-
globalThis.fetch = async (input, init) => {
|
|
285
|
-
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
|
|
286
|
-
const method = init?.method?.toUpperCase() ?? "GET";
|
|
287
|
-
if (relayerUrls.size > 0 && [...relayerUrls].some((base) => url.startsWith(base))) {
|
|
288
|
-
const headers = new Headers(init?.headers);
|
|
289
|
-
if (MUTATING_METHODS.has(method) && csrfTokenBase) headers.set(CSRF_HEADER_NAME, csrfTokenBase);
|
|
290
|
-
return originalFetch(input, {
|
|
291
|
-
...init,
|
|
292
|
-
headers,
|
|
293
|
-
credentials: "include"
|
|
294
|
-
});
|
|
295
|
-
}
|
|
296
|
-
return originalFetch(input, init);
|
|
297
|
-
};
|
|
298
|
-
}
|
|
299
|
-
/**
|
|
300
|
-
* Verify a fetched script's SHA-384 hash matches the expected integrity value.
|
|
301
|
-
*/
|
|
302
|
-
async function verifyIntegrity(content, expectedHash) {
|
|
303
|
-
const encoder = new TextEncoder();
|
|
304
|
-
const hashBuffer = await crypto.subtle.digest("SHA-384", encoder.encode(content));
|
|
305
|
-
const hashHex = [...new Uint8Array(hashBuffer)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
306
|
-
if (hashHex !== expectedHash) throw new Error(`CDN integrity check failed: expected SHA-384 ${expectedHash}, got ${hashHex}`);
|
|
307
|
-
}
|
|
308
|
-
/**
|
|
309
|
-
* Load SDK script from CDN.
|
|
310
|
-
* Uses two strategies depending on the environment:
|
|
311
|
-
* - **Web apps (default):** fetch + blob URL + importScripts. Avoids MIME-type
|
|
312
|
-
* rejections (some CDNs serve .cjs as `application/node`) and CSP
|
|
313
|
-
* `unsafe-eval` violations.
|
|
314
|
-
* - **Browser extensions (Chrome/Firefox/Safari):** importScripts directly.
|
|
315
|
-
* Blob URLs are blocked by extension CSP, but the CDN must be allowed
|
|
316
|
-
* in the extension's manifest CSP.
|
|
317
|
-
*
|
|
318
|
-
* Integrity is always verified when a hash is provided, regardless of strategy.
|
|
319
|
-
*/
|
|
320
|
-
async function fetchScript(cdnUrl) {
|
|
321
|
-
const response = await originalFetch(cdnUrl);
|
|
322
|
-
if (!response.ok) throw new Error(`Failed to fetch SDK: ${response.status} ${response.statusText}`);
|
|
323
|
-
return response.text();
|
|
324
|
-
}
|
|
325
|
-
async function loadSdkScript(cdnUrl, integrity) {
|
|
326
|
-
const validatedUrl = validateCdnUrl(cdnUrl);
|
|
327
|
-
if (getBrowserExtensionRuntime()) {
|
|
328
|
-
if (integrity) await verifyIntegrity(await fetchScript(validatedUrl), integrity);
|
|
329
|
-
return self.importScripts(validatedUrl);
|
|
330
|
-
}
|
|
331
|
-
const scriptContent = await fetchScript(validatedUrl);
|
|
332
|
-
if (integrity) await verifyIntegrity(scriptContent, integrity);
|
|
333
|
-
const blob = new Blob([scriptContent], { type: "application/javascript" });
|
|
334
|
-
const blobUrl = URL.createObjectURL(blob);
|
|
335
|
-
try {
|
|
336
|
-
self.importScripts(blobUrl);
|
|
337
|
-
} finally {
|
|
338
|
-
URL.revokeObjectURL(blobUrl);
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
/**
|
|
342
|
-
* Handle INIT request - load SDK WASM and register chain configs (instances are lazy).
|
|
343
|
-
*/
|
|
344
|
-
async function handleInit(request) {
|
|
345
|
-
const { id, type, payload } = request;
|
|
346
|
-
try {
|
|
347
|
-
if (payload.env !== "web") throw new Error(`Web worker received unexpected env: ${payload.env}`);
|
|
348
|
-
const { cdnUrl, csrfToken, integrity, thread } = payload;
|
|
349
|
-
csrfTokenBase = csrfToken;
|
|
350
|
-
setupFetchInterceptor();
|
|
351
|
-
await loadSdkScript(cdnUrl, integrity);
|
|
352
|
-
if (!self.relayerSDK) throw new Error("Failed to load relayerSDK from CDN");
|
|
353
|
-
sdkGlobal = self.relayerSDK;
|
|
354
|
-
await sdkGlobal.initSDK(thread !== null && thread !== void 0 ? { thread } : void 0);
|
|
355
|
-
registerRelayerUrls(payload.chains);
|
|
356
|
-
for (const chain of payload.chains) configs.set(chain.id, chain);
|
|
357
|
-
sendSuccess(id, type, { initialized: true });
|
|
358
|
-
} catch (error) {
|
|
359
|
-
sendError(id, type, error);
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
/** Coerce a boolean to bigint for numeric FHE types. */
|
|
363
|
-
function toBigInt(value) {
|
|
364
|
-
return typeof value === "boolean" ? value ? 1n : 0n : value;
|
|
365
|
-
}
|
|
366
|
-
/**
|
|
367
|
-
* Add a single typed value to the encrypted input builder.
|
|
368
|
-
*/
|
|
369
|
-
function addTypedValue(input, entry) {
|
|
370
|
-
const { value, type: fheType } = entry;
|
|
371
|
-
switch (fheType) {
|
|
372
|
-
case "ebool":
|
|
373
|
-
input.addBool(typeof value === "boolean" ? value : value !== 0n);
|
|
374
|
-
break;
|
|
375
|
-
case "euint8":
|
|
376
|
-
input.add8(toBigInt(value));
|
|
377
|
-
break;
|
|
378
|
-
case "euint16":
|
|
379
|
-
input.add16(toBigInt(value));
|
|
380
|
-
break;
|
|
381
|
-
case "euint32":
|
|
382
|
-
input.add32(toBigInt(value));
|
|
383
|
-
break;
|
|
384
|
-
case "euint64":
|
|
385
|
-
input.add64(toBigInt(value));
|
|
386
|
-
break;
|
|
387
|
-
case "euint128":
|
|
388
|
-
input.add128(toBigInt(value));
|
|
389
|
-
break;
|
|
390
|
-
case "euint256":
|
|
391
|
-
input.add256(toBigInt(value));
|
|
392
|
-
break;
|
|
393
|
-
case "eaddress":
|
|
394
|
-
input.addAddress(value);
|
|
395
|
-
break;
|
|
396
|
-
default: unreachableFheType(fheType);
|
|
397
|
-
}
|
|
398
|
-
}
|
|
399
|
-
/**
|
|
400
|
-
* Handle ENCRYPT request.
|
|
401
|
-
*/
|
|
402
|
-
async function handleEncrypt(request) {
|
|
403
|
-
const { id, type, payload } = request;
|
|
404
|
-
const { values, contractAddress, userAddress } = payload;
|
|
405
|
-
try {
|
|
406
|
-
const input = (await getInstance(payload.chainId)).createEncryptedInput(contractAddress, userAddress);
|
|
407
|
-
for (const entry of values) addTypedValue(input, entry);
|
|
408
|
-
const encrypted = await input.encrypt();
|
|
409
|
-
sendSuccess(id, type, {
|
|
410
|
-
handles: encrypted.handles,
|
|
411
|
-
inputProof: encrypted.inputProof
|
|
412
|
-
}, [encrypted.inputProof.buffer, ...encrypted.handles.map((h) => h.buffer)]);
|
|
413
|
-
} catch (error) {
|
|
414
|
-
sendError(id, type, error);
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
/**
|
|
418
|
-
* Handle USER_DECRYPT request.
|
|
419
|
-
*/
|
|
420
|
-
async function handleUserDecrypt(request) {
|
|
421
|
-
const { id, type, payload } = request;
|
|
422
|
-
try {
|
|
423
|
-
const instance = await getInstance(payload.chainId);
|
|
424
|
-
const handleContractPairs = payload.encryptedValues.map((encryptedValue) => ({
|
|
425
|
-
handle: encryptedValue,
|
|
426
|
-
contractAddress: payload.contractAddress
|
|
427
|
-
}));
|
|
428
|
-
sendSuccess(id, type, { clearValues: await instance.userDecrypt(handleContractPairs, unprefixHex(payload.privateKey), unprefixHex(payload.publicKey), payload.signature, payload.signedContractAddresses, payload.signerAddress, payload.startTimestamp, payload.durationDays) });
|
|
429
|
-
} catch (error) {
|
|
430
|
-
sendError(id, type, error);
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
/**
|
|
434
|
-
* Handle PUBLIC_DECRYPT request.
|
|
435
|
-
*/
|
|
436
|
-
async function handlePublicDecrypt(request) {
|
|
437
|
-
const { id, type, payload } = request;
|
|
438
|
-
try {
|
|
439
|
-
sendSuccess(id, type, { ...await (await getInstance(payload.chainId)).publicDecrypt(payload.encryptedValues) });
|
|
440
|
-
} catch (error) {
|
|
441
|
-
sendError(id, type, error);
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
/**
|
|
445
|
-
* Handle GENERATE_KEYPAIR request.
|
|
446
|
-
*/
|
|
447
|
-
async function handleGenerateKeypair(request) {
|
|
448
|
-
const { id, type, payload } = request;
|
|
449
|
-
try {
|
|
450
|
-
const keypair = (await getInstance(payload.chainId)).generateKeypair();
|
|
451
|
-
sendSuccess(id, type, {
|
|
452
|
-
publicKey: prefixHex(keypair.publicKey),
|
|
453
|
-
privateKey: prefixHex(keypair.privateKey)
|
|
454
|
-
});
|
|
455
|
-
} catch (error) {
|
|
456
|
-
sendError(id, type, error);
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
/**
|
|
460
|
-
* Handle CREATE_EIP712 request.
|
|
461
|
-
*/
|
|
462
|
-
async function handleCreateEIP712(request) {
|
|
463
|
-
const { id, type, payload } = request;
|
|
464
|
-
try {
|
|
465
|
-
sendSuccess(id, type, (await getInstance(payload.chainId)).createEIP712(unprefixHex(payload.publicKey), payload.contractAddresses, payload.startTimestamp, payload.durationDays));
|
|
466
|
-
} catch (error) {
|
|
467
|
-
sendError(id, type, error);
|
|
468
|
-
}
|
|
469
|
-
}
|
|
470
|
-
/**
|
|
471
|
-
* Handle CREATE_DELEGATED_EIP712 request.
|
|
472
|
-
*/
|
|
473
|
-
async function handleCreateDelegatedEIP712(request) {
|
|
474
|
-
const { id, type, payload } = request;
|
|
475
|
-
try {
|
|
476
|
-
sendSuccess(id, type, (await getInstance(payload.chainId)).createDelegatedUserDecryptEIP712(unprefixHex(payload.publicKey), payload.contractAddresses, payload.delegatorAddress, payload.startTimestamp, payload.durationDays));
|
|
477
|
-
} catch (error) {
|
|
478
|
-
sendError(id, type, error);
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
|
-
/**
|
|
482
|
-
* Handle DELEGATED_USER_DECRYPT request.
|
|
483
|
-
*/
|
|
484
|
-
async function handleDelegatedUserDecrypt(request) {
|
|
485
|
-
const { id, type, payload } = request;
|
|
486
|
-
try {
|
|
487
|
-
const instance = await getInstance(payload.chainId);
|
|
488
|
-
const handleContractPairs = payload.encryptedValues.map((encryptedValue) => ({
|
|
489
|
-
handle: encryptedValue,
|
|
490
|
-
contractAddress: payload.contractAddress
|
|
491
|
-
}));
|
|
492
|
-
sendSuccess(id, type, { clearValues: await instance.delegatedUserDecrypt(handleContractPairs, unprefixHex(payload.privateKey), unprefixHex(payload.publicKey), payload.signature, payload.signedContractAddresses, payload.delegatorAddress, payload.delegateAddress, payload.startTimestamp, payload.durationDays) });
|
|
493
|
-
} catch (error) {
|
|
494
|
-
sendError(id, type, error);
|
|
495
|
-
}
|
|
496
|
-
}
|
|
497
|
-
/**
|
|
498
|
-
* Handle REQUEST_ZK_PROOF_VERIFICATION request.
|
|
499
|
-
*/
|
|
500
|
-
async function handleRequestZKProofVerification(request) {
|
|
501
|
-
const { id, type, payload } = request;
|
|
502
|
-
try {
|
|
503
|
-
const result = await (await getInstance(payload.chainId)).requestZKProofVerification(payload.zkProof);
|
|
504
|
-
sendSuccess(id, type, result, [result.inputProof.buffer, ...result.handles.map((h) => h.buffer)]);
|
|
505
|
-
} catch (error) {
|
|
506
|
-
sendError(id, type, error);
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
/**
|
|
510
|
-
* Handle GET_PUBLIC_KEY request.
|
|
511
|
-
*/
|
|
512
|
-
async function handleGetPublicKey(request) {
|
|
513
|
-
const { id, type, payload } = request;
|
|
514
|
-
try {
|
|
515
|
-
sendSuccess(id, type, { result: (await getInstance(payload.chainId)).getPublicKey() });
|
|
516
|
-
} catch (error) {
|
|
517
|
-
sendError(id, type, error);
|
|
518
|
-
}
|
|
519
|
-
}
|
|
520
|
-
/**
|
|
521
|
-
* Handle GET_PUBLIC_PARAMS request.
|
|
522
|
-
*/
|
|
523
|
-
async function handleGetPublicParams(request) {
|
|
524
|
-
const { id, type, payload } = request;
|
|
525
|
-
try {
|
|
526
|
-
sendSuccess(id, type, { result: (await getInstance(payload.chainId)).getPublicParams(payload.bits) });
|
|
527
|
-
} catch (error) {
|
|
528
|
-
sendError(id, type, error);
|
|
529
|
-
}
|
|
530
|
-
}
|
|
531
|
-
/**
|
|
532
|
-
* Handle UPDATE_CSRF request - update the stored CSRF token.
|
|
533
|
-
*/
|
|
534
|
-
function handleUpdateCsrf(request) {
|
|
535
|
-
const { id, type, payload } = request;
|
|
536
|
-
csrfTokenBase = payload.csrfToken;
|
|
537
|
-
sendSuccess(id, type, { updated: true });
|
|
538
|
-
}
|
|
539
|
-
/**
|
|
540
|
-
* Main message handler.
|
|
541
|
-
*/
|
|
542
|
-
self.onmessage = async (event) => {
|
|
543
|
-
const request = event.data;
|
|
544
|
-
try {
|
|
545
|
-
switch (request.type) {
|
|
546
|
-
case "INIT":
|
|
547
|
-
await handleInit(request);
|
|
548
|
-
break;
|
|
549
|
-
case "UPDATE_CSRF":
|
|
550
|
-
handleUpdateCsrf(request);
|
|
551
|
-
break;
|
|
552
|
-
case "ENCRYPT":
|
|
553
|
-
await handleEncrypt(request);
|
|
554
|
-
break;
|
|
555
|
-
case "USER_DECRYPT":
|
|
556
|
-
await handleUserDecrypt(request);
|
|
557
|
-
break;
|
|
558
|
-
case "PUBLIC_DECRYPT":
|
|
559
|
-
await handlePublicDecrypt(request);
|
|
560
|
-
break;
|
|
561
|
-
case "GENERATE_KEYPAIR":
|
|
562
|
-
await handleGenerateKeypair(request);
|
|
563
|
-
break;
|
|
564
|
-
case "CREATE_EIP712":
|
|
565
|
-
await handleCreateEIP712(request);
|
|
566
|
-
break;
|
|
567
|
-
case "CREATE_DELEGATED_EIP712":
|
|
568
|
-
await handleCreateDelegatedEIP712(request);
|
|
569
|
-
break;
|
|
570
|
-
case "DELEGATED_USER_DECRYPT":
|
|
571
|
-
await handleDelegatedUserDecrypt(request);
|
|
572
|
-
break;
|
|
573
|
-
case "REQUEST_ZK_PROOF_VERIFICATION":
|
|
574
|
-
await handleRequestZKProofVerification(request);
|
|
575
|
-
break;
|
|
576
|
-
case "GET_PUBLIC_KEY":
|
|
577
|
-
await handleGetPublicKey(request);
|
|
578
|
-
break;
|
|
579
|
-
case "GET_PUBLIC_PARAMS":
|
|
580
|
-
await handleGetPublicParams(request);
|
|
581
|
-
break;
|
|
582
|
-
default: throw new Error(`Unknown request type: ${request.type}`);
|
|
583
|
-
}
|
|
584
|
-
} catch (error) {
|
|
585
|
-
sendError(request?.id ?? "unknown", request?.type ?? "UNKNOWN", error);
|
|
586
|
-
}
|
|
587
|
-
};
|
|
588
|
-
//#endregion
|
|
589
|
-
})();
|
package/dist/cjs/timeout.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./relayer.cjs");var t=class extends e.r{operation;timeout;elapsed;worker;constructor(t,n){super(e.i.OperationTimeout,`Worker operation ${t.operation} timed out after ${t.timeout}s`+(t.worker?` (worker ${t.worker})`:``),n),this.name=`WorkerTimeoutError`,this.operation=t.operation,this.timeout=t.timeout,this.elapsed=t.elapsed,this.worker=t.worker}},n=class extends e.r{operation;worker;constructor(t,n){super(e.i.WorkerRecycled,`Worker operation ${t.operation} was aborted because its worker was recycled after a timeout`+(t.worker?` (worker ${t.worker})`:``),n),this.name=`WorkerRecycledError`,this.operation=t.operation,this.worker=t.worker}};Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return n}});
|
|
2
|
-
//# sourceMappingURL=timeout.cjs.map
|
package/dist/cjs/timeout.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"timeout.cjs","names":["ZamaError","ZamaErrorCode"],"sources":["../../src/errors/timeout.ts"],"sourcesContent":["import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/**\n * A worker operation (encrypt / decrypt / EIP-712 / key fetch) did not complete\n * within its configured timeout — typically a stuck relayer or WASM call. On the\n * Node pool the SDK **recycles the affected worker** (terminating the hung\n * thread) so it self-heals; the operation itself is **retryable**.\n *\n * Configure the bound (seconds) via `node({ operationTimeout })`. Distinct from a\n * decryption/entitlement failure — a timeout is an infrastructure/latency\n * condition, so it no longer collapses into {@link DecryptionFailedError}.\n *\n * @example\n * ```ts\n * try {\n * await sdk.decryption.decryptValues([{ encryptedValue, contractAddress }]);\n * } catch (e) {\n * if (e instanceof WorkerTimeoutError) {\n * // retry (the worker was recycled); consider raising operationTimeout\n * }\n * }\n * ```\n */\nexport class WorkerTimeoutError extends ZamaError {\n /**\n * The worker operation that timed out. This is the internal worker op code\n * (e.g. `USER_DECRYPT`, `ENCRYPT`), not the public SDK method name.\n */\n readonly operation: string;\n /** The configured timeout that was exceeded, in **seconds** (the SDK's duration unit). */\n readonly timeout: number;\n /** Wall-clock time the operation ran before being abandoned, in **seconds** (may be fractional). */\n readonly elapsed: number;\n /** Label of the worker that stalled, when known (e.g. `node-worker-2`). */\n readonly worker: string | undefined;\n\n constructor(\n args: { operation: string; timeout: number; elapsed: number; worker?: string },\n options?: ErrorOptions,\n ) {\n super(\n ZamaErrorCode.OperationTimeout,\n `Worker operation ${args.operation} timed out after ${args.timeout}s` +\n (args.worker ? ` (worker ${args.worker})` : \"\"),\n options,\n );\n this.name = \"WorkerTimeoutError\";\n this.operation = args.operation;\n this.timeout = args.timeout;\n this.elapsed = args.elapsed;\n this.worker = args.worker;\n }\n}\n\n/**\n * An in-flight worker operation was aborted as **collateral** when its worker was\n * recycled — the worker was torn down to recover from *another* operation's\n * timeout (Node pool self-healing), not because this operation itself timed out.\n *\n * The operation never reached a verdict, so it is **retryable**: the next call\n * lazily re-inits a fresh worker. It is intentionally distinct from\n * {@link WorkerTimeoutError} (this op did not exceed its own bound) and from\n * {@link DecryptionFailedError} (nothing actually failed to decrypt) — so a\n * consumer can retry it instead of surfacing a terminal failure.\n *\n * @example\n * ```ts\n * matchZamaError(error, {\n * WORKER_RECYCLED: () => retry(), // transient: the worker was replaced\n * });\n * ```\n */\nexport class WorkerRecycledError extends ZamaError {\n /**\n * The worker operation that was aborted. This is the internal worker op code\n * (e.g. `USER_DECRYPT`, `ENCRYPT`), not the public SDK method name.\n */\n readonly operation: string;\n /** Label of the recycled worker, when known (e.g. `node-worker-2`). */\n readonly worker: string | undefined;\n\n constructor(args: { operation: string; worker?: string }, options?: ErrorOptions) {\n super(\n ZamaErrorCode.WorkerRecycled,\n `Worker operation ${args.operation} was aborted because its worker was recycled after a timeout` +\n (args.worker ? ` (worker ${args.worker})` : \"\"),\n options,\n );\n this.name = \"WorkerRecycledError\";\n this.operation = args.operation;\n this.worker = args.worker;\n }\n}\n"],"mappings":"iCAuBA,IAAa,EAAb,cAAwCA,EAAAA,CAAU,CAKhD,UAEA,QAEA,QAEA,OAEA,YACE,EACA,EACA,CACA,MACEC,EAAAA,EAAc,iBACd,oBAAoB,EAAK,UAAU,mBAAmB,EAAK,QAAQ,IAChE,EAAK,OAAS,YAAY,EAAK,OAAO,GAAK,IAC9C,CACF,EACA,KAAK,KAAO,qBACZ,KAAK,UAAY,EAAK,UACtB,KAAK,QAAU,EAAK,QACpB,KAAK,QAAU,EAAK,QACpB,KAAK,OAAS,EAAK,MACrB,CACF,EAoBa,EAAb,cAAyCD,EAAAA,CAAU,CAKjD,UAEA,OAEA,YAAY,EAA8C,EAAwB,CAChF,MACEC,EAAAA,EAAc,eACd,oBAAoB,EAAK,UAAU,+DAChC,EAAK,OAAS,YAAY,EAAK,OAAO,GAAK,IAC9C,CACF,EACA,KAAK,KAAO,sBACZ,KAAK,UAAY,EAAK,UACtB,KAAK,OAAS,EAAK,MACrB,CACF"}
|
package/dist/cjs/validation.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./relayer.cjs");let t=require("zod/mini");var n=class{#e=null;#t=null;#n;#r;#i;constructor(e=`CredentialStore`,t=1,n=`credentials`){this.#n=e,this.#r=t,this.#i=n}#a(){return this.#e?Promise.resolve(this.#e):(this.#t||=new Promise((e,t)=>{let n=indexedDB.open(this.#n,this.#r);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(this.#i)||e.createObjectStore(this.#i,{keyPath:`key`})},n.onsuccess=()=>{this.#e=n.result,this.#t=null,this.#e.onversionchange=()=>{this.#e?.close(),this.#e=null,this.#t=null},this.#e.onclose=()=>{this.#e=null,this.#t=null},e(this.#e)},n.onerror=()=>{this.#e=null,this.#t=null,t(n.error)}}),this.#t)}async#o(e,t){let n=await this.#a();return new Promise((r,i)=>{let a=n.transaction(this.#i,e);a.onabort=()=>i(a.error??Error(`Transaction aborted`));let o=t(a.objectStore(this.#i));e===`readonly`?o.onsuccess=()=>r(o.result):a.oncomplete=()=>r(o.result),o.onerror=()=>i(o.error)})}async get(e){return(await this.#o(`readonly`,t=>t.get(e)))?.value??null}async set(e,t){await this.#o(`readwrite`,n=>n.put({key:e,value:t}))}async delete(e){await this.#o(`readwrite`,t=>t.delete(e))}async clear(){await this.#o(`readwrite`,e=>e.clear())}};const r=new n;function i(n,r){let i=t.z.safeParse(n,r);if(i.success)return i.data;throw new e.t(t.z.prettifyError(i.error),{cause:i.error})}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return i}});
|
|
2
|
-
//# sourceMappingURL=validation.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"validation.cjs","names":["#dbName","#dbVersion","#storeName","#db","#dbPromise","#withTransaction","#getDB","z","ConfigurationError"],"sources":["../../src/storage/indexeddb-storage.ts","../../src/validation.ts"],"sourcesContent":["\"use client\";\n\nimport type { GenericStorage } from \"../types\";\n\n/**\n * IndexedDB-backed {@link GenericStorage}.\n *\n * Stores keypair and permit objects keyed by a hashed wallet address. The\n * SDK delegates security to the storage backend — values are persisted\n * verbatim with no SDK-layer encryption.\n */\nexport class IndexedDBStorage implements GenericStorage {\n #db: IDBDatabase | null = null;\n #dbPromise: Promise<IDBDatabase> | null = null;\n #dbName: string;\n #dbVersion: number;\n #storeName: string;\n\n constructor(dbName = \"CredentialStore\", dbVersion = 1, storeName = \"credentials\") {\n this.#dbName = dbName;\n this.#dbVersion = dbVersion;\n this.#storeName = storeName;\n }\n\n #getDB(): Promise<IDBDatabase> {\n if (this.#db) {\n return Promise.resolve(this.#db);\n }\n if (this.#dbPromise) {\n return this.#dbPromise;\n }\n\n this.#dbPromise = new Promise((resolve, reject) => {\n const request = indexedDB.open(this.#dbName, this.#dbVersion);\n\n request.onupgradeneeded = () => {\n const db = request.result;\n if (!db.objectStoreNames.contains(this.#storeName)) {\n db.createObjectStore(this.#storeName, { keyPath: \"key\" });\n }\n };\n\n request.onsuccess = () => {\n this.#db = request.result;\n this.#dbPromise = null;\n this.#db.onversionchange = () => {\n // Another tab upgraded the DB; close our handle so it can proceed.\n // Informational only and self-healing, so emit nothing to the console.\n this.#db?.close();\n this.#db = null;\n this.#dbPromise = null;\n };\n this.#db.onclose = () => {\n this.#db = null;\n this.#dbPromise = null;\n };\n resolve(this.#db);\n };\n\n request.onerror = () => {\n this.#db = null;\n this.#dbPromise = null;\n reject(request.error);\n };\n });\n\n return this.#dbPromise;\n }\n\n async #withTransaction<T>(\n mode: IDBTransactionMode,\n fn: (store: IDBObjectStore) => IDBRequest,\n ): Promise<T> {\n const db = await this.#getDB();\n return new Promise((resolve, reject) => {\n const tx = db.transaction(this.#storeName, mode);\n tx.onabort = () => reject(tx.error ?? new Error(\"Transaction aborted\"));\n const request = fn(tx.objectStore(this.#storeName));\n if (mode === \"readonly\") {\n request.onsuccess = () => resolve(request.result);\n } else {\n tx.oncomplete = () => resolve(request.result);\n }\n request.onerror = () => reject(request.error);\n });\n }\n\n async get<T = unknown>(key: string): Promise<T | null> {\n const result = await this.#withTransaction<{ value: T } | undefined>(\"readonly\", (store) =>\n store.get(key),\n );\n return result?.value ?? null;\n }\n\n async set<T = unknown>(key: string, value: T): Promise<void> {\n await this.#withTransaction<void>(\"readwrite\", (store) => store.put({ key, value }));\n }\n\n async delete(key: string): Promise<void> {\n await this.#withTransaction<void>(\"readwrite\", (store) => store.delete(key));\n }\n\n async clear(): Promise<void> {\n await this.#withTransaction<void>(\"readwrite\", (store) => store.clear());\n }\n}\n\n/** Default singleton for application-wide use. */\nexport const indexedDBStorage = new IndexedDBStorage();\n","import { z } from \"zod/mini\";\nimport { ConfigurationError } from \"./errors\";\n\nexport function parseConfiguration<T>(schema: z.core.$ZodType<T>, value: unknown): T {\n const parsed = z.safeParse(schema, value);\n if (parsed.success) {\n return parsed.data;\n }\n throw new ConfigurationError(z.prettifyError(parsed.error), { cause: parsed.error });\n}\n"],"mappings":"2DAWA,IAAa,EAAb,KAAwD,CACtD,GAA0B,KAC1B,GAA0C,KAC1C,GACA,GACA,GAEA,YAAY,EAAS,kBAAmB,EAAY,EAAG,EAAY,cAAe,CAChF,KAAKA,GAAU,EACf,KAAKC,GAAa,EAClB,KAAKC,GAAa,CACpB,CAEA,IAA+B,CA0C7B,OAzCI,KAAKC,GACA,QAAQ,QAAQ,KAAKA,EAAG,GAE7B,AAIJ,KAAKC,KAAa,IAAI,SAAS,EAAS,IAAW,CACjD,IAAM,EAAU,UAAU,KAAK,KAAKJ,GAAS,KAAKC,EAAU,EAE5D,EAAQ,oBAAwB,CAC9B,IAAM,EAAK,EAAQ,OACd,EAAG,iBAAiB,SAAS,KAAKC,EAAU,GAC/C,EAAG,kBAAkB,KAAKA,GAAY,CAAE,QAAS,KAAM,CAAC,CAE5D,EAEA,EAAQ,cAAkB,CACxB,KAAKC,GAAM,EAAQ,OACnB,KAAKC,GAAa,KAClB,KAAKD,GAAI,oBAAwB,CAG/B,KAAKA,IAAK,MAAM,EAChB,KAAKA,GAAM,KACX,KAAKC,GAAa,IACpB,EACA,KAAKD,GAAI,YAAgB,CACvB,KAAKA,GAAM,KACX,KAAKC,GAAa,IACpB,EACA,EAAQ,KAAKD,EAAG,CAClB,EAEA,EAAQ,YAAgB,CACtB,KAAKA,GAAM,KACX,KAAKC,GAAa,KAClB,EAAO,EAAQ,KAAK,CACtB,CACF,CAAC,EAnCQ,KAAKA,GAsChB,CAEA,KAAMC,GACJ,EACA,EACY,CACZ,IAAM,EAAK,MAAM,KAAKC,GAAO,EAC7B,OAAO,IAAI,SAAS,EAAS,IAAW,CACtC,IAAM,EAAK,EAAG,YAAY,KAAKJ,GAAY,CAAI,EAC/C,EAAG,YAAgB,EAAO,EAAG,OAAa,MAAM,qBAAqB,CAAC,EACtE,IAAM,EAAU,EAAG,EAAG,YAAY,KAAKA,EAAU,CAAC,EAC9C,IAAS,WACX,EAAQ,cAAkB,EAAQ,EAAQ,MAAM,EAEhD,EAAG,eAAmB,EAAQ,EAAQ,MAAM,EAE9C,EAAQ,YAAgB,EAAO,EAAQ,KAAK,CAC9C,CAAC,CACH,CAEA,MAAM,IAAiB,EAAgC,CAIrD,OAAO,MAHc,KAAKG,GAA2C,WAAa,GAChF,EAAM,IAAI,CAAG,CACf,EAAA,EACe,OAAS,IAC1B,CAEA,MAAM,IAAiB,EAAa,EAAyB,CAC3D,MAAM,KAAKA,GAAuB,YAAc,GAAU,EAAM,IAAI,CAAE,MAAK,OAAM,CAAC,CAAC,CACrF,CAEA,MAAM,OAAO,EAA4B,CACvC,MAAM,KAAKA,GAAuB,YAAc,GAAU,EAAM,OAAO,CAAG,CAAC,CAC7E,CAEA,MAAM,OAAuB,CAC3B,MAAM,KAAKA,GAAuB,YAAc,GAAU,EAAM,MAAM,CAAC,CACzE,CACF,EAGA,MAAa,EAAmB,IAAI,ECzGpC,SAAgB,EAAsB,EAA4B,EAAmB,CACnF,IAAM,EAASE,EAAAA,EAAE,UAAU,EAAQ,CAAK,EACxC,GAAI,EAAO,QACT,OAAO,EAAO,KAEhB,MAAM,IAAIC,EAAAA,EAAmBD,EAAAA,EAAE,cAAc,EAAO,KAAK,EAAG,CAAE,MAAO,EAAO,KAAM,CAAC,CACrF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
function e(e){return e instanceof Error?e:typeof e==`object`&&e&&`message`in e?Error(String(e.message)):Error(String(e))}function t(e){if(!(e instanceof Error))return!1;if(e.name===`ContractFunctionExecutionError`||e.name===`ContractFunctionRevertedError`||`code`in e&&e.code===`CALL_EXCEPTION`)return!0;let t=e.message.toLowerCase();return t.includes(`execution reverted`)||t.includes(`call revert exception`)}const n=[`cause`,`error`,`info`];function r(e,t,i=6){if(i<0||typeof e!=`object`||!e)return;let a=e;if(t(a))return a;for(let e of n){let n=a[e];if(typeof n==`object`&&n){let e=r(n,t,i-1);if(e)return e}}}const i=[`code`,`status`,`statusCode`,`retryAfter`];function a(e){let t=e.info;if(typeof t==`object`&&t){let e=t.responseStatus;if(typeof e==`string`)return e}}function o(e,t){if(t.code===void 0&&(typeof e.code==`string`||typeof e.code==`number`)&&(t.code=e.code),t.status===void 0&&typeof e.status==`number`&&(t.status=e.status),t.statusCode===void 0&&typeof e.statusCode==`number`&&(t.statusCode=e.statusCode),t.responseStatus===void 0){let n=a(e);n!==void 0&&(t.responseStatus=n)}if(t.retryAfter===void 0)if(typeof e.retryAfter==`number`)t.retryAfter=e.retryAfter;else{let n=S(e);n!==void 0&&(t.retryAfter=n)}}function s(e,t){t.code===void 0&&e.code!==void 0&&(t.code=e.code),t.status===void 0&&e.status!==void 0&&(t.status=e.status),t.statusCode===void 0&&e.statusCode!==void 0&&(t.statusCode=e.statusCode),t.responseStatus===void 0&&e.responseStatus!==void 0&&(t.responseStatus=e.responseStatus),t.retryAfter===void 0&&e.retryAfter!==void 0&&(t.retryAfter=e.retryAfter)}function c(t,r=6){let i=e(t),a=typeof t==`object`&&t?t:i,l={name:i.name,message:i.message};if(o(a,l),r>0)for(let e of n){let t=a[e];if(typeof t==`object`&&t){let e=c(t,r-1);l.cause===void 0&&(l.cause=e),s(e,l)}}return l}function l(e){let t=Error(e.message);e.name&&(t.name=e.name);for(let n of i){let r=e[n];r!==void 0&&(t[n]=r)}return e.responseStatus!==void 0&&(t.info={responseStatus:e.responseStatus}),e.cause&&(t.cause=l(e.cause)),t}function u(e){if(e.code===-32005||e.status===429||e.code===429)return!0;if(e.code===`SERVER_ERROR`&&typeof e.info==`object`&&e.info!==null){let t=e.info.responseStatus;if(typeof t==`string`&&/^\s*429\b/.test(t))return!0}return!1}function d(e){if(u(e))return!0;if(typeof e.message==`string`){let t=e.message.toLowerCase();return t.includes(`too many requests`)||t.includes(`rate limit`)||t.includes(`rate-limit`)}return!1}function f(e){return r(e,e=>e.code===`RELAYER_FETCH_ERROR`)!==void 0}function p(e){return f(e)?!1:r(e,d)!==void 0}function m(e){return f(e)?!1:r(e,u)!==void 0}function h(e){let t=e.code;if(t===`NETWORK_ERROR`||t===`SERVER_ERROR`||t===`TIMEOUT`)return!0;let n=e.name;return n===`HttpRequestError`||n===`RpcRequestError`||n===`TimeoutError`||n===`WebSocketRequestError`}function g(e){return f(e)?!1:m(e)?!0:r(e,h)!==void 0}function _(e){if(!(e instanceof Error)||g(e))return!1;if(r(e,e=>e.code===`RELAYER_FETCH_ERROR`&&(e.status===502||e.status===503||e.status===504)))return!0;let t=e.message.toLowerCase();return t.includes(`econnreset`)||t.includes(`econnrefused`)||t.includes(`socket hang up`)||t.includes(`fetch failed`)||t.includes(`network`)}function v(e){let t=e.toLowerCase();return t.includes(`user address`)&&t.includes(`is not authorized to user decrypt`)}function y(e){return/handle (0x[0-9a-fA-F]{64})/.exec(e)?.[1]}function b(e){if(e==null)return;let t=e.trim();if(t!==``){if(/^\d+$/.test(t))return Number(t);if(/[a-zA-Z]/.test(t)){let e=Date.parse(t);if(!Number.isNaN(e))return Math.max(0,Math.round((e-Date.now())/1e3))}}}function x(e){if(typeof e!=`object`||!e)return;let t=e.get;if(typeof t==`function`)return b(t.call(e,`Retry-After`))}function S(e){let t=e.response;if(typeof t==`object`&&t)return x(t.headers)}function C(e){return typeof e.retryAfter==`number`&&Number.isFinite(e.retryAfter)&&e.retryAfter>0?e.retryAfter:S(e)}function w(e){let t=r(e,e=>C(e)!==void 0);return t?C(t):void 0}function T(e){let t=r(e,e=>typeof e.statusCode==`number`||typeof e.status==`number`);if(t)return typeof t.statusCode==`number`?t.statusCode:t.status}function E(e,t){if(e==null)throw TypeError(`${t} must not be null or undefined`)}function D(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`${t} must be an object, got ${typeof e}`)}function O(e,t){if(typeof e!=`string`)throw TypeError(`${t} must be a string, got ${typeof e}`)}function k(e,t){if(typeof e!=`function`)throw TypeError(`${t} must be a function, got ${typeof e}`)}function A(e,t){if(typeof e!=`bigint`)throw TypeError(`${t} must be a bigint, got ${typeof e}`)}function j(e,t,n){O(e[t],n)}function M(e,t,n){k(e[t],n)}function N(e,t){if(!e)throw TypeError(t)}export{e as _,D as a,T as c,t as d,v as f,c as g,y as h,E as i,w as l,p as m,N as n,j as o,_ as p,M as r,l as s,A as t,m as u};
|
|
2
|
-
//# sourceMappingURL=assertions-zYseN5Xz.js.map
|