@cloudflare/vite-plugin 0.0.0-1d2d23683 → 0.0.0-1f27e267f

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
@@ -1,6 +1,8 @@
1
1
  // src/index.ts
2
- import assert9 from "node:assert";
2
+ import assert8 from "node:assert";
3
3
  import * as fs5 from "node:fs";
4
+ import * as fsp2 from "node:fs/promises";
5
+ import { builtinModules as builtinModules2 } from "node:module";
4
6
  import * as path7 from "node:path";
5
7
  import { createMiddleware } from "@hattip/adapter-node";
6
8
 
@@ -1072,801 +1074,128 @@ var MagicString = class _MagicString {
1072
1074
  import { Miniflare } from "miniflare";
1073
1075
  import * as vite6 from "vite";
1074
1076
 
1075
- // src/cloudflare-environment.ts
1076
- import assert from "node:assert";
1077
- import * as vite2 from "vite";
1078
-
1079
1077
  // src/constants.ts
1080
1078
  var ROUTER_WORKER_NAME = "__router-worker__";
1081
1079
  var ASSET_WORKER_NAME = "__asset-worker__";
1082
1080
  var ASSET_WORKERS_COMPATIBILITY_DATE = "2024-10-04";
1083
- var MODULE_TYPES = ["CompiledWasm"];
1084
-
1085
- // src/shared.ts
1086
- var UNKNOWN_HOST = "http://localhost";
1087
- var INIT_PATH = "/__vite_plugin_cloudflare_init__";
1088
- var MODULE_PATTERN = `__CLOUDFLARE_MODULE__(${MODULE_TYPES.join("|")})__(.*?)__`;
1081
+ var ADDITIONAL_MODULE_TYPES = [
1082
+ "CompiledWasm",
1083
+ "Data",
1084
+ "Text"
1085
+ ];
1086
+ var DEFAULT_INSPECTOR_PORT = 9229;
1089
1087
 
1090
- // src/utils.ts
1091
- import { builtinModules } from "node:module";
1092
- import * as path from "node:path";
1093
- import { Request as MiniflareRequest } from "miniflare";
1094
- import "vite";
1095
- var nodeBuiltInModules = new Set(
1096
- builtinModules.concat(builtinModules.map((m) => `node:${m}`))
1097
- );
1098
- function getOutputDirectory(userConfig, environmentName) {
1099
- const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
1100
- return userConfig.environments?.[environmentName]?.build?.outDir ?? path.join(rootOutputDirectory, environmentName);
1101
- }
1102
- function toMiniflareRequest(request) {
1103
- return new MiniflareRequest(request.url, {
1104
- method: request.method,
1105
- headers: [["accept-encoding", "identity"], ...request.headers],
1106
- body: request.body,
1107
- duplex: "half"
1108
- });
1109
- }
1110
- function nodeHeadersToWebHeaders(nodeHeaders) {
1111
- const headers = new Headers();
1112
- for (const [key, value] of Object.entries(nodeHeaders)) {
1113
- if (typeof value === "string") {
1114
- headers.append(key, value);
1115
- } else if (Array.isArray(value)) {
1116
- for (const item of value) {
1117
- headers.append(key, item);
1088
+ // src/additional-modules.ts
1089
+ var moduleRules = [
1090
+ { type: "CompiledWasm", extensions: [".wasm", ".wasm?module"] },
1091
+ { type: "Data", extensions: [".bin"] },
1092
+ { type: "Text", extensions: [".txt", ".html"] }
1093
+ ];
1094
+ function matchAdditionalModule(source) {
1095
+ for (const rule of moduleRules) {
1096
+ for (const extension of rule.extensions) {
1097
+ if (source.endsWith(extension)) {
1098
+ return rule.type;
1118
1099
  }
1119
1100
  }
1120
1101
  }
1121
- return headers;
1102
+ return null;
1103
+ }
1104
+ function createModuleReference(type, id) {
1105
+ return `__CLOUDFLARE_MODULE__${type}__${id}__`;
1122
1106
  }
1123
1107
 
1124
1108
  // src/cloudflare-environment.ts
1125
- var webSocketUndefinedError = "The WebSocket is undefined";
1126
- function createHotChannel(webSocketContainer) {
1127
- const listenersMap = /* @__PURE__ */ new Map();
1128
- const client = {
1129
- send(payload) {
1130
- const webSocket = webSocketContainer.webSocket;
1131
- assert(webSocket, webSocketUndefinedError);
1132
- webSocket.send(JSON.stringify(payload));
1109
+ import assert3 from "node:assert";
1110
+ import * as vite2 from "vite";
1111
+
1112
+ // src/node-js-compat.ts
1113
+ import assert2 from "node:assert";
1114
+ import { cloudflare } from "@cloudflare/unenv-preset";
1115
+ import { getNodeCompat } from "miniflare";
1116
+
1117
+ // ../../node_modules/.pnpm/acorn@8.14.0/node_modules/acorn/dist/acorn.mjs
1118
+ var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 80, 3, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 343, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 726, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
1119
+ var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 2, 60, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 42, 9, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 496, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191];
1120
+ var nonASCIIidentifierChars = "\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ACE\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F\uFF65";
1121
+ var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CD\uA7D0\uA7D1\uA7D3\uA7D5-\uA7DC\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC";
1122
+ var reservedWords = {
1123
+ 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
1124
+ 5: "class enum extends super const export import",
1125
+ 6: "enum",
1126
+ strict: "implements interface let package private protected public static yield",
1127
+ strictBind: "eval arguments"
1128
+ };
1129
+ var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
1130
+ var keywords$1 = {
1131
+ 5: ecma5AndLessKeywords,
1132
+ "5module": ecma5AndLessKeywords + " export import",
1133
+ 6: ecma5AndLessKeywords + " const class extends export import super"
1134
+ };
1135
+ var keywordRelationalOperator = /^in(stanceof)?$/;
1136
+ var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
1137
+ var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
1138
+ function isInAstralSet(code, set) {
1139
+ var pos = 65536;
1140
+ for (var i = 0; i < set.length; i += 2) {
1141
+ pos += set[i];
1142
+ if (pos > code) {
1143
+ return false;
1133
1144
  }
1134
- };
1135
- function onMessage(event) {
1136
- const payload = JSON.parse(event.data.toString());
1137
- const listeners = listenersMap.get(payload.event) ?? /* @__PURE__ */ new Set();
1138
- for (const listener of listeners) {
1139
- listener(payload.data, client);
1145
+ pos += set[i + 1];
1146
+ if (pos >= code) {
1147
+ return true;
1140
1148
  }
1141
1149
  }
1142
- return {
1143
- send(payload) {
1144
- const webSocket = webSocketContainer.webSocket;
1145
- assert(webSocket, webSocketUndefinedError);
1146
- webSocket.send(JSON.stringify(payload));
1147
- },
1148
- on(event, listener) {
1149
- const listeners = listenersMap.get(event) ?? /* @__PURE__ */ new Set();
1150
- listeners.add(listener);
1151
- listenersMap.set(event, listeners);
1152
- },
1153
- off(event, listener) {
1154
- listenersMap.get(event)?.delete(listener);
1155
- },
1156
- listen() {
1157
- const webSocket = webSocketContainer.webSocket;
1158
- assert(webSocket, webSocketUndefinedError);
1159
- webSocket.addEventListener("message", onMessage);
1160
- },
1161
- close() {
1162
- const webSocket = webSocketContainer.webSocket;
1163
- assert(webSocket, webSocketUndefinedError);
1164
- webSocket.removeEventListener("message", onMessage);
1165
- }
1166
- };
1150
+ return false;
1167
1151
  }
1168
- var CloudflareDevEnvironment = class extends vite2.DevEnvironment {
1169
- #webSocketContainer;
1170
- #worker;
1171
- constructor(name2, config) {
1172
- const webSocketContainer = {};
1173
- super(name2, config, {
1174
- hot: true,
1175
- transport: createHotChannel(webSocketContainer)
1176
- });
1177
- this.#webSocketContainer = webSocketContainer;
1152
+ function isIdentifierStart(code, astral) {
1153
+ if (code < 65) {
1154
+ return code === 36;
1178
1155
  }
1179
- async initRunner(worker) {
1180
- this.#worker = worker;
1181
- const response = await this.#worker.fetch(
1182
- new URL(INIT_PATH, UNKNOWN_HOST),
1183
- {
1184
- headers: {
1185
- upgrade: "websocket"
1186
- }
1187
- }
1188
- );
1189
- assert(
1190
- response.ok,
1191
- `Failed to initialize module runner, error: ${await response.text()}`
1192
- );
1193
- const webSocket = response.webSocket;
1194
- assert(webSocket, "Failed to establish WebSocket");
1195
- webSocket.accept();
1196
- this.#webSocketContainer.webSocket = webSocket;
1156
+ if (code < 91) {
1157
+ return true;
1197
1158
  }
1198
- };
1199
- var cloudflareBuiltInModules = [
1200
- "cloudflare:email",
1201
- "cloudflare:sockets",
1202
- "cloudflare:workers",
1203
- "cloudflare:workflows"
1204
- ];
1205
- var defaultConditions = ["workerd", "module", "browser"];
1206
- function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmentName) {
1207
- return {
1208
- resolve: {
1209
- // Note: in order for ssr pre-bundling to take effect we need to ask vite to treat all
1210
- // dependencies as not external
1211
- noExternal: true,
1212
- // We want to use `workerd` package exports if available (e.g. for postgres).
1213
- conditions: [...defaultConditions, "development|production"],
1214
- // The Cloudflare ones are proper builtins in the environment
1215
- builtins: [...cloudflareBuiltInModules],
1216
- // The Node.js ones are no proper builtins in the environment since we also polyfill them using unenv
1217
- external: [...nodeBuiltInModules]
1218
- },
1219
- dev: {
1220
- createEnvironment(name2, config) {
1221
- return new CloudflareDevEnvironment(name2, config);
1222
- }
1223
- },
1224
- build: {
1225
- createEnvironment(name2, config) {
1226
- return new vite2.BuildEnvironment(name2, config);
1227
- },
1228
- target: "es2022",
1229
- // We need to enable `emitAssets` in order to support additional modules defined by `rules`
1230
- emitAssets: true,
1231
- outDir: getOutputDirectory(userConfig, environmentName),
1232
- copyPublicDir: false,
1233
- ssr: true,
1234
- rollupOptions: {
1235
- // Note: vite starts dev pre-bundling crawling from either optimizeDeps.entries or rollupOptions.input
1236
- // so the input value here serves both as the build input as well as the starting point for
1237
- // dev pre-bundling crawling (were we not to set this input field we'd have to appropriately set
1238
- // optimizeDeps.entries in the dev config)
1239
- input: workerConfig.main
1240
- }
1241
- },
1242
- optimizeDeps: {
1243
- // Note: ssr pre-bundling is opt-in and we need to enable it by setting `noDiscovery` to false
1244
- noDiscovery: false,
1245
- entries: workerConfig.main,
1246
- exclude: [
1247
- // we have to exclude all node modules to work in dev-mode not just the unenv externals...
1248
- ...nodeBuiltInModules
1249
- ],
1250
- esbuildOptions: {
1251
- platform: "neutral",
1252
- conditions: [...defaultConditions, "development"],
1253
- resolveExtensions: [
1254
- ".mjs",
1255
- ".js",
1256
- ".mts",
1257
- ".ts",
1258
- ".jsx",
1259
- ".tsx",
1260
- ".json",
1261
- ".cjs",
1262
- ".cts",
1263
- ".ctx"
1264
- ]
1265
- }
1266
- },
1267
- keepProcessEnv: false
1268
- };
1269
- }
1270
- function initRunners(resolvedPluginConfig, viteDevServer, miniflare) {
1271
- if (resolvedPluginConfig.type === "assets-only") {
1272
- return;
1159
+ if (code < 97) {
1160
+ return code === 95;
1273
1161
  }
1274
- return Promise.all(
1275
- Object.entries(resolvedPluginConfig.workers).map(
1276
- async ([environmentName, workerConfig]) => {
1277
- const worker = await miniflare.getWorker(workerConfig.name);
1278
- return viteDevServer.environments[environmentName].initRunner(worker);
1279
- }
1280
- )
1281
- );
1162
+ if (code < 123) {
1163
+ return true;
1164
+ }
1165
+ if (code <= 65535) {
1166
+ return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code));
1167
+ }
1168
+ if (astral === false) {
1169
+ return false;
1170
+ }
1171
+ return isInAstralSet(code, astralIdentifierStartCodes);
1282
1172
  }
1283
-
1284
- // src/deploy-config.ts
1285
- import assert2 from "node:assert";
1286
- import * as fs from "node:fs";
1287
- import * as path2 from "node:path";
1288
- import "vite";
1289
- function getDeployConfigPath(root) {
1290
- return path2.resolve(root, ".wrangler", "deploy", "config.json");
1291
- }
1292
- function getWorkerConfigPaths(root) {
1293
- const deployConfigPath = getDeployConfigPath(root);
1294
- const deployConfig = JSON.parse(
1295
- fs.readFileSync(deployConfigPath, "utf-8")
1296
- );
1297
- return [
1298
- { configPath: deployConfig.configPath },
1299
- ...deployConfig.auxiliaryWorkers
1300
- ].map(
1301
- ({ configPath }) => path2.resolve(path2.dirname(deployConfigPath), configPath)
1302
- );
1303
- }
1304
- function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
1305
- return path2.relative(
1306
- deployConfigDirectory,
1307
- path2.resolve(root, outputDirectory, "wrangler.json")
1308
- );
1309
- }
1310
- function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
1311
- const deployConfigPath = getDeployConfigPath(resolvedViteConfig.root);
1312
- const deployConfigDirectory = path2.dirname(deployConfigPath);
1313
- fs.mkdirSync(deployConfigDirectory, { recursive: true });
1314
- if (resolvedPluginConfig.type === "assets-only") {
1315
- const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
1316
- assert2(
1317
- clientOutputDirectory,
1318
- "Unexpected error: client environment output directory is undefined"
1319
- );
1320
- const deployConfig = {
1321
- configPath: getRelativePathToWorkerConfig(
1322
- deployConfigDirectory,
1323
- resolvedViteConfig.root,
1324
- clientOutputDirectory
1325
- ),
1326
- auxiliaryWorkers: []
1327
- };
1328
- fs.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
1329
- } else {
1330
- let entryWorkerConfigPath;
1331
- const auxiliaryWorkers = [];
1332
- for (const environmentName of Object.keys(resolvedPluginConfig.workers)) {
1333
- const outputDirectory = resolvedViteConfig.environments[environmentName]?.build.outDir;
1334
- assert2(
1335
- outputDirectory,
1336
- `Unexpected error: ${environmentName} environment output directory is undefined`
1337
- );
1338
- const configPath = getRelativePathToWorkerConfig(
1339
- deployConfigDirectory,
1340
- resolvedViteConfig.root,
1341
- outputDirectory
1342
- );
1343
- if (environmentName === resolvedPluginConfig.entryWorkerEnvironmentName) {
1344
- entryWorkerConfigPath = configPath;
1345
- } else {
1346
- auxiliaryWorkers.push({ configPath });
1347
- }
1348
- }
1349
- assert2(
1350
- entryWorkerConfigPath,
1351
- `Unexpected error: entryWorkerConfigPath is undefined`
1352
- );
1353
- const deployConfig = {
1354
- configPath: entryWorkerConfigPath,
1355
- auxiliaryWorkers
1356
- };
1357
- fs.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
1358
- }
1359
- }
1360
-
1361
- // src/dev.ts
1362
- import assert3 from "node:assert";
1363
- function getDevEntryWorker(resolvedPluginConfig, miniflare) {
1364
- const entryWorkerConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config : resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
1365
- assert3(entryWorkerConfig, "Unexpected error: No entry worker configuration");
1366
- return entryWorkerConfig.assets ? miniflare.getWorker(ROUTER_WORKER_NAME) : miniflare.getWorker(entryWorkerConfig.name);
1367
- }
1368
-
1369
- // src/miniflare-options.ts
1370
- import assert4 from "node:assert";
1371
- import * as fs2 from "node:fs";
1372
- import * as fsp from "node:fs/promises";
1373
- import * as path3 from "node:path";
1374
- import { fileURLToPath } from "node:url";
1375
- import { Log, LogLevel, Response as MiniflareResponse } from "miniflare";
1376
- import "vite";
1377
- import {
1378
- unstable_getMiniflareWorkerOptions,
1379
- unstable_readConfig
1380
- } from "wrangler";
1381
- function getPersistence(root, persistState) {
1382
- if (persistState === false) {
1383
- return {};
1384
- }
1385
- const defaultPersistPath = ".wrangler/state";
1386
- const persistPath = path3.resolve(
1387
- root,
1388
- typeof persistState === "object" ? persistState.path : defaultPersistPath,
1389
- "v3"
1390
- );
1391
- return {
1392
- cachePersist: path3.join(persistPath, "cache"),
1393
- d1Persist: path3.join(persistPath, "d1"),
1394
- durableObjectsPersist: path3.join(persistPath, "do"),
1395
- kvPersist: path3.join(persistPath, "kv"),
1396
- r2Persist: path3.join(persistPath, "r2"),
1397
- workflowsPersist: path3.join(persistPath, "workflows")
1398
- };
1399
- }
1400
- function missingWorkerErrorMessage(workerName) {
1401
- return `${workerName} does not match a worker name.`;
1402
- }
1403
- function getWorkerToWorkerEntrypointNamesMap(workers) {
1404
- const workerToWorkerEntrypointNamesMap = new Map(
1405
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1406
- );
1407
- for (const worker of workers) {
1408
- for (const value of Object.values(worker.serviceBindings ?? {})) {
1409
- if (typeof value === "object" && "name" in value && typeof value.name === "string" && value.entrypoint !== void 0 && value.entrypoint !== "default") {
1410
- const entrypointNames = workerToWorkerEntrypointNamesMap.get(
1411
- value.name
1412
- );
1413
- assert4(entrypointNames, missingWorkerErrorMessage(value.name));
1414
- entrypointNames.add(value.entrypoint);
1415
- }
1416
- }
1417
- }
1418
- return workerToWorkerEntrypointNamesMap;
1419
- }
1420
- function getWorkerToDurableObjectClassNamesMap(workers) {
1421
- const workerToDurableObjectClassNamesMap = new Map(
1422
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1423
- );
1424
- for (const worker of workers) {
1425
- for (const value of Object.values(worker.durableObjects ?? {})) {
1426
- if (typeof value === "string") {
1427
- const classNames = workerToDurableObjectClassNamesMap.get(worker.name);
1428
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1429
- classNames.add(value);
1430
- } else if (typeof value === "object") {
1431
- if (value.scriptName) {
1432
- const classNames = workerToDurableObjectClassNamesMap.get(
1433
- value.scriptName
1434
- );
1435
- assert4(classNames, missingWorkerErrorMessage(value.scriptName));
1436
- classNames.add(value.className);
1437
- } else {
1438
- const classNames = workerToDurableObjectClassNamesMap.get(
1439
- worker.name
1440
- );
1441
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1442
- classNames.add(value.className);
1443
- }
1444
- }
1445
- }
1446
- }
1447
- return workerToDurableObjectClassNamesMap;
1448
- }
1449
- function getWorkerToWorkflowEntrypointClassNamesMap(workers) {
1450
- const workerToWorkflowEntrypointClassNamesMap = new Map(
1451
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1452
- );
1453
- for (const worker of workers) {
1454
- for (const value of Object.values(worker.workflows ?? {})) {
1455
- if (value.scriptName) {
1456
- const classNames = workerToWorkflowEntrypointClassNamesMap.get(
1457
- value.scriptName
1458
- );
1459
- assert4(classNames, missingWorkerErrorMessage(value.scriptName));
1460
- classNames.add(value.className);
1461
- } else {
1462
- const classNames = workerToWorkflowEntrypointClassNamesMap.get(
1463
- worker.name
1464
- );
1465
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1466
- classNames.add(value.className);
1467
- }
1468
- }
1469
- }
1470
- return workerToWorkflowEntrypointClassNamesMap;
1471
- }
1472
- var miniflareModulesRoot = process.platform === "win32" ? "Z:\\" : "/";
1473
- var ROUTER_WORKER_PATH = "./asset-workers/router-worker.js";
1474
- var ASSET_WORKER_PATH = "./asset-workers/asset-worker.js";
1475
- var WRAPPER_PATH = "__VITE_WORKER_ENTRY__";
1476
- var RUNNER_PATH = "./runner-worker/index.js";
1477
- function getEntryWorkerConfig(resolvedPluginConfig) {
1478
- if (resolvedPluginConfig.type === "assets-only") {
1479
- return;
1480
- }
1481
- return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
1482
- }
1483
- function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1484
- const resolvedViteConfig = viteDevServer.config;
1485
- const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
1486
- const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
1487
- const assetWorkers = [
1488
- {
1489
- name: ROUTER_WORKER_NAME,
1490
- compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
1491
- modulesRoot: miniflareModulesRoot,
1492
- modules: [
1493
- {
1494
- type: "ESModule",
1495
- path: path3.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
1496
- contents: fs2.readFileSync(
1497
- fileURLToPath(new URL(ROUTER_WORKER_PATH, import.meta.url))
1498
- )
1499
- }
1500
- ],
1501
- bindings: {
1502
- CONFIG: {
1503
- has_user_worker: resolvedPluginConfig.type === "workers"
1504
- }
1505
- },
1506
- serviceBindings: {
1507
- ASSET_WORKER: ASSET_WORKER_NAME,
1508
- ...entryWorkerConfig ? { USER_WORKER: entryWorkerConfig.name } : {}
1509
- }
1510
- },
1511
- {
1512
- name: ASSET_WORKER_NAME,
1513
- compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
1514
- modulesRoot: miniflareModulesRoot,
1515
- modules: [
1516
- {
1517
- type: "ESModule",
1518
- path: path3.join(miniflareModulesRoot, ASSET_WORKER_PATH),
1519
- contents: fs2.readFileSync(
1520
- fileURLToPath(new URL(ASSET_WORKER_PATH, import.meta.url))
1521
- )
1522
- }
1523
- ],
1524
- bindings: {
1525
- CONFIG: {
1526
- ...assetsConfig?.html_handling ? { html_handling: assetsConfig.html_handling } : {},
1527
- ...assetsConfig?.not_found_handling ? { not_found_handling: assetsConfig.not_found_handling } : {}
1528
- }
1529
- },
1530
- serviceBindings: {
1531
- __VITE_ASSET_EXISTS__: async (request) => {
1532
- const { pathname } = new URL(request.url);
1533
- const filePath = path3.join(resolvedViteConfig.root, pathname);
1534
- let exists;
1535
- try {
1536
- exists = fs2.statSync(filePath).isFile();
1537
- } catch (error) {
1538
- exists = false;
1539
- }
1540
- return MiniflareResponse.json(exists);
1541
- },
1542
- __VITE_FETCH_ASSET__: async (request) => {
1543
- const { pathname } = new URL(request.url);
1544
- const filePath = path3.join(resolvedViteConfig.root, pathname);
1545
- try {
1546
- let html = await fsp.readFile(filePath, "utf-8");
1547
- html = await viteDevServer.transformIndexHtml(pathname, html);
1548
- return new MiniflareResponse(html, {
1549
- headers: { "Content-Type": "text/html" }
1550
- });
1551
- } catch (error) {
1552
- throw new Error(`Unexpected error. Failed to load ${pathname}`);
1553
- }
1554
- }
1555
- }
1556
- }
1557
- ];
1558
- const userWorkers = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1559
- ([environmentName, workerConfig]) => {
1560
- const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
1561
- {
1562
- ...workerConfig,
1563
- assets: void 0
1564
- },
1565
- resolvedPluginConfig.cloudflareEnv
1566
- );
1567
- const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1568
- return {
1569
- ...workerOptions,
1570
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1571
- name: workerConfig.name,
1572
- modulesRoot: miniflareModulesRoot,
1573
- unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
1574
- bindings: {
1575
- ...workerOptions.bindings,
1576
- __VITE_ROOT__: resolvedViteConfig.root,
1577
- __VITE_ENTRY_PATH__: workerConfig.main
1578
- },
1579
- serviceBindings: {
1580
- ...workerOptions.serviceBindings,
1581
- ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
1582
- [workerConfig.assets.binding]: ASSET_WORKER_NAME
1583
- } : {},
1584
- __VITE_INVOKE_MODULE__: async (request) => {
1585
- const payload = await request.json();
1586
- const invokePayloadData = payload.data;
1587
- assert4(
1588
- invokePayloadData.name === "fetchModule",
1589
- `Invalid invoke event: ${invokePayloadData.name}`
1590
- );
1591
- const [moduleId] = invokePayloadData.data;
1592
- const moduleRE = new RegExp(MODULE_PATTERN);
1593
- const shouldExternalize = (
1594
- // Worker modules (CompiledWasm, Text, Data)
1595
- moduleRE.test(moduleId) || // Node.js builtin node modules (they will be resolved to unenv aliases)
1596
- nodeBuiltInModules.has(moduleId)
1597
- );
1598
- if (shouldExternalize) {
1599
- const result2 = {
1600
- externalize: moduleId,
1601
- type: "module"
1602
- };
1603
- return MiniflareResponse.json({ result: result2 });
1604
- }
1605
- const devEnvironment = viteDevServer.environments[environmentName];
1606
- const result = await devEnvironment.hot.handleInvoke(payload);
1607
- return MiniflareResponse.json(result);
1608
- }
1609
- }
1610
- };
1611
- }
1612
- ) : [];
1613
- const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
1614
- const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
1615
- const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
1616
- const logger = new ViteMiniflareLogger(resolvedViteConfig);
1617
- return {
1618
- log: logger,
1619
- handleRuntimeStdio(stdout, stderr) {
1620
- const decoder = new TextDecoder();
1621
- stdout.forEach((data2) => logger.info(decoder.decode(data2)));
1622
- stderr.forEach(
1623
- (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
1624
- );
1625
- },
1626
- ...getPersistence(
1627
- resolvedViteConfig.root,
1628
- resolvedPluginConfig.persistState
1629
- ),
1630
- workers: [
1631
- ...assetWorkers,
1632
- ...userWorkers.map((workerOptions) => {
1633
- const wrappers = [
1634
- `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
1635
- `export default createWorkerEntrypointWrapper('default');`
1636
- ];
1637
- const workerEntrypointNames = workerToWorkerEntrypointNamesMap.get(
1638
- workerOptions.name
1639
- );
1640
- assert4(
1641
- workerEntrypointNames,
1642
- `WorkerEntrypoint names not found for worker ${workerOptions.name}`
1643
- );
1644
- for (const entrypointName of [...workerEntrypointNames].sort()) {
1645
- wrappers.push(
1646
- `export const ${entrypointName} = createWorkerEntrypointWrapper('${entrypointName}');`
1647
- );
1648
- }
1649
- const durableObjectClassNames = workerToDurableObjectClassNamesMap.get(
1650
- workerOptions.name
1651
- );
1652
- assert4(
1653
- durableObjectClassNames,
1654
- `DurableObject class names not found for worker ${workerOptions.name}`
1655
- );
1656
- for (const className of [...durableObjectClassNames].sort()) {
1657
- wrappers.push(
1658
- `export const ${className} = createDurableObjectWrapper('${className}');`
1659
- );
1660
- }
1661
- const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
1662
- assert4(
1663
- workflowEntrypointClassNames,
1664
- `WorkflowEntrypoint class names not found for worker ${workerOptions.name}`
1665
- );
1666
- for (const className of [...workflowEntrypointClassNames].sort()) {
1667
- wrappers.push(
1668
- `export const ${className} = createWorkflowEntrypointWrapper('${className}');`
1669
- );
1670
- }
1671
- return {
1672
- ...workerOptions,
1673
- modules: [
1674
- {
1675
- type: "ESModule",
1676
- path: path3.join(miniflareModulesRoot, WRAPPER_PATH),
1677
- contents: wrappers.join("\n")
1678
- },
1679
- {
1680
- type: "ESModule",
1681
- path: path3.join(miniflareModulesRoot, RUNNER_PATH),
1682
- contents: fs2.readFileSync(
1683
- fileURLToPath(new URL(RUNNER_PATH, import.meta.url))
1684
- )
1685
- }
1686
- ],
1687
- unsafeUseModuleFallbackService: true
1688
- };
1689
- })
1690
- ],
1691
- unsafeModuleFallbackService(request) {
1692
- const url = new URL(request.url);
1693
- const rawSpecifier = url.searchParams.get("rawSpecifier");
1694
- assert4(
1695
- rawSpecifier,
1696
- `Unexpected error: no specifier in request to module fallback service.`
1697
- );
1698
- const moduleRE = new RegExp(MODULE_PATTERN);
1699
- const match = moduleRE.exec(rawSpecifier);
1700
- assert4(match, `Unexpected error: no match for module ${rawSpecifier}.`);
1701
- const [full, moduleType, modulePath] = match;
1702
- assert4(
1703
- modulePath,
1704
- `Unexpected error: module path not found in reference ${full}.`
1705
- );
1706
- let source;
1707
- try {
1708
- source = fs2.readFileSync(modulePath);
1709
- } catch (error) {
1710
- throw new Error(`Import ${modulePath} not found. Does the file exist?`);
1711
- }
1712
- return MiniflareResponse.json({
1713
- // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
1714
- wasm: Array.from(source)
1715
- });
1716
- }
1717
- };
1718
- }
1719
- function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
1720
- const resolvedViteConfig = vitePreviewServer.config;
1721
- const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
1722
- const workerConfigs = configPaths.map(
1723
- (configPath) => unstable_readConfig({ config: configPath })
1724
- );
1725
- const workers = workerConfigs.map((config) => {
1726
- const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
1727
- const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1728
- return {
1729
- ...workerOptions,
1730
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1731
- name: config.name,
1732
- modules: true,
1733
- ...miniflareWorkerOptions.main ? { scriptPath: miniflareWorkerOptions.main } : { script: "" }
1734
- };
1735
- });
1736
- const logger = new ViteMiniflareLogger(resolvedViteConfig);
1737
- return {
1738
- log: logger,
1739
- handleRuntimeStdio(stdout, stderr) {
1740
- const decoder = new TextDecoder();
1741
- stdout.forEach((data2) => logger.info(decoder.decode(data2)));
1742
- stderr.forEach(
1743
- (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
1744
- );
1745
- },
1746
- ...getPersistence(resolvedViteConfig.root, persistState),
1747
- workers
1748
- };
1749
- }
1750
- var ViteMiniflareLogger = class extends Log {
1751
- logger;
1752
- constructor(config) {
1753
- super(miniflareLogLevelFromViteLogLevel(config.logLevel));
1754
- this.logger = config.logger;
1755
- }
1756
- logWithLevel(level, message) {
1757
- if (/^Ready on http/.test(message)) {
1758
- level = LogLevel.DEBUG;
1759
- }
1760
- switch (level) {
1761
- case LogLevel.ERROR:
1762
- return this.logger.error(message);
1763
- case LogLevel.WARN:
1764
- return this.logger.warn(message);
1765
- case LogLevel.INFO:
1766
- return this.logger.info(message);
1767
- }
1768
- }
1769
- };
1770
- function miniflareLogLevelFromViteLogLevel(level = "info") {
1771
- switch (level) {
1772
- case "error":
1773
- return LogLevel.ERROR;
1774
- case "warn":
1775
- return LogLevel.WARN;
1776
- case "info":
1777
- return LogLevel.INFO;
1778
- case "silent":
1779
- return LogLevel.NONE;
1780
- }
1781
- }
1782
-
1783
- // src/node-js-compat.ts
1784
- import assert6 from "node:assert";
1785
- import { cloudflare } from "@cloudflare/unenv-preset";
1786
- import { getNodeCompat } from "miniflare";
1787
-
1788
- // ../../node_modules/.pnpm/acorn@8.14.0/node_modules/acorn/dist/acorn.mjs
1789
- var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 80, 3, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 343, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 726, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
1790
- var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 2, 60, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 42, 9, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 496, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191];
1791
- var nonASCIIidentifierChars = "\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ACE\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F\uFF65";
1792
- var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CD\uA7D0\uA7D1\uA7D3\uA7D5-\uA7DC\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC";
1793
- var reservedWords = {
1794
- 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
1795
- 5: "class enum extends super const export import",
1796
- 6: "enum",
1797
- strict: "implements interface let package private protected public static yield",
1798
- strictBind: "eval arguments"
1799
- };
1800
- var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
1801
- var keywords$1 = {
1802
- 5: ecma5AndLessKeywords,
1803
- "5module": ecma5AndLessKeywords + " export import",
1804
- 6: ecma5AndLessKeywords + " const class extends export import super"
1805
- };
1806
- var keywordRelationalOperator = /^in(stanceof)?$/;
1807
- var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
1808
- var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
1809
- function isInAstralSet(code, set) {
1810
- var pos = 65536;
1811
- for (var i = 0; i < set.length; i += 2) {
1812
- pos += set[i];
1813
- if (pos > code) {
1814
- return false;
1815
- }
1816
- pos += set[i + 1];
1817
- if (pos >= code) {
1818
- return true;
1819
- }
1820
- }
1821
- return false;
1822
- }
1823
- function isIdentifierStart(code, astral) {
1824
- if (code < 65) {
1825
- return code === 36;
1826
- }
1827
- if (code < 91) {
1828
- return true;
1829
- }
1830
- if (code < 97) {
1831
- return code === 95;
1832
- }
1833
- if (code < 123) {
1834
- return true;
1835
- }
1836
- if (code <= 65535) {
1837
- return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code));
1838
- }
1839
- if (astral === false) {
1840
- return false;
1841
- }
1842
- return isInAstralSet(code, astralIdentifierStartCodes);
1843
- }
1844
- function isIdentifierChar(code, astral) {
1845
- if (code < 48) {
1846
- return code === 36;
1847
- }
1848
- if (code < 58) {
1849
- return true;
1850
- }
1851
- if (code < 65) {
1852
- return false;
1853
- }
1854
- if (code < 91) {
1855
- return true;
1856
- }
1857
- if (code < 97) {
1858
- return code === 95;
1859
- }
1860
- if (code < 123) {
1861
- return true;
1862
- }
1863
- if (code <= 65535) {
1864
- return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code));
1865
- }
1866
- if (astral === false) {
1867
- return false;
1868
- }
1869
- return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
1173
+ function isIdentifierChar(code, astral) {
1174
+ if (code < 48) {
1175
+ return code === 36;
1176
+ }
1177
+ if (code < 58) {
1178
+ return true;
1179
+ }
1180
+ if (code < 65) {
1181
+ return false;
1182
+ }
1183
+ if (code < 91) {
1184
+ return true;
1185
+ }
1186
+ if (code < 97) {
1187
+ return code === 95;
1188
+ }
1189
+ if (code < 123) {
1190
+ return true;
1191
+ }
1192
+ if (code <= 65535) {
1193
+ return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code));
1194
+ }
1195
+ if (astral === false) {
1196
+ return false;
1197
+ }
1198
+ return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
1870
1199
  }
1871
1200
  var TokenType = function TokenType2(label, conf) {
1872
1201
  if (conf === void 0) conf = {};
@@ -1881,16 +1210,16 @@ var TokenType = function TokenType2(label, conf) {
1881
1210
  this.binop = conf.binop || null;
1882
1211
  this.updateContext = null;
1883
1212
  };
1884
- function binop(name2, prec) {
1885
- return new TokenType(name2, { beforeExpr: true, binop: prec });
1213
+ function binop(name, prec) {
1214
+ return new TokenType(name, { beforeExpr: true, binop: prec });
1886
1215
  }
1887
1216
  var beforeExpr = { beforeExpr: true };
1888
1217
  var startsExpr = { startsExpr: true };
1889
1218
  var keywords = {};
1890
- function kw(name2, options) {
1219
+ function kw(name, options) {
1891
1220
  if (options === void 0) options = {};
1892
- options.keyword = name2;
1893
- return keywords[name2] = new TokenType(name2, options);
1221
+ options.keyword = name;
1222
+ return keywords[name] = new TokenType(name, options);
1894
1223
  }
1895
1224
  var types$1 = {
1896
1225
  num: new TokenType("num", startsExpr),
@@ -2367,18 +1696,18 @@ pp$9.eat = function(type) {
2367
1696
  return false;
2368
1697
  }
2369
1698
  };
2370
- pp$9.isContextual = function(name2) {
2371
- return this.type === types$1.name && this.value === name2 && !this.containsEsc;
1699
+ pp$9.isContextual = function(name) {
1700
+ return this.type === types$1.name && this.value === name && !this.containsEsc;
2372
1701
  };
2373
- pp$9.eatContextual = function(name2) {
2374
- if (!this.isContextual(name2)) {
1702
+ pp$9.eatContextual = function(name) {
1703
+ if (!this.isContextual(name)) {
2375
1704
  return false;
2376
1705
  }
2377
1706
  this.next();
2378
1707
  return true;
2379
1708
  };
2380
- pp$9.expectContextual = function(name2) {
2381
- if (!this.eatContextual(name2)) {
1709
+ pp$9.expectContextual = function(name) {
1710
+ if (!this.eatContextual(name)) {
2382
1711
  this.unexpected();
2383
1712
  }
2384
1713
  };
@@ -2472,8 +1801,8 @@ pp$8.parseTopLevel = function(node) {
2472
1801
  }
2473
1802
  if (this.inModule) {
2474
1803
  for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) {
2475
- var name2 = list[i];
2476
- this.raiseRecoverable(this.undefinedExports[name2].start, "Export '" + name2 + "' is not defined");
1804
+ var name = list[i];
1805
+ this.raiseRecoverable(this.undefinedExports[name].start, "Export '" + name + "' is not defined");
2477
1806
  }
2478
1807
  }
2479
1808
  this.adaptDirectivePrologue(node.body);
@@ -3216,26 +2545,26 @@ pp$8.exitClassBody = function() {
3216
2545
  }
3217
2546
  };
3218
2547
  function isPrivateNameConflicted(privateNameMap, element) {
3219
- var name2 = element.key.name;
3220
- var curr = privateNameMap[name2];
2548
+ var name = element.key.name;
2549
+ var curr = privateNameMap[name];
3221
2550
  var next = "true";
3222
2551
  if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
3223
2552
  next = (element.static ? "s" : "i") + element.kind;
3224
2553
  }
3225
2554
  if (curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget") {
3226
- privateNameMap[name2] = "true";
2555
+ privateNameMap[name] = "true";
3227
2556
  return false;
3228
2557
  } else if (!curr) {
3229
- privateNameMap[name2] = next;
2558
+ privateNameMap[name] = next;
3230
2559
  return false;
3231
2560
  } else {
3232
2561
  return true;
3233
2562
  }
3234
2563
  }
3235
- function checkKeyName(node, name2) {
2564
+ function checkKeyName(node, name) {
3236
2565
  var computed = node.computed;
3237
2566
  var key = node.key;
3238
- return !computed && (key.type === "Identifier" && key.name === name2 || key.type === "Literal" && key.value === name2);
2567
+ return !computed && (key.type === "Identifier" && key.name === name || key.type === "Literal" && key.value === name);
3239
2568
  }
3240
2569
  pp$8.parseExportAllDeclaration = function(node, exports) {
3241
2570
  if (this.options.ecmaVersion >= 11) {
@@ -3323,17 +2652,17 @@ pp$8.parseExportDefaultDeclaration = function() {
3323
2652
  return declaration;
3324
2653
  }
3325
2654
  };
3326
- pp$8.checkExport = function(exports, name2, pos) {
2655
+ pp$8.checkExport = function(exports, name, pos) {
3327
2656
  if (!exports) {
3328
2657
  return;
3329
2658
  }
3330
- if (typeof name2 !== "string") {
3331
- name2 = name2.type === "Identifier" ? name2.name : name2.value;
2659
+ if (typeof name !== "string") {
2660
+ name = name.type === "Identifier" ? name.name : name.value;
3332
2661
  }
3333
- if (hasOwn(exports, name2)) {
3334
- this.raiseRecoverable(pos, "Duplicate export '" + name2 + "'");
2662
+ if (hasOwn(exports, name)) {
2663
+ this.raiseRecoverable(pos, "Duplicate export '" + name + "'");
3335
2664
  }
3336
- exports[name2] = true;
2665
+ exports[name] = true;
3337
2666
  };
3338
2667
  pp$8.checkPatternExport = function(exports, pat) {
3339
2668
  var type = pat.type;
@@ -3913,20 +3242,20 @@ pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
3913
3242
  return;
3914
3243
  }
3915
3244
  var key = prop.key;
3916
- var name2;
3245
+ var name;
3917
3246
  switch (key.type) {
3918
3247
  case "Identifier":
3919
- name2 = key.name;
3248
+ name = key.name;
3920
3249
  break;
3921
3250
  case "Literal":
3922
- name2 = String(key.value);
3251
+ name = String(key.value);
3923
3252
  break;
3924
3253
  default:
3925
3254
  return;
3926
3255
  }
3927
3256
  var kind = prop.kind;
3928
3257
  if (this.options.ecmaVersion >= 6) {
3929
- if (name2 === "__proto__" && kind === "init") {
3258
+ if (name === "__proto__" && kind === "init") {
3930
3259
  if (propHash.proto) {
3931
3260
  if (refDestructuringErrors) {
3932
3261
  if (refDestructuringErrors.doubleProto < 0) {
@@ -3940,8 +3269,8 @@ pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
3940
3269
  }
3941
3270
  return;
3942
3271
  }
3943
- name2 = "$" + name2;
3944
- var other = propHash[name2];
3272
+ name = "$" + name;
3273
+ var other = propHash[name];
3945
3274
  if (other) {
3946
3275
  var redefinition;
3947
3276
  if (kind === "init") {
@@ -3953,7 +3282,7 @@ pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
3953
3282
  this.raiseRecoverable(key.start, "Redefinition of property");
3954
3283
  }
3955
3284
  } else {
3956
- other = propHash[name2] = {
3285
+ other = propHash[name] = {
3957
3286
  init: false,
3958
3287
  get: false,
3959
3288
  set: false
@@ -4853,31 +4182,31 @@ pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestruct
4853
4182
  pp$5.checkUnreserved = function(ref2) {
4854
4183
  var start = ref2.start;
4855
4184
  var end = ref2.end;
4856
- var name2 = ref2.name;
4857
- if (this.inGenerator && name2 === "yield") {
4185
+ var name = ref2.name;
4186
+ if (this.inGenerator && name === "yield") {
4858
4187
  this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator");
4859
4188
  }
4860
- if (this.inAsync && name2 === "await") {
4189
+ if (this.inAsync && name === "await") {
4861
4190
  this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function");
4862
4191
  }
4863
- if (this.currentThisScope().inClassFieldInit && name2 === "arguments") {
4192
+ if (this.currentThisScope().inClassFieldInit && name === "arguments") {
4864
4193
  this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer");
4865
4194
  }
4866
- if (this.inClassStaticBlock && (name2 === "arguments" || name2 === "await")) {
4867
- this.raise(start, "Cannot use " + name2 + " in class static initialization block");
4195
+ if (this.inClassStaticBlock && (name === "arguments" || name === "await")) {
4196
+ this.raise(start, "Cannot use " + name + " in class static initialization block");
4868
4197
  }
4869
- if (this.keywords.test(name2)) {
4870
- this.raise(start, "Unexpected keyword '" + name2 + "'");
4198
+ if (this.keywords.test(name)) {
4199
+ this.raise(start, "Unexpected keyword '" + name + "'");
4871
4200
  }
4872
4201
  if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) {
4873
4202
  return;
4874
4203
  }
4875
4204
  var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
4876
- if (re.test(name2)) {
4877
- if (!this.inAsync && name2 === "await") {
4205
+ if (re.test(name)) {
4206
+ if (!this.inAsync && name === "await") {
4878
4207
  this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function");
4879
4208
  }
4880
- this.raiseRecoverable(start, "The keyword '" + name2 + "' is reserved");
4209
+ this.raiseRecoverable(start, "The keyword '" + name + "' is reserved");
4881
4210
  }
4882
4211
  };
4883
4212
  pp$5.parseIdent = function(liberal) {
@@ -4982,36 +4311,36 @@ pp$3.exitScope = function() {
4982
4311
  pp$3.treatFunctionsAsVarInScope = function(scope) {
4983
4312
  return scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_TOP;
4984
4313
  };
4985
- pp$3.declareName = function(name2, bindingType, pos) {
4314
+ pp$3.declareName = function(name, bindingType, pos) {
4986
4315
  var redeclared = false;
4987
4316
  if (bindingType === BIND_LEXICAL) {
4988
4317
  var scope = this.currentScope();
4989
- redeclared = scope.lexical.indexOf(name2) > -1 || scope.functions.indexOf(name2) > -1 || scope.var.indexOf(name2) > -1;
4990
- scope.lexical.push(name2);
4318
+ redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
4319
+ scope.lexical.push(name);
4991
4320
  if (this.inModule && scope.flags & SCOPE_TOP) {
4992
- delete this.undefinedExports[name2];
4321
+ delete this.undefinedExports[name];
4993
4322
  }
4994
4323
  } else if (bindingType === BIND_SIMPLE_CATCH) {
4995
4324
  var scope$1 = this.currentScope();
4996
- scope$1.lexical.push(name2);
4325
+ scope$1.lexical.push(name);
4997
4326
  } else if (bindingType === BIND_FUNCTION) {
4998
4327
  var scope$2 = this.currentScope();
4999
4328
  if (this.treatFunctionsAsVar) {
5000
- redeclared = scope$2.lexical.indexOf(name2) > -1;
4329
+ redeclared = scope$2.lexical.indexOf(name) > -1;
5001
4330
  } else {
5002
- redeclared = scope$2.lexical.indexOf(name2) > -1 || scope$2.var.indexOf(name2) > -1;
4331
+ redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1;
5003
4332
  }
5004
- scope$2.functions.push(name2);
4333
+ scope$2.functions.push(name);
5005
4334
  } else {
5006
4335
  for (var i = this.scopeStack.length - 1; i >= 0; --i) {
5007
4336
  var scope$3 = this.scopeStack[i];
5008
- if (scope$3.lexical.indexOf(name2) > -1 && !(scope$3.flags & SCOPE_SIMPLE_CATCH && scope$3.lexical[0] === name2) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name2) > -1) {
4337
+ if (scope$3.lexical.indexOf(name) > -1 && !(scope$3.flags & SCOPE_SIMPLE_CATCH && scope$3.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
5009
4338
  redeclared = true;
5010
4339
  break;
5011
4340
  }
5012
- scope$3.var.push(name2);
4341
+ scope$3.var.push(name);
5013
4342
  if (this.inModule && scope$3.flags & SCOPE_TOP) {
5014
- delete this.undefinedExports[name2];
4343
+ delete this.undefinedExports[name];
5015
4344
  }
5016
4345
  if (scope$3.flags & SCOPE_VAR) {
5017
4346
  break;
@@ -5019,7 +4348,7 @@ pp$3.declareName = function(name2, bindingType, pos) {
5019
4348
  }
5020
4349
  }
5021
4350
  if (redeclared) {
5022
- this.raiseRecoverable(pos, "Identifier '" + name2 + "' has already been declared");
4351
+ this.raiseRecoverable(pos, "Identifier '" + name + "' has already been declared");
5023
4352
  }
5024
4353
  };
5025
4354
  pp$3.checkLocalExport = function(id) {
@@ -5339,8 +4668,8 @@ pp$1.regexp_pattern = function(state) {
5339
4668
  state.raise("Invalid escape");
5340
4669
  }
5341
4670
  for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
5342
- var name2 = list[i];
5343
- if (!state.groupNames[name2]) {
4671
+ var name = list[i];
4672
+ if (!state.groupNames[name]) {
5344
4673
  state.raise("Invalid named capture referenced");
5345
4674
  }
5346
4675
  }
@@ -5979,10 +5308,10 @@ pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
5979
5308
  61
5980
5309
  /* = */
5981
5310
  )) {
5982
- var name2 = state.lastStringValue;
5311
+ var name = state.lastStringValue;
5983
5312
  if (this.regexp_eatUnicodePropertyValue(state)) {
5984
5313
  var value = state.lastStringValue;
5985
- this.regexp_validateUnicodePropertyNameAndValue(state, name2, value);
5314
+ this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
5986
5315
  return CharSetOk;
5987
5316
  }
5988
5317
  }
@@ -5993,11 +5322,11 @@ pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
5993
5322
  }
5994
5323
  return CharSetNone;
5995
5324
  };
5996
- pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name2, value) {
5997
- if (!hasOwn(state.unicodeProperties.nonBinary, name2)) {
5325
+ pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
5326
+ if (!hasOwn(state.unicodeProperties.nonBinary, name)) {
5998
5327
  state.raise("Invalid property name");
5999
5328
  }
6000
- if (!state.unicodeProperties.nonBinary[name2].test(value)) {
5329
+ if (!state.unicodeProperties.nonBinary[name].test(value)) {
6001
5330
  state.raise("Invalid property value");
6002
5331
  }
6003
5332
  };
@@ -7313,8 +6642,8 @@ Parser.acorn = {
7313
6642
  };
7314
6643
 
7315
6644
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7316
- import { builtinModules as builtinModules2, createRequire } from "node:module";
7317
- import fs3, { realpathSync, statSync as statSync2, promises } from "node:fs";
6645
+ import { builtinModules, createRequire } from "node:module";
6646
+ import fs, { realpathSync, statSync, promises } from "node:fs";
7318
6647
 
7319
6648
  // ../../node_modules/.pnpm/ufo@1.5.4/node_modules/ufo/dist/index.mjs
7320
6649
  var r = String.fromCharCode;
@@ -7371,12 +6700,12 @@ var isAbsolute = function(p) {
7371
6700
 
7372
6701
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7373
6702
  import { fileURLToPath as fileURLToPath$1, URL as URL$1, pathToFileURL as pathToFileURL$1 } from "node:url";
7374
- import assert5 from "node:assert";
6703
+ import assert from "node:assert";
7375
6704
  import process$1 from "node:process";
7376
- import path4, { dirname as dirname3 } from "node:path";
6705
+ import path, { dirname as dirname2 } from "node:path";
7377
6706
  import v8 from "node:v8";
7378
6707
  import { format as format2, inspect } from "node:util";
7379
- var BUILTIN_MODULES = new Set(builtinModules2);
6708
+ var BUILTIN_MODULES = new Set(builtinModules);
7380
6709
  function normalizeSlash(path8) {
7381
6710
  return path8.replace(/\\/g, "/");
7382
6711
  }
@@ -7408,31 +6737,31 @@ codes.ERR_INVALID_ARG_TYPE = createError(
7408
6737
  * @param {Array<string> | string} expected
7409
6738
  * @param {unknown} actual
7410
6739
  */
7411
- (name2, expected, actual) => {
7412
- assert5(typeof name2 === "string", "'name' must be a string");
6740
+ (name, expected, actual) => {
6741
+ assert(typeof name === "string", "'name' must be a string");
7413
6742
  if (!Array.isArray(expected)) {
7414
6743
  expected = [expected];
7415
6744
  }
7416
6745
  let message = "The ";
7417
- if (name2.endsWith(" argument")) {
7418
- message += `${name2} `;
6746
+ if (name.endsWith(" argument")) {
6747
+ message += `${name} `;
7419
6748
  } else {
7420
- const type = name2.includes(".") ? "property" : "argument";
7421
- message += `"${name2}" ${type} `;
6749
+ const type = name.includes(".") ? "property" : "argument";
6750
+ message += `"${name}" ${type} `;
7422
6751
  }
7423
6752
  message += "must be ";
7424
6753
  const types2 = [];
7425
6754
  const instances = [];
7426
6755
  const other = [];
7427
6756
  for (const value of expected) {
7428
- assert5(
6757
+ assert(
7429
6758
  typeof value === "string",
7430
6759
  "All expected entries have to be of type string"
7431
6760
  );
7432
6761
  if (kTypes.has(value)) {
7433
6762
  types2.push(value.toLowerCase());
7434
6763
  } else if (classRegExp.exec(value) === null) {
7435
- assert5(
6764
+ assert(
7436
6765
  value !== "object",
7437
6766
  'The value "object" should be written as "Object"'
7438
6767
  );
@@ -7505,14 +6834,14 @@ codes.ERR_INVALID_PACKAGE_TARGET = createError(
7505
6834
  * @param {boolean} [isImport=false]
7506
6835
  * @param {string} [base]
7507
6836
  */
7508
- (packagePath, key, target, isImport = false, base = void 0) => {
7509
- const relatedError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./");
6837
+ (packagePath, key, target2, isImport = false, base = void 0) => {
6838
+ const relatedError = typeof target2 === "string" && !isImport && target2.length > 0 && !target2.startsWith("./");
7510
6839
  if (key === ".") {
7511
- assert5(isImport === false);
7512
- return `Invalid "exports" main target ${JSON.stringify(target)} defined in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
6840
+ assert(isImport === false);
6841
+ return `Invalid "exports" main target ${JSON.stringify(target2)} defined in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
7513
6842
  }
7514
6843
  return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(
7515
- target
6844
+ target2
7516
6845
  )} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
7517
6846
  },
7518
6847
  Error
@@ -7588,13 +6917,13 @@ codes.ERR_INVALID_ARG_VALUE = createError(
7588
6917
  * @param {unknown} value
7589
6918
  * @param {string} [reason='is invalid']
7590
6919
  */
7591
- (name2, value, reason = "is invalid") => {
6920
+ (name, value, reason = "is invalid") => {
7592
6921
  let inspected = inspect(value);
7593
6922
  if (inspected.length > 128) {
7594
6923
  inspected = `${inspected.slice(0, 128)}...`;
7595
6924
  }
7596
- const type = name2.includes(".") ? "property" : "argument";
7597
- return `The ${type} '${name2}' ${reason}. Received ${inspected}`;
6925
+ const type = name.includes(".") ? "property" : "argument";
6926
+ return `The ${type} '${name}' ${reason}. Received ${inspected}`;
7598
6927
  },
7599
6928
  TypeError
7600
6929
  // Note: extra classes have been shaken out.
@@ -7673,9 +7002,9 @@ var captureLargerStackTrace = hideStackFrames(
7673
7002
  );
7674
7003
  function getMessage(key, parameters, self) {
7675
7004
  const message = messages.get(key);
7676
- assert5(message !== void 0, "expected `message` to be found");
7005
+ assert(message !== void 0, "expected `message` to be found");
7677
7006
  if (typeof message === "function") {
7678
- assert5(
7007
+ assert(
7679
7008
  message.length <= parameters.length,
7680
7009
  // Default options do not count.
7681
7010
  `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`
@@ -7685,7 +7014,7 @@ function getMessage(key, parameters, self) {
7685
7014
  const regex = /%[dfijoOs]/g;
7686
7015
  let expectedLength = 0;
7687
7016
  while (regex.exec(message) !== null) expectedLength++;
7688
- assert5(
7017
+ assert(
7689
7018
  expectedLength === parameters.length,
7690
7019
  `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`
7691
7020
  );
@@ -7722,7 +7051,7 @@ function read(jsonPath, { base, specifier }) {
7722
7051
  }
7723
7052
  let string;
7724
7053
  try {
7725
- string = fs3.readFileSync(path4.toNamespacedPath(jsonPath), "utf8");
7054
+ string = fs.readFileSync(path.toNamespacedPath(jsonPath), "utf8");
7726
7055
  } catch (error) {
7727
7056
  const exception = (
7728
7057
  /** @type {ErrnoException} */
@@ -7798,1022 +7127,1827 @@ function getPackageScopeConfig(resolved) {
7798
7127
  break;
7799
7128
  }
7800
7129
  }
7801
- const packageJSONPath = fileURLToPath$1(packageJSONUrl);
7802
- return {
7803
- pjsonPath: packageJSONPath,
7804
- exists: false,
7805
- type: "none"
7806
- };
7130
+ const packageJSONPath = fileURLToPath$1(packageJSONUrl);
7131
+ return {
7132
+ pjsonPath: packageJSONPath,
7133
+ exists: false,
7134
+ type: "none"
7135
+ };
7136
+ }
7137
+ function getPackageType(url) {
7138
+ return getPackageScopeConfig(url).type;
7139
+ }
7140
+ var { ERR_UNKNOWN_FILE_EXTENSION } = codes;
7141
+ var hasOwnProperty2 = {}.hasOwnProperty;
7142
+ var extensionFormatMap = {
7143
+ // @ts-expect-error: hush.
7144
+ __proto__: null,
7145
+ ".cjs": "commonjs",
7146
+ ".js": "module",
7147
+ ".json": "json",
7148
+ ".mjs": "module"
7149
+ };
7150
+ function mimeToFormat(mime) {
7151
+ if (mime && /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime))
7152
+ return "module";
7153
+ if (mime === "application/json") return "json";
7154
+ return null;
7155
+ }
7156
+ var protocolHandlers = {
7157
+ // @ts-expect-error: hush.
7158
+ __proto__: null,
7159
+ "data:": getDataProtocolModuleFormat,
7160
+ "file:": getFileProtocolModuleFormat,
7161
+ "http:": getHttpProtocolModuleFormat,
7162
+ "https:": getHttpProtocolModuleFormat,
7163
+ "node:"() {
7164
+ return "builtin";
7165
+ }
7166
+ };
7167
+ function getDataProtocolModuleFormat(parsed) {
7168
+ const { 1: mime } = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(
7169
+ parsed.pathname
7170
+ ) || [null, null, null];
7171
+ return mimeToFormat(mime);
7172
+ }
7173
+ function extname2(url) {
7174
+ const pathname = url.pathname;
7175
+ let index = pathname.length;
7176
+ while (index--) {
7177
+ const code = pathname.codePointAt(index);
7178
+ if (code === 47) {
7179
+ return "";
7180
+ }
7181
+ if (code === 46) {
7182
+ return pathname.codePointAt(index - 1) === 47 ? "" : pathname.slice(index);
7183
+ }
7184
+ }
7185
+ return "";
7186
+ }
7187
+ function getFileProtocolModuleFormat(url, _context, ignoreErrors) {
7188
+ const value = extname2(url);
7189
+ if (value === ".js") {
7190
+ const packageType = getPackageType(url);
7191
+ if (packageType !== "none") {
7192
+ return packageType;
7193
+ }
7194
+ return "commonjs";
7195
+ }
7196
+ if (value === "") {
7197
+ const packageType = getPackageType(url);
7198
+ if (packageType === "none" || packageType === "commonjs") {
7199
+ return "commonjs";
7200
+ }
7201
+ return "module";
7202
+ }
7203
+ const format3 = extensionFormatMap[value];
7204
+ if (format3) return format3;
7205
+ if (ignoreErrors) {
7206
+ return void 0;
7207
+ }
7208
+ const filepath = fileURLToPath$1(url);
7209
+ throw new ERR_UNKNOWN_FILE_EXTENSION(value, filepath);
7210
+ }
7211
+ function getHttpProtocolModuleFormat() {
7212
+ }
7213
+ function defaultGetFormatWithoutErrors(url, context) {
7214
+ const protocol = url.protocol;
7215
+ if (!hasOwnProperty2.call(protocolHandlers, protocol)) {
7216
+ return null;
7217
+ }
7218
+ return protocolHandlers[protocol](url, context, true) || null;
7219
+ }
7220
+ var RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
7221
+ var {
7222
+ ERR_NETWORK_IMPORT_DISALLOWED,
7223
+ ERR_INVALID_MODULE_SPECIFIER,
7224
+ ERR_INVALID_PACKAGE_CONFIG,
7225
+ ERR_INVALID_PACKAGE_TARGET,
7226
+ ERR_MODULE_NOT_FOUND,
7227
+ ERR_PACKAGE_IMPORT_NOT_DEFINED,
7228
+ ERR_PACKAGE_PATH_NOT_EXPORTED,
7229
+ ERR_UNSUPPORTED_DIR_IMPORT,
7230
+ ERR_UNSUPPORTED_RESOLVE_REQUEST
7231
+ } = codes;
7232
+ var own = {}.hasOwnProperty;
7233
+ var invalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i;
7234
+ var deprecatedInvalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i;
7235
+ var invalidPackageNameRegEx = /^\.|%|\\/;
7236
+ var patternRegEx = /\*/g;
7237
+ var encodedSeparatorRegEx = /%2f|%5c/i;
7238
+ var emittedPackageWarnings = /* @__PURE__ */ new Set();
7239
+ var doubleSlashRegEx = /[/\\]{2}/;
7240
+ function emitInvalidSegmentDeprecation(target2, request, match, packageJsonUrl, internal, base, isTarget) {
7241
+ if (process$1.noDeprecation) {
7242
+ return;
7243
+ }
7244
+ const pjsonPath = fileURLToPath$1(packageJsonUrl);
7245
+ const double = doubleSlashRegEx.exec(isTarget ? target2 : request) !== null;
7246
+ process$1.emitWarning(
7247
+ `Use of deprecated ${double ? "double slash" : "leading or trailing slash matching"} resolving "${target2}" for module request "${request}" ${request === match ? "" : `matched to "${match}" `}in the "${internal ? "imports" : "exports"}" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath$1(base)}` : ""}.`,
7248
+ "DeprecationWarning",
7249
+ "DEP0166"
7250
+ );
7251
+ }
7252
+ function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
7253
+ if (process$1.noDeprecation) {
7254
+ return;
7255
+ }
7256
+ const format3 = defaultGetFormatWithoutErrors(url, { parentURL: base.href });
7257
+ if (format3 !== "module") return;
7258
+ const urlPath = fileURLToPath$1(url.href);
7259
+ const packagePath = fileURLToPath$1(new URL$1(".", packageJsonUrl));
7260
+ const basePath = fileURLToPath$1(base);
7261
+ if (!main) {
7262
+ process$1.emitWarning(
7263
+ `No "main" or "exports" field defined in the package.json for ${packagePath} resolving the main entry point "${urlPath.slice(
7264
+ packagePath.length
7265
+ )}", imported from ${basePath}.
7266
+ Default "index" lookups for the main are deprecated for ES modules.`,
7267
+ "DeprecationWarning",
7268
+ "DEP0151"
7269
+ );
7270
+ } else if (path.resolve(packagePath, main) !== urlPath) {
7271
+ process$1.emitWarning(
7272
+ `Package ${packagePath} has a "main" field set to "${main}", excluding the full filename and extension to the resolved file at "${urlPath.slice(
7273
+ packagePath.length
7274
+ )}", imported from ${basePath}.
7275
+ Automatic extension resolution of the "main" field is deprecated for ES modules.`,
7276
+ "DeprecationWarning",
7277
+ "DEP0151"
7278
+ );
7279
+ }
7280
+ }
7281
+ function tryStatSync(path8) {
7282
+ try {
7283
+ return statSync(path8);
7284
+ } catch {
7285
+ }
7286
+ }
7287
+ function fileExists(url) {
7288
+ const stats = statSync(url, { throwIfNoEntry: false });
7289
+ const isFile = stats ? stats.isFile() : void 0;
7290
+ return isFile === null || isFile === void 0 ? false : isFile;
7291
+ }
7292
+ function legacyMainResolve(packageJsonUrl, packageConfig, base) {
7293
+ let guess;
7294
+ if (packageConfig.main !== void 0) {
7295
+ guess = new URL$1(packageConfig.main, packageJsonUrl);
7296
+ if (fileExists(guess)) return guess;
7297
+ const tries2 = [
7298
+ `./${packageConfig.main}.js`,
7299
+ `./${packageConfig.main}.json`,
7300
+ `./${packageConfig.main}.node`,
7301
+ `./${packageConfig.main}/index.js`,
7302
+ `./${packageConfig.main}/index.json`,
7303
+ `./${packageConfig.main}/index.node`
7304
+ ];
7305
+ let i2 = -1;
7306
+ while (++i2 < tries2.length) {
7307
+ guess = new URL$1(tries2[i2], packageJsonUrl);
7308
+ if (fileExists(guess)) break;
7309
+ guess = void 0;
7310
+ }
7311
+ if (guess) {
7312
+ emitLegacyIndexDeprecation(
7313
+ guess,
7314
+ packageJsonUrl,
7315
+ base,
7316
+ packageConfig.main
7317
+ );
7318
+ return guess;
7319
+ }
7320
+ }
7321
+ const tries = ["./index.js", "./index.json", "./index.node"];
7322
+ let i = -1;
7323
+ while (++i < tries.length) {
7324
+ guess = new URL$1(tries[i], packageJsonUrl);
7325
+ if (fileExists(guess)) break;
7326
+ guess = void 0;
7327
+ }
7328
+ if (guess) {
7329
+ emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
7330
+ return guess;
7331
+ }
7332
+ throw new ERR_MODULE_NOT_FOUND(
7333
+ fileURLToPath$1(new URL$1(".", packageJsonUrl)),
7334
+ fileURLToPath$1(base)
7335
+ );
7336
+ }
7337
+ function finalizeResolution(resolved, base, preserveSymlinks) {
7338
+ if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) {
7339
+ throw new ERR_INVALID_MODULE_SPECIFIER(
7340
+ resolved.pathname,
7341
+ 'must not include encoded "/" or "\\" characters',
7342
+ fileURLToPath$1(base)
7343
+ );
7344
+ }
7345
+ let filePath;
7346
+ try {
7347
+ filePath = fileURLToPath$1(resolved);
7348
+ } catch (error) {
7349
+ const cause = (
7350
+ /** @type {ErrnoException} */
7351
+ error
7352
+ );
7353
+ Object.defineProperty(cause, "input", { value: String(resolved) });
7354
+ Object.defineProperty(cause, "module", { value: String(base) });
7355
+ throw cause;
7356
+ }
7357
+ const stats = tryStatSync(
7358
+ filePath.endsWith("/") ? filePath.slice(-1) : filePath
7359
+ );
7360
+ if (stats && stats.isDirectory()) {
7361
+ const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath$1(base));
7362
+ error.url = String(resolved);
7363
+ throw error;
7364
+ }
7365
+ if (!stats || !stats.isFile()) {
7366
+ const error = new ERR_MODULE_NOT_FOUND(
7367
+ filePath || resolved.pathname,
7368
+ base && fileURLToPath$1(base),
7369
+ true
7370
+ );
7371
+ error.url = String(resolved);
7372
+ throw error;
7373
+ }
7374
+ {
7375
+ const real = realpathSync(filePath);
7376
+ const { search, hash } = resolved;
7377
+ resolved = pathToFileURL$1(real + (filePath.endsWith(path.sep) ? "/" : ""));
7378
+ resolved.search = search;
7379
+ resolved.hash = hash;
7380
+ }
7381
+ return resolved;
7807
7382
  }
7808
- function getPackageType(url) {
7809
- return getPackageScopeConfig(url).type;
7383
+ function importNotDefined(specifier, packageJsonUrl, base) {
7384
+ return new ERR_PACKAGE_IMPORT_NOT_DEFINED(
7385
+ specifier,
7386
+ packageJsonUrl && fileURLToPath$1(new URL$1(".", packageJsonUrl)),
7387
+ fileURLToPath$1(base)
7388
+ );
7810
7389
  }
7811
- var { ERR_UNKNOWN_FILE_EXTENSION } = codes;
7812
- var hasOwnProperty2 = {}.hasOwnProperty;
7813
- var extensionFormatMap = {
7814
- // @ts-expect-error: hush.
7815
- __proto__: null,
7816
- ".cjs": "commonjs",
7817
- ".js": "module",
7818
- ".json": "json",
7819
- ".mjs": "module"
7820
- };
7821
- function mimeToFormat(mime) {
7822
- if (mime && /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime))
7823
- return "module";
7824
- if (mime === "application/json") return "json";
7825
- return null;
7390
+ function exportsNotFound(subpath, packageJsonUrl, base) {
7391
+ return new ERR_PACKAGE_PATH_NOT_EXPORTED(
7392
+ fileURLToPath$1(new URL$1(".", packageJsonUrl)),
7393
+ subpath,
7394
+ base && fileURLToPath$1(base)
7395
+ );
7826
7396
  }
7827
- var protocolHandlers = {
7828
- // @ts-expect-error: hush.
7829
- __proto__: null,
7830
- "data:": getDataProtocolModuleFormat,
7831
- "file:": getFileProtocolModuleFormat,
7832
- "http:": getHttpProtocolModuleFormat,
7833
- "https:": getHttpProtocolModuleFormat,
7834
- "node:"() {
7835
- return "builtin";
7836
- }
7837
- };
7838
- function getDataProtocolModuleFormat(parsed) {
7839
- const { 1: mime } = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(
7840
- parsed.pathname
7841
- ) || [null, null, null];
7842
- return mimeToFormat(mime);
7397
+ function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
7398
+ const reason = `request is not a valid match in pattern "${match}" for the "${internal ? "imports" : "exports"}" resolution of ${fileURLToPath$1(packageJsonUrl)}`;
7399
+ throw new ERR_INVALID_MODULE_SPECIFIER(
7400
+ request,
7401
+ reason,
7402
+ base && fileURLToPath$1(base)
7403
+ );
7843
7404
  }
7844
- function extname2(url) {
7845
- const pathname = url.pathname;
7846
- let index = pathname.length;
7847
- while (index--) {
7848
- const code = pathname.codePointAt(index);
7849
- if (code === 47) {
7850
- return "";
7851
- }
7852
- if (code === 46) {
7853
- return pathname.codePointAt(index - 1) === 47 ? "" : pathname.slice(index);
7405
+ function invalidPackageTarget(subpath, target2, packageJsonUrl, internal, base) {
7406
+ target2 = typeof target2 === "object" && target2 !== null ? JSON.stringify(target2, null, "") : `${target2}`;
7407
+ return new ERR_INVALID_PACKAGE_TARGET(
7408
+ fileURLToPath$1(new URL$1(".", packageJsonUrl)),
7409
+ subpath,
7410
+ target2,
7411
+ internal,
7412
+ base && fileURLToPath$1(base)
7413
+ );
7414
+ }
7415
+ function resolvePackageTargetString(target2, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
7416
+ if (subpath !== "" && !pattern && target2[target2.length - 1] !== "/")
7417
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
7418
+ if (!target2.startsWith("./")) {
7419
+ if (internal && !target2.startsWith("../") && !target2.startsWith("/")) {
7420
+ let isURL = false;
7421
+ try {
7422
+ new URL$1(target2);
7423
+ isURL = true;
7424
+ } catch {
7425
+ }
7426
+ if (!isURL) {
7427
+ const exportTarget = pattern ? RegExpPrototypeSymbolReplace.call(
7428
+ patternRegEx,
7429
+ target2,
7430
+ () => subpath
7431
+ ) : target2 + subpath;
7432
+ return packageResolve(exportTarget, packageJsonUrl, conditions);
7433
+ }
7854
7434
  }
7435
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
7855
7436
  }
7856
- return "";
7857
- }
7858
- function getFileProtocolModuleFormat(url, _context, ignoreErrors) {
7859
- const value = extname2(url);
7860
- if (value === ".js") {
7861
- const packageType = getPackageType(url);
7862
- if (packageType !== "none") {
7863
- return packageType;
7437
+ if (invalidSegmentRegEx.exec(target2.slice(2)) !== null) {
7438
+ if (deprecatedInvalidSegmentRegEx.exec(target2.slice(2)) === null) {
7439
+ if (!isPathMap) {
7440
+ const request = pattern ? match.replace("*", () => subpath) : match + subpath;
7441
+ const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
7442
+ patternRegEx,
7443
+ target2,
7444
+ () => subpath
7445
+ ) : target2;
7446
+ emitInvalidSegmentDeprecation(
7447
+ resolvedTarget,
7448
+ request,
7449
+ match,
7450
+ packageJsonUrl,
7451
+ internal,
7452
+ base,
7453
+ true
7454
+ );
7455
+ }
7456
+ } else {
7457
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
7864
7458
  }
7865
- return "commonjs";
7866
7459
  }
7867
- if (value === "") {
7868
- const packageType = getPackageType(url);
7869
- if (packageType === "none" || packageType === "commonjs") {
7870
- return "commonjs";
7460
+ const resolved = new URL$1(target2, packageJsonUrl);
7461
+ const resolvedPath = resolved.pathname;
7462
+ const packagePath = new URL$1(".", packageJsonUrl).pathname;
7463
+ if (!resolvedPath.startsWith(packagePath))
7464
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
7465
+ if (subpath === "") return resolved;
7466
+ if (invalidSegmentRegEx.exec(subpath) !== null) {
7467
+ const request = pattern ? match.replace("*", () => subpath) : match + subpath;
7468
+ if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
7469
+ if (!isPathMap) {
7470
+ const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
7471
+ patternRegEx,
7472
+ target2,
7473
+ () => subpath
7474
+ ) : target2;
7475
+ emitInvalidSegmentDeprecation(
7476
+ resolvedTarget,
7477
+ request,
7478
+ match,
7479
+ packageJsonUrl,
7480
+ internal,
7481
+ base,
7482
+ false
7483
+ );
7484
+ }
7485
+ } else {
7486
+ throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
7871
7487
  }
7872
- return "module";
7873
7488
  }
7874
- const format3 = extensionFormatMap[value];
7875
- if (format3) return format3;
7876
- if (ignoreErrors) {
7877
- return void 0;
7489
+ if (pattern) {
7490
+ return new URL$1(
7491
+ RegExpPrototypeSymbolReplace.call(
7492
+ patternRegEx,
7493
+ resolved.href,
7494
+ () => subpath
7495
+ )
7496
+ );
7878
7497
  }
7879
- const filepath = fileURLToPath$1(url);
7880
- throw new ERR_UNKNOWN_FILE_EXTENSION(value, filepath);
7498
+ return new URL$1(subpath, resolved);
7881
7499
  }
7882
- function getHttpProtocolModuleFormat() {
7500
+ function isArrayIndex(key) {
7501
+ const keyNumber = Number(key);
7502
+ if (`${keyNumber}` !== key) return false;
7503
+ return keyNumber >= 0 && keyNumber < 4294967295;
7883
7504
  }
7884
- function defaultGetFormatWithoutErrors(url, context) {
7885
- const protocol = url.protocol;
7886
- if (!hasOwnProperty2.call(protocolHandlers, protocol)) {
7505
+ function resolvePackageTarget(packageJsonUrl, target2, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
7506
+ if (typeof target2 === "string") {
7507
+ return resolvePackageTargetString(
7508
+ target2,
7509
+ subpath,
7510
+ packageSubpath,
7511
+ packageJsonUrl,
7512
+ base,
7513
+ pattern,
7514
+ internal,
7515
+ isPathMap,
7516
+ conditions
7517
+ );
7518
+ }
7519
+ if (Array.isArray(target2)) {
7520
+ const targetList = target2;
7521
+ if (targetList.length === 0) return null;
7522
+ let lastException;
7523
+ let i = -1;
7524
+ while (++i < targetList.length) {
7525
+ const targetItem = targetList[i];
7526
+ let resolveResult;
7527
+ try {
7528
+ resolveResult = resolvePackageTarget(
7529
+ packageJsonUrl,
7530
+ targetItem,
7531
+ subpath,
7532
+ packageSubpath,
7533
+ base,
7534
+ pattern,
7535
+ internal,
7536
+ isPathMap,
7537
+ conditions
7538
+ );
7539
+ } catch (error) {
7540
+ const exception = (
7541
+ /** @type {ErrnoException} */
7542
+ error
7543
+ );
7544
+ lastException = exception;
7545
+ if (exception.code === "ERR_INVALID_PACKAGE_TARGET") continue;
7546
+ throw error;
7547
+ }
7548
+ if (resolveResult === void 0) continue;
7549
+ if (resolveResult === null) {
7550
+ lastException = null;
7551
+ continue;
7552
+ }
7553
+ return resolveResult;
7554
+ }
7555
+ if (lastException === void 0 || lastException === null) {
7556
+ return null;
7557
+ }
7558
+ throw lastException;
7559
+ }
7560
+ if (typeof target2 === "object" && target2 !== null) {
7561
+ const keys = Object.getOwnPropertyNames(target2);
7562
+ let i = -1;
7563
+ while (++i < keys.length) {
7564
+ const key = keys[i];
7565
+ if (isArrayIndex(key)) {
7566
+ throw new ERR_INVALID_PACKAGE_CONFIG(
7567
+ fileURLToPath$1(packageJsonUrl),
7568
+ base,
7569
+ '"exports" cannot contain numeric property keys.'
7570
+ );
7571
+ }
7572
+ }
7573
+ i = -1;
7574
+ while (++i < keys.length) {
7575
+ const key = keys[i];
7576
+ if (key === "default" || conditions && conditions.has(key)) {
7577
+ const conditionalTarget = (
7578
+ /** @type {unknown} */
7579
+ target2[key]
7580
+ );
7581
+ const resolveResult = resolvePackageTarget(
7582
+ packageJsonUrl,
7583
+ conditionalTarget,
7584
+ subpath,
7585
+ packageSubpath,
7586
+ base,
7587
+ pattern,
7588
+ internal,
7589
+ isPathMap,
7590
+ conditions
7591
+ );
7592
+ if (resolveResult === void 0) continue;
7593
+ return resolveResult;
7594
+ }
7595
+ }
7596
+ return null;
7597
+ }
7598
+ if (target2 === null) {
7887
7599
  return null;
7888
7600
  }
7889
- return protocolHandlers[protocol](url, context, true) || null;
7601
+ throw invalidPackageTarget(
7602
+ packageSubpath,
7603
+ target2,
7604
+ packageJsonUrl,
7605
+ internal,
7606
+ base
7607
+ );
7890
7608
  }
7891
- var RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
7892
- var {
7893
- ERR_NETWORK_IMPORT_DISALLOWED,
7894
- ERR_INVALID_MODULE_SPECIFIER,
7895
- ERR_INVALID_PACKAGE_CONFIG,
7896
- ERR_INVALID_PACKAGE_TARGET,
7897
- ERR_MODULE_NOT_FOUND,
7898
- ERR_PACKAGE_IMPORT_NOT_DEFINED,
7899
- ERR_PACKAGE_PATH_NOT_EXPORTED,
7900
- ERR_UNSUPPORTED_DIR_IMPORT,
7901
- ERR_UNSUPPORTED_RESOLVE_REQUEST
7902
- } = codes;
7903
- var own = {}.hasOwnProperty;
7904
- var invalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i;
7905
- var deprecatedInvalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i;
7906
- var invalidPackageNameRegEx = /^\.|%|\\/;
7907
- var patternRegEx = /\*/g;
7908
- var encodedSeparatorRegEx = /%2f|%5c/i;
7909
- var emittedPackageWarnings = /* @__PURE__ */ new Set();
7910
- var doubleSlashRegEx = /[/\\]{2}/;
7911
- function emitInvalidSegmentDeprecation(target, request, match, packageJsonUrl, internal, base, isTarget) {
7609
+ function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
7610
+ if (typeof exports === "string" || Array.isArray(exports)) return true;
7611
+ if (typeof exports !== "object" || exports === null) return false;
7612
+ const keys = Object.getOwnPropertyNames(exports);
7613
+ let isConditionalSugar = false;
7614
+ let i = 0;
7615
+ let keyIndex = -1;
7616
+ while (++keyIndex < keys.length) {
7617
+ const key = keys[keyIndex];
7618
+ const currentIsConditionalSugar = key === "" || key[0] !== ".";
7619
+ if (i++ === 0) {
7620
+ isConditionalSugar = currentIsConditionalSugar;
7621
+ } else if (isConditionalSugar !== currentIsConditionalSugar) {
7622
+ throw new ERR_INVALID_PACKAGE_CONFIG(
7623
+ fileURLToPath$1(packageJsonUrl),
7624
+ base,
7625
+ `"exports" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only.`
7626
+ );
7627
+ }
7628
+ }
7629
+ return isConditionalSugar;
7630
+ }
7631
+ function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
7912
7632
  if (process$1.noDeprecation) {
7913
7633
  return;
7914
7634
  }
7915
- const pjsonPath = fileURLToPath$1(packageJsonUrl);
7916
- const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
7635
+ const pjsonPath = fileURLToPath$1(pjsonUrl);
7636
+ if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return;
7637
+ emittedPackageWarnings.add(pjsonPath + "|" + match);
7917
7638
  process$1.emitWarning(
7918
- `Use of deprecated ${double ? "double slash" : "leading or trailing slash matching"} resolving "${target}" for module request "${request}" ${request === match ? "" : `matched to "${match}" `}in the "${internal ? "imports" : "exports"}" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath$1(base)}` : ""}.`,
7639
+ `Use of deprecated trailing slash pattern mapping "${match}" in the "exports" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath$1(base)}` : ""}. Mapping specifiers ending in "/" is no longer supported.`,
7919
7640
  "DeprecationWarning",
7920
- "DEP0166"
7641
+ "DEP0155"
7921
7642
  );
7922
7643
  }
7923
- function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
7924
- if (process$1.noDeprecation) {
7925
- return;
7644
+ function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
7645
+ let exports = packageConfig.exports;
7646
+ if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
7647
+ exports = { ".": exports };
7926
7648
  }
7927
- const format3 = defaultGetFormatWithoutErrors(url, { parentURL: base.href });
7928
- if (format3 !== "module") return;
7929
- const urlPath = fileURLToPath$1(url.href);
7930
- const packagePath = fileURLToPath$1(new URL$1(".", packageJsonUrl));
7931
- const basePath = fileURLToPath$1(base);
7932
- if (!main) {
7933
- process$1.emitWarning(
7934
- `No "main" or "exports" field defined in the package.json for ${packagePath} resolving the main entry point "${urlPath.slice(
7935
- packagePath.length
7936
- )}", imported from ${basePath}.
7937
- Default "index" lookups for the main are deprecated for ES modules.`,
7938
- "DeprecationWarning",
7939
- "DEP0151"
7940
- );
7941
- } else if (path4.resolve(packagePath, main) !== urlPath) {
7942
- process$1.emitWarning(
7943
- `Package ${packagePath} has a "main" field set to "${main}", excluding the full filename and extension to the resolved file at "${urlPath.slice(
7944
- packagePath.length
7945
- )}", imported from ${basePath}.
7946
- Automatic extension resolution of the "main" field is deprecated for ES modules.`,
7947
- "DeprecationWarning",
7948
- "DEP0151"
7649
+ if (own.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
7650
+ const target2 = exports[packageSubpath];
7651
+ const resolveResult = resolvePackageTarget(
7652
+ packageJsonUrl,
7653
+ target2,
7654
+ "",
7655
+ packageSubpath,
7656
+ base,
7657
+ false,
7658
+ false,
7659
+ false,
7660
+ conditions
7949
7661
  );
7662
+ if (resolveResult === null || resolveResult === void 0) {
7663
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7664
+ }
7665
+ return resolveResult;
7950
7666
  }
7951
- }
7952
- function tryStatSync(path8) {
7953
- try {
7954
- return statSync2(path8);
7955
- } catch {
7667
+ let bestMatch = "";
7668
+ let bestMatchSubpath = "";
7669
+ const keys = Object.getOwnPropertyNames(exports);
7670
+ let i = -1;
7671
+ while (++i < keys.length) {
7672
+ const key = keys[i];
7673
+ const patternIndex = key.indexOf("*");
7674
+ if (patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex))) {
7675
+ if (packageSubpath.endsWith("/")) {
7676
+ emitTrailingSlashPatternDeprecation(
7677
+ packageSubpath,
7678
+ packageJsonUrl,
7679
+ base
7680
+ );
7681
+ }
7682
+ const patternTrailer = key.slice(patternIndex + 1);
7683
+ if (packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
7684
+ bestMatch = key;
7685
+ bestMatchSubpath = packageSubpath.slice(
7686
+ patternIndex,
7687
+ packageSubpath.length - patternTrailer.length
7688
+ );
7689
+ }
7690
+ }
7956
7691
  }
7692
+ if (bestMatch) {
7693
+ const target2 = (
7694
+ /** @type {unknown} */
7695
+ exports[bestMatch]
7696
+ );
7697
+ const resolveResult = resolvePackageTarget(
7698
+ packageJsonUrl,
7699
+ target2,
7700
+ bestMatchSubpath,
7701
+ bestMatch,
7702
+ base,
7703
+ true,
7704
+ false,
7705
+ packageSubpath.endsWith("/"),
7706
+ conditions
7707
+ );
7708
+ if (resolveResult === null || resolveResult === void 0) {
7709
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7710
+ }
7711
+ return resolveResult;
7712
+ }
7713
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7957
7714
  }
7958
- function fileExists(url) {
7959
- const stats = statSync2(url, { throwIfNoEntry: false });
7960
- const isFile = stats ? stats.isFile() : void 0;
7961
- return isFile === null || isFile === void 0 ? false : isFile;
7715
+ function patternKeyCompare(a, b) {
7716
+ const aPatternIndex = a.indexOf("*");
7717
+ const bPatternIndex = b.indexOf("*");
7718
+ const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
7719
+ const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
7720
+ if (baseLengthA > baseLengthB) return -1;
7721
+ if (baseLengthB > baseLengthA) return 1;
7722
+ if (aPatternIndex === -1) return 1;
7723
+ if (bPatternIndex === -1) return -1;
7724
+ if (a.length > b.length) return -1;
7725
+ if (b.length > a.length) return 1;
7726
+ return 0;
7962
7727
  }
7963
- function legacyMainResolve(packageJsonUrl, packageConfig, base) {
7964
- let guess;
7965
- if (packageConfig.main !== void 0) {
7966
- guess = new URL$1(packageConfig.main, packageJsonUrl);
7967
- if (fileExists(guess)) return guess;
7968
- const tries2 = [
7969
- `./${packageConfig.main}.js`,
7970
- `./${packageConfig.main}.json`,
7971
- `./${packageConfig.main}.node`,
7972
- `./${packageConfig.main}/index.js`,
7973
- `./${packageConfig.main}/index.json`,
7974
- `./${packageConfig.main}/index.node`
7975
- ];
7976
- let i2 = -1;
7977
- while (++i2 < tries2.length) {
7978
- guess = new URL$1(tries2[i2], packageJsonUrl);
7979
- if (fileExists(guess)) break;
7980
- guess = void 0;
7981
- }
7982
- if (guess) {
7983
- emitLegacyIndexDeprecation(
7984
- guess,
7985
- packageJsonUrl,
7986
- base,
7987
- packageConfig.main
7988
- );
7989
- return guess;
7728
+ function packageImportsResolve(name, base, conditions) {
7729
+ if (name === "#" || name.startsWith("#/") || name.endsWith("/")) {
7730
+ const reason = "is not a valid internal imports specifier name";
7731
+ throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath$1(base));
7732
+ }
7733
+ let packageJsonUrl;
7734
+ const packageConfig = getPackageScopeConfig(base);
7735
+ if (packageConfig.exists) {
7736
+ packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
7737
+ const imports = packageConfig.imports;
7738
+ if (imports) {
7739
+ if (own.call(imports, name) && !name.includes("*")) {
7740
+ const resolveResult = resolvePackageTarget(
7741
+ packageJsonUrl,
7742
+ imports[name],
7743
+ "",
7744
+ name,
7745
+ base,
7746
+ false,
7747
+ true,
7748
+ false,
7749
+ conditions
7750
+ );
7751
+ if (resolveResult !== null && resolveResult !== void 0) {
7752
+ return resolveResult;
7753
+ }
7754
+ } else {
7755
+ let bestMatch = "";
7756
+ let bestMatchSubpath = "";
7757
+ const keys = Object.getOwnPropertyNames(imports);
7758
+ let i = -1;
7759
+ while (++i < keys.length) {
7760
+ const key = keys[i];
7761
+ const patternIndex = key.indexOf("*");
7762
+ if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) {
7763
+ const patternTrailer = key.slice(patternIndex + 1);
7764
+ if (name.length >= key.length && name.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
7765
+ bestMatch = key;
7766
+ bestMatchSubpath = name.slice(
7767
+ patternIndex,
7768
+ name.length - patternTrailer.length
7769
+ );
7770
+ }
7771
+ }
7772
+ }
7773
+ if (bestMatch) {
7774
+ const target2 = imports[bestMatch];
7775
+ const resolveResult = resolvePackageTarget(
7776
+ packageJsonUrl,
7777
+ target2,
7778
+ bestMatchSubpath,
7779
+ bestMatch,
7780
+ base,
7781
+ true,
7782
+ true,
7783
+ false,
7784
+ conditions
7785
+ );
7786
+ if (resolveResult !== null && resolveResult !== void 0) {
7787
+ return resolveResult;
7788
+ }
7789
+ }
7790
+ }
7990
7791
  }
7991
7792
  }
7992
- const tries = ["./index.js", "./index.json", "./index.node"];
7993
- let i = -1;
7994
- while (++i < tries.length) {
7995
- guess = new URL$1(tries[i], packageJsonUrl);
7996
- if (fileExists(guess)) break;
7997
- guess = void 0;
7793
+ throw importNotDefined(name, packageJsonUrl, base);
7794
+ }
7795
+ function parsePackageName(specifier, base) {
7796
+ let separatorIndex = specifier.indexOf("/");
7797
+ let validPackageName = true;
7798
+ let isScoped = false;
7799
+ if (specifier[0] === "@") {
7800
+ isScoped = true;
7801
+ if (separatorIndex === -1 || specifier.length === 0) {
7802
+ validPackageName = false;
7803
+ } else {
7804
+ separatorIndex = specifier.indexOf("/", separatorIndex + 1);
7805
+ }
7998
7806
  }
7999
- if (guess) {
8000
- emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
8001
- return guess;
7807
+ const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
7808
+ if (invalidPackageNameRegEx.exec(packageName) !== null) {
7809
+ validPackageName = false;
8002
7810
  }
8003
- throw new ERR_MODULE_NOT_FOUND(
8004
- fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8005
- fileURLToPath$1(base)
8006
- );
8007
- }
8008
- function finalizeResolution(resolved, base, preserveSymlinks) {
8009
- if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) {
7811
+ if (!validPackageName) {
8010
7812
  throw new ERR_INVALID_MODULE_SPECIFIER(
8011
- resolved.pathname,
8012
- 'must not include encoded "/" or "\\" characters',
7813
+ specifier,
7814
+ "is not a valid package name",
8013
7815
  fileURLToPath$1(base)
8014
7816
  );
8015
7817
  }
8016
- let filePath;
8017
- try {
8018
- filePath = fileURLToPath$1(resolved);
8019
- } catch (error) {
8020
- const cause = (
8021
- /** @type {ErrnoException} */
8022
- error
8023
- );
8024
- Object.defineProperty(cause, "input", { value: String(resolved) });
8025
- Object.defineProperty(cause, "module", { value: String(base) });
8026
- throw cause;
8027
- }
8028
- const stats = tryStatSync(
8029
- filePath.endsWith("/") ? filePath.slice(-1) : filePath
8030
- );
8031
- if (stats && stats.isDirectory()) {
8032
- const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath$1(base));
8033
- error.url = String(resolved);
8034
- throw error;
8035
- }
8036
- if (!stats || !stats.isFile()) {
8037
- const error = new ERR_MODULE_NOT_FOUND(
8038
- filePath || resolved.pathname,
8039
- base && fileURLToPath$1(base),
8040
- true
8041
- );
8042
- error.url = String(resolved);
8043
- throw error;
8044
- }
8045
- {
8046
- const real = realpathSync(filePath);
8047
- const { search, hash } = resolved;
8048
- resolved = pathToFileURL$1(real + (filePath.endsWith(path4.sep) ? "/" : ""));
8049
- resolved.search = search;
8050
- resolved.hash = hash;
8051
- }
8052
- return resolved;
7818
+ const packageSubpath = "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex));
7819
+ return { packageName, packageSubpath, isScoped };
8053
7820
  }
8054
- function importNotDefined(specifier, packageJsonUrl, base) {
8055
- return new ERR_PACKAGE_IMPORT_NOT_DEFINED(
7821
+ function packageResolve(specifier, base, conditions) {
7822
+ if (builtinModules.includes(specifier)) {
7823
+ return new URL$1("node:" + specifier);
7824
+ }
7825
+ const { packageName, packageSubpath, isScoped } = parsePackageName(
8056
7826
  specifier,
8057
- packageJsonUrl && fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8058
- fileURLToPath$1(base)
7827
+ base
8059
7828
  );
8060
- }
8061
- function exportsNotFound(subpath, packageJsonUrl, base) {
8062
- return new ERR_PACKAGE_PATH_NOT_EXPORTED(
8063
- fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8064
- subpath,
8065
- base && fileURLToPath$1(base)
7829
+ const packageConfig = getPackageScopeConfig(base);
7830
+ if (packageConfig.exists) {
7831
+ const packageJsonUrl2 = pathToFileURL$1(packageConfig.pjsonPath);
7832
+ if (packageConfig.name === packageName && packageConfig.exports !== void 0 && packageConfig.exports !== null) {
7833
+ return packageExportsResolve(
7834
+ packageJsonUrl2,
7835
+ packageSubpath,
7836
+ packageConfig,
7837
+ base,
7838
+ conditions
7839
+ );
7840
+ }
7841
+ }
7842
+ let packageJsonUrl = new URL$1(
7843
+ "./node_modules/" + packageName + "/package.json",
7844
+ base
8066
7845
  );
7846
+ let packageJsonPath = fileURLToPath$1(packageJsonUrl);
7847
+ let lastPath;
7848
+ do {
7849
+ const stat = tryStatSync(packageJsonPath.slice(0, -13));
7850
+ if (!stat || !stat.isDirectory()) {
7851
+ lastPath = packageJsonPath;
7852
+ packageJsonUrl = new URL$1(
7853
+ (isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json",
7854
+ packageJsonUrl
7855
+ );
7856
+ packageJsonPath = fileURLToPath$1(packageJsonUrl);
7857
+ continue;
7858
+ }
7859
+ const packageConfig2 = read(packageJsonPath, { base, specifier });
7860
+ if (packageConfig2.exports !== void 0 && packageConfig2.exports !== null) {
7861
+ return packageExportsResolve(
7862
+ packageJsonUrl,
7863
+ packageSubpath,
7864
+ packageConfig2,
7865
+ base,
7866
+ conditions
7867
+ );
7868
+ }
7869
+ if (packageSubpath === ".") {
7870
+ return legacyMainResolve(packageJsonUrl, packageConfig2, base);
7871
+ }
7872
+ return new URL$1(packageSubpath, packageJsonUrl);
7873
+ } while (packageJsonPath.length !== lastPath.length);
7874
+ throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath$1(base), false);
8067
7875
  }
8068
- function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
8069
- const reason = `request is not a valid match in pattern "${match}" for the "${internal ? "imports" : "exports"}" resolution of ${fileURLToPath$1(packageJsonUrl)}`;
8070
- throw new ERR_INVALID_MODULE_SPECIFIER(
8071
- request,
8072
- reason,
8073
- base && fileURLToPath$1(base)
8074
- );
7876
+ function isRelativeSpecifier(specifier) {
7877
+ if (specifier[0] === ".") {
7878
+ if (specifier.length === 1 || specifier[1] === "/") return true;
7879
+ if (specifier[1] === "." && (specifier.length === 2 || specifier[2] === "/")) {
7880
+ return true;
7881
+ }
7882
+ }
7883
+ return false;
8075
7884
  }
8076
- function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
8077
- target = typeof target === "object" && target !== null ? JSON.stringify(target, null, "") : `${target}`;
8078
- return new ERR_INVALID_PACKAGE_TARGET(
8079
- fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8080
- subpath,
8081
- target,
8082
- internal,
8083
- base && fileURLToPath$1(base)
8084
- );
7885
+ function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
7886
+ if (specifier === "") return false;
7887
+ if (specifier[0] === "/") return true;
7888
+ return isRelativeSpecifier(specifier);
8085
7889
  }
8086
- function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
8087
- if (subpath !== "" && !pattern && target[target.length - 1] !== "/")
8088
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8089
- if (!target.startsWith("./")) {
8090
- if (internal && !target.startsWith("../") && !target.startsWith("/")) {
8091
- let isURL = false;
8092
- try {
8093
- new URL$1(target);
8094
- isURL = true;
8095
- } catch {
8096
- }
8097
- if (!isURL) {
8098
- const exportTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8099
- patternRegEx,
8100
- target,
8101
- () => subpath
8102
- ) : target + subpath;
8103
- return packageResolve(exportTarget, packageJsonUrl, conditions);
7890
+ function moduleResolve(specifier, base, conditions, preserveSymlinks) {
7891
+ const protocol = base.protocol;
7892
+ const isData = protocol === "data:";
7893
+ const isRemote = isData || protocol === "http:" || protocol === "https:";
7894
+ let resolved;
7895
+ if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
7896
+ try {
7897
+ resolved = new URL$1(specifier, base);
7898
+ } catch (error_) {
7899
+ const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
7900
+ error.cause = error_;
7901
+ throw error;
7902
+ }
7903
+ } else if (protocol === "file:" && specifier[0] === "#") {
7904
+ resolved = packageImportsResolve(specifier, base, conditions);
7905
+ } else {
7906
+ try {
7907
+ resolved = new URL$1(specifier);
7908
+ } catch (error_) {
7909
+ if (isRemote && !builtinModules.includes(specifier)) {
7910
+ const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
7911
+ error.cause = error_;
7912
+ throw error;
8104
7913
  }
7914
+ resolved = packageResolve(specifier, base, conditions);
8105
7915
  }
8106
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8107
7916
  }
8108
- if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
8109
- if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
8110
- if (!isPathMap) {
8111
- const request = pattern ? match.replace("*", () => subpath) : match + subpath;
8112
- const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8113
- patternRegEx,
8114
- target,
8115
- () => subpath
8116
- ) : target;
8117
- emitInvalidSegmentDeprecation(
8118
- resolvedTarget,
8119
- request,
8120
- match,
8121
- packageJsonUrl,
8122
- internal,
8123
- base,
8124
- true
8125
- );
8126
- }
8127
- } else {
8128
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
7917
+ assert(resolved !== void 0, "expected to be defined");
7918
+ if (resolved.protocol !== "file:") {
7919
+ return resolved;
7920
+ }
7921
+ return finalizeResolution(resolved, base);
7922
+ }
7923
+ function fileURLToPath(id) {
7924
+ if (typeof id === "string" && !id.startsWith("file://")) {
7925
+ return normalizeSlash(id);
7926
+ }
7927
+ return normalizeSlash(fileURLToPath$1(id));
7928
+ }
7929
+ function pathToFileURL(id) {
7930
+ return pathToFileURL$1(fileURLToPath(id)).toString();
7931
+ }
7932
+ function normalizeid(id) {
7933
+ if (typeof id !== "string") {
7934
+ id = id.toString();
7935
+ }
7936
+ if (/(node|data|http|https|file):/.test(id)) {
7937
+ return id;
7938
+ }
7939
+ if (BUILTIN_MODULES.has(id)) {
7940
+ return "node:" + id;
7941
+ }
7942
+ return "file://" + encodeURI(normalizeSlash(id));
7943
+ }
7944
+ var DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
7945
+ var DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
7946
+ var NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
7947
+ "ERR_MODULE_NOT_FOUND",
7948
+ "ERR_UNSUPPORTED_DIR_IMPORT",
7949
+ "MODULE_NOT_FOUND",
7950
+ "ERR_PACKAGE_PATH_NOT_EXPORTED"
7951
+ ]);
7952
+ function _tryModuleResolve(id, url, conditions) {
7953
+ try {
7954
+ return moduleResolve(id, url, conditions);
7955
+ } catch (error) {
7956
+ if (!NOT_FOUND_ERRORS.has(error?.code)) {
7957
+ throw error;
8129
7958
  }
8130
7959
  }
8131
- const resolved = new URL$1(target, packageJsonUrl);
8132
- const resolvedPath = resolved.pathname;
8133
- const packagePath = new URL$1(".", packageJsonUrl).pathname;
8134
- if (!resolvedPath.startsWith(packagePath))
8135
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8136
- if (subpath === "") return resolved;
8137
- if (invalidSegmentRegEx.exec(subpath) !== null) {
8138
- const request = pattern ? match.replace("*", () => subpath) : match + subpath;
8139
- if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
8140
- if (!isPathMap) {
8141
- const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8142
- patternRegEx,
8143
- target,
8144
- () => subpath
8145
- ) : target;
8146
- emitInvalidSegmentDeprecation(
8147
- resolvedTarget,
8148
- request,
8149
- match,
8150
- packageJsonUrl,
8151
- internal,
8152
- base,
8153
- false
8154
- );
8155
- }
7960
+ }
7961
+ function _resolve(id, options = {}) {
7962
+ if (typeof id !== "string") {
7963
+ if (id instanceof URL) {
7964
+ id = fileURLToPath(id);
8156
7965
  } else {
8157
- throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
7966
+ throw new TypeError("input must be a `string` or `URL`");
8158
7967
  }
8159
7968
  }
8160
- if (pattern) {
8161
- return new URL$1(
8162
- RegExpPrototypeSymbolReplace.call(
8163
- patternRegEx,
8164
- resolved.href,
8165
- () => subpath
8166
- )
8167
- );
7969
+ if (/(node|data|http|https):/.test(id)) {
7970
+ return id;
8168
7971
  }
8169
- return new URL$1(subpath, resolved);
8170
- }
8171
- function isArrayIndex(key) {
8172
- const keyNumber = Number(key);
8173
- if (`${keyNumber}` !== key) return false;
8174
- return keyNumber >= 0 && keyNumber < 4294967295;
8175
- }
8176
- function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
8177
- if (typeof target === "string") {
8178
- return resolvePackageTargetString(
8179
- target,
8180
- subpath,
8181
- packageSubpath,
8182
- packageJsonUrl,
8183
- base,
8184
- pattern,
8185
- internal,
8186
- isPathMap,
8187
- conditions
8188
- );
7972
+ if (BUILTIN_MODULES.has(id)) {
7973
+ return "node:" + id;
8189
7974
  }
8190
- if (Array.isArray(target)) {
8191
- const targetList = target;
8192
- if (targetList.length === 0) return null;
8193
- let lastException;
8194
- let i = -1;
8195
- while (++i < targetList.length) {
8196
- const targetItem = targetList[i];
8197
- let resolveResult;
8198
- try {
8199
- resolveResult = resolvePackageTarget(
8200
- packageJsonUrl,
8201
- targetItem,
8202
- subpath,
8203
- packageSubpath,
8204
- base,
8205
- pattern,
8206
- internal,
8207
- isPathMap,
8208
- conditions
8209
- );
8210
- } catch (error) {
8211
- const exception = (
8212
- /** @type {ErrnoException} */
8213
- error
8214
- );
8215
- lastException = exception;
8216
- if (exception.code === "ERR_INVALID_PACKAGE_TARGET") continue;
8217
- throw error;
7975
+ if (id.startsWith("file://")) {
7976
+ id = fileURLToPath(id);
7977
+ }
7978
+ if (isAbsolute(id)) {
7979
+ try {
7980
+ const stat = statSync(id);
7981
+ if (stat.isFile()) {
7982
+ return pathToFileURL(id);
8218
7983
  }
8219
- if (resolveResult === void 0) continue;
8220
- if (resolveResult === null) {
8221
- lastException = null;
8222
- continue;
7984
+ } catch (error) {
7985
+ if (error?.code !== "ENOENT") {
7986
+ throw error;
8223
7987
  }
8224
- return resolveResult;
8225
7988
  }
8226
- if (lastException === void 0 || lastException === null) {
8227
- return null;
7989
+ }
7990
+ const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
7991
+ const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString())));
7992
+ if (_urls.length === 0) {
7993
+ _urls.push(new URL(pathToFileURL(process.cwd())));
7994
+ }
7995
+ const urls = [..._urls];
7996
+ for (const url of _urls) {
7997
+ if (url.protocol === "file:") {
7998
+ urls.push(
7999
+ new URL("./", url),
8000
+ // If url is directory
8001
+ new URL(joinURL(url.pathname, "_index.js"), url),
8002
+ // TODO: Remove in next major version?
8003
+ new URL("node_modules", url)
8004
+ );
8228
8005
  }
8229
- throw lastException;
8230
8006
  }
8231
- if (typeof target === "object" && target !== null) {
8232
- const keys = Object.getOwnPropertyNames(target);
8233
- let i = -1;
8234
- while (++i < keys.length) {
8235
- const key = keys[i];
8236
- if (isArrayIndex(key)) {
8237
- throw new ERR_INVALID_PACKAGE_CONFIG(
8238
- fileURLToPath$1(packageJsonUrl),
8239
- base,
8240
- '"exports" cannot contain numeric property keys.'
8241
- );
8242
- }
8007
+ let resolved;
8008
+ for (const url of urls) {
8009
+ resolved = _tryModuleResolve(id, url, conditionsSet);
8010
+ if (resolved) {
8011
+ break;
8243
8012
  }
8244
- i = -1;
8245
- while (++i < keys.length) {
8246
- const key = keys[i];
8247
- if (key === "default" || conditions && conditions.has(key)) {
8248
- const conditionalTarget = (
8249
- /** @type {unknown} */
8250
- target[key]
8251
- );
8252
- const resolveResult = resolvePackageTarget(
8253
- packageJsonUrl,
8254
- conditionalTarget,
8255
- subpath,
8256
- packageSubpath,
8257
- base,
8258
- pattern,
8259
- internal,
8260
- isPathMap,
8261
- conditions
8013
+ for (const prefix of ["", "/index"]) {
8014
+ for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
8015
+ resolved = _tryModuleResolve(
8016
+ joinURL(id, prefix) + extension,
8017
+ url,
8018
+ conditionsSet
8262
8019
  );
8263
- if (resolveResult === void 0) continue;
8264
- return resolveResult;
8020
+ if (resolved) {
8021
+ break;
8022
+ }
8023
+ }
8024
+ if (resolved) {
8025
+ break;
8265
8026
  }
8266
8027
  }
8267
- return null;
8028
+ if (resolved) {
8029
+ break;
8030
+ }
8268
8031
  }
8269
- if (target === null) {
8270
- return null;
8032
+ if (!resolved) {
8033
+ const error = new Error(
8034
+ `Cannot find module ${id} imported from ${urls.join(", ")}`
8035
+ );
8036
+ error.code = "ERR_MODULE_NOT_FOUND";
8037
+ throw error;
8271
8038
  }
8272
- throw invalidPackageTarget(
8273
- packageSubpath,
8274
- target,
8275
- packageJsonUrl,
8276
- internal,
8277
- base
8278
- );
8039
+ return pathToFileURL(resolved);
8279
8040
  }
8280
- function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
8281
- if (typeof exports === "string" || Array.isArray(exports)) return true;
8282
- if (typeof exports !== "object" || exports === null) return false;
8283
- const keys = Object.getOwnPropertyNames(exports);
8284
- let isConditionalSugar = false;
8285
- let i = 0;
8286
- let keyIndex = -1;
8287
- while (++keyIndex < keys.length) {
8288
- const key = keys[keyIndex];
8289
- const currentIsConditionalSugar = key === "" || key[0] !== ".";
8290
- if (i++ === 0) {
8291
- isConditionalSugar = currentIsConditionalSugar;
8292
- } else if (isConditionalSugar !== currentIsConditionalSugar) {
8293
- throw new ERR_INVALID_PACKAGE_CONFIG(
8294
- fileURLToPath$1(packageJsonUrl),
8295
- base,
8296
- `"exports" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only.`
8041
+ function resolveSync(id, options) {
8042
+ return _resolve(id, options);
8043
+ }
8044
+ function resolvePathSync(id, options) {
8045
+ return fileURLToPath(resolveSync(id, options));
8046
+ }
8047
+
8048
+ // src/node-js-compat.ts
8049
+ import { defineEnv } from "unenv";
8050
+ var { env } = defineEnv({
8051
+ nodeCompat: true,
8052
+ presets: [cloudflare]
8053
+ });
8054
+ var nodeCompatExternals = new Set(env.external);
8055
+ var nodeCompatEntries = getNodeCompatEntries();
8056
+ function isNodeCompat(workerConfig) {
8057
+ if (workerConfig === void 0) {
8058
+ return false;
8059
+ }
8060
+ const nodeCompatMode = getNodeCompat(
8061
+ workerConfig.compatibility_date,
8062
+ workerConfig.compatibility_flags ?? []
8063
+ ).mode;
8064
+ if (nodeCompatMode === "v2") {
8065
+ return true;
8066
+ }
8067
+ if (nodeCompatMode === "v1") {
8068
+ throw new Error(
8069
+ `Unsupported Node.js compat mode (v1). Only the v2 mode is supported, either change your compat date to "2024-09-23" or later, or set the "nodejs_compat_v2" compatibility flag`
8070
+ );
8071
+ }
8072
+ return false;
8073
+ }
8074
+ function injectGlobalCode(id, code) {
8075
+ const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
8076
+ if (typeof globalInject === "string") {
8077
+ const moduleSpecifier2 = globalInject;
8078
+ return `import var_${globalName} from "${moduleSpecifier2}";
8079
+ globalThis.${globalName} = var_${globalName};
8080
+ `;
8081
+ }
8082
+ const [moduleSpecifier, exportName] = globalInject;
8083
+ assert2(
8084
+ moduleSpecifier !== void 0,
8085
+ "Expected moduleSpecifier to be defined"
8086
+ );
8087
+ assert2(exportName !== void 0, "Expected exportName to be defined");
8088
+ return `import var_${globalName} from "${moduleSpecifier}";
8089
+ globalThis.${globalName} = var_${globalName}.${exportName};
8090
+ `;
8091
+ }).join("\n");
8092
+ const polyfillCode = env.polyfill.map((polyfillPath) => `import "${polyfillPath}";
8093
+ `).join("");
8094
+ const modified = new MagicString(code);
8095
+ modified.prepend(injectedCode);
8096
+ modified.prepend(polyfillCode);
8097
+ return {
8098
+ code: modified.toString(),
8099
+ map: modified.generateMap({ hires: "boundary", source: id })
8100
+ };
8101
+ }
8102
+ function resolveNodeJSImport(source) {
8103
+ const alias = env.alias[source];
8104
+ if (alias) {
8105
+ return {
8106
+ unresolved: alias,
8107
+ resolved: resolvePathSync(alias, { url: import.meta.url })
8108
+ };
8109
+ }
8110
+ if (nodeCompatEntries.has(source)) {
8111
+ return {
8112
+ unresolved: source,
8113
+ resolved: resolvePathSync(source, { url: import.meta.url })
8114
+ };
8115
+ }
8116
+ }
8117
+ function getNodeCompatEntries() {
8118
+ const entries = new Set(Object.values(env.alias));
8119
+ for (const globalInject of Object.values(env.inject)) {
8120
+ if (typeof globalInject === "string") {
8121
+ entries.add(globalInject);
8122
+ } else {
8123
+ assert2(
8124
+ globalInject[0] !== void 0,
8125
+ "Expected first element of globalInject to be defined"
8297
8126
  );
8127
+ entries.add(globalInject[0]);
8128
+ }
8129
+ }
8130
+ env.polyfill.forEach((polyfill) => entries.add(polyfill));
8131
+ nodeCompatExternals.forEach((external) => entries.delete(external));
8132
+ return entries;
8133
+ }
8134
+
8135
+ // src/shared.ts
8136
+ var UNKNOWN_HOST = "http://localhost";
8137
+ var INIT_PATH = "/__vite_plugin_cloudflare_init__";
8138
+ var ADDITIONAL_MODULE_PATTERN = `__CLOUDFLARE_MODULE__(${ADDITIONAL_MODULE_TYPES.join("|")})__(.*?)__`;
8139
+ var additionalModuleRE = new RegExp(ADDITIONAL_MODULE_PATTERN);
8140
+ var additionalModuleGlobalRE = new RegExp(
8141
+ ADDITIONAL_MODULE_PATTERN,
8142
+ "g"
8143
+ );
8144
+ var VITE_DEV_METADATA_HEADER = "__VITE_DEV_METADATA__";
8145
+
8146
+ // src/utils.ts
8147
+ import * as path2 from "node:path";
8148
+ import { Request as MiniflareRequest } from "miniflare";
8149
+ import "vite";
8150
+ function getOutputDirectory(userConfig, environmentName) {
8151
+ const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
8152
+ return userConfig.environments?.[environmentName]?.build?.outDir ?? path2.join(rootOutputDirectory, environmentName);
8153
+ }
8154
+ function getRouterWorker(miniflare) {
8155
+ return miniflare.getWorker(ROUTER_WORKER_NAME);
8156
+ }
8157
+ function toMiniflareRequest(request) {
8158
+ const secFetchMode = request.headers.get("Sec-Fetch-Mode");
8159
+ if (secFetchMode) {
8160
+ request.headers.set("X-Mf-Sec-Fetch-Mode", secFetchMode);
8161
+ }
8162
+ return new MiniflareRequest(request.url, {
8163
+ method: request.method,
8164
+ headers: [["accept-encoding", "identity"], ...request.headers],
8165
+ body: request.body,
8166
+ duplex: "half"
8167
+ });
8168
+ }
8169
+ function nodeHeadersToWebHeaders(nodeHeaders) {
8170
+ const headers = new Headers();
8171
+ for (const [key, value] of Object.entries(nodeHeaders)) {
8172
+ if (typeof value === "string") {
8173
+ headers.append(key, value);
8174
+ } else if (Array.isArray(value)) {
8175
+ for (const item of value) {
8176
+ headers.append(key, item);
8177
+ }
8298
8178
  }
8299
8179
  }
8300
- return isConditionalSugar;
8180
+ return headers;
8301
8181
  }
8302
- function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
8303
- if (process$1.noDeprecation) {
8304
- return;
8305
- }
8306
- const pjsonPath = fileURLToPath$1(pjsonUrl);
8307
- if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return;
8308
- emittedPackageWarnings.add(pjsonPath + "|" + match);
8309
- process$1.emitWarning(
8310
- `Use of deprecated trailing slash pattern mapping "${match}" in the "exports" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath$1(base)}` : ""}. Mapping specifiers ending in "/" is no longer supported.`,
8311
- "DeprecationWarning",
8312
- "DEP0155"
8313
- );
8182
+ var postfixRE = /[?#].*$/;
8183
+ function cleanUrl(url) {
8184
+ return url.replace(postfixRE, "");
8314
8185
  }
8315
- function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
8316
- let exports = packageConfig.exports;
8317
- if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
8318
- exports = { ".": exports };
8319
- }
8320
- if (own.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
8321
- const target = exports[packageSubpath];
8322
- const resolveResult = resolvePackageTarget(
8323
- packageJsonUrl,
8324
- target,
8325
- "",
8326
- packageSubpath,
8327
- base,
8328
- false,
8329
- false,
8330
- false,
8331
- conditions
8332
- );
8333
- if (resolveResult === null || resolveResult === void 0) {
8334
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
8186
+
8187
+ // src/cloudflare-environment.ts
8188
+ var webSocketUndefinedError = "The WebSocket is undefined";
8189
+ function createHotChannel(webSocketContainer) {
8190
+ const listenersMap = /* @__PURE__ */ new Map();
8191
+ const client = {
8192
+ send(payload) {
8193
+ const webSocket = webSocketContainer.webSocket;
8194
+ assert3(webSocket, webSocketUndefinedError);
8195
+ webSocket.send(JSON.stringify(payload));
8335
8196
  }
8336
- return resolveResult;
8337
- }
8338
- let bestMatch = "";
8339
- let bestMatchSubpath = "";
8340
- const keys = Object.getOwnPropertyNames(exports);
8341
- let i = -1;
8342
- while (++i < keys.length) {
8343
- const key = keys[i];
8344
- const patternIndex = key.indexOf("*");
8345
- if (patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex))) {
8346
- if (packageSubpath.endsWith("/")) {
8347
- emitTrailingSlashPatternDeprecation(
8348
- packageSubpath,
8349
- packageJsonUrl,
8350
- base
8351
- );
8352
- }
8353
- const patternTrailer = key.slice(patternIndex + 1);
8354
- if (packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
8355
- bestMatch = key;
8356
- bestMatchSubpath = packageSubpath.slice(
8357
- patternIndex,
8358
- packageSubpath.length - patternTrailer.length
8359
- );
8360
- }
8197
+ };
8198
+ function onMessage(event) {
8199
+ const payload = JSON.parse(event.data.toString());
8200
+ const listeners = listenersMap.get(payload.event) ?? /* @__PURE__ */ new Set();
8201
+ for (const listener of listeners) {
8202
+ listener(payload.data, client);
8361
8203
  }
8362
8204
  }
8363
- if (bestMatch) {
8364
- const target = (
8365
- /** @type {unknown} */
8366
- exports[bestMatch]
8367
- );
8368
- const resolveResult = resolvePackageTarget(
8369
- packageJsonUrl,
8370
- target,
8371
- bestMatchSubpath,
8372
- bestMatch,
8373
- base,
8374
- true,
8375
- false,
8376
- packageSubpath.endsWith("/"),
8377
- conditions
8378
- );
8379
- if (resolveResult === null || resolveResult === void 0) {
8380
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
8205
+ return {
8206
+ send(payload) {
8207
+ const webSocket = webSocketContainer.webSocket;
8208
+ assert3(webSocket, webSocketUndefinedError);
8209
+ webSocket.send(JSON.stringify(payload));
8210
+ },
8211
+ on(event, listener) {
8212
+ const listeners = listenersMap.get(event) ?? /* @__PURE__ */ new Set();
8213
+ listeners.add(listener);
8214
+ listenersMap.set(event, listeners);
8215
+ },
8216
+ off(event, listener) {
8217
+ listenersMap.get(event)?.delete(listener);
8218
+ },
8219
+ listen() {
8220
+ const webSocket = webSocketContainer.webSocket;
8221
+ assert3(webSocket, webSocketUndefinedError);
8222
+ webSocket.addEventListener("message", onMessage);
8223
+ },
8224
+ close() {
8225
+ const webSocket = webSocketContainer.webSocket;
8226
+ assert3(webSocket, webSocketUndefinedError);
8227
+ webSocket.removeEventListener("message", onMessage);
8381
8228
  }
8382
- return resolveResult;
8383
- }
8384
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
8385
- }
8386
- function patternKeyCompare(a, b) {
8387
- const aPatternIndex = a.indexOf("*");
8388
- const bPatternIndex = b.indexOf("*");
8389
- const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
8390
- const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
8391
- if (baseLengthA > baseLengthB) return -1;
8392
- if (baseLengthB > baseLengthA) return 1;
8393
- if (aPatternIndex === -1) return 1;
8394
- if (bPatternIndex === -1) return -1;
8395
- if (a.length > b.length) return -1;
8396
- if (b.length > a.length) return 1;
8397
- return 0;
8229
+ };
8398
8230
  }
8399
- function packageImportsResolve(name2, base, conditions) {
8400
- if (name2 === "#" || name2.startsWith("#/") || name2.endsWith("/")) {
8401
- const reason = "is not a valid internal imports specifier name";
8402
- throw new ERR_INVALID_MODULE_SPECIFIER(name2, reason, fileURLToPath$1(base));
8231
+ var CloudflareDevEnvironment = class extends vite2.DevEnvironment {
8232
+ #webSocketContainer;
8233
+ #worker;
8234
+ constructor(name, config) {
8235
+ const webSocketContainer = {};
8236
+ super(name, config, {
8237
+ hot: true,
8238
+ transport: createHotChannel(webSocketContainer)
8239
+ });
8240
+ this.#webSocketContainer = webSocketContainer;
8403
8241
  }
8404
- let packageJsonUrl;
8405
- const packageConfig = getPackageScopeConfig(base);
8406
- if (packageConfig.exists) {
8407
- packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
8408
- const imports = packageConfig.imports;
8409
- if (imports) {
8410
- if (own.call(imports, name2) && !name2.includes("*")) {
8411
- const resolveResult = resolvePackageTarget(
8412
- packageJsonUrl,
8413
- imports[name2],
8414
- "",
8415
- name2,
8416
- base,
8417
- false,
8418
- true,
8419
- false,
8420
- conditions
8421
- );
8422
- if (resolveResult !== null && resolveResult !== void 0) {
8423
- return resolveResult;
8424
- }
8425
- } else {
8426
- let bestMatch = "";
8427
- let bestMatchSubpath = "";
8428
- const keys = Object.getOwnPropertyNames(imports);
8429
- let i = -1;
8430
- while (++i < keys.length) {
8431
- const key = keys[i];
8432
- const patternIndex = key.indexOf("*");
8433
- if (patternIndex !== -1 && name2.startsWith(key.slice(0, -1))) {
8434
- const patternTrailer = key.slice(patternIndex + 1);
8435
- if (name2.length >= key.length && name2.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
8436
- bestMatch = key;
8437
- bestMatchSubpath = name2.slice(
8438
- patternIndex,
8439
- name2.length - patternTrailer.length
8440
- );
8441
- }
8442
- }
8443
- }
8444
- if (bestMatch) {
8445
- const target = imports[bestMatch];
8446
- const resolveResult = resolvePackageTarget(
8447
- packageJsonUrl,
8448
- target,
8449
- bestMatchSubpath,
8450
- bestMatch,
8451
- base,
8452
- true,
8453
- true,
8454
- false,
8455
- conditions
8456
- );
8457
- if (resolveResult !== null && resolveResult !== void 0) {
8458
- return resolveResult;
8459
- }
8242
+ async initRunner(worker, root, workerConfig) {
8243
+ this.#worker = worker;
8244
+ const response = await this.#worker.fetch(
8245
+ new URL(INIT_PATH, UNKNOWN_HOST),
8246
+ {
8247
+ headers: {
8248
+ [VITE_DEV_METADATA_HEADER]: JSON.stringify({
8249
+ root,
8250
+ entryPath: workerConfig.main
8251
+ }),
8252
+ upgrade: "websocket"
8460
8253
  }
8461
8254
  }
8462
- }
8463
- }
8464
- throw importNotDefined(name2, packageJsonUrl, base);
8465
- }
8466
- function parsePackageName(specifier, base) {
8467
- let separatorIndex = specifier.indexOf("/");
8468
- let validPackageName = true;
8469
- let isScoped = false;
8470
- if (specifier[0] === "@") {
8471
- isScoped = true;
8472
- if (separatorIndex === -1 || specifier.length === 0) {
8473
- validPackageName = false;
8474
- } else {
8475
- separatorIndex = specifier.indexOf("/", separatorIndex + 1);
8476
- }
8477
- }
8478
- const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
8479
- if (invalidPackageNameRegEx.exec(packageName) !== null) {
8480
- validPackageName = false;
8481
- }
8482
- if (!validPackageName) {
8483
- throw new ERR_INVALID_MODULE_SPECIFIER(
8484
- specifier,
8485
- "is not a valid package name",
8486
- fileURLToPath$1(base)
8487
- );
8488
- }
8489
- const packageSubpath = "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex));
8490
- return { packageName, packageSubpath, isScoped };
8255
+ );
8256
+ assert3(
8257
+ response.ok,
8258
+ `Failed to initialize module runner, error: ${await response.text()}`
8259
+ );
8260
+ const webSocket = response.webSocket;
8261
+ assert3(webSocket, "Failed to establish WebSocket");
8262
+ webSocket.accept();
8263
+ this.#webSocketContainer.webSocket = webSocket;
8264
+ }
8265
+ };
8266
+ var cloudflareBuiltInModules = [
8267
+ "cloudflare:email",
8268
+ "cloudflare:sockets",
8269
+ "cloudflare:workers",
8270
+ "cloudflare:workflows"
8271
+ ];
8272
+ var defaultConditions = ["workerd", "module", "browser"];
8273
+ var target = "es2022";
8274
+ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmentName) {
8275
+ return {
8276
+ resolve: {
8277
+ // Note: in order for ssr pre-bundling to take effect we need to ask vite to treat all
8278
+ // dependencies as not external
8279
+ noExternal: true,
8280
+ // We want to use `workerd` package exports if available (e.g. for postgres).
8281
+ conditions: [...defaultConditions, "development|production"],
8282
+ // The Cloudflare ones are proper builtins in the environment
8283
+ builtins: [...cloudflareBuiltInModules]
8284
+ },
8285
+ dev: {
8286
+ createEnvironment(name, config) {
8287
+ return new CloudflareDevEnvironment(name, config);
8288
+ }
8289
+ },
8290
+ build: {
8291
+ createEnvironment(name, config) {
8292
+ return new vite2.BuildEnvironment(name, config);
8293
+ },
8294
+ target,
8295
+ // We need to enable `emitAssets` in order to support additional modules defined by `rules`
8296
+ emitAssets: true,
8297
+ outDir: getOutputDirectory(userConfig, environmentName),
8298
+ copyPublicDir: false,
8299
+ ssr: true,
8300
+ rollupOptions: {
8301
+ // Note: vite starts dev pre-bundling crawling from either optimizeDeps.entries or rollupOptions.input
8302
+ // so the input value here serves both as the build input as well as the starting point for
8303
+ // dev pre-bundling crawling (were we not to set this input field we'd have to appropriately set
8304
+ // optimizeDeps.entries in the dev config)
8305
+ input: workerConfig.main
8306
+ }
8307
+ },
8308
+ optimizeDeps: {
8309
+ // Note: ssr pre-bundling is opt-in and we need to enable it by setting `noDiscovery` to false
8310
+ noDiscovery: false,
8311
+ entries: workerConfig.main,
8312
+ exclude: [...cloudflareBuiltInModules],
8313
+ esbuildOptions: {
8314
+ platform: "neutral",
8315
+ target,
8316
+ conditions: [...defaultConditions, "development"],
8317
+ resolveExtensions: [
8318
+ ".mjs",
8319
+ ".js",
8320
+ ".mts",
8321
+ ".ts",
8322
+ ".jsx",
8323
+ ".tsx",
8324
+ ".json",
8325
+ ".cjs",
8326
+ ".cts",
8327
+ ".ctx"
8328
+ ]
8329
+ }
8330
+ },
8331
+ // if nodeCompat is enabled then let's keep the real process.env so that workerd can manipulate it
8332
+ keepProcessEnv: isNodeCompat(workerConfig)
8333
+ };
8491
8334
  }
8492
- function packageResolve(specifier, base, conditions) {
8493
- if (builtinModules2.includes(specifier)) {
8494
- return new URL$1("node:" + specifier);
8495
- }
8496
- const { packageName, packageSubpath, isScoped } = parsePackageName(
8497
- specifier,
8498
- base
8499
- );
8500
- const packageConfig = getPackageScopeConfig(base);
8501
- if (packageConfig.exists) {
8502
- const packageJsonUrl2 = pathToFileURL$1(packageConfig.pjsonPath);
8503
- if (packageConfig.name === packageName && packageConfig.exports !== void 0 && packageConfig.exports !== null) {
8504
- return packageExportsResolve(
8505
- packageJsonUrl2,
8506
- packageSubpath,
8507
- packageConfig,
8508
- base,
8509
- conditions
8510
- );
8511
- }
8335
+ function initRunners(resolvedPluginConfig, viteDevServer, miniflare) {
8336
+ if (resolvedPluginConfig.type === "assets-only") {
8337
+ return;
8512
8338
  }
8513
- let packageJsonUrl = new URL$1(
8514
- "./node_modules/" + packageName + "/package.json",
8515
- base
8339
+ return Promise.all(
8340
+ Object.entries(resolvedPluginConfig.workers).map(
8341
+ async ([environmentName, workerConfig]) => {
8342
+ const worker = await miniflare.getWorker(workerConfig.name);
8343
+ return viteDevServer.environments[environmentName].initRunner(worker, viteDevServer.config.root, workerConfig);
8344
+ }
8345
+ )
8516
8346
  );
8517
- let packageJsonPath = fileURLToPath$1(packageJsonUrl);
8518
- let lastPath;
8519
- do {
8520
- const stat = tryStatSync(packageJsonPath.slice(0, -13));
8521
- if (!stat || !stat.isDirectory()) {
8522
- lastPath = packageJsonPath;
8523
- packageJsonUrl = new URL$1(
8524
- (isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json",
8525
- packageJsonUrl
8347
+ }
8348
+
8349
+ // src/debugging.ts
8350
+ import assert4 from "node:assert";
8351
+ import colors from "picocolors";
8352
+ var debuggingPath = "/__debug";
8353
+ function addDebugToVitePrintUrls(server) {
8354
+ const originalPrintUrls = server.printUrls;
8355
+ server.printUrls = () => {
8356
+ originalPrintUrls();
8357
+ const localUrl = server.resolvedUrls?.local[0];
8358
+ if (localUrl) {
8359
+ const { protocol, hostname, port } = new URL(localUrl);
8360
+ const colorDebugUrl = (url) => colors.dim(
8361
+ colors.yellow(
8362
+ url.replace(/:(\d+)\//, (_, port2) => `:${colors.bold(port2)}/`)
8363
+ )
8526
8364
  );
8527
- packageJsonPath = fileURLToPath$1(packageJsonUrl);
8528
- continue;
8529
- }
8530
- const packageConfig2 = read(packageJsonPath, { base, specifier });
8531
- if (packageConfig2.exports !== void 0 && packageConfig2.exports !== null) {
8532
- return packageExportsResolve(
8533
- packageJsonUrl,
8534
- packageSubpath,
8535
- packageConfig2,
8536
- base,
8537
- conditions
8365
+ server.config.logger.info(
8366
+ ` ${colors.green("\u279C")} ${colors.bold("Debug")}: ${colorDebugUrl(`${protocol}//${hostname}:${port}${debuggingPath}`)}`
8538
8367
  );
8539
8368
  }
8540
- if (packageSubpath === ".") {
8541
- return legacyMainResolve(packageJsonUrl, packageConfig2, base);
8542
- }
8543
- return new URL$1(packageSubpath, packageJsonUrl);
8544
- } while (packageJsonPath.length !== lastPath.length);
8545
- throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath$1(base), false);
8369
+ };
8546
8370
  }
8547
- function isRelativeSpecifier(specifier) {
8548
- if (specifier[0] === ".") {
8549
- if (specifier.length === 1 || specifier[1] === "/") return true;
8550
- if (specifier[1] === "." && (specifier.length === 2 || specifier[2] === "/")) {
8551
- return true;
8552
- }
8553
- }
8554
- return false;
8371
+ function getDebugPathHtml(workerNames, inspectorPort) {
8372
+ assert4(workerNames.length >= 1, "no workers present to debug");
8373
+ const workerDevtoolsUrls = workerNames.map((workerName) => {
8374
+ const localHost = `localhost:${inspectorPort}/${workerName}`;
8375
+ const searchParams = new URLSearchParams({
8376
+ theme: "systemPreferred",
8377
+ debugger: "true",
8378
+ ws: localHost,
8379
+ domain: workerName
8380
+ });
8381
+ const devtoolsFrontendUrl = `https://devtools.devprod.cloudflare.dev/js_app?${searchParams}`;
8382
+ return devtoolsFrontendUrl;
8383
+ });
8384
+ return `
8385
+ <script>
8386
+ const workerUrls = ${JSON.stringify(workerDevtoolsUrls)};
8387
+ const [firstUrl, ...rest] = workerUrls;
8388
+ for (const workerUrl of rest) {
8389
+ // open new tabs for the devtools of the various workers
8390
+ window.open(workerUrl);
8391
+ }
8392
+ // redirect the current tab to the devtools of the first worker
8393
+ window.location.replace(firstUrl);
8394
+ </script>
8395
+ `;
8555
8396
  }
8556
- function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
8557
- if (specifier === "") return false;
8558
- if (specifier[0] === "/") return true;
8559
- return isRelativeSpecifier(specifier);
8397
+
8398
+ // src/deploy-config.ts
8399
+ import assert5 from "node:assert";
8400
+ import * as fs2 from "node:fs";
8401
+ import * as path3 from "node:path";
8402
+ import "vite";
8403
+ import { unstable_readConfig } from "wrangler";
8404
+ function getDeployConfigPath(root) {
8405
+ return path3.resolve(root, ".wrangler", "deploy", "config.json");
8560
8406
  }
8561
- function moduleResolve(specifier, base, conditions, preserveSymlinks) {
8562
- const protocol = base.protocol;
8563
- const isData = protocol === "data:";
8564
- const isRemote = isData || protocol === "http:" || protocol === "https:";
8565
- let resolved;
8566
- if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
8567
- try {
8568
- resolved = new URL$1(specifier, base);
8569
- } catch (error_) {
8570
- const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8571
- error.cause = error_;
8572
- throw error;
8573
- }
8574
- } else if (protocol === "file:" && specifier[0] === "#") {
8575
- resolved = packageImportsResolve(specifier, base, conditions);
8407
+ function getWorkerConfigs(root) {
8408
+ const deployConfigPath = getDeployConfigPath(root);
8409
+ const deployConfig = JSON.parse(
8410
+ fs2.readFileSync(deployConfigPath, "utf-8")
8411
+ );
8412
+ return [
8413
+ { configPath: deployConfig.configPath },
8414
+ ...deployConfig.auxiliaryWorkers
8415
+ ].map(({ configPath }) => {
8416
+ const resolvedConfigPath = path3.resolve(
8417
+ path3.dirname(deployConfigPath),
8418
+ configPath
8419
+ );
8420
+ return unstable_readConfig({ config: resolvedConfigPath });
8421
+ });
8422
+ }
8423
+ function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
8424
+ return path3.relative(
8425
+ deployConfigDirectory,
8426
+ path3.resolve(root, outputDirectory, "wrangler.json")
8427
+ );
8428
+ }
8429
+ function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
8430
+ const deployConfigPath = getDeployConfigPath(resolvedViteConfig.root);
8431
+ const deployConfigDirectory = path3.dirname(deployConfigPath);
8432
+ fs2.mkdirSync(deployConfigDirectory, { recursive: true });
8433
+ if (resolvedPluginConfig.type === "assets-only") {
8434
+ const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
8435
+ assert5(
8436
+ clientOutputDirectory,
8437
+ "Unexpected error: client environment output directory is undefined"
8438
+ );
8439
+ const deployConfig = {
8440
+ configPath: getRelativePathToWorkerConfig(
8441
+ deployConfigDirectory,
8442
+ resolvedViteConfig.root,
8443
+ clientOutputDirectory
8444
+ ),
8445
+ auxiliaryWorkers: []
8446
+ };
8447
+ fs2.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
8576
8448
  } else {
8577
- try {
8578
- resolved = new URL$1(specifier);
8579
- } catch (error_) {
8580
- if (isRemote && !builtinModules2.includes(specifier)) {
8581
- const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8582
- error.cause = error_;
8583
- throw error;
8449
+ let entryWorkerConfigPath;
8450
+ const auxiliaryWorkers = [];
8451
+ for (const environmentName of Object.keys(resolvedPluginConfig.workers)) {
8452
+ const outputDirectory = resolvedViteConfig.environments[environmentName]?.build.outDir;
8453
+ assert5(
8454
+ outputDirectory,
8455
+ `Unexpected error: ${environmentName} environment output directory is undefined`
8456
+ );
8457
+ const configPath = getRelativePathToWorkerConfig(
8458
+ deployConfigDirectory,
8459
+ resolvedViteConfig.root,
8460
+ outputDirectory
8461
+ );
8462
+ if (environmentName === resolvedPluginConfig.entryWorkerEnvironmentName) {
8463
+ entryWorkerConfigPath = configPath;
8464
+ } else {
8465
+ auxiliaryWorkers.push({ configPath });
8584
8466
  }
8585
- resolved = packageResolve(specifier, base, conditions);
8586
8467
  }
8468
+ assert5(
8469
+ entryWorkerConfigPath,
8470
+ `Unexpected error: entryWorkerConfigPath is undefined`
8471
+ );
8472
+ const deployConfig = {
8473
+ configPath: entryWorkerConfigPath,
8474
+ auxiliaryWorkers
8475
+ };
8476
+ fs2.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
8587
8477
  }
8588
- assert5(resolved !== void 0, "expected to be defined");
8589
- if (resolved.protocol !== "file:") {
8590
- return resolved;
8591
- }
8592
- return finalizeResolution(resolved, base);
8593
8478
  }
8594
- function fileURLToPath2(id) {
8595
- if (typeof id === "string" && !id.startsWith("file://")) {
8596
- return normalizeSlash(id);
8479
+
8480
+ // src/miniflare-options.ts
8481
+ import assert6 from "node:assert";
8482
+ import * as fs3 from "node:fs";
8483
+ import * as fsp from "node:fs/promises";
8484
+ import * as path4 from "node:path";
8485
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
8486
+ import {
8487
+ kCurrentWorker,
8488
+ Log,
8489
+ LogLevel,
8490
+ Response as MiniflareResponse
8491
+ } from "miniflare";
8492
+ import { globSync } from "tinyglobby";
8493
+ import "vite";
8494
+ import {
8495
+ unstable_getMiniflareWorkerOptions
8496
+ } from "wrangler";
8497
+ function getPersistence(root, persistState) {
8498
+ if (persistState === false) {
8499
+ return {};
8597
8500
  }
8598
- return normalizeSlash(fileURLToPath$1(id));
8599
- }
8600
- function pathToFileURL(id) {
8601
- return pathToFileURL$1(fileURLToPath2(id)).toString();
8501
+ const defaultPersistPath = ".wrangler/state";
8502
+ const persistPath = path4.resolve(
8503
+ root,
8504
+ typeof persistState === "object" ? persistState.path : defaultPersistPath,
8505
+ "v3"
8506
+ );
8507
+ return {
8508
+ cachePersist: path4.join(persistPath, "cache"),
8509
+ d1Persist: path4.join(persistPath, "d1"),
8510
+ durableObjectsPersist: path4.join(persistPath, "do"),
8511
+ kvPersist: path4.join(persistPath, "kv"),
8512
+ r2Persist: path4.join(persistPath, "r2"),
8513
+ workflowsPersist: path4.join(persistPath, "workflows")
8514
+ };
8602
8515
  }
8603
- function normalizeid(id) {
8604
- if (typeof id !== "string") {
8605
- id = id.toString();
8606
- }
8607
- if (/(node|data|http|https|file):/.test(id)) {
8608
- return id;
8609
- }
8610
- if (BUILTIN_MODULES.has(id)) {
8611
- return "node:" + id;
8612
- }
8613
- return "file://" + encodeURI(normalizeSlash(id));
8516
+ function missingWorkerErrorMessage(workerName) {
8517
+ return `${workerName} does not match a worker name.`;
8614
8518
  }
8615
- var DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
8616
- var DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
8617
- var NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
8618
- "ERR_MODULE_NOT_FOUND",
8619
- "ERR_UNSUPPORTED_DIR_IMPORT",
8620
- "MODULE_NOT_FOUND",
8621
- "ERR_PACKAGE_PATH_NOT_EXPORTED"
8622
- ]);
8623
- function _tryModuleResolve(id, url, conditions) {
8624
- try {
8625
- return moduleResolve(id, url, conditions);
8626
- } catch (error) {
8627
- if (!NOT_FOUND_ERRORS.has(error?.code)) {
8628
- throw error;
8519
+ function getWorkerToWorkerEntrypointNamesMap(workers) {
8520
+ const workerToWorkerEntrypointNamesMap = new Map(
8521
+ workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
8522
+ );
8523
+ for (const worker of workers) {
8524
+ for (const value of Object.values(worker.serviceBindings ?? {})) {
8525
+ if (typeof value === "object" && "name" in value && value.entrypoint !== void 0 && value.entrypoint !== "default") {
8526
+ const targetWorkerName = value.name === kCurrentWorker ? worker.name : value.name;
8527
+ const entrypointNames = workerToWorkerEntrypointNamesMap.get(targetWorkerName);
8528
+ assert6(entrypointNames, missingWorkerErrorMessage(targetWorkerName));
8529
+ entrypointNames.add(value.entrypoint);
8530
+ }
8629
8531
  }
8630
8532
  }
8533
+ return workerToWorkerEntrypointNamesMap;
8631
8534
  }
8632
- function _resolve(id, options = {}) {
8633
- if (typeof id !== "string") {
8634
- if (id instanceof URL) {
8635
- id = fileURLToPath2(id);
8636
- } else {
8637
- throw new TypeError("input must be a `string` or `URL`");
8535
+ function getWorkerToDurableObjectClassNamesMap(workers) {
8536
+ const workerToDurableObjectClassNamesMap = new Map(
8537
+ workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
8538
+ );
8539
+ for (const worker of workers) {
8540
+ for (const value of Object.values(worker.durableObjects ?? {})) {
8541
+ if (typeof value === "string") {
8542
+ const classNames = workerToDurableObjectClassNamesMap.get(worker.name);
8543
+ assert6(classNames, missingWorkerErrorMessage(worker.name));
8544
+ classNames.add(value);
8545
+ } else if (typeof value === "object") {
8546
+ if (value.scriptName) {
8547
+ const classNames = workerToDurableObjectClassNamesMap.get(
8548
+ value.scriptName
8549
+ );
8550
+ assert6(classNames, missingWorkerErrorMessage(value.scriptName));
8551
+ classNames.add(value.className);
8552
+ } else {
8553
+ const classNames = workerToDurableObjectClassNamesMap.get(
8554
+ worker.name
8555
+ );
8556
+ assert6(classNames, missingWorkerErrorMessage(worker.name));
8557
+ classNames.add(value.className);
8558
+ }
8559
+ }
8638
8560
  }
8639
8561
  }
8640
- if (/(node|data|http|https):/.test(id)) {
8641
- return id;
8642
- }
8643
- if (BUILTIN_MODULES.has(id)) {
8644
- return "node:" + id;
8562
+ return workerToDurableObjectClassNamesMap;
8563
+ }
8564
+ function getWorkerToWorkflowEntrypointClassNamesMap(workers) {
8565
+ const workerToWorkflowEntrypointClassNamesMap = new Map(
8566
+ workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
8567
+ );
8568
+ for (const worker of workers) {
8569
+ for (const value of Object.values(worker.workflows ?? {})) {
8570
+ if (value.scriptName) {
8571
+ const classNames = workerToWorkflowEntrypointClassNamesMap.get(
8572
+ value.scriptName
8573
+ );
8574
+ assert6(classNames, missingWorkerErrorMessage(value.scriptName));
8575
+ classNames.add(value.className);
8576
+ } else {
8577
+ const classNames = workerToWorkflowEntrypointClassNamesMap.get(
8578
+ worker.name
8579
+ );
8580
+ assert6(classNames, missingWorkerErrorMessage(worker.name));
8581
+ classNames.add(value.className);
8582
+ }
8583
+ }
8645
8584
  }
8646
- if (id.startsWith("file://")) {
8647
- id = fileURLToPath2(id);
8585
+ return workerToWorkflowEntrypointClassNamesMap;
8586
+ }
8587
+ var miniflareModulesRoot = process.platform === "win32" ? "Z:\\" : "/";
8588
+ var ROUTER_WORKER_PATH = "./asset-workers/router-worker.js";
8589
+ var ASSET_WORKER_PATH = "./asset-workers/asset-worker.js";
8590
+ var WRAPPER_PATH = "__VITE_WORKER_ENTRY__";
8591
+ var RUNNER_PATH = "./runner-worker/index.js";
8592
+ function getEntryWorkerConfig(resolvedPluginConfig) {
8593
+ if (resolvedPluginConfig.type === "assets-only") {
8594
+ return;
8648
8595
  }
8649
- if (isAbsolute(id)) {
8650
- try {
8651
- const stat = statSync2(id);
8652
- if (stat.isFile()) {
8653
- return pathToFileURL(id);
8596
+ return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
8597
+ }
8598
+ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
8599
+ const resolvedViteConfig = viteDevServer.config;
8600
+ const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
8601
+ const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
8602
+ const compatibilityOptions = resolvedPluginConfig.type === "assets-only" ? {
8603
+ compatibility_date: resolvedPluginConfig.config.compatibility_date,
8604
+ compatibility_flags: resolvedPluginConfig.config.compatibility_flags
8605
+ } : {
8606
+ ...entryWorkerConfig?.compatibility_date ? { compatibility_date: entryWorkerConfig?.compatibility_date } : {},
8607
+ ...entryWorkerConfig?.compatibility_flags ? { compatibility_flags: entryWorkerConfig?.compatibility_flags } : {}
8608
+ };
8609
+ const assetWorkers = [
8610
+ {
8611
+ name: ROUTER_WORKER_NAME,
8612
+ compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
8613
+ modulesRoot: miniflareModulesRoot,
8614
+ modules: [
8615
+ {
8616
+ type: "ESModule",
8617
+ path: path4.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
8618
+ contents: fs3.readFileSync(
8619
+ fileURLToPath2(new URL(ROUTER_WORKER_PATH, import.meta.url))
8620
+ )
8621
+ }
8622
+ ],
8623
+ bindings: {
8624
+ CONFIG: {
8625
+ has_user_worker: resolvedPluginConfig.type === "workers"
8626
+ }
8627
+ },
8628
+ serviceBindings: {
8629
+ ASSET_WORKER: ASSET_WORKER_NAME,
8630
+ ...entryWorkerConfig ? { USER_WORKER: entryWorkerConfig.name } : {}
8654
8631
  }
8655
- } catch (error) {
8656
- if (error?.code !== "ENOENT") {
8657
- throw error;
8632
+ },
8633
+ {
8634
+ name: ASSET_WORKER_NAME,
8635
+ compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
8636
+ modulesRoot: miniflareModulesRoot,
8637
+ modules: [
8638
+ {
8639
+ type: "ESModule",
8640
+ path: path4.join(miniflareModulesRoot, ASSET_WORKER_PATH),
8641
+ contents: fs3.readFileSync(
8642
+ fileURLToPath2(new URL(ASSET_WORKER_PATH, import.meta.url))
8643
+ )
8644
+ }
8645
+ ],
8646
+ bindings: {
8647
+ CONFIG: {
8648
+ ...compatibilityOptions,
8649
+ ...assetsConfig?.html_handling ? { html_handling: assetsConfig.html_handling } : {},
8650
+ ...assetsConfig?.not_found_handling ? { not_found_handling: assetsConfig.not_found_handling } : {}
8651
+ }
8652
+ },
8653
+ serviceBindings: {
8654
+ __VITE_ASSET_EXISTS__: async (request) => {
8655
+ const { pathname } = new URL(request.url);
8656
+ const filePath = path4.join(resolvedViteConfig.root, pathname);
8657
+ let exists;
8658
+ try {
8659
+ exists = fs3.statSync(filePath).isFile();
8660
+ } catch (error) {
8661
+ exists = false;
8662
+ }
8663
+ return MiniflareResponse.json(exists);
8664
+ },
8665
+ __VITE_FETCH_ASSET__: async (request) => {
8666
+ const { pathname } = new URL(request.url);
8667
+ const filePath = path4.join(resolvedViteConfig.root, pathname);
8668
+ try {
8669
+ let html = await fsp.readFile(filePath, "utf-8");
8670
+ html = await viteDevServer.transformIndexHtml(pathname, html);
8671
+ return new MiniflareResponse(html, {
8672
+ headers: { "Content-Type": "text/html" }
8673
+ });
8674
+ } catch (error) {
8675
+ throw new Error(`Unexpected error. Failed to load ${pathname}`);
8676
+ }
8677
+ }
8658
8678
  }
8659
8679
  }
8660
- }
8661
- const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
8662
- const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString())));
8663
- if (_urls.length === 0) {
8664
- _urls.push(new URL(pathToFileURL(process.cwd())));
8665
- }
8666
- const urls = [..._urls];
8667
- for (const url of _urls) {
8668
- if (url.protocol === "file:") {
8669
- urls.push(
8670
- new URL("./", url),
8671
- // If url is directory
8672
- new URL(joinURL(url.pathname, "_index.js"), url),
8673
- // TODO: Remove in next major version?
8674
- new URL("node_modules", url)
8680
+ ];
8681
+ const workersFromConfig = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
8682
+ ([environmentName, workerConfig]) => {
8683
+ const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
8684
+ {
8685
+ ...workerConfig,
8686
+ assets: void 0
8687
+ },
8688
+ resolvedPluginConfig.cloudflareEnv
8675
8689
  );
8690
+ const { externalWorkers: externalWorkers2 } = miniflareWorkerOptions;
8691
+ const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
8692
+ return {
8693
+ externalWorkers: externalWorkers2,
8694
+ worker: {
8695
+ ...workerOptions,
8696
+ name: workerOptions.name ?? workerConfig.name,
8697
+ unsafeInspectorProxy: resolvedPluginConfig.inspectorPort !== false,
8698
+ modulesRoot: miniflareModulesRoot,
8699
+ unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
8700
+ serviceBindings: {
8701
+ ...workerOptions.serviceBindings,
8702
+ ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
8703
+ [workerConfig.assets.binding]: ASSET_WORKER_NAME
8704
+ } : {},
8705
+ __VITE_INVOKE_MODULE__: async (request) => {
8706
+ const payload = await request.json();
8707
+ const invokePayloadData = payload.data;
8708
+ assert6(
8709
+ invokePayloadData.name === "fetchModule",
8710
+ `Invalid invoke event: ${invokePayloadData.name}`
8711
+ );
8712
+ const [moduleId] = invokePayloadData.data;
8713
+ if (additionalModuleRE.test(moduleId)) {
8714
+ const result2 = {
8715
+ externalize: moduleId,
8716
+ type: "module"
8717
+ };
8718
+ return MiniflareResponse.json({ result: result2 });
8719
+ }
8720
+ const devEnvironment = viteDevServer.environments[environmentName];
8721
+ const result = await devEnvironment.hot.handleInvoke(payload);
8722
+ return MiniflareResponse.json(result);
8723
+ }
8724
+ }
8725
+ }
8726
+ };
8676
8727
  }
8677
- }
8678
- let resolved;
8679
- for (const url of urls) {
8680
- resolved = _tryModuleResolve(id, url, conditionsSet);
8681
- if (resolved) {
8682
- break;
8683
- }
8684
- for (const prefix of ["", "/index"]) {
8685
- for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
8686
- resolved = _tryModuleResolve(
8687
- joinURL(id, prefix) + extension,
8688
- url,
8689
- conditionsSet
8728
+ ) : [];
8729
+ const userWorkers = workersFromConfig.map((options) => options.worker);
8730
+ const externalWorkers = workersFromConfig.flatMap(
8731
+ (options) => options.externalWorkers
8732
+ );
8733
+ const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
8734
+ const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
8735
+ const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
8736
+ const logger = new ViteMiniflareLogger(resolvedViteConfig);
8737
+ return {
8738
+ log: logger,
8739
+ inspectorPort: resolvedPluginConfig.inspectorPort || void 0,
8740
+ unsafeInspectorProxy: resolvedPluginConfig.inspectorPort !== false,
8741
+ handleRuntimeStdio(stdout, stderr) {
8742
+ const decoder = new TextDecoder();
8743
+ stdout.forEach((data2) => logger.info(decoder.decode(data2)));
8744
+ stderr.forEach(
8745
+ (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
8746
+ );
8747
+ },
8748
+ ...getPersistence(
8749
+ resolvedViteConfig.root,
8750
+ resolvedPluginConfig.persistState
8751
+ ),
8752
+ workers: [
8753
+ ...assetWorkers,
8754
+ ...externalWorkers,
8755
+ ...userWorkers.map((workerOptions) => {
8756
+ const wrappers = [
8757
+ `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
8758
+ `export default createWorkerEntrypointWrapper('default');`
8759
+ ];
8760
+ const workerEntrypointNames = workerToWorkerEntrypointNamesMap.get(
8761
+ workerOptions.name
8762
+ );
8763
+ assert6(
8764
+ workerEntrypointNames,
8765
+ `WorkerEntrypoint names not found for worker ${workerOptions.name}`
8766
+ );
8767
+ for (const entrypointName of [...workerEntrypointNames].sort()) {
8768
+ wrappers.push(
8769
+ `export const ${entrypointName} = createWorkerEntrypointWrapper('${entrypointName}');`
8770
+ );
8771
+ }
8772
+ const durableObjectClassNames = workerToDurableObjectClassNamesMap.get(
8773
+ workerOptions.name
8774
+ );
8775
+ assert6(
8776
+ durableObjectClassNames,
8777
+ `DurableObject class names not found for worker ${workerOptions.name}`
8778
+ );
8779
+ for (const className of [...durableObjectClassNames].sort()) {
8780
+ wrappers.push(
8781
+ `export const ${className} = createDurableObjectWrapper('${className}');`
8782
+ );
8783
+ }
8784
+ const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
8785
+ assert6(
8786
+ workflowEntrypointClassNames,
8787
+ `WorkflowEntrypoint class names not found for worker: ${workerOptions.name}`
8788
+ );
8789
+ for (const className of [...workflowEntrypointClassNames].sort()) {
8790
+ wrappers.push(
8791
+ `export const ${className} = createWorkflowEntrypointWrapper('${className}');`
8792
+ );
8793
+ }
8794
+ return {
8795
+ ...workerOptions,
8796
+ modules: [
8797
+ {
8798
+ type: "ESModule",
8799
+ path: path4.join(miniflareModulesRoot, WRAPPER_PATH),
8800
+ contents: wrappers.join("\n")
8801
+ },
8802
+ {
8803
+ type: "ESModule",
8804
+ path: path4.join(miniflareModulesRoot, RUNNER_PATH),
8805
+ contents: fs3.readFileSync(
8806
+ fileURLToPath2(new URL(RUNNER_PATH, import.meta.url))
8807
+ )
8808
+ }
8809
+ ],
8810
+ unsafeUseModuleFallbackService: true
8811
+ };
8812
+ })
8813
+ ],
8814
+ async unsafeModuleFallbackService(request) {
8815
+ const url = new URL(request.url);
8816
+ const rawSpecifier = url.searchParams.get("rawSpecifier");
8817
+ assert6(
8818
+ rawSpecifier,
8819
+ `Unexpected error: no specifier in request to module fallback service.`
8820
+ );
8821
+ const match = additionalModuleRE.exec(rawSpecifier);
8822
+ assert6(match, `Unexpected error: no match for module: ${rawSpecifier}.`);
8823
+ const [full, moduleType, modulePath] = match;
8824
+ assert6(
8825
+ moduleType,
8826
+ `Unexpected error: module type not found in reference: ${full}.`
8827
+ );
8828
+ assert6(
8829
+ modulePath,
8830
+ `Unexpected error: module path not found in reference: ${full}.`
8831
+ );
8832
+ let contents;
8833
+ try {
8834
+ contents = await fsp.readFile(modulePath);
8835
+ } catch (error) {
8836
+ throw new Error(
8837
+ `Import "${modulePath}" not found. Does the file exist?`
8690
8838
  );
8691
- if (resolved) {
8692
- break;
8693
- }
8694
8839
  }
8695
- if (resolved) {
8696
- break;
8840
+ switch (moduleType) {
8841
+ case "CompiledWasm": {
8842
+ return MiniflareResponse.json({ wasm: Array.from(contents) });
8843
+ }
8844
+ case "Data": {
8845
+ return MiniflareResponse.json({ data: Array.from(contents) });
8846
+ }
8847
+ case "Text": {
8848
+ return MiniflareResponse.json({ text: contents.toString() });
8849
+ }
8850
+ default: {
8851
+ return MiniflareResponse.error();
8852
+ }
8697
8853
  }
8698
8854
  }
8699
- if (resolved) {
8700
- break;
8701
- }
8702
- }
8703
- if (!resolved) {
8704
- const error = new Error(
8705
- `Cannot find module ${id} imported from ${urls.join(", ")}`
8706
- );
8707
- error.code = "ERR_MODULE_NOT_FOUND";
8708
- throw error;
8709
- }
8710
- return pathToFileURL(resolved);
8711
- }
8712
- function resolveSync(id, options) {
8713
- return _resolve(id, options);
8714
- }
8715
- function resolvePathSync(id, options) {
8716
- return fileURLToPath2(resolveSync(id, options));
8717
- }
8718
-
8719
- // src/node-js-compat.ts
8720
- import { defineEnv } from "unenv";
8721
- var { env } = defineEnv({
8722
- nodeCompat: true,
8723
- presets: [cloudflare]
8724
- });
8725
- var CLOUDFLARE_VIRTUAL_PREFIX = "\0__CLOUDFLARE_NODEJS_COMPAT__";
8726
- function isNodeCompat(workerConfig) {
8727
- if (workerConfig === void 0) {
8728
- return false;
8729
- }
8730
- const nodeCompatMode = getNodeCompat(
8731
- workerConfig.compatibility_date,
8732
- workerConfig.compatibility_flags ?? []
8733
- ).mode;
8734
- if (nodeCompatMode === "v2") {
8735
- return true;
8736
- }
8737
- if (nodeCompatMode === "legacy") {
8738
- throw new Error(
8739
- "Unsupported Node.js compat mode (legacy). Remove the `node_compat` setting and add the `nodejs_compat` flag instead."
8740
- );
8741
- }
8742
- if (nodeCompatMode === "v1") {
8743
- throw new Error(
8744
- `Unsupported Node.js compat mode (v1). Only the v2 mode is supported, either change your compat date to "2024-09-23" or later, or set the "nodejs_compat_v2" compatibility flag`
8745
- );
8746
- }
8747
- return false;
8855
+ };
8748
8856
  }
8749
- function injectGlobalCode(id, code) {
8750
- const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
8751
- if (typeof globalInject === "string") {
8752
- const moduleSpecifier2 = globalInject;
8753
- return `import var_${globalName} from "${CLOUDFLARE_VIRTUAL_PREFIX}${moduleSpecifier2}";
8754
- globalThis.${globalName} = var_${globalName};
8755
- `;
8756
- }
8757
- const [moduleSpecifier, exportName] = globalInject;
8758
- return `import var_${globalName} from "${CLOUDFLARE_VIRTUAL_PREFIX}${moduleSpecifier}";
8759
- globalThis.${globalName} = var_${globalName}.${exportName};
8760
- `;
8761
- }).join("\n");
8762
- const modified = new MagicString(code);
8763
- modified.prepend(injectedCode);
8857
+ function getPreviewModules(main, modulesRules) {
8858
+ assert6(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
8859
+ const rootPath = path4.dirname(main);
8860
+ const entryPath = path4.basename(main);
8764
8861
  return {
8765
- code: modified.toString(),
8766
- map: modified.generateMap({ hires: "boundary", source: id })
8862
+ rootPath,
8863
+ modules: [
8864
+ {
8865
+ type: "ESModule",
8866
+ path: entryPath
8867
+ },
8868
+ ...modulesRules.flatMap(
8869
+ ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path8) => ({
8870
+ type,
8871
+ path: path8
8872
+ }))
8873
+ )
8874
+ ]
8767
8875
  };
8768
8876
  }
8769
- function getNodeCompatAliases() {
8770
- const aliases = {};
8771
- Object.keys(env.alias).forEach((key) => {
8772
- if (!env.external.includes(key)) {
8773
- aliases[key] = CLOUDFLARE_VIRTUAL_PREFIX + key;
8774
- }
8775
- });
8776
- return aliases;
8777
- }
8778
- function getNodeCompatExternals() {
8779
- return env.external;
8780
- }
8781
- function maybeStripNodeJsVirtualPrefix(source) {
8782
- return source.startsWith(CLOUDFLARE_VIRTUAL_PREFIX) ? source.slice(CLOUDFLARE_VIRTUAL_PREFIX.length) : void 0;
8783
- }
8784
- function resolveNodeJSImport(source) {
8785
- const alias = env.alias[source];
8786
- if (alias) {
8787
- assert6(
8788
- !env.external.includes(alias),
8789
- `Unexpected unenv alias to external module: ${source} -> ${alias}`
8790
- );
8791
- source = alias;
8792
- }
8793
- const resolved = resolvePathSync(source, {
8794
- url: import.meta.url
8877
+ function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistState, inspectorPort = DEFAULT_INSPECTOR_PORT) {
8878
+ const resolvedViteConfig = vitePreviewServer.config;
8879
+ const workers = workerConfigs.flatMap((config) => {
8880
+ const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
8881
+ const { externalWorkers } = miniflareWorkerOptions;
8882
+ const { ratelimits, modulesRules, ...workerOptions } = miniflareWorkerOptions.workerOptions;
8883
+ return [
8884
+ {
8885
+ ...workerOptions,
8886
+ name: workerOptions.name ?? config.name,
8887
+ unsafeInspectorProxy: inspectorPort !== false,
8888
+ ...miniflareWorkerOptions.main ? getPreviewModules(miniflareWorkerOptions.main, modulesRules) : { modules: true, script: "" }
8889
+ },
8890
+ ...externalWorkers
8891
+ ];
8795
8892
  });
8893
+ const logger = new ViteMiniflareLogger(resolvedViteConfig);
8796
8894
  return {
8797
- unresolved: source,
8798
- resolved
8895
+ log: logger,
8896
+ inspectorPort: inspectorPort || void 0,
8897
+ unsafeInspectorProxy: inspectorPort !== false,
8898
+ handleRuntimeStdio(stdout, stderr) {
8899
+ const decoder = new TextDecoder();
8900
+ stdout.forEach((data2) => logger.info(decoder.decode(data2)));
8901
+ stderr.forEach(
8902
+ (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
8903
+ );
8904
+ },
8905
+ ...getPersistence(resolvedViteConfig.root, persistState),
8906
+ workers
8799
8907
  };
8800
8908
  }
8909
+ var ViteMiniflareLogger = class extends Log {
8910
+ logger;
8911
+ constructor(config) {
8912
+ super(miniflareLogLevelFromViteLogLevel(config.logLevel));
8913
+ this.logger = config.logger;
8914
+ }
8915
+ logWithLevel(level, message) {
8916
+ if (/^Ready on http/.test(message)) {
8917
+ level = LogLevel.DEBUG;
8918
+ }
8919
+ switch (level) {
8920
+ case LogLevel.ERROR:
8921
+ return this.logger.error(message);
8922
+ case LogLevel.WARN:
8923
+ return this.logger.warn(message);
8924
+ case LogLevel.INFO:
8925
+ return this.logger.info(message);
8926
+ }
8927
+ }
8928
+ };
8929
+ function miniflareLogLevelFromViteLogLevel(level = "info") {
8930
+ switch (level) {
8931
+ case "error":
8932
+ return LogLevel.ERROR;
8933
+ case "warn":
8934
+ return LogLevel.WARN;
8935
+ case "info":
8936
+ return LogLevel.INFO;
8937
+ case "silent":
8938
+ return LogLevel.NONE;
8939
+ }
8940
+ }
8801
8941
 
8802
8942
  // src/plugin-config.ts
8803
- import assert8 from "node:assert";
8943
+ import assert7 from "node:assert";
8804
8944
  import * as path6 from "node:path";
8805
8945
  import * as vite5 from "vite";
8806
8946
 
8807
8947
  // src/workers-configs.ts
8808
- import assert7 from "node:assert";
8809
8948
  import * as fs4 from "node:fs";
8810
8949
  import * as path5 from "node:path";
8811
- import { unstable_readConfig as unstable_readConfig2 } from "wrangler";
8812
-
8813
- // package.json
8814
- var name = "@cloudflare/vite-plugin";
8815
-
8816
- // src/workers-configs.ts
8950
+ import { unstable_readConfig as unstable_readConfig3 } from "wrangler";
8817
8951
  var nonApplicableWorkerConfigs = {
8818
8952
  /**
8819
8953
  * Object containing configs that have a vite replacement, the object's field contain details about the config's replacement
@@ -8841,16 +8975,12 @@ var nonApplicableWorkerConfigs = {
8841
8975
  "build",
8842
8976
  "find_additional_modules",
8843
8977
  "no_bundle",
8844
- "node_compat",
8845
8978
  "preserve_file_names",
8979
+ "rules",
8846
8980
  "site",
8847
8981
  "tsconfig",
8848
8982
  "upload_source_maps"
8849
- ],
8850
- /**
8851
- * All the configs that get overridden by our plugin
8852
- */
8853
- overridden: ["rules"]
8983
+ ]
8854
8984
  };
8855
8985
  var nullableNonApplicable = [
8856
8986
  "alias",
@@ -8858,7 +8988,6 @@ var nullableNonApplicable = [
8858
8988
  "find_additional_modules",
8859
8989
  "minify",
8860
8990
  "no_bundle",
8861
- "node_compat",
8862
8991
  "preserve_file_names",
8863
8992
  "site",
8864
8993
  "tsconfig",
@@ -8867,10 +8996,9 @@ var nullableNonApplicable = [
8867
8996
  function readWorkerConfig(configPath, env2) {
8868
8997
  const nonApplicable = {
8869
8998
  replacedByVite: /* @__PURE__ */ new Set(),
8870
- notRelevant: /* @__PURE__ */ new Set(),
8871
- overridden: /* @__PURE__ */ new Set()
8999
+ notRelevant: /* @__PURE__ */ new Set()
8872
9000
  };
8873
- const config = unstable_readConfig2({ config: configPath, env: env2 }, {});
9001
+ const config = unstable_readConfig3({ config: configPath, env: env2 }, {});
8874
9002
  const raw = structuredClone(config);
8875
9003
  nullableNonApplicable.forEach((prop) => {
8876
9004
  if (config[prop] !== void 0) {
@@ -8880,9 +9008,6 @@ function readWorkerConfig(configPath, env2) {
8880
9008
  if (isNotRelevant(prop)) {
8881
9009
  nonApplicable.notRelevant.add(prop);
8882
9010
  }
8883
- if (isOverridden(prop)) {
8884
- nonApplicable.overridden.add(prop);
8885
- }
8886
9011
  }
8887
9012
  delete config[prop];
8888
9013
  });
@@ -8895,7 +9020,7 @@ function readWorkerConfig(configPath, env2) {
8895
9020
  }
8896
9021
  delete config["define"];
8897
9022
  if (config.rules.length > 0) {
8898
- nonApplicable.overridden.add("rules");
9023
+ nonApplicable.notRelevant.add("rules");
8899
9024
  }
8900
9025
  return {
8901
9026
  raw,
@@ -8947,7 +9072,7 @@ function getWarningForWorkersConfigs(configs) {
8947
9072
  }
8948
9073
  function getWorkerNonApplicableWarnLines(workerConfig, linePrefix) {
8949
9074
  const lines = [];
8950
- const { replacedByVite, notRelevant, overridden } = workerConfig.nonApplicable;
9075
+ const { replacedByVite, notRelevant } = workerConfig.nonApplicable;
8951
9076
  for (const config of replacedByVite) {
8952
9077
  lines.push(
8953
9078
  `${linePrefix}\`${config}\` which is replaced by Vite's \`${nonApplicableWorkerConfigs.replacedByVite[config].viteReplacement}\` (docs: ${nonApplicableWorkerConfigs.replacedByVite[config].viteDocs})`
@@ -8957,10 +9082,6 @@ function getWorkerNonApplicableWarnLines(workerConfig, linePrefix) {
8957
9082
  lines.push(
8958
9083
  `${linePrefix}${[...notRelevant].map((config) => `\`${config}\``).join(", ")} which ${notRelevant.size > 1 ? "are" : "is"} not relevant in the context of a Vite project`
8959
9084
  );
8960
- if (overridden.size > 0)
8961
- lines.push(
8962
- `${linePrefix}${[...overridden].map((config) => `\`${config}\``).join(", ")} which ${overridden.size > 1 ? "are" : "is"} overridden by \`${name}\``
8963
- );
8964
9085
  return lines;
8965
9086
  }
8966
9087
  function isReplacedByVite(configName) {
@@ -8969,9 +9090,6 @@ function isReplacedByVite(configName) {
8969
9090
  function isNotRelevant(configName) {
8970
9091
  return nonApplicableWorkerConfigs.notRelevant.includes(configName);
8971
9092
  }
8972
- function isOverridden(configName) {
8973
- return nonApplicableWorkerConfigs.overridden.includes(configName);
8974
- }
8975
9093
  function missingFieldErrorMessage(field, configPath, env2) {
8976
9094
  return `No ${field} field provided in '${configPath}'${env2 ? ` for '${env2}' environment` : ""}`;
8977
9095
  }
@@ -8981,42 +9099,55 @@ function getWorkerConfig(configPath, env2, opts) {
8981
9099
  }
8982
9100
  const { raw, config, nonApplicable } = readWorkerConfig(configPath, env2);
8983
9101
  opts?.visitedConfigPaths?.add(configPath);
8984
- assert7(
8985
- config.topLevelName,
8986
- missingFieldErrorMessage(`top-level 'name'`, configPath, env2)
8987
- );
8988
- assert7(config.name, missingFieldErrorMessage(`'name'`, configPath, env2));
8989
- assert7(
8990
- config.compatibility_date,
8991
- missingFieldErrorMessage(`'compatibility_date'`, configPath, env2)
8992
- );
8993
- if (opts?.isEntryWorker && !config.main) {
8994
- assert7(
8995
- config.assets,
8996
- missingFieldErrorMessage(`'main' or 'assets'`, configPath, env2)
9102
+ if (!config.name) {
9103
+ throw new Error(missingFieldErrorMessage(`'name'`, configPath, env2));
9104
+ }
9105
+ if (!config.topLevelName) {
9106
+ throw new Error(
9107
+ missingFieldErrorMessage(`top-level 'name'`, configPath, env2)
8997
9108
  );
9109
+ }
9110
+ if (!config.compatibility_date) {
9111
+ throw new Error(
9112
+ missingFieldErrorMessage(`'compatibility_date`, configPath, env2)
9113
+ );
9114
+ }
9115
+ const requiredFields = {
9116
+ topLevelName: config.topLevelName,
9117
+ name: config.name,
9118
+ compatibility_date: config.compatibility_date
9119
+ };
9120
+ if (opts?.isEntryWorker && !config.main) {
8998
9121
  return {
8999
9122
  type: "assets-only",
9000
9123
  raw,
9001
9124
  config: {
9002
9125
  ...config,
9003
- topLevelName: config.topLevelName,
9004
- name: config.name,
9005
- compatibility_date: config.compatibility_date,
9006
- assets: config.assets
9126
+ ...requiredFields
9007
9127
  },
9008
9128
  nonApplicable
9009
9129
  };
9010
9130
  }
9011
- assert7(config.main, missingFieldErrorMessage(`'main'`, configPath, env2));
9131
+ if (!config.main) {
9132
+ throw new Error(missingFieldErrorMessage(`'main'`, configPath, env2));
9133
+ }
9134
+ const mainStat = fs4.statSync(config.main, { throwIfNoEntry: false });
9135
+ if (!mainStat) {
9136
+ throw new Error(
9137
+ `The provided Wrangler config main field (${config.main}) doesn't point to an existing file`
9138
+ );
9139
+ }
9140
+ if (mainStat.isDirectory()) {
9141
+ throw new Error(
9142
+ `The provided Wrangler config main field (${config.main}) points to a directory, it needs to point to a file instead`
9143
+ );
9144
+ }
9012
9145
  return {
9013
9146
  type: "worker",
9014
9147
  raw,
9015
9148
  config: {
9016
9149
  ...config,
9017
- topLevelName: config.topLevelName,
9018
- name: config.name,
9019
- compatibility_date: config.compatibility_date,
9150
+ ...requiredFields,
9020
9151
  main: config.main
9021
9152
  },
9022
9153
  nonApplicable
@@ -9038,6 +9169,7 @@ function workerNameToEnvironmentName(workerName) {
9038
9169
  function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9039
9170
  const configPaths = /* @__PURE__ */ new Set();
9040
9171
  const persistState = pluginConfig.persistState ?? true;
9172
+ const inspectorPort = pluginConfig.inspectorPort ?? DEFAULT_INSPECTOR_PORT;
9041
9173
  const root = userConfig.root ? path6.resolve(userConfig.root) : process.cwd();
9042
9174
  const { CLOUDFLARE_ENV: cloudflareEnv } = vite5.loadEnv(
9043
9175
  viteEnv.mode,
@@ -9046,10 +9178,11 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9046
9178
  ""
9047
9179
  );
9048
9180
  const configPath = pluginConfig.configPath ? path6.resolve(root, pluginConfig.configPath) : findWranglerConfig(root);
9049
- assert8(
9050
- configPath,
9051
- `Config not found. Have you created a wrangler.json(c) or wrangler.toml file?`
9052
- );
9181
+ if (!configPath) {
9182
+ throw new Error(
9183
+ `Config not found. Have you created a wrangler.json(c) or wrangler.toml file?`
9184
+ );
9185
+ }
9053
9186
  const entryWorkerResolvedConfig = getWorkerConfig(configPath, cloudflareEnv, {
9054
9187
  visitedConfigPaths: configPaths,
9055
9188
  isEntryWorker: true
@@ -9059,6 +9192,7 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9059
9192
  type: "assets-only",
9060
9193
  config: entryWorkerResolvedConfig.config,
9061
9194
  configPaths,
9195
+ inspectorPort,
9062
9196
  persistState,
9063
9197
  rawConfigs: {
9064
9198
  entryWorker: entryWorkerResolvedConfig
@@ -9081,7 +9215,7 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9081
9215
  }
9082
9216
  );
9083
9217
  auxiliaryWorkersResolvedConfigs.push(workerResolvedConfig);
9084
- assert8(
9218
+ assert7(
9085
9219
  workerResolvedConfig.type === "worker",
9086
9220
  "Unexpected error: received AssetsOnlyResult with auxiliary workers."
9087
9221
  );
@@ -9098,6 +9232,7 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9098
9232
  type: "workers",
9099
9233
  configPaths,
9100
9234
  persistState,
9235
+ inspectorPort,
9101
9236
  workers,
9102
9237
  entryWorkerEnvironmentName,
9103
9238
  rawConfigs: {
@@ -9109,9 +9244,10 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9109
9244
  }
9110
9245
 
9111
9246
  // src/websockets.ts
9112
- import ws from "ws";
9113
- function handleWebSocket(httpServer, fetcher, logger) {
9114
- const nodeWebSocket = new ws.Server({ noServer: true });
9247
+ import { coupleWebSocket } from "miniflare";
9248
+ import { WebSocketServer } from "ws";
9249
+ function handleWebSocket(httpServer, fetcher) {
9250
+ const nodeWebSocket = new WebSocketServer({ noServer: true });
9115
9251
  httpServer.on(
9116
9252
  "upgrade",
9117
9253
  async (request, socket, head) => {
@@ -9134,34 +9270,7 @@ function handleWebSocket(httpServer, fetcher, logger) {
9134
9270
  socket,
9135
9271
  head,
9136
9272
  async (clientWebSocket) => {
9137
- workerWebSocket.accept();
9138
- workerWebSocket.addEventListener("message", (event) => {
9139
- clientWebSocket.send(event.data);
9140
- });
9141
- workerWebSocket.addEventListener("error", (event) => {
9142
- logger.error(
9143
- `WebSocket error:
9144
- ${event.error?.stack || event.error?.message}`,
9145
- { error: event.error }
9146
- );
9147
- });
9148
- workerWebSocket.addEventListener("close", () => {
9149
- clientWebSocket.close();
9150
- });
9151
- clientWebSocket.on("message", (data2, isBinary) => {
9152
- workerWebSocket.send(
9153
- isBinary ? Array.isArray(data2) ? Buffer.concat(data2) : data2 : data2.toString()
9154
- );
9155
- });
9156
- clientWebSocket.on("error", (error) => {
9157
- logger.error(`WebSocket error:
9158
- ${error.stack || error.message}`, {
9159
- error
9160
- });
9161
- });
9162
- clientWebSocket.on("close", () => {
9163
- workerWebSocket.close();
9164
- });
9273
+ coupleWebSocket(clientWebSocket, workerWebSocket);
9165
9274
  nodeWebSocket.emit("connection", clientWebSocket, request);
9166
9275
  }
9167
9276
  );
@@ -9170,14 +9279,18 @@ ${error.stack || error.message}`, {
9170
9279
  }
9171
9280
 
9172
9281
  // src/index.ts
9282
+ var workersConfigsWarningShown = false;
9173
9283
  function cloudflare2(pluginConfig = {}) {
9174
9284
  let resolvedPluginConfig;
9175
9285
  let resolvedViteConfig;
9176
9286
  let miniflare;
9177
- let workersConfigsWarningShown = false;
9287
+ const additionalModulePaths = /* @__PURE__ */ new Set();
9288
+ let hasClientBuild = false;
9178
9289
  return [
9179
9290
  {
9180
9291
  name: "vite-plugin-cloudflare",
9292
+ // This only applies to this plugin so is safe to use while other plugins migrate to the Environment API
9293
+ sharedDuringBuild: true,
9181
9294
  config(userConfig, env2) {
9182
9295
  if (env2.isPreview) {
9183
9296
  return { appType: "custom" };
@@ -9220,7 +9333,7 @@ function cloudflare2(pluginConfig = {}) {
9220
9333
  }
9221
9334
  } : void 0,
9222
9335
  builder: {
9223
- async buildApp(builder) {
9336
+ buildApp: userConfig.builder?.buildApp ?? (async (builder) => {
9224
9337
  const clientEnvironment = builder.environments.client;
9225
9338
  const defaultHtmlPath = path7.resolve(
9226
9339
  builder.config.root,
@@ -9234,7 +9347,7 @@ function cloudflare2(pluginConfig = {}) {
9234
9347
  resolvedPluginConfig.workers
9235
9348
  ).map((environmentName) => {
9236
9349
  const environment = builder.environments[environmentName];
9237
- assert9(
9350
+ assert8(
9238
9351
  environment,
9239
9352
  `${environmentName} environment not found`
9240
9353
  );
@@ -9246,10 +9359,13 @@ function cloudflare2(pluginConfig = {}) {
9246
9359
  )
9247
9360
  );
9248
9361
  }
9249
- }
9362
+ })
9250
9363
  }
9251
9364
  };
9252
9365
  },
9366
+ buildStart() {
9367
+ workersConfigsWarningShown = false;
9368
+ },
9253
9369
  configResolved(config) {
9254
9370
  resolvedViteConfig = config;
9255
9371
  },
@@ -9264,18 +9380,27 @@ function cloudflare2(pluginConfig = {}) {
9264
9380
  return;
9265
9381
  }
9266
9382
  workerConfig.main = entryChunk[0];
9383
+ workerConfig.no_bundle = true;
9384
+ workerConfig.rules = [
9385
+ { type: "ESModule", globs: ["**/*.js", "**/*.mjs"] }
9386
+ ];
9267
9387
  const isEntryWorker = this.environment.name === resolvedPluginConfig.entryWorkerEnvironmentName;
9268
- if (isEntryWorker && workerConfig.assets) {
9388
+ if (isEntryWorker && hasClientBuild) {
9269
9389
  const workerOutputDirectory = this.environment.config.build.outDir;
9270
9390
  const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
9271
- assert9(
9391
+ assert8(
9272
9392
  clientOutputDirectory,
9273
9393
  "Unexpected error: client output directory is undefined"
9274
9394
  );
9275
- workerConfig.assets.directory = path7.relative(
9276
- path7.resolve(resolvedViteConfig.root, workerOutputDirectory),
9277
- path7.resolve(resolvedViteConfig.root, clientOutputDirectory)
9278
- );
9395
+ workerConfig.assets = {
9396
+ ...workerConfig.assets,
9397
+ directory: path7.relative(
9398
+ path7.resolve(resolvedViteConfig.root, workerOutputDirectory),
9399
+ path7.resolve(resolvedViteConfig.root, clientOutputDirectory)
9400
+ )
9401
+ };
9402
+ } else {
9403
+ workerConfig.assets = void 0;
9279
9404
  }
9280
9405
  config = workerConfig;
9281
9406
  if (workerConfig.configPath) {
@@ -9293,7 +9418,10 @@ function cloudflare2(pluginConfig = {}) {
9293
9418
  }
9294
9419
  } else if (this.environment.name === "client") {
9295
9420
  const assetsOnlyConfig = resolvedPluginConfig.config;
9296
- assetsOnlyConfig.assets.directory = ".";
9421
+ assetsOnlyConfig.assets = {
9422
+ ...assetsOnlyConfig.assets,
9423
+ directory: "."
9424
+ };
9297
9425
  const filesToAssetsIgnore = ["wrangler.json", ".dev.vars"];
9298
9426
  this.emitFile({
9299
9427
  type: "asset",
@@ -9306,8 +9434,6 @@ function cloudflare2(pluginConfig = {}) {
9306
9434
  if (!config) {
9307
9435
  return;
9308
9436
  }
9309
- config.no_bundle = true;
9310
- config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
9311
9437
  if (config.unsafe && Object.keys(config.unsafe).length === 0) {
9312
9438
  config.unsafe = void 0;
9313
9439
  }
@@ -9318,6 +9444,9 @@ function cloudflare2(pluginConfig = {}) {
9318
9444
  });
9319
9445
  },
9320
9446
  writeBundle() {
9447
+ if (this.environment.name === "client") {
9448
+ hasClientBuild = true;
9449
+ }
9321
9450
  if (this.environment.name === (resolvedPluginConfig.type === "assets-only" ? "client" : resolvedPluginConfig.entryWorkerEnvironmentName)) {
9322
9451
  writeDeployConfig(resolvedPluginConfig, resolvedViteConfig);
9323
9452
  }
@@ -9334,7 +9463,7 @@ function cloudflare2(pluginConfig = {}) {
9334
9463
  }
9335
9464
  },
9336
9465
  async configureServer(viteDevServer) {
9337
- assert9(
9466
+ assert8(
9338
9467
  viteDevServer.httpServer,
9339
9468
  "Unexpected error: No Vite HTTP server"
9340
9469
  );
@@ -9342,23 +9471,16 @@ function cloudflare2(pluginConfig = {}) {
9342
9471
  getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
9343
9472
  );
9344
9473
  await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
9345
- const entryWorker = await getDevEntryWorker(
9346
- resolvedPluginConfig,
9347
- miniflare
9348
- );
9474
+ const routerWorker = await getRouterWorker(miniflare);
9349
9475
  const middleware = createMiddleware(
9350
9476
  ({ request }) => {
9351
- return entryWorker.fetch(toMiniflareRequest(request), {
9477
+ return routerWorker.fetch(toMiniflareRequest(request), {
9352
9478
  redirect: "manual"
9353
9479
  });
9354
9480
  },
9355
9481
  { alwaysCallNext: false }
9356
9482
  );
9357
- handleWebSocket(
9358
- viteDevServer.httpServer,
9359
- entryWorker.fetch,
9360
- viteDevServer.config.logger
9361
- );
9483
+ handleWebSocket(viteDevServer.httpServer, routerWorker.fetch);
9362
9484
  return () => {
9363
9485
  viteDevServer.middlewares.use((req, res, next) => {
9364
9486
  middleware(req, res, next);
@@ -9366,10 +9488,13 @@ function cloudflare2(pluginConfig = {}) {
9366
9488
  };
9367
9489
  },
9368
9490
  configurePreviewServer(vitePreviewServer) {
9491
+ const workerConfigs = getWorkerConfigs(vitePreviewServer.config.root);
9369
9492
  const miniflare2 = new Miniflare(
9370
9493
  getPreviewMiniflareOptions(
9371
9494
  vitePreviewServer,
9372
- pluginConfig.persistState ?? true
9495
+ workerConfigs,
9496
+ pluginConfig.persistState ?? true,
9497
+ pluginConfig.inspectorPort
9373
9498
  )
9374
9499
  );
9375
9500
  const middleware = createMiddleware(
@@ -9380,58 +9505,80 @@ function cloudflare2(pluginConfig = {}) {
9380
9505
  },
9381
9506
  { alwaysCallNext: false }
9382
9507
  );
9383
- handleWebSocket(
9384
- vitePreviewServer.httpServer,
9385
- miniflare2.dispatchFetch,
9386
- vitePreviewServer.config.logger
9387
- );
9388
- return () => {
9389
- vitePreviewServer.middlewares.use((req, res, next) => {
9390
- middleware(req, res, next);
9391
- });
9392
- };
9508
+ handleWebSocket(vitePreviewServer.httpServer, miniflare2.dispatchFetch);
9509
+ vitePreviewServer.middlewares.use((req, res, next) => {
9510
+ middleware(req, res, next);
9511
+ });
9512
+ }
9513
+ },
9514
+ // Plugin to support `.wasm?init` extension
9515
+ {
9516
+ name: "vite-plugin-cloudflare:wasm-helper",
9517
+ enforce: "pre",
9518
+ applyToEnvironment(environment) {
9519
+ return getWorkerConfig2(environment.name) !== void 0;
9520
+ },
9521
+ load(id) {
9522
+ if (!id.endsWith(".wasm?init")) {
9523
+ return;
9524
+ }
9525
+ return `
9526
+ import wasm from "${cleanUrl(id)}";
9527
+ export default function(opts = {}) {
9528
+ return WebAssembly.instantiate(wasm, opts);
9529
+ }
9530
+ `;
9393
9531
  }
9394
9532
  },
9395
- // Plugin to support `CompiledWasm` modules
9533
+ // Plugin to support additional modules
9396
9534
  {
9397
- name: "vite-plugin-cloudflare:modules",
9535
+ name: "vite-plugin-cloudflare:additional-modules",
9398
9536
  // We set `enforce: "pre"` so that this plugin runs before the Vite core plugins.
9399
9537
  // Otherwise the `vite:wasm-fallback` plugin prevents the `.wasm` extension being used for module imports.
9400
9538
  enforce: "pre",
9401
9539
  applyToEnvironment(environment) {
9402
9540
  return getWorkerConfig2(environment.name) !== void 0;
9403
9541
  },
9404
- async resolveId(source, importer) {
9405
- if (!source.endsWith(".wasm")) {
9542
+ async resolveId(source, importer, options) {
9543
+ const additionalModuleType = matchAdditionalModule(source);
9544
+ if (!additionalModuleType) {
9406
9545
  return;
9407
9546
  }
9408
- const resolved = await this.resolve(source, importer);
9409
- assert9(
9410
- resolved,
9411
- `Unexpected error: could not resolve Wasm module ${source}`
9547
+ const resolved = await this.resolve(
9548
+ cleanUrl(source),
9549
+ importer,
9550
+ options
9412
9551
  );
9552
+ if (!resolved) {
9553
+ throw new Error(`Import "${source}" not found. Does the file exist?`);
9554
+ }
9555
+ additionalModulePaths.add(resolved.id);
9413
9556
  return {
9414
9557
  external: true,
9415
- id: createModuleReference("CompiledWasm", resolved.id)
9558
+ id: createModuleReference(additionalModuleType, resolved.id)
9416
9559
  };
9417
9560
  },
9418
- renderChunk(code, chunk) {
9419
- const moduleRE = new RegExp(MODULE_PATTERN, "g");
9420
- let match;
9561
+ hotUpdate(options) {
9562
+ if (additionalModulePaths.has(options.file)) {
9563
+ options.server.restart();
9564
+ }
9565
+ },
9566
+ async renderChunk(code, chunk) {
9567
+ const matches = code.matchAll(additionalModuleGlobalRE);
9421
9568
  let magicString;
9422
- while (match = moduleRE.exec(code)) {
9569
+ for (const match of matches) {
9423
9570
  magicString ??= new MagicString(code);
9424
- const [full, moduleType, modulePath] = match;
9425
- assert9(
9571
+ const [full, _, modulePath] = match;
9572
+ assert8(
9426
9573
  modulePath,
9427
9574
  `Unexpected error: module path not found in reference ${full}.`
9428
9575
  );
9429
9576
  let source;
9430
9577
  try {
9431
- source = fs5.readFileSync(modulePath);
9578
+ source = await fsp2.readFile(modulePath);
9432
9579
  } catch (error) {
9433
9580
  throw new Error(
9434
- `Import ${modulePath} not found. Does the file exist?`
9581
+ `Import "${modulePath}" not found. Does the file exist?`
9435
9582
  );
9436
9583
  }
9437
9584
  const referenceId = this.emitFile({
@@ -9465,58 +9612,117 @@ function cloudflare2(pluginConfig = {}) {
9465
9612
  apply(_config, env2) {
9466
9613
  return !env2.isPreview;
9467
9614
  },
9468
- config() {
9469
- return {
9470
- resolve: {
9471
- alias: getNodeCompatAliases()
9472
- }
9473
- };
9474
- },
9475
- configEnvironment(environmentName) {
9476
- const workerConfig = getWorkerConfig2(environmentName);
9477
- if (isNodeCompat(workerConfig)) {
9615
+ configEnvironment(name) {
9616
+ if (isNodeCompat(getWorkerConfig2(name))) {
9478
9617
  return {
9479
- build: {
9480
- rollupOptions: {
9481
- external: getNodeCompatExternals()
9482
- }
9618
+ resolve: {
9619
+ builtins: [...nodeCompatExternals]
9620
+ },
9621
+ optimizeDeps: {
9622
+ // This is a list of dependency entry-points that should be pre-bundled.
9623
+ // In this case we provide a list of all the possible polyfills so that they are pre-bundled,
9624
+ // ready ahead the first request to the dev server.
9625
+ // Without this the dependency optimizer will try to bundle them on-the-fly in the middle of the first request,
9626
+ // which can potentially cause problems if it leads to previous pre-bundling to become stale and needing to be reloaded.
9627
+ // TODO: work out how to re-enable pre-bundling of these
9628
+ // include: [...getNodeCompatEntries()],
9629
+ // This is a list of module specifiers that the dependency optimizer should not follow when doing import analysis.
9630
+ // In this case we provide a list of all the Node.js modules, both those built-in to workerd and those that will be polyfilled.
9631
+ // Obviously we don't want/need the optimizer to try to process modules that are built-in;
9632
+ // But also we want to avoid following the ones that are polyfilled since the dependency-optimizer import analyzer does not
9633
+ // resolve these imports using our `resolveId()` hook causing the optimization step to fail.
9634
+ exclude: [
9635
+ ...builtinModules2,
9636
+ ...builtinModules2.map((m) => `node:${m}`)
9637
+ ]
9483
9638
  }
9484
9639
  };
9485
9640
  }
9486
9641
  },
9642
+ applyToEnvironment(environment) {
9643
+ return isNodeCompat(getWorkerConfig2(environment.name));
9644
+ },
9645
+ // We need the resolver from this plugin to run before built-in ones, otherwise Vite's built-in
9646
+ // resolver will try to externalize the Node.js module imports (e.g. `perf_hooks` and `node:tty`)
9647
+ // rather than allowing the resolve hook here to alias then to polyfills.
9648
+ enforce: "pre",
9487
9649
  async resolveId(source, importer, options) {
9488
- const strippedSource = maybeStripNodeJsVirtualPrefix(source);
9489
- if (!strippedSource) {
9490
- return;
9491
- }
9492
- const workerConfig = getWorkerConfig2(this.environment.name);
9493
- if (!isNodeCompat(workerConfig)) {
9494
- return this.resolve(strippedSource, importer, options);
9650
+ const result = resolveNodeJSImport(source);
9651
+ if (!result) {
9652
+ return this.resolve(source, importer, options);
9495
9653
  }
9496
- const { unresolved, resolved } = resolveNodeJSImport(strippedSource);
9497
- if (this.environment.mode === "dev" && this.environment.depsOptimizer) {
9498
- const optimized = this.environment.depsOptimizer.registerMissingImport(
9499
- unresolved,
9500
- resolved
9501
- ).id;
9502
- return this.resolve(optimized, importer, options);
9654
+ if (this.environment.mode === "dev") {
9655
+ assert8(
9656
+ this.environment.depsOptimizer,
9657
+ "depsOptimizer is required in dev mode"
9658
+ );
9659
+ const { id } = this.environment.depsOptimizer.registerMissingImport(
9660
+ result.unresolved,
9661
+ result.resolved
9662
+ );
9663
+ return this.resolve(id, importer, options);
9503
9664
  }
9504
- return this.resolve(resolved, importer, options);
9665
+ return this.resolve(result.resolved, importer, options);
9505
9666
  },
9506
9667
  async transform(code, id) {
9507
9668
  const workerConfig = getWorkerConfig2(this.environment.name);
9508
- if (!isNodeCompat(workerConfig)) {
9509
- return;
9510
- }
9669
+ assert8(workerConfig, "Expected a worker config");
9511
9670
  const resolvedId = await this.resolve(workerConfig.main);
9512
9671
  if (id === resolvedId?.id) {
9513
9672
  return injectGlobalCode(id, code);
9514
9673
  }
9515
9674
  }
9675
+ },
9676
+ // Plugin that provides an __debug path for debugging the Cloudflare Workers.
9677
+ {
9678
+ name: "vite-plugin-cloudflare:debug",
9679
+ // Note: this plugin needs to run before the main vite-plugin-cloudflare so that
9680
+ // the preview middleware here can take precedence
9681
+ enforce: "pre",
9682
+ configureServer(viteDevServer) {
9683
+ if (resolvedPluginConfig.type === "workers" && resolvedPluginConfig.inspectorPort !== false) {
9684
+ addDebugToVitePrintUrls(viteDevServer);
9685
+ }
9686
+ const workerNames = resolvedPluginConfig.type === "assets-only" ? [] : Object.values(resolvedPluginConfig.workers).map(
9687
+ (worker) => worker.name
9688
+ );
9689
+ viteDevServer.middlewares.use((req, res, next) => {
9690
+ if (req.url === debuggingPath && resolvedPluginConfig.inspectorPort !== false) {
9691
+ const html = getDebugPathHtml(
9692
+ workerNames,
9693
+ resolvedPluginConfig.inspectorPort
9694
+ );
9695
+ res.setHeader("Content-Type", "text/html");
9696
+ return res.end(html);
9697
+ }
9698
+ next();
9699
+ });
9700
+ },
9701
+ configurePreviewServer(vitePreviewServer) {
9702
+ const workerConfigs = getWorkerConfigs(vitePreviewServer.config.root);
9703
+ if (workerConfigs.length >= 1 && pluginConfig.inspectorPort !== false) {
9704
+ addDebugToVitePrintUrls(vitePreviewServer);
9705
+ }
9706
+ const workerNames = workerConfigs.map((worker) => {
9707
+ assert8(worker.name);
9708
+ return worker.name;
9709
+ });
9710
+ vitePreviewServer.middlewares.use((req, res, next) => {
9711
+ if (req.url === debuggingPath && pluginConfig.inspectorPort !== false) {
9712
+ const html = getDebugPathHtml(
9713
+ workerNames,
9714
+ pluginConfig.inspectorPort ?? DEFAULT_INSPECTOR_PORT
9715
+ );
9716
+ res.setHeader("Content-Type", "text/html");
9717
+ return res.end(html);
9718
+ }
9719
+ next();
9720
+ });
9721
+ }
9516
9722
  }
9517
9723
  ];
9518
9724
  function getWorkerConfig2(environmentName) {
9519
- assert9(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
9725
+ assert8(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
9520
9726
  return resolvedPluginConfig.type !== "assets-only" ? resolvedPluginConfig.workers[environmentName] : void 0;
9521
9727
  }
9522
9728
  }
@@ -9531,9 +9737,6 @@ function getDotDevDotVarsContent(configPath, cloudflareEnv) {
9531
9737
  }
9532
9738
  return null;
9533
9739
  }
9534
- function createModuleReference(type, id) {
9535
- return `__CLOUDFLARE_MODULE__${type}__${id}__`;
9536
- }
9537
9740
  export {
9538
9741
  cloudflare2 as cloudflare
9539
9742
  };