@cloudflare/vite-plugin 1.70.0 → 1.70.2

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.
@@ -1,18 +1,13 @@
1
- import { DurableObject, WorkerEntrypoint, WorkflowEntrypoint } from "cloudflare:workers";
1
+ import { DurableObject, WorkerEntrypoint, WorkflowEntrypoint, waitUntil } from "cloudflare:workers";
2
2
  import { ModuleRunner, ssrDynamicImportKey, ssrModuleExportsKey } from "vite/module-runner";
3
-
4
3
  //#region src/shared.ts
5
4
  const UNKNOWN_HOST = "http://localhost";
6
- const INIT_PATH = "/__vite_plugin_cloudflare_init__";
7
- const GET_EXPORT_TYPES_PATH = "/__vite_plugin_cloudflare_get_export_types__";
8
5
  const WORKER_ENTRY_PATH_HEADER = "__VITE_WORKER_ENTRY_PATH__";
9
6
  const IS_ENTRY_WORKER_HEADER = "__VITE_IS_ENTRY_WORKER__";
10
7
  const ENVIRONMENT_NAME_HEADER = "__VITE_ENVIRONMENT_NAME__";
11
- const IS_PARENT_ENVIRONMENT_HEADER = "__VITE_IS_PARENT_ENVIRONMENT__";
12
8
  const virtualPrefix = "virtual:cloudflare/";
13
9
  const VIRTUAL_WORKER_ENTRY = `${virtualPrefix}worker-entry`;
14
10
  const VIRTUAL_EXPORT_TYPES = `${virtualPrefix}export-types`;
15
-
16
11
  //#endregion
17
12
  //#region src/workers/runner-worker/env.ts
18
13
  /**
@@ -21,10 +16,9 @@ const VIRTUAL_EXPORT_TYPES = `${virtualPrefix}export-types`;
21
16
  * @returns The user-defined env
22
17
  */
23
18
  function stripInternalEnv(internalEnv) {
24
- const { __VITE_RUNNER_OBJECT__: __VITE_RUNNER_OBJECT__$1, __VITE_INVOKE_MODULE__, __VITE_UNSAFE_EVAL__,...userEnv } = internalEnv;
19
+ const { __VITE_RUNNER_OBJECT__, __VITE_INVOKE_MODULE__, __VITE_UNSAFE_EVAL__, ...userEnv } = internalEnv;
25
20
  return userEnv;
26
21
  }
27
-
28
22
  //#endregion
29
23
  //#region src/workers/runner-worker/errors.ts
30
24
  /**
@@ -56,7 +50,6 @@ async function maybeCaptureError(options, fn) {
56
50
  });
57
51
  }
58
52
  }
59
-
60
53
  //#endregion
61
54
  //#region src/workers/runner-worker/keys.ts
62
55
  /** Keys that should be ignored during RPC property access */
@@ -84,7 +77,6 @@ const DURABLE_OBJECT_KEYS = [
84
77
  ];
85
78
  /** Available methods for `WorkflowEntrypoint` classes */
86
79
  const WORKFLOW_ENTRYPOINT_KEYS = ["run"];
87
-
88
80
  //#endregion
89
81
  //#region src/workers/runner-worker/module-runner.ts
90
82
  /** Module runner instances keyed by environment name */
@@ -100,16 +92,20 @@ const callbackResults = /* @__PURE__ */ new Map();
100
92
  * since both run in the same V8 isolate). Only a numeric ID crosses the RPC
101
93
  * boundary.
102
94
  */
103
- async function runInRunnerObject(env, callback) {
104
- const id = nextCallbackId++;
105
- pendingCallbacks.set(id, callback);
106
- try {
107
- await env.__VITE_RUNNER_OBJECT__.get("singleton").executeCallback(id);
108
- return callbackResults.get(id);
109
- } finally {
110
- pendingCallbacks.delete(id);
111
- callbackResults.delete(id);
112
- }
95
+ function runInRunnerObject(env, callback) {
96
+ const operation = (async () => {
97
+ const id = nextCallbackId++;
98
+ pendingCallbacks.set(id, callback);
99
+ try {
100
+ await env.__VITE_RUNNER_OBJECT__.get("singleton").executeCallback(id);
101
+ return callbackResults.get(id);
102
+ } finally {
103
+ pendingCallbacks.delete(id);
104
+ callbackResults.delete(id);
105
+ }
106
+ })();
107
+ waitUntil(operation);
108
+ return operation;
113
109
  }
114
110
  /**
115
111
  * Durable Object that provides an IoContext for module evaluation and handles
@@ -127,11 +123,11 @@ var __VITE_RUNNER_OBJECT__ = class extends DurableObject {
127
123
  */
128
124
  async fetch(request) {
129
125
  const { pathname } = new URL(request.url);
130
- if (pathname !== INIT_PATH) throw new Error(`__VITE_RUNNER_OBJECT__ received invalid pathname: "${pathname}"`);
126
+ if (pathname !== "/__vite_plugin_cloudflare_init__") throw new Error(`__VITE_RUNNER_OBJECT__ received invalid pathname: "${pathname}"`);
131
127
  const environmentName = request.headers.get(ENVIRONMENT_NAME_HEADER);
132
128
  if (!environmentName) throw new Error(`__VITE_RUNNER_OBJECT__ received request without "${ENVIRONMENT_NAME_HEADER}" header`);
133
129
  if (moduleRunners.has(environmentName)) throw new Error(`Module runner already initialized for environment: "${environmentName}"`);
134
- if (request.headers.get(IS_PARENT_ENVIRONMENT_HEADER) === "true") {
130
+ if (request.headers.get("__VITE_IS_PARENT_ENVIRONMENT__") === "true") {
135
131
  parentEnvironmentName = environmentName;
136
132
  globalThis.__VITE_ENVIRONMENT_RUNNER_IMPORT__ = async (envName, id) => {
137
133
  const runner = moduleRunners.get(envName);
@@ -236,11 +232,11 @@ async function createModuleRunner(env, webSocket, environmentName) {
236
232
  /**
237
233
  * Retrieves a specific export from a Worker entry module using the module runner.
238
234
  */
239
- async function getWorkerEntryExport(workerEntryPath$1, exportName) {
235
+ async function getWorkerEntryExport(workerEntryPath, exportName) {
240
236
  if (!parentEnvironmentName) throw new Error(`Parent environment not initialized`);
241
237
  const module = await globalThis.__VITE_ENVIRONMENT_RUNNER_IMPORT__(parentEnvironmentName, VIRTUAL_WORKER_ENTRY);
242
238
  const exportValue = typeof module === "object" && module !== null && exportName in module && module[exportName];
243
- if (!exportValue) throw new Error(`"${workerEntryPath$1}" does not define a "${exportName}" export.`);
239
+ if (!exportValue) throw new Error(`"${workerEntryPath}" does not define a "${exportName}" export.`);
244
240
  return exportValue;
245
241
  }
246
242
  /**
@@ -251,7 +247,6 @@ async function getWorkerEntryExportTypes() {
251
247
  const { getExportTypes } = await globalThis.__VITE_ENVIRONMENT_RUNNER_IMPORT__(parentEnvironmentName, VIRTUAL_EXPORT_TYPES);
252
248
  return getExportTypes(await globalThis.__VITE_ENVIRONMENT_RUNNER_IMPORT__(parentEnvironmentName, VIRTUAL_WORKER_ENTRY));
253
249
  }
254
-
255
250
  //#endregion
256
251
  //#region src/workers/runner-worker/index.ts
257
252
  /** The path to the Worker entry file. We store it in the module scope so that it is easily accessible in error messages etc.. */
@@ -341,8 +336,8 @@ function createWorkerEntrypointWrapper(exportName) {
341
336
  if (key === "fetch") {
342
337
  const request = arg;
343
338
  const url = new URL(request.url);
344
- if (url.pathname === INIT_PATH) {
345
- if (request.headers.get(IS_PARENT_ENVIRONMENT_HEADER) === "true") {
339
+ if (url.pathname === "/__vite_plugin_cloudflare_init__") {
340
+ if (request.headers.get("__VITE_IS_PARENT_ENVIRONMENT__") === "true") {
346
341
  const workerEntryPathHeader = request.headers.get(WORKER_ENTRY_PATH_HEADER);
347
342
  if (!workerEntryPathHeader) throw new Error(`Unexpected error: "${WORKER_ENTRY_PATH_HEADER}" header not set.`);
348
343
  const isEntryWorkerHeader = request.headers.get(IS_ENTRY_WORKER_HEADER);
@@ -352,7 +347,7 @@ function createWorkerEntrypointWrapper(exportName) {
352
347
  }
353
348
  return this.env.__VITE_RUNNER_OBJECT__.get("singleton").fetch(request);
354
349
  }
355
- if (url.pathname === GET_EXPORT_TYPES_PATH) {
350
+ if (url.pathname === "/__vite_plugin_cloudflare_get_export_types__") {
356
351
  const workerEntryExportTypes = await getWorkerEntryExportTypes();
357
352
  return Response.json(workerEntryExportTypes);
358
353
  }
@@ -415,9 +410,10 @@ function createDurableObjectWrapper(exportName) {
415
410
  if (typeof ctor !== "function") throw new TypeError(`Expected "${exportName}" export of "${workerEntryPath}" to be a subclass of \`DurableObject\`.`);
416
411
  if (!this[kInstance] || this[kInstance].ctor !== ctor) {
417
412
  const userEnv = stripInternalEnv(this.env);
413
+ const instance = new ctor(this.ctx, userEnv);
418
414
  this[kInstance] = {
419
415
  ctor,
420
- instance: new ctor(this.ctx, userEnv)
416
+ instance
421
417
  };
422
418
  await this.ctx.blockConcurrencyWhile(async () => {});
423
419
  }
@@ -451,6 +447,5 @@ function createWorkflowEntrypointWrapper(exportName) {
451
447
  };
452
448
  return Wrapper;
453
449
  }
454
-
455
450
  //#endregion
456
- export { __VITE_RUNNER_OBJECT__, createDurableObjectWrapper, createWorkerEntrypointWrapper, createWorkflowEntrypointWrapper };
451
+ export { __VITE_RUNNER_OBJECT__, createDurableObjectWrapper, createWorkerEntrypointWrapper, createWorkflowEntrypointWrapper };
@@ -39,7 +39,8 @@ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
39
39
  function normalizeWindowsPath(input = "") {
40
40
  return input && input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
41
41
  }
42
- const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/, _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
42
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
43
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
43
44
  function cwd() {
44
45
  return typeof process < "u" && typeof process.cwd == "function" ? process.cwd().replace(/\\/g, "/") : "/";
45
46
  }
@@ -79,14 +80,24 @@ function normalizeString(path, allowAboveRoot) {
79
80
  }
80
81
  const isAbsolute = function(p) {
81
82
  return _IS_ABSOLUTE_RE.test(p);
82
- }, dirname = function(p) {
83
+ };
84
+ const dirname = function(p) {
83
85
  let segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
84
86
  return segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0]) && (segments[0] += "/"), segments.join("/") || (isAbsolute(p) ? "/" : ".");
85
- }, decodeBase64 = typeof atob < "u" ? atob : (str) => Buffer.from(str, "base64").toString("utf-8"), percentRegEx = /%/g, backslashRegEx = /\\/g, newlineRegEx = /\n/g, carriageReturnRegEx = /\r/g, tabRegEx = /\t/g, questionRegex = /\?/g, hashRegex = /#/g;
87
+ };
88
+ const decodeBase64 = typeof atob < "u" ? atob : (str) => Buffer.from(str, "base64").toString("utf-8");
89
+ const percentRegEx = /%/g;
90
+ const backslashRegEx = /\\/g;
91
+ const newlineRegEx = /\n/g;
92
+ const carriageReturnRegEx = /\r/g;
93
+ const tabRegEx = /\t/g;
94
+ const questionRegex = /\?/g;
95
+ const hashRegex = /#/g;
86
96
  function encodePathChars(filepath) {
87
97
  return filepath.indexOf("%") !== -1 && (filepath = filepath.replace(percentRegEx, "%25")), !isWindows && filepath.indexOf("\\") !== -1 && (filepath = filepath.replace(backslashRegEx, "%5C")), filepath.indexOf("\n") !== -1 && (filepath = filepath.replace(newlineRegEx, "%0A")), filepath.indexOf("\r") !== -1 && (filepath = filepath.replace(carriageReturnRegEx, "%0D")), filepath.indexOf(" ") !== -1 && (filepath = filepath.replace(tabRegEx, "%09")), filepath;
88
98
  }
89
- const posixDirname = dirname, posixResolve = resolve;
99
+ const posixDirname = dirname;
100
+ const posixResolve = resolve;
90
101
  function posixPathToFileHref(posixPath) {
91
102
  let resolved = posixResolve(posixPath), filePathLast = posixPath.charCodeAt(posixPath.length - 1);
92
103
  return (filePathLast === 47 || isWindows && filePathLast === 92) && resolved[resolved.length - 1] !== "/" && (resolved += "/"), resolved = encodePathChars(resolved), resolved.indexOf("?") !== -1 && (resolved = resolved.replace(questionRegex, "%3F")), resolved.indexOf("#") !== -1 && (resolved = resolved.replace(hashRegex, "%23")), new URL(`file://${resolved}`).href;
@@ -94,7 +105,10 @@ function posixPathToFileHref(posixPath) {
94
105
  function toWindowsPath(path) {
95
106
  return path.replace(/\//g, "\\");
96
107
  }
97
- var comma = 44, chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", intToChar = new Uint8Array(64), charToInt = new Uint8Array(128);
108
+ var comma = 44;
109
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
110
+ var intToChar = /* @__PURE__ */ new Uint8Array(64);
111
+ var charToInt = /* @__PURE__ */ new Uint8Array(128);
98
112
  for (let i = 0; i < chars.length; i++) {
99
113
  let c = chars.charCodeAt(i);
100
114
  intToChar[i] = c, charToInt[c] = i;
@@ -154,7 +168,12 @@ function sort(line) {
154
168
  function sortComparator(a, b) {
155
169
  return a[0] - b[0];
156
170
  }
157
- var COLUMN = 0, SOURCES_INDEX = 1, SOURCE_LINE = 2, SOURCE_COLUMN = 3, NAMES_INDEX = 4, found = !1;
171
+ var COLUMN = 0;
172
+ var SOURCES_INDEX = 1;
173
+ var SOURCE_LINE = 2;
174
+ var SOURCE_COLUMN = 3;
175
+ var NAMES_INDEX = 4;
176
+ var found = !1;
158
177
  function binarySearch(haystack, needle, low, high) {
159
178
  for (; low <= high;) {
160
179
  let mid = low + (high - low >> 1), cmp = haystack[mid][COLUMN] - needle;
@@ -179,7 +198,10 @@ function memoizedBinarySearch(haystack, needle, state, key) {
179
198
  }
180
199
  return state.lastKey = key, state.lastNeedle = needle, state.lastIndex = binarySearch(haystack, needle, low, high);
181
200
  }
182
- var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)", COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)", LEAST_UPPER_BOUND = -1, GREATEST_LOWER_BOUND = 1;
201
+ var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)";
202
+ var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)";
203
+ var LEAST_UPPER_BOUND = -1;
204
+ var GREATEST_LOWER_BOUND = 1;
183
205
  function cast(map) {
184
206
  return map;
185
207
  }
@@ -250,7 +272,8 @@ var EvaluatedModuleNode = class {
250
272
  constructor(id, url) {
251
273
  this.id = id, this.url = url, this.file = cleanUrl(id);
252
274
  }
253
- }, EvaluatedModules = class {
275
+ };
276
+ var EvaluatedModules = class {
254
277
  idToModuleMap = /* @__PURE__ */ new Map();
255
278
  fileToModulesMap = /* @__PURE__ */ new Map();
256
279
  urlToIdModuleMap = /* @__PURE__ */ new Map();
@@ -290,7 +313,7 @@ var EvaluatedModuleNode = class {
290
313
  this.idToModuleMap.clear(), this.fileToModulesMap.clear(), this.urlToIdModuleMap.clear();
291
314
  }
292
315
  };
293
- const prefixedBuiltins = new Set([
316
+ const prefixedBuiltins = /* @__PURE__ */ new Set([
294
317
  "node:sea",
295
318
  "node:sqlite",
296
319
  "node:test",
@@ -380,7 +403,8 @@ var HMRContext = class {
380
403
  fn: callback
381
404
  }), this.hmrClient.hotModulesMap.set(this.ownerPath, mod);
382
405
  }
383
- }, HMRClient = class {
406
+ };
407
+ var HMRClient = class {
384
408
  hotModulesMap = /* @__PURE__ */ new Map();
385
409
  disposeMap = /* @__PURE__ */ new Map();
386
410
  pruneMap = /* @__PURE__ */ new Map();
@@ -548,7 +572,8 @@ const createInvokeableTransport = (transport) => {
548
572
  }
549
573
  }
550
574
  };
551
- }, normalizeModuleRunnerTransport = (transport) => {
575
+ };
576
+ const normalizeModuleRunnerTransport = (transport) => {
552
577
  let invokeableTransport = createInvokeableTransport(transport), isConnected = !invokeableTransport.connect, connectingPromise;
553
578
  return {
554
579
  ...transport,
@@ -582,7 +607,8 @@ const createInvokeableTransport = (transport) => {
582
607
  return invokeableTransport.invoke(name, data);
583
608
  }
584
609
  };
585
- }, createWebSocketModuleRunnerTransport = (options) => {
610
+ };
611
+ const createWebSocketModuleRunnerTransport = (options) => {
586
612
  let pingInterval = options.pingInterval ?? 3e4, ws, pingIntervalId;
587
613
  return {
588
614
  async connect({ onMessage, onDisconnection }) {
@@ -620,10 +646,19 @@ const createInvokeableTransport = (transport) => {
620
646
  ws.send(JSON.stringify(data));
621
647
  }
622
648
  };
623
- }, ssrModuleExportsKey = "__vite_ssr_exports__", ssrImportKey = "__vite_ssr_import__", ssrDynamicImportKey = "__vite_ssr_dynamic_import__", ssrExportAllKey = "__vite_ssr_exportAll__", ssrExportNameKey = "__vite_ssr_exportName__", ssrImportMetaKey = "__vite_ssr_import_meta__", noop = () => {}, silentConsole = {
649
+ };
650
+ const ssrModuleExportsKey = "__vite_ssr_exports__";
651
+ const ssrImportKey = "__vite_ssr_import__";
652
+ const ssrDynamicImportKey = "__vite_ssr_dynamic_import__";
653
+ const ssrExportAllKey = "__vite_ssr_exportAll__";
654
+ const ssrExportNameKey = "__vite_ssr_exportName__";
655
+ const ssrImportMetaKey = "__vite_ssr_import_meta__";
656
+ const noop = () => {};
657
+ const silentConsole = {
624
658
  debug: noop,
625
659
  error: noop
626
- }, hmrLogger = {
660
+ };
661
+ const hmrLogger = {
627
662
  debug: (...msg) => console.log("[vite]", ...msg),
628
663
  error: (error) => console.log("[vite]", error)
629
664
  };
@@ -715,13 +750,20 @@ function findAllEntrypoints(runner, entrypoints = /* @__PURE__ */ new Set()) {
715
750
  for (let mod of runner.evaluatedModules.idToModuleMap.values()) mod.importers.size || entrypoints.add(mod.url);
716
751
  return entrypoints;
717
752
  }
718
- const sourceMapCache = {}, fileContentsCache = {}, evaluatedModulesCache = /* @__PURE__ */ new Set(), retrieveFileHandlers = /* @__PURE__ */ new Set(), retrieveSourceMapHandlers = /* @__PURE__ */ new Set(), createExecHandlers = (handlers) => ((...args) => {
753
+ const sourceMapCache = {};
754
+ const fileContentsCache = {};
755
+ const evaluatedModulesCache = /* @__PURE__ */ new Set();
756
+ const retrieveFileHandlers = /* @__PURE__ */ new Set();
757
+ const retrieveSourceMapHandlers = /* @__PURE__ */ new Set();
758
+ const createExecHandlers = (handlers) => ((...args) => {
719
759
  for (let handler of handlers) {
720
760
  let result = handler(...args);
721
761
  if (result) return result;
722
762
  }
723
763
  return null;
724
- }), retrieveFileFromHandlers = createExecHandlers(retrieveFileHandlers), retrieveSourceMapFromHandlers = createExecHandlers(retrieveSourceMapHandlers);
764
+ });
765
+ const retrieveFileFromHandlers = createExecHandlers(retrieveFileHandlers);
766
+ const retrieveSourceMapFromHandlers = createExecHandlers(retrieveSourceMapHandlers);
725
767
  let overridden = !1;
726
768
  const originalPrepare = Error.prepareStackTrace;
727
769
  function resetInterceptor(runner, options) {
@@ -909,7 +951,8 @@ var ESModulesEvaluator = class {
909
951
  return import(filepath);
910
952
  }
911
953
  };
912
- const customizationHookNamespace = "vite-module-runner:import-meta-resolve/v1/", customizationHooksModule = `
954
+ const customizationHookNamespace = "vite-module-runner:import-meta-resolve/v1/";
955
+ const customizationHooksModule = `
913
956
 
914
957
  export async function resolve(specifier, context, nextResolve) {
915
958
  if (specifier.startsWith(${JSON.stringify(customizationHookNamespace)})) {
@@ -1124,6 +1167,5 @@ function exportAll(exports, sourceModule) {
1124
1167
  } catch {}
1125
1168
  }
1126
1169
  }
1127
-
1128
1170
  //#endregion
1129
- export { ESModulesEvaluator, EvaluatedModules, ModuleRunner, createDefaultImportMeta, createNodeImportMeta, createWebSocketModuleRunnerTransport, normalizeModuleId, ssrDynamicImportKey, ssrExportAllKey, ssrExportNameKey, ssrImportKey, ssrImportMetaKey, ssrModuleExportsKey };
1171
+ export { ESModulesEvaluator, EvaluatedModules, ModuleRunner, createDefaultImportMeta, createNodeImportMeta, createWebSocketModuleRunnerTransport, normalizeModuleId, ssrDynamicImportKey, ssrExportAllKey, ssrExportNameKey, ssrImportKey, ssrImportMetaKey, ssrModuleExportsKey };