miden-client-web 0.15.2

Web Client library that facilitates interaction with the Miden network
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
import rust from "@wasm-tool/rollup-plugin-rust";
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import copy from "rollup-plugin-copy";
import path from "node:path";

// `wasm-bindgen-rayon`'s `workerHelpers.js` lives at
//   <out-dir>/snippets/wasm-bindgen-rayon-XXX/src/workerHelpers.js
// and does `await import('../../..')`, expecting node-style directory
// resolution to find `<out-dir>/index.js`. Rollup doesn't auto-resolve
// directories to `index.js` for snippet imports (it errors EISDIR), so we
// need an explicit resolveId hook to map that path.
// Factory: returns a rollup plugin that emits a `workerHelpers.js` next to
// the Cargo-*.js chunk in this build's output. wasm-bindgen-rayon spawns
// rayon worker threads via `new Worker(new URL('./workerHelpers.js',
// import.meta.url), {type:'module'})` from inside the bundled Cargo-*.js.
// We've inlined the snippet (via wasmBindgenRayonSnippetResolver) so that
// sibling file would be missing without this. Webpack/Next.js then can't
// trace the URL and falls back to "Module not found".
const emitWorkerHelpers = (label) => ({
  name: `emit-worker-helpers-${label}`,
  generateBundle(_, bundle) {
    let cargoChunkName = null;
    for (const [name, chunk] of Object.entries(bundle)) {
      if (chunk.type !== "chunk") continue;
      if (
        chunk.code &&
        chunk.code.includes("wbg_rayon_start_worker") &&
        name.startsWith("Cargo-")
      ) {
        cargoChunkName = name;
        break;
      }
    }
    if (!cargoChunkName) {
      this.warn(
        `[emit-worker-helpers/${label}] no Cargo-*.js chunk found with wbg_rayon_start_worker`
      );
      return;
    }
    const shim = `// Auto-generated by rollup.config.js (emit-worker-helpers).
// Spawned by wasm-bindgen-rayon via:
//   new Worker(new URL('./workerHelpers.js', import.meta.url), {type:'module'})
// Imports the sibling Cargo chunk to get __wbg_init (default) and
// wbg_rayon_start_worker, then mirrors the message protocol from
// wasm-bindgen-rayon/src/workerHelpers.js.
function waitForMsgType(target, type) {
  return new Promise(resolve => {
    target.addEventListener('message', function onMsg({ data }) {
      if (data?.type !== type) return;
      target.removeEventListener('message', onMsg);
      resolve(data);
    });
  });
}
waitForMsgType(self, 'wasm_bindgen_worker_init').then(async ({ init, receiver }) => {
  const pkg = await import('./${cargoChunkName}');
  // Our build exports __wbg_init by name (the [remove-wasm-tla] plugin adds
  // it back so loadWasm() can call it explicitly). Stock wasm-bindgen-rayon
  // expects pkg.default  not present here, since rollup-plugin-rust's
  // bundler-mode output doesn't synthesize a default. Try named first, then
  // fall back to default for resilience.
  const initWasm = pkg.__wbg_init || pkg.default;
  if (typeof initWasm !== 'function') throw new Error('Cargo-*.js: no __wbg_init or default export');
  await initWasm(init);
  postMessage({ type: 'wasm_bindgen_worker_ready' });
  pkg.wbg_rayon_start_worker(receiver);
});
`;
    this.emitFile({
      type: "asset",
      fileName: "workerHelpers.js",
      source: shim,
    });
    console.log(`[emit-worker-helpers/${label}] -> ${cargoChunkName}`);
  },
});

// Rewrites the worker's static import `../../dist/wasm.js` to point at the
// variant-specific build output (`../../dist/${variant}/wasm.js`). The
// worker source has to use a static (non-templated) import since JS module
// imports can't take variables, but the actual file lives under a
// per-variant subdir. resolveId fires before rollup tries to load the file
// so the rewrite is transparent.
const rewriteWorkerWasmImport = {
  name: "rewrite-worker-wasm-import",
  resolveId(source, importer) {
    if (
      source === "../../dist/wasm.js" &&
      importer &&
      importer.includes("web-client-methods-worker.js")
    ) {
      return path.resolve(
        path.dirname(importer),
        "..",
        "..",
        distDir,
        "wasm.js"
      );
    }
    return null;
  },
};

const wasmBindgenRayonSnippetResolver = {
  name: "wasm-bindgen-rayon-snippet-resolver",
  // Use `order: 'pre'` so our resolveId fires BEFORE rollup-plugin-rust's
  // internal resolution, which otherwise resolves '../../..' from the snippet
  // to the wasm-bindgen output DIRECTORY (which rollup then fails to load
  // with EISDIR).
  resolveId: {
    order: "pre",
    handler(source, importer) {
      if (
        importer &&
        importer.includes("wasm-bindgen-rayon") &&
        importer.endsWith("workerHelpers.js")
      ) {
        console.log(`[wbr-resolver] source="${source}" importer="${importer}"`);
        if (source === "../../..") {
          // Importer like:
          //   .__rollup-plugin-rust__<crate>/snippets/wasm-bindgen-rayon-XXX/src/workerHelpers.js
          // '../../..' resolves to .__rollup-plugin-rust__<crate>/, the
          // wasm-bindgen output root. Redirect to its index.js.
          const target = path.resolve(
            path.dirname(importer),
            "../../..",
            "index.js"
          );
          console.log(`[wbr-resolver] REWRITE -> ${target}`);
          return target;
        }
      }
      return null;
    },
  },
};

// Build variant: "st" (single-threaded, works in any browser context) or
// "mt" (multi-threaded via wasm-bindgen-rayon, requires cross-origin
// isolation). The two variants ship to separate dist subdirs and are
// surfaced via package.json `exports` subpaths:
//
//   `@miden-sdk/miden-sdk`           → dist/st/eager.js
//   `@miden-sdk/miden-sdk/lazy`      → dist/st/index.js
//   `@miden-sdk/miden-sdk/mt`        → dist/mt/eager.js
//   `@miden-sdk/miden-sdk/mt/lazy`   → dist/mt/index.js
//
// The package.json build script invokes rollup twice (once per variant)
// to produce both subdirs. PR-CI builds may set MIDEN_BUILD_VARIANT=st
// for fast validation; release builds run both. Default is "st" — the
// safer fallback that loads anywhere — so that omitting the env var
// during local iteration produces the same artifact as v0.14.2.
const variant = process.env.MIDEN_BUILD_VARIANT || "st";
if (variant !== "st" && variant !== "mt") {
  throw new Error(
    `MIDEN_BUILD_VARIANT must be "st" or "mt" (got "${variant}")`
  );
}
const distDir = `dist/${variant}`;
const isMt = variant === "mt";

// Toolchain selection. The MT path needs the project-pinned nightly:
//   - `cfg(target_feature = "atomics")` only flips true on nightly. Stable
//     1.93 silently emits the +atomics bit but the cfg() check still says
//     false, so wasm-bindgen-rayon's compile_error! gate fires.
//   - `-Z build-std` (in mtOnlyCargoArgs below) is nightly-only.
// MT inherits the date-pinned nightly from rust-toolchain.toml — we leave
// RUSTUP_TOOLCHAIN unset for that path so the toolchain file takes effect.
//
// The ST path stays on stable: nothing in its dep graph requires nightly
// once `mt-threads` gates wasm-bindgen-rayon / rayon / concurrent out.
// We override RUSTUP_TOOLCHAIN=stable for ST only (rustup precedence:
// env > toolchain file). The cargo subprocess spawned by
// @wasm-tool/rollup-plugin-rust inherits this env.
if (!isMt) {
  process.env.RUSTUP_TOOLCHAIN = "stable";
}

// MT-only target rustflags. These set up the WASM module's atomics + shared
// memory imports that wasm-bindgen-rayon needs. Passed via cargo's
// `--config target.<triple>.rustflags=[...]` so they only apply to the MT
// build invocation. Previously these lived in `.cargo/config.toml` and
// applied unconditionally, which broke the ST build (stable cargo's
// precompiled rust-std-wasm32 has atomics disabled, so any std code path
// using atomics fails at link time).
const mtTargetRustflags = [
  // Target features: atomics + bulk-memory + mutable-globals are required
  // by wasm-bindgen-rayon. Plus `+simd128` — see commit 05dcac9b for the
  // earlier blanket-SIMD regression data. Re-enabled here paired with
  // `-C llvm-args=-vectorize-loops=false -vectorize-slp=false` to suppress
  // LLVM auto-vectorization. The earlier regression came from autovec
  // incorrectly vectorizing Goldilocks's u64 modular reduction (WASM v128 has no
  // widening 64×64 mul, so emulation costs more than scalar). With autovec
  // off, hand-written WASM-SIMD paths in libraries (BLAKE3, etc.) still
  // light up via `cfg(target_feature = "simd128")` while Goldilocks scalar
  // code stays scalar.
  //
  // Measured on testnet, ECDSA, M-series Mac, 10-cycle send/consume bench:
  //   median send:    4173 ms -> 3895 ms  (-6.7%)
  //   median consume: 4132 ms -> 3903 ms  (-5.5%)
  //   min send:       3795 ms -> 3325 ms  (-12%)
  //   min consume:    3799 ms -> 3499 ms  (-7.9%)
  // Variance widened (max-cycle outliers got worse), but typical-case prove
  // is faster. Net positive.
  //
  // The deeper win is upstream: hand-written std::arch::wasm32 intrinsics
  // for Goldilocks mul/reduce in p3-goldilocks (Plonky3). That's the only
  // change that closes the WASM-vs-native gap meaningfully; this flag
  // combo is a free incremental on top.
  "-C",
  "target-feature=+atomics,+bulk-memory,+mutable-globals,+simd128",
  "-C",
  "llvm-args=-vectorize-loops=false",
  "-C",
  "llvm-args=-vectorize-slp=false",
  // Linker flags: import a SHARED memory rather than defining one. Without
  // these the rayon worker spawn fails with "Memory could not be cloned"
  // (because a non-shared memory can't be postMessaged to a Worker).
  "-C",
  "link-arg=--shared-memory",
  "-C",
  "link-arg=--import-memory",
  // Per-thread TLS exports. wasm-bindgen-cli's threading-prep step rewrites
  // every export to call `__wasm_init_tls` first, but only if lld kept the
  // symbol. By default lld GCs them because no Rust code references them
  // directly.
  "-C",
  "link-arg=--export=__wasm_init_tls",
  "-C",
  "link-arg=--export=__tls_size",
  "-C",
  "link-arg=--export=__tls_align",
  "-C",
  "link-arg=--export=__tls_base",
  "-C",
  "link-arg=--max-memory=4294967296",
  "-C",
  "panic=abort",
  "--cfg",
  'getrandom_backend="wasm_js"',
];

// Flag that indicates if the build is meant for development purposes.
// If true, wasm-opt is not applied.
const devMode = process.env.MIDEN_WEB_DEV === "true";

// Flag that opts into the fast PR-CI build profile. When set, we override
// the implicit `release` profile flags that @wasm-tool/rollup-plugin-rust
// passes (lto=true, codegen-units=1) to instead use the lighter
// `release-fast` settings defined in the workspace Cargo.toml. We also skip
// the wasm-opt -O3 pass entirely, since post-link optimization adds another
// 1-2 minutes for output that PR CI doesn't ship. Trade is ~1.5x larger
// WASM and slightly slower runtime — fine for verification, not for the
// published artifact. The `verify-release-build` CI job continues to run
// without this flag so the canonical artifact is always exercised before
// release.
const fastBuild = process.env.MIDEN_FAST_BUILD === "true";

// Arguments to tell cargo to add full debug symbols
// to the generated .wasm file (dev mode only).
// Note: strip='none' is already set by cargoArgsLineTablesDebug.
const cargoArgsUseDebugSymbols = ["--config", "profile.release.debug='full'"];

// Lightweight debug info for readable stack traces (always applied).
// Produces function names and line numbers with minimal size overhead.
const cargoArgsLineTablesDebug = [
  "--config",
  "profile.release.debug='line-tables-only'",
  "--config",
  "profile.release.strip='none'",
];

// Override the lto/codegen-units flags that the plugin sets for `--release`.
// Cargo --config is last-wins, so these win over the plugin's defaults when
// MIDEN_FAST_BUILD is set. The values match `[profile.release-fast]` in the
// workspace Cargo.toml so the two stay in sync.
const cargoArgsFastBuild = [
  "--config",
  "profile.release.lto=false",
  "--config",
  "profile.release.codegen-units=16",
];

const wasmOptArgs = [
  // Strip DWARF sections before optimization to avoid binaryen crashes on
  // unsupported DWARF versions. The name section (function names) is kept.
  "--strip-dwarf",
  devMode ? "-O0" : "-O3",
  "--enable-bulk-memory",
  "--enable-nontrapping-float-to-int",
  // Threads: the WASM uses shared memory + atomics for the rayon thread
  // pool. Tell binaryen to leave those instructions alone instead of
  // either erroring or "optimizing" them into a non-shared form.
  "--enable-threads",
  // SIMD: required when the input WASM contains v128 instructions, which
  // it does once `+simd128` is on in mtTargetRustflags. Without this,
  // binaryen would refuse to process the module.
  "--enable-simd",
  // Preserve the name section through optimization passes.
  "--debuginfo",
];

// MT-only cargo args. For the MT build we additionally need:
// - `--features mt-threads` enables the optional wasm-bindgen-rayon + rayon
//   deps and miden-crypto/concurrent (cargo feature unification turns on
//   the parallel paths in Plonky3 / miden-tx via miden-protocol).
// - `--config target.wasm32-unknown-unknown.rustflags=[...]` injects the
//   atomics target feature + shared-memory linker flags + TLS exports.
//   Previously these lived in .cargo/config.toml unconditionally; moved
//   here so they only apply to the MT invocation. The `+atomics` target
//   feature requires `-Z build-std` (below) to recompile std with atomics
//   enabled — without it, the precompiled rust-std-wasm32 has atomics
//   disabled and wasm-bindgen-rayon's compile-time compile_error! gate
//   fires.
// - `-Z build-std=std,panic_abort` recompiles std (and panic_abort) from
//   rust-src for wasm32-unknown-unknown so std atomic ops link against
//   an atomics-enabled std. Nightly-only flag — the ST path uses the
//   precompiled stable rust-std-wasm32 instead.
const mtOnlyCargoArgs = isMt
  ? [
      "-Z",
      "build-std=std,panic_abort",
      "--features",
      "mt-threads",
      // Cargo --config accepts an inline TOML expression. Quote-wrap each
      // entry so spaces/commas in the rustflags array don't get mangled
      // by shell parsing. cargo expects the value as: `[ "-C", "...", ... ]`.
      "--config",
      `target.wasm32-unknown-unknown.rustflags=${JSON.stringify(mtTargetRustflags)}`,
    ]
  : [];

// Base cargo arguments shared by both ST and MT builds.
//
// The ST path stays on stable Rust: nothing in its dep graph
// (`miden-client` + `miden-protocol` + Plonky3 + idxdb-store, with the
// `mt-threads` feature gating wasm-bindgen-rayon / rayon / concurrent
// out) requires nightly. The CI workflow installs the precompiled
// rust-std-wasm32 binary for stable so this build links cleanly without
// `-Z build-std`. The MT path keeps nightly + `-Z build-std` (see
// mtOnlyCargoArgs above) — `+atomics` cfg requires nightly to flip true,
// and atomics-enabled std requires recompiling std from rust-src.
const baseCargoArgs = [
  "--features",
  // `browser` must be passed explicitly: the build runs with
  // `--no-default-features`, and the wasm_bindgen surface (plus the
  // idxdb-store backend) is gated behind the `browser` feature on the
  // dual browser/nodejs crate. Atomics-related rustflags are NOT part of
  // the base args — the ST variant must load in non-cross-origin-isolated
  // contexts on stable Rust; the MT variant adds them via mtOnlyCargoArgs.
  "browser,testing",
  "--no-default-features",
  // Always include line-tables-only debug info for readable stack traces.
  ...cargoArgsLineTablesDebug,
  // In dev mode, append full debug symbols AFTER line-tables-only.
  // Cargo uses last-wins semantics for repeated --config keys,
  // so debug='full' overrides debug='line-tables-only'.
]
  .concat(mtOnlyCargoArgs)
  .concat(devMode ? cargoArgsUseDebugSymbols : [])
  // Fast-build overrides come LAST so they win the last-wins race against
  // both the plugin's defaults and any earlier --config entries.
  .concat(fastBuild ? cargoArgsFastBuild : []);

/**
 * Rollup configuration file for building a Cargo project and creating a WebAssembly (WASM) module,
 * as well as bundling a dedicated web worker file.
 *
 * The configuration sets up three build processes:
 *
 * 1. **WASM Module Build:**
 *    Compiles Rust code into WASM using the @wasm-tool/rollup-plugin-rust plugin. This process
 *    applies specific cargo arguments to enable necessary WebAssembly features (such as atomics,
 *    bulk memory operations, and mutable globals) and to set maximum memory limits. For testing builds,
 *    the WASM optimization level is set to 0 to improve build times, reducing the feedback loop during development.
 *
 * 2. **Worker Build:**
 *    Bundles the dedicated web worker file (`web-client-methods-worker.js`) into the `dist/workers` directory.
 *    This configuration resolves WASM module imports and uses the copy plugin to ensure that the generated
 *    WASM assets are available to the worker.
 *
 * 3. **Main Entry Point Build:**
 *    Resolves and bundles the main JavaScript file (`index.js`) for the primary entry point of the application
 *    into the `dist` directory.
 *
 * Each build configuration outputs ES module format files with source maps to facilitate easier debugging.
 */
export default [
  {
    input: ["./js/wasm.js", "./js/index.js", "./js/eager.js"],
    output: {
      dir: distDir,
      format: "es",
      sourcemap: true,
      assetFileNames: "assets/[name][extname]",
    },
    plugins: [
      wasmBindgenRayonSnippetResolver,
      rust({
        verbose: true,
        extraArgs: {
          cargo: [...baseCargoArgs],
          // Skip wasm-opt entirely in fast mode — it's the post-link
          // optimization pass and accounts for ~1-2 min on its own. Empty
          // args array tells the plugin to bypass it. dev mode keeps -O0
          // for the same reason.
          wasmOpt: fastBuild ? [] : wasmOptArgs,
          wasmBindgen: ["--keep-debug"],
        },
        experimental: {
          typescriptDeclarationDir: `${distDir}/crates`,
        },
        optimize: { release: true, rustc: !devMode },
      }),
      resolve(),
      commonjs(),
      emitWorkerHelpers(distDir),
      // Convert the top-level `await __wbg_init(...)` to a non-blocking
      // exported Promise. This prevents the TLA from blocking WKWebView
      // module evaluation while still allowing the Worker (and anyone else)
      // to await WASM initialization explicitly via `wasmReady`.
      //
      // Before: `await __wbg_init({ module_or_path: url });`  (TLA — blocks)
      // After:  `var wasmReady = __wbg_init({ module_or_path: url });` (fire-and-forget)
      //         + exported as `wasmReady` for explicit awaiting
      {
        name: "remove-wasm-tla",
        generateBundle(_, bundle) {
          for (const [name, chunk] of Object.entries(bundle)) {
            if (chunk.type !== "chunk" || !chunk.code) continue;
            if (!chunk.code.includes("__wbg_init")) continue;
            const before = chunk.code.length;
            // Simply remove the TLA line
            chunk.code = chunk.code.replace(
              /\n\s*await __wbg_init\([^)]*\);\s*\n/g,
              "\n"
            );
            if (chunk.code.length !== before) {
              // Export __wbg_init and the WASM URL so loadWasm() can call
              // __wbg_init with the correct URL explicitly. The previous
              // "already exported?" guard checked `__wbg_init,` anywhere in
              // the file — but the wasm-bindgen output contains
              // `default: __wbg_init,` inside a frozen-namespace object, so
              // the guard fired a false-positive and the export-rewrite was
              // skipped, leaving __wbg_init unreachable. Detect the actual
              // top-level `export { ... }` token list instead.
              const exportListRe = /export \{([^}]+)\};(\s*)$/m;
              const m = chunk.code.match(exportListRe);
              const alreadyExported = m && /\b__wbg_init\b/.test(m[1]);
              if (!alreadyExported) {
                chunk.code = chunk.code.replace(
                  exportListRe,
                  "export { $1, __wbg_init, module$$1 as __wasm_url };$2"
                );
              }
              console.log(
                `[remove-wasm-tla] Stripped TLA from ${name} (added wbg_init export: ${!alreadyExported})`
              );
            }
          }
        },
      },
    ],
  },
  // Classic worker build.
  //
  // Safari/WKWebView is extremely slow with module workers ({type: "module"}),
  // so we ship a self-contained async-IIFE classic script alongside the module
  // variant below. `wrap-worker-classic` rewrites `import.meta.url` →
  // `self.location.href` (the only form a classic worker can see at runtime),
  // strips `export` clauses, and wraps the rollup ESM output in an async IIFE.
  //
  // Output: dist/{st,mt}/workers/web-client-methods-worker.js
  {
    input: "./js/workers/web-client-methods-worker.js",
    output: {
      dir: `${distDir}/workers`,
      format: "es",
      sourcemap: true,
      inlineDynamicImports: true,
    },
    plugins: [
      rewriteWorkerWasmImport,
      resolve(),
      commonjs(),
      copy({
        targets: [
          // Copy WASM into the worker's assets dir alongside the worker bundle
          {
            src: `${distDir}/assets/*.wasm`,
            dest: `${distDir}/workers/assets`,
          },
        ],
        verbose: true,
      }),
      // Wrap the worker in an async IIFE so it works as a classic script.
      // Replace ESM-only constructs (import.meta, export) with compatible alternatives.
      {
        name: "wrap-worker-classic",
        generateBundle(_, bundle) {
          for (const [, chunk] of Object.entries(bundle)) {
            if (chunk.type !== "chunk" || !chunk.code) continue;
            // Replace import.meta references for classic script compatibility.
            // Downstream bundlers (Vite) will transform these URLs before our
            // replacement runs, so the hashed paths are preserved.
            chunk.code = chunk.code.replace(
              /import\.meta\.url/g,
              "self.location.href"
            );
            chunk.code = chunk.code.replace(/import\.meta\.env/g, "undefined");
            chunk.code = chunk.code.replace(/^export\s*\{[^}]*\};?\s*$/gm, "");
            chunk.code = chunk.code.replace(
              /^export\s+default\s+/gm,
              "var _default = "
            );
            chunk.code = chunk.code.replace(
              /^export\s+(const|let|var|function|class|async)\s/gm,
              "$1 "
            );
            chunk.code = "(async function() {\n" + chunk.code + "\n})();";
          }
        },
      },
    ],
  },
  // Module worker build.
  //
  // Same input as above, but emitted as a plain ES module (.mjs) without the
  // classic IIFE wrapping. `import.meta.url` is preserved, which lets webpack
  // 5's asset tracer statically resolve `new URL("assets/miden_client_web.wasm",
  // import.meta.url)` inside the Cargo-bindgen glue and copy the WASM file into
  // the bundler's output correctly. Issue #2046: v0.14.1's classic-only worker
  // rewrites that reference to `self.location.href`, which webpack cannot trace,
  // producing a 404 on the WASM file for Next.js/webpack consumers.
  //
  // Output: dist/{st,mt}/workers/web-client-methods-worker.module.js
  {
    input: "./js/workers/web-client-methods-worker.js",
    output: {
      dir: `${distDir}/workers`,
      format: "es",
      sourcemap: true,
      // Two deliberate choices here:
      //
      // 1. NOT inlining dynamic imports. Keeping the
      //    `await import("./Cargo-*.js")` as a real dynamic ESM import
      //    lets webpack's module-graph analysis follow the Cargo glue and
      //    copy the sibling `miden_client_web.wasm` that the glue references
      //    via `new URL("assets/...", import.meta.url)`. With
      //    `inlineDynamicImports`, the URL literal ends up buried inside the
      //    worker bundle and webpack's worker sub-compilation never sees it
      //    as a graph dependency.
      //
      // 2. `.js` extension, not `.mjs`. Webpack 5 routes `.mjs` worker files
      //    through `type: "asset/resource"` (copy-only, no sub-compilation),
      //    so dynamic imports inside them never get chunked and runtime fetch
      //    404s on the Cargo glue. `.js` with `{ type: "module" }` on the
      //    Worker constructor triggers the proper worker sub-compilation and
      //    all chunking works. The `.module` infix disambiguates this file
      //    from the classic worker output that sits alongside it.
      entryFileNames: "[name].module.js",
    },
    plugins: [
      rewriteWorkerWasmImport,
      resolve(),
      commonjs(),
      emitWorkerHelpers(`${distDir}/workers`),
    ],
  },
];