@cloudflare/vite-plugin 0.0.0-36ef9c620 → 0.0.0-375cd12a4

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,7 @@
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";
4
5
  import { builtinModules as builtinModules2 } from "node:module";
5
6
  import * as path7 from "node:path";
6
7
  import { createMiddleware } from "@hattip/adapter-node";
@@ -1073,795 +1074,128 @@ var MagicString = class _MagicString {
1073
1074
  import { Miniflare } from "miniflare";
1074
1075
  import * as vite6 from "vite";
1075
1076
 
1076
- // src/cloudflare-environment.ts
1077
- import assert from "node:assert";
1078
- import * as vite2 from "vite";
1079
-
1080
1077
  // src/constants.ts
1081
1078
  var ROUTER_WORKER_NAME = "__router-worker__";
1082
1079
  var ASSET_WORKER_NAME = "__asset-worker__";
1083
1080
  var ASSET_WORKERS_COMPATIBILITY_DATE = "2024-10-04";
1084
- var MODULE_TYPES = ["CompiledWasm"];
1085
-
1086
- // src/shared.ts
1087
- var UNKNOWN_HOST = "http://localhost";
1088
- var INIT_PATH = "/__vite_plugin_cloudflare_init__";
1089
- 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;
1090
1087
 
1091
- // src/utils.ts
1092
- import * as path from "node:path";
1093
- import { Request as MiniflareRequest } from "miniflare";
1094
- import "vite";
1095
- function getOutputDirectory(userConfig, environmentName) {
1096
- const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
1097
- return userConfig.environments?.[environmentName]?.build?.outDir ?? path.join(rootOutputDirectory, environmentName);
1098
- }
1099
- function toMiniflareRequest(request) {
1100
- return new MiniflareRequest(request.url, {
1101
- method: request.method,
1102
- headers: [["accept-encoding", "identity"], ...request.headers],
1103
- body: request.body,
1104
- duplex: "half"
1105
- });
1106
- }
1107
- function nodeHeadersToWebHeaders(nodeHeaders) {
1108
- const headers = new Headers();
1109
- for (const [key, value] of Object.entries(nodeHeaders)) {
1110
- if (typeof value === "string") {
1111
- headers.append(key, value);
1112
- } else if (Array.isArray(value)) {
1113
- for (const item of value) {
1114
- 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;
1115
1099
  }
1116
1100
  }
1117
1101
  }
1118
- return headers;
1102
+ return null;
1103
+ }
1104
+ function createModuleReference(type, id) {
1105
+ return `__CLOUDFLARE_MODULE__${type}__${id}__`;
1119
1106
  }
1120
1107
 
1121
1108
  // src/cloudflare-environment.ts
1122
- var webSocketUndefinedError = "The WebSocket is undefined";
1123
- function createHotChannel(webSocketContainer) {
1124
- const listenersMap = /* @__PURE__ */ new Map();
1125
- const client = {
1126
- send(payload) {
1127
- const webSocket = webSocketContainer.webSocket;
1128
- assert(webSocket, webSocketUndefinedError);
1129
- 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;
1130
1144
  }
1131
- };
1132
- function onMessage(event) {
1133
- const payload = JSON.parse(event.data.toString());
1134
- const listeners = listenersMap.get(payload.event) ?? /* @__PURE__ */ new Set();
1135
- for (const listener of listeners) {
1136
- listener(payload.data, client);
1145
+ pos += set[i + 1];
1146
+ if (pos >= code) {
1147
+ return true;
1137
1148
  }
1138
1149
  }
1139
- return {
1140
- send(payload) {
1141
- const webSocket = webSocketContainer.webSocket;
1142
- assert(webSocket, webSocketUndefinedError);
1143
- webSocket.send(JSON.stringify(payload));
1144
- },
1145
- on(event, listener) {
1146
- const listeners = listenersMap.get(event) ?? /* @__PURE__ */ new Set();
1147
- listeners.add(listener);
1148
- listenersMap.set(event, listeners);
1149
- },
1150
- off(event, listener) {
1151
- listenersMap.get(event)?.delete(listener);
1152
- },
1153
- listen() {
1154
- const webSocket = webSocketContainer.webSocket;
1155
- assert(webSocket, webSocketUndefinedError);
1156
- webSocket.addEventListener("message", onMessage);
1157
- },
1158
- close() {
1159
- const webSocket = webSocketContainer.webSocket;
1160
- assert(webSocket, webSocketUndefinedError);
1161
- webSocket.removeEventListener("message", onMessage);
1162
- }
1163
- };
1150
+ return false;
1164
1151
  }
1165
- var CloudflareDevEnvironment = class extends vite2.DevEnvironment {
1166
- #webSocketContainer;
1167
- #worker;
1168
- constructor(name2, config) {
1169
- const webSocketContainer = {};
1170
- super(name2, config, {
1171
- hot: true,
1172
- transport: createHotChannel(webSocketContainer)
1173
- });
1174
- this.#webSocketContainer = webSocketContainer;
1152
+ function isIdentifierStart(code, astral) {
1153
+ if (code < 65) {
1154
+ return code === 36;
1175
1155
  }
1176
- async initRunner(worker) {
1177
- this.#worker = worker;
1178
- const response = await this.#worker.fetch(
1179
- new URL(INIT_PATH, UNKNOWN_HOST),
1180
- {
1181
- headers: {
1182
- upgrade: "websocket"
1183
- }
1184
- }
1185
- );
1186
- assert(
1187
- response.ok,
1188
- `Failed to initialize module runner, error: ${await response.text()}`
1189
- );
1190
- const webSocket = response.webSocket;
1191
- assert(webSocket, "Failed to establish WebSocket");
1192
- webSocket.accept();
1193
- this.#webSocketContainer.webSocket = webSocket;
1156
+ if (code < 91) {
1157
+ return true;
1194
1158
  }
1195
- };
1196
- var cloudflareBuiltInModules = [
1197
- "cloudflare:email",
1198
- "cloudflare:sockets",
1199
- "cloudflare:workers",
1200
- "cloudflare:workflows"
1201
- ];
1202
- var defaultConditions = ["workerd", "module", "browser"];
1203
- function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmentName) {
1204
- return {
1205
- resolve: {
1206
- // Note: in order for ssr pre-bundling to take effect we need to ask vite to treat all
1207
- // dependencies as not external
1208
- noExternal: true,
1209
- // We want to use `workerd` package exports if available (e.g. for postgres).
1210
- conditions: [...defaultConditions, "development|production"],
1211
- // The Cloudflare ones are proper builtins in the environment
1212
- builtins: [...cloudflareBuiltInModules]
1213
- },
1214
- dev: {
1215
- createEnvironment(name2, config) {
1216
- return new CloudflareDevEnvironment(name2, config);
1217
- }
1218
- },
1219
- build: {
1220
- createEnvironment(name2, config) {
1221
- return new vite2.BuildEnvironment(name2, config);
1222
- },
1223
- target: "es2022",
1224
- // We need to enable `emitAssets` in order to support additional modules defined by `rules`
1225
- emitAssets: true,
1226
- outDir: getOutputDirectory(userConfig, environmentName),
1227
- copyPublicDir: false,
1228
- ssr: true,
1229
- rollupOptions: {
1230
- // Note: vite starts dev pre-bundling crawling from either optimizeDeps.entries or rollupOptions.input
1231
- // so the input value here serves both as the build input as well as the starting point for
1232
- // dev pre-bundling crawling (were we not to set this input field we'd have to appropriately set
1233
- // optimizeDeps.entries in the dev config)
1234
- input: workerConfig.main
1235
- }
1236
- },
1237
- optimizeDeps: {
1238
- // Note: ssr pre-bundling is opt-in and we need to enable it by setting `noDiscovery` to false
1239
- noDiscovery: false,
1240
- entries: workerConfig.main,
1241
- exclude: [...cloudflareBuiltInModules],
1242
- esbuildOptions: {
1243
- platform: "neutral",
1244
- conditions: [...defaultConditions, "development"],
1245
- resolveExtensions: [
1246
- ".mjs",
1247
- ".js",
1248
- ".mts",
1249
- ".ts",
1250
- ".jsx",
1251
- ".tsx",
1252
- ".json",
1253
- ".cjs",
1254
- ".cts",
1255
- ".ctx"
1256
- ]
1257
- }
1258
- },
1259
- keepProcessEnv: false
1260
- };
1261
- }
1262
- function initRunners(resolvedPluginConfig, viteDevServer, miniflare) {
1263
- if (resolvedPluginConfig.type === "assets-only") {
1264
- return;
1159
+ if (code < 97) {
1160
+ return code === 95;
1265
1161
  }
1266
- return Promise.all(
1267
- Object.entries(resolvedPluginConfig.workers).map(
1268
- async ([environmentName, workerConfig]) => {
1269
- const worker = await miniflare.getWorker(workerConfig.name);
1270
- return viteDevServer.environments[environmentName].initRunner(worker);
1271
- }
1272
- )
1273
- );
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);
1274
1172
  }
1275
-
1276
- // src/deploy-config.ts
1277
- import assert2 from "node:assert";
1278
- import * as fs from "node:fs";
1279
- import * as path2 from "node:path";
1280
- import "vite";
1281
- function getDeployConfigPath(root) {
1282
- return path2.resolve(root, ".wrangler", "deploy", "config.json");
1283
- }
1284
- function getWorkerConfigPaths(root) {
1285
- const deployConfigPath = getDeployConfigPath(root);
1286
- const deployConfig = JSON.parse(
1287
- fs.readFileSync(deployConfigPath, "utf-8")
1288
- );
1289
- return [
1290
- { configPath: deployConfig.configPath },
1291
- ...deployConfig.auxiliaryWorkers
1292
- ].map(
1293
- ({ configPath }) => path2.resolve(path2.dirname(deployConfigPath), configPath)
1294
- );
1295
- }
1296
- function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
1297
- return path2.relative(
1298
- deployConfigDirectory,
1299
- path2.resolve(root, outputDirectory, "wrangler.json")
1300
- );
1301
- }
1302
- function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
1303
- const deployConfigPath = getDeployConfigPath(resolvedViteConfig.root);
1304
- const deployConfigDirectory = path2.dirname(deployConfigPath);
1305
- fs.mkdirSync(deployConfigDirectory, { recursive: true });
1306
- if (resolvedPluginConfig.type === "assets-only") {
1307
- const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
1308
- assert2(
1309
- clientOutputDirectory,
1310
- "Unexpected error: client environment output directory is undefined"
1311
- );
1312
- const deployConfig = {
1313
- configPath: getRelativePathToWorkerConfig(
1314
- deployConfigDirectory,
1315
- resolvedViteConfig.root,
1316
- clientOutputDirectory
1317
- ),
1318
- auxiliaryWorkers: []
1319
- };
1320
- fs.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
1321
- } else {
1322
- let entryWorkerConfigPath;
1323
- const auxiliaryWorkers = [];
1324
- for (const environmentName of Object.keys(resolvedPluginConfig.workers)) {
1325
- const outputDirectory = resolvedViteConfig.environments[environmentName]?.build.outDir;
1326
- assert2(
1327
- outputDirectory,
1328
- `Unexpected error: ${environmentName} environment output directory is undefined`
1329
- );
1330
- const configPath = getRelativePathToWorkerConfig(
1331
- deployConfigDirectory,
1332
- resolvedViteConfig.root,
1333
- outputDirectory
1334
- );
1335
- if (environmentName === resolvedPluginConfig.entryWorkerEnvironmentName) {
1336
- entryWorkerConfigPath = configPath;
1337
- } else {
1338
- auxiliaryWorkers.push({ configPath });
1339
- }
1340
- }
1341
- assert2(
1342
- entryWorkerConfigPath,
1343
- `Unexpected error: entryWorkerConfigPath is undefined`
1344
- );
1345
- const deployConfig = {
1346
- configPath: entryWorkerConfigPath,
1347
- auxiliaryWorkers
1348
- };
1349
- fs.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
1350
- }
1351
- }
1352
-
1353
- // src/dev.ts
1354
- import assert3 from "node:assert";
1355
- function getDevEntryWorker(resolvedPluginConfig, miniflare) {
1356
- const entryWorkerConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config : resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
1357
- assert3(entryWorkerConfig, "Unexpected error: No entry worker configuration");
1358
- return entryWorkerConfig.assets ? miniflare.getWorker(ROUTER_WORKER_NAME) : miniflare.getWorker(entryWorkerConfig.name);
1359
- }
1360
-
1361
- // src/miniflare-options.ts
1362
- import assert4 from "node:assert";
1363
- import * as fs2 from "node:fs";
1364
- import * as fsp from "node:fs/promises";
1365
- import * as path3 from "node:path";
1366
- import { fileURLToPath } from "node:url";
1367
- import {
1368
- kCurrentWorker,
1369
- Log,
1370
- LogLevel,
1371
- Response as MiniflareResponse
1372
- } from "miniflare";
1373
- import "vite";
1374
- import {
1375
- unstable_getMiniflareWorkerOptions,
1376
- unstable_readConfig
1377
- } from "wrangler";
1378
- function getPersistence(root, persistState) {
1379
- if (persistState === false) {
1380
- return {};
1381
- }
1382
- const defaultPersistPath = ".wrangler/state";
1383
- const persistPath = path3.resolve(
1384
- root,
1385
- typeof persistState === "object" ? persistState.path : defaultPersistPath,
1386
- "v3"
1387
- );
1388
- return {
1389
- cachePersist: path3.join(persistPath, "cache"),
1390
- d1Persist: path3.join(persistPath, "d1"),
1391
- durableObjectsPersist: path3.join(persistPath, "do"),
1392
- kvPersist: path3.join(persistPath, "kv"),
1393
- r2Persist: path3.join(persistPath, "r2"),
1394
- workflowsPersist: path3.join(persistPath, "workflows")
1395
- };
1396
- }
1397
- function missingWorkerErrorMessage(workerName) {
1398
- return `${workerName} does not match a worker name.`;
1399
- }
1400
- function getWorkerToWorkerEntrypointNamesMap(workers) {
1401
- const workerToWorkerEntrypointNamesMap = new Map(
1402
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1403
- );
1404
- for (const worker of workers) {
1405
- for (const value of Object.values(worker.serviceBindings ?? {})) {
1406
- if (typeof value === "object" && "name" in value && value.entrypoint !== void 0 && value.entrypoint !== "default") {
1407
- const targetWorkerName = value.name === kCurrentWorker ? worker.name : value.name;
1408
- const entrypointNames = workerToWorkerEntrypointNamesMap.get(targetWorkerName);
1409
- assert4(entrypointNames, missingWorkerErrorMessage(targetWorkerName));
1410
- entrypointNames.add(value.entrypoint);
1411
- }
1412
- }
1413
- }
1414
- return workerToWorkerEntrypointNamesMap;
1415
- }
1416
- function getWorkerToDurableObjectClassNamesMap(workers) {
1417
- const workerToDurableObjectClassNamesMap = new Map(
1418
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1419
- );
1420
- for (const worker of workers) {
1421
- for (const value of Object.values(worker.durableObjects ?? {})) {
1422
- if (typeof value === "string") {
1423
- const classNames = workerToDurableObjectClassNamesMap.get(worker.name);
1424
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1425
- classNames.add(value);
1426
- } else if (typeof value === "object") {
1427
- if (value.scriptName) {
1428
- const classNames = workerToDurableObjectClassNamesMap.get(
1429
- value.scriptName
1430
- );
1431
- assert4(classNames, missingWorkerErrorMessage(value.scriptName));
1432
- classNames.add(value.className);
1433
- } else {
1434
- const classNames = workerToDurableObjectClassNamesMap.get(
1435
- worker.name
1436
- );
1437
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1438
- classNames.add(value.className);
1439
- }
1440
- }
1441
- }
1442
- }
1443
- return workerToDurableObjectClassNamesMap;
1444
- }
1445
- function getWorkerToWorkflowEntrypointClassNamesMap(workers) {
1446
- const workerToWorkflowEntrypointClassNamesMap = new Map(
1447
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1448
- );
1449
- for (const worker of workers) {
1450
- for (const value of Object.values(worker.workflows ?? {})) {
1451
- if (value.scriptName) {
1452
- const classNames = workerToWorkflowEntrypointClassNamesMap.get(
1453
- value.scriptName
1454
- );
1455
- assert4(classNames, missingWorkerErrorMessage(value.scriptName));
1456
- classNames.add(value.className);
1457
- } else {
1458
- const classNames = workerToWorkflowEntrypointClassNamesMap.get(
1459
- worker.name
1460
- );
1461
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1462
- classNames.add(value.className);
1463
- }
1464
- }
1465
- }
1466
- return workerToWorkflowEntrypointClassNamesMap;
1467
- }
1468
- var miniflareModulesRoot = process.platform === "win32" ? "Z:\\" : "/";
1469
- var ROUTER_WORKER_PATH = "./asset-workers/router-worker.js";
1470
- var ASSET_WORKER_PATH = "./asset-workers/asset-worker.js";
1471
- var WRAPPER_PATH = "__VITE_WORKER_ENTRY__";
1472
- var RUNNER_PATH = "./runner-worker/index.js";
1473
- function getEntryWorkerConfig(resolvedPluginConfig) {
1474
- if (resolvedPluginConfig.type === "assets-only") {
1475
- return;
1476
- }
1477
- return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
1478
- }
1479
- function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1480
- const resolvedViteConfig = viteDevServer.config;
1481
- const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
1482
- const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
1483
- const assetWorkers = [
1484
- {
1485
- name: ROUTER_WORKER_NAME,
1486
- compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
1487
- modulesRoot: miniflareModulesRoot,
1488
- modules: [
1489
- {
1490
- type: "ESModule",
1491
- path: path3.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
1492
- contents: fs2.readFileSync(
1493
- fileURLToPath(new URL(ROUTER_WORKER_PATH, import.meta.url))
1494
- )
1495
- }
1496
- ],
1497
- bindings: {
1498
- CONFIG: {
1499
- has_user_worker: resolvedPluginConfig.type === "workers"
1500
- }
1501
- },
1502
- serviceBindings: {
1503
- ASSET_WORKER: ASSET_WORKER_NAME,
1504
- ...entryWorkerConfig ? { USER_WORKER: entryWorkerConfig.name } : {}
1505
- }
1506
- },
1507
- {
1508
- name: ASSET_WORKER_NAME,
1509
- compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
1510
- modulesRoot: miniflareModulesRoot,
1511
- modules: [
1512
- {
1513
- type: "ESModule",
1514
- path: path3.join(miniflareModulesRoot, ASSET_WORKER_PATH),
1515
- contents: fs2.readFileSync(
1516
- fileURLToPath(new URL(ASSET_WORKER_PATH, import.meta.url))
1517
- )
1518
- }
1519
- ],
1520
- bindings: {
1521
- CONFIG: {
1522
- ...assetsConfig?.html_handling ? { html_handling: assetsConfig.html_handling } : {},
1523
- ...assetsConfig?.not_found_handling ? { not_found_handling: assetsConfig.not_found_handling } : {}
1524
- }
1525
- },
1526
- serviceBindings: {
1527
- __VITE_ASSET_EXISTS__: async (request) => {
1528
- const { pathname } = new URL(request.url);
1529
- const filePath = path3.join(resolvedViteConfig.root, pathname);
1530
- let exists;
1531
- try {
1532
- exists = fs2.statSync(filePath).isFile();
1533
- } catch (error) {
1534
- exists = false;
1535
- }
1536
- return MiniflareResponse.json(exists);
1537
- },
1538
- __VITE_FETCH_ASSET__: async (request) => {
1539
- const { pathname } = new URL(request.url);
1540
- const filePath = path3.join(resolvedViteConfig.root, pathname);
1541
- try {
1542
- let html = await fsp.readFile(filePath, "utf-8");
1543
- html = await viteDevServer.transformIndexHtml(pathname, html);
1544
- return new MiniflareResponse(html, {
1545
- headers: { "Content-Type": "text/html" }
1546
- });
1547
- } catch (error) {
1548
- throw new Error(`Unexpected error. Failed to load ${pathname}`);
1549
- }
1550
- }
1551
- }
1552
- }
1553
- ];
1554
- const userWorkers = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1555
- ([environmentName, workerConfig]) => {
1556
- const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
1557
- {
1558
- ...workerConfig,
1559
- assets: void 0
1560
- },
1561
- resolvedPluginConfig.cloudflareEnv
1562
- );
1563
- const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1564
- return {
1565
- ...workerOptions,
1566
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1567
- name: workerConfig.name,
1568
- modulesRoot: miniflareModulesRoot,
1569
- unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
1570
- bindings: {
1571
- ...workerOptions.bindings,
1572
- __VITE_ROOT__: resolvedViteConfig.root,
1573
- __VITE_ENTRY_PATH__: workerConfig.main
1574
- },
1575
- serviceBindings: {
1576
- ...workerOptions.serviceBindings,
1577
- ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
1578
- [workerConfig.assets.binding]: ASSET_WORKER_NAME
1579
- } : {},
1580
- __VITE_INVOKE_MODULE__: async (request) => {
1581
- const payload = await request.json();
1582
- const invokePayloadData = payload.data;
1583
- assert4(
1584
- invokePayloadData.name === "fetchModule",
1585
- `Invalid invoke event: ${invokePayloadData.name}`
1586
- );
1587
- const [moduleId] = invokePayloadData.data;
1588
- const moduleRE = new RegExp(MODULE_PATTERN);
1589
- const shouldExternalize = (
1590
- // Worker modules (CompiledWasm, Text, Data)
1591
- moduleRE.test(moduleId)
1592
- );
1593
- if (shouldExternalize) {
1594
- const result2 = {
1595
- externalize: moduleId,
1596
- type: "module"
1597
- };
1598
- return MiniflareResponse.json({ result: result2 });
1599
- }
1600
- const devEnvironment = viteDevServer.environments[environmentName];
1601
- const result = await devEnvironment.hot.handleInvoke(payload);
1602
- return MiniflareResponse.json(result);
1603
- }
1604
- }
1605
- };
1606
- }
1607
- ) : [];
1608
- const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
1609
- const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
1610
- const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
1611
- const logger = new ViteMiniflareLogger(resolvedViteConfig);
1612
- return {
1613
- log: logger,
1614
- handleRuntimeStdio(stdout, stderr) {
1615
- const decoder = new TextDecoder();
1616
- stdout.forEach((data2) => logger.info(decoder.decode(data2)));
1617
- stderr.forEach(
1618
- (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
1619
- );
1620
- },
1621
- ...getPersistence(
1622
- resolvedViteConfig.root,
1623
- resolvedPluginConfig.persistState
1624
- ),
1625
- workers: [
1626
- ...assetWorkers,
1627
- ...userWorkers.map((workerOptions) => {
1628
- const wrappers = [
1629
- `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
1630
- `export default createWorkerEntrypointWrapper('default');`
1631
- ];
1632
- const workerEntrypointNames = workerToWorkerEntrypointNamesMap.get(
1633
- workerOptions.name
1634
- );
1635
- assert4(
1636
- workerEntrypointNames,
1637
- `WorkerEntrypoint names not found for worker ${workerOptions.name}`
1638
- );
1639
- for (const entrypointName of [...workerEntrypointNames].sort()) {
1640
- wrappers.push(
1641
- `export const ${entrypointName} = createWorkerEntrypointWrapper('${entrypointName}');`
1642
- );
1643
- }
1644
- const durableObjectClassNames = workerToDurableObjectClassNamesMap.get(
1645
- workerOptions.name
1646
- );
1647
- assert4(
1648
- durableObjectClassNames,
1649
- `DurableObject class names not found for worker ${workerOptions.name}`
1650
- );
1651
- for (const className of [...durableObjectClassNames].sort()) {
1652
- wrappers.push(
1653
- `export const ${className} = createDurableObjectWrapper('${className}');`
1654
- );
1655
- }
1656
- const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
1657
- assert4(
1658
- workflowEntrypointClassNames,
1659
- `WorkflowEntrypoint class names not found for worker ${workerOptions.name}`
1660
- );
1661
- for (const className of [...workflowEntrypointClassNames].sort()) {
1662
- wrappers.push(
1663
- `export const ${className} = createWorkflowEntrypointWrapper('${className}');`
1664
- );
1665
- }
1666
- return {
1667
- ...workerOptions,
1668
- modules: [
1669
- {
1670
- type: "ESModule",
1671
- path: path3.join(miniflareModulesRoot, WRAPPER_PATH),
1672
- contents: wrappers.join("\n")
1673
- },
1674
- {
1675
- type: "ESModule",
1676
- path: path3.join(miniflareModulesRoot, RUNNER_PATH),
1677
- contents: fs2.readFileSync(
1678
- fileURLToPath(new URL(RUNNER_PATH, import.meta.url))
1679
- )
1680
- }
1681
- ],
1682
- unsafeUseModuleFallbackService: true
1683
- };
1684
- })
1685
- ],
1686
- unsafeModuleFallbackService(request) {
1687
- const url = new URL(request.url);
1688
- const rawSpecifier = url.searchParams.get("rawSpecifier");
1689
- assert4(
1690
- rawSpecifier,
1691
- `Unexpected error: no specifier in request to module fallback service.`
1692
- );
1693
- const moduleRE = new RegExp(MODULE_PATTERN);
1694
- const match = moduleRE.exec(rawSpecifier);
1695
- assert4(match, `Unexpected error: no match for module ${rawSpecifier}.`);
1696
- const [full, moduleType, modulePath] = match;
1697
- assert4(
1698
- modulePath,
1699
- `Unexpected error: module path not found in reference ${full}.`
1700
- );
1701
- let source;
1702
- try {
1703
- source = fs2.readFileSync(modulePath);
1704
- } catch (error) {
1705
- throw new Error(`Import ${modulePath} not found. Does the file exist?`);
1706
- }
1707
- return MiniflareResponse.json({
1708
- // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
1709
- wasm: Array.from(source)
1710
- });
1711
- }
1712
- };
1713
- }
1714
- function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
1715
- const resolvedViteConfig = vitePreviewServer.config;
1716
- const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
1717
- const workerConfigs = configPaths.map(
1718
- (configPath) => unstable_readConfig({ config: configPath })
1719
- );
1720
- const workers = workerConfigs.map((config) => {
1721
- const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
1722
- const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1723
- return {
1724
- ...workerOptions,
1725
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1726
- name: config.name,
1727
- modules: true,
1728
- ...miniflareWorkerOptions.main ? { scriptPath: miniflareWorkerOptions.main } : { script: "" }
1729
- };
1730
- });
1731
- const logger = new ViteMiniflareLogger(resolvedViteConfig);
1732
- return {
1733
- log: logger,
1734
- handleRuntimeStdio(stdout, stderr) {
1735
- const decoder = new TextDecoder();
1736
- stdout.forEach((data2) => logger.info(decoder.decode(data2)));
1737
- stderr.forEach(
1738
- (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
1739
- );
1740
- },
1741
- ...getPersistence(resolvedViteConfig.root, persistState),
1742
- workers
1743
- };
1744
- }
1745
- var ViteMiniflareLogger = class extends Log {
1746
- logger;
1747
- constructor(config) {
1748
- super(miniflareLogLevelFromViteLogLevel(config.logLevel));
1749
- this.logger = config.logger;
1750
- }
1751
- logWithLevel(level, message) {
1752
- if (/^Ready on http/.test(message)) {
1753
- level = LogLevel.DEBUG;
1754
- }
1755
- switch (level) {
1756
- case LogLevel.ERROR:
1757
- return this.logger.error(message);
1758
- case LogLevel.WARN:
1759
- return this.logger.warn(message);
1760
- case LogLevel.INFO:
1761
- return this.logger.info(message);
1762
- }
1763
- }
1764
- };
1765
- function miniflareLogLevelFromViteLogLevel(level = "info") {
1766
- switch (level) {
1767
- case "error":
1768
- return LogLevel.ERROR;
1769
- case "warn":
1770
- return LogLevel.WARN;
1771
- case "info":
1772
- return LogLevel.INFO;
1773
- case "silent":
1774
- return LogLevel.NONE;
1775
- }
1776
- }
1777
-
1778
- // src/node-js-compat.ts
1779
- import assert6 from "node:assert";
1780
- import { cloudflare } from "@cloudflare/unenv-preset";
1781
- import { getNodeCompat } from "miniflare";
1782
-
1783
- // ../../node_modules/.pnpm/acorn@8.14.0/node_modules/acorn/dist/acorn.mjs
1784
- 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];
1785
- 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];
1786
- 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";
1787
- 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";
1788
- var reservedWords = {
1789
- 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",
1790
- 5: "class enum extends super const export import",
1791
- 6: "enum",
1792
- strict: "implements interface let package private protected public static yield",
1793
- strictBind: "eval arguments"
1794
- };
1795
- 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";
1796
- var keywords$1 = {
1797
- 5: ecma5AndLessKeywords,
1798
- "5module": ecma5AndLessKeywords + " export import",
1799
- 6: ecma5AndLessKeywords + " const class extends export import super"
1800
- };
1801
- var keywordRelationalOperator = /^in(stanceof)?$/;
1802
- var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
1803
- var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
1804
- function isInAstralSet(code, set) {
1805
- var pos = 65536;
1806
- for (var i = 0; i < set.length; i += 2) {
1807
- pos += set[i];
1808
- if (pos > code) {
1809
- return false;
1810
- }
1811
- pos += set[i + 1];
1812
- if (pos >= code) {
1813
- return true;
1814
- }
1815
- }
1816
- return false;
1817
- }
1818
- function isIdentifierStart(code, astral) {
1819
- if (code < 65) {
1820
- return code === 36;
1821
- }
1822
- if (code < 91) {
1823
- return true;
1824
- }
1825
- if (code < 97) {
1826
- return code === 95;
1827
- }
1828
- if (code < 123) {
1829
- return true;
1830
- }
1831
- if (code <= 65535) {
1832
- return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code));
1833
- }
1834
- if (astral === false) {
1835
- return false;
1836
- }
1837
- return isInAstralSet(code, astralIdentifierStartCodes);
1838
- }
1839
- function isIdentifierChar(code, astral) {
1840
- if (code < 48) {
1841
- return code === 36;
1842
- }
1843
- if (code < 58) {
1844
- return true;
1845
- }
1846
- if (code < 65) {
1847
- return false;
1848
- }
1849
- if (code < 91) {
1850
- return true;
1851
- }
1852
- if (code < 97) {
1853
- return code === 95;
1854
- }
1855
- if (code < 123) {
1856
- return true;
1857
- }
1858
- if (code <= 65535) {
1859
- return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code));
1860
- }
1861
- if (astral === false) {
1862
- return false;
1863
- }
1864
- 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);
1865
1199
  }
1866
1200
  var TokenType = function TokenType2(label, conf) {
1867
1201
  if (conf === void 0) conf = {};
@@ -1876,16 +1210,16 @@ var TokenType = function TokenType2(label, conf) {
1876
1210
  this.binop = conf.binop || null;
1877
1211
  this.updateContext = null;
1878
1212
  };
1879
- function binop(name2, prec) {
1880
- return new TokenType(name2, { beforeExpr: true, binop: prec });
1213
+ function binop(name, prec) {
1214
+ return new TokenType(name, { beforeExpr: true, binop: prec });
1881
1215
  }
1882
1216
  var beforeExpr = { beforeExpr: true };
1883
1217
  var startsExpr = { startsExpr: true };
1884
1218
  var keywords = {};
1885
- function kw(name2, options) {
1219
+ function kw(name, options) {
1886
1220
  if (options === void 0) options = {};
1887
- options.keyword = name2;
1888
- return keywords[name2] = new TokenType(name2, options);
1221
+ options.keyword = name;
1222
+ return keywords[name] = new TokenType(name, options);
1889
1223
  }
1890
1224
  var types$1 = {
1891
1225
  num: new TokenType("num", startsExpr),
@@ -2362,18 +1696,18 @@ pp$9.eat = function(type) {
2362
1696
  return false;
2363
1697
  }
2364
1698
  };
2365
- pp$9.isContextual = function(name2) {
2366
- 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;
2367
1701
  };
2368
- pp$9.eatContextual = function(name2) {
2369
- if (!this.isContextual(name2)) {
1702
+ pp$9.eatContextual = function(name) {
1703
+ if (!this.isContextual(name)) {
2370
1704
  return false;
2371
1705
  }
2372
1706
  this.next();
2373
1707
  return true;
2374
1708
  };
2375
- pp$9.expectContextual = function(name2) {
2376
- if (!this.eatContextual(name2)) {
1709
+ pp$9.expectContextual = function(name) {
1710
+ if (!this.eatContextual(name)) {
2377
1711
  this.unexpected();
2378
1712
  }
2379
1713
  };
@@ -2467,8 +1801,8 @@ pp$8.parseTopLevel = function(node) {
2467
1801
  }
2468
1802
  if (this.inModule) {
2469
1803
  for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) {
2470
- var name2 = list[i];
2471
- 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");
2472
1806
  }
2473
1807
  }
2474
1808
  this.adaptDirectivePrologue(node.body);
@@ -3211,26 +2545,26 @@ pp$8.exitClassBody = function() {
3211
2545
  }
3212
2546
  };
3213
2547
  function isPrivateNameConflicted(privateNameMap, element) {
3214
- var name2 = element.key.name;
3215
- var curr = privateNameMap[name2];
2548
+ var name = element.key.name;
2549
+ var curr = privateNameMap[name];
3216
2550
  var next = "true";
3217
2551
  if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
3218
2552
  next = (element.static ? "s" : "i") + element.kind;
3219
2553
  }
3220
2554
  if (curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget") {
3221
- privateNameMap[name2] = "true";
2555
+ privateNameMap[name] = "true";
3222
2556
  return false;
3223
2557
  } else if (!curr) {
3224
- privateNameMap[name2] = next;
2558
+ privateNameMap[name] = next;
3225
2559
  return false;
3226
2560
  } else {
3227
2561
  return true;
3228
2562
  }
3229
2563
  }
3230
- function checkKeyName(node, name2) {
2564
+ function checkKeyName(node, name) {
3231
2565
  var computed = node.computed;
3232
2566
  var key = node.key;
3233
- 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);
3234
2568
  }
3235
2569
  pp$8.parseExportAllDeclaration = function(node, exports) {
3236
2570
  if (this.options.ecmaVersion >= 11) {
@@ -3318,17 +2652,17 @@ pp$8.parseExportDefaultDeclaration = function() {
3318
2652
  return declaration;
3319
2653
  }
3320
2654
  };
3321
- pp$8.checkExport = function(exports, name2, pos) {
2655
+ pp$8.checkExport = function(exports, name, pos) {
3322
2656
  if (!exports) {
3323
2657
  return;
3324
2658
  }
3325
- if (typeof name2 !== "string") {
3326
- name2 = name2.type === "Identifier" ? name2.name : name2.value;
2659
+ if (typeof name !== "string") {
2660
+ name = name.type === "Identifier" ? name.name : name.value;
3327
2661
  }
3328
- if (hasOwn(exports, name2)) {
3329
- this.raiseRecoverable(pos, "Duplicate export '" + name2 + "'");
2662
+ if (hasOwn(exports, name)) {
2663
+ this.raiseRecoverable(pos, "Duplicate export '" + name + "'");
3330
2664
  }
3331
- exports[name2] = true;
2665
+ exports[name] = true;
3332
2666
  };
3333
2667
  pp$8.checkPatternExport = function(exports, pat) {
3334
2668
  var type = pat.type;
@@ -3908,20 +3242,20 @@ pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
3908
3242
  return;
3909
3243
  }
3910
3244
  var key = prop.key;
3911
- var name2;
3245
+ var name;
3912
3246
  switch (key.type) {
3913
3247
  case "Identifier":
3914
- name2 = key.name;
3248
+ name = key.name;
3915
3249
  break;
3916
3250
  case "Literal":
3917
- name2 = String(key.value);
3251
+ name = String(key.value);
3918
3252
  break;
3919
3253
  default:
3920
3254
  return;
3921
3255
  }
3922
3256
  var kind = prop.kind;
3923
3257
  if (this.options.ecmaVersion >= 6) {
3924
- if (name2 === "__proto__" && kind === "init") {
3258
+ if (name === "__proto__" && kind === "init") {
3925
3259
  if (propHash.proto) {
3926
3260
  if (refDestructuringErrors) {
3927
3261
  if (refDestructuringErrors.doubleProto < 0) {
@@ -3935,8 +3269,8 @@ pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
3935
3269
  }
3936
3270
  return;
3937
3271
  }
3938
- name2 = "$" + name2;
3939
- var other = propHash[name2];
3272
+ name = "$" + name;
3273
+ var other = propHash[name];
3940
3274
  if (other) {
3941
3275
  var redefinition;
3942
3276
  if (kind === "init") {
@@ -3948,7 +3282,7 @@ pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
3948
3282
  this.raiseRecoverable(key.start, "Redefinition of property");
3949
3283
  }
3950
3284
  } else {
3951
- other = propHash[name2] = {
3285
+ other = propHash[name] = {
3952
3286
  init: false,
3953
3287
  get: false,
3954
3288
  set: false
@@ -4848,31 +4182,31 @@ pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestruct
4848
4182
  pp$5.checkUnreserved = function(ref2) {
4849
4183
  var start = ref2.start;
4850
4184
  var end = ref2.end;
4851
- var name2 = ref2.name;
4852
- if (this.inGenerator && name2 === "yield") {
4185
+ var name = ref2.name;
4186
+ if (this.inGenerator && name === "yield") {
4853
4187
  this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator");
4854
4188
  }
4855
- if (this.inAsync && name2 === "await") {
4189
+ if (this.inAsync && name === "await") {
4856
4190
  this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function");
4857
4191
  }
4858
- if (this.currentThisScope().inClassFieldInit && name2 === "arguments") {
4192
+ if (this.currentThisScope().inClassFieldInit && name === "arguments") {
4859
4193
  this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer");
4860
4194
  }
4861
- if (this.inClassStaticBlock && (name2 === "arguments" || name2 === "await")) {
4862
- 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");
4863
4197
  }
4864
- if (this.keywords.test(name2)) {
4865
- this.raise(start, "Unexpected keyword '" + name2 + "'");
4198
+ if (this.keywords.test(name)) {
4199
+ this.raise(start, "Unexpected keyword '" + name + "'");
4866
4200
  }
4867
4201
  if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) {
4868
4202
  return;
4869
4203
  }
4870
4204
  var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
4871
- if (re.test(name2)) {
4872
- if (!this.inAsync && name2 === "await") {
4205
+ if (re.test(name)) {
4206
+ if (!this.inAsync && name === "await") {
4873
4207
  this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function");
4874
4208
  }
4875
- this.raiseRecoverable(start, "The keyword '" + name2 + "' is reserved");
4209
+ this.raiseRecoverable(start, "The keyword '" + name + "' is reserved");
4876
4210
  }
4877
4211
  };
4878
4212
  pp$5.parseIdent = function(liberal) {
@@ -4977,36 +4311,36 @@ pp$3.exitScope = function() {
4977
4311
  pp$3.treatFunctionsAsVarInScope = function(scope) {
4978
4312
  return scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_TOP;
4979
4313
  };
4980
- pp$3.declareName = function(name2, bindingType, pos) {
4314
+ pp$3.declareName = function(name, bindingType, pos) {
4981
4315
  var redeclared = false;
4982
4316
  if (bindingType === BIND_LEXICAL) {
4983
4317
  var scope = this.currentScope();
4984
- redeclared = scope.lexical.indexOf(name2) > -1 || scope.functions.indexOf(name2) > -1 || scope.var.indexOf(name2) > -1;
4985
- 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);
4986
4320
  if (this.inModule && scope.flags & SCOPE_TOP) {
4987
- delete this.undefinedExports[name2];
4321
+ delete this.undefinedExports[name];
4988
4322
  }
4989
4323
  } else if (bindingType === BIND_SIMPLE_CATCH) {
4990
4324
  var scope$1 = this.currentScope();
4991
- scope$1.lexical.push(name2);
4325
+ scope$1.lexical.push(name);
4992
4326
  } else if (bindingType === BIND_FUNCTION) {
4993
4327
  var scope$2 = this.currentScope();
4994
4328
  if (this.treatFunctionsAsVar) {
4995
- redeclared = scope$2.lexical.indexOf(name2) > -1;
4329
+ redeclared = scope$2.lexical.indexOf(name) > -1;
4996
4330
  } else {
4997
- 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;
4998
4332
  }
4999
- scope$2.functions.push(name2);
4333
+ scope$2.functions.push(name);
5000
4334
  } else {
5001
4335
  for (var i = this.scopeStack.length - 1; i >= 0; --i) {
5002
4336
  var scope$3 = this.scopeStack[i];
5003
- 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) {
5004
4338
  redeclared = true;
5005
4339
  break;
5006
4340
  }
5007
- scope$3.var.push(name2);
4341
+ scope$3.var.push(name);
5008
4342
  if (this.inModule && scope$3.flags & SCOPE_TOP) {
5009
- delete this.undefinedExports[name2];
4343
+ delete this.undefinedExports[name];
5010
4344
  }
5011
4345
  if (scope$3.flags & SCOPE_VAR) {
5012
4346
  break;
@@ -5014,7 +4348,7 @@ pp$3.declareName = function(name2, bindingType, pos) {
5014
4348
  }
5015
4349
  }
5016
4350
  if (redeclared) {
5017
- this.raiseRecoverable(pos, "Identifier '" + name2 + "' has already been declared");
4351
+ this.raiseRecoverable(pos, "Identifier '" + name + "' has already been declared");
5018
4352
  }
5019
4353
  };
5020
4354
  pp$3.checkLocalExport = function(id) {
@@ -5334,8 +4668,8 @@ pp$1.regexp_pattern = function(state) {
5334
4668
  state.raise("Invalid escape");
5335
4669
  }
5336
4670
  for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
5337
- var name2 = list[i];
5338
- if (!state.groupNames[name2]) {
4671
+ var name = list[i];
4672
+ if (!state.groupNames[name]) {
5339
4673
  state.raise("Invalid named capture referenced");
5340
4674
  }
5341
4675
  }
@@ -5974,10 +5308,10 @@ pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
5974
5308
  61
5975
5309
  /* = */
5976
5310
  )) {
5977
- var name2 = state.lastStringValue;
5311
+ var name = state.lastStringValue;
5978
5312
  if (this.regexp_eatUnicodePropertyValue(state)) {
5979
5313
  var value = state.lastStringValue;
5980
- this.regexp_validateUnicodePropertyNameAndValue(state, name2, value);
5314
+ this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
5981
5315
  return CharSetOk;
5982
5316
  }
5983
5317
  }
@@ -5988,11 +5322,11 @@ pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
5988
5322
  }
5989
5323
  return CharSetNone;
5990
5324
  };
5991
- pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name2, value) {
5992
- if (!hasOwn(state.unicodeProperties.nonBinary, name2)) {
5325
+ pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
5326
+ if (!hasOwn(state.unicodeProperties.nonBinary, name)) {
5993
5327
  state.raise("Invalid property name");
5994
5328
  }
5995
- if (!state.unicodeProperties.nonBinary[name2].test(value)) {
5329
+ if (!state.unicodeProperties.nonBinary[name].test(value)) {
5996
5330
  state.raise("Invalid property value");
5997
5331
  }
5998
5332
  };
@@ -7309,7 +6643,7 @@ Parser.acorn = {
7309
6643
 
7310
6644
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7311
6645
  import { builtinModules, createRequire } from "node:module";
7312
- import fs3, { realpathSync, statSync as statSync2, promises } from "node:fs";
6646
+ import fs, { realpathSync, statSync, promises } from "node:fs";
7313
6647
 
7314
6648
  // ../../node_modules/.pnpm/ufo@1.5.4/node_modules/ufo/dist/index.mjs
7315
6649
  var r = String.fromCharCode;
@@ -7366,9 +6700,9 @@ var isAbsolute = function(p) {
7366
6700
 
7367
6701
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7368
6702
  import { fileURLToPath as fileURLToPath$1, URL as URL$1, pathToFileURL as pathToFileURL$1 } from "node:url";
7369
- import assert5 from "node:assert";
6703
+ import assert from "node:assert";
7370
6704
  import process$1 from "node:process";
7371
- import path4, { dirname as dirname3 } from "node:path";
6705
+ import path, { dirname as dirname2 } from "node:path";
7372
6706
  import v8 from "node:v8";
7373
6707
  import { format as format2, inspect } from "node:util";
7374
6708
  var BUILTIN_MODULES = new Set(builtinModules);
@@ -7403,31 +6737,31 @@ codes.ERR_INVALID_ARG_TYPE = createError(
7403
6737
  * @param {Array<string> | string} expected
7404
6738
  * @param {unknown} actual
7405
6739
  */
7406
- (name2, expected, actual) => {
7407
- assert5(typeof name2 === "string", "'name' must be a string");
6740
+ (name, expected, actual) => {
6741
+ assert(typeof name === "string", "'name' must be a string");
7408
6742
  if (!Array.isArray(expected)) {
7409
6743
  expected = [expected];
7410
6744
  }
7411
6745
  let message = "The ";
7412
- if (name2.endsWith(" argument")) {
7413
- message += `${name2} `;
6746
+ if (name.endsWith(" argument")) {
6747
+ message += `${name} `;
7414
6748
  } else {
7415
- const type = name2.includes(".") ? "property" : "argument";
7416
- message += `"${name2}" ${type} `;
6749
+ const type = name.includes(".") ? "property" : "argument";
6750
+ message += `"${name}" ${type} `;
7417
6751
  }
7418
6752
  message += "must be ";
7419
6753
  const types2 = [];
7420
6754
  const instances = [];
7421
6755
  const other = [];
7422
6756
  for (const value of expected) {
7423
- assert5(
6757
+ assert(
7424
6758
  typeof value === "string",
7425
6759
  "All expected entries have to be of type string"
7426
6760
  );
7427
6761
  if (kTypes.has(value)) {
7428
6762
  types2.push(value.toLowerCase());
7429
6763
  } else if (classRegExp.exec(value) === null) {
7430
- assert5(
6764
+ assert(
7431
6765
  value !== "object",
7432
6766
  'The value "object" should be written as "Object"'
7433
6767
  );
@@ -7500,14 +6834,14 @@ codes.ERR_INVALID_PACKAGE_TARGET = createError(
7500
6834
  * @param {boolean} [isImport=false]
7501
6835
  * @param {string} [base]
7502
6836
  */
7503
- (packagePath, key, target, isImport = false, base = void 0) => {
7504
- 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("./");
7505
6839
  if (key === ".") {
7506
- assert5(isImport === false);
7507
- 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 "./"' : ""}`;
7508
6842
  }
7509
6843
  return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(
7510
- target
6844
+ target2
7511
6845
  )} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
7512
6846
  },
7513
6847
  Error
@@ -7583,13 +6917,13 @@ codes.ERR_INVALID_ARG_VALUE = createError(
7583
6917
  * @param {unknown} value
7584
6918
  * @param {string} [reason='is invalid']
7585
6919
  */
7586
- (name2, value, reason = "is invalid") => {
6920
+ (name, value, reason = "is invalid") => {
7587
6921
  let inspected = inspect(value);
7588
6922
  if (inspected.length > 128) {
7589
6923
  inspected = `${inspected.slice(0, 128)}...`;
7590
6924
  }
7591
- const type = name2.includes(".") ? "property" : "argument";
7592
- return `The ${type} '${name2}' ${reason}. Received ${inspected}`;
6925
+ const type = name.includes(".") ? "property" : "argument";
6926
+ return `The ${type} '${name}' ${reason}. Received ${inspected}`;
7593
6927
  },
7594
6928
  TypeError
7595
6929
  // Note: extra classes have been shaken out.
@@ -7668,9 +7002,9 @@ var captureLargerStackTrace = hideStackFrames(
7668
7002
  );
7669
7003
  function getMessage(key, parameters, self) {
7670
7004
  const message = messages.get(key);
7671
- assert5(message !== void 0, "expected `message` to be found");
7005
+ assert(message !== void 0, "expected `message` to be found");
7672
7006
  if (typeof message === "function") {
7673
- assert5(
7007
+ assert(
7674
7008
  message.length <= parameters.length,
7675
7009
  // Default options do not count.
7676
7010
  `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`
@@ -7680,7 +7014,7 @@ function getMessage(key, parameters, self) {
7680
7014
  const regex = /%[dfijoOs]/g;
7681
7015
  let expectedLength = 0;
7682
7016
  while (regex.exec(message) !== null) expectedLength++;
7683
- assert5(
7017
+ assert(
7684
7018
  expectedLength === parameters.length,
7685
7019
  `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`
7686
7020
  );
@@ -7717,7 +7051,7 @@ function read(jsonPath, { base, specifier }) {
7717
7051
  }
7718
7052
  let string;
7719
7053
  try {
7720
- string = fs3.readFileSync(path4.toNamespacedPath(jsonPath), "utf8");
7054
+ string = fs.readFileSync(path.toNamespacedPath(jsonPath), "utf8");
7721
7055
  } catch (error) {
7722
7056
  const exception = (
7723
7057
  /** @type {ErrnoException} */
@@ -7903,14 +7237,14 @@ var patternRegEx = /\*/g;
7903
7237
  var encodedSeparatorRegEx = /%2f|%5c/i;
7904
7238
  var emittedPackageWarnings = /* @__PURE__ */ new Set();
7905
7239
  var doubleSlashRegEx = /[/\\]{2}/;
7906
- function emitInvalidSegmentDeprecation(target, request, match, packageJsonUrl, internal, base, isTarget) {
7240
+ function emitInvalidSegmentDeprecation(target2, request, match, packageJsonUrl, internal, base, isTarget) {
7907
7241
  if (process$1.noDeprecation) {
7908
7242
  return;
7909
7243
  }
7910
7244
  const pjsonPath = fileURLToPath$1(packageJsonUrl);
7911
- const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
7245
+ const double = doubleSlashRegEx.exec(isTarget ? target2 : request) !== null;
7912
7246
  process$1.emitWarning(
7913
- `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)}` : ""}.`,
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)}` : ""}.`,
7914
7248
  "DeprecationWarning",
7915
7249
  "DEP0166"
7916
7250
  );
@@ -7933,7 +7267,7 @@ Default "index" lookups for the main are deprecated for ES modules.`,
7933
7267
  "DeprecationWarning",
7934
7268
  "DEP0151"
7935
7269
  );
7936
- } else if (path4.resolve(packagePath, main) !== urlPath) {
7270
+ } else if (path.resolve(packagePath, main) !== urlPath) {
7937
7271
  process$1.emitWarning(
7938
7272
  `Package ${packagePath} has a "main" field set to "${main}", excluding the full filename and extension to the resolved file at "${urlPath.slice(
7939
7273
  packagePath.length
@@ -7946,12 +7280,12 @@ Default "index" lookups for the main are deprecated for ES modules.`,
7946
7280
  }
7947
7281
  function tryStatSync(path8) {
7948
7282
  try {
7949
- return statSync2(path8);
7283
+ return statSync(path8);
7950
7284
  } catch {
7951
7285
  }
7952
7286
  }
7953
7287
  function fileExists(url) {
7954
- const stats = statSync2(url, { throwIfNoEntry: false });
7288
+ const stats = statSync(url, { throwIfNoEntry: false });
7955
7289
  const isFile = stats ? stats.isFile() : void 0;
7956
7290
  return isFile === null || isFile === void 0 ? false : isFile;
7957
7291
  }
@@ -8040,7 +7374,7 @@ function finalizeResolution(resolved, base, preserveSymlinks) {
8040
7374
  {
8041
7375
  const real = realpathSync(filePath);
8042
7376
  const { search, hash } = resolved;
8043
- resolved = pathToFileURL$1(real + (filePath.endsWith(path4.sep) ? "/" : ""));
7377
+ resolved = pathToFileURL$1(real + (filePath.endsWith(path.sep) ? "/" : ""));
8044
7378
  resolved.search = search;
8045
7379
  resolved.hash = hash;
8046
7380
  }
@@ -8068,47 +7402,47 @@ function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
8068
7402
  base && fileURLToPath$1(base)
8069
7403
  );
8070
7404
  }
8071
- function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
8072
- target = typeof target === "object" && target !== null ? JSON.stringify(target, null, "") : `${target}`;
7405
+ function invalidPackageTarget(subpath, target2, packageJsonUrl, internal, base) {
7406
+ target2 = typeof target2 === "object" && target2 !== null ? JSON.stringify(target2, null, "") : `${target2}`;
8073
7407
  return new ERR_INVALID_PACKAGE_TARGET(
8074
7408
  fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8075
7409
  subpath,
8076
- target,
7410
+ target2,
8077
7411
  internal,
8078
7412
  base && fileURLToPath$1(base)
8079
7413
  );
8080
7414
  }
8081
- function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
8082
- if (subpath !== "" && !pattern && target[target.length - 1] !== "/")
8083
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8084
- if (!target.startsWith("./")) {
8085
- if (internal && !target.startsWith("../") && !target.startsWith("/")) {
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("/")) {
8086
7420
  let isURL = false;
8087
7421
  try {
8088
- new URL$1(target);
7422
+ new URL$1(target2);
8089
7423
  isURL = true;
8090
7424
  } catch {
8091
7425
  }
8092
7426
  if (!isURL) {
8093
7427
  const exportTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8094
7428
  patternRegEx,
8095
- target,
7429
+ target2,
8096
7430
  () => subpath
8097
- ) : target + subpath;
7431
+ ) : target2 + subpath;
8098
7432
  return packageResolve(exportTarget, packageJsonUrl, conditions);
8099
7433
  }
8100
7434
  }
8101
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
7435
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
8102
7436
  }
8103
- if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
8104
- if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
7437
+ if (invalidSegmentRegEx.exec(target2.slice(2)) !== null) {
7438
+ if (deprecatedInvalidSegmentRegEx.exec(target2.slice(2)) === null) {
8105
7439
  if (!isPathMap) {
8106
7440
  const request = pattern ? match.replace("*", () => subpath) : match + subpath;
8107
7441
  const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8108
7442
  patternRegEx,
8109
- target,
7443
+ target2,
8110
7444
  () => subpath
8111
- ) : target;
7445
+ ) : target2;
8112
7446
  emitInvalidSegmentDeprecation(
8113
7447
  resolvedTarget,
8114
7448
  request,
@@ -8120,14 +7454,14 @@ function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base
8120
7454
  );
8121
7455
  }
8122
7456
  } else {
8123
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
7457
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
8124
7458
  }
8125
7459
  }
8126
- const resolved = new URL$1(target, packageJsonUrl);
7460
+ const resolved = new URL$1(target2, packageJsonUrl);
8127
7461
  const resolvedPath = resolved.pathname;
8128
7462
  const packagePath = new URL$1(".", packageJsonUrl).pathname;
8129
7463
  if (!resolvedPath.startsWith(packagePath))
8130
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
7464
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
8131
7465
  if (subpath === "") return resolved;
8132
7466
  if (invalidSegmentRegEx.exec(subpath) !== null) {
8133
7467
  const request = pattern ? match.replace("*", () => subpath) : match + subpath;
@@ -8135,9 +7469,9 @@ function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base
8135
7469
  if (!isPathMap) {
8136
7470
  const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8137
7471
  patternRegEx,
8138
- target,
7472
+ target2,
8139
7473
  () => subpath
8140
- ) : target;
7474
+ ) : target2;
8141
7475
  emitInvalidSegmentDeprecation(
8142
7476
  resolvedTarget,
8143
7477
  request,
@@ -8148,672 +7482,1472 @@ function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base
8148
7482
  false
8149
7483
  );
8150
7484
  }
8151
- } else {
8152
- throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
7485
+ } else {
7486
+ throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
7487
+ }
7488
+ }
7489
+ if (pattern) {
7490
+ return new URL$1(
7491
+ RegExpPrototypeSymbolReplace.call(
7492
+ patternRegEx,
7493
+ resolved.href,
7494
+ () => subpath
7495
+ )
7496
+ );
7497
+ }
7498
+ return new URL$1(subpath, resolved);
7499
+ }
7500
+ function isArrayIndex(key) {
7501
+ const keyNumber = Number(key);
7502
+ if (`${keyNumber}` !== key) return false;
7503
+ return keyNumber >= 0 && keyNumber < 4294967295;
7504
+ }
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) {
7599
+ return null;
7600
+ }
7601
+ throw invalidPackageTarget(
7602
+ packageSubpath,
7603
+ target2,
7604
+ packageJsonUrl,
7605
+ internal,
7606
+ base
7607
+ );
7608
+ }
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) {
7632
+ if (process$1.noDeprecation) {
7633
+ return;
7634
+ }
7635
+ const pjsonPath = fileURLToPath$1(pjsonUrl);
7636
+ if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return;
7637
+ emittedPackageWarnings.add(pjsonPath + "|" + match);
7638
+ process$1.emitWarning(
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.`,
7640
+ "DeprecationWarning",
7641
+ "DEP0155"
7642
+ );
7643
+ }
7644
+ function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
7645
+ let exports = packageConfig.exports;
7646
+ if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
7647
+ exports = { ".": exports };
7648
+ }
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
7661
+ );
7662
+ if (resolveResult === null || resolveResult === void 0) {
7663
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7664
+ }
7665
+ return resolveResult;
7666
+ }
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
+ }
8153
7690
  }
8154
7691
  }
8155
- if (pattern) {
8156
- return new URL$1(
8157
- RegExpPrototypeSymbolReplace.call(
8158
- patternRegEx,
8159
- resolved.href,
8160
- () => subpath
8161
- )
7692
+ if (bestMatch) {
7693
+ const target2 = (
7694
+ /** @type {unknown} */
7695
+ exports[bestMatch]
8162
7696
  );
8163
- }
8164
- return new URL$1(subpath, resolved);
8165
- }
8166
- function isArrayIndex(key) {
8167
- const keyNumber = Number(key);
8168
- if (`${keyNumber}` !== key) return false;
8169
- return keyNumber >= 0 && keyNumber < 4294967295;
8170
- }
8171
- function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
8172
- if (typeof target === "string") {
8173
- return resolvePackageTargetString(
8174
- target,
8175
- subpath,
8176
- packageSubpath,
7697
+ const resolveResult = resolvePackageTarget(
8177
7698
  packageJsonUrl,
7699
+ target2,
7700
+ bestMatchSubpath,
7701
+ bestMatch,
8178
7702
  base,
8179
- pattern,
8180
- internal,
8181
- isPathMap,
7703
+ true,
7704
+ false,
7705
+ packageSubpath.endsWith("/"),
8182
7706
  conditions
8183
7707
  );
7708
+ if (resolveResult === null || resolveResult === void 0) {
7709
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7710
+ }
7711
+ return resolveResult;
8184
7712
  }
8185
- if (Array.isArray(target)) {
8186
- const targetList = target;
8187
- if (targetList.length === 0) return null;
8188
- let lastException;
8189
- let i = -1;
8190
- while (++i < targetList.length) {
8191
- const targetItem = targetList[i];
8192
- let resolveResult;
8193
- try {
8194
- resolveResult = resolvePackageTarget(
7713
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7714
+ }
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;
7727
+ }
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(
8195
7741
  packageJsonUrl,
8196
- targetItem,
8197
- subpath,
8198
- packageSubpath,
7742
+ imports[name],
7743
+ "",
7744
+ name,
8199
7745
  base,
8200
- pattern,
8201
- internal,
8202
- isPathMap,
7746
+ false,
7747
+ true,
7748
+ false,
8203
7749
  conditions
8204
7750
  );
8205
- } catch (error) {
8206
- const exception = (
8207
- /** @type {ErrnoException} */
8208
- error
8209
- );
8210
- lastException = exception;
8211
- if (exception.code === "ERR_INVALID_PACKAGE_TARGET") continue;
8212
- throw error;
8213
- }
8214
- if (resolveResult === void 0) continue;
8215
- if (resolveResult === null) {
8216
- lastException = null;
8217
- continue;
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
+ }
8218
7790
  }
8219
- return resolveResult;
8220
7791
  }
8221
- if (lastException === void 0 || lastException === null) {
8222
- return null;
7792
+ }
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);
8223
7805
  }
8224
- throw lastException;
8225
7806
  }
8226
- if (typeof target === "object" && target !== null) {
8227
- const keys = Object.getOwnPropertyNames(target);
8228
- let i = -1;
8229
- while (++i < keys.length) {
8230
- const key = keys[i];
8231
- if (isArrayIndex(key)) {
8232
- throw new ERR_INVALID_PACKAGE_CONFIG(
8233
- fileURLToPath$1(packageJsonUrl),
8234
- base,
8235
- '"exports" cannot contain numeric property keys.'
8236
- );
8237
- }
7807
+ const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
7808
+ if (invalidPackageNameRegEx.exec(packageName) !== null) {
7809
+ validPackageName = false;
7810
+ }
7811
+ if (!validPackageName) {
7812
+ throw new ERR_INVALID_MODULE_SPECIFIER(
7813
+ specifier,
7814
+ "is not a valid package name",
7815
+ fileURLToPath$1(base)
7816
+ );
7817
+ }
7818
+ const packageSubpath = "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex));
7819
+ return { packageName, packageSubpath, isScoped };
7820
+ }
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(
7826
+ specifier,
7827
+ base
7828
+ );
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
+ );
8238
7840
  }
8239
- i = -1;
8240
- while (++i < keys.length) {
8241
- const key = keys[i];
8242
- if (key === "default" || conditions && conditions.has(key)) {
8243
- const conditionalTarget = (
8244
- /** @type {unknown} */
8245
- target[key]
8246
- );
8247
- const resolveResult = resolvePackageTarget(
8248
- packageJsonUrl,
8249
- conditionalTarget,
8250
- subpath,
8251
- packageSubpath,
8252
- base,
8253
- pattern,
8254
- internal,
8255
- isPathMap,
8256
- conditions
8257
- );
8258
- if (resolveResult === void 0) continue;
8259
- return resolveResult;
7841
+ }
7842
+ let packageJsonUrl = new URL$1(
7843
+ "./node_modules/" + packageName + "/package.json",
7844
+ base
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);
7875
+ }
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;
7884
+ }
7885
+ function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
7886
+ if (specifier === "") return false;
7887
+ if (specifier[0] === "/") return true;
7888
+ return isRelativeSpecifier(specifier);
7889
+ }
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;
8260
7913
  }
7914
+ resolved = packageResolve(specifier, base, conditions);
8261
7915
  }
8262
- return null;
8263
7916
  }
8264
- if (target === null) {
8265
- return null;
7917
+ assert(resolved !== void 0, "expected to be defined");
7918
+ if (resolved.protocol !== "file:") {
7919
+ return resolved;
8266
7920
  }
8267
- throw invalidPackageTarget(
8268
- packageSubpath,
8269
- target,
8270
- packageJsonUrl,
8271
- internal,
8272
- base
8273
- );
7921
+ return finalizeResolution(resolved, base);
8274
7922
  }
8275
- function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
8276
- if (typeof exports === "string" || Array.isArray(exports)) return true;
8277
- if (typeof exports !== "object" || exports === null) return false;
8278
- const keys = Object.getOwnPropertyNames(exports);
8279
- let isConditionalSugar = false;
8280
- let i = 0;
8281
- let keyIndex = -1;
8282
- while (++keyIndex < keys.length) {
8283
- const key = keys[keyIndex];
8284
- const currentIsConditionalSugar = key === "" || key[0] !== ".";
8285
- if (i++ === 0) {
8286
- isConditionalSugar = currentIsConditionalSugar;
8287
- } else if (isConditionalSugar !== currentIsConditionalSugar) {
8288
- throw new ERR_INVALID_PACKAGE_CONFIG(
8289
- fileURLToPath$1(packageJsonUrl),
8290
- base,
8291
- `"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.`
8292
- );
8293
- }
7923
+ function fileURLToPath(id) {
7924
+ if (typeof id === "string" && !id.startsWith("file://")) {
7925
+ return normalizeSlash(id);
8294
7926
  }
8295
- return isConditionalSugar;
7927
+ return normalizeSlash(fileURLToPath$1(id));
8296
7928
  }
8297
- function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
8298
- if (process$1.noDeprecation) {
8299
- return;
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();
8300
7935
  }
8301
- const pjsonPath = fileURLToPath$1(pjsonUrl);
8302
- if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return;
8303
- emittedPackageWarnings.add(pjsonPath + "|" + match);
8304
- process$1.emitWarning(
8305
- `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.`,
8306
- "DeprecationWarning",
8307
- "DEP0155"
8308
- );
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));
8309
7943
  }
8310
- function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
8311
- let exports = packageConfig.exports;
8312
- if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
8313
- exports = { ".": exports };
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;
7958
+ }
8314
7959
  }
8315
- if (own.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
8316
- const target = exports[packageSubpath];
8317
- const resolveResult = resolvePackageTarget(
8318
- packageJsonUrl,
8319
- target,
8320
- "",
8321
- packageSubpath,
8322
- base,
8323
- false,
8324
- false,
8325
- false,
8326
- conditions
8327
- );
8328
- if (resolveResult === null || resolveResult === void 0) {
8329
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7960
+ }
7961
+ function _resolve(id, options = {}) {
7962
+ if (typeof id !== "string") {
7963
+ if (id instanceof URL) {
7964
+ id = fileURLToPath(id);
7965
+ } else {
7966
+ throw new TypeError("input must be a `string` or `URL`");
8330
7967
  }
8331
- return resolveResult;
8332
7968
  }
8333
- let bestMatch = "";
8334
- let bestMatchSubpath = "";
8335
- const keys = Object.getOwnPropertyNames(exports);
8336
- let i = -1;
8337
- while (++i < keys.length) {
8338
- const key = keys[i];
8339
- const patternIndex = key.indexOf("*");
8340
- if (patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex))) {
8341
- if (packageSubpath.endsWith("/")) {
8342
- emitTrailingSlashPatternDeprecation(
8343
- packageSubpath,
8344
- packageJsonUrl,
8345
- base
8346
- );
7969
+ if (/(node|data|http|https):/.test(id)) {
7970
+ return id;
7971
+ }
7972
+ if (BUILTIN_MODULES.has(id)) {
7973
+ return "node:" + id;
7974
+ }
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);
8347
7983
  }
8348
- const patternTrailer = key.slice(patternIndex + 1);
8349
- if (packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
8350
- bestMatch = key;
8351
- bestMatchSubpath = packageSubpath.slice(
8352
- patternIndex,
8353
- packageSubpath.length - patternTrailer.length
7984
+ } catch (error) {
7985
+ if (error?.code !== "ENOENT") {
7986
+ throw error;
7987
+ }
7988
+ }
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
+ );
8005
+ }
8006
+ }
8007
+ let resolved;
8008
+ for (const url of urls) {
8009
+ resolved = _tryModuleResolve(id, url, conditionsSet);
8010
+ if (resolved) {
8011
+ break;
8012
+ }
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
8354
8019
  );
8020
+ if (resolved) {
8021
+ break;
8022
+ }
8023
+ }
8024
+ if (resolved) {
8025
+ break;
8355
8026
  }
8356
8027
  }
8028
+ if (resolved) {
8029
+ break;
8030
+ }
8357
8031
  }
8358
- if (bestMatch) {
8359
- const target = (
8360
- /** @type {unknown} */
8361
- exports[bestMatch]
8032
+ if (!resolved) {
8033
+ const error = new Error(
8034
+ `Cannot find module ${id} imported from ${urls.join(", ")}`
8362
8035
  );
8363
- const resolveResult = resolvePackageTarget(
8364
- packageJsonUrl,
8365
- target,
8366
- bestMatchSubpath,
8367
- bestMatch,
8368
- base,
8369
- true,
8370
- false,
8371
- packageSubpath.endsWith("/"),
8372
- conditions
8036
+ error.code = "ERR_MODULE_NOT_FOUND";
8037
+ throw error;
8038
+ }
8039
+ return pathToFileURL(resolved);
8040
+ }
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"
8373
8086
  );
8374
- if (resolveResult === null || resolveResult === void 0) {
8375
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
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"
8126
+ );
8127
+ entries.add(globalInject[0]);
8376
8128
  }
8377
- return resolveResult;
8378
8129
  }
8379
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
8130
+ env.polyfill.forEach((polyfill) => entries.add(polyfill));
8131
+ nodeCompatExternals.forEach((external) => entries.delete(external));
8132
+ return entries;
8380
8133
  }
8381
- function patternKeyCompare(a, b) {
8382
- const aPatternIndex = a.indexOf("*");
8383
- const bPatternIndex = b.indexOf("*");
8384
- const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
8385
- const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
8386
- if (baseLengthA > baseLengthB) return -1;
8387
- if (baseLengthB > baseLengthA) return 1;
8388
- if (aPatternIndex === -1) return 1;
8389
- if (bPatternIndex === -1) return -1;
8390
- if (a.length > b.length) return -1;
8391
- if (b.length > a.length) return 1;
8392
- return 0;
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);
8393
8153
  }
8394
- function packageImportsResolve(name2, base, conditions) {
8395
- if (name2 === "#" || name2.startsWith("#/") || name2.endsWith("/")) {
8396
- const reason = "is not a valid internal imports specifier name";
8397
- throw new ERR_INVALID_MODULE_SPECIFIER(name2, reason, fileURLToPath$1(base));
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);
8398
8161
  }
8399
- let packageJsonUrl;
8400
- const packageConfig = getPackageScopeConfig(base);
8401
- if (packageConfig.exists) {
8402
- packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
8403
- const imports = packageConfig.imports;
8404
- if (imports) {
8405
- if (own.call(imports, name2) && !name2.includes("*")) {
8406
- const resolveResult = resolvePackageTarget(
8407
- packageJsonUrl,
8408
- imports[name2],
8409
- "",
8410
- name2,
8411
- base,
8412
- false,
8413
- true,
8414
- false,
8415
- conditions
8416
- );
8417
- if (resolveResult !== null && resolveResult !== void 0) {
8418
- return resolveResult;
8419
- }
8420
- } else {
8421
- let bestMatch = "";
8422
- let bestMatchSubpath = "";
8423
- const keys = Object.getOwnPropertyNames(imports);
8424
- let i = -1;
8425
- while (++i < keys.length) {
8426
- const key = keys[i];
8427
- const patternIndex = key.indexOf("*");
8428
- if (patternIndex !== -1 && name2.startsWith(key.slice(0, -1))) {
8429
- const patternTrailer = key.slice(patternIndex + 1);
8430
- if (name2.length >= key.length && name2.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
8431
- bestMatch = key;
8432
- bestMatchSubpath = name2.slice(
8433
- patternIndex,
8434
- name2.length - patternTrailer.length
8435
- );
8436
- }
8437
- }
8438
- }
8439
- if (bestMatch) {
8440
- const target = imports[bestMatch];
8441
- const resolveResult = resolvePackageTarget(
8442
- packageJsonUrl,
8443
- target,
8444
- bestMatchSubpath,
8445
- bestMatch,
8446
- base,
8447
- true,
8448
- true,
8449
- false,
8450
- conditions
8451
- );
8452
- if (resolveResult !== null && resolveResult !== void 0) {
8453
- return resolveResult;
8454
- }
8455
- }
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);
8456
8177
  }
8457
8178
  }
8458
8179
  }
8459
- throw importNotDefined(name2, packageJsonUrl, base);
8180
+ return headers;
8460
8181
  }
8461
- function parsePackageName(specifier, base) {
8462
- let separatorIndex = specifier.indexOf("/");
8463
- let validPackageName = true;
8464
- let isScoped = false;
8465
- if (specifier[0] === "@") {
8466
- isScoped = true;
8467
- if (separatorIndex === -1 || specifier.length === 0) {
8468
- validPackageName = false;
8469
- } else {
8470
- separatorIndex = specifier.indexOf("/", separatorIndex + 1);
8182
+ var postfixRE = /[?#].*$/;
8183
+ function cleanUrl(url) {
8184
+ return url.replace(postfixRE, "");
8185
+ }
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));
8196
+ }
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);
8471
8203
  }
8472
8204
  }
8473
- const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
8474
- if (invalidPackageNameRegEx.exec(packageName) !== null) {
8475
- validPackageName = false;
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);
8228
+ }
8229
+ };
8230
+ }
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;
8476
8241
  }
8477
- if (!validPackageName) {
8478
- throw new ERR_INVALID_MODULE_SPECIFIER(
8479
- specifier,
8480
- "is not a valid package name",
8481
- fileURLToPath$1(base)
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"
8253
+ }
8254
+ }
8255
+ );
8256
+ assert3(
8257
+ response.ok,
8258
+ `Failed to initialize module runner, error: ${await response.text()}`
8482
8259
  );
8260
+ const webSocket = response.webSocket;
8261
+ assert3(webSocket, "Failed to establish WebSocket");
8262
+ webSocket.accept();
8263
+ this.#webSocketContainer.webSocket = webSocket;
8483
8264
  }
8484
- const packageSubpath = "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex));
8485
- return { packageName, packageSubpath, isScoped };
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
+ };
8486
8334
  }
8487
- function packageResolve(specifier, base, conditions) {
8488
- if (builtinModules.includes(specifier)) {
8489
- return new URL$1("node:" + specifier);
8490
- }
8491
- const { packageName, packageSubpath, isScoped } = parsePackageName(
8492
- specifier,
8493
- base
8494
- );
8495
- const packageConfig = getPackageScopeConfig(base);
8496
- if (packageConfig.exists) {
8497
- const packageJsonUrl2 = pathToFileURL$1(packageConfig.pjsonPath);
8498
- if (packageConfig.name === packageName && packageConfig.exports !== void 0 && packageConfig.exports !== null) {
8499
- return packageExportsResolve(
8500
- packageJsonUrl2,
8501
- packageSubpath,
8502
- packageConfig,
8503
- base,
8504
- conditions
8505
- );
8506
- }
8335
+ function initRunners(resolvedPluginConfig, viteDevServer, miniflare) {
8336
+ if (resolvedPluginConfig.type === "assets-only") {
8337
+ return;
8507
8338
  }
8508
- let packageJsonUrl = new URL$1(
8509
- "./node_modules/" + packageName + "/package.json",
8510
- 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
+ )
8511
8346
  );
8512
- let packageJsonPath = fileURLToPath$1(packageJsonUrl);
8513
- let lastPath;
8514
- do {
8515
- const stat = tryStatSync(packageJsonPath.slice(0, -13));
8516
- if (!stat || !stat.isDirectory()) {
8517
- lastPath = packageJsonPath;
8518
- packageJsonUrl = new URL$1(
8519
- (isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json",
8520
- 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
+ )
8521
8364
  );
8522
- packageJsonPath = fileURLToPath$1(packageJsonUrl);
8523
- continue;
8524
- }
8525
- const packageConfig2 = read(packageJsonPath, { base, specifier });
8526
- if (packageConfig2.exports !== void 0 && packageConfig2.exports !== null) {
8527
- return packageExportsResolve(
8528
- packageJsonUrl,
8529
- packageSubpath,
8530
- packageConfig2,
8531
- base,
8532
- conditions
8365
+ server.config.logger.info(
8366
+ ` ${colors.green("\u279C")} ${colors.bold("Debug")}: ${colorDebugUrl(`${protocol}//${hostname}:${port}${debuggingPath}`)}`
8533
8367
  );
8534
8368
  }
8535
- if (packageSubpath === ".") {
8536
- return legacyMainResolve(packageJsonUrl, packageConfig2, base);
8537
- }
8538
- return new URL$1(packageSubpath, packageJsonUrl);
8539
- } while (packageJsonPath.length !== lastPath.length);
8540
- throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath$1(base), false);
8369
+ };
8541
8370
  }
8542
- function isRelativeSpecifier(specifier) {
8543
- if (specifier[0] === ".") {
8544
- if (specifier.length === 1 || specifier[1] === "/") return true;
8545
- if (specifier[1] === "." && (specifier.length === 2 || specifier[2] === "/")) {
8546
- return true;
8547
- }
8548
- }
8549
- 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
+ `;
8550
8396
  }
8551
- function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
8552
- if (specifier === "") return false;
8553
- if (specifier[0] === "/") return true;
8554
- 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");
8555
8406
  }
8556
- function moduleResolve(specifier, base, conditions, preserveSymlinks) {
8557
- const protocol = base.protocol;
8558
- const isData = protocol === "data:";
8559
- const isRemote = isData || protocol === "http:" || protocol === "https:";
8560
- let resolved;
8561
- if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
8562
- try {
8563
- resolved = new URL$1(specifier, base);
8564
- } catch (error_) {
8565
- const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8566
- error.cause = error_;
8567
- throw error;
8568
- }
8569
- } else if (protocol === "file:" && specifier[0] === "#") {
8570
- 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));
8571
8448
  } else {
8572
- try {
8573
- resolved = new URL$1(specifier);
8574
- } catch (error_) {
8575
- if (isRemote && !builtinModules.includes(specifier)) {
8576
- const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8577
- error.cause = error_;
8578
- 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 });
8579
8466
  }
8580
- resolved = packageResolve(specifier, base, conditions);
8581
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));
8582
8477
  }
8583
- assert5(resolved !== void 0, "expected to be defined");
8584
- if (resolved.protocol !== "file:") {
8585
- return resolved;
8586
- }
8587
- return finalizeResolution(resolved, base);
8588
8478
  }
8589
- function fileURLToPath2(id) {
8590
- if (typeof id === "string" && !id.startsWith("file://")) {
8591
- 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 {};
8592
8500
  }
8593
- return normalizeSlash(fileURLToPath$1(id));
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
+ };
8594
8515
  }
8595
- function pathToFileURL(id) {
8596
- return pathToFileURL$1(fileURLToPath2(id)).toString();
8516
+ function missingWorkerErrorMessage(workerName) {
8517
+ return `${workerName} does not match a worker name.`;
8597
8518
  }
8598
- function normalizeid(id) {
8599
- if (typeof id !== "string") {
8600
- id = id.toString();
8601
- }
8602
- if (/(node|data|http|https|file):/.test(id)) {
8603
- return id;
8604
- }
8605
- if (BUILTIN_MODULES.has(id)) {
8606
- return "node:" + id;
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
+ }
8531
+ }
8607
8532
  }
8608
- return "file://" + encodeURI(normalizeSlash(id));
8533
+ return workerToWorkerEntrypointNamesMap;
8609
8534
  }
8610
- var DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
8611
- var DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
8612
- var NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
8613
- "ERR_MODULE_NOT_FOUND",
8614
- "ERR_UNSUPPORTED_DIR_IMPORT",
8615
- "MODULE_NOT_FOUND",
8616
- "ERR_PACKAGE_PATH_NOT_EXPORTED"
8617
- ]);
8618
- function _tryModuleResolve(id, url, conditions) {
8619
- try {
8620
- return moduleResolve(id, url, conditions);
8621
- } catch (error) {
8622
- if (!NOT_FOUND_ERRORS.has(error?.code)) {
8623
- throw error;
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
+ }
8624
8560
  }
8625
8561
  }
8562
+ return workerToDurableObjectClassNamesMap;
8626
8563
  }
8627
- function _resolve(id, options = {}) {
8628
- if (typeof id !== "string") {
8629
- if (id instanceof URL) {
8630
- id = fileURLToPath2(id);
8631
- } else {
8632
- throw new TypeError("input must be a `string` or `URL`");
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
+ }
8633
8583
  }
8634
8584
  }
8635
- if (/(node|data|http|https):/.test(id)) {
8636
- return id;
8637
- }
8638
- if (BUILTIN_MODULES.has(id)) {
8639
- return "node:" + id;
8640
- }
8641
- if (id.startsWith("file://")) {
8642
- 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;
8643
8595
  }
8644
- if (isAbsolute(id)) {
8645
- try {
8646
- const stat = statSync2(id);
8647
- if (stat.isFile()) {
8648
- 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 } : {}
8649
8631
  }
8650
- } catch (error) {
8651
- if (error?.code !== "ENOENT") {
8652
- 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
+ }
8653
8678
  }
8654
8679
  }
8655
- }
8656
- const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
8657
- const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString())));
8658
- if (_urls.length === 0) {
8659
- _urls.push(new URL(pathToFileURL(process.cwd())));
8660
- }
8661
- const urls = [..._urls];
8662
- for (const url of _urls) {
8663
- if (url.protocol === "file:") {
8664
- urls.push(
8665
- new URL("./", url),
8666
- // If url is directory
8667
- new URL(joinURL(url.pathname, "_index.js"), url),
8668
- // TODO: Remove in next major version?
8669
- 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
8670
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
+ };
8671
8727
  }
8672
- }
8673
- let resolved;
8674
- for (const url of urls) {
8675
- resolved = _tryModuleResolve(id, url, conditionsSet);
8676
- if (resolved) {
8677
- break;
8678
- }
8679
- for (const prefix of ["", "/index"]) {
8680
- for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
8681
- resolved = _tryModuleResolve(
8682
- joinURL(id, prefix) + extension,
8683
- url,
8684
- 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?`
8685
8838
  );
8686
- if (resolved) {
8687
- break;
8688
- }
8689
8839
  }
8690
- if (resolved) {
8691
- 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
+ }
8692
8853
  }
8693
8854
  }
8694
- if (resolved) {
8695
- break;
8696
- }
8697
- }
8698
- if (!resolved) {
8699
- const error = new Error(
8700
- `Cannot find module ${id} imported from ${urls.join(", ")}`
8701
- );
8702
- error.code = "ERR_MODULE_NOT_FOUND";
8703
- throw error;
8704
- }
8705
- return pathToFileURL(resolved);
8706
- }
8707
- function resolveSync(id, options) {
8708
- return _resolve(id, options);
8709
- }
8710
- function resolvePathSync(id, options) {
8711
- return fileURLToPath2(resolveSync(id, options));
8855
+ };
8712
8856
  }
8713
-
8714
- // src/node-js-compat.ts
8715
- import { defineEnv } from "unenv";
8716
- var { env } = defineEnv({
8717
- nodeCompat: true,
8718
- presets: [cloudflare]
8719
- });
8720
- var nodeCompatExternals = new Set(env.external);
8721
- var nodeCompatEntries = getNodeCompatEntries();
8722
- function isNodeCompat(workerConfig) {
8723
- if (workerConfig === void 0) {
8724
- return false;
8725
- }
8726
- const nodeCompatMode = getNodeCompat(
8727
- workerConfig.compatibility_date,
8728
- workerConfig.compatibility_flags ?? []
8729
- ).mode;
8730
- if (nodeCompatMode === "v2") {
8731
- return true;
8732
- }
8733
- if (nodeCompatMode === "legacy") {
8734
- throw new Error(
8735
- "Unsupported Node.js compat mode (legacy). Remove the `node_compat` setting and add the `nodejs_compat` flag instead."
8736
- );
8737
- }
8738
- if (nodeCompatMode === "v1") {
8739
- throw new Error(
8740
- `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`
8741
- );
8742
- }
8743
- return false;
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);
8861
+ return {
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
+ ]
8875
+ };
8744
8876
  }
8745
- function injectGlobalCode(id, code) {
8746
- const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
8747
- if (typeof globalInject === "string") {
8748
- const moduleSpecifier2 = globalInject;
8749
- return `import var_${globalName} from "${moduleSpecifier2}";
8750
- globalThis.${globalName} = var_${globalName};
8751
- `;
8752
- }
8753
- const [moduleSpecifier, exportName] = globalInject;
8754
- assert6(
8755
- moduleSpecifier !== void 0,
8756
- "Expected moduleSpecifier to be defined"
8757
- );
8758
- assert6(exportName !== void 0, "Expected exportName to be defined");
8759
- return `import var_${globalName} from "${moduleSpecifier}";
8760
- globalThis.${globalName} = var_${globalName}.${exportName};
8761
- `;
8762
- }).join("\n");
8763
- const modified = new MagicString(code);
8764
- modified.prepend(injectedCode);
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
+ ];
8892
+ });
8893
+ const logger = new ViteMiniflareLogger(resolvedViteConfig);
8765
8894
  return {
8766
- code: modified.toString(),
8767
- map: modified.generateMap({ hires: "boundary", source: id })
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
8768
8907
  };
8769
8908
  }
8770
- function resolveNodeJSImport(source) {
8771
- const alias = env.alias[source];
8772
- if (alias) {
8773
- return {
8774
- unresolved: alias,
8775
- resolved: resolvePathSync(alias, { url: import.meta.url })
8776
- };
8777
- }
8778
- if (nodeCompatEntries.has(source)) {
8779
- return {
8780
- unresolved: source,
8781
- resolved: resolvePathSync(source, { url: import.meta.url })
8782
- };
8909
+ var ViteMiniflareLogger = class extends Log {
8910
+ logger;
8911
+ constructor(config) {
8912
+ super(miniflareLogLevelFromViteLogLevel(config.logLevel));
8913
+ this.logger = config.logger;
8783
8914
  }
8784
- }
8785
- function getNodeCompatEntries() {
8786
- const entries = new Set(Object.values(env.alias));
8787
- for (const globalInject of Object.values(env.inject)) {
8788
- if (typeof globalInject === "string") {
8789
- entries.add(globalInject);
8790
- } else {
8791
- assert6(
8792
- globalInject[0] !== void 0,
8793
- "Expected first element of globalInject to be defined"
8794
- );
8795
- entries.add(globalInject[0]);
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);
8796
8926
  }
8797
8927
  }
8798
- nodeCompatExternals.forEach((external) => entries.delete(external));
8799
- return entries;
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
+ }
8800
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)
9108
+ );
9109
+ }
9110
+ if (!config.compatibility_date) {
9111
+ throw new Error(
9112
+ missingFieldErrorMessage(`'compatibility_date`, configPath, env2)
8997
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,8 +9244,9 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9109
9244
  }
9110
9245
 
9111
9246
  // src/websockets.ts
9247
+ import { coupleWebSocket } from "miniflare";
9112
9248
  import { WebSocketServer } from "ws";
9113
- function handleWebSocket(httpServer, fetcher, logger) {
9249
+ function handleWebSocket(httpServer, fetcher) {
9114
9250
  const nodeWebSocket = new WebSocketServer({ noServer: true });
9115
9251
  httpServer.on(
9116
9252
  "upgrade",
@@ -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" };
@@ -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
  );
@@ -9250,6 +9363,9 @@ function cloudflare2(pluginConfig = {}) {
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,8 +9612,8 @@ function cloudflare2(pluginConfig = {}) {
9465
9612
  apply(_config, env2) {
9466
9613
  return !env2.isPreview;
9467
9614
  },
9468
- configEnvironment(name2) {
9469
- if (isNodeCompat(getWorkerConfig2(name2))) {
9615
+ configEnvironment(name) {
9616
+ if (isNodeCompat(getWorkerConfig2(name))) {
9470
9617
  return {
9471
9618
  resolve: {
9472
9619
  builtins: [...nodeCompatExternals]
@@ -9505,7 +9652,7 @@ function cloudflare2(pluginConfig = {}) {
9505
9652
  return this.resolve(source, importer, options);
9506
9653
  }
9507
9654
  if (this.environment.mode === "dev") {
9508
- assert9(
9655
+ assert8(
9509
9656
  this.environment.depsOptimizer,
9510
9657
  "depsOptimizer is required in dev mode"
9511
9658
  );
@@ -9519,16 +9666,63 @@ function cloudflare2(pluginConfig = {}) {
9519
9666
  },
9520
9667
  async transform(code, id) {
9521
9668
  const workerConfig = getWorkerConfig2(this.environment.name);
9522
- assert9(workerConfig, "Expected a worker config");
9669
+ assert8(workerConfig, "Expected a worker config");
9523
9670
  const resolvedId = await this.resolve(workerConfig.main);
9524
9671
  if (id === resolvedId?.id) {
9525
9672
  return injectGlobalCode(id, code);
9526
9673
  }
9527
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
+ }
9528
9722
  }
9529
9723
  ];
9530
9724
  function getWorkerConfig2(environmentName) {
9531
- assert9(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
9725
+ assert8(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
9532
9726
  return resolvedPluginConfig.type !== "assets-only" ? resolvedPluginConfig.workers[environmentName] : void 0;
9533
9727
  }
9534
9728
  }
@@ -9543,9 +9737,6 @@ function getDotDevDotVarsContent(configPath, cloudflareEnv) {
9543
9737
  }
9544
9738
  return null;
9545
9739
  }
9546
- function createModuleReference(type, id) {
9547
- return `__CLOUDFLARE_MODULE__${type}__${id}__`;
9548
- }
9549
9740
  export {
9550
9741
  cloudflare2 as cloudflare
9551
9742
  };