@dignetwork/dig-sdk 0.2.0 → 0.2.1
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 +9 -6
- package/dist/adapters.cjs.map +1 -1
- package/dist/adapters.js.map +1 -1
- package/dist/{dig-client-entry-ChYxUvBn.d.cts → dig-client-entry-Bc95rd_t.d.cts} +10 -6
- package/dist/{dig-client-entry-ChYxUvBn.d.ts → dig-client-entry-Bc95rd_t.d.ts} +10 -6
- package/dist/dig-client.cjs +38 -31
- package/dist/dig-client.cjs.map +1 -1
- package/dist/dig-client.d.cts +1 -1
- package/dist/dig-client.d.ts +1 -1
- package/dist/dig-client.js +38 -31
- package/dist/dig-client.js.map +1 -1
- package/dist/index.cjs +40 -33
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +40 -33
- package/dist/index.js.map +1 -1
- package/dist/next.cjs.map +1 -1
- package/dist/next.js.map +1 -1
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.js.map +1 -1
- package/package.json +5 -6
- package/vendor/PROVENANCE.md +0 -102
- package/vendor/dig_client.d.ts +0 -150
- package/vendor/dig_client.mjs +0 -805
- package/vendor/dig_client_bg.wasm +0 -0
package/dist/next.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/provider/injected.ts","../src/adapters/dev-shim.ts","../src/adapters/config.ts","../src/adapters/dig-toml.ts","../src/adapters/deploy.ts","../src/adapters/run.ts","../src/next.ts"],"names":[],"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,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A,EAAU,IAAA;AAAA,YACV,MAAA,EAAQ,GAAA,CAAI,KAAA,CAAM,CAAA,EAAG,GAAI;AAAA,WAC1B;AAAA,SACH;AAAA,IACJ,CAAC,CAAA;AAAA,EACH,CAAC,CAAA;AAED,EAAA,MAAM,MAAA,GAAS,kBAAkB,MAAM,CAAA;AACvC,EAAA,GAAA,CAAI,CAAA,wBAAA,EAAsB,MAAA,CAAO,OAAO,CAAA,CAAE,CAAA;AAE1C,EAAA,GAAA,CAAI,CAAA,UAAA,EAAa,MAAA,CAAO,OAAO,CAAA,CAAE,CAAA;AACjC,EAAA,GAAA,CAAI,CAAA,UAAA,EAAa,MAAA,CAAO,MAAM,CAAA,CAAE,CAAA;AAChC,EAAA,OAAO,MAAA;AACT;;;AChGA,IAAM,eAAA,GAAkB,KAAA;AAMjB,SAAS,oBAAA,CAAqB,OAAA,GAA0B,EAAC,EAAW;AACzE,EAAA,OAAO,cAAc,OAAO,CAAA;AAC9B;AAQO,SAAS,iBAAA,CAAkB,OAAA,GAA0B,EAAC,EAAW;AACtE,EAAA,OAAO,CAAA,QAAA,EAAW,aAAA,CAAc,OAAO,CAAC,CAAA,SAAA,CAAA;AAC1C;AAQO,SAAS,SAAA,CAAU,OAAA,GAA0B,EAAC,EAA0B;AAC7E,EAAA,OAAO,SAAA,CAAU,EAAE,GAAG,OAAA,EAAS,SAAA,EAAW,QAAQ,SAAA,IAAa,eAAA,EAAiB,SAAA,EAAW,IAAA,EAAM,CAAA;AACnG;AAEA,IAAO,YAAA,GAAQ","file":"next.cjs","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 vendored 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","// Injected-provider transport — the DIG Browser's in-process wallet (and compatible CHIP-0002\n// extensions), exposed on every page as `window.chia`. When present the SDK PREFERS it over\n// WalletConnect: no QR, no relay, no pairing. The native provider returns the SAME response shapes\n// Sage returns over WalletConnect, so the normalizers in provider/methods.ts are unchanged — only\n// the TRANSPORT differs. Genericized from hub.dig.net/apps/web/lib/injected-wallet.js.\n//\n// Detection: we key on the explicit, unspoofable `isDIG` marker the DIG Browser provider sets, not\n// merely the presence of `window.chia` (a different Chia provider could also define that).\n\nimport type { InjectedChiaProvider, WalletBackend } from \"../types.js\";\nimport { WALLET_METHODS, DEFAULT_CHAIN } from \"../methods.js\";\nimport type { WalletTransport } from \"./transport.js\";\nimport { DigSdkError } from \"../errors.js\";\n\n/** The injected provider on the current global, or undefined when not running in a DIG Browser. */\nexport function getInjectedProvider(): InjectedChiaProvider | undefined {\n const g = globalThis as { chia?: InjectedChiaProvider };\n return typeof g !== \"undefined\" ? g.chia : undefined;\n}\n\n/**\n * True iff an injected DIG wallet is available. Detects on the unspoofable `isDIG` marker. Pass\n * `{ anyChia: true }` to accept any `window.chia` that implements `request` (e.g. a non-DIG\n * CHIP-0002 extension).\n */\nexport function isInjectedAvailable(opts: { anyChia?: boolean } = {}): boolean {\n const p = getInjectedProvider();\n if (!p) return false;\n if (opts.anyChia) return typeof p.request === \"function\";\n return !!p.isDIG;\n}\n\n/** Sentinel topic for the injected backend (it has no per-session relay topic). */\nexport const INJECTED_TOPIC = \"injected\";\n\n/** A WalletTransport backed by the injected window.chia provider. */\nexport class InjectedTransport implements WalletTransport {\n readonly backend: WalletBackend = \"injected\";\n readonly topic = INJECTED_TOPIC;\n readonly chain: string;\n private readonly provider: InjectedChiaProvider;\n\n constructor(provider: InjectedChiaProvider, chain: string = DEFAULT_CHAIN) {\n this.provider = provider;\n this.chain = chain;\n }\n\n /** Connect: ask the native wallet to approve this origin. Blocks until approved/rejected. */\n async connect(eager = false): Promise<void> {\n if (typeof this.provider.connect === \"function\") {\n await this.provider.connect(eager);\n }\n // A provider without connect() (older build) is tolerated — request() will gate per-method.\n }\n\n // The native wallet implements the full canonical set (it returns Sage-shaped responses), so\n // support is a static allowlist — no per-session negotiation as with WalletConnect.\n supports(method: string): boolean {\n return (WALLET_METHODS as readonly string[]).includes(method);\n }\n\n async request(method: string, params: unknown): Promise<unknown> {\n if (!this.supports(method)) {\n throw new DigSdkError(\n \"METHOD_NOT_SUPPORTED\",\n `The DIG Browser wallet does not support \"${method}\".`,\n { method },\n );\n }\n return this.provider.request({ method, params });\n }\n\n async disconnect(): Promise<void> {\n // The injected wallet has no per-session teardown; per-origin consent is managed in the wallet.\n }\n}\n","// The `window.chia` DEV shim the adapters inject during `dev`.\n//\n// In production a dapp's wallet is the REAL injected provider — the DIG Browser's in-process wallet\n// (or a CHIP-0002 extension) — which the SDK's ChiaProvider detects on `window.chia` via the\n// `isDIG` marker (see src/provider/injected.ts). During local `vite dev` / `next dev` there is no\n// such wallet, so calling `ChiaProvider.connect({ mode: \"injected\" })` would fail and the developer\n// couldn't exercise the wallet path at all.\n//\n// This shim installs a MINIMAL, clearly-labelled stub that satisfies the SAME injected-provider\n// contract the SDK detects (`isDIG`, `request({method,params})`, `connect()`), so the wallet code\n// path runs end-to-end in dev. It is a STUB, not a wallet: it returns a configurable mock address\n// and otherwise throws on methods that would need real signing, so a developer is never misled into\n// thinking a signature is real. It is generated as a self-contained, eval-free `<script>` body\n// (CSP-safe) that GUARDS on an existing `window.chia`, so a real wallet always wins.\n//\n// The shim's method names + response envelope mirror src/provider/injected.ts and\n// src/provider/methods.ts (the native provider returns `{ data }`), so the SAME normalizers run in\n// dev as in production — only the values are mocked.\n\nimport { INJECTED_TOPIC } from \"../provider/injected.js\";\n\n/** A literal substring stamped into the shim so it is unmistakably a dev stub (asserted in tests). */\nexport const DEV_SHIM_MARKER = \"dig-sdk:dev-wallet-shim\";\n\n/** Options for the generated dev shim. */\nexport interface DevShimOptions {\n /** Mock receive address the shim returns from `getAddress`. A clearly-fake default is used. */\n address?: string;\n}\n\n/** A clearly-fake default dev address (so it is obvious in the UI this is not a real wallet). */\nconst DEFAULT_DEV_ADDRESS = \"xch1dev0000000000000000000000000000000000000000000000000000devshim\";\n\n/** JSON-encode a string for safe inlining into a script literal. */\nfunction lit(s: string): string {\n return JSON.stringify(s);\n}\n\n/**\n * Generate the dev-shim `<script>` body (no surrounding `<script>` tags). Inline it into the dev\n * server's served HTML. It is an IIFE that installs `window.chia` ONLY if one is not already\n * present, so the DIG Browser / a real extension always takes precedence. Eval-free and\n * dependency-free — safe under a strict CSP.\n */\nexport function devShimScript(options: DevShimOptions = {}): string {\n const address = options.address ?? DEFAULT_DEV_ADDRESS;\n // The shim mirrors the injected-provider contract the SDK detects. `request` resolves a small set\n // of read methods with mock data and rejects signing methods (a dev stub must not fake a\n // signature). Method names are the bare CHIP-0002 names the SDK normalizes.\n return [\n `/* ${DEV_SHIM_MARKER} — DEV ONLY. A stub wallet for local development; NOT a real wallet. */`,\n `(function () {`,\n ` \"use strict\";`,\n ` if (typeof window === \"undefined\") return;`,\n ` // A real injected wallet (DIG Browser / extension) always wins — never clobber it.`,\n ` if (window.chia) return;`,\n ` var DEV_ADDRESS = ${lit(address)};`,\n ` var TOPIC = ${lit(INJECTED_TOPIC)};`,\n ` function ok(data) { return Promise.resolve({ data: data }); }`,\n ` function nope(method) {`,\n ` return Promise.reject(new Error(`,\n ` \"[\" + ${lit(DEV_SHIM_MARKER)} + \"] '\" + method + \"' needs a real wallet; the dev shim does not sign. \" +`,\n ` \"Open in the DIG Browser or connect a wallet to sign for real.\"));`,\n ` }`,\n ` window.chia = {`,\n ` isDIG: true, // detected by the SDK's injected-provider check`,\n ` isDevShim: true, // so the app can tell it is the dev stub`,\n ` topic: TOPIC,`,\n ` connect: function () { return Promise.resolve(true); },`,\n ` request: function (args) {`,\n ` var method = args && args.method ? String(args.method) : \"\";`,\n ` switch (method) {`,\n ` case \"chip0002_connect\": return ok(true);`,\n ` case \"chip0002_getPublicKeys\": return ok([]);`,\n ` case \"getAddress\":`,\n ` case \"chia_getAddress\": return ok(DEV_ADDRESS);`,\n ` default:`,\n ` // Signing / spend methods must not be faked.`,\n ` return nope(method);`,\n ` }`,\n ` },`,\n ` on: function () {},`,\n ` off: function () {},`,\n ` };`,\n ` if (window.console && window.console.info) {`,\n ` window.console.info(\"[\" + ${lit(DEV_SHIM_MARKER)} + \"] installed a DEV window.chia (mock address \" + DEV_ADDRESS + \").\");`,\n ` }`,\n `})();`,\n ].join(\"\\n\");\n}\n","// Deploy-config resolution for the framework adapters.\n//\n// The final config a deploy runs with is composed from three layers, highest precedence first:\n// 1. plugin options — what the developer wrote in vite.config / the Next adapter call\n// 2. environment vars — what CI injects (DIGSTORE_*), incl. the SECRETS (deploy key, salt)\n// 3. dig.toml — the project's checked-in defaults\n// 4. built-in defaults — outputDir=\"dist\", network=\"mainnet\" (mirrors deploy.rs::resolve_config)\n//\n// This mirrors `digstore deploy`'s own resolution order (flag/env > dig.toml > default) so the\n// adapters never disagree with the CLI about what a project deploys. SECRETS are resolved ONLY from\n// env — never from options or dig.toml — so they can't end up checked into a repo or a config file.\n\nimport type { DigTomlConfig } from \"./dig-toml.js\";\n\n/** Per-call options a developer passes to the Vite plugin / Next adapter. */\nexport interface AdapterOptions {\n /** On-chain store id (64-hex) to advance. Usually set in dig.toml instead. */\n storeId?: string;\n /** Built-output directory to publish. Defaults to the framework's output (or \"dist\"). */\n outputDir?: string;\n /** Shell build command for `digstore` to run. Omit when the adapter builds itself. */\n buildCommand?: string;\n /** Commit message for the new capsule. */\n message?: string;\n /** Chain network. Defaults to \"mainnet\". */\n network?: string;\n /** The `origin` remote to publish to (e.g. `dig://<storeId>`). */\n remote?: string;\n /** Seconds to wait for on-chain confirmation. */\n waitTimeout?: number;\n}\n\n/** The fully resolved config a deploy runs with. Secrets are present only if env supplied them. */\nexport interface ResolvedDeployConfig {\n storeId?: string;\n outputDir: string;\n buildCommand?: string;\n message?: string;\n network: string;\n remote?: string;\n waitTimeout?: number;\n /** Publisher deploy key (64-hex). From env only. */\n deployKey?: string;\n /** Private-store secret salt (64-hex). From env only. */\n salt?: string;\n}\n\n/** Inputs to resolution — kept explicit so it is a pure function (no process.env read inside). */\nexport interface ResolveInput {\n options: AdapterOptions;\n digToml: DigTomlConfig;\n env: Record<string, string | undefined>;\n}\n\n/** A non-empty, trimmed env value, or undefined. Empty/whitespace env vars count as unset. */\nfunction envVal(env: Record<string, string | undefined>, key: string): string | undefined {\n const v = env[key];\n if (v == null) return undefined;\n const t = v.trim();\n return t === \"\" ? undefined : t;\n}\n\n/** First defined of the candidates (treating \"\" the caller already filtered as undefined). */\nfunction pick<T>(...candidates: (T | undefined)[]): T | undefined {\n for (const c of candidates) if (c !== undefined) return c;\n return undefined;\n}\n\n/**\n * Resolve the final deploy config. Precedence per field: options > env (DIGSTORE_*) > dig.toml >\n * default. Secrets (deployKey, salt) are taken from env ONLY.\n */\nexport function resolveDeployConfig(input: ResolveInput): ResolvedDeployConfig {\n const { options, digToml, env } = input;\n\n const storeId = pick(\n options.storeId,\n envVal(env, \"DIGSTORE_STORE_ID\"),\n digToml.storeId,\n );\n const outputDir =\n pick(options.outputDir, envVal(env, \"DIGSTORE_OUTPUT_DIR\"), digToml.outputDir) ?? \"dist\";\n const buildCommand = pick(\n options.buildCommand,\n envVal(env, \"DIGSTORE_BUILD_COMMAND\"),\n digToml.buildCommand,\n );\n const message = pick(options.message, envVal(env, \"DIGSTORE_MESSAGE\"), digToml.message);\n const network =\n pick(options.network, envVal(env, \"DIGSTORE_NETWORK\"), digToml.network) ?? \"mainnet\";\n const remote = pick(options.remote, envVal(env, \"DIGSTORE_REMOTE\"), digToml.remote);\n\n const waitFromEnv = envVal(env, \"DIGSTORE_WAIT_TIMEOUT\");\n const waitTimeout = pick(\n options.waitTimeout,\n waitFromEnv != null ? Number.parseInt(waitFromEnv, 10) : undefined,\n digToml.waitTimeout,\n );\n\n return {\n storeId,\n outputDir,\n buildCommand,\n message,\n network,\n remote,\n waitTimeout: Number.isFinite(waitTimeout) ? waitTimeout : undefined,\n // SECRETS — env only.\n deployKey: envVal(env, \"DIGSTORE_DEPLOY_KEY\"),\n salt: envVal(env, \"DIGSTORE_STORE_SALT\"),\n };\n}\n","// Minimal `dig.toml` reader for the framework adapters.\n//\n// `digstore deploy` reads its config from a project's `dig.toml` (digstore-cli/src/dig_toml.rs).\n// The adapters need the SAME few top-level keys so a project's `dig.toml` is the single source of\n// truth across the CLI and the plugins. Rather than pull in a TOML parser dependency for ~7 flat\n// `key = \"value\"` lines, we parse just those keys ourselves. We accept BOTH the canonical\n// kebab-case key and the snake_case alias, exactly like digstore's `#[serde(rename/alias)]`.\n//\n// Anything beyond these keys (tables, arrays, nested values) is intentionally ignored — the\n// adapters only forward the deploy-relevant scalars to `digstore deploy`, which re-reads the full\n// file authoritatively.\n\n/** The deploy-relevant subset of `dig.toml`, in the adapters' camelCase shape. */\nexport interface DigTomlConfig {\n storeId?: string;\n outputDir?: string;\n buildCommand?: string;\n message?: string;\n network?: string;\n remote?: string;\n waitTimeout?: number;\n}\n\n// Map each canonical/alias TOML key onto the camelCase field. kebab-case is canonical (it is what\n// `digstore new` writes); snake_case is the tolerated alias. When both appear, the canonical\n// kebab-case key wins (it is applied last).\nconst KEY_MAP: Record<string, keyof DigTomlConfig> = {\n store_id: \"storeId\",\n \"store-id\": \"storeId\",\n output_dir: \"outputDir\",\n \"output-dir\": \"outputDir\",\n build_command: \"buildCommand\",\n \"build-command\": \"buildCommand\",\n message: \"message\",\n network: \"network\",\n remote: \"remote\",\n wait_timeout: \"waitTimeout\",\n \"wait-timeout\": \"waitTimeout\",\n};\n\n// Apply snake_case first then kebab-case so the canonical kebab form overrides the alias.\nconst APPLY_ORDER = Object.keys(KEY_MAP).sort((a) =>\n a.includes(\"-\") ? 1 : -1,\n);\n\n/** Strip a `# comment` that is not inside a quoted value. */\nfunction stripComment(line: string): string {\n let inSingle = false;\n let inDouble = false;\n for (let i = 0; i < line.length; i++) {\n const ch = line[i];\n if (ch === \"'\" && !inDouble) inSingle = !inSingle;\n else if (ch === '\"' && !inSingle) inDouble = !inDouble;\n else if (ch === \"#\" && !inSingle && !inDouble) return line.slice(0, i);\n }\n return line;\n}\n\n/** Unquote a TOML scalar: `\"x\"` / `'x'` → `x`; a bare token is returned trimmed. */\nfunction unquote(raw: string): string {\n const v = raw.trim();\n if (\n (v.startsWith('\"') && v.endsWith('\"') && v.length >= 2) ||\n (v.startsWith(\"'\") && v.endsWith(\"'\") && v.length >= 2)\n ) {\n return v.slice(1, -1);\n }\n return v;\n}\n\n/**\n * Parse the deploy-relevant keys out of a `dig.toml` string. Unknown keys, tables, and nested\n * structures are ignored. Returns only the keys actually present (so it composes cleanly under the\n * precedence rules in resolveDeployConfig).\n */\nexport function parseDigToml(text: string): DigTomlConfig {\n // Collect raw (canonical-or-alias) string values keyed by the TOML key as written.\n const raw: Record<string, string> = {};\n for (const lineRaw of text.split(/\\r?\\n/)) {\n const line = stripComment(lineRaw).trim();\n if (!line || line.startsWith(\"[\")) continue; // skip blanks + table headers\n const eq = line.indexOf(\"=\");\n if (eq <= 0) continue;\n const key = line.slice(0, eq).trim();\n if (!(key in KEY_MAP)) continue;\n raw[key] = unquote(line.slice(eq + 1));\n }\n\n const out: DigTomlConfig = {};\n for (const key of APPLY_ORDER) {\n const value = raw[key];\n const field = KEY_MAP[key];\n if (value === undefined || field === undefined) continue;\n if (field === \"waitTimeout\") {\n const n = Number.parseInt(value, 10);\n if (Number.isFinite(n)) out.waitTimeout = n;\n } else {\n out[field] = value;\n }\n }\n return out;\n}\n","// The pure glue around `digstore deploy --json`: build the child argv + env, and parse the result.\n//\n// The adapters SHELL OUT to the installed `digstore` binary (the canonical deployer — it advances\n// the on-chain root, stages the build dir, and pushes the new capsule to DIGHUb). They never\n// re-implement deploy. These helpers are the deterministic, side-effect-free pieces:\n//\n// • buildDeployArgs — resolved config → argv (always `deploy --json`, only set flags).\n// • buildDeployEnv — resolved config → the env overlay carrying the SECRETS to the child, so the\n// deploy key / salt are NEVER on the argv (process-table leak), matching\n// digstore-cli's own guidance (deploy.rs).\n// • parseDeployResult— `digstore deploy --json` stdout → { capsule, storeId, root, chiaUrl,\n// digUrl, hubUrl, pushed }, deriving the URLs exactly as digstore does\n// (capsule = storeId:root; hub view = https://hub.dig.net/stores/<id>;\n// chiaUrl = the user-facing content-open address chia://<store>:<root>/,\n// matching digstore's printed `content_address`).\n\nimport type { ResolvedDeployConfig } from \"./config.js\";\nimport { DigSdkError } from \"../errors.js\";\n\n/** Knobs for argv construction. */\nexport interface DeployArgsOptions {\n /**\n * The adapter already ran the framework build, so don't hand `--build-command` to digstore (it\n * would rebuild). The output dir is staged as-is.\n */\n skipBuild?: boolean;\n}\n\n/**\n * Build the argv for `digstore <argv>` from a resolved config. Always `deploy --json`. Only flags\n * whose values are set are emitted. SECRETS (deployKey, salt) are intentionally excluded — they go\n * through the env (buildDeployEnv) so they never appear in the process table.\n */\nexport function buildDeployArgs(\n cfg: ResolvedDeployConfig,\n opts: DeployArgsOptions = {},\n): string[] {\n const argv: string[] = [\"deploy\", \"--json\"];\n if (cfg.storeId) argv.push(\"--store-id\", cfg.storeId);\n if (cfg.outputDir) argv.push(\"--output-dir\", cfg.outputDir);\n if (!opts.skipBuild && cfg.buildCommand) argv.push(\"--build-command\", cfg.buildCommand);\n if (cfg.message) argv.push(\"--message\", cfg.message);\n if (cfg.network) argv.push(\"--network\", cfg.network);\n if (cfg.remote) argv.push(\"--remote\", cfg.remote);\n if (cfg.waitTimeout != null) argv.push(\"--wait-timeout\", String(cfg.waitTimeout));\n return argv;\n}\n\n/**\n * The env overlay to merge onto the child process env: the SECRETS, passed out-of-band so they are\n * never visible on the command line. Returns only the keys that have a value.\n */\nexport function buildDeployEnv(cfg: ResolvedDeployConfig): Record<string, string> {\n const env: Record<string, string> = {};\n if (cfg.deployKey) env.DIGSTORE_DEPLOY_KEY = cfg.deployKey;\n if (cfg.salt) env.DIGSTORE_STORE_SALT = cfg.salt;\n return env;\n}\n\n/** The friendly, parsed outcome of a deploy. */\nexport interface DeployResult {\n /** `storeId:rootHash` — the capsule identity (the ecosystem-vocabulary id the user shares). */\n capsule: string;\n /** Store identity (64-hex). */\n storeId: string;\n /** The new on-chain root (64-hex). */\n root: string;\n /**\n * The user-facing content-open address `chia://<storeId>:<rootHash>/` — what a user types/clicks\n * to open this verified capsule in the DIG Browser / extension (the scheme they register). This\n * matches digstore deploy's printed `content_address` exactly. (Distinct from the §21 remote\n * locator `dig://<host>/<store_id>` and the `urn:dig:` namespace, which stay `dig://`.)\n */\n chiaUrl: string;\n /**\n * @deprecated Use {@link chiaUrl}. Kept as a back-compat alias for consumers that read `digUrl`;\n * it now carries the SAME `chia://<storeId>:<rootHash>/` content-open value (NOT a `dig://` URL).\n */\n digUrl: string;\n /** The human \"view it\" URL on DIGHUb (the same one `digstore deploy` prints). */\n hubUrl: string;\n /** Whether the capsule was pushed to DIGHUb (when the JSON reported it). */\n pushed?: boolean;\n}\n\nconst CAPSULE_RE = /^([0-9a-f]{64}):([0-9a-f]{64})$/i;\n\n/**\n * Parse `digstore deploy --json` stdout into a DeployResult. digstore emits a single JSON object\n * (with at least `capsule` and `root`); we also tolerate extra JSON log lines by scanning lines\n * bottom-up for the first object that carries a `capsule`. Throws a clear error if none is found or\n * the output isn't JSON at all.\n */\nexport function parseDeployResult(stdout: string): DeployResult {\n const lines = stdout\n .split(/\\r?\\n/)\n .map((l) => l.trim())\n .filter((l) => l.startsWith(\"{\") && l.endsWith(\"}\"));\n\n if (lines.length === 0) {\n throw new DigSdkError(\n \"DEPLOY_OUTPUT_UNPARSEABLE\",\n `could not parse digstore deploy output (no JSON object found). Output was:\\n${stdout.slice(0, 500)}`,\n { stdout: stdout.slice(0, 500) },\n );\n }\n\n // Prefer the LAST JSON object that has a capsule (deploy emits one final result object). Keep the\n // first parseable object as a fallback so the error message can show what digstore DID return.\n let obj: Record<string, unknown> | undefined;\n let fallback: Record<string, unknown> | undefined;\n for (let i = lines.length - 1; i >= 0; i--) {\n const line = lines[i];\n if (line === undefined) continue;\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(line) as Record<string, unknown>;\n } catch {\n continue; // not JSON — skip this line\n }\n if (typeof parsed.capsule === \"string\") {\n obj = parsed;\n break;\n }\n if (!fallback) fallback = parsed;\n }\n\n if (!obj) {\n if (fallback) {\n throw new DigSdkError(\n \"DEPLOY_OUTPUT_UNPARSEABLE\",\n `digstore deploy did not report a capsule (deploy may have failed). Output:\\n${JSON.stringify(fallback)}`,\n { output: fallback },\n );\n }\n throw new DigSdkError(\n \"DEPLOY_OUTPUT_UNPARSEABLE\",\n `could not parse digstore deploy output as JSON:\\n${stdout.slice(0, 500)}`,\n { stdout: stdout.slice(0, 500) },\n );\n }\n\n const capsule = obj.capsule as string;\n const m = CAPSULE_RE.exec(capsule);\n if (!m || m[1] === undefined || m[2] === undefined) {\n throw new DigSdkError(\n \"INVALID_ARGUMENT\",\n `digstore deploy reported a malformed capsule \"${capsule}\" (expected storeId:root)`,\n { value: capsule, expected: \"storeId:root\" },\n );\n }\n const storeId = m[1].toLowerCase();\n const root = (typeof obj.root === \"string\" ? obj.root : m[2]).toLowerCase();\n\n // The user-facing content-open address. Prefer the value digstore itself printed\n // (`content_address`, the single source of truth — digstore deploy.rs::branding::content_url) so\n // the SDK stays byte-identical to the CLI; otherwise derive it the same way digstore does:\n // chia://<storeId>:<rootHash>/ (trailing slash, no resource). This is what a user opens in the\n // DIG Browser/extension — NOT the §21 remote dig:// locator.\n const chiaUrl =\n typeof obj.content_address === \"string\"\n ? obj.content_address\n : `chia://${storeId}:${root}/`;\n\n return {\n capsule,\n storeId,\n root,\n chiaUrl,\n // Deprecated alias: same chia:// content-open value (back-compat for consumers reading digUrl).\n digUrl: chiaUrl,\n // Mirrors digstore deploy.rs::hub_url — the public DIGHUb view of an owned store.\n hubUrl: `https://hub.dig.net/stores/${storeId}`,\n pushed: typeof obj.pushed === \"boolean\" ? obj.pushed : undefined,\n };\n}\n","// The shared, Node-only deploy runner both framework adapters call on their `publish` step.\n//\n// It composes the pure pieces (load dig.toml → resolve config → build argv + env), spawns the\n// installed `digstore` binary with `deploy --json`, and parses the result into a friendly\n// DeployResult ({ capsule, chiaUrl, hubUrl }). It is intentionally thin: ALL deploy logic lives in\n// `digstore deploy` (the canonical deployer — advances the on-chain root, stages, pushes the\n// capsule); this only marshals config in and the result out.\n//\n// Node-only: it uses node:child_process / node:fs. The framework entrypoints import it lazily on\n// the publish path so importing the plugin in a browser/config context never pulls Node APIs.\n\nimport { resolveDeployConfig, type AdapterOptions } from \"./config.js\";\nimport { parseDigToml, type DigTomlConfig } from \"./dig-toml.js\";\nimport {\n buildDeployArgs,\n buildDeployEnv,\n parseDeployResult,\n type DeployArgsOptions,\n type DeployResult,\n} from \"./deploy.js\";\nimport { DigSdkError } from \"../errors.js\";\n\n/** Options for {@link runDeploy}. */\nexport interface RunDeployOptions extends AdapterOptions, DeployArgsOptions {\n /** Project root that holds `dig.toml` and the build output. Defaults to `process.cwd()`. */\n cwd?: string;\n /** The `digstore` executable. Defaults to `\"digstore\"` (must be on PATH). */\n digstoreBin?: string;\n /** Sink for human-readable progress. Defaults to `console.log`. */\n logger?: (line: string) => void;\n}\n\n/** Read `dig.toml` from `cwd` (returns {} when absent). */\nasync function readDigToml(cwd: string): Promise<DigTomlConfig> {\n const { readFile } = await import(\"node:fs/promises\");\n const path = await import(\"node:path\");\n try {\n const text = await readFile(path.join(cwd, \"dig.toml\"), \"utf8\");\n return parseDigToml(text);\n } catch {\n return {}; // no dig.toml — rely on options + env\n }\n}\n\n/**\n * Resolve config, run `digstore deploy --json`, and parse the capsule. Spawns `digstore` with the\n * SECRETS injected through the child env (never the argv). Rejects with digstore's stderr on\n * non-zero exit. Returns the parsed {@link DeployResult}.\n */\nexport async function runDeploy(options: RunDeployOptions = {}): Promise<DeployResult> {\n const cwd = options.cwd ?? process.cwd();\n const bin = options.digstoreBin ?? \"digstore\";\n const log = options.logger ?? ((l: string) => console.log(l));\n\n const digToml = await readDigToml(cwd);\n const cfg = resolveDeployConfig({\n options: {\n storeId: options.storeId,\n outputDir: options.outputDir,\n buildCommand: options.buildCommand,\n message: options.message,\n network: options.network,\n remote: options.remote,\n waitTimeout: options.waitTimeout,\n },\n digToml,\n env: process.env,\n });\n\n const argv = buildDeployArgs(cfg, { skipBuild: options.skipBuild });\n const childEnv = { ...process.env, ...buildDeployEnv(cfg) };\n\n log(`▶ digstore ${argv.filter((a) => a !== cfg.deployKey && a !== cfg.salt).join(\" \")}`);\n\n const { spawn } = await import(\"node:child_process\");\n const stdout = await new Promise<string>((resolve, reject) => {\n const child = spawn(bin, argv, {\n cwd,\n env: childEnv,\n // digstore reads no stdin here; capture stdout (the JSON) and stream stderr through.\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n shell: false,\n });\n let out = \"\";\n let err = \"\";\n child.stdout.on(\"data\", (d: Buffer) => {\n out += d.toString();\n });\n child.stderr.on(\"data\", (d: Buffer) => {\n err += d.toString();\n });\n child.on(\"error\", (e: Error) => {\n reject(\n new DigSdkError(\n \"DIGSTORE_NOT_FOUND\",\n `could not run \"${bin}\" — is digstore installed and on PATH? (${e.message})`,\n { bin },\n { cause: e },\n ),\n );\n });\n child.on(\"close\", (code: number | null) => {\n if (code === 0) resolve(out);\n else\n reject(\n new DigSdkError(\"DEPLOY_FAILED\", `digstore deploy failed (exit ${code}).\\n${err || out}`, {\n exitCode: code,\n stderr: err.slice(0, 2000),\n }),\n );\n });\n });\n\n const result = parseDeployResult(stdout);\n log(`✓ deployed capsule ${result.capsule}`);\n // chia:// is the user-facing content-open address (what they open in the DIG Browser/extension).\n log(` open ${result.chiaUrl}`);\n log(` view ${result.hubUrl}`);\n return result;\n}\n","// `@dignetwork/dig-sdk/next` — a Next.js static-export adapter for shipping to DIG.\n//\n// Next has no Vite-style `transformIndexHtml` hook, so the two jobs are surfaced as helpers a Next\n// project wires in:\n// 1. DEV: `digNextDevShimTag()` returns a ready `<script …>` string to drop into the app's\n// `<head>` (e.g. in `app/layout.tsx` or `_document`) so `next dev` has the SDK's `window.chia`\n// dev shim — the SAME injected-provider contract production uses. It guards on a real wallet\n// and is eval-free. Gate it on `process.env.NODE_ENV !== \"production\"` in your layout so it\n// ships only in dev.\n// 2. PUBLISH: `digDeploy()` ships the static-export output (`out/` by default — what\n// `next build` writes with `output: \"export\"`) to a DIG capsule via `digstore deploy --json`,\n// printing the chia:// content-open URL + the DIGHUb view URL. Call it from a `publish` script\n// after the build.\n//\n// Next is an OPTIONAL peer: this module imports nothing from \"next\". The publish runner is the\n// shared Node-only `runDeploy`.\n\nimport { devShimScript, type DevShimOptions } from \"./adapters/dev-shim.js\";\nimport type { AdapterOptions } from \"./adapters/config.js\";\nimport type { DeployResult } from \"./adapters/deploy.js\";\nimport { runDeploy } from \"./adapters/run.js\";\n\n/** Next static-export writes here by default (`output: \"export\"`). */\nconst NEXT_EXPORT_DIR = \"out\";\n\n/**\n * The raw dev-shim script BODY (no `<script>` tags) — for callers that inject it themselves (e.g.\n * via Next's `<Script id=… dangerouslySetInnerHTML>` or a custom `_document`).\n */\nexport function digNextDevShimScript(options: DevShimOptions = {}): string {\n return devShimScript(options);\n}\n\n/**\n * A ready-to-inline `<script>…</script>` tag carrying the dev shim. Drop into the app `<head>`\n * (guard on dev): e.g. in `app/layout.tsx`\n * `{process.env.NODE_ENV !== \"production\" && <head dangerouslySetInnerHTML={{ __html: digNextDevShimTag() }} />}`.\n * Prefer `digNextDevShimScript()` with Next's `<Script>` component when you can.\n */\nexport function digNextDevShimTag(options: DevShimOptions = {}): string {\n return `<script>${devShimScript(options)}</script>`;\n}\n\n/**\n * Deploy the Next static export to a DIG capsule. Call from a `publish` script AFTER\n * `next build` (with `output: \"export\"`). Defaults `outputDir` to `out` (Next's export dir); reads\n * `dig.toml` + env (DIGSTORE_*) for the rest. The adapter has already built, so digstore stages the\n * existing `out/` rather than rebuilding.\n */\nexport function digDeploy(options: AdapterOptions = {}): Promise<DeployResult> {\n return runDeploy({ ...options, outputDir: options.outputDir ?? NEXT_EXPORT_DIR, skipBuild: true });\n}\n\nexport default digDeploy;\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/provider/injected.ts","../src/adapters/dev-shim.ts","../src/adapters/config.ts","../src/adapters/dig-toml.ts","../src/adapters/deploy.ts","../src/adapters/run.ts","../src/next.ts"],"names":[],"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,EA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AChGA,IAAM,eAAA,GAAkB,KAAA;AAMjB,SAAS,oBAAA,CAAqB,OAAA,GAA0B,EAAC,EAAW;AACzE,EAAA,OAAO,cAAc,OAAO,CAAA;AAC9B;AAQO,SAAS,iBAAA,CAAkB,OAAA,GAA0B,EAAC,EAAW;AACtE,EAAA,OAAO,CAAA,QAAA,EAAW,aAAA,CAAc,OAAO,CAAC,CAAA,SAAA,CAAA;AAC1C;AAQO,SAAS,SAAA,CAAU,OAAA,GAA0B,EAAC,EAA0B;AAC7E,EAAA,OAAO,SAAA,CAAU,EAAE,GAAG,OAAA,EAAS,SAAA,EAAW,QAAQ,SAAA,IAAa,eAAA,EAAiB,SAAA,EAAW,IAAA,EAAM,CAAA;AACnG;AAEA,IAAO,YAAA,GAAQ","file":"next.cjs","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","// Injected-provider transport — the DIG Browser's in-process wallet (and compatible CHIP-0002\n// extensions), exposed on every page as `window.chia`. When present the SDK PREFERS it over\n// WalletConnect: no QR, no relay, no pairing. The native provider returns the SAME response shapes\n// Sage returns over WalletConnect, so the normalizers in provider/methods.ts are unchanged — only\n// the TRANSPORT differs. Genericized from hub.dig.net/apps/web/lib/injected-wallet.js.\n//\n// Detection: we key on the explicit, unspoofable `isDIG` marker the DIG Browser provider sets, not\n// merely the presence of `window.chia` (a different Chia provider could also define that).\n\nimport type { InjectedChiaProvider, WalletBackend } from \"../types.js\";\nimport { WALLET_METHODS, DEFAULT_CHAIN } from \"../methods.js\";\nimport type { WalletTransport } from \"./transport.js\";\nimport { DigSdkError } from \"../errors.js\";\n\n/** The injected provider on the current global, or undefined when not running in a DIG Browser. */\nexport function getInjectedProvider(): InjectedChiaProvider | undefined {\n const g = globalThis as { chia?: InjectedChiaProvider };\n return typeof g !== \"undefined\" ? g.chia : undefined;\n}\n\n/**\n * True iff an injected DIG wallet is available. Detects on the unspoofable `isDIG` marker. Pass\n * `{ anyChia: true }` to accept any `window.chia` that implements `request` (e.g. a non-DIG\n * CHIP-0002 extension).\n */\nexport function isInjectedAvailable(opts: { anyChia?: boolean } = {}): boolean {\n const p = getInjectedProvider();\n if (!p) return false;\n if (opts.anyChia) return typeof p.request === \"function\";\n return !!p.isDIG;\n}\n\n/** Sentinel topic for the injected backend (it has no per-session relay topic). */\nexport const INJECTED_TOPIC = \"injected\";\n\n/** A WalletTransport backed by the injected window.chia provider. */\nexport class InjectedTransport implements WalletTransport {\n readonly backend: WalletBackend = \"injected\";\n readonly topic = INJECTED_TOPIC;\n readonly chain: string;\n private readonly provider: InjectedChiaProvider;\n\n constructor(provider: InjectedChiaProvider, chain: string = DEFAULT_CHAIN) {\n this.provider = provider;\n this.chain = chain;\n }\n\n /** Connect: ask the native wallet to approve this origin. Blocks until approved/rejected. */\n async connect(eager = false): Promise<void> {\n if (typeof this.provider.connect === \"function\") {\n await this.provider.connect(eager);\n }\n // A provider without connect() (older build) is tolerated — request() will gate per-method.\n }\n\n // The native wallet implements the full canonical set (it returns Sage-shaped responses), so\n // support is a static allowlist — no per-session negotiation as with WalletConnect.\n supports(method: string): boolean {\n return (WALLET_METHODS as readonly string[]).includes(method);\n }\n\n async request(method: string, params: unknown): Promise<unknown> {\n if (!this.supports(method)) {\n throw new DigSdkError(\n \"METHOD_NOT_SUPPORTED\",\n `The DIG Browser wallet does not support \"${method}\".`,\n { method },\n );\n }\n return this.provider.request({ method, params });\n }\n\n async disconnect(): Promise<void> {\n // The injected wallet has no per-session teardown; per-origin consent is managed in the wallet.\n }\n}\n","// The `window.chia` DEV shim the adapters inject during `dev`.\n//\n// In production a dapp's wallet is the REAL injected provider — the DIG Browser's in-process wallet\n// (or a CHIP-0002 extension) — which the SDK's ChiaProvider detects on `window.chia` via the\n// `isDIG` marker (see src/provider/injected.ts). During local `vite dev` / `next dev` there is no\n// such wallet, so calling `ChiaProvider.connect({ mode: \"injected\" })` would fail and the developer\n// couldn't exercise the wallet path at all.\n//\n// This shim installs a MINIMAL, clearly-labelled stub that satisfies the SAME injected-provider\n// contract the SDK detects (`isDIG`, `request({method,params})`, `connect()`), so the wallet code\n// path runs end-to-end in dev. It is a STUB, not a wallet: it returns a configurable mock address\n// and otherwise throws on methods that would need real signing, so a developer is never misled into\n// thinking a signature is real. It is generated as a self-contained, eval-free `<script>` body\n// (CSP-safe) that GUARDS on an existing `window.chia`, so a real wallet always wins.\n//\n// The shim's method names + response envelope mirror src/provider/injected.ts and\n// src/provider/methods.ts (the native provider returns `{ data }`), so the SAME normalizers run in\n// dev as in production — only the values are mocked.\n\nimport { INJECTED_TOPIC } from \"../provider/injected.js\";\n\n/** A literal substring stamped into the shim so it is unmistakably a dev stub (asserted in tests). */\nexport const DEV_SHIM_MARKER = \"dig-sdk:dev-wallet-shim\";\n\n/** Options for the generated dev shim. */\nexport interface DevShimOptions {\n /** Mock receive address the shim returns from `getAddress`. A clearly-fake default is used. */\n address?: string;\n}\n\n/** A clearly-fake default dev address (so it is obvious in the UI this is not a real wallet). */\nconst DEFAULT_DEV_ADDRESS = \"xch1dev0000000000000000000000000000000000000000000000000000devshim\";\n\n/** JSON-encode a string for safe inlining into a script literal. */\nfunction lit(s: string): string {\n return JSON.stringify(s);\n}\n\n/**\n * Generate the dev-shim `<script>` body (no surrounding `<script>` tags). Inline it into the dev\n * server's served HTML. It is an IIFE that installs `window.chia` ONLY if one is not already\n * present, so the DIG Browser / a real extension always takes precedence. Eval-free and\n * dependency-free — safe under a strict CSP.\n */\nexport function devShimScript(options: DevShimOptions = {}): string {\n const address = options.address ?? DEFAULT_DEV_ADDRESS;\n // The shim mirrors the injected-provider contract the SDK detects. `request` resolves a small set\n // of read methods with mock data and rejects signing methods (a dev stub must not fake a\n // signature). Method names are the bare CHIP-0002 names the SDK normalizes.\n return [\n `/* ${DEV_SHIM_MARKER} — DEV ONLY. A stub wallet for local development; NOT a real wallet. */`,\n `(function () {`,\n ` \"use strict\";`,\n ` if (typeof window === \"undefined\") return;`,\n ` // A real injected wallet (DIG Browser / extension) always wins — never clobber it.`,\n ` if (window.chia) return;`,\n ` var DEV_ADDRESS = ${lit(address)};`,\n ` var TOPIC = ${lit(INJECTED_TOPIC)};`,\n ` function ok(data) { return Promise.resolve({ data: data }); }`,\n ` function nope(method) {`,\n ` return Promise.reject(new Error(`,\n ` \"[\" + ${lit(DEV_SHIM_MARKER)} + \"] '\" + method + \"' needs a real wallet; the dev shim does not sign. \" +`,\n ` \"Open in the DIG Browser or connect a wallet to sign for real.\"));`,\n ` }`,\n ` window.chia = {`,\n ` isDIG: true, // detected by the SDK's injected-provider check`,\n ` isDevShim: true, // so the app can tell it is the dev stub`,\n ` topic: TOPIC,`,\n ` connect: function () { return Promise.resolve(true); },`,\n ` request: function (args) {`,\n ` var method = args && args.method ? String(args.method) : \"\";`,\n ` switch (method) {`,\n ` case \"chip0002_connect\": return ok(true);`,\n ` case \"chip0002_getPublicKeys\": return ok([]);`,\n ` case \"getAddress\":`,\n ` case \"chia_getAddress\": return ok(DEV_ADDRESS);`,\n ` default:`,\n ` // Signing / spend methods must not be faked.`,\n ` return nope(method);`,\n ` }`,\n ` },`,\n ` on: function () {},`,\n ` off: function () {},`,\n ` };`,\n ` if (window.console && window.console.info) {`,\n ` window.console.info(\"[\" + ${lit(DEV_SHIM_MARKER)} + \"] installed a DEV window.chia (mock address \" + DEV_ADDRESS + \").\");`,\n ` }`,\n `})();`,\n ].join(\"\\n\");\n}\n","// Deploy-config resolution for the framework adapters.\n//\n// The final config a deploy runs with is composed from three layers, highest precedence first:\n// 1. plugin options — what the developer wrote in vite.config / the Next adapter call\n// 2. environment vars — what CI injects (DIGSTORE_*), incl. the SECRETS (deploy key, salt)\n// 3. dig.toml — the project's checked-in defaults\n// 4. built-in defaults — outputDir=\"dist\", network=\"mainnet\" (mirrors deploy.rs::resolve_config)\n//\n// This mirrors `digstore deploy`'s own resolution order (flag/env > dig.toml > default) so the\n// adapters never disagree with the CLI about what a project deploys. SECRETS are resolved ONLY from\n// env — never from options or dig.toml — so they can't end up checked into a repo or a config file.\n\nimport type { DigTomlConfig } from \"./dig-toml.js\";\n\n/** Per-call options a developer passes to the Vite plugin / Next adapter. */\nexport interface AdapterOptions {\n /** On-chain store id (64-hex) to advance. Usually set in dig.toml instead. */\n storeId?: string;\n /** Built-output directory to publish. Defaults to the framework's output (or \"dist\"). */\n outputDir?: string;\n /** Shell build command for `digstore` to run. Omit when the adapter builds itself. */\n buildCommand?: string;\n /** Commit message for the new capsule. */\n message?: string;\n /** Chain network. Defaults to \"mainnet\". */\n network?: string;\n /** The `origin` remote to publish to (e.g. `dig://<storeId>`). */\n remote?: string;\n /** Seconds to wait for on-chain confirmation. */\n waitTimeout?: number;\n}\n\n/** The fully resolved config a deploy runs with. Secrets are present only if env supplied them. */\nexport interface ResolvedDeployConfig {\n storeId?: string;\n outputDir: string;\n buildCommand?: string;\n message?: string;\n network: string;\n remote?: string;\n waitTimeout?: number;\n /** Publisher deploy key (64-hex). From env only. */\n deployKey?: string;\n /** Private-store secret salt (64-hex). From env only. */\n salt?: string;\n}\n\n/** Inputs to resolution — kept explicit so it is a pure function (no process.env read inside). */\nexport interface ResolveInput {\n options: AdapterOptions;\n digToml: DigTomlConfig;\n env: Record<string, string | undefined>;\n}\n\n/** A non-empty, trimmed env value, or undefined. Empty/whitespace env vars count as unset. */\nfunction envVal(env: Record<string, string | undefined>, key: string): string | undefined {\n const v = env[key];\n if (v == null) return undefined;\n const t = v.trim();\n return t === \"\" ? undefined : t;\n}\n\n/** First defined of the candidates (treating \"\" the caller already filtered as undefined). */\nfunction pick<T>(...candidates: (T | undefined)[]): T | undefined {\n for (const c of candidates) if (c !== undefined) return c;\n return undefined;\n}\n\n/**\n * Resolve the final deploy config. Precedence per field: options > env (DIGSTORE_*) > dig.toml >\n * default. Secrets (deployKey, salt) are taken from env ONLY.\n */\nexport function resolveDeployConfig(input: ResolveInput): ResolvedDeployConfig {\n const { options, digToml, env } = input;\n\n const storeId = pick(\n options.storeId,\n envVal(env, \"DIGSTORE_STORE_ID\"),\n digToml.storeId,\n );\n const outputDir =\n pick(options.outputDir, envVal(env, \"DIGSTORE_OUTPUT_DIR\"), digToml.outputDir) ?? \"dist\";\n const buildCommand = pick(\n options.buildCommand,\n envVal(env, \"DIGSTORE_BUILD_COMMAND\"),\n digToml.buildCommand,\n );\n const message = pick(options.message, envVal(env, \"DIGSTORE_MESSAGE\"), digToml.message);\n const network =\n pick(options.network, envVal(env, \"DIGSTORE_NETWORK\"), digToml.network) ?? \"mainnet\";\n const remote = pick(options.remote, envVal(env, \"DIGSTORE_REMOTE\"), digToml.remote);\n\n const waitFromEnv = envVal(env, \"DIGSTORE_WAIT_TIMEOUT\");\n const waitTimeout = pick(\n options.waitTimeout,\n waitFromEnv != null ? Number.parseInt(waitFromEnv, 10) : undefined,\n digToml.waitTimeout,\n );\n\n return {\n storeId,\n outputDir,\n buildCommand,\n message,\n network,\n remote,\n waitTimeout: Number.isFinite(waitTimeout) ? waitTimeout : undefined,\n // SECRETS — env only.\n deployKey: envVal(env, \"DIGSTORE_DEPLOY_KEY\"),\n salt: envVal(env, \"DIGSTORE_STORE_SALT\"),\n };\n}\n","// Minimal `dig.toml` reader for the framework adapters.\n//\n// `digstore deploy` reads its config from a project's `dig.toml` (digstore-cli/src/dig_toml.rs).\n// The adapters need the SAME few top-level keys so a project's `dig.toml` is the single source of\n// truth across the CLI and the plugins. Rather than pull in a TOML parser dependency for ~7 flat\n// `key = \"value\"` lines, we parse just those keys ourselves. We accept BOTH the canonical\n// kebab-case key and the snake_case alias, exactly like digstore's `#[serde(rename/alias)]`.\n//\n// Anything beyond these keys (tables, arrays, nested values) is intentionally ignored — the\n// adapters only forward the deploy-relevant scalars to `digstore deploy`, which re-reads the full\n// file authoritatively.\n\n/** The deploy-relevant subset of `dig.toml`, in the adapters' camelCase shape. */\nexport interface DigTomlConfig {\n storeId?: string;\n outputDir?: string;\n buildCommand?: string;\n message?: string;\n network?: string;\n remote?: string;\n waitTimeout?: number;\n}\n\n// Map each canonical/alias TOML key onto the camelCase field. kebab-case is canonical (it is what\n// `digstore new` writes); snake_case is the tolerated alias. When both appear, the canonical\n// kebab-case key wins (it is applied last).\nconst KEY_MAP: Record<string, keyof DigTomlConfig> = {\n store_id: \"storeId\",\n \"store-id\": \"storeId\",\n output_dir: \"outputDir\",\n \"output-dir\": \"outputDir\",\n build_command: \"buildCommand\",\n \"build-command\": \"buildCommand\",\n message: \"message\",\n network: \"network\",\n remote: \"remote\",\n wait_timeout: \"waitTimeout\",\n \"wait-timeout\": \"waitTimeout\",\n};\n\n// Apply snake_case first then kebab-case so the canonical kebab form overrides the alias.\nconst APPLY_ORDER = Object.keys(KEY_MAP).sort((a) =>\n a.includes(\"-\") ? 1 : -1,\n);\n\n/** Strip a `# comment` that is not inside a quoted value. */\nfunction stripComment(line: string): string {\n let inSingle = false;\n let inDouble = false;\n for (let i = 0; i < line.length; i++) {\n const ch = line[i];\n if (ch === \"'\" && !inDouble) inSingle = !inSingle;\n else if (ch === '\"' && !inSingle) inDouble = !inDouble;\n else if (ch === \"#\" && !inSingle && !inDouble) return line.slice(0, i);\n }\n return line;\n}\n\n/** Unquote a TOML scalar: `\"x\"` / `'x'` → `x`; a bare token is returned trimmed. */\nfunction unquote(raw: string): string {\n const v = raw.trim();\n if (\n (v.startsWith('\"') && v.endsWith('\"') && v.length >= 2) ||\n (v.startsWith(\"'\") && v.endsWith(\"'\") && v.length >= 2)\n ) {\n return v.slice(1, -1);\n }\n return v;\n}\n\n/**\n * Parse the deploy-relevant keys out of a `dig.toml` string. Unknown keys, tables, and nested\n * structures are ignored. Returns only the keys actually present (so it composes cleanly under the\n * precedence rules in resolveDeployConfig).\n */\nexport function parseDigToml(text: string): DigTomlConfig {\n // Collect raw (canonical-or-alias) string values keyed by the TOML key as written.\n const raw: Record<string, string> = {};\n for (const lineRaw of text.split(/\\r?\\n/)) {\n const line = stripComment(lineRaw).trim();\n if (!line || line.startsWith(\"[\")) continue; // skip blanks + table headers\n const eq = line.indexOf(\"=\");\n if (eq <= 0) continue;\n const key = line.slice(0, eq).trim();\n if (!(key in KEY_MAP)) continue;\n raw[key] = unquote(line.slice(eq + 1));\n }\n\n const out: DigTomlConfig = {};\n for (const key of APPLY_ORDER) {\n const value = raw[key];\n const field = KEY_MAP[key];\n if (value === undefined || field === undefined) continue;\n if (field === \"waitTimeout\") {\n const n = Number.parseInt(value, 10);\n if (Number.isFinite(n)) out.waitTimeout = n;\n } else {\n out[field] = value;\n }\n }\n return out;\n}\n","// The pure glue around `digstore deploy --json`: build the child argv + env, and parse the result.\n//\n// The adapters SHELL OUT to the installed `digstore` binary (the canonical deployer — it advances\n// the on-chain root, stages the build dir, and pushes the new capsule to DIGHUb). They never\n// re-implement deploy. These helpers are the deterministic, side-effect-free pieces:\n//\n// • buildDeployArgs — resolved config → argv (always `deploy --json`, only set flags).\n// • buildDeployEnv — resolved config → the env overlay carrying the SECRETS to the child, so the\n// deploy key / salt are NEVER on the argv (process-table leak), matching\n// digstore-cli's own guidance (deploy.rs).\n// • parseDeployResult— `digstore deploy --json` stdout → { capsule, storeId, root, chiaUrl,\n// digUrl, hubUrl, pushed }, deriving the URLs exactly as digstore does\n// (capsule = storeId:root; hub view = https://hub.dig.net/stores/<id>;\n// chiaUrl = the user-facing content-open address chia://<store>:<root>/,\n// matching digstore's printed `content_address`).\n\nimport type { ResolvedDeployConfig } from \"./config.js\";\nimport { DigSdkError } from \"../errors.js\";\n\n/** Knobs for argv construction. */\nexport interface DeployArgsOptions {\n /**\n * The adapter already ran the framework build, so don't hand `--build-command` to digstore (it\n * would rebuild). The output dir is staged as-is.\n */\n skipBuild?: boolean;\n}\n\n/**\n * Build the argv for `digstore <argv>` from a resolved config. Always `deploy --json`. Only flags\n * whose values are set are emitted. SECRETS (deployKey, salt) are intentionally excluded — they go\n * through the env (buildDeployEnv) so they never appear in the process table.\n */\nexport function buildDeployArgs(\n cfg: ResolvedDeployConfig,\n opts: DeployArgsOptions = {},\n): string[] {\n const argv: string[] = [\"deploy\", \"--json\"];\n if (cfg.storeId) argv.push(\"--store-id\", cfg.storeId);\n if (cfg.outputDir) argv.push(\"--output-dir\", cfg.outputDir);\n if (!opts.skipBuild && cfg.buildCommand) argv.push(\"--build-command\", cfg.buildCommand);\n if (cfg.message) argv.push(\"--message\", cfg.message);\n if (cfg.network) argv.push(\"--network\", cfg.network);\n if (cfg.remote) argv.push(\"--remote\", cfg.remote);\n if (cfg.waitTimeout != null) argv.push(\"--wait-timeout\", String(cfg.waitTimeout));\n return argv;\n}\n\n/**\n * The env overlay to merge onto the child process env: the SECRETS, passed out-of-band so they are\n * never visible on the command line. Returns only the keys that have a value.\n */\nexport function buildDeployEnv(cfg: ResolvedDeployConfig): Record<string, string> {\n const env: Record<string, string> = {};\n if (cfg.deployKey) env.DIGSTORE_DEPLOY_KEY = cfg.deployKey;\n if (cfg.salt) env.DIGSTORE_STORE_SALT = cfg.salt;\n return env;\n}\n\n/** The friendly, parsed outcome of a deploy. */\nexport interface DeployResult {\n /** `storeId:rootHash` — the capsule identity (the ecosystem-vocabulary id the user shares). */\n capsule: string;\n /** Store identity (64-hex). */\n storeId: string;\n /** The new on-chain root (64-hex). */\n root: string;\n /**\n * The user-facing content-open address `chia://<storeId>:<rootHash>/` — what a user types/clicks\n * to open this verified capsule in the DIG Browser / extension (the scheme they register). This\n * matches digstore deploy's printed `content_address` exactly. (Distinct from the §21 remote\n * locator `dig://<host>/<store_id>` and the `urn:dig:` namespace, which stay `dig://`.)\n */\n chiaUrl: string;\n /**\n * @deprecated Use {@link chiaUrl}. Kept as a back-compat alias for consumers that read `digUrl`;\n * it now carries the SAME `chia://<storeId>:<rootHash>/` content-open value (NOT a `dig://` URL).\n */\n digUrl: string;\n /** The human \"view it\" URL on DIGHUb (the same one `digstore deploy` prints). */\n hubUrl: string;\n /** Whether the capsule was pushed to DIGHUb (when the JSON reported it). */\n pushed?: boolean;\n}\n\nconst CAPSULE_RE = /^([0-9a-f]{64}):([0-9a-f]{64})$/i;\n\n/**\n * Parse `digstore deploy --json` stdout into a DeployResult. digstore emits a single JSON object\n * (with at least `capsule` and `root`); we also tolerate extra JSON log lines by scanning lines\n * bottom-up for the first object that carries a `capsule`. Throws a clear error if none is found or\n * the output isn't JSON at all.\n */\nexport function parseDeployResult(stdout: string): DeployResult {\n const lines = stdout\n .split(/\\r?\\n/)\n .map((l) => l.trim())\n .filter((l) => l.startsWith(\"{\") && l.endsWith(\"}\"));\n\n if (lines.length === 0) {\n throw new DigSdkError(\n \"DEPLOY_OUTPUT_UNPARSEABLE\",\n `could not parse digstore deploy output (no JSON object found). Output was:\\n${stdout.slice(0, 500)}`,\n { stdout: stdout.slice(0, 500) },\n );\n }\n\n // Prefer the LAST JSON object that has a capsule (deploy emits one final result object). Keep the\n // first parseable object as a fallback so the error message can show what digstore DID return.\n let obj: Record<string, unknown> | undefined;\n let fallback: Record<string, unknown> | undefined;\n for (let i = lines.length - 1; i >= 0; i--) {\n const line = lines[i];\n if (line === undefined) continue;\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(line) as Record<string, unknown>;\n } catch {\n continue; // not JSON — skip this line\n }\n if (typeof parsed.capsule === \"string\") {\n obj = parsed;\n break;\n }\n if (!fallback) fallback = parsed;\n }\n\n if (!obj) {\n if (fallback) {\n throw new DigSdkError(\n \"DEPLOY_OUTPUT_UNPARSEABLE\",\n `digstore deploy did not report a capsule (deploy may have failed). Output:\\n${JSON.stringify(fallback)}`,\n { output: fallback },\n );\n }\n throw new DigSdkError(\n \"DEPLOY_OUTPUT_UNPARSEABLE\",\n `could not parse digstore deploy output as JSON:\\n${stdout.slice(0, 500)}`,\n { stdout: stdout.slice(0, 500) },\n );\n }\n\n const capsule = obj.capsule as string;\n const m = CAPSULE_RE.exec(capsule);\n if (!m || m[1] === undefined || m[2] === undefined) {\n throw new DigSdkError(\n \"INVALID_ARGUMENT\",\n `digstore deploy reported a malformed capsule \"${capsule}\" (expected storeId:root)`,\n { value: capsule, expected: \"storeId:root\" },\n );\n }\n const storeId = m[1].toLowerCase();\n const root = (typeof obj.root === \"string\" ? obj.root : m[2]).toLowerCase();\n\n // The user-facing content-open address. Prefer the value digstore itself printed\n // (`content_address`, the single source of truth — digstore deploy.rs::branding::content_url) so\n // the SDK stays byte-identical to the CLI; otherwise derive it the same way digstore does:\n // chia://<storeId>:<rootHash>/ (trailing slash, no resource). This is what a user opens in the\n // DIG Browser/extension — NOT the §21 remote dig:// locator.\n const chiaUrl =\n typeof obj.content_address === \"string\"\n ? obj.content_address\n : `chia://${storeId}:${root}/`;\n\n return {\n capsule,\n storeId,\n root,\n chiaUrl,\n // Deprecated alias: same chia:// content-open value (back-compat for consumers reading digUrl).\n digUrl: chiaUrl,\n // Mirrors digstore deploy.rs::hub_url — the public DIGHUb view of an owned store.\n hubUrl: `https://hub.dig.net/stores/${storeId}`,\n pushed: typeof obj.pushed === \"boolean\" ? obj.pushed : undefined,\n };\n}\n","// The shared, Node-only deploy runner both framework adapters call on their `publish` step.\n//\n// It composes the pure pieces (load dig.toml → resolve config → build argv + env), spawns the\n// installed `digstore` binary with `deploy --json`, and parses the result into a friendly\n// DeployResult ({ capsule, chiaUrl, hubUrl }). It is intentionally thin: ALL deploy logic lives in\n// `digstore deploy` (the canonical deployer — advances the on-chain root, stages, pushes the\n// capsule); this only marshals config in and the result out.\n//\n// Node-only: it uses node:child_process / node:fs. The framework entrypoints import it lazily on\n// the publish path so importing the plugin in a browser/config context never pulls Node APIs.\n\nimport { resolveDeployConfig, type AdapterOptions } from \"./config.js\";\nimport { parseDigToml, type DigTomlConfig } from \"./dig-toml.js\";\nimport {\n buildDeployArgs,\n buildDeployEnv,\n parseDeployResult,\n type DeployArgsOptions,\n type DeployResult,\n} from \"./deploy.js\";\nimport { DigSdkError } from \"../errors.js\";\n\n/** Options for {@link runDeploy}. */\nexport interface RunDeployOptions extends AdapterOptions, DeployArgsOptions {\n /** Project root that holds `dig.toml` and the build output. Defaults to `process.cwd()`. */\n cwd?: string;\n /** The `digstore` executable. Defaults to `\"digstore\"` (must be on PATH). */\n digstoreBin?: string;\n /** Sink for human-readable progress. Defaults to `console.log`. */\n logger?: (line: string) => void;\n}\n\n/** Read `dig.toml` from `cwd` (returns {} when absent). */\nasync function readDigToml(cwd: string): Promise<DigTomlConfig> {\n const { readFile } = await import(\"node:fs/promises\");\n const path = await import(\"node:path\");\n try {\n const text = await readFile(path.join(cwd, \"dig.toml\"), \"utf8\");\n return parseDigToml(text);\n } catch {\n return {}; // no dig.toml — rely on options + env\n }\n}\n\n/**\n * Resolve config, run `digstore deploy --json`, and parse the capsule. Spawns `digstore` with the\n * SECRETS injected through the child env (never the argv). Rejects with digstore's stderr on\n * non-zero exit. Returns the parsed {@link DeployResult}.\n */\nexport async function runDeploy(options: RunDeployOptions = {}): Promise<DeployResult> {\n const cwd = options.cwd ?? process.cwd();\n const bin = options.digstoreBin ?? \"digstore\";\n const log = options.logger ?? ((l: string) => console.log(l));\n\n const digToml = await readDigToml(cwd);\n const cfg = resolveDeployConfig({\n options: {\n storeId: options.storeId,\n outputDir: options.outputDir,\n buildCommand: options.buildCommand,\n message: options.message,\n network: options.network,\n remote: options.remote,\n waitTimeout: options.waitTimeout,\n },\n digToml,\n env: process.env,\n });\n\n const argv = buildDeployArgs(cfg, { skipBuild: options.skipBuild });\n const childEnv = { ...process.env, ...buildDeployEnv(cfg) };\n\n log(`▶ digstore ${argv.filter((a) => a !== cfg.deployKey && a !== cfg.salt).join(\" \")}`);\n\n const { spawn } = await import(\"node:child_process\");\n const stdout = await new Promise<string>((resolve, reject) => {\n const child = spawn(bin, argv, {\n cwd,\n env: childEnv,\n // digstore reads no stdin here; capture stdout (the JSON) and stream stderr through.\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n shell: false,\n });\n let out = \"\";\n let err = \"\";\n child.stdout.on(\"data\", (d: Buffer) => {\n out += d.toString();\n });\n child.stderr.on(\"data\", (d: Buffer) => {\n err += d.toString();\n });\n child.on(\"error\", (e: Error) => {\n reject(\n new DigSdkError(\n \"DIGSTORE_NOT_FOUND\",\n `could not run \"${bin}\" — is digstore installed and on PATH? (${e.message})`,\n { bin },\n { cause: e },\n ),\n );\n });\n child.on(\"close\", (code: number | null) => {\n if (code === 0) resolve(out);\n else\n reject(\n new DigSdkError(\"DEPLOY_FAILED\", `digstore deploy failed (exit ${code}).\\n${err || out}`, {\n exitCode: code,\n stderr: err.slice(0, 2000),\n }),\n );\n });\n });\n\n const result = parseDeployResult(stdout);\n log(`✓ deployed capsule ${result.capsule}`);\n // chia:// is the user-facing content-open address (what they open in the DIG Browser/extension).\n log(` open ${result.chiaUrl}`);\n log(` view ${result.hubUrl}`);\n return result;\n}\n","// `@dignetwork/dig-sdk/next` — a Next.js static-export adapter for shipping to DIG.\n//\n// Next has no Vite-style `transformIndexHtml` hook, so the two jobs are surfaced as helpers a Next\n// project wires in:\n// 1. DEV: `digNextDevShimTag()` returns a ready `<script …>` string to drop into the app's\n// `<head>` (e.g. in `app/layout.tsx` or `_document`) so `next dev` has the SDK's `window.chia`\n// dev shim — the SAME injected-provider contract production uses. It guards on a real wallet\n// and is eval-free. Gate it on `process.env.NODE_ENV !== \"production\"` in your layout so it\n// ships only in dev.\n// 2. PUBLISH: `digDeploy()` ships the static-export output (`out/` by default — what\n// `next build` writes with `output: \"export\"`) to a DIG capsule via `digstore deploy --json`,\n// printing the chia:// content-open URL + the DIGHUb view URL. Call it from a `publish` script\n// after the build.\n//\n// Next is an OPTIONAL peer: this module imports nothing from \"next\". The publish runner is the\n// shared Node-only `runDeploy`.\n\nimport { devShimScript, type DevShimOptions } from \"./adapters/dev-shim.js\";\nimport type { AdapterOptions } from \"./adapters/config.js\";\nimport type { DeployResult } from \"./adapters/deploy.js\";\nimport { runDeploy } from \"./adapters/run.js\";\n\n/** Next static-export writes here by default (`output: \"export\"`). */\nconst NEXT_EXPORT_DIR = \"out\";\n\n/**\n * The raw dev-shim script BODY (no `<script>` tags) — for callers that inject it themselves (e.g.\n * via Next's `<Script id=… dangerouslySetInnerHTML>` or a custom `_document`).\n */\nexport function digNextDevShimScript(options: DevShimOptions = {}): string {\n return devShimScript(options);\n}\n\n/**\n * A ready-to-inline `<script>…</script>` tag carrying the dev shim. Drop into the app `<head>`\n * (guard on dev): e.g. in `app/layout.tsx`\n * `{process.env.NODE_ENV !== \"production\" && <head dangerouslySetInnerHTML={{ __html: digNextDevShimTag() }} />}`.\n * Prefer `digNextDevShimScript()` with Next's `<Script>` component when you can.\n */\nexport function digNextDevShimTag(options: DevShimOptions = {}): string {\n return `<script>${devShimScript(options)}</script>`;\n}\n\n/**\n * Deploy the Next static export to a DIG capsule. Call from a `publish` script AFTER\n * `next build` (with `output: \"export\"`). Defaults `outputDir` to `out` (Next's export dir); reads\n * `dig.toml` + env (DIGSTORE_*) for the rest. The adapter has already built, so digstore stages the\n * existing `out/` rather than rebuilding.\n */\nexport function digDeploy(options: AdapterOptions = {}): Promise<DeployResult> {\n return runDeploy({ ...options, outputDir: options.outputDir ?? NEXT_EXPORT_DIR, skipBuild: true });\n}\n\nexport default digDeploy;\n"]}
|
package/dist/next.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/provider/injected.ts","../src/adapters/dev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M,CAAA;AACnG;AAEA,IAAO,YAAA,GAAQ","file":"next.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 vendored 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","// Injected-provider transport — the DIG Browser's in-process wallet (and compatible CHIP-0002\n// extensions), exposed on every page as `window.chia`. When present the SDK PREFERS it over\n// WalletConnect: no QR, no relay, no pairing. The native provider returns the SAME response shapes\n// Sage returns over WalletConnect, so the normalizers in provider/methods.ts are unchanged — only\n// the TRANSPORT differs. Genericized from hub.dig.net/apps/web/lib/injected-wallet.js.\n//\n// Detection: we key on the explicit, unspoofable `isDIG` marker the DIG Browser provider sets, not\n// merely the presence of `window.chia` (a different Chia provider could also define that).\n\nimport type { InjectedChiaProvider, WalletBackend } from \"../types.js\";\nimport { WALLET_METHODS, DEFAULT_CHAIN } from \"../methods.js\";\nimport type { WalletTransport } from \"./transport.js\";\nimport { DigSdkError } from \"../errors.js\";\n\n/** The injected provider on the current global, or undefined when not running in a DIG Browser. */\nexport function getInjectedProvider(): InjectedChiaProvider | undefined {\n const g = globalThis as { chia?: InjectedChiaProvider };\n return typeof g !== \"undefined\" ? g.chia : undefined;\n}\n\n/**\n * True iff an injected DIG wallet is available. Detects on the unspoofable `isDIG` marker. Pass\n * `{ anyChia: true }` to accept any `window.chia` that implements `request` (e.g. a non-DIG\n * CHIP-0002 extension).\n */\nexport function isInjectedAvailable(opts: { anyChia?: boolean } = {}): boolean {\n const p = getInjectedProvider();\n if (!p) return false;\n if (opts.anyChia) return typeof p.request === \"function\";\n return !!p.isDIG;\n}\n\n/** Sentinel topic for the injected backend (it has no per-session relay topic). */\nexport const INJECTED_TOPIC = \"injected\";\n\n/** A WalletTransport backed by the injected window.chia provider. */\nexport class InjectedTransport implements WalletTransport {\n readonly backend: WalletBackend = \"injected\";\n readonly topic = INJECTED_TOPIC;\n readonly chain: string;\n private readonly provider: InjectedChiaProvider;\n\n constructor(provider: InjectedChiaProvider, chain: string = DEFAULT_CHAIN) {\n this.provider = provider;\n this.chain = chain;\n }\n\n /** Connect: ask the native wallet to approve this origin. Blocks until approved/rejected. */\n async connect(eager = false): Promise<void> {\n if (typeof this.provider.connect === \"function\") {\n await this.provider.connect(eager);\n }\n // A provider without connect() (older build) is tolerated — request() will gate per-method.\n }\n\n // The native wallet implements the full canonical set (it returns Sage-shaped responses), so\n // support is a static allowlist — no per-session negotiation as with WalletConnect.\n supports(method: string): boolean {\n return (WALLET_METHODS as readonly string[]).includes(method);\n }\n\n async request(method: string, params: unknown): Promise<unknown> {\n if (!this.supports(method)) {\n throw new DigSdkError(\n \"METHOD_NOT_SUPPORTED\",\n `The DIG Browser wallet does not support \"${method}\".`,\n { method },\n );\n }\n return this.provider.request({ method, params });\n }\n\n async disconnect(): Promise<void> {\n // The injected wallet has no per-session teardown; per-origin consent is managed in the wallet.\n }\n}\n","// The `window.chia` DEV shim the adapters inject during `dev`.\n//\n// In production a dapp's wallet is the REAL injected provider — the DIG Browser's in-process wallet\n// (or a CHIP-0002 extension) — which the SDK's ChiaProvider detects on `window.chia` via the\n// `isDIG` marker (see src/provider/injected.ts). During local `vite dev` / `next dev` there is no\n// such wallet, so calling `ChiaProvider.connect({ mode: \"injected\" })` would fail and the developer\n// couldn't exercise the wallet path at all.\n//\n// This shim installs a MINIMAL, clearly-labelled stub that satisfies the SAME injected-provider\n// contract the SDK detects (`isDIG`, `request({method,params})`, `connect()`), so the wallet code\n// path runs end-to-end in dev. It is a STUB, not a wallet: it returns a configurable mock address\n// and otherwise throws on methods that would need real signing, so a developer is never misled into\n// thinking a signature is real. It is generated as a self-contained, eval-free `<script>` body\n// (CSP-safe) that GUARDS on an existing `window.chia`, so a real wallet always wins.\n//\n// The shim's method names + response envelope mirror src/provider/injected.ts and\n// src/provider/methods.ts (the native provider returns `{ data }`), so the SAME normalizers run in\n// dev as in production — only the values are mocked.\n\nimport { INJECTED_TOPIC } from \"../provider/injected.js\";\n\n/** A literal substring stamped into the shim so it is unmistakably a dev stub (asserted in tests). */\nexport const DEV_SHIM_MARKER = \"dig-sdk:dev-wallet-shim\";\n\n/** Options for the generated dev shim. */\nexport interface DevShimOptions {\n /** Mock receive address the shim returns from `getAddress`. A clearly-fake default is used. */\n address?: string;\n}\n\n/** A clearly-fake default dev address (so it is obvious in the UI this is not a real wallet). */\nconst DEFAULT_DEV_ADDRESS = \"xch1dev0000000000000000000000000000000000000000000000000000devshim\";\n\n/** JSON-encode a string for safe inlining into a script literal. */\nfunction lit(s: string): string {\n return JSON.stringify(s);\n}\n\n/**\n * Generate the dev-shim `<script>` body (no surrounding `<script>` tags). Inline it into the dev\n * server's served HTML. It is an IIFE that installs `window.chia` ONLY if one is not already\n * present, so the DIG Browser / a real extension always takes precedence. Eval-free and\n * dependency-free — safe under a strict CSP.\n */\nexport function devShimScript(options: DevShimOptions = {}): string {\n const address = options.address ?? DEFAULT_DEV_ADDRESS;\n // The shim mirrors the injected-provider contract the SDK detects. `request` resolves a small set\n // of read methods with mock data and rejects signing methods (a dev stub must not fake a\n // signature). Method names are the bare CHIP-0002 names the SDK normalizes.\n return [\n `/* ${DEV_SHIM_MARKER} — DEV ONLY. A stub wallet for local development; NOT a real wallet. */`,\n `(function () {`,\n ` \"use strict\";`,\n ` if (typeof window === \"undefined\") return;`,\n ` // A real injected wallet (DIG Browser / extension) always wins — never clobber it.`,\n ` if (window.chia) return;`,\n ` var DEV_ADDRESS = ${lit(address)};`,\n ` var TOPIC = ${lit(INJECTED_TOPIC)};`,\n ` function ok(data) { return Promise.resolve({ data: data }); }`,\n ` function nope(method) {`,\n ` return Promise.reject(new Error(`,\n ` \"[\" + ${lit(DEV_SHIM_MARKER)} + \"] '\" + method + \"' needs a real wallet; the dev shim does not sign. \" +`,\n ` \"Open in the DIG Browser or connect a wallet to sign for real.\"));`,\n ` }`,\n ` window.chia = {`,\n ` isDIG: true, // detected by the SDK's injected-provider check`,\n ` isDevShim: true, // so the app can tell it is the dev stub`,\n ` topic: TOPIC,`,\n ` connect: function () { return Promise.resolve(true); },`,\n ` request: function (args) {`,\n ` var method = args && args.method ? String(args.method) : \"\";`,\n ` switch (method) {`,\n ` case \"chip0002_connect\": return ok(true);`,\n ` case \"chip0002_getPublicKeys\": return ok([]);`,\n ` case \"getAddress\":`,\n ` case \"chia_getAddress\": return ok(DEV_ADDRESS);`,\n ` default:`,\n ` // Signing / spend methods must not be faked.`,\n ` return nope(method);`,\n ` }`,\n ` },`,\n ` on: function () {},`,\n ` off: function () {},`,\n ` };`,\n ` if (window.console && window.console.info) {`,\n ` window.console.info(\"[\" + ${lit(DEV_SHIM_MARKER)} + \"] installed a DEV window.chia (mock address \" + DEV_ADDRESS + \").\");`,\n ` }`,\n `})();`,\n ].join(\"\\n\");\n}\n","// Deploy-config resolution for the framework adapters.\n//\n// The final config a deploy runs with is composed from three layers, highest precedence first:\n// 1. plugin options — what the developer wrote in vite.config / the Next adapter call\n// 2. environment vars — what CI injects (DIGSTORE_*), incl. the SECRETS (deploy key, salt)\n// 3. dig.toml — the project's checked-in defaults\n// 4. built-in defaults — outputDir=\"dist\", network=\"mainnet\" (mirrors deploy.rs::resolve_config)\n//\n// This mirrors `digstore deploy`'s own resolution order (flag/env > dig.toml > default) so the\n// adapters never disagree with the CLI about what a project deploys. SECRETS are resolved ONLY from\n// env — never from options or dig.toml — so they can't end up checked into a repo or a config file.\n\nimport type { DigTomlConfig } from \"./dig-toml.js\";\n\n/** Per-call options a developer passes to the Vite plugin / Next adapter. */\nexport interface AdapterOptions {\n /** On-chain store id (64-hex) to advance. Usually set in dig.toml instead. */\n storeId?: string;\n /** Built-output directory to publish. Defaults to the framework's output (or \"dist\"). */\n outputDir?: string;\n /** Shell build command for `digstore` to run. Omit when the adapter builds itself. */\n buildCommand?: string;\n /** Commit message for the new capsule. */\n message?: string;\n /** Chain network. Defaults to \"mainnet\". */\n network?: string;\n /** The `origin` remote to publish to (e.g. `dig://<storeId>`). */\n remote?: string;\n /** Seconds to wait for on-chain confirmation. */\n waitTimeout?: number;\n}\n\n/** The fully resolved config a deploy runs with. Secrets are present only if env supplied them. */\nexport interface ResolvedDeployConfig {\n storeId?: string;\n outputDir: string;\n buildCommand?: string;\n message?: string;\n network: string;\n remote?: string;\n waitTimeout?: number;\n /** Publisher deploy key (64-hex). From env only. */\n deployKey?: string;\n /** Private-store secret salt (64-hex). From env only. */\n salt?: string;\n}\n\n/** Inputs to resolution — kept explicit so it is a pure function (no process.env read inside). */\nexport interface ResolveInput {\n options: AdapterOptions;\n digToml: DigTomlConfig;\n env: Record<string, string | undefined>;\n}\n\n/** A non-empty, trimmed env value, or undefined. Empty/whitespace env vars count as unset. */\nfunction envVal(env: Record<string, string | undefined>, key: string): string | undefined {\n const v = env[key];\n if (v == null) return undefined;\n const t = v.trim();\n return t === \"\" ? undefined : t;\n}\n\n/** First defined of the candidates (treating \"\" the caller already filtered as undefined). */\nfunction pick<T>(...candidates: (T | undefined)[]): T | undefined {\n for (const c of candidates) if (c !== undefined) return c;\n return undefined;\n}\n\n/**\n * Resolve the final deploy config. Precedence per field: options > env (DIGSTORE_*) > dig.toml >\n * default. Secrets (deployKey, salt) are taken from env ONLY.\n */\nexport function resolveDeployConfig(input: ResolveInput): ResolvedDeployConfig {\n const { options, digToml, env } = input;\n\n const storeId = pick(\n options.storeId,\n envVal(env, \"DIGSTORE_STORE_ID\"),\n digToml.storeId,\n );\n const outputDir =\n pick(options.outputDir, envVal(env, \"DIGSTORE_OUTPUT_DIR\"), digToml.outputDir) ?? \"dist\";\n const buildCommand = pick(\n options.buildCommand,\n envVal(env, \"DIGSTORE_BUILD_COMMAND\"),\n digToml.buildCommand,\n );\n const message = pick(options.message, envVal(env, \"DIGSTORE_MESSAGE\"), digToml.message);\n const network =\n pick(options.network, envVal(env, \"DIGSTORE_NETWORK\"), digToml.network) ?? \"mainnet\";\n const remote = pick(options.remote, envVal(env, \"DIGSTORE_REMOTE\"), digToml.remote);\n\n const waitFromEnv = envVal(env, \"DIGSTORE_WAIT_TIMEOUT\");\n const waitTimeout = pick(\n options.waitTimeout,\n waitFromEnv != null ? Number.parseInt(waitFromEnv, 10) : undefined,\n digToml.waitTimeout,\n );\n\n return {\n storeId,\n outputDir,\n buildCommand,\n message,\n network,\n remote,\n waitTimeout: Number.isFinite(waitTimeout) ? waitTimeout : undefined,\n // SECRETS — env only.\n deployKey: envVal(env, \"DIGSTORE_DEPLOY_KEY\"),\n salt: envVal(env, \"DIGSTORE_STORE_SALT\"),\n };\n}\n","// Minimal `dig.toml` reader for the framework adapters.\n//\n// `digstore deploy` reads its config from a project's `dig.toml` (digstore-cli/src/dig_toml.rs).\n// The adapters need the SAME few top-level keys so a project's `dig.toml` is the single source of\n// truth across the CLI and the plugins. Rather than pull in a TOML parser dependency for ~7 flat\n// `key = \"value\"` lines, we parse just those keys ourselves. We accept BOTH the canonical\n// kebab-case key and the snake_case alias, exactly like digstore's `#[serde(rename/alias)]`.\n//\n// Anything beyond these keys (tables, arrays, nested values) is intentionally ignored — the\n// adapters only forward the deploy-relevant scalars to `digstore deploy`, which re-reads the full\n// file authoritatively.\n\n/** The deploy-relevant subset of `dig.toml`, in the adapters' camelCase shape. */\nexport interface DigTomlConfig {\n storeId?: string;\n outputDir?: string;\n buildCommand?: string;\n message?: string;\n network?: string;\n remote?: string;\n waitTimeout?: number;\n}\n\n// Map each canonical/alias TOML key onto the camelCase field. kebab-case is canonical (it is what\n// `digstore new` writes); snake_case is the tolerated alias. When both appear, the canonical\n// kebab-case key wins (it is applied last).\nconst KEY_MAP: Record<string, keyof DigTomlConfig> = {\n store_id: \"storeId\",\n \"store-id\": \"storeId\",\n output_dir: \"outputDir\",\n \"output-dir\": \"outputDir\",\n build_command: \"buildCommand\",\n \"build-command\": \"buildCommand\",\n message: \"message\",\n network: \"network\",\n remote: \"remote\",\n wait_timeout: \"waitTimeout\",\n \"wait-timeout\": \"waitTimeout\",\n};\n\n// Apply snake_case first then kebab-case so the canonical kebab form overrides the alias.\nconst APPLY_ORDER = Object.keys(KEY_MAP).sort((a) =>\n a.includes(\"-\") ? 1 : -1,\n);\n\n/** Strip a `# comment` that is not inside a quoted value. */\nfunction stripComment(line: string): string {\n let inSingle = false;\n let inDouble = false;\n for (let i = 0; i < line.length; i++) {\n const ch = line[i];\n if (ch === \"'\" && !inDouble) inSingle = !inSingle;\n else if (ch === '\"' && !inSingle) inDouble = !inDouble;\n else if (ch === \"#\" && !inSingle && !inDouble) return line.slice(0, i);\n }\n return line;\n}\n\n/** Unquote a TOML scalar: `\"x\"` / `'x'` → `x`; a bare token is returned trimmed. */\nfunction unquote(raw: string): string {\n const v = raw.trim();\n if (\n (v.startsWith('\"') && v.endsWith('\"') && v.length >= 2) ||\n (v.startsWith(\"'\") && v.endsWith(\"'\") && v.length >= 2)\n ) {\n return v.slice(1, -1);\n }\n return v;\n}\n\n/**\n * Parse the deploy-relevant keys out of a `dig.toml` string. Unknown keys, tables, and nested\n * structures are ignored. Returns only the keys actually present (so it composes cleanly under the\n * precedence rules in resolveDeployConfig).\n */\nexport function parseDigToml(text: string): DigTomlConfig {\n // Collect raw (canonical-or-alias) string values keyed by the TOML key as written.\n const raw: Record<string, string> = {};\n for (const lineRaw of text.split(/\\r?\\n/)) {\n const line = stripComment(lineRaw).trim();\n if (!line || line.startsWith(\"[\")) continue; // skip blanks + table headers\n const eq = line.indexOf(\"=\");\n if (eq <= 0) continue;\n const key = line.slice(0, eq).trim();\n if (!(key in KEY_MAP)) continue;\n raw[key] = unquote(line.slice(eq + 1));\n }\n\n const out: DigTomlConfig = {};\n for (const key of APPLY_ORDER) {\n const value = raw[key];\n const field = KEY_MAP[key];\n if (value === undefined || field === undefined) continue;\n if (field === \"waitTimeout\") {\n const n = Number.parseInt(value, 10);\n if (Number.isFinite(n)) out.waitTimeout = n;\n } else {\n out[field] = value;\n }\n }\n return out;\n}\n","// The pure glue around `digstore deploy --json`: build the child argv + env, and parse the result.\n//\n// The adapters SHELL OUT to the installed `digstore` binary (the canonical deployer — it advances\n// the on-chain root, stages the build dir, and pushes the new capsule to DIGHUb). They never\n// re-implement deploy. These helpers are the deterministic, side-effect-free pieces:\n//\n// • buildDeployArgs — resolved config → argv (always `deploy --json`, only set flags).\n// • buildDeployEnv — resolved config → the env overlay carrying the SECRETS to the child, so the\n// deploy key / salt are NEVER on the argv (process-table leak), matching\n// digstore-cli's own guidance (deploy.rs).\n// • parseDeployResult— `digstore deploy --json` stdout → { capsule, storeId, root, chiaUrl,\n// digUrl, hubUrl, pushed }, deriving the URLs exactly as digstore does\n// (capsule = storeId:root; hub view = https://hub.dig.net/stores/<id>;\n// chiaUrl = the user-facing content-open address chia://<store>:<root>/,\n// matching digstore's printed `content_address`).\n\nimport type { ResolvedDeployConfig } from \"./config.js\";\nimport { DigSdkError } from \"../errors.js\";\n\n/** Knobs for argv construction. */\nexport interface DeployArgsOptions {\n /**\n * The adapter already ran the framework build, so don't hand `--build-command` to digstore (it\n * would rebuild). The output dir is staged as-is.\n */\n skipBuild?: boolean;\n}\n\n/**\n * Build the argv for `digstore <argv>` from a resolved config. Always `deploy --json`. Only flags\n * whose values are set are emitted. SECRETS (deployKey, salt) are intentionally excluded — they go\n * through the env (buildDeployEnv) so they never appear in the process table.\n */\nexport function buildDeployArgs(\n cfg: ResolvedDeployConfig,\n opts: DeployArgsOptions = {},\n): string[] {\n const argv: string[] = [\"deploy\", \"--json\"];\n if (cfg.storeId) argv.push(\"--store-id\", cfg.storeId);\n if (cfg.outputDir) argv.push(\"--output-dir\", cfg.outputDir);\n if (!opts.skipBuild && cfg.buildCommand) argv.push(\"--build-command\", cfg.buildCommand);\n if (cfg.message) argv.push(\"--message\", cfg.message);\n if (cfg.network) argv.push(\"--network\", cfg.network);\n if (cfg.remote) argv.push(\"--remote\", cfg.remote);\n if (cfg.waitTimeout != null) argv.push(\"--wait-timeout\", String(cfg.waitTimeout));\n return argv;\n}\n\n/**\n * The env overlay to merge onto the child process env: the SECRETS, passed out-of-band so they are\n * never visible on the command line. Returns only the keys that have a value.\n */\nexport function buildDeployEnv(cfg: ResolvedDeployConfig): Record<string, string> {\n const env: Record<string, string> = {};\n if (cfg.deployKey) env.DIGSTORE_DEPLOY_KEY = cfg.deployKey;\n if (cfg.salt) env.DIGSTORE_STORE_SALT = cfg.salt;\n return env;\n}\n\n/** The friendly, parsed outcome of a deploy. */\nexport interface DeployResult {\n /** `storeId:rootHash` — the capsule identity (the ecosystem-vocabulary id the user shares). */\n capsule: string;\n /** Store identity (64-hex). */\n storeId: string;\n /** The new on-chain root (64-hex). */\n root: string;\n /**\n * The user-facing content-open address `chia://<storeId>:<rootHash>/` — what a user types/clicks\n * to open this verified capsule in the DIG Browser / extension (the scheme they register). This\n * matches digstore deploy's printed `content_address` exactly. (Distinct from the §21 remote\n * locator `dig://<host>/<store_id>` and the `urn:dig:` namespace, which stay `dig://`.)\n */\n chiaUrl: string;\n /**\n * @deprecated Use {@link chiaUrl}. Kept as a back-compat alias for consumers that read `digUrl`;\n * it now carries the SAME `chia://<storeId>:<rootHash>/` content-open value (NOT a `dig://` URL).\n */\n digUrl: string;\n /** The human \"view it\" URL on DIGHUb (the same one `digstore deploy` prints). */\n hubUrl: string;\n /** Whether the capsule was pushed to DIGHUb (when the JSON reported it). */\n pushed?: boolean;\n}\n\nconst CAPSULE_RE = /^([0-9a-f]{64}):([0-9a-f]{64})$/i;\n\n/**\n * Parse `digstore deploy --json` stdout into a DeployResult. digstore emits a single JSON object\n * (with at least `capsule` and `root`); we also tolerate extra JSON log lines by scanning lines\n * bottom-up for the first object that carries a `capsule`. Throws a clear error if none is found or\n * the output isn't JSON at all.\n */\nexport function parseDeployResult(stdout: string): DeployResult {\n const lines = stdout\n .split(/\\r?\\n/)\n .map((l) => l.trim())\n .filter((l) => l.startsWith(\"{\") && l.endsWith(\"}\"));\n\n if (lines.length === 0) {\n throw new DigSdkError(\n \"DEPLOY_OUTPUT_UNPARSEABLE\",\n `could not parse digstore deploy output (no JSON object found). Output was:\\n${stdout.slice(0, 500)}`,\n { stdout: stdout.slice(0, 500) },\n );\n }\n\n // Prefer the LAST JSON object that has a capsule (deploy emits one final result object). Keep the\n // first parseable object as a fallback so the error message can show what digstore DID return.\n let obj: Record<string, unknown> | undefined;\n let fallback: Record<string, unknown> | undefined;\n for (let i = lines.length - 1; i >= 0; i--) {\n const line = lines[i];\n if (line === undefined) continue;\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(line) as Record<string, unknown>;\n } catch {\n continue; // not JSON — skip this line\n }\n if (typeof parsed.capsule === \"string\") {\n obj = parsed;\n break;\n }\n if (!fallback) fallback = parsed;\n }\n\n if (!obj) {\n if (fallback) {\n throw new DigSdkError(\n \"DEPLOY_OUTPUT_UNPARSEABLE\",\n `digstore deploy did not report a capsule (deploy may have failed). Output:\\n${JSON.stringify(fallback)}`,\n { output: fallback },\n );\n }\n throw new DigSdkError(\n \"DEPLOY_OUTPUT_UNPARSEABLE\",\n `could not parse digstore deploy output as JSON:\\n${stdout.slice(0, 500)}`,\n { stdout: stdout.slice(0, 500) },\n );\n }\n\n const capsule = obj.capsule as string;\n const m = CAPSULE_RE.exec(capsule);\n if (!m || m[1] === undefined || m[2] === undefined) {\n throw new DigSdkError(\n \"INVALID_ARGUMENT\",\n `digstore deploy reported a malformed capsule \"${capsule}\" (expected storeId:root)`,\n { value: capsule, expected: \"storeId:root\" },\n );\n }\n const storeId = m[1].toLowerCase();\n const root = (typeof obj.root === \"string\" ? obj.root : m[2]).toLowerCase();\n\n // The user-facing content-open address. Prefer the value digstore itself printed\n // (`content_address`, the single source of truth — digstore deploy.rs::branding::content_url) so\n // the SDK stays byte-identical to the CLI; otherwise derive it the same way digstore does:\n // chia://<storeId>:<rootHash>/ (trailing slash, no resource). This is what a user opens in the\n // DIG Browser/extension — NOT the §21 remote dig:// locator.\n const chiaUrl =\n typeof obj.content_address === \"string\"\n ? obj.content_address\n : `chia://${storeId}:${root}/`;\n\n return {\n capsule,\n storeId,\n root,\n chiaUrl,\n // Deprecated alias: same chia:// content-open value (back-compat for consumers reading digUrl).\n digUrl: chiaUrl,\n // Mirrors digstore deploy.rs::hub_url — the public DIGHUb view of an owned store.\n hubUrl: `https://hub.dig.net/stores/${storeId}`,\n pushed: typeof obj.pushed === \"boolean\" ? obj.pushed : undefined,\n };\n}\n","// The shared, Node-only deploy runner both framework adapters call on their `publish` step.\n//\n// It composes the pure pieces (load dig.toml → resolve config → build argv + env), spawns the\n// installed `digstore` binary with `deploy --json`, and parses the result into a friendly\n// DeployResult ({ capsule, chiaUrl, hubUrl }). It is intentionally thin: ALL deploy logic lives in\n// `digstore deploy` (the canonical deployer — advances the on-chain root, stages, pushes the\n// capsule); this only marshals config in and the result out.\n//\n// Node-only: it uses node:child_process / node:fs. The framework entrypoints import it lazily on\n// the publish path so importing the plugin in a browser/config context never pulls Node APIs.\n\nimport { resolveDeployConfig, type AdapterOptions } from \"./config.js\";\nimport { parseDigToml, type DigTomlConfig } from \"./dig-toml.js\";\nimport {\n buildDeployArgs,\n buildDeployEnv,\n parseDeployResult,\n type DeployArgsOptions,\n type DeployResult,\n} from \"./deploy.js\";\nimport { DigSdkError } from \"../errors.js\";\n\n/** Options for {@link runDeploy}. */\nexport interface RunDeployOptions extends AdapterOptions, DeployArgsOptions {\n /** Project root that holds `dig.toml` and the build output. Defaults to `process.cwd()`. */\n cwd?: string;\n /** The `digstore` executable. Defaults to `\"digstore\"` (must be on PATH). */\n digstoreBin?: string;\n /** Sink for human-readable progress. Defaults to `console.log`. */\n logger?: (line: string) => void;\n}\n\n/** Read `dig.toml` from `cwd` (returns {} when absent). */\nasync function readDigToml(cwd: string): Promise<DigTomlConfig> {\n const { readFile } = await import(\"node:fs/promises\");\n const path = await import(\"node:path\");\n try {\n const text = await readFile(path.join(cwd, \"dig.toml\"), \"utf8\");\n return parseDigToml(text);\n } catch {\n return {}; // no dig.toml — rely on options + env\n }\n}\n\n/**\n * Resolve config, run `digstore deploy --json`, and parse the capsule. Spawns `digstore` with the\n * SECRETS injected through the child env (never the argv). Rejects with digstore's stderr on\n * non-zero exit. Returns the parsed {@link DeployResult}.\n */\nexport async function runDeploy(options: RunDeployOptions = {}): Promise<DeployResult> {\n const cwd = options.cwd ?? process.cwd();\n const bin = options.digstoreBin ?? \"digstore\";\n const log = options.logger ?? ((l: string) => console.log(l));\n\n const digToml = await readDigToml(cwd);\n const cfg = resolveDeployConfig({\n options: {\n storeId: options.storeId,\n outputDir: options.outputDir,\n buildCommand: options.buildCommand,\n message: options.message,\n network: options.network,\n remote: options.remote,\n waitTimeout: options.waitTimeout,\n },\n digToml,\n env: process.env,\n });\n\n const argv = buildDeployArgs(cfg, { skipBuild: options.skipBuild });\n const childEnv = { ...process.env, ...buildDeployEnv(cfg) };\n\n log(`▶ digstore ${argv.filter((a) => a !== cfg.deployKey && a !== cfg.salt).join(\" \")}`);\n\n const { spawn } = await import(\"node:child_process\");\n const stdout = await new Promise<string>((resolve, reject) => {\n const child = spawn(bin, argv, {\n cwd,\n env: childEnv,\n // digstore reads no stdin here; capture stdout (the JSON) and stream stderr through.\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n shell: false,\n });\n let out = \"\";\n let err = \"\";\n child.stdout.on(\"data\", (d: Buffer) => {\n out += d.toString();\n });\n child.stderr.on(\"data\", (d: Buffer) => {\n err += d.toString();\n });\n child.on(\"error\", (e: Error) => {\n reject(\n new DigSdkError(\n \"DIGSTORE_NOT_FOUND\",\n `could not run \"${bin}\" — is digstore installed and on PATH? (${e.message})`,\n { bin },\n { cause: e },\n ),\n );\n });\n child.on(\"close\", (code: number | null) => {\n if (code === 0) resolve(out);\n else\n reject(\n new DigSdkError(\"DEPLOY_FAILED\", `digstore deploy failed (exit ${code}).\\n${err || out}`, {\n exitCode: code,\n stderr: err.slice(0, 2000),\n }),\n );\n });\n });\n\n const result = parseDeployResult(stdout);\n log(`✓ deployed capsule ${result.capsule}`);\n // chia:// is the user-facing content-open address (what they open in the DIG Browser/extension).\n log(` open ${result.chiaUrl}`);\n log(` view ${result.hubUrl}`);\n return result;\n}\n","// `@dignetwork/dig-sdk/next` — a Next.js static-export adapter for shipping to DIG.\n//\n// Next has no Vite-style `transformIndexHtml` hook, so the two jobs are surfaced as helpers a Next\n// project wires in:\n// 1. DEV: `digNextDevShimTag()` returns a ready `<script …>` string to drop into the app's\n// `<head>` (e.g. in `app/layout.tsx` or `_document`) so `next dev` has the SDK's `window.chia`\n// dev shim — the SAME injected-provider contract production uses. It guards on a real wallet\n// and is eval-free. Gate it on `process.env.NODE_ENV !== \"production\"` in your layout so it\n// ships only in dev.\n// 2. PUBLISH: `digDeploy()` ships the static-export output (`out/` by default — what\n// `next build` writes with `output: \"export\"`) to a DIG capsule via `digstore deploy --json`,\n// printing the chia:// content-open URL + the DIGHUb view URL. Call it from a `publish` script\n// after the build.\n//\n// Next is an OPTIONAL peer: this module imports nothing from \"next\". The publish runner is the\n// shared Node-only `runDeploy`.\n\nimport { devShimScript, type DevShimOptions } from \"./adapters/dev-shim.js\";\nimport type { AdapterOptions } from \"./adapters/config.js\";\nimport type { DeployResult } from \"./adapters/deploy.js\";\nimport { runDeploy } from \"./adapters/run.js\";\n\n/** Next static-export writes here by default (`output: \"export\"`). */\nconst NEXT_EXPORT_DIR = \"out\";\n\n/**\n * The raw dev-shim script BODY (no `<script>` tags) — for callers that inject it themselves (e.g.\n * via Next's `<Script id=… dangerouslySetInnerHTML>` or a custom `_document`).\n */\nexport function digNextDevShimScript(options: DevShimOptions = {}): string {\n return devShimScript(options);\n}\n\n/**\n * A ready-to-inline `<script>…</script>` tag carrying the dev shim. Drop into the app `<head>`\n * (guard on dev): e.g. in `app/layout.tsx`\n * `{process.env.NODE_ENV !== \"production\" && <head dangerouslySetInnerHTML={{ __html: digNextDevShimTag() }} />}`.\n * Prefer `digNextDevShimScript()` with Next's `<Script>` component when you can.\n */\nexport function digNextDevShimTag(options: DevShimOptions = {}): string {\n return `<script>${devShimScript(options)}</script>`;\n}\n\n/**\n * Deploy the Next static export to a DIG capsule. Call from a `publish` script AFTER\n * `next build` (with `output: \"export\"`). Defaults `outputDir` to `out` (Next's export dir); reads\n * `dig.toml` + env (DIGSTORE_*) for the rest. The adapter has already built, so digstore stages the\n * existing `out/` rather than rebuilding.\n */\nexport function digDeploy(options: AdapterOptions = {}): Promise<DeployResult> {\n return runDeploy({ ...options, outputDir: options.outputDir ?? NEXT_EXPORT_DIR, skipBuild: true });\n}\n\nexport default digDeploy;\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/provider/injected.ts","../src/adapters/dev-shim.ts","../src/adapters/config.ts","../src/adapters/dig-toml.ts","../src/adapters/deploy.ts","../src/adapters/run.ts","../src/next.ts"],"names":[],"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,M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AED,EAAA,MAAM,MAAA,GAAS,kBAAkB,MAAM,CAAA;AACvC,EAAA,GAAA,CAAI,CAAA,wBAAA,EAAsB,MAAA,CAAO,OAAO,CAAA,CAAE,CAAA;AAE1C,EAAA,GAAA,CAAI,CAAA,UAAA,EAAa,MAAA,CAAO,OAAO,CAAA,CAAE,CAAA;AACjC,EAAA,GAAA,CAAI,CAAA,UAAA,EAAa,MAAA,CAAO,MAAM,CAAA,CAAE,CAAA;AAChC,EAAA,OAAO,MAAA;AACT;;;AChGA,IAAM,eAAA,GAAkB,KAAA;AAMjB,SAAS,oBAAA,CAAqB,OAAA,GAA0B,EAAC,EAAW;AACzE,EAAA,OAAO,cAAc,OAAO,CAAA;AAC9B;AAQO,SAAS,iBAAA,CAAkB,OAAA,GAA0B,EAAC,EAAW;AACtE,EAAA,OAAO,CAAA,QAAA,EAAW,aAAA,CAAc,OAAO,CAAC,CAAA,SAAA,CAAA;AAC1C;AAQO,SAAS,SAAA,CAAU,OAAA,GAA0B,EAAC,EAA0B;AAC7E,EAAA,OAAO,SAAA,CAAU,EAAE,GAAG,OAAA,EAAS,SAAA,EAAW,QAAQ,SAAA,IAAa,eAAA,EAAiB,SAAA,EAAW,IAAA,EAAM,CAAA;AACnG;AAEA,IAAO,YAAA,GAAQ","file":"next.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","// Injected-provider transport — the DIG Browser's in-process wallet (and compatible CHIP-0002\n// extensions), exposed on every page as `window.chia`. When present the SDK PREFERS it over\n// WalletConnect: no QR, no relay, no pairing. The native provider returns the SAME response shapes\n// Sage returns over WalletConnect, so the normalizers in provider/methods.ts are unchanged — only\n// the TRANSPORT differs. Genericized from hub.dig.net/apps/web/lib/injected-wallet.js.\n//\n// Detection: we key on the explicit, unspoofable `isDIG` marker the DIG Browser provider sets, not\n// merely the presence of `window.chia` (a different Chia provider could also define that).\n\nimport type { InjectedChiaProvider, WalletBackend } from \"../types.js\";\nimport { WALLET_METHODS, DEFAULT_CHAIN } from \"../methods.js\";\nimport type { WalletTransport } from \"./transport.js\";\nimport { DigSdkError } from \"../errors.js\";\n\n/** The injected provider on the current global, or undefined when not running in a DIG Browser. */\nexport function getInjectedProvider(): InjectedChiaProvider | undefined {\n const g = globalThis as { chia?: InjectedChiaProvider };\n return typeof g !== \"undefined\" ? g.chia : undefined;\n}\n\n/**\n * True iff an injected DIG wallet is available. Detects on the unspoofable `isDIG` marker. Pass\n * `{ anyChia: true }` to accept any `window.chia` that implements `request` (e.g. a non-DIG\n * CHIP-0002 extension).\n */\nexport function isInjectedAvailable(opts: { anyChia?: boolean } = {}): boolean {\n const p = getInjectedProvider();\n if (!p) return false;\n if (opts.anyChia) return typeof p.request === \"function\";\n return !!p.isDIG;\n}\n\n/** Sentinel topic for the injected backend (it has no per-session relay topic). */\nexport const INJECTED_TOPIC = \"injected\";\n\n/** A WalletTransport backed by the injected window.chia provider. */\nexport class InjectedTransport implements WalletTransport {\n readonly backend: WalletBackend = \"injected\";\n readonly topic = INJECTED_TOPIC;\n readonly chain: string;\n private readonly provider: InjectedChiaProvider;\n\n constructor(provider: InjectedChiaProvider, chain: string = DEFAULT_CHAIN) {\n this.provider = provider;\n this.chain = chain;\n }\n\n /** Connect: ask the native wallet to approve this origin. Blocks until approved/rejected. */\n async connect(eager = false): Promise<void> {\n if (typeof this.provider.connect === \"function\") {\n await this.provider.connect(eager);\n }\n // A provider without connect() (older build) is tolerated — request() will gate per-method.\n }\n\n // The native wallet implements the full canonical set (it returns Sage-shaped responses), so\n // support is a static allowlist — no per-session negotiation as with WalletConnect.\n supports(method: string): boolean {\n return (WALLET_METHODS as readonly string[]).includes(method);\n }\n\n async request(method: string, params: unknown): Promise<unknown> {\n if (!this.supports(method)) {\n throw new DigSdkError(\n \"METHOD_NOT_SUPPORTED\",\n `The DIG Browser wallet does not support \"${method}\".`,\n { method },\n );\n }\n return this.provider.request({ method, params });\n }\n\n async disconnect(): Promise<void> {\n // The injected wallet has no per-session teardown; per-origin consent is managed in the wallet.\n }\n}\n","// The `window.chia` DEV shim the adapters inject during `dev`.\n//\n// In production a dapp's wallet is the REAL injected provider — the DIG Browser's in-process wallet\n// (or a CHIP-0002 extension) — which the SDK's ChiaProvider detects on `window.chia` via the\n// `isDIG` marker (see src/provider/injected.ts). During local `vite dev` / `next dev` there is no\n// such wallet, so calling `ChiaProvider.connect({ mode: \"injected\" })` would fail and the developer\n// couldn't exercise the wallet path at all.\n//\n// This shim installs a MINIMAL, clearly-labelled stub that satisfies the SAME injected-provider\n// contract the SDK detects (`isDIG`, `request({method,params})`, `connect()`), so the wallet code\n// path runs end-to-end in dev. It is a STUB, not a wallet: it returns a configurable mock address\n// and otherwise throws on methods that would need real signing, so a developer is never misled into\n// thinking a signature is real. It is generated as a self-contained, eval-free `<script>` body\n// (CSP-safe) that GUARDS on an existing `window.chia`, so a real wallet always wins.\n//\n// The shim's method names + response envelope mirror src/provider/injected.ts and\n// src/provider/methods.ts (the native provider returns `{ data }`), so the SAME normalizers run in\n// dev as in production — only the values are mocked.\n\nimport { INJECTED_TOPIC } from \"../provider/injected.js\";\n\n/** A literal substring stamped into the shim so it is unmistakably a dev stub (asserted in tests). */\nexport const DEV_SHIM_MARKER = \"dig-sdk:dev-wallet-shim\";\n\n/** Options for the generated dev shim. */\nexport interface DevShimOptions {\n /** Mock receive address the shim returns from `getAddress`. A clearly-fake default is used. */\n address?: string;\n}\n\n/** A clearly-fake default dev address (so it is obvious in the UI this is not a real wallet). */\nconst DEFAULT_DEV_ADDRESS = \"xch1dev0000000000000000000000000000000000000000000000000000devshim\";\n\n/** JSON-encode a string for safe inlining into a script literal. */\nfunction lit(s: string): string {\n return JSON.stringify(s);\n}\n\n/**\n * Generate the dev-shim `<script>` body (no surrounding `<script>` tags). Inline it into the dev\n * server's served HTML. It is an IIFE that installs `window.chia` ONLY if one is not already\n * present, so the DIG Browser / a real extension always takes precedence. Eval-free and\n * dependency-free — safe under a strict CSP.\n */\nexport function devShimScript(options: DevShimOptions = {}): string {\n const address = options.address ?? DEFAULT_DEV_ADDRESS;\n // The shim mirrors the injected-provider contract the SDK detects. `request` resolves a small set\n // of read methods with mock data and rejects signing methods (a dev stub must not fake a\n // signature). Method names are the bare CHIP-0002 names the SDK normalizes.\n return [\n `/* ${DEV_SHIM_MARKER} — DEV ONLY. A stub wallet for local development; NOT a real wallet. */`,\n `(function () {`,\n ` \"use strict\";`,\n ` if (typeof window === \"undefined\") return;`,\n ` // A real injected wallet (DIG Browser / extension) always wins — never clobber it.`,\n ` if (window.chia) return;`,\n ` var DEV_ADDRESS = ${lit(address)};`,\n ` var TOPIC = ${lit(INJECTED_TOPIC)};`,\n ` function ok(data) { return Promise.resolve({ data: data }); }`,\n ` function nope(method) {`,\n ` return Promise.reject(new Error(`,\n ` \"[\" + ${lit(DEV_SHIM_MARKER)} + \"] '\" + method + \"' needs a real wallet; the dev shim does not sign. \" +`,\n ` \"Open in the DIG Browser or connect a wallet to sign for real.\"));`,\n ` }`,\n ` window.chia = {`,\n ` isDIG: true, // detected by the SDK's injected-provider check`,\n ` isDevShim: true, // so the app can tell it is the dev stub`,\n ` topic: TOPIC,`,\n ` connect: function () { return Promise.resolve(true); },`,\n ` request: function (args) {`,\n ` var method = args && args.method ? String(args.method) : \"\";`,\n ` switch (method) {`,\n ` case \"chip0002_connect\": return ok(true);`,\n ` case \"chip0002_getPublicKeys\": return ok([]);`,\n ` case \"getAddress\":`,\n ` case \"chia_getAddress\": return ok(DEV_ADDRESS);`,\n ` default:`,\n ` // Signing / spend methods must not be faked.`,\n ` return nope(method);`,\n ` }`,\n ` },`,\n ` on: function () {},`,\n ` off: function () {},`,\n ` };`,\n ` if (window.console && window.console.info) {`,\n ` window.console.info(\"[\" + ${lit(DEV_SHIM_MARKER)} + \"] installed a DEV window.chia (mock address \" + DEV_ADDRESS + \").\");`,\n ` }`,\n `})();`,\n ].join(\"\\n\");\n}\n","// Deploy-config resolution for the framework adapters.\n//\n// The final config a deploy runs with is composed from three layers, highest precedence first:\n// 1. plugin options — what the developer wrote in vite.config / the Next adapter call\n// 2. environment vars — what CI injects (DIGSTORE_*), incl. the SECRETS (deploy key, salt)\n// 3. dig.toml — the project's checked-in defaults\n// 4. built-in defaults — outputDir=\"dist\", network=\"mainnet\" (mirrors deploy.rs::resolve_config)\n//\n// This mirrors `digstore deploy`'s own resolution order (flag/env > dig.toml > default) so the\n// adapters never disagree with the CLI about what a project deploys. SECRETS are resolved ONLY from\n// env — never from options or dig.toml — so they can't end up checked into a repo or a config file.\n\nimport type { DigTomlConfig } from \"./dig-toml.js\";\n\n/** Per-call options a developer passes to the Vite plugin / Next adapter. */\nexport interface AdapterOptions {\n /** On-chain store id (64-hex) to advance. Usually set in dig.toml instead. */\n storeId?: string;\n /** Built-output directory to publish. Defaults to the framework's output (or \"dist\"). */\n outputDir?: string;\n /** Shell build command for `digstore` to run. Omit when the adapter builds itself. */\n buildCommand?: string;\n /** Commit message for the new capsule. */\n message?: string;\n /** Chain network. Defaults to \"mainnet\". */\n network?: string;\n /** The `origin` remote to publish to (e.g. `dig://<storeId>`). */\n remote?: string;\n /** Seconds to wait for on-chain confirmation. */\n waitTimeout?: number;\n}\n\n/** The fully resolved config a deploy runs with. Secrets are present only if env supplied them. */\nexport interface ResolvedDeployConfig {\n storeId?: string;\n outputDir: string;\n buildCommand?: string;\n message?: string;\n network: string;\n remote?: string;\n waitTimeout?: number;\n /** Publisher deploy key (64-hex). From env only. */\n deployKey?: string;\n /** Private-store secret salt (64-hex). From env only. */\n salt?: string;\n}\n\n/** Inputs to resolution — kept explicit so it is a pure function (no process.env read inside). */\nexport interface ResolveInput {\n options: AdapterOptions;\n digToml: DigTomlConfig;\n env: Record<string, string | undefined>;\n}\n\n/** A non-empty, trimmed env value, or undefined. Empty/whitespace env vars count as unset. */\nfunction envVal(env: Record<string, string | undefined>, key: string): string | undefined {\n const v = env[key];\n if (v == null) return undefined;\n const t = v.trim();\n return t === \"\" ? undefined : t;\n}\n\n/** First defined of the candidates (treating \"\" the caller already filtered as undefined). */\nfunction pick<T>(...candidates: (T | undefined)[]): T | undefined {\n for (const c of candidates) if (c !== undefined) return c;\n return undefined;\n}\n\n/**\n * Resolve the final deploy config. Precedence per field: options > env (DIGSTORE_*) > dig.toml >\n * default. Secrets (deployKey, salt) are taken from env ONLY.\n */\nexport function resolveDeployConfig(input: ResolveInput): ResolvedDeployConfig {\n const { options, digToml, env } = input;\n\n const storeId = pick(\n options.storeId,\n envVal(env, \"DIGSTORE_STORE_ID\"),\n digToml.storeId,\n );\n const outputDir =\n pick(options.outputDir, envVal(env, \"DIGSTORE_OUTPUT_DIR\"), digToml.outputDir) ?? \"dist\";\n const buildCommand = pick(\n options.buildCommand,\n envVal(env, \"DIGSTORE_BUILD_COMMAND\"),\n digToml.buildCommand,\n );\n const message = pick(options.message, envVal(env, \"DIGSTORE_MESSAGE\"), digToml.message);\n const network =\n pick(options.network, envVal(env, \"DIGSTORE_NETWORK\"), digToml.network) ?? \"mainnet\";\n const remote = pick(options.remote, envVal(env, \"DIGSTORE_REMOTE\"), digToml.remote);\n\n const waitFromEnv = envVal(env, \"DIGSTORE_WAIT_TIMEOUT\");\n const waitTimeout = pick(\n options.waitTimeout,\n waitFromEnv != null ? Number.parseInt(waitFromEnv, 10) : undefined,\n digToml.waitTimeout,\n );\n\n return {\n storeId,\n outputDir,\n buildCommand,\n message,\n network,\n remote,\n waitTimeout: Number.isFinite(waitTimeout) ? waitTimeout : undefined,\n // SECRETS — env only.\n deployKey: envVal(env, \"DIGSTORE_DEPLOY_KEY\"),\n salt: envVal(env, \"DIGSTORE_STORE_SALT\"),\n };\n}\n","// Minimal `dig.toml` reader for the framework adapters.\n//\n// `digstore deploy` reads its config from a project's `dig.toml` (digstore-cli/src/dig_toml.rs).\n// The adapters need the SAME few top-level keys so a project's `dig.toml` is the single source of\n// truth across the CLI and the plugins. Rather than pull in a TOML parser dependency for ~7 flat\n// `key = \"value\"` lines, we parse just those keys ourselves. We accept BOTH the canonical\n// kebab-case key and the snake_case alias, exactly like digstore's `#[serde(rename/alias)]`.\n//\n// Anything beyond these keys (tables, arrays, nested values) is intentionally ignored — the\n// adapters only forward the deploy-relevant scalars to `digstore deploy`, which re-reads the full\n// file authoritatively.\n\n/** The deploy-relevant subset of `dig.toml`, in the adapters' camelCase shape. */\nexport interface DigTomlConfig {\n storeId?: string;\n outputDir?: string;\n buildCommand?: string;\n message?: string;\n network?: string;\n remote?: string;\n waitTimeout?: number;\n}\n\n// Map each canonical/alias TOML key onto the camelCase field. kebab-case is canonical (it is what\n// `digstore new` writes); snake_case is the tolerated alias. When both appear, the canonical\n// kebab-case key wins (it is applied last).\nconst KEY_MAP: Record<string, keyof DigTomlConfig> = {\n store_id: \"storeId\",\n \"store-id\": \"storeId\",\n output_dir: \"outputDir\",\n \"output-dir\": \"outputDir\",\n build_command: \"buildCommand\",\n \"build-command\": \"buildCommand\",\n message: \"message\",\n network: \"network\",\n remote: \"remote\",\n wait_timeout: \"waitTimeout\",\n \"wait-timeout\": \"waitTimeout\",\n};\n\n// Apply snake_case first then kebab-case so the canonical kebab form overrides the alias.\nconst APPLY_ORDER = Object.keys(KEY_MAP).sort((a) =>\n a.includes(\"-\") ? 1 : -1,\n);\n\n/** Strip a `# comment` that is not inside a quoted value. */\nfunction stripComment(line: string): string {\n let inSingle = false;\n let inDouble = false;\n for (let i = 0; i < line.length; i++) {\n const ch = line[i];\n if (ch === \"'\" && !inDouble) inSingle = !inSingle;\n else if (ch === '\"' && !inSingle) inDouble = !inDouble;\n else if (ch === \"#\" && !inSingle && !inDouble) return line.slice(0, i);\n }\n return line;\n}\n\n/** Unquote a TOML scalar: `\"x\"` / `'x'` → `x`; a bare token is returned trimmed. */\nfunction unquote(raw: string): string {\n const v = raw.trim();\n if (\n (v.startsWith('\"') && v.endsWith('\"') && v.length >= 2) ||\n (v.startsWith(\"'\") && v.endsWith(\"'\") && v.length >= 2)\n ) {\n return v.slice(1, -1);\n }\n return v;\n}\n\n/**\n * Parse the deploy-relevant keys out of a `dig.toml` string. Unknown keys, tables, and nested\n * structures are ignored. Returns only the keys actually present (so it composes cleanly under the\n * precedence rules in resolveDeployConfig).\n */\nexport function parseDigToml(text: string): DigTomlConfig {\n // Collect raw (canonical-or-alias) string values keyed by the TOML key as written.\n const raw: Record<string, string> = {};\n for (const lineRaw of text.split(/\\r?\\n/)) {\n const line = stripComment(lineRaw).trim();\n if (!line || line.startsWith(\"[\")) continue; // skip blanks + table headers\n const eq = line.indexOf(\"=\");\n if (eq <= 0) continue;\n const key = line.slice(0, eq).trim();\n if (!(key in KEY_MAP)) continue;\n raw[key] = unquote(line.slice(eq + 1));\n }\n\n const out: DigTomlConfig = {};\n for (const key of APPLY_ORDER) {\n const value = raw[key];\n const field = KEY_MAP[key];\n if (value === undefined || field === undefined) continue;\n if (field === \"waitTimeout\") {\n const n = Number.parseInt(value, 10);\n if (Number.isFinite(n)) out.waitTimeout = n;\n } else {\n out[field] = value;\n }\n }\n return out;\n}\n","// The pure glue around `digstore deploy --json`: build the child argv + env, and parse the result.\n//\n// The adapters SHELL OUT to the installed `digstore` binary (the canonical deployer — it advances\n// the on-chain root, stages the build dir, and pushes the new capsule to DIGHUb). They never\n// re-implement deploy. These helpers are the deterministic, side-effect-free pieces:\n//\n// • buildDeployArgs — resolved config → argv (always `deploy --json`, only set flags).\n// • buildDeployEnv — resolved config → the env overlay carrying the SECRETS to the child, so the\n// deploy key / salt are NEVER on the argv (process-table leak), matching\n// digstore-cli's own guidance (deploy.rs).\n// • parseDeployResult— `digstore deploy --json` stdout → { capsule, storeId, root, chiaUrl,\n// digUrl, hubUrl, pushed }, deriving the URLs exactly as digstore does\n// (capsule = storeId:root; hub view = https://hub.dig.net/stores/<id>;\n// chiaUrl = the user-facing content-open address chia://<store>:<root>/,\n// matching digstore's printed `content_address`).\n\nimport type { ResolvedDeployConfig } from \"./config.js\";\nimport { DigSdkError } from \"../errors.js\";\n\n/** Knobs for argv construction. */\nexport interface DeployArgsOptions {\n /**\n * The adapter already ran the framework build, so don't hand `--build-command` to digstore (it\n * would rebuild). The output dir is staged as-is.\n */\n skipBuild?: boolean;\n}\n\n/**\n * Build the argv for `digstore <argv>` from a resolved config. Always `deploy --json`. Only flags\n * whose values are set are emitted. SECRETS (deployKey, salt) are intentionally excluded — they go\n * through the env (buildDeployEnv) so they never appear in the process table.\n */\nexport function buildDeployArgs(\n cfg: ResolvedDeployConfig,\n opts: DeployArgsOptions = {},\n): string[] {\n const argv: string[] = [\"deploy\", \"--json\"];\n if (cfg.storeId) argv.push(\"--store-id\", cfg.storeId);\n if (cfg.outputDir) argv.push(\"--output-dir\", cfg.outputDir);\n if (!opts.skipBuild && cfg.buildCommand) argv.push(\"--build-command\", cfg.buildCommand);\n if (cfg.message) argv.push(\"--message\", cfg.message);\n if (cfg.network) argv.push(\"--network\", cfg.network);\n if (cfg.remote) argv.push(\"--remote\", cfg.remote);\n if (cfg.waitTimeout != null) argv.push(\"--wait-timeout\", String(cfg.waitTimeout));\n return argv;\n}\n\n/**\n * The env overlay to merge onto the child process env: the SECRETS, passed out-of-band so they are\n * never visible on the command line. Returns only the keys that have a value.\n */\nexport function buildDeployEnv(cfg: ResolvedDeployConfig): Record<string, string> {\n const env: Record<string, string> = {};\n if (cfg.deployKey) env.DIGSTORE_DEPLOY_KEY = cfg.deployKey;\n if (cfg.salt) env.DIGSTORE_STORE_SALT = cfg.salt;\n return env;\n}\n\n/** The friendly, parsed outcome of a deploy. */\nexport interface DeployResult {\n /** `storeId:rootHash` — the capsule identity (the ecosystem-vocabulary id the user shares). */\n capsule: string;\n /** Store identity (64-hex). */\n storeId: string;\n /** The new on-chain root (64-hex). */\n root: string;\n /**\n * The user-facing content-open address `chia://<storeId>:<rootHash>/` — what a user types/clicks\n * to open this verified capsule in the DIG Browser / extension (the scheme they register). This\n * matches digstore deploy's printed `content_address` exactly. (Distinct from the §21 remote\n * locator `dig://<host>/<store_id>` and the `urn:dig:` namespace, which stay `dig://`.)\n */\n chiaUrl: string;\n /**\n * @deprecated Use {@link chiaUrl}. Kept as a back-compat alias for consumers that read `digUrl`;\n * it now carries the SAME `chia://<storeId>:<rootHash>/` content-open value (NOT a `dig://` URL).\n */\n digUrl: string;\n /** The human \"view it\" URL on DIGHUb (the same one `digstore deploy` prints). */\n hubUrl: string;\n /** Whether the capsule was pushed to DIGHUb (when the JSON reported it). */\n pushed?: boolean;\n}\n\nconst CAPSULE_RE = /^([0-9a-f]{64}):([0-9a-f]{64})$/i;\n\n/**\n * Parse `digstore deploy --json` stdout into a DeployResult. digstore emits a single JSON object\n * (with at least `capsule` and `root`); we also tolerate extra JSON log lines by scanning lines\n * bottom-up for the first object that carries a `capsule`. Throws a clear error if none is found or\n * the output isn't JSON at all.\n */\nexport function parseDeployResult(stdout: string): DeployResult {\n const lines = stdout\n .split(/\\r?\\n/)\n .map((l) => l.trim())\n .filter((l) => l.startsWith(\"{\") && l.endsWith(\"}\"));\n\n if (lines.length === 0) {\n throw new DigSdkError(\n \"DEPLOY_OUTPUT_UNPARSEABLE\",\n `could not parse digstore deploy output (no JSON object found). Output was:\\n${stdout.slice(0, 500)}`,\n { stdout: stdout.slice(0, 500) },\n );\n }\n\n // Prefer the LAST JSON object that has a capsule (deploy emits one final result object). Keep the\n // first parseable object as a fallback so the error message can show what digstore DID return.\n let obj: Record<string, unknown> | undefined;\n let fallback: Record<string, unknown> | undefined;\n for (let i = lines.length - 1; i >= 0; i--) {\n const line = lines[i];\n if (line === undefined) continue;\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(line) as Record<string, unknown>;\n } catch {\n continue; // not JSON — skip this line\n }\n if (typeof parsed.capsule === \"string\") {\n obj = parsed;\n break;\n }\n if (!fallback) fallback = parsed;\n }\n\n if (!obj) {\n if (fallback) {\n throw new DigSdkError(\n \"DEPLOY_OUTPUT_UNPARSEABLE\",\n `digstore deploy did not report a capsule (deploy may have failed). Output:\\n${JSON.stringify(fallback)}`,\n { output: fallback },\n );\n }\n throw new DigSdkError(\n \"DEPLOY_OUTPUT_UNPARSEABLE\",\n `could not parse digstore deploy output as JSON:\\n${stdout.slice(0, 500)}`,\n { stdout: stdout.slice(0, 500) },\n );\n }\n\n const capsule = obj.capsule as string;\n const m = CAPSULE_RE.exec(capsule);\n if (!m || m[1] === undefined || m[2] === undefined) {\n throw new DigSdkError(\n \"INVALID_ARGUMENT\",\n `digstore deploy reported a malformed capsule \"${capsule}\" (expected storeId:root)`,\n { value: capsule, expected: \"storeId:root\" },\n );\n }\n const storeId = m[1].toLowerCase();\n const root = (typeof obj.root === \"string\" ? obj.root : m[2]).toLowerCase();\n\n // The user-facing content-open address. Prefer the value digstore itself printed\n // (`content_address`, the single source of truth — digstore deploy.rs::branding::content_url) so\n // the SDK stays byte-identical to the CLI; otherwise derive it the same way digstore does:\n // chia://<storeId>:<rootHash>/ (trailing slash, no resource). This is what a user opens in the\n // DIG Browser/extension — NOT the §21 remote dig:// locator.\n const chiaUrl =\n typeof obj.content_address === \"string\"\n ? obj.content_address\n : `chia://${storeId}:${root}/`;\n\n return {\n capsule,\n storeId,\n root,\n chiaUrl,\n // Deprecated alias: same chia:// content-open value (back-compat for consumers reading digUrl).\n digUrl: chiaUrl,\n // Mirrors digstore deploy.rs::hub_url — the public DIGHUb view of an owned store.\n hubUrl: `https://hub.dig.net/stores/${storeId}`,\n pushed: typeof obj.pushed === \"boolean\" ? obj.pushed : undefined,\n };\n}\n","// The shared, Node-only deploy runner both framework adapters call on their `publish` step.\n//\n// It composes the pure pieces (load dig.toml → resolve config → build argv + env), spawns the\n// installed `digstore` binary with `deploy --json`, and parses the result into a friendly\n// DeployResult ({ capsule, chiaUrl, hubUrl }). It is intentionally thin: ALL deploy logic lives in\n// `digstore deploy` (the canonical deployer — advances the on-chain root, stages, pushes the\n// capsule); this only marshals config in and the result out.\n//\n// Node-only: it uses node:child_process / node:fs. The framework entrypoints import it lazily on\n// the publish path so importing the plugin in a browser/config context never pulls Node APIs.\n\nimport { resolveDeployConfig, type AdapterOptions } from \"./config.js\";\nimport { parseDigToml, type DigTomlConfig } from \"./dig-toml.js\";\nimport {\n buildDeployArgs,\n buildDeployEnv,\n parseDeployResult,\n type DeployArgsOptions,\n type DeployResult,\n} from \"./deploy.js\";\nimport { DigSdkError } from \"../errors.js\";\n\n/** Options for {@link runDeploy}. */\nexport interface RunDeployOptions extends AdapterOptions, DeployArgsOptions {\n /** Project root that holds `dig.toml` and the build output. Defaults to `process.cwd()`. */\n cwd?: string;\n /** The `digstore` executable. Defaults to `\"digstore\"` (must be on PATH). */\n digstoreBin?: string;\n /** Sink for human-readable progress. Defaults to `console.log`. */\n logger?: (line: string) => void;\n}\n\n/** Read `dig.toml` from `cwd` (returns {} when absent). */\nasync function readDigToml(cwd: string): Promise<DigTomlConfig> {\n const { readFile } = await import(\"node:fs/promises\");\n const path = await import(\"node:path\");\n try {\n const text = await readFile(path.join(cwd, \"dig.toml\"), \"utf8\");\n return parseDigToml(text);\n } catch {\n return {}; // no dig.toml — rely on options + env\n }\n}\n\n/**\n * Resolve config, run `digstore deploy --json`, and parse the capsule. Spawns `digstore` with the\n * SECRETS injected through the child env (never the argv). Rejects with digstore's stderr on\n * non-zero exit. Returns the parsed {@link DeployResult}.\n */\nexport async function runDeploy(options: RunDeployOptions = {}): Promise<DeployResult> {\n const cwd = options.cwd ?? process.cwd();\n const bin = options.digstoreBin ?? \"digstore\";\n const log = options.logger ?? ((l: string) => console.log(l));\n\n const digToml = await readDigToml(cwd);\n const cfg = resolveDeployConfig({\n options: {\n storeId: options.storeId,\n outputDir: options.outputDir,\n buildCommand: options.buildCommand,\n message: options.message,\n network: options.network,\n remote: options.remote,\n waitTimeout: options.waitTimeout,\n },\n digToml,\n env: process.env,\n });\n\n const argv = buildDeployArgs(cfg, { skipBuild: options.skipBuild });\n const childEnv = { ...process.env, ...buildDeployEnv(cfg) };\n\n log(`▶ digstore ${argv.filter((a) => a !== cfg.deployKey && a !== cfg.salt).join(\" \")}`);\n\n const { spawn } = await import(\"node:child_process\");\n const stdout = await new Promise<string>((resolve, reject) => {\n const child = spawn(bin, argv, {\n cwd,\n env: childEnv,\n // digstore reads no stdin here; capture stdout (the JSON) and stream stderr through.\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n shell: false,\n });\n let out = \"\";\n let err = \"\";\n child.stdout.on(\"data\", (d: Buffer) => {\n out += d.toString();\n });\n child.stderr.on(\"data\", (d: Buffer) => {\n err += d.toString();\n });\n child.on(\"error\", (e: Error) => {\n reject(\n new DigSdkError(\n \"DIGSTORE_NOT_FOUND\",\n `could not run \"${bin}\" — is digstore installed and on PATH? (${e.message})`,\n { bin },\n { cause: e },\n ),\n );\n });\n child.on(\"close\", (code: number | null) => {\n if (code === 0) resolve(out);\n else\n reject(\n new DigSdkError(\"DEPLOY_FAILED\", `digstore deploy failed (exit ${code}).\\n${err || out}`, {\n exitCode: code,\n stderr: err.slice(0, 2000),\n }),\n );\n });\n });\n\n const result = parseDeployResult(stdout);\n log(`✓ deployed capsule ${result.capsule}`);\n // chia:// is the user-facing content-open address (what they open in the DIG Browser/extension).\n log(` open ${result.chiaUrl}`);\n log(` view ${result.hubUrl}`);\n return result;\n}\n","// `@dignetwork/dig-sdk/next` — a Next.js static-export adapter for shipping to DIG.\n//\n// Next has no Vite-style `transformIndexHtml` hook, so the two jobs are surfaced as helpers a Next\n// project wires in:\n// 1. DEV: `digNextDevShimTag()` returns a ready `<script …>` string to drop into the app's\n// `<head>` (e.g. in `app/layout.tsx` or `_document`) so `next dev` has the SDK's `window.chia`\n// dev shim — the SAME injected-provider contract production uses. It guards on a real wallet\n// and is eval-free. Gate it on `process.env.NODE_ENV !== \"production\"` in your layout so it\n// ships only in dev.\n// 2. PUBLISH: `digDeploy()` ships the static-export output (`out/` by default — what\n// `next build` writes with `output: \"export\"`) to a DIG capsule via `digstore deploy --json`,\n// printing the chia:// content-open URL + the DIGHUb view URL. Call it from a `publish` script\n// after the build.\n//\n// Next is an OPTIONAL peer: this module imports nothing from \"next\". The publish runner is the\n// shared Node-only `runDeploy`.\n\nimport { devShimScript, type DevShimOptions } from \"./adapters/dev-shim.js\";\nimport type { AdapterOptions } from \"./adapters/config.js\";\nimport type { DeployResult } from \"./adapters/deploy.js\";\nimport { runDeploy } from \"./adapters/run.js\";\n\n/** Next static-export writes here by default (`output: \"export\"`). */\nconst NEXT_EXPORT_DIR = \"out\";\n\n/**\n * The raw dev-shim script BODY (no `<script>` tags) — for callers that inject it themselves (e.g.\n * via Next's `<Script id=… dangerouslySetInnerHTML>` or a custom `_document`).\n */\nexport function digNextDevShimScript(options: DevShimOptions = {}): string {\n return devShimScript(options);\n}\n\n/**\n * A ready-to-inline `<script>…</script>` tag carrying the dev shim. Drop into the app `<head>`\n * (guard on dev): e.g. in `app/layout.tsx`\n * `{process.env.NODE_ENV !== \"production\" && <head dangerouslySetInnerHTML={{ __html: digNextDevShimTag() }} />}`.\n * Prefer `digNextDevShimScript()` with Next's `<Script>` component when you can.\n */\nexport function digNextDevShimTag(options: DevShimOptions = {}): string {\n return `<script>${devShimScript(options)}</script>`;\n}\n\n/**\n * Deploy the Next static export to a DIG capsule. Call from a `publish` script AFTER\n * `next build` (with `output: \"export\"`). Defaults `outputDir` to `out` (Next's export dir); reads\n * `dig.toml` + env (DIGSTORE_*) for the rest. The adapter has already built, so digstore stages the\n * existing `out/` rather than rebuilding.\n */\nexport function digDeploy(options: AdapterOptions = {}): Promise<DeployResult> {\n return runDeploy({ ...options, outputDir: options.outputDir ?? NEXT_EXPORT_DIR, skipBuild: true });\n}\n\nexport default digDeploy;\n"]}
|