rspack-plugin-cloudflare 0.2.0 → 0.4.0

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 CHANGED
@@ -4,7 +4,7 @@
4
4
  [![CI](https://github.com/Cherry/rspack-plugin-cloudflare/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/Cherry/rspack-plugin-cloudflare/actions/workflows/ci.yml)
5
5
  [![license](https://img.shields.io/npm/l/rspack-plugin-cloudflare)](./LICENSE)
6
6
 
7
- Run Cloudflare Workers in workerd while developing with `rspack serve`, with hot module replacement inside the Worker, and build them alongside the client with `rspack build`. It's the rspack counterpart to `@cloudflare/vite-plugin`, and it reads the same Wrangler config.
7
+ Run Cloudflare Workers in workerd while developing with `rspack serve`, with hot module replacement inside the Worker, and build them alongside the client with `rspack build`. It's the rspack counterpart to `@cloudflare/vite-plugin`, and it reads the same Wrangler config or `cloudflare.config.ts`.
8
8
 
9
9
  > [!NOTE]
10
10
  > **Heads-up:** this project was primarily AI-authored. The plugin, its tests, and this README were written by AI coding agents in interactive sessions, with a human operator directing the work, reviewing output, and validating it against real rspack and Wrangler projects. Read the code before trusting it in production.
@@ -30,7 +30,7 @@ export default {
30
30
  };
31
31
  ```
32
32
 
33
- The Worker is configured in your existing `wrangler.toml` / `wrangler.json(c)`, found by walking up from rspack's `context`.
33
+ The Worker is configured in your existing `wrangler.toml` / `wrangler.json(c)` or a [`cloudflare.config.ts`](#cloudflareconfigts), found by walking up from rspack's `context`.
34
34
 
35
35
  | Command | What happens |
36
36
  | --- | --- |
@@ -41,11 +41,44 @@ The Worker is configured in your existing `wrangler.toml` / `wrangler.json(c)`,
41
41
 
42
42
  Set `CLOUDFLARE_ENV` to pick a Wrangler environment for dev and build, as with the Vite plugin.
43
43
 
44
+ `minify = true` in the Wrangler config minifies the Worker in `rspack build`, since `wrangler deploy` no longer bundles it. Dev stays unminified, and source maps are uploaded either way unless `upload_source_maps = false`.
45
+
46
+ ### cloudflare.config.ts
47
+
48
+ The TypeScript config the Vite plugin uses works too, loaded with the same `@cloudflare/config` package wrangler uses for `--experimental-new-config`:
49
+
50
+ ```ts
51
+ // cloudflare.config.ts
52
+ import { bindings, defineConfig } from 'cf/config';
53
+ import * as entrypoint from './worker/index.ts' with { type: 'cf-worker' };
54
+
55
+ export default defineConfig({
56
+ worker: {
57
+ name: 'my-worker',
58
+ entrypoint,
59
+ compatibilityDate: '2026-10-23',
60
+ env: {
61
+ ASSETS: bindings.assets(),
62
+ KV: bindings.kv({ id: '<namespace id>' }),
63
+ },
64
+ },
65
+ });
66
+ ```
67
+
68
+ - It's converted into the same config a Wrangler file gives, so everything else in this README applies, and `rspack build` still writes a `wrangler.json` that a plain `wrangler deploy` reads.
69
+ - `cloudflare.config.ts` doesn't name an assets directory, so it uses rspack's `output.path`, the same as Vite using its client build. Use the `config` option to point it somewhere else, for example `config: { assets: { directory: 'build' } }`.
70
+ - `CLOUDFLARE_ENV` (or `environment`) becomes the config's `mode`, since it has no Wrangler environments.
71
+ - Editing the config, or any local file it imports, rebuilds the Worker in dev.
72
+ - A project with both `cloudflare.config.ts` and a Wrangler config next to each other is an error. Pick one with `configPath`.
73
+ - `wrangler.config.ts` and generating types from the config aren't supported yet.
74
+
75
+ `cloudflare.config.ts` and `cf/config` are still experimental upstream, so expect them to change with wrangler releases.
76
+
44
77
  ### Options
45
78
 
46
79
  | Option | Default | |
47
80
  | --- | --- | --- |
48
- | `configPath` | nearest wrangler config | Wrangler config, relative to `context` |
81
+ | `configPath` | nearest config | `cloudflare.config.ts` or Wrangler config, relative to `context` |
49
82
  | `config` | | Overrides merged into the Wrangler config, or a function that edits it |
50
83
  | `environment` | `CLOUDFLARE_ENV` | Wrangler environment, like `--env` |
51
84
  | `auxiliaryWorkers` | | `[{ configPath, config?, outputDir? }]`, more Workers the entry Worker reaches through service bindings |
@@ -75,7 +108,7 @@ The dev bundle includes rspack's HMR runtime. After a rebuild, the plugin asks t
75
108
 
76
109
  - Changed modules and their importers re-evaluate in place. Other modules keep their state, and Durable Objects keep their storage.
77
110
  - Exports are wrapped so workerd's startup bindings (default handlers, Durable Objects, named entrypoints, Workflows) always call the current code.
78
- - The Worker restarts instead when its exports change, its `.wasm`/`.bin` modules change, its Wrangler config or local secrets change, or an update can't be applied.
111
+ - The Worker restarts instead when its exports change, its `.wasm`/`.bin` modules change, its config or local secrets change, or an update can't be applied. A config that fails to load keeps the previous build serving until it's fixed.
79
112
 
80
113
  Uncaught errors come back as a page with a source-mapped stack, and Worker build errors show in the dev server's overlay.
81
114
 
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ type WorkerConfig = Unstable_Config;
4
4
  /** Overrides merged into the Wrangler config after it loads, or a function that edits or returns overrides. */
5
5
  type WorkerConfigCustomizer = Partial<WorkerConfig> | ((config: WorkerConfig) => Partial<WorkerConfig> | void);
6
6
  interface AuxiliaryWorkerOptions {
7
- /** Wrangler config for the auxiliary Worker, relative to the rspack `context`. */
7
+ /** `cloudflare.config.ts` or Wrangler config for the auxiliary Worker, relative to the rspack `context`. */
8
8
  configPath: string;
9
9
  /** Changes the auxiliary Worker's config in code, applied after its config file loads. */
10
10
  config?: WorkerConfigCustomizer;
@@ -18,7 +18,7 @@ interface TunnelOptions {
18
18
  allowedMail?: string[];
19
19
  }
20
20
  interface CloudflarePluginOptions {
21
- /** Wrangler config file, relative to the rspack `context`. Defaults to the nearest wrangler.jsonc, wrangler.json or wrangler.toml at or above `context`. */
21
+ /** `cloudflare.config.ts` or Wrangler config file, relative to the rspack `context`. Defaults to the nearest one at or above `context`. */
22
22
  configPath?: string;
23
23
  /** Changes the Worker config in code, applied after the config file loads. */
24
24
  config?: WorkerConfigCustomizer;
package/dist/index.js CHANGED
@@ -8,6 +8,8 @@ import { fileURLToPath } from "node:url";
8
8
  import { getCloudflarePreset } from "@cloudflare/unenv-preset";
9
9
  import * as miniflare from "miniflare";
10
10
  import { defineEnv } from "unenv";
11
+ import { convertToWranglerConfig, loadAndParseConfig } from "@cloudflare/config";
12
+ import { normalizeAndValidateConfig } from "@cloudflare/workers-utils";
11
13
  import { WebSocketServer } from "ws";
12
14
  import { cleanupContainers, createContainerDevPlan, generateContainerBuildId, prepareContainerImagesForDev, resolveDockerHost } from "@cloudflare/containers-shared";
13
15
  import { Readable } from "node:stream";
@@ -278,7 +280,7 @@ function createWorkerConfig(options) {
278
280
  }, { oneOf: getAssetRules(worker, textExtensions) }] },
279
281
  devtool: "source-map",
280
282
  optimization: {
281
- minimize: false,
283
+ minimize: Boolean(worker.config.minify) && !hot,
282
284
  emitOnErrors: false
283
285
  },
284
286
  plugins,
@@ -306,6 +308,7 @@ const OMITTED_CONFIG_KEYS = /* @__PURE__ */ new Set([
306
308
  "alias",
307
309
  "tsconfig",
308
310
  "find_additional_modules",
311
+ "minify",
309
312
  "base_dir",
310
313
  "preserve_file_names"
311
314
  ]);
@@ -419,7 +422,8 @@ async function buildWorkers(options) {
419
422
  }));
420
423
  }
421
424
  // src/config.ts
422
- const CONFIG_FILE_NAMES = [
425
+ const CLOUDFLARE_CONFIG_FILE_NAME = "cloudflare.config.ts";
426
+ const WRANGLER_CONFIG_FILE_NAMES = [
423
427
  "wrangler.jsonc",
424
428
  "wrangler.json",
425
429
  "wrangler.toml"
@@ -428,15 +432,49 @@ function findConfigPath(context, configPath) {
428
432
  if (configPath) return path.resolve(context, configPath);
429
433
  let directory = context;
430
434
  while (true) {
431
- for (const fileName of CONFIG_FILE_NAMES) {
432
- const candidate = path.join(directory, fileName);
433
- if (fs.existsSync(candidate)) return candidate;
435
+ const cloudflareConfigPath = path.join(directory, CLOUDFLARE_CONFIG_FILE_NAME);
436
+ const wranglerConfigPath = WRANGLER_CONFIG_FILE_NAMES.map((fileName) => path.join(directory, fileName)).find((candidate) => fs.existsSync(candidate));
437
+ if (fs.existsSync(cloudflareConfigPath)) {
438
+ if (wranglerConfigPath) throw new Error(`Found both ${cloudflareConfigPath} and ${wranglerConfigPath}. Remove one, or choose one with the \`configPath\` option.`);
439
+ return cloudflareConfigPath;
434
440
  }
441
+ if (wranglerConfigPath) return wranglerConfigPath;
435
442
  const parent = path.dirname(directory);
436
- if (parent === directory) throw new Error(`No Wrangler config found in ${context} or its parents. Looked for ${CONFIG_FILE_NAMES.join(", ")}.`);
443
+ if (parent === directory) throw new Error(`No Cloudflare config found in ${context} or its parents. Looked for ${[CLOUDFLARE_CONFIG_FILE_NAME, ...WRANGLER_CONFIG_FILE_NAMES].join(", ")}.`);
437
444
  directory = parent;
438
445
  }
439
446
  }
447
+ /** Loads `cloudflare.config.ts` into the same Config wrangler reads from its own files, the way `wrangler --experimental-new-config` does. */
448
+ async function readCloudflareConfig(configPath, mode, clientOutputPath) {
449
+ const { result, dependencies } = await loadAndParseConfig(configPath, {
450
+ isPreview: false,
451
+ mode
452
+ });
453
+ if (!result.success) {
454
+ const issues = result.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`);
455
+ throw new Error(`Invalid ${configPath}:\n${issues.join("\n")}`);
456
+ }
457
+ if (!result.data.worker) throw new Error(`${configPath} must define a Worker using the \`worker\` property.`);
458
+ const rawConfig = convertToWranglerConfig(result.data);
459
+ if (rawConfig.assets && clientOutputPath) rawConfig.assets.directory = clientOutputPath;
460
+ const { config, diagnostics } = normalizeAndValidateConfig(rawConfig, configPath, configPath, {}, true);
461
+ if (diagnostics.hasErrors()) throw new Error(diagnostics.renderErrors());
462
+ if (diagnostics.hasWarnings()) console.warn(diagnostics.renderWarnings());
463
+ return {
464
+ config,
465
+ configFiles: [.../* @__PURE__ */ new Set([configPath, ...dependencies])]
466
+ };
467
+ }
468
+ async function readConfig(configPath, environment, clientOutputPath) {
469
+ if (path.basename(configPath) === CLOUDFLARE_CONFIG_FILE_NAME) return readCloudflareConfig(configPath, environment, clientOutputPath);
470
+ return {
471
+ config: unstable_readConfig({
472
+ config: configPath,
473
+ env: environment
474
+ }, { preserveOriginalMain: true }),
475
+ configFiles: [configPath]
476
+ };
477
+ }
440
478
  function isInside(parent, child) {
441
479
  const relative = path.relative(parent, child);
442
480
  return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
@@ -457,13 +495,11 @@ function applyCustomizer(config, customizer) {
457
495
  const overrides = typeof customizer === "function" ? customizer(config) : customizer;
458
496
  if (overrides) mergeConfig(config, overrides);
459
497
  }
460
- function resolveWorker(context, options) {
498
+ /** Reads a Worker's config, with `clientOutputPath` (rspack's `output.path`) serving as the assets directory `cloudflare.config.ts` can't name. */
499
+ async function resolveWorker(context, options, clientOutputPath) {
461
500
  const configPath = findConfigPath(context, options.configPath);
462
501
  const environment = options.environment ?? process.env.CLOUDFLARE_ENV;
463
- const config = unstable_readConfig({
464
- config: configPath,
465
- env: environment
466
- }, { preserveOriginalMain: true });
502
+ const { config, configFiles } = await readConfig(configPath, environment, clientOutputPath);
467
503
  applyCustomizer(config, options.config);
468
504
  const rootDir = path.dirname(configPath);
469
505
  if (!config.main && !config.assets?.directory) throw new Error(`${configPath} needs a \`main\` Worker entry, or an \`assets.directory\` for an assets-only project.`);
@@ -477,6 +513,7 @@ function resolveWorker(context, options) {
477
513
  return {
478
514
  config,
479
515
  configPath,
516
+ configFiles,
480
517
  environment,
481
518
  name: config.name,
482
519
  main: config.main ? path.resolve(rootDir, config.main) : void 0,
@@ -486,18 +523,18 @@ function resolveWorker(context, options) {
486
523
  };
487
524
  }
488
525
  /** Resolves an auxiliary Worker, which only the entry Worker's service bindings reach, so it can't serve assets. */
489
- function resolveAuxiliaryWorker(context, options, auxiliary) {
490
- const worker = resolveWorker(context, {
526
+ async function resolveAuxiliaryWorker(context, options, auxiliary, clientOutputPath) {
527
+ const worker = await resolveWorker(context, {
491
528
  ...auxiliary,
492
529
  environment: options.environment
493
- });
530
+ }, clientOutputPath);
494
531
  if (!worker.main) throw new Error(`Auxiliary Worker config ${worker.configPath} needs a \`main\` entry.`);
495
532
  if (worker.assets) throw new Error(`Auxiliary Worker "${worker.name}" has \`assets\`, which only the entry Worker supports.`);
496
533
  return worker;
497
534
  }
498
535
  /** A resolver per Worker, entry first, so a config change can re-read just the Worker it belongs to. */
499
- function getWorkerResolvers(context, options) {
500
- return [() => resolveWorker(context, options), ...(options.auxiliaryWorkers ?? []).map((auxiliary) => () => resolveAuxiliaryWorker(context, options, auxiliary))];
536
+ function getWorkerResolvers(context, options, clientOutputPath) {
537
+ return [() => resolveWorker(context, options, clientOutputPath), ...(options.auxiliaryWorkers ?? []).map((auxiliary) => () => resolveAuxiliaryWorker(context, options, auxiliary, clientOutputPath))];
501
538
  }
502
539
  // workers-sdk/packages/workers-shared/utils/configuration/constants.ts
503
540
  const PERMITTED_STATUS_CODES = /* @__PURE__ */ new Set([
@@ -2688,7 +2725,7 @@ var DevWorker = class {
2688
2725
  this.#logger = options.logger;
2689
2726
  this.#events = options.events;
2690
2727
  this.#resolve = options.resolve;
2691
- this.#resolved = options.resolve();
2728
+ this.#resolved = options.resolved;
2692
2729
  }
2693
2730
  get #outputDir() {
2694
2731
  return path.join(this.#resolved.rootDir, ".wrangler", "rspack", this.#resolved.name);
@@ -2811,11 +2848,12 @@ var DevWorker = class {
2811
2848
  }
2812
2849
  });
2813
2850
  }
2814
- /** Re-reads the Wrangler config and rebuilds from scratch, since anything from `main` to bindings may have changed. */
2851
+ /** Re-reads the config and rebuilds from scratch, since anything from `main` to bindings may have changed. */
2815
2852
  async reload() {
2853
+ const resolved = await this.#resolve();
2816
2854
  await this.#closeWatcher();
2817
- this.#resolved = this.#resolve();
2818
- this.#restartReason = "its Wrangler config changed";
2855
+ this.#resolved = resolved;
2856
+ this.#restartReason = "its config changed";
2819
2857
  this.start();
2820
2858
  }
2821
2859
  /** Records that Miniflare is now running this Worker's latest build. */
@@ -3025,7 +3063,20 @@ function rewriteLegacyMiniflarePath(pathname) {
3025
3063
  return pathname;
3026
3064
  }
3027
3065
  /** Runs the entry Worker and any auxiliary Workers in one Miniflare, routing dev server requests like Cloudflare does. */
3028
- var DevSession = class {
3066
+ var DevSession = class DevSession {
3067
+ /** Reads every Worker's config before the session starts, since `cloudflare.config.ts` can only be loaded asynchronously. */
3068
+ static async create(options) {
3069
+ const workers = await Promise.all(options.resolvers.map(async (resolve) => {
3070
+ return {
3071
+ resolve,
3072
+ resolved: await resolve()
3073
+ };
3074
+ }));
3075
+ return new DevSession({
3076
+ ...options,
3077
+ workers
3078
+ });
3079
+ }
3029
3080
  #compiler;
3030
3081
  #options;
3031
3082
  #logger;
@@ -3035,7 +3086,8 @@ var DevSession = class {
3035
3086
  #assets;
3036
3087
  #miniflare;
3037
3088
  #inspectorPort;
3038
- #configWatchers = [];
3089
+ #configWatchers = /* @__PURE__ */ new Map();
3090
+ #pendingReloads = /* @__PURE__ */ new Map();
3039
3091
  #containerTags = /* @__PURE__ */ new Set();
3040
3092
  #removeContainersOnExit = () => removeContainers(getDockerPath(), this.#containerTags);
3041
3093
  #updated = /* @__PURE__ */ new Set();
@@ -3047,8 +3099,9 @@ var DevSession = class {
3047
3099
  this.#compiler = options.compiler;
3048
3100
  this.#options = options.pluginOptions;
3049
3101
  this.#logger = options.logger;
3050
- this.#workers = options.resolvers.map((resolve) => new DevWorker({
3102
+ this.#workers = options.workers.map(({ resolved, resolve }) => new DevWorker({
3051
3103
  compiler: options.compiler,
3104
+ resolved,
3052
3105
  resolve,
3053
3106
  pluginOptions: options.pluginOptions,
3054
3107
  logger: options.logger,
@@ -3267,32 +3320,40 @@ var DevSession = class {
3267
3320
  waitUntilValid: hooks.waitUntilValid
3268
3321
  });
3269
3322
  }
3270
- /** Rebuilds a Worker when its Wrangler config or local secrets change, like the Vite plugin restarting its server. */
3323
+ /** Rebuilds a Worker when its config, a file its config imports, or its local secrets change, like the Vite plugin restarting its server. */
3271
3324
  #watchConfigs() {
3272
- const pending = /* @__PURE__ */ new Map();
3273
- const reload = (worker) => {
3274
- clearTimeout(pending.get(worker));
3275
- pending.set(worker, setTimeout(() => {
3276
- pending.delete(worker);
3277
- this.#reloadWorker(worker).catch((error) => {
3278
- this.#logger.error(`Worker "${worker.name}" failed to reload its config:\n${String(error)}`);
3279
- });
3280
- }, 100));
3281
- };
3282
- const directories = new Set(this.#workers.map((worker) => worker.resolved.rootDir));
3283
- for (const directory of directories) this.#configWatchers.push(fs.watch(directory, (_event, fileName) => {
3284
- if (!fileName) return;
3285
- for (const worker of this.#workers) {
3286
- const { configPath, rootDir } = worker.resolved;
3287
- if (rootDir === directory && (fileName === path.basename(configPath) || SECRETS_FILE_RE.test(fileName))) reload(worker);
3288
- }
3289
- }));
3325
+ for (const worker of this.#workers) {
3326
+ const { configFiles, rootDir } = worker.resolved;
3327
+ for (const directory of [rootDir, ...configFiles.map((file) => path.dirname(file))]) if (!this.#configWatchers.has(directory)) this.#configWatchers.set(directory, fs.watch(directory, (_event, fileName) => this.#onConfigDirectoryChange(directory, fileName)));
3328
+ }
3329
+ }
3330
+ #onConfigDirectoryChange(directory, fileName) {
3331
+ if (!fileName) return;
3332
+ const filePath = path.join(directory, fileName);
3333
+ for (const worker of this.#workers) {
3334
+ const { configFiles, rootDir } = worker.resolved;
3335
+ if (configFiles.includes(filePath) || rootDir === directory && SECRETS_FILE_RE.test(fileName)) this.#scheduleReload(worker);
3336
+ }
3337
+ }
3338
+ #scheduleReload(worker) {
3339
+ clearTimeout(this.#pendingReloads.get(worker));
3340
+ this.#pendingReloads.set(worker, setTimeout(() => {
3341
+ this.#pendingReloads.delete(worker);
3342
+ this.#reloadWorker(worker).catch((error) => {
3343
+ this.#logger.error(`Worker "${worker.name}" failed to reload its config:\n${String(error)}`);
3344
+ });
3345
+ }, 100));
3290
3346
  }
3291
3347
  async #reloadWorker(worker) {
3292
3348
  this.#logger.info(`Worker "${worker.name}" config changed; rebuilding`);
3293
3349
  this.#openGate();
3294
- await worker.reload();
3295
- if (worker === this.#entry) this.#assets = this.#createDevAssets();
3350
+ try {
3351
+ await worker.reload();
3352
+ if (worker === this.#entry) this.#assets = this.#createDevAssets();
3353
+ } finally {
3354
+ this.#releaseGateIfIdle();
3355
+ }
3356
+ this.#watchConfigs();
3296
3357
  }
3297
3358
  async #upgrade(webSocketServer, url, req, socket, head) {
3298
3359
  const mf = await this.#ready();
@@ -3382,8 +3443,13 @@ var DevSession = class {
3382
3443
  });
3383
3444
  });
3384
3445
  }
3446
+ /** The entry Worker as its config was last read. */
3447
+ get entry() {
3448
+ return this.#entry.resolved;
3449
+ }
3385
3450
  async dispose() {
3386
- for (const watcher of this.#configWatchers) watcher.close();
3451
+ for (const watcher of this.#configWatchers.values()) watcher.close();
3452
+ for (const timeout of this.#pendingReloads.values()) clearTimeout(timeout);
3387
3453
  await Promise.all(this.#workers.map((worker) => worker.dispose()));
3388
3454
  await this.#miniflare?.dispose();
3389
3455
  this.#miniflare = void 0;
@@ -3516,9 +3582,10 @@ var CloudflarePlugin = class {
3516
3582
  constructor(options = {}) {
3517
3583
  this.options = options;
3518
3584
  }
3519
- async #openTunnel(server, entry, logger) {
3585
+ async #openTunnel(server, session, logger) {
3520
3586
  const { tunnel: tunnelOption } = this.options;
3521
- if (!entry || !tunnelOption) return;
3587
+ if (!session || !tunnelOption) return;
3588
+ const { entry } = await session;
3522
3589
  logger.warn("Starting a Cloudflare Tunnel: anyone with its URL can reach this dev server and its Worker's local bindings.");
3523
3590
  this.#tunnel = await startTunnel({
3524
3591
  origin: getDevServerOrigin(server),
@@ -3531,41 +3598,47 @@ var CloudflarePlugin = class {
3531
3598
  }
3532
3599
  apply(compiler) {
3533
3600
  const logger = compiler.getInfrastructureLogger(PLUGIN_NAME);
3534
- const resolvers = getWorkerResolvers(compiler.context, this.options);
3601
+ const resolvers = getWorkerResolvers(compiler.context, this.options, compiler.options.output.path);
3535
3602
  let session;
3536
3603
  const devServer = compiler.options.devServer;
3537
3604
  if (devServer) {
3538
3605
  const { setupMiddlewares, onListening } = devServer;
3539
3606
  devServer.setupMiddlewares = (middlewares, server) => {
3540
3607
  const result = setupMiddlewares ? setupMiddlewares(middlewares, server) : middlewares;
3541
- session = new DevSession({
3608
+ const activeSession = DevSession.create({
3542
3609
  compiler,
3543
3610
  resolvers,
3544
3611
  pluginOptions: this.options,
3545
3612
  logger
3613
+ }).then((created) => {
3614
+ created.start({
3615
+ waitUntilValid: () => new Promise((resolve) => {
3616
+ if (server.middleware) server.middleware.waitUntilValid(() => resolve());
3617
+ else resolve();
3618
+ }),
3619
+ sendToClients: (type, data) => {
3620
+ if (server.webSocketServer) server.sendMessage(server.webSocketServer.clients, type, data);
3621
+ }
3622
+ });
3623
+ return created;
3546
3624
  });
3547
- session.start({
3548
- waitUntilValid: () => new Promise((resolve) => {
3549
- if (server.middleware) server.middleware.waitUntilValid(() => resolve());
3550
- else resolve();
3551
- }),
3552
- sendToClients: (type, data) => {
3553
- if (server.webSocketServer) server.sendMessage(server.webSocketServer.clients, type, data);
3554
- }
3625
+ activeSession.catch((error) => {
3626
+ logger.error(`Workers failed to start:\n${String(error)}`);
3555
3627
  });
3556
- const activeSession = session;
3628
+ session = activeSession;
3557
3629
  const devMiddlewareIndex = result.findIndex((middleware) => typeof middleware === "object" && middleware.name === "@rspack/dev-middleware");
3558
3630
  result.splice(devMiddlewareIndex === -1 ? result.length : devMiddlewareIndex, 0, {
3559
3631
  name: PLUGIN_NAME,
3560
3632
  middleware: (req, res, next) => {
3561
- activeSession.handle(req, res, next).catch(next);
3633
+ activeSession.then((created) => created.handle(req, res, next)).catch(next);
3562
3634
  }
3563
3635
  });
3564
3636
  return result;
3565
3637
  };
3566
3638
  devServer.onListening = (server) => {
3567
- if (session && server.server) session.attachUpgradeHandler(server.server, getSocketPath(server));
3568
- if (this.options.tunnel) this.#openTunnel(server, resolvers[0]?.(), logger).catch((error) => {
3639
+ const httpServer = server.server;
3640
+ if (session && httpServer) session.then((created) => created.attachUpgradeHandler(httpServer, getSocketPath(server))).catch(() => {});
3641
+ if (this.options.tunnel) this.#openTunnel(server, session, logger).catch((error) => {
3569
3642
  logger.error(`Tunnel failed to start: ${error instanceof Error ? error.message : String(error)}`);
3570
3643
  });
3571
3644
  onListening?.(server);
@@ -3573,7 +3646,7 @@ var CloudflarePlugin = class {
3573
3646
  }
3574
3647
  let builtWorkers;
3575
3648
  compiler.hooks.beforeRun.tapPromise(PLUGIN_NAME, async () => {
3576
- const workers = resolvers.map((resolve) => resolve());
3649
+ const workers = await Promise.all(resolvers.map((resolve) => resolve()));
3577
3650
  await buildWorkers({
3578
3651
  compiler,
3579
3652
  workers,
@@ -3587,7 +3660,7 @@ var CloudflarePlugin = class {
3587
3660
  });
3588
3661
  compiler.hooks.shutdown.tapPromise(PLUGIN_NAME, async () => {
3589
3662
  this.#tunnel?.close();
3590
- await session?.dispose();
3663
+ await (await session?.catch(() => {}))?.dispose();
3591
3664
  });
3592
3665
  }
3593
3666
  };