@cloudflare/vite-plugin 1.23.0 → 1.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import module$1, { builtinModules, createRequire } from "node:module";
2
2
  import assert from "node:assert";
3
+ import { randomUUID } from "node:crypto";
3
4
  import { CoreHeaders, Log, LogLevel, Miniflare, Request as Request$1, Response as Response$1, coupleWebSocket, getDefaultDevRegistryPath, getNodeCompat, getWorkerRegistry, kUnsafeEphemeralUniqueKey } from "miniflare";
4
5
  import * as wrangler from "wrangler";
5
6
  import * as nodePath from "node:path";
@@ -19,7 +20,6 @@ import { defineEnv } from "unenv";
19
20
  import * as fsp from "node:fs/promises";
20
21
  import net from "node:net";
21
22
  import { execFileSync, spawn } from "node:child_process";
22
- import { randomUUID } from "node:crypto";
23
23
  import path, { posix } from "path";
24
24
  import { WebSocketServer } from "ws";
25
25
 
@@ -1584,13 +1584,13 @@ function cleanUrl(url) {
1584
1584
  function withTrailingSlash(path$1) {
1585
1585
  return path$1.endsWith("/") ? path$1 : `${path$1}/`;
1586
1586
  }
1587
- function createRequestHandler(handler) {
1587
+ function createRequestHandler(ctx, handler) {
1588
1588
  return async (req, res, next) => {
1589
1589
  let request$1;
1590
1590
  try {
1591
1591
  if (req.originalUrl) req.url = req.originalUrl;
1592
1592
  request$1 = createRequest(req, res);
1593
- let response = await handler(toMiniflareRequest(request$1), req);
1593
+ let response = await handler(toMiniflareRequest(ctx, request$1), req);
1594
1594
  if (req.httpVersionMajor === 2) {
1595
1595
  response = new Response$1(response.body, response);
1596
1596
  response.headers.delete("transfer-encoding");
@@ -1605,10 +1605,11 @@ function createRequestHandler(handler) {
1605
1605
  function satisfiesViteVersion(minVersion$2) {
1606
1606
  return (0, import_gte.default)(version, minVersion$2);
1607
1607
  }
1608
- function toMiniflareRequest(request$1) {
1608
+ function toMiniflareRequest(ctx, request$1) {
1609
1609
  const host = request$1.headers.get("Host");
1610
1610
  const xForwardedHost = request$1.headers.get("X-Forwarded-Host");
1611
1611
  if (host && !xForwardedHost) request$1.headers.set("X-Forwarded-Host", host);
1612
+ request$1.headers.set(CoreHeaders.PROXY_SHARED_SECRET, ctx.proxySharedSecret);
1612
1613
  const secFetchMode = request$1.headers.get("Sec-Fetch-Mode");
1613
1614
  if (secFetchMode) request$1.headers.set(CoreHeaders.SEC_FETCH_MODE, secFetchMode);
1614
1615
  return new Request$1(request$1.url, {
@@ -1709,8 +1710,10 @@ var PluginContext = class {
1709
1710
  #sharedContext;
1710
1711
  #resolvedPluginConfig;
1711
1712
  #resolvedViteConfig;
1713
+ #proxySharedSecret;
1712
1714
  constructor(sharedContext$1) {
1713
1715
  this.#sharedContext = sharedContext$1;
1716
+ this.#proxySharedSecret = randomUUID();
1714
1717
  }
1715
1718
  /** Creates a new Miniflare instance or updates the existing instance */
1716
1719
  async startOrUpdateMiniflare(options) {
@@ -1800,6 +1803,9 @@ var PluginContext = class {
1800
1803
  getNodeJsCompat(environmentName) {
1801
1804
  return this.#getWorker(environmentName)?.nodeJsCompat;
1802
1805
  }
1806
+ get proxySharedSecret() {
1807
+ return this.#proxySharedSecret;
1808
+ }
1803
1809
  };
1804
1810
  function assertIsNotPreview(ctx) {
1805
1811
  assert(ctx.resolvedPluginConfig.type !== "preview", `Expected "assets-only" or "workers" plugin config`);
@@ -5346,7 +5352,7 @@ function assertOneOf(choices, value) {
5346
5352
  __name(assertOneOf, "assertOneOf");
5347
5353
  var getC3CommandFromEnv = getEnvironmentVariableFactory({
5348
5354
  variableName: "WRANGLER_C3_COMMAND",
5349
- defaultValue: /* @__PURE__ */ __name(() => "create cloudflare@^2.5.0", "defaultValue")
5355
+ defaultValue: /* @__PURE__ */ __name(() => "create cloudflare", "defaultValue")
5350
5356
  });
5351
5357
  var getWranglerSendMetricsFromEnv = getBooleanEnvironmentVariableFactory({ variableName: "WRANGLER_SEND_METRICS" });
5352
5358
  var getWranglerSendErrorReportsFromEnv = getBooleanEnvironmentVariableFactory({ variableName: "WRANGLER_SEND_ERROR_REPORTS" });
@@ -5437,6 +5443,11 @@ var getLocalExplorerEnabledFromEnv = getBooleanEnvironmentVariableFactory({
5437
5443
  variableName: "X_LOCAL_EXPLORER",
5438
5444
  defaultValue: false
5439
5445
  });
5446
+ var getCfFetchEnabledFromEnv = getBooleanEnvironmentVariableFactory({
5447
+ variableName: "CLOUDFLARE_CF_FETCH_ENABLED",
5448
+ defaultValue: true
5449
+ });
5450
+ var getCfFetchPathFromEnv = getEnvironmentVariableFactory({ variableName: "CLOUDFLARE_CF_FETCH_PATH" });
5440
5451
  var Diagnostics = class {
5441
5452
  /**
5442
5453
  * Create a new Diagnostics object.
@@ -5723,6 +5734,47 @@ var friendlyBindingNames = {
5723
5734
  worker_loaders: "Worker Loader",
5724
5735
  vpc_services: "VPC Service"
5725
5736
  };
5737
+ var bindingTypeFriendlyNames = {
5738
+ plain_text: "Environment Variable",
5739
+ secret_text: "Environment Variable",
5740
+ json: "Environment Variable",
5741
+ kv_namespace: "KV Namespace",
5742
+ send_email: "Send Email",
5743
+ wasm_module: "Wasm Module",
5744
+ text_blob: "Text Blob",
5745
+ browser: "Browser",
5746
+ ai: "AI",
5747
+ images: "Images",
5748
+ version_metadata: "Worker Version Metadata",
5749
+ data_blob: "Data Blob",
5750
+ durable_object_namespace: "Durable Object",
5751
+ workflow: "Workflow",
5752
+ queue: "Queue",
5753
+ r2_bucket: "R2 Bucket",
5754
+ d1: "D1 Database",
5755
+ vectorize: "Vectorize Index",
5756
+ hyperdrive: "Hyperdrive Config",
5757
+ service: "Worker",
5758
+ fetcher: "Service Binding",
5759
+ analytics_engine: "Analytics Engine Dataset",
5760
+ dispatch_namespace: "Dispatch Namespace",
5761
+ mtls_certificate: "mTLS Certificate",
5762
+ pipeline: "Pipeline",
5763
+ secrets_store_secret: "Secrets Store Secret",
5764
+ logfwdr: "logfwdr",
5765
+ unsafe_hello_world: "Hello World",
5766
+ ratelimit: "Rate Limit",
5767
+ worker_loader: "Worker Loader",
5768
+ vpc_service: "VPC Service",
5769
+ media: "Media",
5770
+ assets: "Assets"
5771
+ };
5772
+ function getBindingTypeFriendlyName(bindingType) {
5773
+ if (bindingType in bindingTypeFriendlyNames) return bindingTypeFriendlyNames[bindingType];
5774
+ if (bindingType.startsWith("unsafe_")) return "Unsafe Metadata";
5775
+ return bindingType;
5776
+ }
5777
+ __name(getBindingTypeFriendlyName, "getBindingTypeFriendlyName");
5726
5778
  var ENGLISH = new Intl.ListFormat("en-US");
5727
5779
  var ALLOWED_INSTANCE_TYPES = [
5728
5780
  "lite",
@@ -15938,7 +15990,7 @@ function parseRedirects(input, { htmlHandling = void 0, maxStaticRules = MAX_STA
15938
15990
  invalid.push({ message: `Ignoring line ${i$1 + 1} as it exceeds the maximum allowed length of ${maxLineLength}.` });
15939
15991
  continue;
15940
15992
  }
15941
- const tokens = line.split(/\s+/);
15993
+ const tokens = line.replace(/\s+#.*$/, "").split(/\s+/);
15942
15994
  if (tokens.length < 2 || tokens.length > 3) {
15943
15995
  invalid.push({
15944
15996
  line,
@@ -21610,7 +21662,17 @@ function createCloudflareEnvironmentOptions({ workerConfig, userConfig, mode, en
21610
21662
  noDiscovery: false,
21611
21663
  ignoreOutdatedRequests: true,
21612
21664
  entries: vite.normalizePath(workerConfig.main),
21613
- exclude: [...cloudflareBuiltInModules],
21665
+ exclude: [
21666
+ ...cloudflareBuiltInModules,
21667
+ ...nonPrefixedNodeModules,
21668
+ ...nonPrefixedNodeModules.map((module$2) => `node:${module$2}`),
21669
+ ...[
21670
+ "node:sea",
21671
+ "node:sqlite",
21672
+ "node:test",
21673
+ "node:test/reporters"
21674
+ ]
21675
+ ],
21614
21676
  ...isRolldown ? { rolldownOptions: {
21615
21677
  platform: "neutral",
21616
21678
  resolve: {
@@ -21620,7 +21682,11 @@ function createCloudflareEnvironmentOptions({ workerConfig, userConfig, mode, en
21620
21682
  transform: {
21621
21683
  target,
21622
21684
  define: define$1
21623
- }
21685
+ },
21686
+ plugins: [vite.esmExternalRequirePlugin({
21687
+ external: [nodeBuiltinsRE],
21688
+ skipDuplicateCheck: true
21689
+ })]
21624
21690
  } } : { esbuildOptions: {
21625
21691
  platform: "neutral",
21626
21692
  conditions: [...defaultConditions, "development"],
@@ -25982,6 +26048,7 @@ async function getDevMiniflareOptions(ctx, viteDevServer) {
25982
26048
  return {
25983
26049
  miniflareOptions: {
25984
26050
  log: logger,
26051
+ unsafeProxySharedSecret: ctx.proxySharedSecret,
25985
26052
  logRequests: false,
25986
26053
  inspectorPort: inputInspectorPort === false ? void 0 : inputInspectorPort,
25987
26054
  unsafeDevRegistryPath: getDefaultDevRegistryPath(),
@@ -26086,6 +26153,7 @@ async function getPreviewMiniflareOptions(ctx, vitePreviewServer) {
26086
26153
  return {
26087
26154
  miniflareOptions: {
26088
26155
  log: logger,
26156
+ unsafeProxySharedSecret: ctx.proxySharedSecret,
26089
26157
  inspectorPort: inputInspectorPort === false ? void 0 : inputInspectorPort,
26090
26158
  unsafeDevRegistryPath: getDefaultDevRegistryPath(),
26091
26159
  unsafeTriggerHandlers: true,
@@ -26226,7 +26294,7 @@ const devPlugin = createPlugin("dev", (ctx) => {
26226
26294
  if (staticRouting) {
26227
26295
  const excludeRulesMatcher = generateStaticRoutingRuleMatcher(staticRouting.asset_worker ?? []);
26228
26296
  const includeRulesMatcher = generateStaticRoutingRuleMatcher(staticRouting.user_worker);
26229
- const userWorkerHandler = createRequestHandler(async (request$1) => {
26297
+ const userWorkerHandler = createRequestHandler(ctx, async (request$1) => {
26230
26298
  request$1.headers.set(CoreHeaders.ROUTE_OVERRIDE, entryWorkerName);
26231
26299
  return ctx.miniflare.dispatchFetch(request$1, { redirect: "manual" });
26232
26300
  });
@@ -26268,7 +26336,7 @@ const devPlugin = createPlugin("dev", (ctx) => {
26268
26336
  handle: preMiddleware
26269
26337
  });
26270
26338
  }
26271
- viteDevServer.middlewares.use(createRequestHandler(async (request$1, req) => {
26339
+ viteDevServer.middlewares.use(createRequestHandler(ctx, async (request$1, req) => {
26272
26340
  if (req[kRequestType] === "asset") {
26273
26341
  request$1.headers.set(CoreHeaders.ROUTE_OVERRIDE, ASSET_WORKER_NAME);
26274
26342
  return ctx.miniflare.dispatchFetch(request$1, { redirect: "manual" });
@@ -26307,23 +26375,7 @@ const nodeJsCompatPlugin = createPlugin("nodejs-compat", (ctx) => {
26307
26375
  ...isRolldown ? { build: { rolldownOptions: { plugins: [vite.esmExternalRequirePlugin({
26308
26376
  external: [...nodeJsCompat.externals],
26309
26377
  skipDuplicateCheck: true
26310
- })] } } } : {},
26311
- optimizeDeps: {
26312
- exclude: [
26313
- ...nonPrefixedNodeModules,
26314
- ...nonPrefixedNodeModules.map((module$2) => `node:${module$2}`),
26315
- ...[
26316
- "node:sea",
26317
- "node:sqlite",
26318
- "node:test",
26319
- "node:test/reporters"
26320
- ]
26321
- ],
26322
- ...isRolldown ? { rolldownOptions: { plugins: [vite.esmExternalRequirePlugin({
26323
- external: [nodeBuiltinsRE],
26324
- skipDuplicateCheck: true
26325
- })] } } : {}
26326
- }
26378
+ })] } } } : {}
26327
26379
  };
26328
26380
  },
26329
26381
  applyToEnvironment(environment) {
@@ -26375,46 +26427,8 @@ const nodeJsCompatWarningsPlugin = createPlugin("nodejs-compat-warnings", (ctx)
26375
26427
  exitCallback$1 = () => {
26376
26428
  for (const nodeJsCompatWarnings of nodeJsCompatWarningsMap.values()) nodeJsCompatWarnings.renderWarnings();
26377
26429
  };
26378
- function resolveId(environmentName, source, importer) {
26379
- if (!nodeBuiltinsRE.test(source)) return;
26380
- const workerConfig = ctx.getWorkerConfig(environmentName);
26381
- const nodeJsCompat = ctx.getNodeJsCompat(environmentName);
26382
- if (workerConfig && !nodeJsCompat) {
26383
- if (hasNodeJsAls(workerConfig) && isNodeAlsModule(source)) return;
26384
- nodeJsCompatWarningsMap.get(workerConfig)?.registerImport(source, importer);
26385
- return {
26386
- id: source,
26387
- external: true
26388
- };
26389
- }
26390
- }
26391
26430
  return {
26392
26431
  enforce: "pre",
26393
- configEnvironment(environmentName) {
26394
- const workerConfig = ctx.getWorkerConfig(environmentName);
26395
- const nodeJsCompat = ctx.getNodeJsCompat(environmentName);
26396
- if (workerConfig && !nodeJsCompat) return { optimizeDeps: { ...isRolldown ? { rolldownOptions: { plugins: [{
26397
- name: "vite-plugin-cloudflare:nodejs-compat-warnings-resolver",
26398
- resolveId: {
26399
- filter: { id: nodeBuiltinsRE },
26400
- handler(source, importer) {
26401
- return resolveId(environmentName, source, importer);
26402
- }
26403
- }
26404
- }] } } : { esbuildOptions: { plugins: [{
26405
- name: "vite-plugin-cloudflare:nodejs-compat-warnings-resolver",
26406
- setup(build$8) {
26407
- build$8.onResolve({ filter: nodeBuiltinsRE }, ({ path: path$1, importer }) => {
26408
- if (hasNodeJsAls(workerConfig) && isNodeAlsModule(path$1)) return;
26409
- nodeJsCompatWarningsMap.get(workerConfig)?.registerImport(path$1, importer);
26410
- return {
26411
- path: path$1,
26412
- external: true
26413
- };
26414
- });
26415
- }
26416
- }] } } } };
26417
- },
26418
26432
  configResolved(resolvedViteConfig) {
26419
26433
  for (const environmentName of Object.keys(resolvedViteConfig.environments)) {
26420
26434
  const workerConfig = ctx.getWorkerConfig(environmentName);
@@ -26428,7 +26442,15 @@ const nodeJsCompatWarningsPlugin = createPlugin("nodejs-compat-warnings", (ctx)
26428
26442
  resolveId: {
26429
26443
  filter: { id: nodeBuiltinsRE },
26430
26444
  handler(source, importer) {
26431
- return resolveId(this.environment.name, source, importer);
26445
+ if (!nodeBuiltinsRE.test(source)) return;
26446
+ const workerConfig = ctx.getWorkerConfig(this.environment.name);
26447
+ assert(workerConfig, `expected workerConfig to be defined`);
26448
+ if (hasNodeJsAls(workerConfig) && isNodeAlsModule(source)) return;
26449
+ nodeJsCompatWarningsMap.get(workerConfig)?.registerImport(source, importer);
26450
+ return {
26451
+ id: source,
26452
+ external: true
26453
+ };
26432
26454
  }
26433
26455
  }
26434
26456
  };
@@ -26464,6 +26486,7 @@ const outputConfigPlugin = createPlugin("output-config", (ctx) => {
26464
26486
  directory: getAssetsDirectory(this.environment.config.build.outDir, ctx.resolvedViteConfig)
26465
26487
  } : void 0
26466
26488
  };
26489
+ if (inputWorkerConfig.upload_source_maps === void 0 && this.environment.config.build.sourcemap) outputConfig.upload_source_maps = true;
26467
26490
  if (inputWorkerConfig.configPath) {
26468
26491
  const localDevVars = getLocalDevVarsForPreview(inputWorkerConfig.configPath, ctx.resolvedPluginConfig.cloudflareEnv);
26469
26492
  if (localDevVars) this.emitFile({
@@ -26546,7 +26569,7 @@ const previewPlugin = createPlugin("preview", (ctx) => {
26546
26569
  };
26547
26570
  }
26548
26571
  handleWebSocket(vitePreviewServer.httpServer, ctx.miniflare);
26549
- vitePreviewServer.middlewares.use(createRequestHandler((request$1) => {
26572
+ vitePreviewServer.middlewares.use(createRequestHandler(ctx, (request$1) => {
26550
26573
  return ctx.miniflare.dispatchFetch(request$1, { redirect: "manual" });
26551
26574
  }));
26552
26575
  } };
@@ -26624,7 +26647,7 @@ const triggerHandlersPlugin = createPlugin("trigger-handlers", (ctx) => {
26624
26647
  const entryWorkerConfig = ctx.entryWorkerConfig;
26625
26648
  if (!entryWorkerConfig) return;
26626
26649
  const entryWorkerName = entryWorkerConfig.name;
26627
- const requestHandler = createRequestHandler((request$1) => {
26650
+ const requestHandler = createRequestHandler(ctx, (request$1) => {
26628
26651
  request$1.headers.set(CoreHeaders.ROUTE_OVERRIDE, entryWorkerName);
26629
26652
  return ctx.miniflare.dispatchFetch(request$1, { redirect: "manual" });
26630
26653
  });