@dignetwork/dig-sdk 0.2.1 → 0.3.3

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/loader.ts","../src/urn.ts","../src/dig-client.ts"],"names":["require"],"mappings":";AA6GA,IAAM,mBAAA,GAAsB,8BAAA;AAErB,IAAM,WAAA,GAAN,MAAM,YAAA,SAAoB,KAAA,CAAM;AAAA,EAMrC,WAAA,CACE,MACA,OAAA,EACA,OAAA,GAA8B,EAAC,EAC/B,OAAA,GAA+B,EAAC,EAChC;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAGf,IAAA,IAAI,OAAA,CAAQ,UAAU,MAAA,EAAW;AAC/B,MAAC,IAAA,CAA6B,QAAQ,OAAA,CAAQ,KAAA;AAAA,IAChD;AAEA,IAAA,MAAA,CAAO,cAAA,CAAe,MAAM,mBAAA,EAAqB,EAAE,OAAO,IAAA,EAAM,UAAA,EAAY,OAAO,CAAA;AAEnF,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,YAAA,CAAY,SAAS,CAAA;AAAA,EACnD;AAAA;AAAA,EAGA,MAAA,GAAkF;AAChF,IAAA,OAAO,EAAE,MAAM,IAAA,CAAK,IAAA,EAAM,SAAS,IAAA,CAAK,OAAA,EAAS,OAAA,EAAS,IAAA,CAAK,OAAA,EAAQ;AAAA,EACzE;AACF,CAAA;;;ACjHO,IAAM,sBAAA,GACX;AAuBF,IAAI,UAAsB,EAAC;AAC3B,IAAI,MAAA,GAAwC,IAAA;AAOrC,SAAS,cAAc,MAAA,EAA0B;AACtD,EAAA,OAAA,GAAU,EAAE,GAAG,MAAA,EAAO;AACtB,EAAA,MAAA,GAAS,IAAA;AAC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AE,MAAA,EAAQ,CAAC,CAAC,CAAA;AAClE,EAAA,IAAI,CAAA,GAAI,CAAA;AACR,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,GAAA,CAAI,GAAA,CAAI,MAAM,CAAC,CAAA;AACf,IAAA,CAAA,IAAK,IAAA,CAAK,MAAA;AAAA,EACZ;AACA,EAAA,OAAO,GAAA;AACT;AAEA,SAAS,cAAA,GAA+B;AACtC,EAAA,QAAQ,MAAM;AACZ,IAAA,MAAM,IAAI,WAAA;AAAA,MACR,kBAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF,CAAA;AACF","file":"dig-client.js","sourcesContent":["// The SDK's typed error taxonomy — the machine-readable failure contract.\n//\n// Every failure the SDK surfaces is a `DigSdkError` (an `Error` subclass) carrying a STABLE,\n// documented `.code` (UPPER_SNAKE) plus structured context fields. An agent (or a UI) can branch on\n// `err.code` instead of string-matching the human `.message`, and the catalogue is discoverable from\n// the `.d.ts` via the exported `DIG_SDK_ERROR_CODES` const and the `DigSdkErrorCode` union.\n//\n// The codes are symbolic and never derived from the human message — the message is for humans, the\n// code is for machines. Keep this catalogue and the README \"Error codes\" table in lockstep.\n\n/**\n * The stable error-code catalogue. Each value is an UPPER_SNAKE symbolic string that callers may\n * branch on. Frozen so it can't be mutated at runtime; the README documents each meaning.\n */\nexport const DIG_SDK_ERROR_CODES = Object.freeze({\n // ---- provider / connect (provider/chia-provider.ts, provider/*) ----\n /** WalletConnect was requested/needed but no `walletConnect` options were supplied. */\n WC_OPTIONS_REQUIRED: \"WC_OPTIONS_REQUIRED\",\n /** `mode: \"injected\"` (or the injected leg of `auto`) found no usable `window.chia`. */\n NO_INJECTED_WALLET: \"NO_INJECTED_WALLET\",\n /** The optional `@walletconnect/sign-client` peer dependency is not installed/usable. */\n WC_DEPENDENCY_MISSING: \"WC_DEPENDENCY_MISSING\",\n /** The active wallet session/transport does not grant the requested method. */\n METHOD_NOT_SUPPORTED: \"METHOD_NOT_SUPPORTED\",\n /** A wallet RPC timed out (e.g. Sage did not respond within the per-request timeout). */\n WALLET_TIMEOUT: \"WALLET_TIMEOUT\",\n /** The wallet returned no public keys / no key to sign with. */\n WALLET_NO_KEYS: \"WALLET_NO_KEYS\",\n\n // ---- read-crypto / RPC (dig-client.ts, loader.ts) ----\n /** A content read needs a confirmed on-chain root and none was supplied/derivable. */\n ROOT_REQUIRED: \"ROOT_REQUIRED\",\n /** The resource did not decrypt+authenticate under this URN (wrong key/salt, or a decoy). */\n DECRYPT_FAILED: \"DECRYPT_FAILED\",\n /** The dig RPC could not be reached (network/transport failure). */\n RPC_TRANSPORT: \"RPC_TRANSPORT\",\n /** The dig RPC responded with an HTTP error or a JSON-RPC `error` object. */\n RPC_ERROR: \"RPC_ERROR\",\n /** The dig RPC returned a malformed / inconsistent payload (e.g. chunk-length mismatch). */\n RPC_MALFORMED_RESPONSE: \"RPC_MALFORMED_RESPONSE\",\n /** The read-crypto wasm failed its SRI integrity check — fail closed. */\n WASM_INTEGRITY: \"WASM_INTEGRITY\",\n /** The read-crypto wasm could not be loaded (fetch/resolve failure). */\n WASM_LOAD_FAILED: \"WASM_LOAD_FAILED\",\n\n // ---- paywall / spends (paywall.ts) ----\n /** The canonical chip35 wasm builder for this operation is unavailable (never hand-rolled). */\n SPEND_BUILDER_UNAVAILABLE: \"SPEND_BUILDER_UNAVAILABLE\",\n /** No secure random source was available to generate a payment nonce. */\n NO_SECURE_RANDOM: \"NO_SECURE_RANDOM\",\n\n // ---- deploy / adapters (adapters/run.ts, adapters/deploy.ts) ----\n /** The `digstore` binary could not be spawned (not installed / not on PATH). */\n DIGSTORE_NOT_FOUND: \"DIGSTORE_NOT_FOUND\",\n /** `digstore deploy` exited non-zero. */\n DEPLOY_FAILED: \"DEPLOY_FAILED\",\n /** `digstore deploy --json` output could not be parsed into a capsule result. */\n DEPLOY_OUTPUT_UNPARSEABLE: \"DEPLOY_OUTPUT_UNPARSEABLE\",\n\n // ---- argument validation (shared) ----\n /** An argument was malformed (e.g. a non-hex string, a bad URN, mutually-exclusive options). */\n INVALID_ARGUMENT: \"INVALID_ARGUMENT\",\n} as const);\n\n/** The union of every stable SDK error code. Branch on `err.code` against these. */\nexport type DigSdkErrorCode = (typeof DIG_SDK_ERROR_CODES)[keyof typeof DIG_SDK_ERROR_CODES];\n\n/** Structured, code-specific context attached to a {@link DigSdkError}. All fields optional. */\nexport interface DigSdkErrorContext {\n /** The dig RPC method involved (RPC_* errors). */\n rpcMethod?: string;\n /** The HTTP status returned (RPC_ERROR on a non-2xx). */\n httpStatus?: number;\n /** The JSON-RPC error code returned by the server (RPC_ERROR). */\n rpcCode?: number;\n /** The `digstore` process exit code (DEPLOY_FAILED). */\n exitCode?: number | null;\n /** The wallet method that was unsupported (METHOD_NOT_SUPPORTED). */\n method?: string;\n /** The connection mode in play (provider errors). */\n mode?: string;\n /** The offending value (INVALID_ARGUMENT — e.g. the bad hex / URN). */\n value?: string;\n /** The expected vs actual SRI digest (WASM_INTEGRITY). */\n expected?: string;\n actual?: string;\n /** Any further structured detail; kept open so codes can carry extra fields. */\n [key: string]: unknown;\n}\n\n/**\n * The SDK's typed error. Always thrown (never a bare `Error`) so consumers can branch on `.code`.\n *\n * @example\n * try {\n * await dig.read({ urn });\n * } catch (e) {\n * if (e instanceof DigSdkError && e.code === \"ROOT_REQUIRED\") promptForRoot();\n * else throw e;\n * }\n */\n/**\n * A brand stamped on every {@link DigSdkError}. The SDK ships several independently-bundled entry\n * points (index, adapters, vite, next, dig-client), each of which inlines its own copy of this\n * module — so two `DigSdkError`s can have DIFFERENT class identities across bundles and a plain\n * `instanceof` would miss one. {@link isDigSdkError} brand-checks instead, so a coded error thrown\n * from `@dignetwork/dig-sdk/adapters` is still recognized by `isDigSdkError` imported from the main\n * entry. Non-enumerable so it never shows up in `toJSON()` / spreads.\n */\nconst DIG_SDK_ERROR_BRAND = \"__dignetwork_dig_sdk_error__\";\n\nexport class DigSdkError extends Error {\n /** The stable machine code (UPPER_SNAKE). Branch on this, not the message. */\n readonly code: DigSdkErrorCode;\n /** Structured, code-specific context (rpcMethod, httpStatus, exitCode, …). */\n readonly context: DigSdkErrorContext;\n\n constructor(\n code: DigSdkErrorCode,\n message: string,\n context: DigSdkErrorContext = {},\n options: { cause?: unknown } = {},\n ) {\n super(message);\n this.name = \"DigSdkError\";\n this.code = code;\n this.context = context;\n // Set `cause` directly (rather than via the ES2022 Error options arg) so the lib target stays\n // ES2020 while still preserving the underlying error for diagnostics.\n if (options.cause !== undefined) {\n (this as { cause?: unknown }).cause = options.cause;\n }\n // Brand the instance (non-enumerable) so isDigSdkError recognizes it across bundle boundaries.\n Object.defineProperty(this, DIG_SDK_ERROR_BRAND, { value: true, enumerable: false });\n // Preserve a correct prototype chain when compiled to ES5-ish targets / across realms.\n Object.setPrototypeOf(this, DigSdkError.prototype);\n }\n\n /** A JSON-friendly view of the error: `{ code, message, context }`. */\n toJSON(): { code: DigSdkErrorCode; message: string; context: DigSdkErrorContext } {\n return { code: this.code, message: this.message, context: this.context };\n }\n}\n\n/**\n * True iff `e` is a {@link DigSdkError} (optionally with a specific `code`). Uses a non-enumerable\n * BRAND rather than `instanceof` so it recognizes coded errors thrown from any of the SDK's\n * separately-bundled entry points (the main entry and `/adapters` inline distinct class identities).\n */\nexport function isDigSdkError(e: unknown, code?: DigSdkErrorCode): e is DigSdkError {\n const branded =\n e instanceof DigSdkError ||\n (typeof e === \"object\" && e !== null && (e as Record<string, unknown>)[DIG_SDK_ERROR_BRAND] === true);\n return branded && (code === undefined || (e as DigSdkError).code === code);\n}\n","// Cross-target loader for the `dig_client` read-crypto WASM.\n//\n// The wasm is consumed from the published `@dignetwork/dig-client` package (the installable form of\n// digstore's dig-client-wasm crate) — the SAME artifact the DIG Browser, extension, node, and hub\n// run. We NEVER run it unverified: we obtain the package's raw wasm bytes, SHA-256 them, compare\n// against the pinned digest, and only then let the module's crypto run. A mismatch (tampered / wrong\n// artifact) throws — the reader FAILS CLOSED rather than running unverified crypto.\n//\n// Two targets are consumed from the one package, auto-detected, with an escape hatch\n// (`configureWasm`):\n// • Node / Bun — `@dignetwork/dig-client/node`, the wasm-bindgen `nodejs` build. It reads\n// + instantiates the wasm synchronously on import; we independently\n// SHA-256-verify the shipped `dig_client_bg.wasm` and fail closed on a\n// mismatch.\n// • Browser (bundler) — `@dignetwork/dig-client/web`, the `--target web` build. We fetch the\n// package's `dig_client_bg.wasm`, SRI-verify the bytes, and hand them to\n// the module's async init.\n// • Browser (no bundler) — `configureWasm` with a URL/bytes you serve yourself.\n//\n// Memoized: the wasm initializes at most once per process/page.\n\nimport type { DigClientWasm } from \"./wasm.js\";\nimport { DigSdkError } from \"./errors.js\";\n\n/**\n * SHA-256 (lowercase hex) of `@dignetwork/dig-client`'s `dig_client_bg.wasm` — the SRI digest. It\n * is the canonical trust anchor (pinned regardless of the npm semver), mirrored by the package's\n * `integrity.json` `sha256`. Fail closed on a mismatch.\n */\nexport const DIG_CLIENT_WASM_SHA256 =\n \"8c983561eabca34778abf698ca7c2fba36117f87282ca649079599ef7d1b1156\";\n\n/** Optional explicit wasm inputs, for environments where package resolution can't reach the wasm. */\nexport interface WasmConfig {\n /**\n * The wasm bytes (already loaded). When provided, SRI is still enforced unless `skipIntegrity`.\n * Pass this in CSP-strict browsers where you fetch + verify the bytes yourself.\n */\n wasmBytes?: BufferSource;\n /**\n * URL to the wasm-bindgen `web` glue module for browser dynamic import. When omitted in a browser,\n * the loader imports `@dignetwork/dig-client/web` (the bundler resolves it).\n */\n glueUrl?: string;\n /**\n * URL to fetch the wasm bytes from (browser) when `wasmBytes` is not supplied. The fetched bytes\n * are SRI-verified before init. Defaults to the package's `dig_client_bg.wasm`.\n */\n wasmUrl?: string;\n /** Skip the SRI check. Only for tests / trusted custom builds — NOT recommended. */\n skipIntegrity?: boolean;\n}\n\nlet _config: WasmConfig = {};\nlet _ready: Promise<DigClientWasm> | null = null;\n\n/**\n * Override how the read-crypto wasm is located/loaded. Call BEFORE the first `DigClient` read.\n * Mainly for browsers without a bundler that resolves package files, or CSP-strict apps that fetch\n * + verify the wasm bytes themselves and hand them in. Resets any cached instance.\n */\nexport function configureWasm(config: WasmConfig): void {\n _config = { ...config };\n _ready = null;\n}\n\nconst isNode =\n typeof process !== \"undefined\" &&\n !!(process as { versions?: { node?: string } }).versions?.node;\n\n/** SHA-256 a buffer to lowercase hex, using node:crypto or WebCrypto. */\nasync function sha256Hex(bytes: BufferSource): Promise<string> {\n if (isNode) {\n const { createHash } = await import(\"node:crypto\");\n const view =\n bytes instanceof ArrayBuffer\n ? new Uint8Array(bytes)\n : new Uint8Array(\n (bytes as ArrayBufferView).buffer,\n (bytes as ArrayBufferView).byteOffset,\n (bytes as ArrayBufferView).byteLength,\n );\n return createHash(\"sha256\").update(view).digest(\"hex\");\n }\n const digest = await crypto.subtle.digest(\"SHA-256\", bytes as BufferSource);\n return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction assertIntegrity(hex: string): void {\n if (_config.skipIntegrity) return;\n if (hex !== DIG_CLIENT_WASM_SHA256) {\n throw new DigSdkError(\n \"WASM_INTEGRITY\",\n \"dig-client wasm integrity check failed — refusing to run unverified crypto \" +\n `(expected ${DIG_CLIENT_WASM_SHA256}, got ${hex}).`,\n { expected: DIG_CLIENT_WASM_SHA256, actual: hex },\n );\n }\n}\n\n// The read-crypto function surface the SDK uses (a subset of the package's exports). Both the node\n// and web builds export these camelCase functions at the module top level.\ntype DigClientModule = DigClientWasm & {\n default?: (input: { module_or_path: BufferSource }) => Promise<unknown>;\n};\n\n// Node: consume the `--target nodejs` build. It reads `dig_client_bg.wasm` from the package and\n// instantiates SYNCHRONOUSLY on import, so its functions are ready immediately (no init call). We\n// independently SHA-256-verify the shipped wasm and fail closed on a mismatch — so a tampered\n// package binary refuses to run even though wasm-bindgen already loaded it.\nasync function loadNode(): Promise<DigClientWasm> {\n const { createRequire } = await import(\"node:module\");\n const { readFile } = await import(\"node:fs/promises\");\n const require = createRequire(import.meta.url);\n const wasmPath = require.resolve(\"@dignetwork/dig-client/dig_client_bg.wasm\");\n const buf = await readFile(wasmPath);\n const bytes = new Uint8Array(buf.byteLength);\n bytes.set(buf);\n assertIntegrity(await sha256Hex(bytes));\n const mod = (await import(\"@dignetwork/dig-client/node\")) as unknown as DigClientModule;\n return mod as unknown as DigClientWasm;\n}\n\n// Browser: consume the `--target web` build (`@dignetwork/dig-client/web`).\n//\n// Two modes:\n// • Caller-supplied bytes/URL (`configureWasm`) — the fail-closed path for CSP-strict apps or an\n// untrusted CDN. We fetch (if a URL) the bytes, SHA-256-VERIFY them against the pinned digest,\n// and hand the very bytes we checked to the glue's async init — so nothing runs unverified.\n// • Default — call the glue's `init()` with no args. The `--target web` build resolves its\n// sibling `dig_client_bg.wasm` relative to its OWN module URL (the bundler-correct way to\n// locate a package asset) and instantiates it. Those bytes are the pinned package artifact\n// (the SDK depends on an exact `@dignetwork/dig-client` version). Apps that need byte-level SRI\n// over an untrusted delivery path use `configureWasm({ wasmUrl })` above.\nasync function loadBrowser(): Promise<DigClientWasm> {\n const glueHref = _config.glueUrl ?? \"@dignetwork/dig-client/web\";\n const mod = (await import(/* @vite-ignore */ glueHref)) as unknown as DigClientModule;\n if (typeof mod.default !== \"function\") {\n throw new DigSdkError(\n \"WASM_LOAD_FAILED\",\n \"dig-client web build exposed no init function (unexpected module shape)\",\n {},\n );\n }\n if (_config.wasmBytes || _config.wasmUrl) {\n let bytes: BufferSource;\n if (_config.wasmBytes) {\n bytes = _config.wasmBytes;\n } else {\n const wasmUrl = _config.wasmUrl!;\n const res = await fetch(wasmUrl);\n if (!res.ok)\n throw new DigSdkError(\"WASM_LOAD_FAILED\", `dig-client wasm fetch failed (${res.status})`, {\n httpStatus: res.status,\n wasmUrl,\n });\n bytes = await res.arrayBuffer();\n }\n assertIntegrity(await sha256Hex(bytes));\n await mod.default({ module_or_path: bytes });\n } else {\n // The glue resolves + instantiates its own sibling wasm (the pinned package artifact).\n await (mod.default as unknown as () => Promise<unknown>)();\n }\n return mod as unknown as DigClientWasm;\n}\n\n/**\n * Load, SRI-verify, and instantiate the read-crypto wasm, returning its functions. Memoized — at\n * most one init per process/page. Fails closed on an integrity mismatch.\n */\nexport function loadDigClientWasm(): Promise<DigClientWasm> {\n if (_ready) return _ready;\n _ready = (isNode ? loadNode() : loadBrowser()).catch((e) => {\n _ready = null; // allow a retry on transient load failure\n throw e;\n });\n return _ready;\n}\n","// DIG URN parsing + canonicalization — PURE, dependency-free, and identical to the parser the\n// hub (apps/web/lib/dig-client.js), the extension, and the companion use. Kept pure (no wasm) so\n// it is trivially unit-testable under `node --test` and usable on any runtime.\n//\n// A DIG URN addresses one resource inside a store:\n//\n// urn:dig:chia:<store_id>[:<root>]/<resource_key>[?salt=<hex>]\n//\n// • <store_id> — 64 hex chars, the singleton launcher id (the store identity).\n// • :<root> — OPTIONAL 64 hex chars, pins a specific on-chain generation. Omit for the\n// canonical, root-INDEPENDENT form. The root is only the trust anchor for\n// inclusion verification; it is NOT a key input (retrieval/decryption keys are\n// root-independent).\n// • <resource_key> — the path within the store (e.g. \"index.html\", \"img/logo.png\"). An empty\n// key resolves to the §8.5 default view \"index.html\".\n// • ?salt=<hex> — OPTIONAL out-of-band secret salt for a PRIVATE store.\n\nimport { DigSdkError } from \"./errors.js\";\n\n/** The parts of a parsed DIG URN. `root`/`salt` are null when absent. */\nexport interface ParsedUrn {\n /** Store identity (64-hex launcher id), lowercased. */\n readonly storeId: string;\n /** Generation root (64-hex), lowercased — or null for the root-independent form. */\n readonly root: string | null;\n /** Resource path within the store (verbatim, not lowercased). */\n readonly resourceKey: string;\n /** Private-store secret salt (hex), lowercased — or null for a public store. */\n readonly salt: string | null;\n}\n\nconst URN_RE =\n /^urn:dig:chia:([0-9a-fA-F]{64})(?::([0-9a-fA-F]{64}))?\\/(.+?)(?:\\?salt=([0-9a-fA-F]+))?$/;\n\n/**\n * Parse a DIG URN into its parts. Throws on a malformed URN.\n *\n * @example\n * parseUrn(\"urn:dig:chia:\" + \"ab\".repeat(32) + \"/index.html\")\n * // → { storeId: \"abab…\", root: null, resourceKey: \"index.html\", salt: null }\n */\nexport function parseUrn(raw: string): ParsedUrn {\n const s = String(raw ?? \"\").trim();\n const m = URN_RE.exec(s);\n if (!m) {\n throw new DigSdkError(\n \"INVALID_ARGUMENT\",\n \"Not a valid dig URN (expected urn:dig:chia:<store-id>[:<root>]/<path>[?salt=<hex>]).\",\n { value: s, expected: \"urn:dig:chia:<store-id>[:<root>]/<path>[?salt=<hex>]\" },\n );\n }\n return {\n storeId: m[1]!.toLowerCase(),\n root: m[2] ? m[2].toLowerCase() : null,\n resourceKey: m[3]!,\n salt: m[4] ? m[4].toLowerCase() : null,\n };\n}\n\n/** True iff `raw` is a syntactically valid DIG URN. Never throws. */\nexport function isUrn(raw: string): boolean {\n try {\n parseUrn(raw);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Reconstruct the canonical, root-INDEPENDENT URN string for a store + resource key:\n * `urn:dig:chia:<store_id>/<resource_key>`. An empty resource key resolves to the default view\n * `index.html`. This is the form whose SHA-256 is the retrieval key and whose bytes seed the AES\n * key — matching the wasm's `reconstructUrn`.\n */\nexport function reconstructUrn(storeId: string, resourceKey: string): string {\n const key = resourceKey && resourceKey.length > 0 ? resourceKey : \"index.html\";\n return `urn:dig:chia:${storeId.toLowerCase()}/${key}`;\n}\n\n/**\n * Reconstruct a root-PINNED display URN: `urn:dig:chia:<store_id>:<root>/<resource_key>`. Useful\n * for sharing a URN bound to a specific generation; the retrieval/AES keys still use the rootless\n * form (`reconstructUrn`).\n */\nexport function reconstructUrnWithRoot(\n storeId: string,\n root: string,\n resourceKey: string,\n): string {\n const key = resourceKey && resourceKey.length > 0 ? resourceKey : \"index.html\";\n return `urn:dig:chia:${storeId.toLowerCase()}:${root.toLowerCase()}/${key}`;\n}\n","// DigClient — the read side of the SDK. It fetches a resource's served ciphertext from the dig RPC,\n// derives the URN's keys CLIENT-SIDE via the read-crypto wasm, verifies inclusion against an\n// on-chain root, and decrypts — so the serving host stays BLIND (it only ever relays opaque\n// ciphertext + proofs). Genericized from hub.dig.net/apps/web/lib/dig-client.js, with the hub-app\n// coupling removed (no Vite import.meta.env, no window.location origin; the RPC endpoint and the\n// trust root are explicit inputs).\n//\n// HARD BOUNDARY (read sources). Everything read from a .dig — ciphertext, inclusion proofs, the\n// public manifest, metadata — comes ONLY from the dig RPC. The trust ROOT it is verified against\n// comes from the chain (the caller resolves it from coinset.org and passes it in). The host can\n// never become the trust anchor: every content read REQUIRES a caller-supplied root.\n//\n// OBLIVIOUS model. The host returns indistinguishable ciphertext for any retrieval key, so\n// presence is UNKNOWABLE. A read therefore NEVER concludes \"not found\": it returns plaintext when\n// the URN key decrypts the bytes, otherwise the raw ciphertext (a decoy is just opaque bytes). The\n// only thrown error is a transport failure.\n\nimport { loadDigClientWasm } from \"./loader.js\";\nimport type { DigClientWasm } from \"./wasm.js\";\nimport { parseUrn } from \"./urn.js\";\nimport type {\n CollectionItemsPage,\n CollectionMeta,\n ReadOptions,\n ReadResult,\n UrnKeys,\n} from \"./types.js\";\nimport { DigSdkError } from \"./errors.js\";\n\n/** The default public dig RPC endpoint. */\nexport const DEFAULT_RPC = \"https://rpc.dig.net\";\n\n// The backend caps each dig.getContent chunk at 3 MiB (Lambda/APIGW response ceiling); the client\n// loops chunks until `complete`.\nconst RPC_CHUNK_BYTES = 3 * 1024 * 1024;\n\n/** Options to construct a DigClient. */\nexport interface DigClientOptions {\n /** dig RPC endpoint. Defaults to the public `https://rpc.dig.net`. */\n rpc?: string;\n /** Override `fetch` (e.g. an instrumented one). Defaults to the global `fetch`. */\n fetch?: typeof fetch;\n}\n\ninterface GetContentResult {\n total_length: number;\n offset: number;\n next_offset?: number | null;\n complete?: boolean;\n ciphertext?: string;\n inclusion_proof?: string;\n chunk_lens?: number[];\n}\n\n/** Decode a standard-base64 string (the RPC ciphertext encoding) to bytes — no DOM dependency. */\nfunction b64ToBytes(b64: string): Uint8Array {\n // atob exists in browsers and modern Node; fall back to Buffer in older Node.\n if (typeof atob === \"function\") {\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new Uint8Array((globalThis as any).Buffer.from(b64, \"base64\"));\n}\n\n/**\n * The read-crypto client. Construct once and reuse — the wasm is loaded + SRI-verified lazily on\n * the first read and memoized process/page-wide.\n *\n * @example\n * const dig = new DigClient();\n * const { bytes, decrypted } = await dig.read({\n * urn: \"urn:dig:chia:<storeId>/index.html\",\n * root: \"<onchain-root-hex>\",\n * });\n * if (decrypted) console.log(new TextDecoder().decode(bytes));\n */\nexport class DigClient {\n private readonly rpc: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(options: DigClientOptions = {}) {\n this.rpc = options.rpc ?? DEFAULT_RPC;\n this.fetchImpl =\n options.fetch ??\n (typeof fetch === \"function\" ? fetch.bind(globalThis) : undefinedFetch());\n }\n\n /** Load (and SRI-verify) the read-crypto wasm. Exposed for callers that want the raw functions. */\n async wasm(): Promise<DigClientWasm> {\n return loadDigClientWasm();\n }\n\n /** `retrieval_key = SHA-256(canonical rootless URN)`, lowercase hex. */\n async retrievalKey(storeId: string, resourceKey: string): Promise<string> {\n return (await this.wasm()).retrievalKey(storeId, resourceKey);\n }\n\n /** Derive the per-URN AES-256-GCM-SIV key, lowercase hex. `salt` for a private store. */\n async deriveKey(\n storeId: string,\n resourceKey: string,\n salt?: string | null,\n ): Promise<string> {\n return (await this.wasm()).deriveKey(storeId, resourceKey, salt ?? undefined);\n }\n\n /** Verify served `ciphertext` is included under `root` via the base64 merkle `proof`. */\n async verifyInclusion(\n ciphertext: Uint8Array,\n proof: string,\n root: string,\n ): Promise<boolean> {\n return (await this.wasm()).verifyInclusion(ciphertext, proof, root);\n }\n\n /** Reconstruct the canonical rootless URN whose SHA-256 is the retrieval key. */\n async reconstructUrn(storeId: string, resourceKey: string): Promise<string> {\n return (await this.wasm()).reconstructUrn(storeId, resourceKey);\n }\n\n /**\n * Derive, client-side, the two root-independent keys a URN maps to (retrieval + decryption).\n * Nothing is sent to the network — pure local derivation via the wasm.\n */\n async deriveUrnKeys(input: { urn: string; salt?: string | null }): Promise<UrnKeys> {\n const parsed = parseUrn(input.urn);\n const wasm = await this.wasm();\n const effSalt = input.salt ?? parsed.salt ?? undefined;\n return {\n storeId: parsed.storeId,\n root: parsed.root,\n resourceKey: parsed.resourceKey,\n salt: effSalt ?? null,\n retrievalKey: wasm.retrievalKey(parsed.storeId, parsed.resourceKey),\n decryptionKey: wasm.deriveKey(parsed.storeId, parsed.resourceKey, effSalt),\n };\n }\n\n /**\n * Fetch + verify + decrypt one resource by URN. `root` is the on-chain generation root to verify\n * against (resolved by the caller from the chain); when omitted, the root embedded in the URN is\n * used. Returns the bytes plus advisory `verified`/`decrypted` flags. NEVER throws \"not found\"\n * (presence is unknowable) — it throws only on a transport failure.\n */\n async read(\n input: { urn: string; root?: string | null; salt?: string | null },\n opts: ReadOptions = {},\n ): Promise<ReadResult> {\n const parsed = parseUrn(input.urn);\n const effSalt = input.salt ?? parsed.salt ?? null;\n const effRoot = input.root ?? parsed.root ?? null;\n if (!effRoot) {\n throw new DigSdkError(\n \"ROOT_REQUIRED\",\n \"a confirmed on-chain root is required to read content (pass { root } or use a root-pinned URN)\",\n { urn: input.urn },\n );\n }\n return this.readResource(\n { storeId: parsed.storeId, resourceKey: parsed.resourceKey, root: effRoot, salt: effSalt },\n opts,\n );\n }\n\n /** As `read`, but decoding the plaintext to a UTF-8 string when it decrypts (else throws). */\n async readText(\n input: { urn: string; root?: string | null; salt?: string | null },\n opts: ReadOptions = {},\n ): Promise<string> {\n const r = await this.read(input, opts);\n if (!r.decrypted) {\n throw new DigSdkError(\n \"DECRYPT_FAILED\",\n \"resource did not decrypt under this URN — wrong store/key/salt, or a decoy response\",\n { urn: input.urn },\n );\n }\n return new TextDecoder().decode(r.bytes);\n }\n\n /**\n * Read by explicit (storeId, resourceKey, root, salt) rather than a URN string. The oblivious\n * download primitive the URN read is built on.\n */\n async readResource(\n input: { storeId: string; resourceKey: string; root: string; salt?: string | null },\n opts: ReadOptions = {},\n ): Promise<ReadResult> {\n const rpc = opts.rpc ?? this.rpc;\n const wasm = await this.wasm();\n const rk = wasm.retrievalKey(input.storeId, input.resourceKey);\n const { ciphertext, proof, chunkLens } = await this.fetchCiphertext(\n input.storeId,\n rk,\n input.root,\n rpc,\n );\n let verified = false;\n try {\n verified = !!wasm.verifyInclusion(ciphertext, proof, input.root);\n } catch {\n verified = false;\n }\n const keyHex = wasm.deriveKey(input.storeId, input.resourceKey, input.salt ?? undefined);\n try {\n const bytes = decryptResourceChunks(wasm, keyHex, ciphertext, chunkLens);\n return {\n storeId: input.storeId,\n root: input.root,\n resourceKey: input.resourceKey,\n salt: input.salt ?? null,\n bytes,\n verified,\n decrypted: true,\n };\n } catch {\n // Not decryptable with this URN/salt — hand back the raw bytes; never a \"not present\" verdict.\n return {\n storeId: input.storeId,\n root: input.root,\n resourceKey: input.resourceKey,\n salt: input.salt ?? null,\n bytes: ciphertext,\n verified,\n decrypted: false,\n };\n }\n }\n\n /**\n * Read a collection's public, owner-independent facts (creator DID, item count, uniform royalty)\n * from the dig RPC (`dig.getCollection`). The collection's item set is its NFT launcher ids — the\n * authoritative, owner-independent anchor the mint produced (a DID-attributed NFT is hinted to its\n * OWNER at mint, not to the creator DID, so launcher ids — not the DID — are the read key). Pass\n * the optional `did` to have it echoed back and recorded as the declared creator.\n *\n * No wallet, no read-crypto wasm — a plain JSON-RPC read. Throws a coded {@link DigSdkError} on a\n * transport/RPC failure (never a \"not found\": an empty/partly-confirmed set just resolves to fewer\n * items).\n *\n * @example\n * const meta = await dig.getCollection({ launcherIds: [\"ab…\", \"cd…\"], did: \"ef…\" });\n * console.log(meta.resolved_count, meta.royalty_basis_points);\n */\n async getCollection(\n input: { launcherIds: string[]; did?: string | null },\n opts: ReadOptions = {},\n ): Promise<CollectionMeta> {\n const rpc = opts.rpc ?? this.rpc;\n const params: Record<string, unknown> = { launcher_ids: input.launcherIds };\n if (input.did) params.did = input.did;\n const r = await this.rpcCall<CollectionMeta>(rpc, \"dig.getCollection\", params);\n if (!r)\n throw new DigSdkError(\n \"RPC_MALFORMED_RESPONSE\",\n \"The content network returned no collection facts for this request.\",\n { rpcMethod: \"dig.getCollection\" },\n );\n return r;\n }\n\n /**\n * Read a deterministic, paginated page of a collection's items (`dig.listCollectionItems`), each\n * resolved to its CURRENT on-chain state — current owner, royalty, and CHIP-0007 metadata — by the\n * RPC walking the singleton lineage forward to the live tip (so the owner is never the stale\n * mint-time owner). Items come back in the input launcher-id order. `limit` is clamped to the\n * server cap (200); `offset` defaults to 0.\n *\n * Throws a coded {@link DigSdkError} on a transport/RPC failure.\n *\n * @example\n * let page = await dig.listCollectionItems({ launcherIds, limit: 50 });\n * for (const item of page.items) console.log(item.launcher_id, item.owner_puzzle_hash);\n * // page.next_offset is null on the last page.\n */\n async listCollectionItems(\n input: { launcherIds: string[]; offset?: number; limit?: number },\n opts: ReadOptions = {},\n ): Promise<CollectionItemsPage> {\n const rpc = opts.rpc ?? this.rpc;\n const params: Record<string, unknown> = { launcher_ids: input.launcherIds };\n if (input.offset !== undefined) params.offset = input.offset;\n if (input.limit !== undefined) params.limit = input.limit;\n const r = await this.rpcCall<CollectionItemsPage>(rpc, \"dig.listCollectionItems\", params);\n if (!r)\n throw new DigSdkError(\n \"RPC_MALFORMED_RESPONSE\",\n \"The content network returned no collection items for this request.\",\n { rpcMethod: \"dig.listCollectionItems\" },\n );\n return r;\n }\n\n // Stream the FULL ciphertext for a resource from the RPC by retrieval key, reassembling 3-MiB\n // chunks. A null result is a TRANSPORT failure, never a presence judgment.\n private async fetchCiphertext(\n storeId: string,\n rk: string,\n root: string,\n rpc: string,\n ): Promise<{ ciphertext: Uint8Array; proof: string; chunkLens: number[] | null }> {\n let offset = 0;\n let total: number | null = null;\n let buf: Uint8Array | null = null;\n let proof = \"\";\n let chunkLens: number[] | null = null;\n for (;;) {\n const r = await this.rpcCall<GetContentResult>(rpc, \"dig.getContent\", {\n store_id: storeId,\n root,\n retrieval_key: rk,\n offset,\n length: RPC_CHUNK_BYTES,\n });\n if (!r)\n throw new DigSdkError(\n \"RPC_MALFORMED_RESPONSE\",\n \"The content network returned no data for this request.\",\n { rpcMethod: \"dig.getContent\" },\n );\n if (total === null) {\n total = r.total_length >>> 0;\n buf = new Uint8Array(total);\n }\n if (chunkLens === null && Array.isArray(r.chunk_lens)) {\n chunkLens = r.chunk_lens.map((n) => n >>> 0);\n }\n const chunk = b64ToBytes(r.ciphertext ?? \"\");\n const at = r.offset >>> 0;\n buf!.set(chunk.subarray(0, Math.max(0, Math.min(chunk.length, total - at))), at);\n if (r.inclusion_proof) proof = r.inclusion_proof;\n if (r.complete || r.next_offset == null) break;\n offset = r.next_offset >>> 0;\n }\n return { ciphertext: buf ?? new Uint8Array(0), proof, chunkLens };\n }\n\n // One JSON-RPC 2.0 call. Throws a coded DigSdkError on transport failure (RPC_TRANSPORT) or a\n // JSON-RPC/HTTP error (RPC_ERROR, carrying rpcMethod/httpStatus/rpcCode context); returns `result`.\n private async rpcCall<T>(rpc: string, method: string, params: unknown): Promise<T | null> {\n let res: Response;\n try {\n res = await this.fetchImpl(rpc, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ jsonrpc: \"2.0\", id: 1, method, params }),\n });\n } catch (e) {\n throw new DigSdkError(\n \"RPC_TRANSPORT\",\n \"Could not reach the content network. Check your connection and try again.\",\n { rpcMethod: method },\n { cause: e },\n );\n }\n if (!res.ok)\n throw new DigSdkError(\"RPC_ERROR\", `dig RPC ${method} failed (${res.status})`, {\n rpcMethod: method,\n httpStatus: res.status,\n });\n const json = (await res.json()) as {\n result?: T;\n error?: { message?: string; code?: number };\n };\n if (json && json.error)\n throw new DigSdkError(\n \"RPC_ERROR\",\n `dig RPC ${method}: ${json.error.message ?? \"error\"}`,\n { rpcMethod: method, rpcCode: json.error.code },\n );\n return json ? (json.result ?? null) : null;\n }\n}\n\n// AES-256-GCM-SIV-open a resource's served ciphertext under `keyHex`, splitting the PLAIN-\n// concatenated chunk ciphertexts by `chunkLens` (per-chunk CIPHERTEXT byte lengths) and opening\n// each. Empty/absent chunkLens ⇒ single-chunk resource. Throws if any chunk's tag fails.\nfunction decryptResourceChunks(\n wasm: DigClientWasm,\n keyHex: string,\n ciphertext: Uint8Array,\n chunkLens: number[] | null,\n): Uint8Array {\n const lens = chunkLens && chunkLens.length ? chunkLens : [ciphertext.length];\n const total = lens.reduce((a, n) => a + n, 0);\n if (total !== ciphertext.length) {\n throw new DigSdkError(\n \"RPC_MALFORMED_RESPONSE\",\n \"served ciphertext length does not match chunk lengths\",\n { rpcMethod: \"dig.getContent\", expected: String(total), actual: String(ciphertext.length) },\n );\n }\n if (lens.length === 1) return wasm.decryptChunk(keyHex, ciphertext);\n const parts: Uint8Array[] = [];\n let p = 0;\n for (const len of lens) {\n parts.push(wasm.decryptChunk(keyHex, ciphertext.subarray(p, p + len)));\n p += len;\n }\n const out = new Uint8Array(parts.reduce((a, x) => a + x.length, 0));\n let q = 0;\n for (const part of parts) {\n out.set(part, q);\n q += part.length;\n }\n return out;\n}\n\nfunction undefinedFetch(): typeof fetch {\n return (() => {\n throw new DigSdkError(\n \"INVALID_ARGUMENT\",\n \"No global fetch available. Pass { fetch } to DigClient (Node < 18 needs a fetch polyfill).\",\n );\n }) as unknown as typeof fetch;\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/loader.ts","../src/urn.ts","../src/dig-client.ts"],"names":["require"],"mappings":";AA6GA,IAAM,mBAAA,GAAsB,8BAAA;AAErB,IAAM,WAAA,GAAN,MAAM,YAAA,SAAoB,KAAA,CAAM;AAAA,EAMrC,WAAA,CACE,MACA,OAAA,EACA,OAAA,GAA8B,EAAC,EAC/B,OAAA,GAA+B,EAAC,EAChC;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;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y — the machine-readable failure contract.\n//\n// Every failure the SDK surfaces is a `DigSdkError` (an `Error` subclass) carrying a STABLE,\n// documented `.code` (UPPER_SNAKE) plus structured context fields. An agent (or a UI) can branch on\n// `err.code` instead of string-matching the human `.message`, and the catalogue is discoverable from\n// the `.d.ts` via the exported `DIG_SDK_ERROR_CODES` const and the `DigSdkErrorCode` union.\n//\n// The codes are symbolic and never derived from the human message — the message is for humans, the\n// code is for machines. Keep this catalogue and the README \"Error codes\" table in lockstep.\n\n/**\n * The stable error-code catalogue. Each value is an UPPER_SNAKE symbolic string that callers may\n * branch on. Frozen so it can't be mutated at runtime; the README documents each meaning.\n */\nexport const DIG_SDK_ERROR_CODES = Object.freeze({\n // ---- provider / connect (provider/chia-provider.ts, provider/*) ----\n /** WalletConnect was requested/needed but no `walletConnect` options were supplied. */\n WC_OPTIONS_REQUIRED: \"WC_OPTIONS_REQUIRED\",\n /** `mode: \"injected\"` (or the injected leg of `auto`) found no usable `window.chia`. */\n NO_INJECTED_WALLET: \"NO_INJECTED_WALLET\",\n /** The optional `@walletconnect/sign-client` peer dependency is not installed/usable. */\n WC_DEPENDENCY_MISSING: \"WC_DEPENDENCY_MISSING\",\n /** The active wallet session/transport does not grant the requested method. */\n METHOD_NOT_SUPPORTED: \"METHOD_NOT_SUPPORTED\",\n /** A wallet RPC timed out (e.g. Sage did not respond within the per-request timeout). */\n WALLET_TIMEOUT: \"WALLET_TIMEOUT\",\n /** The wallet returned no public keys / no key to sign with. */\n WALLET_NO_KEYS: \"WALLET_NO_KEYS\",\n\n // ---- read-crypto / RPC (dig-client.ts, loader.ts) ----\n /** A content read needs a confirmed on-chain root and none was supplied/derivable. */\n ROOT_REQUIRED: \"ROOT_REQUIRED\",\n /** The resource did not decrypt+authenticate under this URN (wrong key/salt, or a decoy). */\n DECRYPT_FAILED: \"DECRYPT_FAILED\",\n /** The dig RPC could not be reached (network/transport failure). */\n RPC_TRANSPORT: \"RPC_TRANSPORT\",\n /** The dig RPC responded with an HTTP error or a JSON-RPC `error` object. */\n RPC_ERROR: \"RPC_ERROR\",\n /** The dig RPC returned a malformed / inconsistent payload (e.g. chunk-length mismatch). */\n RPC_MALFORMED_RESPONSE: \"RPC_MALFORMED_RESPONSE\",\n /** The read-crypto wasm failed its SRI integrity check — fail closed. */\n WASM_INTEGRITY: \"WASM_INTEGRITY\",\n /** The read-crypto wasm could not be loaded (fetch/resolve failure). */\n WASM_LOAD_FAILED: \"WASM_LOAD_FAILED\",\n\n // ---- paywall / spends (paywall.ts) ----\n /** The canonical chip35 wasm builder for this operation is unavailable (never hand-rolled). */\n SPEND_BUILDER_UNAVAILABLE: \"SPEND_BUILDER_UNAVAILABLE\",\n /** No secure random source was available to generate a payment nonce. */\n NO_SECURE_RANDOM: \"NO_SECURE_RANDOM\",\n\n // ---- deploy / adapters (adapters/run.ts, adapters/deploy.ts) ----\n /** The `digstore` binary could not be spawned (not installed / not on PATH). */\n DIGSTORE_NOT_FOUND: \"DIGSTORE_NOT_FOUND\",\n /** `digstore deploy` exited non-zero. */\n DEPLOY_FAILED: \"DEPLOY_FAILED\",\n /** `digstore deploy --json` output could not be parsed into a capsule result. */\n DEPLOY_OUTPUT_UNPARSEABLE: \"DEPLOY_OUTPUT_UNPARSEABLE\",\n\n // ---- argument validation (shared) ----\n /** An argument was malformed (e.g. a non-hex string, a bad URN, mutually-exclusive options). */\n INVALID_ARGUMENT: \"INVALID_ARGUMENT\",\n} as const);\n\n/** The union of every stable SDK error code. Branch on `err.code` against these. */\nexport type DigSdkErrorCode = (typeof DIG_SDK_ERROR_CODES)[keyof typeof DIG_SDK_ERROR_CODES];\n\n/** Structured, code-specific context attached to a {@link DigSdkError}. All fields optional. */\nexport interface DigSdkErrorContext {\n /** The dig RPC method involved (RPC_* errors). */\n rpcMethod?: string;\n /** The HTTP status returned (RPC_ERROR on a non-2xx). */\n httpStatus?: number;\n /** The JSON-RPC error code returned by the server (RPC_ERROR). */\n rpcCode?: number;\n /** The `digstore` process exit code (DEPLOY_FAILED). */\n exitCode?: number | null;\n /** The wallet method that was unsupported (METHOD_NOT_SUPPORTED). */\n method?: string;\n /** The connection mode in play (provider errors). */\n mode?: string;\n /** The offending value (INVALID_ARGUMENT — e.g. the bad hex / URN). */\n value?: string;\n /** The expected vs actual SRI digest (WASM_INTEGRITY). */\n expected?: string;\n actual?: string;\n /** Any further structured detail; kept open so codes can carry extra fields. */\n [key: string]: unknown;\n}\n\n/**\n * The SDK's typed error. Always thrown (never a bare `Error`) so consumers can branch on `.code`.\n *\n * @example\n * try {\n * await dig.read({ urn });\n * } catch (e) {\n * if (e instanceof DigSdkError && e.code === \"ROOT_REQUIRED\") promptForRoot();\n * else throw e;\n * }\n */\n/**\n * A brand stamped on every {@link DigSdkError}. The SDK ships several independently-bundled entry\n * points (index, adapters, vite, next, dig-client), each of which inlines its own copy of this\n * module — so two `DigSdkError`s can have DIFFERENT class identities across bundles and a plain\n * `instanceof` would miss one. {@link isDigSdkError} brand-checks instead, so a coded error thrown\n * from `@dignetwork/dig-sdk/adapters` is still recognized by `isDigSdkError` imported from the main\n * entry. Non-enumerable so it never shows up in `toJSON()` / spreads.\n */\nconst DIG_SDK_ERROR_BRAND = \"__dignetwork_dig_sdk_error__\";\n\nexport class DigSdkError extends Error {\n /** The stable machine code (UPPER_SNAKE). Branch on this, not the message. */\n readonly code: DigSdkErrorCode;\n /** Structured, code-specific context (rpcMethod, httpStatus, exitCode, …). */\n readonly context: DigSdkErrorContext;\n\n constructor(\n code: DigSdkErrorCode,\n message: string,\n context: DigSdkErrorContext = {},\n options: { cause?: unknown } = {},\n ) {\n super(message);\n this.name = \"DigSdkError\";\n this.code = code;\n this.context = context;\n // Set `cause` directly (rather than via the ES2022 Error options arg) so the lib target stays\n // ES2020 while still preserving the underlying error for diagnostics.\n if (options.cause !== undefined) {\n (this as { cause?: unknown }).cause = options.cause;\n }\n // Brand the instance (non-enumerable) so isDigSdkError recognizes it across bundle boundaries.\n Object.defineProperty(this, DIG_SDK_ERROR_BRAND, { value: true, enumerable: false });\n // Preserve a correct prototype chain when compiled to ES5-ish targets / across realms.\n Object.setPrototypeOf(this, DigSdkError.prototype);\n }\n\n /** A JSON-friendly view of the error: `{ code, message, context }`. */\n toJSON(): { code: DigSdkErrorCode; message: string; context: DigSdkErrorContext } {\n return { code: this.code, message: this.message, context: this.context };\n }\n}\n\n/**\n * True iff `e` is a {@link DigSdkError} (optionally with a specific `code`). Uses a non-enumerable\n * BRAND rather than `instanceof` so it recognizes coded errors thrown from any of the SDK's\n * separately-bundled entry points (the main entry and `/adapters` inline distinct class identities).\n */\nexport function isDigSdkError(e: unknown, code?: DigSdkErrorCode): e is DigSdkError {\n const branded =\n e instanceof DigSdkError ||\n (typeof e === \"object\" && e !== null && (e as Record<string, unknown>)[DIG_SDK_ERROR_BRAND] === true);\n return branded && (code === undefined || (e as DigSdkError).code === code);\n}\n","// Cross-target loader for the `dig_client` read-crypto WASM.\n//\n// The wasm is consumed from the published `@dignetwork/dig-capsule-wasm` package (the installable form of\n// digstore's dig-client-wasm crate) — the SAME artifact the DIG Browser, extension, node, and hub\n// run. We NEVER run it unverified: we obtain the package's raw wasm bytes, SHA-256 them, compare\n// against the pinned digest, and only then let the module's crypto run. A mismatch (tampered / wrong\n// artifact) throws — the reader FAILS CLOSED rather than running unverified crypto.\n//\n// Two targets are consumed from the one package, auto-detected, with an escape hatch\n// (`configureWasm`):\n// • Node / Bun — `@dignetwork/dig-capsule-wasm/node`, the wasm-bindgen `nodejs` build. It reads\n// + instantiates the wasm synchronously on import; we independently\n// SHA-256-verify the shipped `dig_client_bg.wasm` and fail closed on a\n// mismatch.\n// • Browser (bundler) — `@dignetwork/dig-capsule-wasm/web`, the `--target web` build. We fetch the\n// package's `dig_client_bg.wasm`, SRI-verify the bytes, and hand them to\n// the module's async init.\n// • Browser (no bundler) — `configureWasm` with a URL/bytes you serve yourself.\n//\n// Memoized: the wasm initializes at most once per process/page.\n\nimport type { DigClientWasm } from \"./wasm.js\";\nimport { DigSdkError } from \"./errors.js\";\n\n/**\n * SHA-256 (lowercase hex) of `@dignetwork/dig-capsule-wasm`'s `dig_client_bg.wasm` — the SRI digest. It\n * is the canonical trust anchor (pinned regardless of the npm semver), mirrored by the package's\n * `integrity.json` `sha256`. Fail closed on a mismatch.\n */\nexport const DIG_CLIENT_WASM_SHA256 =\n \"a186fd2d6b348a7caa3112c51b666a6618fe7cf8bb56ad395a1fab4323f6ae7e\";\n\n/** Optional explicit wasm inputs, for environments where package resolution can't reach the wasm. */\nexport interface WasmConfig {\n /**\n * The wasm bytes (already loaded). When provided, SRI is still enforced unless `skipIntegrity`.\n * Pass this in CSP-strict browsers where you fetch + verify the bytes yourself.\n */\n wasmBytes?: BufferSource;\n /**\n * URL to the wasm-bindgen `web` glue module for browser dynamic import. When omitted in a browser,\n * the loader imports `@dignetwork/dig-capsule-wasm/web` (the bundler resolves it).\n */\n glueUrl?: string;\n /**\n * URL to fetch the wasm bytes from (browser) when `wasmBytes` is not supplied. The fetched bytes\n * are SRI-verified before init. Defaults to the package's `dig_client_bg.wasm`.\n */\n wasmUrl?: string;\n /** Skip the SRI check. Only for tests / trusted custom builds — NOT recommended. */\n skipIntegrity?: boolean;\n}\n\nlet _config: WasmConfig = {};\nlet _ready: Promise<DigClientWasm> | null = null;\n\n/**\n * Override how the read-crypto wasm is located/loaded. Call BEFORE the first `DigClient` read.\n * Mainly for browsers without a bundler that resolves package files, or CSP-strict apps that fetch\n * + verify the wasm bytes themselves and hand them in. Resets any cached instance.\n */\nexport function configureWasm(config: WasmConfig): void {\n _config = { ...config };\n _ready = null;\n}\n\nconst isNode =\n typeof process !== \"undefined\" &&\n !!(process as { versions?: { node?: string } }).versions?.node;\n\n/** SHA-256 a buffer to lowercase hex, using node:crypto or WebCrypto. */\nasync function sha256Hex(bytes: BufferSource): Promise<string> {\n if (isNode) {\n const { createHash } = await import(\"node:crypto\");\n const view =\n bytes instanceof ArrayBuffer\n ? new Uint8Array(bytes)\n : new Uint8Array(\n (bytes as ArrayBufferView).buffer,\n (bytes as ArrayBufferView).byteOffset,\n (bytes as ArrayBufferView).byteLength,\n );\n return createHash(\"sha256\").update(view).digest(\"hex\");\n }\n const digest = await crypto.subtle.digest(\"SHA-256\", bytes as BufferSource);\n return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction assertIntegrity(hex: string): void {\n if (_config.skipIntegrity) return;\n if (hex !== DIG_CLIENT_WASM_SHA256) {\n throw new DigSdkError(\n \"WASM_INTEGRITY\",\n \"dig-client wasm integrity check failed — refusing to run unverified crypto \" +\n `(expected ${DIG_CLIENT_WASM_SHA256}, got ${hex}).`,\n { expected: DIG_CLIENT_WASM_SHA256, actual: hex },\n );\n }\n}\n\n// The read-crypto function surface the SDK uses (a subset of the package's exports). Both the node\n// and web builds export these camelCase functions at the module top level.\ntype DigClientModule = DigClientWasm & {\n default?: (input: { module_or_path: BufferSource }) => Promise<unknown>;\n};\n\n// Node: consume the `--target nodejs` build. It reads `dig_client_bg.wasm` from the package and\n// instantiates SYNCHRONOUSLY on import, so its functions are ready immediately (no init call). We\n// independently SHA-256-verify the shipped wasm and fail closed on a mismatch — so a tampered\n// package binary refuses to run even though wasm-bindgen already loaded it.\nasync function loadNode(): Promise<DigClientWasm> {\n const { createRequire } = await import(\"node:module\");\n const { readFile } = await import(\"node:fs/promises\");\n const require = createRequire(import.meta.url);\n const wasmPath = require.resolve(\"@dignetwork/dig-capsule-wasm/dig_client_bg.wasm\");\n const buf = await readFile(wasmPath);\n const bytes = new Uint8Array(buf.byteLength);\n bytes.set(buf);\n assertIntegrity(await sha256Hex(bytes));\n const mod = (await import(\"@dignetwork/dig-capsule-wasm/node\")) as unknown as DigClientModule;\n return mod as unknown as DigClientWasm;\n}\n\n// Browser: consume the `--target web` build (`@dignetwork/dig-capsule-wasm/web`).\n//\n// Two modes:\n// • Caller-supplied bytes/URL (`configureWasm`) — the fail-closed path for CSP-strict apps or an\n// untrusted CDN. We fetch (if a URL) the bytes, SHA-256-VERIFY them against the pinned digest,\n// and hand the very bytes we checked to the glue's async init — so nothing runs unverified.\n// • Default — call the glue's `init()` with no args. The `--target web` build resolves its\n// sibling `dig_client_bg.wasm` relative to its OWN module URL (the bundler-correct way to\n// locate a package asset) and instantiates it. Those bytes are the pinned package artifact\n// (the SDK depends on an exact `@dignetwork/dig-capsule-wasm` version). Apps that need byte-level SRI\n// over an untrusted delivery path use `configureWasm({ wasmUrl })` above.\nasync function loadBrowser(): Promise<DigClientWasm> {\n const glueHref = _config.glueUrl ?? \"@dignetwork/dig-capsule-wasm/web\";\n const mod = (await import(/* @vite-ignore */ glueHref)) as unknown as DigClientModule;\n if (typeof mod.default !== \"function\") {\n throw new DigSdkError(\n \"WASM_LOAD_FAILED\",\n \"dig-client web build exposed no init function (unexpected module shape)\",\n {},\n );\n }\n if (_config.wasmBytes || _config.wasmUrl) {\n let bytes: BufferSource;\n if (_config.wasmBytes) {\n bytes = _config.wasmBytes;\n } else {\n const wasmUrl = _config.wasmUrl!;\n const res = await fetch(wasmUrl);\n if (!res.ok)\n throw new DigSdkError(\"WASM_LOAD_FAILED\", `dig-client wasm fetch failed (${res.status})`, {\n httpStatus: res.status,\n wasmUrl,\n });\n bytes = await res.arrayBuffer();\n }\n assertIntegrity(await sha256Hex(bytes));\n await mod.default({ module_or_path: bytes });\n } else {\n // The glue resolves + instantiates its own sibling wasm (the pinned package artifact).\n await (mod.default as unknown as () => Promise<unknown>)();\n }\n return mod as unknown as DigClientWasm;\n}\n\n/**\n * Load, SRI-verify, and instantiate the read-crypto wasm, returning its functions. Memoized — at\n * most one init per process/page. Fails closed on an integrity mismatch.\n */\nexport function loadDigClientWasm(): Promise<DigClientWasm> {\n if (_ready) return _ready;\n _ready = (isNode ? loadNode() : loadBrowser()).catch((e) => {\n _ready = null; // allow a retry on transient load failure\n throw e;\n });\n return _ready;\n}\n\r\n","// DIG URN parsing + canonicalization — PURE, dependency-free, and identical to the parser the\n// hub (apps/web/lib/dig-client.js), the extension, and the companion use. Kept pure (no wasm) so\n// it is trivially unit-testable under `node --test` and usable on any runtime.\n//\n// A DIG URN addresses one resource inside a store:\n//\n// urn:dig:chia:<store_id>[:<root>]/<resource_key>[?salt=<hex>]\n//\n// • <store_id> — 64 hex chars, the singleton launcher id (the store identity).\n// • :<root> — OPTIONAL 64 hex chars, pins a specific on-chain generation. Omit for the\n// canonical, root-INDEPENDENT form. The root is only the trust anchor for\n// inclusion verification; it is NOT a key input (retrieval/decryption keys are\n// root-independent).\n// • <resource_key> — the path within the store (e.g. \"index.html\", \"img/logo.png\"). An empty\n// key resolves to the §8.5 default view \"index.html\".\n// • ?salt=<hex> — OPTIONAL out-of-band secret salt for a PRIVATE store.\n\nimport { DigSdkError } from \"./errors.js\";\n\n/** The parts of a parsed DIG URN. `root`/`salt` are null when absent. */\nexport interface ParsedUrn {\n /** Store identity (64-hex launcher id), lowercased. */\n readonly storeId: string;\n /** Generation root (64-hex), lowercased — or null for the root-independent form. */\n readonly root: string | null;\n /** Resource path within the store (verbatim, not lowercased). */\n readonly resourceKey: string;\n /** Private-store secret salt (hex), lowercased — or null for a public store. */\n readonly salt: string | null;\n}\n\nconst URN_RE =\n /^urn:dig:chia:([0-9a-fA-F]{64})(?::([0-9a-fA-F]{64}))?\\/(.+?)(?:\\?salt=([0-9a-fA-F]+))?$/;\n\n/**\n * Parse a DIG URN into its parts. Throws on a malformed URN.\n *\n * @example\n * parseUrn(\"urn:dig:chia:\" + \"ab\".repeat(32) + \"/index.html\")\n * // → { storeId: \"abab…\", root: null, resourceKey: \"index.html\", salt: null }\n */\nexport function parseUrn(raw: string): ParsedUrn {\n const s = String(raw ?? \"\").trim();\n const m = URN_RE.exec(s);\n if (!m) {\n throw new DigSdkError(\n \"INVALID_ARGUMENT\",\n \"Not a valid dig URN (expected urn:dig:chia:<store-id>[:<root>]/<path>[?salt=<hex>]).\",\n { value: s, expected: \"urn:dig:chia:<store-id>[:<root>]/<path>[?salt=<hex>]\" },\n );\n }\n return {\n storeId: m[1]!.toLowerCase(),\n root: m[2] ? m[2].toLowerCase() : null,\n resourceKey: m[3]!,\n salt: m[4] ? m[4].toLowerCase() : null,\n };\n}\n\n/** True iff `raw` is a syntactically valid DIG URN. Never throws. */\nexport function isUrn(raw: string): boolean {\n try {\n parseUrn(raw);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Reconstruct the canonical, root-INDEPENDENT URN string for a store + resource key:\n * `urn:dig:chia:<store_id>/<resource_key>`. An empty resource key resolves to the default view\n * `index.html`. This is the form whose SHA-256 is the retrieval key and whose bytes seed the AES\n * key — matching the wasm's `reconstructUrn`.\n */\nexport function reconstructUrn(storeId: string, resourceKey: string): string {\n const key = resourceKey && resourceKey.length > 0 ? resourceKey : \"index.html\";\n return `urn:dig:chia:${storeId.toLowerCase()}/${key}`;\n}\n\n/**\n * Reconstruct a root-PINNED display URN: `urn:dig:chia:<store_id>:<root>/<resource_key>`. Useful\n * for sharing a URN bound to a specific generation; the retrieval/AES keys still use the rootless\n * form (`reconstructUrn`).\n */\nexport function reconstructUrnWithRoot(\n storeId: string,\n root: string,\n resourceKey: string,\n): string {\n const key = resourceKey && resourceKey.length > 0 ? resourceKey : \"index.html\";\n return `urn:dig:chia:${storeId.toLowerCase()}:${root.toLowerCase()}/${key}`;\n}\n","// DigClient — the read side of the SDK. It fetches a resource's served ciphertext from the dig RPC,\n// derives the URN's keys CLIENT-SIDE via the read-crypto wasm, verifies inclusion against an\n// on-chain root, and decrypts — so the serving host stays BLIND (it only ever relays opaque\n// ciphertext + proofs). Genericized from hub.dig.net/apps/web/lib/dig-client.js, with the hub-app\n// coupling removed (no Vite import.meta.env, no window.location origin; the RPC endpoint and the\n// trust root are explicit inputs).\n//\n// HARD BOUNDARY (read sources). Everything read from a .dig — ciphertext, inclusion proofs, the\n// public manifest, metadata — comes ONLY from the dig RPC. The trust ROOT it is verified against\n// comes from the chain (the caller resolves it from coinset.org and passes it in). The host can\n// never become the trust anchor: every content read REQUIRES a caller-supplied root.\n//\n// OBLIVIOUS model. The host returns indistinguishable ciphertext for any retrieval key, so\n// presence is UNKNOWABLE. A read therefore NEVER concludes \"not found\": it returns plaintext when\n// the URN key decrypts the bytes, otherwise the raw ciphertext (a decoy is just opaque bytes). The\n// only thrown error is a transport failure.\n\nimport { loadDigClientWasm } from \"./loader.js\";\nimport type { DigClientWasm } from \"./wasm.js\";\nimport { parseUrn } from \"./urn.js\";\nimport type {\n CollectionItemsPage,\n CollectionMeta,\n ReadOptions,\n ReadResult,\n UrnKeys,\n} from \"./types.js\";\nimport { DigSdkError } from \"./errors.js\";\n\n/** The default public dig RPC endpoint. */\nexport const DEFAULT_RPC = \"https://rpc.dig.net\";\n\n// The backend caps each dig.getContent chunk at 3 MiB (Lambda/APIGW response ceiling); the client\n// loops chunks until `complete`.\nconst RPC_CHUNK_BYTES = 3 * 1024 * 1024;\n\n/** Options to construct a DigClient. */\nexport interface DigClientOptions {\n /** dig RPC endpoint. Defaults to the public `https://rpc.dig.net`. */\n rpc?: string;\n /** Override `fetch` (e.g. an instrumented one). Defaults to the global `fetch`. */\n fetch?: typeof fetch;\n}\n\ninterface GetContentResult {\n total_length: number;\n offset: number;\n next_offset?: number | null;\n complete?: boolean;\n ciphertext?: string;\n inclusion_proof?: string;\n chunk_lens?: number[];\n}\n\n/** Decode a standard-base64 string (the RPC ciphertext encoding) to bytes — no DOM dependency. */\nfunction b64ToBytes(b64: string): Uint8Array {\n // atob exists in browsers and modern Node; fall back to Buffer in older Node.\n if (typeof atob === \"function\") {\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new Uint8Array((globalThis as any).Buffer.from(b64, \"base64\"));\n}\n\n/**\n * The read-crypto client. Construct once and reuse — the wasm is loaded + SRI-verified lazily on\n * the first read and memoized process/page-wide.\n *\n * @example\n * const dig = new DigClient();\n * const { bytes, decrypted } = await dig.read({\n * urn: \"urn:dig:chia:<storeId>/index.html\",\n * root: \"<onchain-root-hex>\",\n * });\n * if (decrypted) console.log(new TextDecoder().decode(bytes));\n */\nexport class DigClient {\n private readonly rpc: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(options: DigClientOptions = {}) {\n this.rpc = options.rpc ?? DEFAULT_RPC;\n this.fetchImpl =\n options.fetch ??\n (typeof fetch === \"function\" ? fetch.bind(globalThis) : undefinedFetch());\n }\n\n /** Load (and SRI-verify) the read-crypto wasm. Exposed for callers that want the raw functions. */\n async wasm(): Promise<DigClientWasm> {\n return loadDigClientWasm();\n }\n\n /** `retrieval_key = SHA-256(canonical rootless URN)`, lowercase hex. */\n async retrievalKey(storeId: string, resourceKey: string): Promise<string> {\n return (await this.wasm()).retrievalKey(storeId, resourceKey);\n }\n\n /** Derive the per-URN AES-256-GCM-SIV key, lowercase hex. `salt` for a private store. */\n async deriveKey(\n storeId: string,\n resourceKey: string,\n salt?: string | null,\n ): Promise<string> {\n return (await this.wasm()).deriveKey(storeId, resourceKey, salt ?? undefined);\n }\n\n /** Verify served `ciphertext` is included under `root` via the base64 merkle `proof`. */\n async verifyInclusion(\n ciphertext: Uint8Array,\n proof: string,\n root: string,\n ): Promise<boolean> {\n return (await this.wasm()).verifyInclusion(ciphertext, proof, root);\n }\n\n /** Reconstruct the canonical rootless URN whose SHA-256 is the retrieval key. */\n async reconstructUrn(storeId: string, resourceKey: string): Promise<string> {\n return (await this.wasm()).reconstructUrn(storeId, resourceKey);\n }\n\n /**\n * Derive, client-side, the two root-independent keys a URN maps to (retrieval + decryption).\n * Nothing is sent to the network — pure local derivation via the wasm.\n */\n async deriveUrnKeys(input: { urn: string; salt?: string | null }): Promise<UrnKeys> {\n const parsed = parseUrn(input.urn);\n const wasm = await this.wasm();\n const effSalt = input.salt ?? parsed.salt ?? undefined;\n return {\n storeId: parsed.storeId,\n root: parsed.root,\n resourceKey: parsed.resourceKey,\n salt: effSalt ?? null,\n retrievalKey: wasm.retrievalKey(parsed.storeId, parsed.resourceKey),\n decryptionKey: wasm.deriveKey(parsed.storeId, parsed.resourceKey, effSalt),\n };\n }\n\n /**\n * Fetch + verify + decrypt one resource by URN. `root` is the on-chain generation root to verify\n * against (resolved by the caller from the chain); when omitted, the root embedded in the URN is\n * used. Returns the bytes plus advisory `verified`/`decrypted` flags. NEVER throws \"not found\"\n * (presence is unknowable) — it throws only on a transport failure.\n */\n async read(\n input: { urn: string; root?: string | null; salt?: string | null },\n opts: ReadOptions = {},\n ): Promise<ReadResult> {\n const parsed = parseUrn(input.urn);\n const effSalt = input.salt ?? parsed.salt ?? null;\n const effRoot = input.root ?? parsed.root ?? null;\n if (!effRoot) {\n throw new DigSdkError(\n \"ROOT_REQUIRED\",\n \"a confirmed on-chain root is required to read content (pass { root } or use a root-pinned URN)\",\n { urn: input.urn },\n );\n }\n return this.readResource(\n { storeId: parsed.storeId, resourceKey: parsed.resourceKey, root: effRoot, salt: effSalt },\n opts,\n );\n }\n\n /** As `read`, but decoding the plaintext to a UTF-8 string when it decrypts (else throws). */\n async readText(\n input: { urn: string; root?: string | null; salt?: string | null },\n opts: ReadOptions = {},\n ): Promise<string> {\n const r = await this.read(input, opts);\n if (!r.decrypted) {\n throw new DigSdkError(\n \"DECRYPT_FAILED\",\n \"resource did not decrypt under this URN — wrong store/key/salt, or a decoy response\",\n { urn: input.urn },\n );\n }\n return new TextDecoder().decode(r.bytes);\n }\n\n /**\n * Read by explicit (storeId, resourceKey, root, salt) rather than a URN string. The oblivious\n * download primitive the URN read is built on.\n */\n async readResource(\n input: { storeId: string; resourceKey: string; root: string; salt?: string | null },\n opts: ReadOptions = {},\n ): Promise<ReadResult> {\n const rpc = opts.rpc ?? this.rpc;\n const wasm = await this.wasm();\n const rk = wasm.retrievalKey(input.storeId, input.resourceKey);\n const { ciphertext, proof, chunkLens } = await this.fetchCiphertext(\n input.storeId,\n rk,\n input.root,\n rpc,\n );\n let verified = false;\n try {\n verified = !!wasm.verifyInclusion(ciphertext, proof, input.root);\n } catch {\n verified = false;\n }\n const keyHex = wasm.deriveKey(input.storeId, input.resourceKey, input.salt ?? undefined);\n try {\n const bytes = decryptResourceChunks(wasm, keyHex, ciphertext, chunkLens);\n return {\n storeId: input.storeId,\n root: input.root,\n resourceKey: input.resourceKey,\n salt: input.salt ?? null,\n bytes,\n verified,\n decrypted: true,\n };\n } catch {\n // Not decryptable with this URN/salt — hand back the raw bytes; never a \"not present\" verdict.\n return {\n storeId: input.storeId,\n root: input.root,\n resourceKey: input.resourceKey,\n salt: input.salt ?? null,\n bytes: ciphertext,\n verified,\n decrypted: false,\n };\n }\n }\n\n /**\n * Read a collection's public, owner-independent facts (creator DID, item count, uniform royalty)\n * from the dig RPC (`dig.getCollection`). The collection's item set is its NFT launcher ids — the\n * authoritative, owner-independent anchor the mint produced (a DID-attributed NFT is hinted to its\n * OWNER at mint, not to the creator DID, so launcher ids — not the DID — are the read key). Pass\n * the optional `did` to have it echoed back and recorded as the declared creator.\n *\n * No wallet, no read-crypto wasm — a plain JSON-RPC read. Throws a coded {@link DigSdkError} on a\n * transport/RPC failure (never a \"not found\": an empty/partly-confirmed set just resolves to fewer\n * items).\n *\n * @example\n * const meta = await dig.getCollection({ launcherIds: [\"ab…\", \"cd…\"], did: \"ef…\" });\n * console.log(meta.resolved_count, meta.royalty_basis_points);\n */\n async getCollection(\n input: { launcherIds: string[]; did?: string | null },\n opts: ReadOptions = {},\n ): Promise<CollectionMeta> {\n const rpc = opts.rpc ?? this.rpc;\n const params: Record<string, unknown> = { launcher_ids: input.launcherIds };\n if (input.did) params.did = input.did;\n const r = await this.rpcCall<CollectionMeta>(rpc, \"dig.getCollection\", params);\n if (!r)\n throw new DigSdkError(\n \"RPC_MALFORMED_RESPONSE\",\n \"The content network returned no collection facts for this request.\",\n { rpcMethod: \"dig.getCollection\" },\n );\n return r;\n }\n\n /**\n * Read a deterministic, paginated page of a collection's items (`dig.listCollectionItems`), each\n * resolved to its CURRENT on-chain state — current owner, royalty, and CHIP-0007 metadata — by the\n * RPC walking the singleton lineage forward to the live tip (so the owner is never the stale\n * mint-time owner). Items come back in the input launcher-id order. `limit` is clamped to the\n * server cap (200); `offset` defaults to 0.\n *\n * Throws a coded {@link DigSdkError} on a transport/RPC failure.\n *\n * @example\n * let page = await dig.listCollectionItems({ launcherIds, limit: 50 });\n * for (const item of page.items) console.log(item.launcher_id, item.owner_puzzle_hash);\n * // page.next_offset is null on the last page.\n */\n async listCollectionItems(\n input: { launcherIds: string[]; offset?: number; limit?: number },\n opts: ReadOptions = {},\n ): Promise<CollectionItemsPage> {\n const rpc = opts.rpc ?? this.rpc;\n const params: Record<string, unknown> = { launcher_ids: input.launcherIds };\n if (input.offset !== undefined) params.offset = input.offset;\n if (input.limit !== undefined) params.limit = input.limit;\n const r = await this.rpcCall<CollectionItemsPage>(rpc, \"dig.listCollectionItems\", params);\n if (!r)\n throw new DigSdkError(\n \"RPC_MALFORMED_RESPONSE\",\n \"The content network returned no collection items for this request.\",\n { rpcMethod: \"dig.listCollectionItems\" },\n );\n return r;\n }\n\n // Stream the FULL ciphertext for a resource from the RPC by retrieval key, reassembling 3-MiB\n // chunks. A null result is a TRANSPORT failure, never a presence judgment.\n private async fetchCiphertext(\n storeId: string,\n rk: string,\n root: string,\n rpc: string,\n ): Promise<{ ciphertext: Uint8Array; proof: string; chunkLens: number[] | null }> {\n let offset = 0;\n let total: number | null = null;\n let buf: Uint8Array | null = null;\n let proof = \"\";\n let chunkLens: number[] | null = null;\n for (;;) {\n const r = await this.rpcCall<GetContentResult>(rpc, \"dig.getContent\", {\n store_id: storeId,\n root,\n retrieval_key: rk,\n offset,\n length: RPC_CHUNK_BYTES,\n });\n if (!r)\n throw new DigSdkError(\n \"RPC_MALFORMED_RESPONSE\",\n \"The content network returned no data for this request.\",\n { rpcMethod: \"dig.getContent\" },\n );\n if (total === null) {\n total = r.total_length >>> 0;\n buf = new Uint8Array(total);\n }\n if (chunkLens === null && Array.isArray(r.chunk_lens)) {\n chunkLens = r.chunk_lens.map((n) => n >>> 0);\n }\n const chunk = b64ToBytes(r.ciphertext ?? \"\");\n const at = r.offset >>> 0;\n buf!.set(chunk.subarray(0, Math.max(0, Math.min(chunk.length, total - at))), at);\n if (r.inclusion_proof) proof = r.inclusion_proof;\n if (r.complete || r.next_offset == null) break;\n offset = r.next_offset >>> 0;\n }\n return { ciphertext: buf ?? new Uint8Array(0), proof, chunkLens };\n }\n\n // One JSON-RPC 2.0 call. Throws a coded DigSdkError on transport failure (RPC_TRANSPORT) or a\n // JSON-RPC/HTTP error (RPC_ERROR, carrying rpcMethod/httpStatus/rpcCode context); returns `result`.\n private async rpcCall<T>(rpc: string, method: string, params: unknown): Promise<T | null> {\n let res: Response;\n try {\n res = await this.fetchImpl(rpc, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ jsonrpc: \"2.0\", id: 1, method, params }),\n });\n } catch (e) {\n throw new DigSdkError(\n \"RPC_TRANSPORT\",\n \"Could not reach the content network. Check your connection and try again.\",\n { rpcMethod: method },\n { cause: e },\n );\n }\n if (!res.ok)\n throw new DigSdkError(\"RPC_ERROR\", `dig RPC ${method} failed (${res.status})`, {\n rpcMethod: method,\n httpStatus: res.status,\n });\n const json = (await res.json()) as {\n result?: T;\n error?: { message?: string; code?: number };\n };\n if (json && json.error)\n throw new DigSdkError(\n \"RPC_ERROR\",\n `dig RPC ${method}: ${json.error.message ?? \"error\"}`,\n { rpcMethod: method, rpcCode: json.error.code },\n );\n return json ? (json.result ?? null) : null;\n }\n}\n\n// AES-256-GCM-SIV-open a resource's served ciphertext under `keyHex`, splitting the PLAIN-\n// concatenated chunk ciphertexts by `chunkLens` (per-chunk CIPHERTEXT byte lengths) and opening\n// each. Empty/absent chunkLens ⇒ single-chunk resource. Throws if any chunk's tag fails.\nfunction decryptResourceChunks(\n wasm: DigClientWasm,\n keyHex: string,\n ciphertext: Uint8Array,\n chunkLens: number[] | null,\n): Uint8Array {\n const lens = chunkLens && chunkLens.length ? chunkLens : [ciphertext.length];\n const total = lens.reduce((a, n) => a + n, 0);\n if (total !== ciphertext.length) {\n throw new DigSdkError(\n \"RPC_MALFORMED_RESPONSE\",\n \"served ciphertext length does not match chunk lengths\",\n { rpcMethod: \"dig.getContent\", expected: String(total), actual: String(ciphertext.length) },\n );\n }\n if (lens.length === 1) return wasm.decryptChunk(keyHex, ciphertext);\n const parts: Uint8Array[] = [];\n let p = 0;\n for (const len of lens) {\n parts.push(wasm.decryptChunk(keyHex, ciphertext.subarray(p, p + len)));\n p += len;\n }\n const out = new Uint8Array(parts.reduce((a, x) => a + x.length, 0));\n let q = 0;\n for (const part of parts) {\n out.set(part, q);\n q += part.length;\n }\n return out;\n}\n\nfunction undefinedFetch(): typeof fetch {\n return (() => {\n throw new DigSdkError(\n \"INVALID_ARGUMENT\",\n \"No global fetch available. Pass { fetch } to DigClient (Node < 18 needs a fetch polyfill).\",\n );\n }) as unknown as typeof fetch;\n}\n"]}
package/dist/index.cjs CHANGED
@@ -403,7 +403,8 @@ var ChiaProvider = class _ChiaProvider {
403
403
  * injected DIG wallet and falls back to WalletConnect.
404
404
  */
405
405
  static async connect(options = {}) {
406
- const mode = options.mode ?? "auto";
406
+ const rawMode = options.mode ?? "auto";
407
+ const mode = rawMode === "browser-wallet" ? "injected" : rawMode;
407
408
  const chain = options.chain ?? DEFAULT_CHAIN;
408
409
  const tryInjected = async () => {
409
410
  if (!isInjectedAvailable({ anyChia: options.acceptAnyInjected })) return null;
@@ -417,7 +418,7 @@ var ChiaProvider = class _ChiaProvider {
417
418
  throw new DigSdkError(
418
419
  "WC_OPTIONS_REQUIRED",
419
420
  "WalletConnect options are required to connect via WalletConnect (pass { walletConnect: { projectId, metadata, onUri } }).",
420
- { mode }
421
+ { mode: rawMode }
421
422
  );
422
423
  }
423
424
  const transport = await WalletConnectTransport.connect({
@@ -432,7 +433,7 @@ var ChiaProvider = class _ChiaProvider {
432
433
  throw new DigSdkError(
433
434
  "NO_INJECTED_WALLET",
434
435
  "No injected DIG wallet found. Open this page in the DIG Browser, or use mode 'auto'.",
435
- { mode, acceptAnyInjected: !!options.acceptAnyInjected }
436
+ { mode: rawMode, acceptAnyInjected: !!options.acceptAnyInjected }
436
437
  );
437
438
  }
438
439
  return injected;
@@ -440,6 +441,34 @@ var ChiaProvider = class _ChiaProvider {
440
441
  if (mode === "walletconnect") return tryWalletConnect();
441
442
  return await tryInjected() ?? await tryWalletConnect();
442
443
  }
444
+ /**
445
+ * Enumerate the connectors a 'Browser Wallet vs WalletConnect' Connect chooser can offer (#63).
446
+ * Pure and side-effect-free — it only DETECTS what's usable right now, it never connects to
447
+ * anything — so a chooser UI built around it always surfaces the choice instead of silently
448
+ * auto-binding to whichever wallet happens to be injected.
449
+ *
450
+ * @example
451
+ * const connectors = ChiaProvider.listConnectors();
452
+ * // render a button per connector, disabling any with `available: false`
453
+ * const chosen = connectors.find((c) => c.id === userPick)!;
454
+ * const provider = await ChiaProvider.connect({ mode: chosen.id, walletConnect });
455
+ */
456
+ static listConnectors(options = {}) {
457
+ return [
458
+ {
459
+ id: "browser-wallet",
460
+ backend: "injected",
461
+ label: "Browser Wallet",
462
+ available: isInjectedAvailable({ anyChia: options.acceptAnyInjected })
463
+ },
464
+ {
465
+ id: "walletconnect",
466
+ backend: "walletconnect",
467
+ label: "WalletConnect",
468
+ available: true
469
+ }
470
+ ];
471
+ }
443
472
  /** Wrap an already-constructed transport (advanced / restored sessions). */
444
473
  static fromTransport(transport) {
445
474
  return new _ChiaProvider(transport);
@@ -702,7 +731,7 @@ var Paywall = class {
702
731
  };
703
732
 
704
733
  // src/loader.ts
705
- var DIG_CLIENT_WASM_SHA256 = "8c983561eabca34778abf698ca7c2fba36117f87282ca649079599ef7d1b1156";
734
+ var DIG_CLIENT_WASM_SHA256 = "a186fd2d6b348a7caa3112c51b666a6618fe7cf8bb56ad395a1fab4323f6ae7e";
706
735
  var _config = {};
707
736
  var _ready = null;
708
737
  function configureWasm(config) {
@@ -737,16 +766,16 @@ async function loadNode() {
737
766
  const { createRequire } = await import('module');
738
767
  const { readFile } = await import('fs/promises');
739
768
  const require2 = createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
740
- const wasmPath = require2.resolve("@dignetwork/dig-client/dig_client_bg.wasm");
769
+ const wasmPath = require2.resolve("@dignetwork/dig-capsule-wasm/dig_client_bg.wasm");
741
770
  const buf = await readFile(wasmPath);
742
771
  const bytes = new Uint8Array(buf.byteLength);
743
772
  bytes.set(buf);
744
773
  assertIntegrity(await sha256Hex(bytes));
745
- const mod = await import('@dignetwork/dig-client/node');
774
+ const mod = await import('@dignetwork/dig-capsule-wasm/node');
746
775
  return mod;
747
776
  }
748
777
  async function loadBrowser() {
749
- const glueHref = _config.glueUrl ?? "@dignetwork/dig-client/web";
778
+ const glueHref = _config.glueUrl ?? "@dignetwork/dig-capsule-wasm/web";
750
779
  const mod = await import(
751
780
  /* @vite-ignore */
752
781
  glueHref
@@ -1118,7 +1147,7 @@ function undefinedFetch() {
1118
1147
  }
1119
1148
 
1120
1149
  // src/capabilities.ts
1121
- var SDK_VERSION = "0.2.1" ;
1150
+ var SDK_VERSION = "0.3.3" ;
1122
1151
  var MODULES = Object.freeze([
1123
1152
  {
1124
1153
  name: "ChiaProvider",