rspack-plugin-cloudflare 0.3.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
  | --- | --- |
@@ -43,11 +43,42 @@ Set `CLOUDFLARE_ENV` to pick a Wrangler environment for dev and build, as with t
43
43
 
44
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
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
+
46
77
  ### Options
47
78
 
48
79
  | Option | Default | |
49
80
  | --- | --- | --- |
50
- | `configPath` | nearest wrangler config | Wrangler config, relative to `context` |
81
+ | `configPath` | nearest config | `cloudflare.config.ts` or Wrangler config, relative to `context` |
51
82
  | `config` | | Overrides merged into the Wrangler config, or a function that edits it |
52
83
  | `environment` | `CLOUDFLARE_ENV` | Wrangler environment, like `--env` |
53
84
  | `auxiliaryWorkers` | | `[{ configPath, config?, outputDir? }]`, more Workers the entry Worker reaches through service bindings |
@@ -77,7 +108,7 @@ The dev bundle includes rspack's HMR runtime. After a rebuild, the plugin asks t
77
108
 
78
109
  - Changed modules and their importers re-evaluate in place. Other modules keep their state, and Durable Objects keep their storage.
79
110
  - Exports are wrapped so workerd's startup bindings (default handlers, Durable Objects, named entrypoints, Workflows) always call the current code.
80
- - 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.
81
112
 
82
113
  Uncaught errors come back as a page with a source-mapped stack, and Worker build errors show in the dev server's overlay.
83
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";
@@ -420,7 +422,8 @@ async function buildWorkers(options) {
420
422
  }));
421
423
  }
422
424
  // src/config.ts
423
- const CONFIG_FILE_NAMES = [
425
+ const CLOUDFLARE_CONFIG_FILE_NAME = "cloudflare.config.ts";
426
+ const WRANGLER_CONFIG_FILE_NAMES = [
424
427
  "wrangler.jsonc",
425
428
  "wrangler.json",
426
429
  "wrangler.toml"
@@ -429,15 +432,49 @@ function findConfigPath(context, configPath) {
429
432
  if (configPath) return path.resolve(context, configPath);
430
433
  let directory = context;
431
434
  while (true) {
432
- for (const fileName of CONFIG_FILE_NAMES) {
433
- const candidate = path.join(directory, fileName);
434
- 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;
435
440
  }
441
+ if (wranglerConfigPath) return wranglerConfigPath;
436
442
  const parent = path.dirname(directory);
437
- 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(", ")}.`);
438
444
  directory = parent;
439
445
  }
440
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
+ }
441
478
  function isInside(parent, child) {
442
479
  const relative = path.relative(parent, child);
443
480
  return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
@@ -458,13 +495,11 @@ function applyCustomizer(config, customizer) {
458
495
  const overrides = typeof customizer === "function" ? customizer(config) : customizer;
459
496
  if (overrides) mergeConfig(config, overrides);
460
497
  }
461
- 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) {
462
500
  const configPath = findConfigPath(context, options.configPath);
463
501
  const environment = options.environment ?? process.env.CLOUDFLARE_ENV;
464
- const config = unstable_readConfig({
465
- config: configPath,
466
- env: environment
467
- }, { preserveOriginalMain: true });
502
+ const { config, configFiles } = await readConfig(configPath, environment, clientOutputPath);
468
503
  applyCustomizer(config, options.config);
469
504
  const rootDir = path.dirname(configPath);
470
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.`);
@@ -478,6 +513,7 @@ function resolveWorker(context, options) {
478
513
  return {
479
514
  config,
480
515
  configPath,
516
+ configFiles,
481
517
  environment,
482
518
  name: config.name,
483
519
  main: config.main ? path.resolve(rootDir, config.main) : void 0,
@@ -487,18 +523,18 @@ function resolveWorker(context, options) {
487
523
  };
488
524
  }
489
525
  /** Resolves an auxiliary Worker, which only the entry Worker's service bindings reach, so it can't serve assets. */
490
- function resolveAuxiliaryWorker(context, options, auxiliary) {
491
- const worker = resolveWorker(context, {
526
+ async function resolveAuxiliaryWorker(context, options, auxiliary, clientOutputPath) {
527
+ const worker = await resolveWorker(context, {
492
528
  ...auxiliary,
493
529
  environment: options.environment
494
- });
530
+ }, clientOutputPath);
495
531
  if (!worker.main) throw new Error(`Auxiliary Worker config ${worker.configPath} needs a \`main\` entry.`);
496
532
  if (worker.assets) throw new Error(`Auxiliary Worker "${worker.name}" has \`assets\`, which only the entry Worker supports.`);
497
533
  return worker;
498
534
  }
499
535
  /** A resolver per Worker, entry first, so a config change can re-read just the Worker it belongs to. */
500
- function getWorkerResolvers(context, options) {
501
- 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))];
502
538
  }
503
539
  // workers-sdk/packages/workers-shared/utils/configuration/constants.ts
504
540
  const PERMITTED_STATUS_CODES = /* @__PURE__ */ new Set([
@@ -2689,7 +2725,7 @@ var DevWorker = class {
2689
2725
  this.#logger = options.logger;
2690
2726
  this.#events = options.events;
2691
2727
  this.#resolve = options.resolve;
2692
- this.#resolved = options.resolve();
2728
+ this.#resolved = options.resolved;
2693
2729
  }
2694
2730
  get #outputDir() {
2695
2731
  return path.join(this.#resolved.rootDir, ".wrangler", "rspack", this.#resolved.name);
@@ -2812,11 +2848,12 @@ var DevWorker = class {
2812
2848
  }
2813
2849
  });
2814
2850
  }
2815
- /** 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. */
2816
2852
  async reload() {
2853
+ const resolved = await this.#resolve();
2817
2854
  await this.#closeWatcher();
2818
- this.#resolved = this.#resolve();
2819
- this.#restartReason = "its Wrangler config changed";
2855
+ this.#resolved = resolved;
2856
+ this.#restartReason = "its config changed";
2820
2857
  this.start();
2821
2858
  }
2822
2859
  /** Records that Miniflare is now running this Worker's latest build. */
@@ -3026,7 +3063,20 @@ function rewriteLegacyMiniflarePath(pathname) {
3026
3063
  return pathname;
3027
3064
  }
3028
3065
  /** Runs the entry Worker and any auxiliary Workers in one Miniflare, routing dev server requests like Cloudflare does. */
3029
- 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
+ }
3030
3080
  #compiler;
3031
3081
  #options;
3032
3082
  #logger;
@@ -3036,7 +3086,8 @@ var DevSession = class {
3036
3086
  #assets;
3037
3087
  #miniflare;
3038
3088
  #inspectorPort;
3039
- #configWatchers = [];
3089
+ #configWatchers = /* @__PURE__ */ new Map();
3090
+ #pendingReloads = /* @__PURE__ */ new Map();
3040
3091
  #containerTags = /* @__PURE__ */ new Set();
3041
3092
  #removeContainersOnExit = () => removeContainers(getDockerPath(), this.#containerTags);
3042
3093
  #updated = /* @__PURE__ */ new Set();
@@ -3048,8 +3099,9 @@ var DevSession = class {
3048
3099
  this.#compiler = options.compiler;
3049
3100
  this.#options = options.pluginOptions;
3050
3101
  this.#logger = options.logger;
3051
- this.#workers = options.resolvers.map((resolve) => new DevWorker({
3102
+ this.#workers = options.workers.map(({ resolved, resolve }) => new DevWorker({
3052
3103
  compiler: options.compiler,
3104
+ resolved,
3053
3105
  resolve,
3054
3106
  pluginOptions: options.pluginOptions,
3055
3107
  logger: options.logger,
@@ -3268,32 +3320,40 @@ var DevSession = class {
3268
3320
  waitUntilValid: hooks.waitUntilValid
3269
3321
  });
3270
3322
  }
3271
- /** 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. */
3272
3324
  #watchConfigs() {
3273
- const pending = /* @__PURE__ */ new Map();
3274
- const reload = (worker) => {
3275
- clearTimeout(pending.get(worker));
3276
- pending.set(worker, setTimeout(() => {
3277
- pending.delete(worker);
3278
- this.#reloadWorker(worker).catch((error) => {
3279
- this.#logger.error(`Worker "${worker.name}" failed to reload its config:\n${String(error)}`);
3280
- });
3281
- }, 100));
3282
- };
3283
- const directories = new Set(this.#workers.map((worker) => worker.resolved.rootDir));
3284
- for (const directory of directories) this.#configWatchers.push(fs.watch(directory, (_event, fileName) => {
3285
- if (!fileName) return;
3286
- for (const worker of this.#workers) {
3287
- const { configPath, rootDir } = worker.resolved;
3288
- if (rootDir === directory && (fileName === path.basename(configPath) || SECRETS_FILE_RE.test(fileName))) reload(worker);
3289
- }
3290
- }));
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));
3291
3346
  }
3292
3347
  async #reloadWorker(worker) {
3293
3348
  this.#logger.info(`Worker "${worker.name}" config changed; rebuilding`);
3294
3349
  this.#openGate();
3295
- await worker.reload();
3296
- 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();
3297
3357
  }
3298
3358
  async #upgrade(webSocketServer, url, req, socket, head) {
3299
3359
  const mf = await this.#ready();
@@ -3383,8 +3443,13 @@ var DevSession = class {
3383
3443
  });
3384
3444
  });
3385
3445
  }
3446
+ /** The entry Worker as its config was last read. */
3447
+ get entry() {
3448
+ return this.#entry.resolved;
3449
+ }
3386
3450
  async dispose() {
3387
- 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);
3388
3453
  await Promise.all(this.#workers.map((worker) => worker.dispose()));
3389
3454
  await this.#miniflare?.dispose();
3390
3455
  this.#miniflare = void 0;
@@ -3517,9 +3582,10 @@ var CloudflarePlugin = class {
3517
3582
  constructor(options = {}) {
3518
3583
  this.options = options;
3519
3584
  }
3520
- async #openTunnel(server, entry, logger) {
3585
+ async #openTunnel(server, session, logger) {
3521
3586
  const { tunnel: tunnelOption } = this.options;
3522
- if (!entry || !tunnelOption) return;
3587
+ if (!session || !tunnelOption) return;
3588
+ const { entry } = await session;
3523
3589
  logger.warn("Starting a Cloudflare Tunnel: anyone with its URL can reach this dev server and its Worker's local bindings.");
3524
3590
  this.#tunnel = await startTunnel({
3525
3591
  origin: getDevServerOrigin(server),
@@ -3532,41 +3598,47 @@ var CloudflarePlugin = class {
3532
3598
  }
3533
3599
  apply(compiler) {
3534
3600
  const logger = compiler.getInfrastructureLogger(PLUGIN_NAME);
3535
- const resolvers = getWorkerResolvers(compiler.context, this.options);
3601
+ const resolvers = getWorkerResolvers(compiler.context, this.options, compiler.options.output.path);
3536
3602
  let session;
3537
3603
  const devServer = compiler.options.devServer;
3538
3604
  if (devServer) {
3539
3605
  const { setupMiddlewares, onListening } = devServer;
3540
3606
  devServer.setupMiddlewares = (middlewares, server) => {
3541
3607
  const result = setupMiddlewares ? setupMiddlewares(middlewares, server) : middlewares;
3542
- session = new DevSession({
3608
+ const activeSession = DevSession.create({
3543
3609
  compiler,
3544
3610
  resolvers,
3545
3611
  pluginOptions: this.options,
3546
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;
3547
3624
  });
3548
- session.start({
3549
- waitUntilValid: () => new Promise((resolve) => {
3550
- if (server.middleware) server.middleware.waitUntilValid(() => resolve());
3551
- else resolve();
3552
- }),
3553
- sendToClients: (type, data) => {
3554
- if (server.webSocketServer) server.sendMessage(server.webSocketServer.clients, type, data);
3555
- }
3625
+ activeSession.catch((error) => {
3626
+ logger.error(`Workers failed to start:\n${String(error)}`);
3556
3627
  });
3557
- const activeSession = session;
3628
+ session = activeSession;
3558
3629
  const devMiddlewareIndex = result.findIndex((middleware) => typeof middleware === "object" && middleware.name === "@rspack/dev-middleware");
3559
3630
  result.splice(devMiddlewareIndex === -1 ? result.length : devMiddlewareIndex, 0, {
3560
3631
  name: PLUGIN_NAME,
3561
3632
  middleware: (req, res, next) => {
3562
- activeSession.handle(req, res, next).catch(next);
3633
+ activeSession.then((created) => created.handle(req, res, next)).catch(next);
3563
3634
  }
3564
3635
  });
3565
3636
  return result;
3566
3637
  };
3567
3638
  devServer.onListening = (server) => {
3568
- if (session && server.server) session.attachUpgradeHandler(server.server, getSocketPath(server));
3569
- 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) => {
3570
3642
  logger.error(`Tunnel failed to start: ${error instanceof Error ? error.message : String(error)}`);
3571
3643
  });
3572
3644
  onListening?.(server);
@@ -3574,7 +3646,7 @@ var CloudflarePlugin = class {
3574
3646
  }
3575
3647
  let builtWorkers;
3576
3648
  compiler.hooks.beforeRun.tapPromise(PLUGIN_NAME, async () => {
3577
- const workers = resolvers.map((resolve) => resolve());
3649
+ const workers = await Promise.all(resolvers.map((resolve) => resolve()));
3578
3650
  await buildWorkers({
3579
3651
  compiler,
3580
3652
  workers,
@@ -3588,7 +3660,7 @@ var CloudflarePlugin = class {
3588
3660
  });
3589
3661
  compiler.hooks.shutdown.tapPromise(PLUGIN_NAME, async () => {
3590
3662
  this.#tunnel?.close();
3591
- await session?.dispose();
3663
+ await (await session?.catch(() => {}))?.dispose();
3592
3664
  });
3593
3665
  }
3594
3666
  };