@cloudflare/vite-plugin 0.0.0-a7163b3a2 → 0.0.0-aa3675bf7

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/dist/index.js CHANGED
@@ -3,16 +3,6 @@ import assert7 from "node:assert";
3
3
  import * as fs4 from "node:fs";
4
4
  import * as path6 from "node:path";
5
5
  import { createMiddleware } from "@hattip/adapter-node";
6
- import { Miniflare } from "miniflare";
7
- import "vite";
8
-
9
- // src/cloudflare-environment.ts
10
- import assert from "node:assert";
11
- import { builtinModules } from "node:module";
12
- import * as vite2 from "vite";
13
-
14
- // src/node-js-compat.ts
15
- import { createRequire } from "node:module";
16
6
 
17
7
  // ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
18
8
  var comma = ",".charCodeAt(0);
@@ -1078,7 +1068,17 @@ var MagicString = class _MagicString {
1078
1068
  }
1079
1069
  };
1080
1070
 
1071
+ // src/index.ts
1072
+ import { Miniflare } from "miniflare";
1073
+ import * as vite6 from "vite";
1074
+
1075
+ // src/cloudflare-environment.ts
1076
+ import assert from "node:assert";
1077
+ import { builtinModules } from "node:module";
1078
+ import * as vite2 from "vite";
1079
+
1081
1080
  // src/node-js-compat.ts
1081
+ import { createRequire } from "node:module";
1082
1082
  import { getNodeCompat } from "miniflare";
1083
1083
  import * as unenv from "unenv";
1084
1084
  var require2 = createRequire(import.meta.url);
@@ -1169,9 +1169,16 @@ function resolveNodeAliases(source, workerConfig) {
1169
1169
  return alias;
1170
1170
  }
1171
1171
 
1172
+ // src/constants.ts
1173
+ var ROUTER_WORKER_NAME = "__router-worker__";
1174
+ var ASSET_WORKER_NAME = "__asset-worker__";
1175
+ var ASSET_WORKERS_COMPATIBILITY_DATE = "2024-10-04";
1176
+ var MODULE_TYPES = ["CompiledWasm"];
1177
+
1172
1178
  // src/shared.ts
1173
1179
  var UNKNOWN_HOST = "http://localhost";
1174
1180
  var INIT_PATH = "/__vite_plugin_cloudflare_init__";
1181
+ var MODULE_PATTERN = `__CLOUDFLARE_MODULE__(${MODULE_TYPES.join("|")})__(.*?)__`;
1175
1182
 
1176
1183
  // src/utils.ts
1177
1184
  import * as path from "node:path";
@@ -1284,6 +1291,7 @@ var cloudflareBuiltInModules = [
1284
1291
  "cloudflare:workers",
1285
1292
  "cloudflare:workflows"
1286
1293
  ];
1294
+ var defaultConditions = ["workerd", "module", "browser"];
1287
1295
  function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmentName) {
1288
1296
  return {
1289
1297
  resolve: {
@@ -1291,7 +1299,7 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1291
1299
  // dependencies as not external
1292
1300
  noExternal: true,
1293
1301
  // We want to use `workerd` package exports if available (e.g. for postgres).
1294
- conditions: ["workerd", "module", "browser", "development|production"]
1302
+ conditions: [...defaultConditions, "development|production"]
1295
1303
  },
1296
1304
  dev: {
1297
1305
  createEnvironment(name2, config) {
@@ -1302,7 +1310,11 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1302
1310
  createEnvironment(name2, config) {
1303
1311
  return new vite2.BuildEnvironment(name2, config);
1304
1312
  },
1313
+ target: "es2022",
1314
+ // We need to enable `emitAssets` in order to support additional modules defined by `rules`
1315
+ emitAssets: true,
1305
1316
  outDir: getOutputDirectory(userConfig, environmentName),
1317
+ copyPublicDir: false,
1306
1318
  ssr: true,
1307
1319
  rollupOptions: {
1308
1320
  // Note: vite starts dev pre-bundling crawling from either optimizeDeps.entries or rollupOptions.input
@@ -1323,6 +1335,7 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1323
1335
  ],
1324
1336
  esbuildOptions: {
1325
1337
  platform: "neutral",
1338
+ conditions: [...defaultConditions, "development"],
1326
1339
  resolveExtensions: [
1327
1340
  ".mjs",
1328
1341
  ".js",
@@ -1433,13 +1446,6 @@ function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
1433
1446
 
1434
1447
  // src/dev.ts
1435
1448
  import assert3 from "node:assert";
1436
-
1437
- // src/constants.ts
1438
- var ROUTER_WORKER_NAME = "__router-worker__";
1439
- var ASSET_WORKER_NAME = "__asset-worker__";
1440
- var ASSET_WORKERS_COMPATIBILITY_DATE = "2024-10-04";
1441
-
1442
- // src/dev.ts
1443
1449
  function getDevEntryWorker(resolvedPluginConfig, miniflare) {
1444
1450
  const entryWorkerConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config : resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
1445
1451
  assert3(entryWorkerConfig, "Unexpected error: No entry worker configuration");
@@ -1637,10 +1643,13 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1637
1643
  ];
1638
1644
  const userWorkers = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1639
1645
  ([environmentName, workerConfig]) => {
1640
- const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions({
1641
- ...workerConfig,
1642
- assets: void 0
1643
- });
1646
+ const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
1647
+ {
1648
+ ...workerConfig,
1649
+ assets: void 0
1650
+ },
1651
+ resolvedPluginConfig.cloudflareEnv
1652
+ );
1644
1653
  const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1645
1654
  return {
1646
1655
  ...workerOptions,
@@ -1666,16 +1675,24 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1666
1675
  `Invalid invoke event: ${invokePayloadData.name}`
1667
1676
  );
1668
1677
  const [moduleId] = invokePayloadData.data;
1678
+ const moduleRE = new RegExp(MODULE_PATTERN);
1679
+ if (moduleRE.test(moduleId)) {
1680
+ const result2 = {
1681
+ externalize: moduleId,
1682
+ type: "module"
1683
+ };
1684
+ return MiniflareResponse.json({ result: result2 });
1685
+ }
1669
1686
  if (moduleId.startsWith("cloudflare:")) {
1670
1687
  const result2 = {
1671
1688
  externalize: moduleId,
1672
1689
  type: "builtin"
1673
1690
  };
1674
- return new MiniflareResponse(JSON.stringify({ result: result2 }));
1691
+ return MiniflareResponse.json({ result: result2 });
1675
1692
  }
1676
1693
  const devEnvironment = viteDevServer.environments[environmentName];
1677
1694
  const result = await devEnvironment.hot.handleInvoke(payload);
1678
- return new MiniflareResponse(JSON.stringify(result));
1695
+ return MiniflareResponse.json(result);
1679
1696
  }
1680
1697
  }
1681
1698
  };
@@ -1754,10 +1771,37 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1754
1771
  fileURLToPath(new URL(RUNNER_PATH, import.meta.url))
1755
1772
  )
1756
1773
  }
1757
- ]
1774
+ ],
1775
+ unsafeUseModuleFallbackService: true
1758
1776
  };
1759
1777
  })
1760
- ]
1778
+ ],
1779
+ unsafeModuleFallbackService(request) {
1780
+ const url = new URL(request.url);
1781
+ const rawSpecifier = url.searchParams.get("rawSpecifier");
1782
+ assert4(
1783
+ rawSpecifier,
1784
+ `Unexpected error: no specifier in request to module fallback service.`
1785
+ );
1786
+ const moduleRE = new RegExp(MODULE_PATTERN);
1787
+ const match = moduleRE.exec(rawSpecifier);
1788
+ assert4(match, `Unexpected error: no match for module ${rawSpecifier}.`);
1789
+ const [full, moduleType, modulePath] = match;
1790
+ assert4(
1791
+ modulePath,
1792
+ `Unexpected error: module path not found in reference ${full}.`
1793
+ );
1794
+ let source;
1795
+ try {
1796
+ source = fs2.readFileSync(modulePath);
1797
+ } catch (error) {
1798
+ throw new Error(`Import ${modulePath} not found. Does the file exist?`);
1799
+ }
1800
+ return MiniflareResponse.json({
1801
+ // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
1802
+ wasm: Array.from(source)
1803
+ });
1804
+ }
1761
1805
  };
1762
1806
  }
1763
1807
  function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
@@ -2064,20 +2108,21 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
2064
2108
  const configPaths = /* @__PURE__ */ new Set();
2065
2109
  const persistState = pluginConfig.persistState ?? true;
2066
2110
  const root = userConfig.root ? path5.resolve(userConfig.root) : process.cwd();
2067
- const { CLOUDFLARE_ENV } = vite5.loadEnv(viteEnv.mode, root, "");
2111
+ const { CLOUDFLARE_ENV: cloudflareEnv } = vite5.loadEnv(
2112
+ viteEnv.mode,
2113
+ root,
2114
+ /* prefixes */
2115
+ ""
2116
+ );
2068
2117
  const configPath = pluginConfig.configPath ? path5.resolve(root, pluginConfig.configPath) : findWranglerConfig(root);
2069
2118
  assert6(
2070
2119
  configPath,
2071
2120
  `Config not found. Have you created a wrangler.json(c) or wrangler.toml file?`
2072
2121
  );
2073
- const entryWorkerResolvedConfig = getWorkerConfig(
2074
- configPath,
2075
- CLOUDFLARE_ENV,
2076
- {
2077
- visitedConfigPaths: configPaths,
2078
- isEntryWorker: true
2079
- }
2080
- );
2122
+ const entryWorkerResolvedConfig = getWorkerConfig(configPath, cloudflareEnv, {
2123
+ visitedConfigPaths: configPaths,
2124
+ isEntryWorker: true
2125
+ });
2081
2126
  if (entryWorkerResolvedConfig.type === "assets-only") {
2082
2127
  return {
2083
2128
  type: "assets-only",
@@ -2086,7 +2131,8 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
2086
2131
  persistState,
2087
2132
  rawConfigs: {
2088
2133
  entryWorker: entryWorkerResolvedConfig
2089
- }
2134
+ },
2135
+ cloudflareEnv
2090
2136
  };
2091
2137
  }
2092
2138
  const entryWorkerConfig = entryWorkerResolvedConfig.config;
@@ -2098,7 +2144,7 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
2098
2144
  for (const auxiliaryWorker of pluginConfig.auxiliaryWorkers ?? []) {
2099
2145
  const workerResolvedConfig = getWorkerConfig(
2100
2146
  path5.resolve(root, auxiliaryWorker.configPath),
2101
- CLOUDFLARE_ENV,
2147
+ cloudflareEnv,
2102
2148
  {
2103
2149
  visitedConfigPaths: configPaths
2104
2150
  }
@@ -2126,7 +2172,8 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
2126
2172
  rawConfigs: {
2127
2173
  entryWorker: entryWorkerResolvedConfig,
2128
2174
  auxiliaryWorkers: auxiliaryWorkersResolvedConfigs
2129
- }
2175
+ },
2176
+ cloudflareEnv
2130
2177
  };
2131
2178
  }
2132
2179
 
@@ -2170,8 +2217,10 @@ ${event.error?.stack || event.error?.message}`,
2170
2217
  workerWebSocket.addEventListener("close", () => {
2171
2218
  clientWebSocket.close();
2172
2219
  });
2173
- clientWebSocket.on("message", (event) => {
2174
- workerWebSocket.send(event);
2220
+ clientWebSocket.on("message", (data, isBinary) => {
2221
+ workerWebSocket.send(
2222
+ isBinary ? Array.isArray(data) ? Buffer.concat(data) : data : data.toString()
2223
+ );
2175
2224
  });
2176
2225
  clientWebSocket.on("error", (error) => {
2177
2226
  logger.error(`WebSocket error:
@@ -2195,211 +2244,326 @@ function cloudflare2(pluginConfig = {}) {
2195
2244
  let resolvedViteConfig;
2196
2245
  let miniflare;
2197
2246
  let workersConfigsWarningShown = false;
2198
- return {
2199
- name: "vite-plugin-cloudflare",
2200
- config(userConfig, env2) {
2201
- if (env2.isPreview) {
2202
- return { appType: "custom" };
2203
- }
2204
- resolvedPluginConfig = resolvePluginConfig(pluginConfig, userConfig, env2);
2205
- if (!workersConfigsWarningShown) {
2206
- workersConfigsWarningShown = true;
2207
- const workersConfigsWarning = getWarningForWorkersConfigs(
2208
- resolvedPluginConfig.rawConfigs
2247
+ return [
2248
+ {
2249
+ name: "vite-plugin-cloudflare",
2250
+ config(userConfig, env2) {
2251
+ if (env2.isPreview) {
2252
+ return { appType: "custom" };
2253
+ }
2254
+ resolvedPluginConfig = resolvePluginConfig(
2255
+ pluginConfig,
2256
+ userConfig,
2257
+ env2
2209
2258
  );
2210
- if (workersConfigsWarning) {
2211
- console.warn(workersConfigsWarning);
2259
+ if (!workersConfigsWarningShown) {
2260
+ workersConfigsWarningShown = true;
2261
+ const workersConfigsWarning = getWarningForWorkersConfigs(
2262
+ resolvedPluginConfig.rawConfigs
2263
+ );
2264
+ if (workersConfigsWarning) {
2265
+ console.warn(workersConfigsWarning);
2266
+ }
2212
2267
  }
2213
- }
2214
- return {
2215
- appType: "custom",
2216
- resolve: {
2217
- alias: getNodeCompatAliases()
2218
- },
2219
- environments: resolvedPluginConfig.type === "workers" ? {
2220
- ...Object.fromEntries(
2221
- Object.entries(resolvedPluginConfig.workers).map(
2222
- ([environmentName, workerConfig]) => {
2223
- return [
2224
- environmentName,
2225
- createCloudflareEnvironmentOptions(
2226
- workerConfig,
2227
- userConfig,
2228
- environmentName
2268
+ return {
2269
+ appType: "custom",
2270
+ resolve: {
2271
+ alias: getNodeCompatAliases()
2272
+ },
2273
+ environments: resolvedPluginConfig.type === "workers" ? {
2274
+ ...Object.fromEntries(
2275
+ Object.entries(resolvedPluginConfig.workers).map(
2276
+ ([environmentName, workerConfig]) => {
2277
+ return [
2278
+ environmentName,
2279
+ createCloudflareEnvironmentOptions(
2280
+ workerConfig,
2281
+ userConfig,
2282
+ environmentName
2283
+ )
2284
+ ];
2285
+ }
2286
+ )
2287
+ ),
2288
+ client: {
2289
+ build: {
2290
+ outDir: getOutputDirectory(userConfig, "client")
2291
+ }
2292
+ }
2293
+ } : void 0,
2294
+ builder: {
2295
+ async buildApp(builder) {
2296
+ const clientEnvironment = builder.environments.client;
2297
+ const defaultHtmlPath = path6.resolve(
2298
+ builder.config.root,
2299
+ "index.html"
2300
+ );
2301
+ if (clientEnvironment && (clientEnvironment.config.build.rollupOptions.input || fs4.existsSync(defaultHtmlPath))) {
2302
+ await builder.build(clientEnvironment);
2303
+ }
2304
+ if (resolvedPluginConfig.type === "workers") {
2305
+ const workerEnvironments = Object.keys(
2306
+ resolvedPluginConfig.workers
2307
+ ).map((environmentName) => {
2308
+ const environment = builder.environments[environmentName];
2309
+ assert7(
2310
+ environment,
2311
+ `${environmentName} environment not found`
2312
+ );
2313
+ return environment;
2314
+ });
2315
+ await Promise.all(
2316
+ workerEnvironments.map(
2317
+ (environment) => builder.build(environment)
2229
2318
  )
2230
- ];
2319
+ );
2231
2320
  }
2232
- )
2233
- ),
2234
- client: {
2235
- build: {
2236
- outDir: getOutputDirectory(userConfig, "client")
2321
+ writeDeployConfig(resolvedPluginConfig, resolvedViteConfig);
2237
2322
  }
2238
2323
  }
2239
- } : void 0,
2240
- builder: {
2241
- async buildApp(builder) {
2242
- const clientEnvironment = builder.environments.client;
2243
- const defaultHtmlPath = path6.resolve(
2244
- builder.config.root,
2245
- "index.html"
2324
+ };
2325
+ },
2326
+ configResolved(config) {
2327
+ resolvedViteConfig = config;
2328
+ },
2329
+ async resolveId(source) {
2330
+ if (resolvedPluginConfig.type === "assets-only") {
2331
+ return;
2332
+ }
2333
+ const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2334
+ if (!workerConfig) {
2335
+ return;
2336
+ }
2337
+ return resolveNodeCompatId(this.environment, workerConfig, source);
2338
+ },
2339
+ async transform(code, id) {
2340
+ if (resolvedPluginConfig.type === "assets-only") {
2341
+ return;
2342
+ }
2343
+ const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2344
+ if (!workerConfig) {
2345
+ return;
2346
+ }
2347
+ const resolvedId = await this.resolve(workerConfig.main);
2348
+ if (id === resolvedId?.id) {
2349
+ return injectGlobalCode(id, code, workerConfig);
2350
+ }
2351
+ },
2352
+ generateBundle(_, bundle) {
2353
+ let config;
2354
+ if (resolvedPluginConfig.type === "workers") {
2355
+ const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2356
+ const entryChunk = Object.entries(bundle).find(
2357
+ ([_2, chunk]) => chunk.type === "chunk" && chunk.isEntry
2358
+ );
2359
+ if (!workerConfig || !entryChunk) {
2360
+ return;
2361
+ }
2362
+ workerConfig.main = entryChunk[0];
2363
+ const isEntryWorker = this.environment.name === resolvedPluginConfig.entryWorkerEnvironmentName;
2364
+ if (isEntryWorker && workerConfig.assets) {
2365
+ const workerOutputDirectory = this.environment.config.build.outDir;
2366
+ const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
2367
+ assert7(
2368
+ clientOutputDirectory,
2369
+ "Unexpected error: client output directory is undefined"
2246
2370
  );
2247
- if (clientEnvironment && (clientEnvironment.config.build.rollupOptions.input || fs4.existsSync(defaultHtmlPath))) {
2248
- await builder.build(clientEnvironment);
2249
- }
2250
- if (resolvedPluginConfig.type === "workers") {
2251
- const workerEnvironments = Object.keys(
2252
- resolvedPluginConfig.workers
2253
- ).map((environmentName) => {
2254
- const environment = builder.environments[environmentName];
2255
- assert7(environment, `${environmentName} environment not found`);
2256
- return environment;
2371
+ workerConfig.assets.directory = path6.relative(
2372
+ path6.resolve(resolvedViteConfig.root, workerOutputDirectory),
2373
+ path6.resolve(resolvedViteConfig.root, clientOutputDirectory)
2374
+ );
2375
+ }
2376
+ config = workerConfig;
2377
+ if (workerConfig.configPath) {
2378
+ const dotDevDotVarsContent = getDotDevDotVarsContent(
2379
+ workerConfig.configPath,
2380
+ resolvedPluginConfig.cloudflareEnv
2381
+ );
2382
+ if (dotDevDotVarsContent) {
2383
+ this.emitFile({
2384
+ type: "asset",
2385
+ fileName: ".dev.vars",
2386
+ source: dotDevDotVarsContent
2257
2387
  });
2258
- await Promise.all(
2259
- workerEnvironments.map(
2260
- (environment) => builder.build(environment)
2261
- )
2262
- );
2263
2388
  }
2264
- writeDeployConfig(resolvedPluginConfig, resolvedViteConfig);
2265
2389
  }
2390
+ } else if (this.environment.name === "client") {
2391
+ const assetsOnlyConfig = resolvedPluginConfig.config;
2392
+ assetsOnlyConfig.assets.directory = ".";
2393
+ const filesToAssetsIgnore = ["wrangler.json", ".dev.vars"];
2394
+ this.emitFile({
2395
+ type: "asset",
2396
+ fileName: ".assetsignore",
2397
+ source: `${filesToAssetsIgnore.join("\n")}
2398
+ `
2399
+ });
2400
+ config = assetsOnlyConfig;
2266
2401
  }
2267
- };
2268
- },
2269
- configResolved(config) {
2270
- resolvedViteConfig = config;
2271
- },
2272
- async resolveId(source) {
2273
- if (resolvedPluginConfig.type === "assets-only") {
2274
- return;
2275
- }
2276
- const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2277
- if (!workerConfig) {
2278
- return;
2279
- }
2280
- return resolveNodeCompatId(this.environment, workerConfig, source);
2281
- },
2282
- async transform(code, id) {
2283
- if (resolvedPluginConfig.type === "assets-only") {
2284
- return;
2285
- }
2286
- const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2287
- if (!workerConfig) {
2288
- return;
2289
- }
2290
- const resolvedId = await this.resolve(workerConfig.main);
2291
- if (id === resolvedId?.id) {
2292
- return injectGlobalCode(id, code, workerConfig);
2402
+ if (!config) {
2403
+ return;
2404
+ }
2405
+ config.no_bundle = true;
2406
+ config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
2407
+ if (config.unsafe && Object.keys(config.unsafe).length === 0) {
2408
+ config.unsafe = void 0;
2409
+ }
2410
+ this.emitFile({
2411
+ type: "asset",
2412
+ fileName: "wrangler.json",
2413
+ source: JSON.stringify(config)
2414
+ });
2415
+ },
2416
+ handleHotUpdate(options) {
2417
+ if (resolvedPluginConfig.configPaths.has(options.file)) {
2418
+ options.server.restart();
2419
+ }
2420
+ },
2421
+ async buildEnd() {
2422
+ if (miniflare) {
2423
+ await miniflare.dispose();
2424
+ miniflare = void 0;
2425
+ }
2426
+ },
2427
+ async configureServer(viteDevServer) {
2428
+ assert7(
2429
+ viteDevServer.httpServer,
2430
+ "Unexpected error: No Vite HTTP server"
2431
+ );
2432
+ miniflare = new Miniflare(
2433
+ getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
2434
+ );
2435
+ await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
2436
+ const entryWorker = await getDevEntryWorker(
2437
+ resolvedPluginConfig,
2438
+ miniflare
2439
+ );
2440
+ const middleware = createMiddleware(({ request }) => {
2441
+ return entryWorker.fetch(toMiniflareRequest(request), {
2442
+ redirect: "manual"
2443
+ });
2444
+ });
2445
+ handleWebSocket(
2446
+ viteDevServer.httpServer,
2447
+ entryWorker.fetch,
2448
+ viteDevServer.config.logger
2449
+ );
2450
+ return () => {
2451
+ viteDevServer.middlewares.use((req, res, next) => {
2452
+ middleware(req, res, next);
2453
+ });
2454
+ };
2455
+ },
2456
+ configurePreviewServer(vitePreviewServer) {
2457
+ const miniflare2 = new Miniflare(
2458
+ getPreviewMiniflareOptions(
2459
+ vitePreviewServer,
2460
+ pluginConfig.persistState ?? true
2461
+ )
2462
+ );
2463
+ const middleware = createMiddleware(({ request }) => {
2464
+ return miniflare2.dispatchFetch(toMiniflareRequest(request), {
2465
+ redirect: "manual"
2466
+ });
2467
+ });
2468
+ handleWebSocket(
2469
+ vitePreviewServer.httpServer,
2470
+ miniflare2.dispatchFetch,
2471
+ vitePreviewServer.config.logger
2472
+ );
2473
+ return () => {
2474
+ vitePreviewServer.middlewares.use((req, res, next) => {
2475
+ middleware(req, res, next);
2476
+ });
2477
+ };
2293
2478
  }
2294
2479
  },
2295
- generateBundle(_, bundle) {
2296
- let config;
2297
- if (resolvedPluginConfig.type === "workers") {
2298
- const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2299
- const entryChunk = Object.entries(bundle).find(
2300
- ([_2, chunk]) => chunk.type === "chunk" && chunk.isEntry
2480
+ // Plugin to support `CompiledWasm` modules
2481
+ {
2482
+ name: "vite-plugin-cloudflare:modules",
2483
+ // We set `enforce: "pre"` so that this plugin runs before the Vite core plugins.
2484
+ // Otherwise the `vite:wasm-fallback` plugin prevents the `.wasm` extension being used for module imports.
2485
+ enforce: "pre",
2486
+ applyToEnvironment(environment) {
2487
+ if (resolvedPluginConfig.type === "assets-only") {
2488
+ return false;
2489
+ }
2490
+ return Object.keys(resolvedPluginConfig.workers).includes(
2491
+ environment.name
2301
2492
  );
2302
- if (!workerConfig || !entryChunk) {
2493
+ },
2494
+ async resolveId(source, importer) {
2495
+ if (!source.endsWith(".wasm")) {
2303
2496
  return;
2304
2497
  }
2305
- workerConfig.main = entryChunk[0];
2306
- const isEntryWorker = this.environment.name === resolvedPluginConfig.entryWorkerEnvironmentName;
2307
- if (isEntryWorker && workerConfig.assets) {
2308
- const workerOutputDirectory = this.environment.config.build.outDir;
2309
- const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
2498
+ const resolved = await this.resolve(source, importer);
2499
+ assert7(
2500
+ resolved,
2501
+ `Unexpected error: could not resolve Wasm module ${source}`
2502
+ );
2503
+ return {
2504
+ external: true,
2505
+ id: createModuleReference("CompiledWasm", resolved.id)
2506
+ };
2507
+ },
2508
+ renderChunk(code, chunk) {
2509
+ const moduleRE = new RegExp(MODULE_PATTERN, "g");
2510
+ let match;
2511
+ let magicString;
2512
+ while (match = moduleRE.exec(code)) {
2513
+ magicString ??= new MagicString(code);
2514
+ const [full, moduleType, modulePath] = match;
2310
2515
  assert7(
2311
- clientOutputDirectory,
2312
- "Unexpected error: client output directory is undefined"
2516
+ modulePath,
2517
+ `Unexpected error: module path not found in reference ${full}.`
2313
2518
  );
2314
- workerConfig.assets.directory = path6.relative(
2315
- path6.resolve(resolvedViteConfig.root, workerOutputDirectory),
2316
- path6.resolve(resolvedViteConfig.root, clientOutputDirectory)
2519
+ let source;
2520
+ try {
2521
+ source = fs4.readFileSync(modulePath);
2522
+ } catch (error) {
2523
+ throw new Error(
2524
+ `Import ${modulePath} not found. Does the file exist?`
2525
+ );
2526
+ }
2527
+ const referenceId = this.emitFile({
2528
+ type: "asset",
2529
+ name: path6.basename(modulePath),
2530
+ originalFileName: modulePath,
2531
+ source
2532
+ });
2533
+ const emittedFileName = this.getFileName(referenceId);
2534
+ const relativePath = vite6.normalizePath(
2535
+ path6.relative(path6.dirname(chunk.fileName), emittedFileName)
2536
+ );
2537
+ const importPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2538
+ magicString.update(
2539
+ match.index,
2540
+ match.index + full.length,
2541
+ importPath
2317
2542
  );
2318
2543
  }
2319
- config = workerConfig;
2320
- } else if (this.environment.name === "client") {
2321
- const assetsOnlyConfig = resolvedPluginConfig.config;
2322
- assetsOnlyConfig.assets.directory = ".";
2323
- this.emitFile({
2324
- type: "asset",
2325
- fileName: ".assetsignore",
2326
- source: "wrangler.json"
2327
- });
2328
- config = assetsOnlyConfig;
2329
- }
2330
- if (!config) {
2331
- return;
2332
- }
2333
- config.no_bundle = true;
2334
- config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
2335
- config.unsafe = void 0;
2336
- this.emitFile({
2337
- type: "asset",
2338
- fileName: "wrangler.json",
2339
- source: JSON.stringify(config)
2340
- });
2341
- },
2342
- handleHotUpdate(options) {
2343
- if (resolvedPluginConfig.configPaths.has(options.file)) {
2344
- options.server.restart();
2345
- }
2346
- },
2347
- async buildEnd() {
2348
- if (miniflare) {
2349
- await miniflare.dispose();
2350
- miniflare = void 0;
2544
+ if (magicString) {
2545
+ return {
2546
+ code: magicString.toString(),
2547
+ map: this.environment.config.build.sourcemap ? magicString.generateMap({ hires: "boundary" }) : null
2548
+ };
2549
+ }
2351
2550
  }
2352
- },
2353
- async configureServer(viteDevServer) {
2354
- assert7(viteDevServer.httpServer, "Unexpected error: No Vite HTTP server");
2355
- miniflare = new Miniflare(
2356
- getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
2357
- );
2358
- await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
2359
- const entryWorker = await getDevEntryWorker(
2360
- resolvedPluginConfig,
2361
- miniflare
2362
- );
2363
- const middleware = createMiddleware(({ request }) => {
2364
- return entryWorker.fetch(toMiniflareRequest(request), {
2365
- redirect: "manual"
2366
- });
2367
- });
2368
- handleWebSocket(
2369
- viteDevServer.httpServer,
2370
- entryWorker.fetch,
2371
- viteDevServer.config.logger
2372
- );
2373
- return () => {
2374
- viteDevServer.middlewares.use((req, res, next) => {
2375
- middleware(req, res, next);
2376
- });
2377
- };
2378
- },
2379
- configurePreviewServer(vitePreviewServer) {
2380
- const miniflare2 = new Miniflare(
2381
- getPreviewMiniflareOptions(
2382
- vitePreviewServer,
2383
- pluginConfig.persistState ?? true
2384
- )
2385
- );
2386
- const middleware = createMiddleware(({ request }) => {
2387
- return miniflare2.dispatchFetch(toMiniflareRequest(request), {
2388
- redirect: "manual"
2389
- });
2390
- });
2391
- handleWebSocket(
2392
- vitePreviewServer.httpServer,
2393
- miniflare2.dispatchFetch,
2394
- vitePreviewServer.config.logger
2395
- );
2396
- return () => {
2397
- vitePreviewServer.middlewares.use((req, res, next) => {
2398
- middleware(req, res, next);
2399
- });
2400
- };
2401
2551
  }
2402
- };
2552
+ ];
2553
+ }
2554
+ function getDotDevDotVarsContent(configPath, cloudflareEnv) {
2555
+ const configDir = path6.dirname(configPath);
2556
+ const defaultDotDevDotVarsPath = `${configDir}/.dev.vars`;
2557
+ const inputDotDevDotVarsPath = `${defaultDotDevDotVarsPath}${cloudflareEnv ? `.${cloudflareEnv}` : ""}`;
2558
+ const targetPath = fs4.existsSync(inputDotDevDotVarsPath) ? inputDotDevDotVarsPath : fs4.existsSync(defaultDotDevDotVarsPath) ? defaultDotDevDotVarsPath : null;
2559
+ if (targetPath) {
2560
+ const dotDevDotVarsContent = fs4.readFileSync(targetPath);
2561
+ return dotDevDotVarsContent;
2562
+ }
2563
+ return null;
2564
+ }
2565
+ function createModuleReference(type, id) {
2566
+ return `__CLOUDFLARE_MODULE__${type}__${id}__`;
2403
2567
  }
2404
2568
  export {
2405
2569
  cloudflare2 as cloudflare