@cloudflare/vite-plugin 0.0.6 → 0.0.7

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");
@@ -1669,16 +1675,24 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1669
1675
  `Invalid invoke event: ${invokePayloadData.name}`
1670
1676
  );
1671
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
+ }
1672
1686
  if (moduleId.startsWith("cloudflare:")) {
1673
1687
  const result2 = {
1674
1688
  externalize: moduleId,
1675
1689
  type: "builtin"
1676
1690
  };
1677
- return new MiniflareResponse(JSON.stringify({ result: result2 }));
1691
+ return MiniflareResponse.json({ result: result2 });
1678
1692
  }
1679
1693
  const devEnvironment = viteDevServer.environments[environmentName];
1680
1694
  const result = await devEnvironment.hot.handleInvoke(payload);
1681
- return new MiniflareResponse(JSON.stringify(result));
1695
+ return MiniflareResponse.json(result);
1682
1696
  }
1683
1697
  }
1684
1698
  };
@@ -1757,10 +1771,37 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1757
1771
  fileURLToPath(new URL(RUNNER_PATH, import.meta.url))
1758
1772
  )
1759
1773
  }
1760
- ]
1774
+ ],
1775
+ unsafeUseModuleFallbackService: true
1761
1776
  };
1762
1777
  })
1763
- ]
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
+ }
1764
1805
  };
1765
1806
  }
1766
1807
  function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
@@ -2176,8 +2217,10 @@ ${event.error?.stack || event.error?.message}`,
2176
2217
  workerWebSocket.addEventListener("close", () => {
2177
2218
  clientWebSocket.close();
2178
2219
  });
2179
- clientWebSocket.on("message", (event) => {
2180
- workerWebSocket.send(event);
2220
+ clientWebSocket.on("message", (data, isBinary) => {
2221
+ workerWebSocket.send(
2222
+ isBinary ? Array.isArray(data) ? Buffer.concat(data) : data : data.toString()
2223
+ );
2181
2224
  });
2182
2225
  clientWebSocket.on("error", (error) => {
2183
2226
  logger.error(`WebSocket error:
@@ -2201,228 +2244,312 @@ function cloudflare2(pluginConfig = {}) {
2201
2244
  let resolvedViteConfig;
2202
2245
  let miniflare;
2203
2246
  let workersConfigsWarningShown = false;
2204
- return {
2205
- name: "vite-plugin-cloudflare",
2206
- config(userConfig, env2) {
2207
- if (env2.isPreview) {
2208
- return { appType: "custom" };
2209
- }
2210
- resolvedPluginConfig = resolvePluginConfig(pluginConfig, userConfig, env2);
2211
- if (!workersConfigsWarningShown) {
2212
- workersConfigsWarningShown = true;
2213
- const workersConfigsWarning = getWarningForWorkersConfigs(
2214
- 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
2215
2258
  );
2216
- if (workersConfigsWarning) {
2217
- 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
+ }
2218
2267
  }
2219
- }
2220
- return {
2221
- appType: "custom",
2222
- resolve: {
2223
- alias: getNodeCompatAliases()
2224
- },
2225
- environments: resolvedPluginConfig.type === "workers" ? {
2226
- ...Object.fromEntries(
2227
- Object.entries(resolvedPluginConfig.workers).map(
2228
- ([environmentName, workerConfig]) => {
2229
- return [
2230
- environmentName,
2231
- createCloudflareEnvironmentOptions(
2232
- workerConfig,
2233
- userConfig,
2234
- 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)
2235
2318
  )
2236
- ];
2319
+ );
2237
2320
  }
2238
- )
2239
- ),
2240
- client: {
2241
- build: {
2242
- outDir: getOutputDirectory(userConfig, "client")
2321
+ writeDeployConfig(resolvedPluginConfig, resolvedViteConfig);
2243
2322
  }
2244
2323
  }
2245
- } : void 0,
2246
- builder: {
2247
- async buildApp(builder) {
2248
- const clientEnvironment = builder.environments.client;
2249
- const defaultHtmlPath = path6.resolve(
2250
- builder.config.root,
2251
- "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"
2252
2370
  );
2253
- if (clientEnvironment && (clientEnvironment.config.build.rollupOptions.input || fs4.existsSync(defaultHtmlPath))) {
2254
- await builder.build(clientEnvironment);
2255
- }
2256
- if (resolvedPluginConfig.type === "workers") {
2257
- const workerEnvironments = Object.keys(
2258
- resolvedPluginConfig.workers
2259
- ).map((environmentName) => {
2260
- const environment = builder.environments[environmentName];
2261
- assert7(environment, `${environmentName} environment not found`);
2262
- 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
2263
2387
  });
2264
- await Promise.all(
2265
- workerEnvironments.map(
2266
- (environment) => builder.build(environment)
2267
- )
2268
- );
2269
2388
  }
2270
- writeDeployConfig(resolvedPluginConfig, resolvedViteConfig);
2271
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;
2272
2401
  }
2273
- };
2274
- },
2275
- configResolved(config) {
2276
- resolvedViteConfig = config;
2277
- },
2278
- async resolveId(source) {
2279
- if (resolvedPluginConfig.type === "assets-only") {
2280
- return;
2281
- }
2282
- const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2283
- if (!workerConfig) {
2284
- return;
2285
- }
2286
- return resolveNodeCompatId(this.environment, workerConfig, source);
2287
- },
2288
- async transform(code, id) {
2289
- if (resolvedPluginConfig.type === "assets-only") {
2290
- return;
2291
- }
2292
- const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2293
- if (!workerConfig) {
2294
- return;
2295
- }
2296
- const resolvedId = await this.resolve(workerConfig.main);
2297
- if (id === resolvedId?.id) {
2298
- 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
+ };
2299
2478
  }
2300
2479
  },
2301
- generateBundle(_, bundle) {
2302
- let config;
2303
- if (resolvedPluginConfig.type === "workers") {
2304
- const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2305
- const entryChunk = Object.entries(bundle).find(
2306
- ([_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
2307
2492
  );
2308
- if (!workerConfig || !entryChunk) {
2493
+ },
2494
+ async resolveId(source, importer) {
2495
+ if (!source.endsWith(".wasm")) {
2309
2496
  return;
2310
2497
  }
2311
- workerConfig.main = entryChunk[0];
2312
- const isEntryWorker = this.environment.name === resolvedPluginConfig.entryWorkerEnvironmentName;
2313
- if (isEntryWorker && workerConfig.assets) {
2314
- const workerOutputDirectory = this.environment.config.build.outDir;
2315
- 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;
2316
2515
  assert7(
2317
- clientOutputDirectory,
2318
- "Unexpected error: client output directory is undefined"
2516
+ modulePath,
2517
+ `Unexpected error: module path not found in reference ${full}.`
2319
2518
  );
2320
- workerConfig.assets.directory = path6.relative(
2321
- path6.resolve(resolvedViteConfig.root, workerOutputDirectory),
2322
- 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)
2323
2536
  );
2324
- }
2325
- config = workerConfig;
2326
- if (workerConfig.configPath) {
2327
- const dotDevDotVarsContent = getDotDevDotVarsContent(
2328
- workerConfig.configPath,
2329
- resolvedPluginConfig.cloudflareEnv
2537
+ const importPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2538
+ magicString.update(
2539
+ match.index,
2540
+ match.index + full.length,
2541
+ importPath
2330
2542
  );
2331
- if (dotDevDotVarsContent) {
2332
- this.emitFile({
2333
- type: "asset",
2334
- fileName: ".dev.vars",
2335
- source: dotDevDotVarsContent
2336
- });
2337
- }
2338
2543
  }
2339
- } else if (this.environment.name === "client") {
2340
- const assetsOnlyConfig = resolvedPluginConfig.config;
2341
- assetsOnlyConfig.assets.directory = ".";
2342
- const filesToAssetsIgnore = ["wrangler.json", ".dev.vars"];
2343
- this.emitFile({
2344
- type: "asset",
2345
- fileName: ".assetsignore",
2346
- source: `${filesToAssetsIgnore.join("\n")}
2347
- `
2348
- });
2349
- config = assetsOnlyConfig;
2350
- }
2351
- if (!config) {
2352
- return;
2353
- }
2354
- config.no_bundle = true;
2355
- config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
2356
- if (config.unsafe && Object.keys(config.unsafe).length === 0) {
2357
- config.unsafe = void 0;
2358
- }
2359
- this.emitFile({
2360
- type: "asset",
2361
- fileName: "wrangler.json",
2362
- source: JSON.stringify(config)
2363
- });
2364
- },
2365
- handleHotUpdate(options) {
2366
- if (resolvedPluginConfig.configPaths.has(options.file)) {
2367
- options.server.restart();
2368
- }
2369
- },
2370
- async buildEnd() {
2371
- if (miniflare) {
2372
- await miniflare.dispose();
2373
- 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
+ }
2374
2550
  }
2375
- },
2376
- async configureServer(viteDevServer) {
2377
- assert7(viteDevServer.httpServer, "Unexpected error: No Vite HTTP server");
2378
- miniflare = new Miniflare(
2379
- getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
2380
- );
2381
- await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
2382
- const entryWorker = await getDevEntryWorker(
2383
- resolvedPluginConfig,
2384
- miniflare
2385
- );
2386
- const middleware = createMiddleware(({ request }) => {
2387
- return entryWorker.fetch(toMiniflareRequest(request), {
2388
- redirect: "manual"
2389
- });
2390
- });
2391
- handleWebSocket(
2392
- viteDevServer.httpServer,
2393
- entryWorker.fetch,
2394
- viteDevServer.config.logger
2395
- );
2396
- return () => {
2397
- viteDevServer.middlewares.use((req, res, next) => {
2398
- middleware(req, res, next);
2399
- });
2400
- };
2401
- },
2402
- configurePreviewServer(vitePreviewServer) {
2403
- const miniflare2 = new Miniflare(
2404
- getPreviewMiniflareOptions(
2405
- vitePreviewServer,
2406
- pluginConfig.persistState ?? true
2407
- )
2408
- );
2409
- const middleware = createMiddleware(({ request }) => {
2410
- return miniflare2.dispatchFetch(toMiniflareRequest(request), {
2411
- redirect: "manual"
2412
- });
2413
- });
2414
- handleWebSocket(
2415
- vitePreviewServer.httpServer,
2416
- miniflare2.dispatchFetch,
2417
- vitePreviewServer.config.logger
2418
- );
2419
- return () => {
2420
- vitePreviewServer.middlewares.use((req, res, next) => {
2421
- middleware(req, res, next);
2422
- });
2423
- };
2424
2551
  }
2425
- };
2552
+ ];
2426
2553
  }
2427
2554
  function getDotDevDotVarsContent(configPath, cloudflareEnv) {
2428
2555
  const configDir = path6.dirname(configPath);
@@ -2435,6 +2562,9 @@ function getDotDevDotVarsContent(configPath, cloudflareEnv) {
2435
2562
  }
2436
2563
  return null;
2437
2564
  }
2565
+ function createModuleReference(type, id) {
2566
+ return `__CLOUDFLARE_MODULE__${type}__${id}__`;
2567
+ }
2438
2568
  export {
2439
2569
  cloudflare2 as cloudflare
2440
2570
  };