@cloudflare/vite-plugin 0.0.0-9ba6374a9 → 0.0.0-9cfe0d8ed

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,6 +1310,9 @@ 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),
1306
1317
  ssr: true,
1307
1318
  rollupOptions: {
@@ -1323,6 +1334,7 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1323
1334
  ],
1324
1335
  esbuildOptions: {
1325
1336
  platform: "neutral",
1337
+ conditions: [...defaultConditions, "development"],
1326
1338
  resolveExtensions: [
1327
1339
  ".mjs",
1328
1340
  ".js",
@@ -1433,13 +1445,6 @@ function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
1433
1445
 
1434
1446
  // src/dev.ts
1435
1447
  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
1448
  function getDevEntryWorker(resolvedPluginConfig, miniflare) {
1444
1449
  const entryWorkerConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config : resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
1445
1450
  assert3(entryWorkerConfig, "Unexpected error: No entry worker configuration");
@@ -1669,16 +1674,24 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1669
1674
  `Invalid invoke event: ${invokePayloadData.name}`
1670
1675
  );
1671
1676
  const [moduleId] = invokePayloadData.data;
1677
+ const moduleRE = new RegExp(MODULE_PATTERN);
1678
+ if (moduleRE.test(moduleId)) {
1679
+ const result2 = {
1680
+ externalize: moduleId,
1681
+ type: "module"
1682
+ };
1683
+ return MiniflareResponse.json({ result: result2 });
1684
+ }
1672
1685
  if (moduleId.startsWith("cloudflare:")) {
1673
1686
  const result2 = {
1674
1687
  externalize: moduleId,
1675
1688
  type: "builtin"
1676
1689
  };
1677
- return new MiniflareResponse(JSON.stringify({ result: result2 }));
1690
+ return MiniflareResponse.json({ result: result2 });
1678
1691
  }
1679
1692
  const devEnvironment = viteDevServer.environments[environmentName];
1680
1693
  const result = await devEnvironment.hot.handleInvoke(payload);
1681
- return new MiniflareResponse(JSON.stringify(result));
1694
+ return MiniflareResponse.json(result);
1682
1695
  }
1683
1696
  }
1684
1697
  };
@@ -1757,10 +1770,37 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1757
1770
  fileURLToPath(new URL(RUNNER_PATH, import.meta.url))
1758
1771
  )
1759
1772
  }
1760
- ]
1773
+ ],
1774
+ unsafeUseModuleFallbackService: true
1761
1775
  };
1762
1776
  })
1763
- ]
1777
+ ],
1778
+ unsafeModuleFallbackService(request) {
1779
+ const url = new URL(request.url);
1780
+ const rawSpecifier = url.searchParams.get("rawSpecifier");
1781
+ assert4(
1782
+ rawSpecifier,
1783
+ `Unexpected error: no specifier in request to module fallback service.`
1784
+ );
1785
+ const moduleRE = new RegExp(MODULE_PATTERN);
1786
+ const match = moduleRE.exec(rawSpecifier);
1787
+ assert4(match, `Unexpected error: no match for module ${rawSpecifier}.`);
1788
+ const [full, moduleType, modulePath] = match;
1789
+ assert4(
1790
+ modulePath,
1791
+ `Unexpected error: module path not found in reference ${full}.`
1792
+ );
1793
+ let source;
1794
+ try {
1795
+ source = fs2.readFileSync(modulePath);
1796
+ } catch (error) {
1797
+ throw new Error(`Import ${modulePath} not found. Does the file exist?`);
1798
+ }
1799
+ return MiniflareResponse.json({
1800
+ // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
1801
+ wasm: Array.from(source)
1802
+ });
1803
+ }
1764
1804
  };
1765
1805
  }
1766
1806
  function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
@@ -2201,228 +2241,312 @@ function cloudflare2(pluginConfig = {}) {
2201
2241
  let resolvedViteConfig;
2202
2242
  let miniflare;
2203
2243
  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
2244
+ return [
2245
+ {
2246
+ name: "vite-plugin-cloudflare",
2247
+ config(userConfig, env2) {
2248
+ if (env2.isPreview) {
2249
+ return { appType: "custom" };
2250
+ }
2251
+ resolvedPluginConfig = resolvePluginConfig(
2252
+ pluginConfig,
2253
+ userConfig,
2254
+ env2
2215
2255
  );
2216
- if (workersConfigsWarning) {
2217
- console.warn(workersConfigsWarning);
2256
+ if (!workersConfigsWarningShown) {
2257
+ workersConfigsWarningShown = true;
2258
+ const workersConfigsWarning = getWarningForWorkersConfigs(
2259
+ resolvedPluginConfig.rawConfigs
2260
+ );
2261
+ if (workersConfigsWarning) {
2262
+ console.warn(workersConfigsWarning);
2263
+ }
2218
2264
  }
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
2265
+ return {
2266
+ appType: "custom",
2267
+ resolve: {
2268
+ alias: getNodeCompatAliases()
2269
+ },
2270
+ environments: resolvedPluginConfig.type === "workers" ? {
2271
+ ...Object.fromEntries(
2272
+ Object.entries(resolvedPluginConfig.workers).map(
2273
+ ([environmentName, workerConfig]) => {
2274
+ return [
2275
+ environmentName,
2276
+ createCloudflareEnvironmentOptions(
2277
+ workerConfig,
2278
+ userConfig,
2279
+ environmentName
2280
+ )
2281
+ ];
2282
+ }
2283
+ )
2284
+ ),
2285
+ client: {
2286
+ build: {
2287
+ outDir: getOutputDirectory(userConfig, "client")
2288
+ }
2289
+ }
2290
+ } : void 0,
2291
+ builder: {
2292
+ async buildApp(builder) {
2293
+ const clientEnvironment = builder.environments.client;
2294
+ const defaultHtmlPath = path6.resolve(
2295
+ builder.config.root,
2296
+ "index.html"
2297
+ );
2298
+ if (clientEnvironment && (clientEnvironment.config.build.rollupOptions.input || fs4.existsSync(defaultHtmlPath))) {
2299
+ await builder.build(clientEnvironment);
2300
+ }
2301
+ if (resolvedPluginConfig.type === "workers") {
2302
+ const workerEnvironments = Object.keys(
2303
+ resolvedPluginConfig.workers
2304
+ ).map((environmentName) => {
2305
+ const environment = builder.environments[environmentName];
2306
+ assert7(
2307
+ environment,
2308
+ `${environmentName} environment not found`
2309
+ );
2310
+ return environment;
2311
+ });
2312
+ await Promise.all(
2313
+ workerEnvironments.map(
2314
+ (environment) => builder.build(environment)
2235
2315
  )
2236
- ];
2316
+ );
2237
2317
  }
2238
- )
2239
- ),
2240
- client: {
2241
- build: {
2242
- outDir: getOutputDirectory(userConfig, "client")
2318
+ writeDeployConfig(resolvedPluginConfig, resolvedViteConfig);
2243
2319
  }
2244
2320
  }
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"
2321
+ };
2322
+ },
2323
+ configResolved(config) {
2324
+ resolvedViteConfig = config;
2325
+ },
2326
+ async resolveId(source) {
2327
+ if (resolvedPluginConfig.type === "assets-only") {
2328
+ return;
2329
+ }
2330
+ const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2331
+ if (!workerConfig) {
2332
+ return;
2333
+ }
2334
+ return resolveNodeCompatId(this.environment, workerConfig, source);
2335
+ },
2336
+ async transform(code, id) {
2337
+ if (resolvedPluginConfig.type === "assets-only") {
2338
+ return;
2339
+ }
2340
+ const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2341
+ if (!workerConfig) {
2342
+ return;
2343
+ }
2344
+ const resolvedId = await this.resolve(workerConfig.main);
2345
+ if (id === resolvedId?.id) {
2346
+ return injectGlobalCode(id, code, workerConfig);
2347
+ }
2348
+ },
2349
+ generateBundle(_, bundle) {
2350
+ let config;
2351
+ if (resolvedPluginConfig.type === "workers") {
2352
+ const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2353
+ const entryChunk = Object.entries(bundle).find(
2354
+ ([_2, chunk]) => chunk.type === "chunk" && chunk.isEntry
2355
+ );
2356
+ if (!workerConfig || !entryChunk) {
2357
+ return;
2358
+ }
2359
+ workerConfig.main = entryChunk[0];
2360
+ const isEntryWorker = this.environment.name === resolvedPluginConfig.entryWorkerEnvironmentName;
2361
+ if (isEntryWorker && workerConfig.assets) {
2362
+ const workerOutputDirectory = this.environment.config.build.outDir;
2363
+ const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
2364
+ assert7(
2365
+ clientOutputDirectory,
2366
+ "Unexpected error: client output directory is undefined"
2252
2367
  );
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;
2368
+ workerConfig.assets.directory = path6.relative(
2369
+ path6.resolve(resolvedViteConfig.root, workerOutputDirectory),
2370
+ path6.resolve(resolvedViteConfig.root, clientOutputDirectory)
2371
+ );
2372
+ }
2373
+ config = workerConfig;
2374
+ if (workerConfig.configPath) {
2375
+ const dotDevDotVarsContent = getDotDevDotVarsContent(
2376
+ workerConfig.configPath,
2377
+ resolvedPluginConfig.cloudflareEnv
2378
+ );
2379
+ if (dotDevDotVarsContent) {
2380
+ this.emitFile({
2381
+ type: "asset",
2382
+ fileName: ".dev.vars",
2383
+ source: dotDevDotVarsContent
2263
2384
  });
2264
- await Promise.all(
2265
- workerEnvironments.map(
2266
- (environment) => builder.build(environment)
2267
- )
2268
- );
2269
2385
  }
2270
- writeDeployConfig(resolvedPluginConfig, resolvedViteConfig);
2271
2386
  }
2387
+ } else if (this.environment.name === "client") {
2388
+ const assetsOnlyConfig = resolvedPluginConfig.config;
2389
+ assetsOnlyConfig.assets.directory = ".";
2390
+ const filesToAssetsIgnore = ["wrangler.json", ".dev.vars"];
2391
+ this.emitFile({
2392
+ type: "asset",
2393
+ fileName: ".assetsignore",
2394
+ source: `${filesToAssetsIgnore.join("\n")}
2395
+ `
2396
+ });
2397
+ config = assetsOnlyConfig;
2272
2398
  }
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);
2399
+ if (!config) {
2400
+ return;
2401
+ }
2402
+ config.no_bundle = true;
2403
+ config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
2404
+ if (config.unsafe && Object.keys(config.unsafe).length === 0) {
2405
+ config.unsafe = void 0;
2406
+ }
2407
+ this.emitFile({
2408
+ type: "asset",
2409
+ fileName: "wrangler.json",
2410
+ source: JSON.stringify(config)
2411
+ });
2412
+ },
2413
+ handleHotUpdate(options) {
2414
+ if (resolvedPluginConfig.configPaths.has(options.file)) {
2415
+ options.server.restart();
2416
+ }
2417
+ },
2418
+ async buildEnd() {
2419
+ if (miniflare) {
2420
+ await miniflare.dispose();
2421
+ miniflare = void 0;
2422
+ }
2423
+ },
2424
+ async configureServer(viteDevServer) {
2425
+ assert7(
2426
+ viteDevServer.httpServer,
2427
+ "Unexpected error: No Vite HTTP server"
2428
+ );
2429
+ miniflare = new Miniflare(
2430
+ getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
2431
+ );
2432
+ await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
2433
+ const entryWorker = await getDevEntryWorker(
2434
+ resolvedPluginConfig,
2435
+ miniflare
2436
+ );
2437
+ const middleware = createMiddleware(({ request }) => {
2438
+ return entryWorker.fetch(toMiniflareRequest(request), {
2439
+ redirect: "manual"
2440
+ });
2441
+ });
2442
+ handleWebSocket(
2443
+ viteDevServer.httpServer,
2444
+ entryWorker.fetch,
2445
+ viteDevServer.config.logger
2446
+ );
2447
+ return () => {
2448
+ viteDevServer.middlewares.use((req, res, next) => {
2449
+ middleware(req, res, next);
2450
+ });
2451
+ };
2452
+ },
2453
+ configurePreviewServer(vitePreviewServer) {
2454
+ const miniflare2 = new Miniflare(
2455
+ getPreviewMiniflareOptions(
2456
+ vitePreviewServer,
2457
+ pluginConfig.persistState ?? true
2458
+ )
2459
+ );
2460
+ const middleware = createMiddleware(({ request }) => {
2461
+ return miniflare2.dispatchFetch(toMiniflareRequest(request), {
2462
+ redirect: "manual"
2463
+ });
2464
+ });
2465
+ handleWebSocket(
2466
+ vitePreviewServer.httpServer,
2467
+ miniflare2.dispatchFetch,
2468
+ vitePreviewServer.config.logger
2469
+ );
2470
+ return () => {
2471
+ vitePreviewServer.middlewares.use((req, res, next) => {
2472
+ middleware(req, res, next);
2473
+ });
2474
+ };
2299
2475
  }
2300
2476
  },
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
2477
+ // Plugin to support `CompiledWasm` modules
2478
+ {
2479
+ name: "vite-plugin-cloudflare:modules",
2480
+ // We set `enforce: "pre"` so that this plugin runs before the Vite core plugins.
2481
+ // Otherwise the `vite:wasm-fallback` plugin prevents the `.wasm` extension being used for module imports.
2482
+ enforce: "pre",
2483
+ applyToEnvironment(environment) {
2484
+ if (resolvedPluginConfig.type === "assets-only") {
2485
+ return false;
2486
+ }
2487
+ return Object.keys(resolvedPluginConfig.workers).includes(
2488
+ environment.name
2307
2489
  );
2308
- if (!workerConfig || !entryChunk) {
2490
+ },
2491
+ async resolveId(source, importer) {
2492
+ if (!source.endsWith(".wasm")) {
2309
2493
  return;
2310
2494
  }
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;
2495
+ const resolved = await this.resolve(source, importer);
2496
+ assert7(
2497
+ resolved,
2498
+ `Unexpected error: could not resolve Wasm module ${source}`
2499
+ );
2500
+ return {
2501
+ external: true,
2502
+ id: createModuleReference("CompiledWasm", resolved.id)
2503
+ };
2504
+ },
2505
+ renderChunk(code, chunk) {
2506
+ const moduleRE = new RegExp(MODULE_PATTERN, "g");
2507
+ let match;
2508
+ let magicString;
2509
+ while (match = moduleRE.exec(code)) {
2510
+ magicString ??= new MagicString(code);
2511
+ const [full, moduleType, modulePath] = match;
2316
2512
  assert7(
2317
- clientOutputDirectory,
2318
- "Unexpected error: client output directory is undefined"
2513
+ modulePath,
2514
+ `Unexpected error: module path not found in reference ${full}.`
2319
2515
  );
2320
- workerConfig.assets.directory = path6.relative(
2321
- path6.resolve(resolvedViteConfig.root, workerOutputDirectory),
2322
- path6.resolve(resolvedViteConfig.root, clientOutputDirectory)
2516
+ let source;
2517
+ try {
2518
+ source = fs4.readFileSync(modulePath);
2519
+ } catch (error) {
2520
+ throw new Error(
2521
+ `Import ${modulePath} not found. Does the file exist?`
2522
+ );
2523
+ }
2524
+ const referenceId = this.emitFile({
2525
+ type: "asset",
2526
+ name: path6.basename(modulePath),
2527
+ originalFileName: modulePath,
2528
+ source
2529
+ });
2530
+ const emittedFileName = this.getFileName(referenceId);
2531
+ const relativePath = vite6.normalizePath(
2532
+ path6.relative(path6.dirname(chunk.fileName), emittedFileName)
2323
2533
  );
2324
- }
2325
- config = workerConfig;
2326
- if (workerConfig.configPath) {
2327
- const dotDevDotVarsContent = getDotDevDotVarsContent(
2328
- workerConfig.configPath,
2329
- resolvedPluginConfig.cloudflareEnv
2534
+ const importPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2535
+ magicString.update(
2536
+ match.index,
2537
+ match.index + full.length,
2538
+ importPath
2330
2539
  );
2331
- if (dotDevDotVarsContent) {
2332
- this.emitFile({
2333
- type: "asset",
2334
- fileName: ".dev.vars",
2335
- source: dotDevDotVarsContent
2336
- });
2337
- }
2338
2540
  }
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;
2541
+ if (magicString) {
2542
+ return {
2543
+ code: magicString.toString(),
2544
+ map: this.environment.config.build.sourcemap ? magicString.generateMap({ hires: "boundary" }) : null
2545
+ };
2546
+ }
2374
2547
  }
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
2548
  }
2425
- };
2549
+ ];
2426
2550
  }
2427
2551
  function getDotDevDotVarsContent(configPath, cloudflareEnv) {
2428
2552
  const configDir = path6.dirname(configPath);
@@ -2435,6 +2559,9 @@ function getDotDevDotVarsContent(configPath, cloudflareEnv) {
2435
2559
  }
2436
2560
  return null;
2437
2561
  }
2562
+ function createModuleReference(type, id) {
2563
+ return `__CLOUDFLARE_MODULE__${type}__${id}__`;
2564
+ }
2438
2565
  export {
2439
2566
  cloudflare2 as cloudflare
2440
2567
  };