rspack-plugin-cloudflare 0.3.0 → 0.4.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 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";
@@ -298,9 +300,6 @@ function createWorkerConfig(options) {
298
300
  const OMITTED_CONFIG_KEYS = /* @__PURE__ */ new Set([
299
301
  "configPath",
300
302
  "userConfigPath",
301
- "topLevelName",
302
- "definedEnvironments",
303
- "targetEnvironment",
304
303
  "build",
305
304
  "define",
306
305
  "alias",
@@ -420,7 +419,8 @@ async function buildWorkers(options) {
420
419
  }));
421
420
  }
422
421
  // src/config.ts
423
- const CONFIG_FILE_NAMES = [
422
+ const CLOUDFLARE_CONFIG_FILE_NAME = "cloudflare.config.ts";
423
+ const WRANGLER_CONFIG_FILE_NAMES = [
424
424
  "wrangler.jsonc",
425
425
  "wrangler.json",
426
426
  "wrangler.toml"
@@ -429,15 +429,49 @@ function findConfigPath(context, configPath) {
429
429
  if (configPath) return path.resolve(context, configPath);
430
430
  let directory = context;
431
431
  while (true) {
432
- for (const fileName of CONFIG_FILE_NAMES) {
433
- const candidate = path.join(directory, fileName);
434
- if (fs.existsSync(candidate)) return candidate;
432
+ const cloudflareConfigPath = path.join(directory, CLOUDFLARE_CONFIG_FILE_NAME);
433
+ const wranglerConfigPath = WRANGLER_CONFIG_FILE_NAMES.map((fileName) => path.join(directory, fileName)).find((candidate) => fs.existsSync(candidate));
434
+ if (fs.existsSync(cloudflareConfigPath)) {
435
+ if (wranglerConfigPath) throw new Error(`Found both ${cloudflareConfigPath} and ${wranglerConfigPath}. Remove one, or choose one with the \`configPath\` option.`);
436
+ return cloudflareConfigPath;
435
437
  }
438
+ if (wranglerConfigPath) return wranglerConfigPath;
436
439
  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(", ")}.`);
440
+ 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
441
  directory = parent;
439
442
  }
440
443
  }
444
+ /** Loads `cloudflare.config.ts` into the same Config wrangler reads from its own files, the way `wrangler --experimental-new-config` does. */
445
+ async function readCloudflareConfig(configPath, mode, clientOutputPath) {
446
+ const { result, dependencies } = await loadAndParseConfig(configPath, {
447
+ isPreview: false,
448
+ mode
449
+ });
450
+ if (!result.success) {
451
+ const issues = result.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`);
452
+ throw new Error(`Invalid ${configPath}:\n${issues.join("\n")}`);
453
+ }
454
+ if (!result.data.worker) throw new Error(`${configPath} must define a Worker using the \`worker\` property.`);
455
+ const rawConfig = convertToWranglerConfig(result.data);
456
+ if (rawConfig.assets && clientOutputPath) rawConfig.assets.directory = clientOutputPath;
457
+ const { config, diagnostics } = normalizeAndValidateConfig(rawConfig, configPath, configPath, {}, true);
458
+ if (diagnostics.hasErrors()) throw new Error(diagnostics.renderErrors());
459
+ if (diagnostics.hasWarnings()) console.warn(diagnostics.renderWarnings());
460
+ return {
461
+ config,
462
+ configFiles: [.../* @__PURE__ */ new Set([configPath, ...dependencies])]
463
+ };
464
+ }
465
+ async function readConfig(configPath, environment, clientOutputPath) {
466
+ if (path.basename(configPath) === CLOUDFLARE_CONFIG_FILE_NAME) return readCloudflareConfig(configPath, environment, clientOutputPath);
467
+ return {
468
+ config: unstable_readConfig({
469
+ config: configPath,
470
+ env: environment
471
+ }, { preserveOriginalMain: true }),
472
+ configFiles: [configPath]
473
+ };
474
+ }
441
475
  function isInside(parent, child) {
442
476
  const relative = path.relative(parent, child);
443
477
  return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
@@ -458,13 +492,11 @@ function applyCustomizer(config, customizer) {
458
492
  const overrides = typeof customizer === "function" ? customizer(config) : customizer;
459
493
  if (overrides) mergeConfig(config, overrides);
460
494
  }
461
- function resolveWorker(context, options) {
495
+ /** Reads a Worker's config, with `clientOutputPath` (rspack's `output.path`) serving as the assets directory `cloudflare.config.ts` can't name. */
496
+ async function resolveWorker(context, options, clientOutputPath) {
462
497
  const configPath = findConfigPath(context, options.configPath);
463
498
  const environment = options.environment ?? process.env.CLOUDFLARE_ENV;
464
- const config = unstable_readConfig({
465
- config: configPath,
466
- env: environment
467
- }, { preserveOriginalMain: true });
499
+ const { config, configFiles } = await readConfig(configPath, environment, clientOutputPath);
468
500
  applyCustomizer(config, options.config);
469
501
  const rootDir = path.dirname(configPath);
470
502
  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 +510,7 @@ function resolveWorker(context, options) {
478
510
  return {
479
511
  config,
480
512
  configPath,
513
+ configFiles,
481
514
  environment,
482
515
  name: config.name,
483
516
  main: config.main ? path.resolve(rootDir, config.main) : void 0,
@@ -487,18 +520,18 @@ function resolveWorker(context, options) {
487
520
  };
488
521
  }
489
522
  /** 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, {
523
+ async function resolveAuxiliaryWorker(context, options, auxiliary, clientOutputPath) {
524
+ const worker = await resolveWorker(context, {
492
525
  ...auxiliary,
493
526
  environment: options.environment
494
- });
527
+ }, clientOutputPath);
495
528
  if (!worker.main) throw new Error(`Auxiliary Worker config ${worker.configPath} needs a \`main\` entry.`);
496
529
  if (worker.assets) throw new Error(`Auxiliary Worker "${worker.name}" has \`assets\`, which only the entry Worker supports.`);
497
530
  return worker;
498
531
  }
499
532
  /** 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))];
533
+ function getWorkerResolvers(context, options, clientOutputPath) {
534
+ return [() => resolveWorker(context, options, clientOutputPath), ...(options.auxiliaryWorkers ?? []).map((auxiliary) => () => resolveAuxiliaryWorker(context, options, auxiliary, clientOutputPath))];
502
535
  }
503
536
  // workers-sdk/packages/workers-shared/utils/configuration/constants.ts
504
537
  const PERMITTED_STATUS_CODES = /* @__PURE__ */ new Set([
@@ -2689,7 +2722,7 @@ var DevWorker = class {
2689
2722
  this.#logger = options.logger;
2690
2723
  this.#events = options.events;
2691
2724
  this.#resolve = options.resolve;
2692
- this.#resolved = options.resolve();
2725
+ this.#resolved = options.resolved;
2693
2726
  }
2694
2727
  get #outputDir() {
2695
2728
  return path.join(this.#resolved.rootDir, ".wrangler", "rspack", this.#resolved.name);
@@ -2812,11 +2845,12 @@ var DevWorker = class {
2812
2845
  }
2813
2846
  });
2814
2847
  }
2815
- /** Re-reads the Wrangler config and rebuilds from scratch, since anything from `main` to bindings may have changed. */
2848
+ /** Re-reads the config and rebuilds from scratch, since anything from `main` to bindings may have changed. */
2816
2849
  async reload() {
2850
+ const resolved = await this.#resolve();
2817
2851
  await this.#closeWatcher();
2818
- this.#resolved = this.#resolve();
2819
- this.#restartReason = "its Wrangler config changed";
2852
+ this.#resolved = resolved;
2853
+ this.#restartReason = "its config changed";
2820
2854
  this.start();
2821
2855
  }
2822
2856
  /** Records that Miniflare is now running this Worker's latest build. */
@@ -3026,7 +3060,20 @@ function rewriteLegacyMiniflarePath(pathname) {
3026
3060
  return pathname;
3027
3061
  }
3028
3062
  /** Runs the entry Worker and any auxiliary Workers in one Miniflare, routing dev server requests like Cloudflare does. */
3029
- var DevSession = class {
3063
+ var DevSession = class DevSession {
3064
+ /** Reads every Worker's config before the session starts, since `cloudflare.config.ts` can only be loaded asynchronously. */
3065
+ static async create(options) {
3066
+ const workers = await Promise.all(options.resolvers.map(async (resolve) => {
3067
+ return {
3068
+ resolve,
3069
+ resolved: await resolve()
3070
+ };
3071
+ }));
3072
+ return new DevSession({
3073
+ ...options,
3074
+ workers
3075
+ });
3076
+ }
3030
3077
  #compiler;
3031
3078
  #options;
3032
3079
  #logger;
@@ -3036,7 +3083,8 @@ var DevSession = class {
3036
3083
  #assets;
3037
3084
  #miniflare;
3038
3085
  #inspectorPort;
3039
- #configWatchers = [];
3086
+ #configWatchers = /* @__PURE__ */ new Map();
3087
+ #pendingReloads = /* @__PURE__ */ new Map();
3040
3088
  #containerTags = /* @__PURE__ */ new Set();
3041
3089
  #removeContainersOnExit = () => removeContainers(getDockerPath(), this.#containerTags);
3042
3090
  #updated = /* @__PURE__ */ new Set();
@@ -3048,8 +3096,9 @@ var DevSession = class {
3048
3096
  this.#compiler = options.compiler;
3049
3097
  this.#options = options.pluginOptions;
3050
3098
  this.#logger = options.logger;
3051
- this.#workers = options.resolvers.map((resolve) => new DevWorker({
3099
+ this.#workers = options.workers.map(({ resolved, resolve }) => new DevWorker({
3052
3100
  compiler: options.compiler,
3101
+ resolved,
3053
3102
  resolve,
3054
3103
  pluginOptions: options.pluginOptions,
3055
3104
  logger: options.logger,
@@ -3268,32 +3317,40 @@ var DevSession = class {
3268
3317
  waitUntilValid: hooks.waitUntilValid
3269
3318
  });
3270
3319
  }
3271
- /** Rebuilds a Worker when its Wrangler config or local secrets change, like the Vite plugin restarting its server. */
3320
+ /** Rebuilds a Worker when its config, a file its config imports, or its local secrets change, like the Vite plugin restarting its server. */
3272
3321
  #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
- }));
3322
+ for (const worker of this.#workers) {
3323
+ const { configFiles, rootDir } = worker.resolved;
3324
+ 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)));
3325
+ }
3326
+ }
3327
+ #onConfigDirectoryChange(directory, fileName) {
3328
+ if (!fileName) return;
3329
+ const filePath = path.join(directory, fileName);
3330
+ for (const worker of this.#workers) {
3331
+ const { configFiles, rootDir } = worker.resolved;
3332
+ if (configFiles.includes(filePath) || rootDir === directory && SECRETS_FILE_RE.test(fileName)) this.#scheduleReload(worker);
3333
+ }
3334
+ }
3335
+ #scheduleReload(worker) {
3336
+ clearTimeout(this.#pendingReloads.get(worker));
3337
+ this.#pendingReloads.set(worker, setTimeout(() => {
3338
+ this.#pendingReloads.delete(worker);
3339
+ this.#reloadWorker(worker).catch((error) => {
3340
+ this.#logger.error(`Worker "${worker.name}" failed to reload its config:\n${String(error)}`);
3341
+ });
3342
+ }, 100));
3291
3343
  }
3292
3344
  async #reloadWorker(worker) {
3293
3345
  this.#logger.info(`Worker "${worker.name}" config changed; rebuilding`);
3294
3346
  this.#openGate();
3295
- await worker.reload();
3296
- if (worker === this.#entry) this.#assets = this.#createDevAssets();
3347
+ try {
3348
+ await worker.reload();
3349
+ if (worker === this.#entry) this.#assets = this.#createDevAssets();
3350
+ } finally {
3351
+ this.#releaseGateIfIdle();
3352
+ }
3353
+ this.#watchConfigs();
3297
3354
  }
3298
3355
  async #upgrade(webSocketServer, url, req, socket, head) {
3299
3356
  const mf = await this.#ready();
@@ -3383,8 +3440,13 @@ var DevSession = class {
3383
3440
  });
3384
3441
  });
3385
3442
  }
3443
+ /** The entry Worker as its config was last read. */
3444
+ get entry() {
3445
+ return this.#entry.resolved;
3446
+ }
3386
3447
  async dispose() {
3387
- for (const watcher of this.#configWatchers) watcher.close();
3448
+ for (const watcher of this.#configWatchers.values()) watcher.close();
3449
+ for (const timeout of this.#pendingReloads.values()) clearTimeout(timeout);
3388
3450
  await Promise.all(this.#workers.map((worker) => worker.dispose()));
3389
3451
  await this.#miniflare?.dispose();
3390
3452
  this.#miniflare = void 0;
@@ -3517,9 +3579,10 @@ var CloudflarePlugin = class {
3517
3579
  constructor(options = {}) {
3518
3580
  this.options = options;
3519
3581
  }
3520
- async #openTunnel(server, entry, logger) {
3582
+ async #openTunnel(server, session, logger) {
3521
3583
  const { tunnel: tunnelOption } = this.options;
3522
- if (!entry || !tunnelOption) return;
3584
+ if (!session || !tunnelOption) return;
3585
+ const { entry } = await session;
3523
3586
  logger.warn("Starting a Cloudflare Tunnel: anyone with its URL can reach this dev server and its Worker's local bindings.");
3524
3587
  this.#tunnel = await startTunnel({
3525
3588
  origin: getDevServerOrigin(server),
@@ -3532,41 +3595,47 @@ var CloudflarePlugin = class {
3532
3595
  }
3533
3596
  apply(compiler) {
3534
3597
  const logger = compiler.getInfrastructureLogger(PLUGIN_NAME);
3535
- const resolvers = getWorkerResolvers(compiler.context, this.options);
3598
+ const resolvers = getWorkerResolvers(compiler.context, this.options, compiler.options.output.path);
3536
3599
  let session;
3537
3600
  const devServer = compiler.options.devServer;
3538
3601
  if (devServer) {
3539
3602
  const { setupMiddlewares, onListening } = devServer;
3540
3603
  devServer.setupMiddlewares = (middlewares, server) => {
3541
3604
  const result = setupMiddlewares ? setupMiddlewares(middlewares, server) : middlewares;
3542
- session = new DevSession({
3605
+ const activeSession = DevSession.create({
3543
3606
  compiler,
3544
3607
  resolvers,
3545
3608
  pluginOptions: this.options,
3546
3609
  logger
3610
+ }).then((created) => {
3611
+ created.start({
3612
+ waitUntilValid: () => new Promise((resolve) => {
3613
+ if (server.middleware) server.middleware.waitUntilValid(() => resolve());
3614
+ else resolve();
3615
+ }),
3616
+ sendToClients: (type, data) => {
3617
+ if (server.webSocketServer) server.sendMessage(server.webSocketServer.clients, type, data);
3618
+ }
3619
+ });
3620
+ return created;
3547
3621
  });
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
- }
3622
+ activeSession.catch((error) => {
3623
+ logger.error(`Workers failed to start:\n${String(error)}`);
3556
3624
  });
3557
- const activeSession = session;
3625
+ session = activeSession;
3558
3626
  const devMiddlewareIndex = result.findIndex((middleware) => typeof middleware === "object" && middleware.name === "@rspack/dev-middleware");
3559
3627
  result.splice(devMiddlewareIndex === -1 ? result.length : devMiddlewareIndex, 0, {
3560
3628
  name: PLUGIN_NAME,
3561
3629
  middleware: (req, res, next) => {
3562
- activeSession.handle(req, res, next).catch(next);
3630
+ activeSession.then((created) => created.handle(req, res, next)).catch(next);
3563
3631
  }
3564
3632
  });
3565
3633
  return result;
3566
3634
  };
3567
3635
  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) => {
3636
+ const httpServer = server.server;
3637
+ if (session && httpServer) session.then((created) => created.attachUpgradeHandler(httpServer, getSocketPath(server))).catch(() => {});
3638
+ if (this.options.tunnel) this.#openTunnel(server, session, logger).catch((error) => {
3570
3639
  logger.error(`Tunnel failed to start: ${error instanceof Error ? error.message : String(error)}`);
3571
3640
  });
3572
3641
  onListening?.(server);
@@ -3574,7 +3643,7 @@ var CloudflarePlugin = class {
3574
3643
  }
3575
3644
  let builtWorkers;
3576
3645
  compiler.hooks.beforeRun.tapPromise(PLUGIN_NAME, async () => {
3577
- const workers = resolvers.map((resolve) => resolve());
3646
+ const workers = await Promise.all(resolvers.map((resolve) => resolve()));
3578
3647
  await buildWorkers({
3579
3648
  compiler,
3580
3649
  workers,
@@ -3588,7 +3657,7 @@ var CloudflarePlugin = class {
3588
3657
  });
3589
3658
  compiler.hooks.shutdown.tapPromise(PLUGIN_NAME, async () => {
3590
3659
  this.#tunnel?.close();
3591
- await session?.dispose();
3660
+ await (await session?.catch(() => {}))?.dispose();
3592
3661
  });
3593
3662
  }
3594
3663
  };