@cloudflare/vite-plugin 0.0.0-8d6d7224b → 0.0.0-8eb206544

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 assert7 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,828 +1074,127 @@ 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
+ ];
1090
1086
 
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);
1087
+ // src/additional-modules.ts
1088
+ var moduleRules = [
1089
+ { type: "CompiledWasm", extensions: [".wasm", ".wasm?module"] },
1090
+ { type: "Data", extensions: [".bin"] },
1091
+ { type: "Text", extensions: [".txt", ".html"] }
1092
+ ];
1093
+ function matchAdditionalModule(source) {
1094
+ for (const rule of moduleRules) {
1095
+ for (const extension of rule.extensions) {
1096
+ if (source.endsWith(extension)) {
1097
+ return rule.type;
1115
1098
  }
1116
1099
  }
1117
1100
  }
1118
- return headers;
1101
+ return null;
1102
+ }
1103
+ function createModuleReference(type, id) {
1104
+ return `__CLOUDFLARE_MODULE__${type}__${id}__`;
1119
1105
  }
1120
1106
 
1121
1107
  // 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));
1108
+ import assert3 from "node:assert";
1109
+ import * as vite2 from "vite";
1110
+
1111
+ // src/node-js-compat.ts
1112
+ import assert2 from "node:assert";
1113
+ import { cloudflare } from "@cloudflare/unenv-preset";
1114
+ import { getNodeCompat } from "miniflare";
1115
+
1116
+ // ../../node_modules/.pnpm/acorn@8.14.0/node_modules/acorn/dist/acorn.mjs
1117
+ 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];
1118
+ 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];
1119
+ 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";
1120
+ 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";
1121
+ var reservedWords = {
1122
+ 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",
1123
+ 5: "class enum extends super const export import",
1124
+ 6: "enum",
1125
+ strict: "implements interface let package private protected public static yield",
1126
+ strictBind: "eval arguments"
1127
+ };
1128
+ 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";
1129
+ var keywords$1 = {
1130
+ 5: ecma5AndLessKeywords,
1131
+ "5module": ecma5AndLessKeywords + " export import",
1132
+ 6: ecma5AndLessKeywords + " const class extends export import super"
1133
+ };
1134
+ var keywordRelationalOperator = /^in(stanceof)?$/;
1135
+ var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
1136
+ var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
1137
+ function isInAstralSet(code, set) {
1138
+ var pos = 65536;
1139
+ for (var i = 0; i < set.length; i += 2) {
1140
+ pos += set[i];
1141
+ if (pos > code) {
1142
+ return false;
1130
1143
  }
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);
1144
+ pos += set[i + 1];
1145
+ if (pos >= code) {
1146
+ return true;
1137
1147
  }
1138
1148
  }
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
- };
1149
+ return false;
1164
1150
  }
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;
1151
+ function isIdentifierStart(code, astral) {
1152
+ if (code < 65) {
1153
+ return code === 36;
1175
1154
  }
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;
1155
+ if (code < 91) {
1156
+ return true;
1194
1157
  }
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;
1158
+ if (code < 97) {
1159
+ return code === 95;
1265
1160
  }
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
- );
1161
+ if (code < 123) {
1162
+ return true;
1163
+ }
1164
+ if (code <= 65535) {
1165
+ return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code));
1166
+ }
1167
+ if (astral === false) {
1168
+ return false;
1169
+ }
1170
+ return isInAstralSet(code, astralIdentifierStartCodes);
1274
1171
  }
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 { globSync } from "tinyglobby";
1374
- import "vite";
1375
- import {
1376
- unstable_getMiniflareWorkerOptions,
1377
- unstable_readConfig
1378
- } from "wrangler";
1379
- function getPersistence(root, persistState) {
1380
- if (persistState === false) {
1381
- return {};
1382
- }
1383
- const defaultPersistPath = ".wrangler/state";
1384
- const persistPath = path3.resolve(
1385
- root,
1386
- typeof persistState === "object" ? persistState.path : defaultPersistPath,
1387
- "v3"
1388
- );
1389
- return {
1390
- cachePersist: path3.join(persistPath, "cache"),
1391
- d1Persist: path3.join(persistPath, "d1"),
1392
- durableObjectsPersist: path3.join(persistPath, "do"),
1393
- kvPersist: path3.join(persistPath, "kv"),
1394
- r2Persist: path3.join(persistPath, "r2"),
1395
- workflowsPersist: path3.join(persistPath, "workflows")
1396
- };
1397
- }
1398
- function missingWorkerErrorMessage(workerName) {
1399
- return `${workerName} does not match a worker name.`;
1400
- }
1401
- function getWorkerToWorkerEntrypointNamesMap(workers) {
1402
- const workerToWorkerEntrypointNamesMap = new Map(
1403
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1404
- );
1405
- for (const worker of workers) {
1406
- for (const value of Object.values(worker.serviceBindings ?? {})) {
1407
- if (typeof value === "object" && "name" in value && value.entrypoint !== void 0 && value.entrypoint !== "default") {
1408
- const targetWorkerName = value.name === kCurrentWorker ? worker.name : value.name;
1409
- const entrypointNames = workerToWorkerEntrypointNamesMap.get(targetWorkerName);
1410
- assert4(entrypointNames, missingWorkerErrorMessage(targetWorkerName));
1411
- entrypointNames.add(value.entrypoint);
1412
- }
1413
- }
1414
- }
1415
- return workerToWorkerEntrypointNamesMap;
1416
- }
1417
- function getWorkerToDurableObjectClassNamesMap(workers) {
1418
- const workerToDurableObjectClassNamesMap = new Map(
1419
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1420
- );
1421
- for (const worker of workers) {
1422
- for (const value of Object.values(worker.durableObjects ?? {})) {
1423
- if (typeof value === "string") {
1424
- const classNames = workerToDurableObjectClassNamesMap.get(worker.name);
1425
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1426
- classNames.add(value);
1427
- } else if (typeof value === "object") {
1428
- if (value.scriptName) {
1429
- const classNames = workerToDurableObjectClassNamesMap.get(
1430
- value.scriptName
1431
- );
1432
- assert4(classNames, missingWorkerErrorMessage(value.scriptName));
1433
- classNames.add(value.className);
1434
- } else {
1435
- const classNames = workerToDurableObjectClassNamesMap.get(
1436
- worker.name
1437
- );
1438
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1439
- classNames.add(value.className);
1440
- }
1441
- }
1442
- }
1443
- }
1444
- return workerToDurableObjectClassNamesMap;
1445
- }
1446
- function getWorkerToWorkflowEntrypointClassNamesMap(workers) {
1447
- const workerToWorkflowEntrypointClassNamesMap = new Map(
1448
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1449
- );
1450
- for (const worker of workers) {
1451
- for (const value of Object.values(worker.workflows ?? {})) {
1452
- if (value.scriptName) {
1453
- const classNames = workerToWorkflowEntrypointClassNamesMap.get(
1454
- value.scriptName
1455
- );
1456
- assert4(classNames, missingWorkerErrorMessage(value.scriptName));
1457
- classNames.add(value.className);
1458
- } else {
1459
- const classNames = workerToWorkflowEntrypointClassNamesMap.get(
1460
- worker.name
1461
- );
1462
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1463
- classNames.add(value.className);
1464
- }
1465
- }
1466
- }
1467
- return workerToWorkflowEntrypointClassNamesMap;
1468
- }
1469
- var miniflareModulesRoot = process.platform === "win32" ? "Z:\\" : "/";
1470
- var ROUTER_WORKER_PATH = "./asset-workers/router-worker.js";
1471
- var ASSET_WORKER_PATH = "./asset-workers/asset-worker.js";
1472
- var WRAPPER_PATH = "__VITE_WORKER_ENTRY__";
1473
- var RUNNER_PATH = "./runner-worker/index.js";
1474
- function getEntryWorkerConfig(resolvedPluginConfig) {
1475
- if (resolvedPluginConfig.type === "assets-only") {
1476
- return;
1477
- }
1478
- return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
1479
- }
1480
- function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1481
- const resolvedViteConfig = viteDevServer.config;
1482
- const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
1483
- const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
1484
- const assetWorkers = [
1485
- {
1486
- name: ROUTER_WORKER_NAME,
1487
- compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
1488
- modulesRoot: miniflareModulesRoot,
1489
- modules: [
1490
- {
1491
- type: "ESModule",
1492
- path: path3.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
1493
- contents: fs2.readFileSync(
1494
- fileURLToPath(new URL(ROUTER_WORKER_PATH, import.meta.url))
1495
- )
1496
- }
1497
- ],
1498
- bindings: {
1499
- CONFIG: {
1500
- has_user_worker: resolvedPluginConfig.type === "workers"
1501
- }
1502
- },
1503
- serviceBindings: {
1504
- ASSET_WORKER: ASSET_WORKER_NAME,
1505
- ...entryWorkerConfig ? { USER_WORKER: entryWorkerConfig.name } : {}
1506
- }
1507
- },
1508
- {
1509
- name: ASSET_WORKER_NAME,
1510
- compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
1511
- modulesRoot: miniflareModulesRoot,
1512
- modules: [
1513
- {
1514
- type: "ESModule",
1515
- path: path3.join(miniflareModulesRoot, ASSET_WORKER_PATH),
1516
- contents: fs2.readFileSync(
1517
- fileURLToPath(new URL(ASSET_WORKER_PATH, import.meta.url))
1518
- )
1519
- }
1520
- ],
1521
- bindings: {
1522
- CONFIG: {
1523
- ...assetsConfig?.html_handling ? { html_handling: assetsConfig.html_handling } : {},
1524
- ...assetsConfig?.not_found_handling ? { not_found_handling: assetsConfig.not_found_handling } : {}
1525
- }
1526
- },
1527
- serviceBindings: {
1528
- __VITE_ASSET_EXISTS__: async (request) => {
1529
- const { pathname } = new URL(request.url);
1530
- const filePath = path3.join(resolvedViteConfig.root, pathname);
1531
- let exists;
1532
- try {
1533
- exists = fs2.statSync(filePath).isFile();
1534
- } catch (error) {
1535
- exists = false;
1536
- }
1537
- return MiniflareResponse.json(exists);
1538
- },
1539
- __VITE_FETCH_ASSET__: async (request) => {
1540
- const { pathname } = new URL(request.url);
1541
- const filePath = path3.join(resolvedViteConfig.root, pathname);
1542
- try {
1543
- let html = await fsp.readFile(filePath, "utf-8");
1544
- html = await viteDevServer.transformIndexHtml(pathname, html);
1545
- return new MiniflareResponse(html, {
1546
- headers: { "Content-Type": "text/html" }
1547
- });
1548
- } catch (error) {
1549
- throw new Error(`Unexpected error. Failed to load ${pathname}`);
1550
- }
1551
- }
1552
- }
1553
- }
1554
- ];
1555
- const workersFromConfig = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1556
- ([environmentName, workerConfig]) => {
1557
- const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
1558
- {
1559
- ...workerConfig,
1560
- assets: void 0
1561
- },
1562
- resolvedPluginConfig.cloudflareEnv
1563
- );
1564
- const { externalWorkers: externalWorkers2 } = miniflareWorkerOptions;
1565
- const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1566
- return {
1567
- externalWorkers: externalWorkers2,
1568
- worker: {
1569
- ...workerOptions,
1570
- name: workerOptions.name ?? workerConfig.name,
1571
- modulesRoot: miniflareModulesRoot,
1572
- unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
1573
- bindings: {
1574
- ...workerOptions.bindings,
1575
- __VITE_ROOT__: resolvedViteConfig.root,
1576
- __VITE_ENTRY_PATH__: workerConfig.main
1577
- },
1578
- serviceBindings: {
1579
- ...workerOptions.serviceBindings,
1580
- ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
1581
- [workerConfig.assets.binding]: ASSET_WORKER_NAME
1582
- } : {},
1583
- __VITE_INVOKE_MODULE__: async (request) => {
1584
- const payload = await request.json();
1585
- const invokePayloadData = payload.data;
1586
- assert4(
1587
- invokePayloadData.name === "fetchModule",
1588
- `Invalid invoke event: ${invokePayloadData.name}`
1589
- );
1590
- const [moduleId] = invokePayloadData.data;
1591
- const moduleRE = new RegExp(MODULE_PATTERN);
1592
- const shouldExternalize = (
1593
- // Worker modules (CompiledWasm, Text, Data)
1594
- moduleRE.test(moduleId)
1595
- );
1596
- if (shouldExternalize) {
1597
- const result2 = {
1598
- externalize: moduleId,
1599
- type: "module"
1600
- };
1601
- return MiniflareResponse.json({ result: result2 });
1602
- }
1603
- const devEnvironment = viteDevServer.environments[environmentName];
1604
- const result = await devEnvironment.hot.handleInvoke(payload);
1605
- return MiniflareResponse.json(result);
1606
- }
1607
- }
1608
- }
1609
- };
1610
- }
1611
- ) : [];
1612
- const userWorkers = workersFromConfig.map((options) => options.worker);
1613
- const externalWorkers = workersFromConfig.flatMap(
1614
- (options) => options.externalWorkers
1615
- );
1616
- const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
1617
- const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
1618
- const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
1619
- const logger = new ViteMiniflareLogger(resolvedViteConfig);
1620
- return {
1621
- log: logger,
1622
- handleRuntimeStdio(stdout, stderr) {
1623
- const decoder = new TextDecoder();
1624
- stdout.forEach((data2) => logger.info(decoder.decode(data2)));
1625
- stderr.forEach(
1626
- (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
1627
- );
1628
- },
1629
- ...getPersistence(
1630
- resolvedViteConfig.root,
1631
- resolvedPluginConfig.persistState
1632
- ),
1633
- workers: [
1634
- ...assetWorkers,
1635
- ...externalWorkers,
1636
- ...userWorkers.map((workerOptions) => {
1637
- const wrappers = [
1638
- `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
1639
- `export default createWorkerEntrypointWrapper('default');`
1640
- ];
1641
- const workerEntrypointNames = workerToWorkerEntrypointNamesMap.get(
1642
- workerOptions.name
1643
- );
1644
- assert4(
1645
- workerEntrypointNames,
1646
- `WorkerEntrypoint names not found for worker ${workerOptions.name}`
1647
- );
1648
- for (const entrypointName of [...workerEntrypointNames].sort()) {
1649
- wrappers.push(
1650
- `export const ${entrypointName} = createWorkerEntrypointWrapper('${entrypointName}');`
1651
- );
1652
- }
1653
- const durableObjectClassNames = workerToDurableObjectClassNamesMap.get(
1654
- workerOptions.name
1655
- );
1656
- assert4(
1657
- durableObjectClassNames,
1658
- `DurableObject class names not found for worker ${workerOptions.name}`
1659
- );
1660
- for (const className of [...durableObjectClassNames].sort()) {
1661
- wrappers.push(
1662
- `export const ${className} = createDurableObjectWrapper('${className}');`
1663
- );
1664
- }
1665
- const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
1666
- assert4(
1667
- workflowEntrypointClassNames,
1668
- `WorkflowEntrypoint class names not found for worker: ${workerOptions.name}`
1669
- );
1670
- for (const className of [...workflowEntrypointClassNames].sort()) {
1671
- wrappers.push(
1672
- `export const ${className} = createWorkflowEntrypointWrapper('${className}');`
1673
- );
1674
- }
1675
- return {
1676
- ...workerOptions,
1677
- modules: [
1678
- {
1679
- type: "ESModule",
1680
- path: path3.join(miniflareModulesRoot, WRAPPER_PATH),
1681
- contents: wrappers.join("\n")
1682
- },
1683
- {
1684
- type: "ESModule",
1685
- path: path3.join(miniflareModulesRoot, RUNNER_PATH),
1686
- contents: fs2.readFileSync(
1687
- fileURLToPath(new URL(RUNNER_PATH, import.meta.url))
1688
- )
1689
- }
1690
- ],
1691
- unsafeUseModuleFallbackService: true
1692
- };
1693
- })
1694
- ],
1695
- unsafeModuleFallbackService(request) {
1696
- const url = new URL(request.url);
1697
- const rawSpecifier = url.searchParams.get("rawSpecifier");
1698
- assert4(
1699
- rawSpecifier,
1700
- `Unexpected error: no specifier in request to module fallback service.`
1701
- );
1702
- const moduleRE = new RegExp(MODULE_PATTERN);
1703
- const match = moduleRE.exec(rawSpecifier);
1704
- assert4(match, `Unexpected error: no match for module: ${rawSpecifier}.`);
1705
- const [full, moduleType, modulePath] = match;
1706
- assert4(
1707
- modulePath,
1708
- `Unexpected error: module path not found in reference: ${full}.`
1709
- );
1710
- let source;
1711
- try {
1712
- source = fs2.readFileSync(modulePath);
1713
- } catch (error) {
1714
- throw new Error(
1715
- `Import "${modulePath}" not found. Does the file exist?`
1716
- );
1717
- }
1718
- return MiniflareResponse.json({
1719
- // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
1720
- wasm: Array.from(source)
1721
- });
1722
- }
1723
- };
1724
- }
1725
- function getPreviewModules(main, modulesRules) {
1726
- assert4(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
1727
- const rootPath = path3.dirname(main);
1728
- const entryPath = path3.basename(main);
1729
- return {
1730
- rootPath,
1731
- modules: [
1732
- {
1733
- type: "ESModule",
1734
- path: entryPath
1735
- },
1736
- ...modulesRules.flatMap(
1737
- ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path8) => ({
1738
- type,
1739
- path: path8
1740
- }))
1741
- )
1742
- ]
1743
- };
1744
- }
1745
- function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
1746
- const resolvedViteConfig = vitePreviewServer.config;
1747
- const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
1748
- const workerConfigs = configPaths.map(
1749
- (configPath) => unstable_readConfig({ config: configPath })
1750
- );
1751
- const workers = workerConfigs.flatMap((config) => {
1752
- const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
1753
- const { externalWorkers } = miniflareWorkerOptions;
1754
- const { ratelimits, modulesRules, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1755
- return [
1756
- {
1757
- ...workerOptions,
1758
- name: workerOptions.name ?? config.name,
1759
- ...miniflareWorkerOptions.main ? getPreviewModules(miniflareWorkerOptions.main, modulesRules) : { modules: true, script: "" }
1760
- },
1761
- ...externalWorkers
1762
- ];
1763
- });
1764
- const logger = new ViteMiniflareLogger(resolvedViteConfig);
1765
- return {
1766
- log: logger,
1767
- handleRuntimeStdio(stdout, stderr) {
1768
- const decoder = new TextDecoder();
1769
- stdout.forEach((data2) => logger.info(decoder.decode(data2)));
1770
- stderr.forEach(
1771
- (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
1772
- );
1773
- },
1774
- ...getPersistence(resolvedViteConfig.root, persistState),
1775
- workers
1776
- };
1777
- }
1778
- var ViteMiniflareLogger = class extends Log {
1779
- logger;
1780
- constructor(config) {
1781
- super(miniflareLogLevelFromViteLogLevel(config.logLevel));
1782
- this.logger = config.logger;
1783
- }
1784
- logWithLevel(level, message) {
1785
- if (/^Ready on http/.test(message)) {
1786
- level = LogLevel.DEBUG;
1787
- }
1788
- switch (level) {
1789
- case LogLevel.ERROR:
1790
- return this.logger.error(message);
1791
- case LogLevel.WARN:
1792
- return this.logger.warn(message);
1793
- case LogLevel.INFO:
1794
- return this.logger.info(message);
1795
- }
1796
- }
1797
- };
1798
- function miniflareLogLevelFromViteLogLevel(level = "info") {
1799
- switch (level) {
1800
- case "error":
1801
- return LogLevel.ERROR;
1802
- case "warn":
1803
- return LogLevel.WARN;
1804
- case "info":
1805
- return LogLevel.INFO;
1806
- case "silent":
1807
- return LogLevel.NONE;
1808
- }
1809
- }
1810
-
1811
- // src/node-js-compat.ts
1812
- import assert6 from "node:assert";
1813
- import { cloudflare } from "@cloudflare/unenv-preset";
1814
- import { getNodeCompat } from "miniflare";
1815
-
1816
- // ../../node_modules/.pnpm/acorn@8.14.0/node_modules/acorn/dist/acorn.mjs
1817
- 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];
1818
- 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];
1819
- 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";
1820
- 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";
1821
- var reservedWords = {
1822
- 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",
1823
- 5: "class enum extends super const export import",
1824
- 6: "enum",
1825
- strict: "implements interface let package private protected public static yield",
1826
- strictBind: "eval arguments"
1827
- };
1828
- 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";
1829
- var keywords$1 = {
1830
- 5: ecma5AndLessKeywords,
1831
- "5module": ecma5AndLessKeywords + " export import",
1832
- 6: ecma5AndLessKeywords + " const class extends export import super"
1833
- };
1834
- var keywordRelationalOperator = /^in(stanceof)?$/;
1835
- var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
1836
- var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
1837
- function isInAstralSet(code, set) {
1838
- var pos = 65536;
1839
- for (var i = 0; i < set.length; i += 2) {
1840
- pos += set[i];
1841
- if (pos > code) {
1842
- return false;
1843
- }
1844
- pos += set[i + 1];
1845
- if (pos >= code) {
1846
- return true;
1847
- }
1848
- }
1849
- return false;
1850
- }
1851
- function isIdentifierStart(code, astral) {
1852
- if (code < 65) {
1853
- return code === 36;
1854
- }
1855
- if (code < 91) {
1856
- return true;
1857
- }
1858
- if (code < 97) {
1859
- return code === 95;
1860
- }
1861
- if (code < 123) {
1862
- return true;
1863
- }
1864
- if (code <= 65535) {
1865
- return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code));
1866
- }
1867
- if (astral === false) {
1868
- return false;
1869
- }
1870
- return isInAstralSet(code, astralIdentifierStartCodes);
1871
- }
1872
- function isIdentifierChar(code, astral) {
1873
- if (code < 48) {
1874
- return code === 36;
1875
- }
1876
- if (code < 58) {
1877
- return true;
1878
- }
1879
- if (code < 65) {
1880
- return false;
1881
- }
1882
- if (code < 91) {
1883
- return true;
1884
- }
1885
- if (code < 97) {
1886
- return code === 95;
1887
- }
1888
- if (code < 123) {
1889
- return true;
1890
- }
1891
- if (code <= 65535) {
1892
- return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code));
1893
- }
1894
- if (astral === false) {
1895
- return false;
1896
- }
1897
- return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
1172
+ function isIdentifierChar(code, astral) {
1173
+ if (code < 48) {
1174
+ return code === 36;
1175
+ }
1176
+ if (code < 58) {
1177
+ return true;
1178
+ }
1179
+ if (code < 65) {
1180
+ return false;
1181
+ }
1182
+ if (code < 91) {
1183
+ return true;
1184
+ }
1185
+ if (code < 97) {
1186
+ return code === 95;
1187
+ }
1188
+ if (code < 123) {
1189
+ return true;
1190
+ }
1191
+ if (code <= 65535) {
1192
+ return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code));
1193
+ }
1194
+ if (astral === false) {
1195
+ return false;
1196
+ }
1197
+ return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
1898
1198
  }
1899
1199
  var TokenType = function TokenType2(label, conf) {
1900
1200
  if (conf === void 0) conf = {};
@@ -1909,16 +1209,16 @@ var TokenType = function TokenType2(label, conf) {
1909
1209
  this.binop = conf.binop || null;
1910
1210
  this.updateContext = null;
1911
1211
  };
1912
- function binop(name2, prec) {
1913
- return new TokenType(name2, { beforeExpr: true, binop: prec });
1212
+ function binop(name, prec) {
1213
+ return new TokenType(name, { beforeExpr: true, binop: prec });
1914
1214
  }
1915
1215
  var beforeExpr = { beforeExpr: true };
1916
1216
  var startsExpr = { startsExpr: true };
1917
1217
  var keywords = {};
1918
- function kw(name2, options) {
1218
+ function kw(name, options) {
1919
1219
  if (options === void 0) options = {};
1920
- options.keyword = name2;
1921
- return keywords[name2] = new TokenType(name2, options);
1220
+ options.keyword = name;
1221
+ return keywords[name] = new TokenType(name, options);
1922
1222
  }
1923
1223
  var types$1 = {
1924
1224
  num: new TokenType("num", startsExpr),
@@ -2395,18 +1695,18 @@ pp$9.eat = function(type) {
2395
1695
  return false;
2396
1696
  }
2397
1697
  };
2398
- pp$9.isContextual = function(name2) {
2399
- return this.type === types$1.name && this.value === name2 && !this.containsEsc;
1698
+ pp$9.isContextual = function(name) {
1699
+ return this.type === types$1.name && this.value === name && !this.containsEsc;
2400
1700
  };
2401
- pp$9.eatContextual = function(name2) {
2402
- if (!this.isContextual(name2)) {
1701
+ pp$9.eatContextual = function(name) {
1702
+ if (!this.isContextual(name)) {
2403
1703
  return false;
2404
1704
  }
2405
1705
  this.next();
2406
1706
  return true;
2407
1707
  };
2408
- pp$9.expectContextual = function(name2) {
2409
- if (!this.eatContextual(name2)) {
1708
+ pp$9.expectContextual = function(name) {
1709
+ if (!this.eatContextual(name)) {
2410
1710
  this.unexpected();
2411
1711
  }
2412
1712
  };
@@ -2500,8 +1800,8 @@ pp$8.parseTopLevel = function(node) {
2500
1800
  }
2501
1801
  if (this.inModule) {
2502
1802
  for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) {
2503
- var name2 = list[i];
2504
- this.raiseRecoverable(this.undefinedExports[name2].start, "Export '" + name2 + "' is not defined");
1803
+ var name = list[i];
1804
+ this.raiseRecoverable(this.undefinedExports[name].start, "Export '" + name + "' is not defined");
2505
1805
  }
2506
1806
  }
2507
1807
  this.adaptDirectivePrologue(node.body);
@@ -3244,26 +2544,26 @@ pp$8.exitClassBody = function() {
3244
2544
  }
3245
2545
  };
3246
2546
  function isPrivateNameConflicted(privateNameMap, element) {
3247
- var name2 = element.key.name;
3248
- var curr = privateNameMap[name2];
2547
+ var name = element.key.name;
2548
+ var curr = privateNameMap[name];
3249
2549
  var next = "true";
3250
2550
  if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
3251
2551
  next = (element.static ? "s" : "i") + element.kind;
3252
2552
  }
3253
2553
  if (curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget") {
3254
- privateNameMap[name2] = "true";
2554
+ privateNameMap[name] = "true";
3255
2555
  return false;
3256
2556
  } else if (!curr) {
3257
- privateNameMap[name2] = next;
2557
+ privateNameMap[name] = next;
3258
2558
  return false;
3259
2559
  } else {
3260
2560
  return true;
3261
2561
  }
3262
2562
  }
3263
- function checkKeyName(node, name2) {
2563
+ function checkKeyName(node, name) {
3264
2564
  var computed = node.computed;
3265
2565
  var key = node.key;
3266
- return !computed && (key.type === "Identifier" && key.name === name2 || key.type === "Literal" && key.value === name2);
2566
+ return !computed && (key.type === "Identifier" && key.name === name || key.type === "Literal" && key.value === name);
3267
2567
  }
3268
2568
  pp$8.parseExportAllDeclaration = function(node, exports) {
3269
2569
  if (this.options.ecmaVersion >= 11) {
@@ -3351,17 +2651,17 @@ pp$8.parseExportDefaultDeclaration = function() {
3351
2651
  return declaration;
3352
2652
  }
3353
2653
  };
3354
- pp$8.checkExport = function(exports, name2, pos) {
2654
+ pp$8.checkExport = function(exports, name, pos) {
3355
2655
  if (!exports) {
3356
2656
  return;
3357
2657
  }
3358
- if (typeof name2 !== "string") {
3359
- name2 = name2.type === "Identifier" ? name2.name : name2.value;
2658
+ if (typeof name !== "string") {
2659
+ name = name.type === "Identifier" ? name.name : name.value;
3360
2660
  }
3361
- if (hasOwn(exports, name2)) {
3362
- this.raiseRecoverable(pos, "Duplicate export '" + name2 + "'");
2661
+ if (hasOwn(exports, name)) {
2662
+ this.raiseRecoverable(pos, "Duplicate export '" + name + "'");
3363
2663
  }
3364
- exports[name2] = true;
2664
+ exports[name] = true;
3365
2665
  };
3366
2666
  pp$8.checkPatternExport = function(exports, pat) {
3367
2667
  var type = pat.type;
@@ -3941,20 +3241,20 @@ pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
3941
3241
  return;
3942
3242
  }
3943
3243
  var key = prop.key;
3944
- var name2;
3244
+ var name;
3945
3245
  switch (key.type) {
3946
3246
  case "Identifier":
3947
- name2 = key.name;
3247
+ name = key.name;
3948
3248
  break;
3949
3249
  case "Literal":
3950
- name2 = String(key.value);
3250
+ name = String(key.value);
3951
3251
  break;
3952
3252
  default:
3953
3253
  return;
3954
3254
  }
3955
3255
  var kind = prop.kind;
3956
3256
  if (this.options.ecmaVersion >= 6) {
3957
- if (name2 === "__proto__" && kind === "init") {
3257
+ if (name === "__proto__" && kind === "init") {
3958
3258
  if (propHash.proto) {
3959
3259
  if (refDestructuringErrors) {
3960
3260
  if (refDestructuringErrors.doubleProto < 0) {
@@ -3968,8 +3268,8 @@ pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
3968
3268
  }
3969
3269
  return;
3970
3270
  }
3971
- name2 = "$" + name2;
3972
- var other = propHash[name2];
3271
+ name = "$" + name;
3272
+ var other = propHash[name];
3973
3273
  if (other) {
3974
3274
  var redefinition;
3975
3275
  if (kind === "init") {
@@ -3981,7 +3281,7 @@ pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
3981
3281
  this.raiseRecoverable(key.start, "Redefinition of property");
3982
3282
  }
3983
3283
  } else {
3984
- other = propHash[name2] = {
3284
+ other = propHash[name] = {
3985
3285
  init: false,
3986
3286
  get: false,
3987
3287
  set: false
@@ -4881,31 +4181,31 @@ pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestruct
4881
4181
  pp$5.checkUnreserved = function(ref2) {
4882
4182
  var start = ref2.start;
4883
4183
  var end = ref2.end;
4884
- var name2 = ref2.name;
4885
- if (this.inGenerator && name2 === "yield") {
4184
+ var name = ref2.name;
4185
+ if (this.inGenerator && name === "yield") {
4886
4186
  this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator");
4887
4187
  }
4888
- if (this.inAsync && name2 === "await") {
4188
+ if (this.inAsync && name === "await") {
4889
4189
  this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function");
4890
4190
  }
4891
- if (this.currentThisScope().inClassFieldInit && name2 === "arguments") {
4191
+ if (this.currentThisScope().inClassFieldInit && name === "arguments") {
4892
4192
  this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer");
4893
4193
  }
4894
- if (this.inClassStaticBlock && (name2 === "arguments" || name2 === "await")) {
4895
- this.raise(start, "Cannot use " + name2 + " in class static initialization block");
4194
+ if (this.inClassStaticBlock && (name === "arguments" || name === "await")) {
4195
+ this.raise(start, "Cannot use " + name + " in class static initialization block");
4896
4196
  }
4897
- if (this.keywords.test(name2)) {
4898
- this.raise(start, "Unexpected keyword '" + name2 + "'");
4197
+ if (this.keywords.test(name)) {
4198
+ this.raise(start, "Unexpected keyword '" + name + "'");
4899
4199
  }
4900
4200
  if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) {
4901
4201
  return;
4902
4202
  }
4903
4203
  var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
4904
- if (re.test(name2)) {
4905
- if (!this.inAsync && name2 === "await") {
4204
+ if (re.test(name)) {
4205
+ if (!this.inAsync && name === "await") {
4906
4206
  this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function");
4907
4207
  }
4908
- this.raiseRecoverable(start, "The keyword '" + name2 + "' is reserved");
4208
+ this.raiseRecoverable(start, "The keyword '" + name + "' is reserved");
4909
4209
  }
4910
4210
  };
4911
4211
  pp$5.parseIdent = function(liberal) {
@@ -5010,36 +4310,36 @@ pp$3.exitScope = function() {
5010
4310
  pp$3.treatFunctionsAsVarInScope = function(scope) {
5011
4311
  return scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_TOP;
5012
4312
  };
5013
- pp$3.declareName = function(name2, bindingType, pos) {
4313
+ pp$3.declareName = function(name, bindingType, pos) {
5014
4314
  var redeclared = false;
5015
4315
  if (bindingType === BIND_LEXICAL) {
5016
4316
  var scope = this.currentScope();
5017
- redeclared = scope.lexical.indexOf(name2) > -1 || scope.functions.indexOf(name2) > -1 || scope.var.indexOf(name2) > -1;
5018
- scope.lexical.push(name2);
4317
+ redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
4318
+ scope.lexical.push(name);
5019
4319
  if (this.inModule && scope.flags & SCOPE_TOP) {
5020
- delete this.undefinedExports[name2];
4320
+ delete this.undefinedExports[name];
5021
4321
  }
5022
4322
  } else if (bindingType === BIND_SIMPLE_CATCH) {
5023
4323
  var scope$1 = this.currentScope();
5024
- scope$1.lexical.push(name2);
4324
+ scope$1.lexical.push(name);
5025
4325
  } else if (bindingType === BIND_FUNCTION) {
5026
4326
  var scope$2 = this.currentScope();
5027
4327
  if (this.treatFunctionsAsVar) {
5028
- redeclared = scope$2.lexical.indexOf(name2) > -1;
4328
+ redeclared = scope$2.lexical.indexOf(name) > -1;
5029
4329
  } else {
5030
- redeclared = scope$2.lexical.indexOf(name2) > -1 || scope$2.var.indexOf(name2) > -1;
4330
+ redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1;
5031
4331
  }
5032
- scope$2.functions.push(name2);
4332
+ scope$2.functions.push(name);
5033
4333
  } else {
5034
4334
  for (var i = this.scopeStack.length - 1; i >= 0; --i) {
5035
4335
  var scope$3 = this.scopeStack[i];
5036
- 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) {
4336
+ 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) {
5037
4337
  redeclared = true;
5038
4338
  break;
5039
4339
  }
5040
- scope$3.var.push(name2);
4340
+ scope$3.var.push(name);
5041
4341
  if (this.inModule && scope$3.flags & SCOPE_TOP) {
5042
- delete this.undefinedExports[name2];
4342
+ delete this.undefinedExports[name];
5043
4343
  }
5044
4344
  if (scope$3.flags & SCOPE_VAR) {
5045
4345
  break;
@@ -5047,7 +4347,7 @@ pp$3.declareName = function(name2, bindingType, pos) {
5047
4347
  }
5048
4348
  }
5049
4349
  if (redeclared) {
5050
- this.raiseRecoverable(pos, "Identifier '" + name2 + "' has already been declared");
4350
+ this.raiseRecoverable(pos, "Identifier '" + name + "' has already been declared");
5051
4351
  }
5052
4352
  };
5053
4353
  pp$3.checkLocalExport = function(id) {
@@ -5367,8 +4667,8 @@ pp$1.regexp_pattern = function(state) {
5367
4667
  state.raise("Invalid escape");
5368
4668
  }
5369
4669
  for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
5370
- var name2 = list[i];
5371
- if (!state.groupNames[name2]) {
4670
+ var name = list[i];
4671
+ if (!state.groupNames[name]) {
5372
4672
  state.raise("Invalid named capture referenced");
5373
4673
  }
5374
4674
  }
@@ -6007,10 +5307,10 @@ pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
6007
5307
  61
6008
5308
  /* = */
6009
5309
  )) {
6010
- var name2 = state.lastStringValue;
5310
+ var name = state.lastStringValue;
6011
5311
  if (this.regexp_eatUnicodePropertyValue(state)) {
6012
5312
  var value = state.lastStringValue;
6013
- this.regexp_validateUnicodePropertyNameAndValue(state, name2, value);
5313
+ this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
6014
5314
  return CharSetOk;
6015
5315
  }
6016
5316
  }
@@ -6021,11 +5321,11 @@ pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
6021
5321
  }
6022
5322
  return CharSetNone;
6023
5323
  };
6024
- pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name2, value) {
6025
- if (!hasOwn(state.unicodeProperties.nonBinary, name2)) {
5324
+ pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
5325
+ if (!hasOwn(state.unicodeProperties.nonBinary, name)) {
6026
5326
  state.raise("Invalid property name");
6027
5327
  }
6028
- if (!state.unicodeProperties.nonBinary[name2].test(value)) {
5328
+ if (!state.unicodeProperties.nonBinary[name].test(value)) {
6029
5329
  state.raise("Invalid property value");
6030
5330
  }
6031
5331
  };
@@ -7342,7 +6642,7 @@ Parser.acorn = {
7342
6642
 
7343
6643
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7344
6644
  import { builtinModules, createRequire } from "node:module";
7345
- import fs3, { realpathSync, statSync as statSync2, promises } from "node:fs";
6645
+ import fs, { realpathSync, statSync, promises } from "node:fs";
7346
6646
 
7347
6647
  // ../../node_modules/.pnpm/ufo@1.5.4/node_modules/ufo/dist/index.mjs
7348
6648
  var r = String.fromCharCode;
@@ -7399,9 +6699,9 @@ var isAbsolute = function(p) {
7399
6699
 
7400
6700
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7401
6701
  import { fileURLToPath as fileURLToPath$1, URL as URL$1, pathToFileURL as pathToFileURL$1 } from "node:url";
7402
- import assert5 from "node:assert";
6702
+ import assert from "node:assert";
7403
6703
  import process$1 from "node:process";
7404
- import path4, { dirname as dirname4 } from "node:path";
6704
+ import path, { dirname as dirname2 } from "node:path";
7405
6705
  import v8 from "node:v8";
7406
6706
  import { format as format2, inspect } from "node:util";
7407
6707
  var BUILTIN_MODULES = new Set(builtinModules);
@@ -7436,31 +6736,31 @@ codes.ERR_INVALID_ARG_TYPE = createError(
7436
6736
  * @param {Array<string> | string} expected
7437
6737
  * @param {unknown} actual
7438
6738
  */
7439
- (name2, expected, actual) => {
7440
- assert5(typeof name2 === "string", "'name' must be a string");
6739
+ (name, expected, actual) => {
6740
+ assert(typeof name === "string", "'name' must be a string");
7441
6741
  if (!Array.isArray(expected)) {
7442
6742
  expected = [expected];
7443
6743
  }
7444
6744
  let message = "The ";
7445
- if (name2.endsWith(" argument")) {
7446
- message += `${name2} `;
6745
+ if (name.endsWith(" argument")) {
6746
+ message += `${name} `;
7447
6747
  } else {
7448
- const type = name2.includes(".") ? "property" : "argument";
7449
- message += `"${name2}" ${type} `;
6748
+ const type = name.includes(".") ? "property" : "argument";
6749
+ message += `"${name}" ${type} `;
7450
6750
  }
7451
6751
  message += "must be ";
7452
6752
  const types2 = [];
7453
6753
  const instances = [];
7454
6754
  const other = [];
7455
6755
  for (const value of expected) {
7456
- assert5(
6756
+ assert(
7457
6757
  typeof value === "string",
7458
6758
  "All expected entries have to be of type string"
7459
6759
  );
7460
6760
  if (kTypes.has(value)) {
7461
6761
  types2.push(value.toLowerCase());
7462
6762
  } else if (classRegExp.exec(value) === null) {
7463
- assert5(
6763
+ assert(
7464
6764
  value !== "object",
7465
6765
  'The value "object" should be written as "Object"'
7466
6766
  );
@@ -7533,14 +6833,14 @@ codes.ERR_INVALID_PACKAGE_TARGET = createError(
7533
6833
  * @param {boolean} [isImport=false]
7534
6834
  * @param {string} [base]
7535
6835
  */
7536
- (packagePath, key, target, isImport = false, base = void 0) => {
7537
- const relatedError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./");
6836
+ (packagePath, key, target2, isImport = false, base = void 0) => {
6837
+ const relatedError = typeof target2 === "string" && !isImport && target2.length > 0 && !target2.startsWith("./");
7538
6838
  if (key === ".") {
7539
- assert5(isImport === false);
7540
- 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 "./"' : ""}`;
6839
+ assert(isImport === false);
6840
+ 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 "./"' : ""}`;
7541
6841
  }
7542
6842
  return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(
7543
- target
6843
+ target2
7544
6844
  )} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
7545
6845
  },
7546
6846
  Error
@@ -7616,13 +6916,13 @@ codes.ERR_INVALID_ARG_VALUE = createError(
7616
6916
  * @param {unknown} value
7617
6917
  * @param {string} [reason='is invalid']
7618
6918
  */
7619
- (name2, value, reason = "is invalid") => {
6919
+ (name, value, reason = "is invalid") => {
7620
6920
  let inspected = inspect(value);
7621
6921
  if (inspected.length > 128) {
7622
6922
  inspected = `${inspected.slice(0, 128)}...`;
7623
6923
  }
7624
- const type = name2.includes(".") ? "property" : "argument";
7625
- return `The ${type} '${name2}' ${reason}. Received ${inspected}`;
6924
+ const type = name.includes(".") ? "property" : "argument";
6925
+ return `The ${type} '${name}' ${reason}. Received ${inspected}`;
7626
6926
  },
7627
6927
  TypeError
7628
6928
  // Note: extra classes have been shaken out.
@@ -7701,9 +7001,9 @@ var captureLargerStackTrace = hideStackFrames(
7701
7001
  );
7702
7002
  function getMessage(key, parameters, self) {
7703
7003
  const message = messages.get(key);
7704
- assert5(message !== void 0, "expected `message` to be found");
7004
+ assert(message !== void 0, "expected `message` to be found");
7705
7005
  if (typeof message === "function") {
7706
- assert5(
7006
+ assert(
7707
7007
  message.length <= parameters.length,
7708
7008
  // Default options do not count.
7709
7009
  `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`
@@ -7713,7 +7013,7 @@ function getMessage(key, parameters, self) {
7713
7013
  const regex = /%[dfijoOs]/g;
7714
7014
  let expectedLength = 0;
7715
7015
  while (regex.exec(message) !== null) expectedLength++;
7716
- assert5(
7016
+ assert(
7717
7017
  expectedLength === parameters.length,
7718
7018
  `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`
7719
7019
  );
@@ -7750,7 +7050,7 @@ function read(jsonPath, { base, specifier }) {
7750
7050
  }
7751
7051
  let string;
7752
7052
  try {
7753
- string = fs3.readFileSync(path4.toNamespacedPath(jsonPath), "utf8");
7053
+ string = fs.readFileSync(path.toNamespacedPath(jsonPath), "utf8");
7754
7054
  } catch (error) {
7755
7055
  const exception = (
7756
7056
  /** @type {ErrnoException} */
@@ -7936,14 +7236,14 @@ var patternRegEx = /\*/g;
7936
7236
  var encodedSeparatorRegEx = /%2f|%5c/i;
7937
7237
  var emittedPackageWarnings = /* @__PURE__ */ new Set();
7938
7238
  var doubleSlashRegEx = /[/\\]{2}/;
7939
- function emitInvalidSegmentDeprecation(target, request, match, packageJsonUrl, internal, base, isTarget) {
7239
+ function emitInvalidSegmentDeprecation(target2, request, match, packageJsonUrl, internal, base, isTarget) {
7940
7240
  if (process$1.noDeprecation) {
7941
7241
  return;
7942
7242
  }
7943
7243
  const pjsonPath = fileURLToPath$1(packageJsonUrl);
7944
- const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
7244
+ const double = doubleSlashRegEx.exec(isTarget ? target2 : request) !== null;
7945
7245
  process$1.emitWarning(
7946
- `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)}` : ""}.`,
7246
+ `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)}` : ""}.`,
7947
7247
  "DeprecationWarning",
7948
7248
  "DEP0166"
7949
7249
  );
@@ -7966,7 +7266,7 @@ Default "index" lookups for the main are deprecated for ES modules.`,
7966
7266
  "DeprecationWarning",
7967
7267
  "DEP0151"
7968
7268
  );
7969
- } else if (path4.resolve(packagePath, main) !== urlPath) {
7269
+ } else if (path.resolve(packagePath, main) !== urlPath) {
7970
7270
  process$1.emitWarning(
7971
7271
  `Package ${packagePath} has a "main" field set to "${main}", excluding the full filename and extension to the resolved file at "${urlPath.slice(
7972
7272
  packagePath.length
@@ -7979,12 +7279,12 @@ Default "index" lookups for the main are deprecated for ES modules.`,
7979
7279
  }
7980
7280
  function tryStatSync(path8) {
7981
7281
  try {
7982
- return statSync2(path8);
7282
+ return statSync(path8);
7983
7283
  } catch {
7984
7284
  }
7985
7285
  }
7986
7286
  function fileExists(url) {
7987
- const stats = statSync2(url, { throwIfNoEntry: false });
7287
+ const stats = statSync(url, { throwIfNoEntry: false });
7988
7288
  const isFile = stats ? stats.isFile() : void 0;
7989
7289
  return isFile === null || isFile === void 0 ? false : isFile;
7990
7290
  }
@@ -8007,846 +7307,1579 @@ function legacyMainResolve(packageJsonUrl, packageConfig, base) {
8007
7307
  if (fileExists(guess)) break;
8008
7308
  guess = void 0;
8009
7309
  }
8010
- if (guess) {
8011
- emitLegacyIndexDeprecation(
8012
- guess,
8013
- packageJsonUrl,
7310
+ if (guess) {
7311
+ emitLegacyIndexDeprecation(
7312
+ guess,
7313
+ packageJsonUrl,
7314
+ base,
7315
+ packageConfig.main
7316
+ );
7317
+ return guess;
7318
+ }
7319
+ }
7320
+ const tries = ["./index.js", "./index.json", "./index.node"];
7321
+ let i = -1;
7322
+ while (++i < tries.length) {
7323
+ guess = new URL$1(tries[i], packageJsonUrl);
7324
+ if (fileExists(guess)) break;
7325
+ guess = void 0;
7326
+ }
7327
+ if (guess) {
7328
+ emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
7329
+ return guess;
7330
+ }
7331
+ throw new ERR_MODULE_NOT_FOUND(
7332
+ fileURLToPath$1(new URL$1(".", packageJsonUrl)),
7333
+ fileURLToPath$1(base)
7334
+ );
7335
+ }
7336
+ function finalizeResolution(resolved, base, preserveSymlinks) {
7337
+ if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) {
7338
+ throw new ERR_INVALID_MODULE_SPECIFIER(
7339
+ resolved.pathname,
7340
+ 'must not include encoded "/" or "\\" characters',
7341
+ fileURLToPath$1(base)
7342
+ );
7343
+ }
7344
+ let filePath;
7345
+ try {
7346
+ filePath = fileURLToPath$1(resolved);
7347
+ } catch (error) {
7348
+ const cause = (
7349
+ /** @type {ErrnoException} */
7350
+ error
7351
+ );
7352
+ Object.defineProperty(cause, "input", { value: String(resolved) });
7353
+ Object.defineProperty(cause, "module", { value: String(base) });
7354
+ throw cause;
7355
+ }
7356
+ const stats = tryStatSync(
7357
+ filePath.endsWith("/") ? filePath.slice(-1) : filePath
7358
+ );
7359
+ if (stats && stats.isDirectory()) {
7360
+ const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath$1(base));
7361
+ error.url = String(resolved);
7362
+ throw error;
7363
+ }
7364
+ if (!stats || !stats.isFile()) {
7365
+ const error = new ERR_MODULE_NOT_FOUND(
7366
+ filePath || resolved.pathname,
7367
+ base && fileURLToPath$1(base),
7368
+ true
7369
+ );
7370
+ error.url = String(resolved);
7371
+ throw error;
7372
+ }
7373
+ {
7374
+ const real = realpathSync(filePath);
7375
+ const { search, hash } = resolved;
7376
+ resolved = pathToFileURL$1(real + (filePath.endsWith(path.sep) ? "/" : ""));
7377
+ resolved.search = search;
7378
+ resolved.hash = hash;
7379
+ }
7380
+ return resolved;
7381
+ }
7382
+ function importNotDefined(specifier, packageJsonUrl, base) {
7383
+ return new ERR_PACKAGE_IMPORT_NOT_DEFINED(
7384
+ specifier,
7385
+ packageJsonUrl && fileURLToPath$1(new URL$1(".", packageJsonUrl)),
7386
+ fileURLToPath$1(base)
7387
+ );
7388
+ }
7389
+ function exportsNotFound(subpath, packageJsonUrl, base) {
7390
+ return new ERR_PACKAGE_PATH_NOT_EXPORTED(
7391
+ fileURLToPath$1(new URL$1(".", packageJsonUrl)),
7392
+ subpath,
7393
+ base && fileURLToPath$1(base)
7394
+ );
7395
+ }
7396
+ function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
7397
+ const reason = `request is not a valid match in pattern "${match}" for the "${internal ? "imports" : "exports"}" resolution of ${fileURLToPath$1(packageJsonUrl)}`;
7398
+ throw new ERR_INVALID_MODULE_SPECIFIER(
7399
+ request,
7400
+ reason,
7401
+ base && fileURLToPath$1(base)
7402
+ );
7403
+ }
7404
+ function invalidPackageTarget(subpath, target2, packageJsonUrl, internal, base) {
7405
+ target2 = typeof target2 === "object" && target2 !== null ? JSON.stringify(target2, null, "") : `${target2}`;
7406
+ return new ERR_INVALID_PACKAGE_TARGET(
7407
+ fileURLToPath$1(new URL$1(".", packageJsonUrl)),
7408
+ subpath,
7409
+ target2,
7410
+ internal,
7411
+ base && fileURLToPath$1(base)
7412
+ );
7413
+ }
7414
+ function resolvePackageTargetString(target2, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
7415
+ if (subpath !== "" && !pattern && target2[target2.length - 1] !== "/")
7416
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
7417
+ if (!target2.startsWith("./")) {
7418
+ if (internal && !target2.startsWith("../") && !target2.startsWith("/")) {
7419
+ let isURL = false;
7420
+ try {
7421
+ new URL$1(target2);
7422
+ isURL = true;
7423
+ } catch {
7424
+ }
7425
+ if (!isURL) {
7426
+ const exportTarget = pattern ? RegExpPrototypeSymbolReplace.call(
7427
+ patternRegEx,
7428
+ target2,
7429
+ () => subpath
7430
+ ) : target2 + subpath;
7431
+ return packageResolve(exportTarget, packageJsonUrl, conditions);
7432
+ }
7433
+ }
7434
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
7435
+ }
7436
+ if (invalidSegmentRegEx.exec(target2.slice(2)) !== null) {
7437
+ if (deprecatedInvalidSegmentRegEx.exec(target2.slice(2)) === null) {
7438
+ if (!isPathMap) {
7439
+ const request = pattern ? match.replace("*", () => subpath) : match + subpath;
7440
+ const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
7441
+ patternRegEx,
7442
+ target2,
7443
+ () => subpath
7444
+ ) : target2;
7445
+ emitInvalidSegmentDeprecation(
7446
+ resolvedTarget,
7447
+ request,
7448
+ match,
7449
+ packageJsonUrl,
7450
+ internal,
7451
+ base,
7452
+ true
7453
+ );
7454
+ }
7455
+ } else {
7456
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
7457
+ }
7458
+ }
7459
+ const resolved = new URL$1(target2, packageJsonUrl);
7460
+ const resolvedPath = resolved.pathname;
7461
+ const packagePath = new URL$1(".", packageJsonUrl).pathname;
7462
+ if (!resolvedPath.startsWith(packagePath))
7463
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
7464
+ if (subpath === "") return resolved;
7465
+ if (invalidSegmentRegEx.exec(subpath) !== null) {
7466
+ const request = pattern ? match.replace("*", () => subpath) : match + subpath;
7467
+ if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
7468
+ if (!isPathMap) {
7469
+ const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
7470
+ patternRegEx,
7471
+ target2,
7472
+ () => subpath
7473
+ ) : target2;
7474
+ emitInvalidSegmentDeprecation(
7475
+ resolvedTarget,
7476
+ request,
7477
+ match,
7478
+ packageJsonUrl,
7479
+ internal,
7480
+ base,
7481
+ false
7482
+ );
7483
+ }
7484
+ } else {
7485
+ throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
7486
+ }
7487
+ }
7488
+ if (pattern) {
7489
+ return new URL$1(
7490
+ RegExpPrototypeSymbolReplace.call(
7491
+ patternRegEx,
7492
+ resolved.href,
7493
+ () => subpath
7494
+ )
7495
+ );
7496
+ }
7497
+ return new URL$1(subpath, resolved);
7498
+ }
7499
+ function isArrayIndex(key) {
7500
+ const keyNumber = Number(key);
7501
+ if (`${keyNumber}` !== key) return false;
7502
+ return keyNumber >= 0 && keyNumber < 4294967295;
7503
+ }
7504
+ function resolvePackageTarget(packageJsonUrl, target2, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
7505
+ if (typeof target2 === "string") {
7506
+ return resolvePackageTargetString(
7507
+ target2,
7508
+ subpath,
7509
+ packageSubpath,
7510
+ packageJsonUrl,
7511
+ base,
7512
+ pattern,
7513
+ internal,
7514
+ isPathMap,
7515
+ conditions
7516
+ );
7517
+ }
7518
+ if (Array.isArray(target2)) {
7519
+ const targetList = target2;
7520
+ if (targetList.length === 0) return null;
7521
+ let lastException;
7522
+ let i = -1;
7523
+ while (++i < targetList.length) {
7524
+ const targetItem = targetList[i];
7525
+ let resolveResult;
7526
+ try {
7527
+ resolveResult = resolvePackageTarget(
7528
+ packageJsonUrl,
7529
+ targetItem,
7530
+ subpath,
7531
+ packageSubpath,
7532
+ base,
7533
+ pattern,
7534
+ internal,
7535
+ isPathMap,
7536
+ conditions
7537
+ );
7538
+ } catch (error) {
7539
+ const exception = (
7540
+ /** @type {ErrnoException} */
7541
+ error
7542
+ );
7543
+ lastException = exception;
7544
+ if (exception.code === "ERR_INVALID_PACKAGE_TARGET") continue;
7545
+ throw error;
7546
+ }
7547
+ if (resolveResult === void 0) continue;
7548
+ if (resolveResult === null) {
7549
+ lastException = null;
7550
+ continue;
7551
+ }
7552
+ return resolveResult;
7553
+ }
7554
+ if (lastException === void 0 || lastException === null) {
7555
+ return null;
7556
+ }
7557
+ throw lastException;
7558
+ }
7559
+ if (typeof target2 === "object" && target2 !== null) {
7560
+ const keys = Object.getOwnPropertyNames(target2);
7561
+ let i = -1;
7562
+ while (++i < keys.length) {
7563
+ const key = keys[i];
7564
+ if (isArrayIndex(key)) {
7565
+ throw new ERR_INVALID_PACKAGE_CONFIG(
7566
+ fileURLToPath$1(packageJsonUrl),
7567
+ base,
7568
+ '"exports" cannot contain numeric property keys.'
7569
+ );
7570
+ }
7571
+ }
7572
+ i = -1;
7573
+ while (++i < keys.length) {
7574
+ const key = keys[i];
7575
+ if (key === "default" || conditions && conditions.has(key)) {
7576
+ const conditionalTarget = (
7577
+ /** @type {unknown} */
7578
+ target2[key]
7579
+ );
7580
+ const resolveResult = resolvePackageTarget(
7581
+ packageJsonUrl,
7582
+ conditionalTarget,
7583
+ subpath,
7584
+ packageSubpath,
7585
+ base,
7586
+ pattern,
7587
+ internal,
7588
+ isPathMap,
7589
+ conditions
7590
+ );
7591
+ if (resolveResult === void 0) continue;
7592
+ return resolveResult;
7593
+ }
7594
+ }
7595
+ return null;
7596
+ }
7597
+ if (target2 === null) {
7598
+ return null;
7599
+ }
7600
+ throw invalidPackageTarget(
7601
+ packageSubpath,
7602
+ target2,
7603
+ packageJsonUrl,
7604
+ internal,
7605
+ base
7606
+ );
7607
+ }
7608
+ function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
7609
+ if (typeof exports === "string" || Array.isArray(exports)) return true;
7610
+ if (typeof exports !== "object" || exports === null) return false;
7611
+ const keys = Object.getOwnPropertyNames(exports);
7612
+ let isConditionalSugar = false;
7613
+ let i = 0;
7614
+ let keyIndex = -1;
7615
+ while (++keyIndex < keys.length) {
7616
+ const key = keys[keyIndex];
7617
+ const currentIsConditionalSugar = key === "" || key[0] !== ".";
7618
+ if (i++ === 0) {
7619
+ isConditionalSugar = currentIsConditionalSugar;
7620
+ } else if (isConditionalSugar !== currentIsConditionalSugar) {
7621
+ throw new ERR_INVALID_PACKAGE_CONFIG(
7622
+ fileURLToPath$1(packageJsonUrl),
8014
7623
  base,
8015
- packageConfig.main
7624
+ `"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.`
8016
7625
  );
8017
- return guess;
8018
7626
  }
8019
7627
  }
8020
- const tries = ["./index.js", "./index.json", "./index.node"];
8021
- let i = -1;
8022
- while (++i < tries.length) {
8023
- guess = new URL$1(tries[i], packageJsonUrl);
8024
- if (fileExists(guess)) break;
8025
- guess = void 0;
8026
- }
8027
- if (guess) {
8028
- emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
8029
- return guess;
7628
+ return isConditionalSugar;
7629
+ }
7630
+ function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
7631
+ if (process$1.noDeprecation) {
7632
+ return;
8030
7633
  }
8031
- throw new ERR_MODULE_NOT_FOUND(
8032
- fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8033
- fileURLToPath$1(base)
7634
+ const pjsonPath = fileURLToPath$1(pjsonUrl);
7635
+ if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return;
7636
+ emittedPackageWarnings.add(pjsonPath + "|" + match);
7637
+ process$1.emitWarning(
7638
+ `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.`,
7639
+ "DeprecationWarning",
7640
+ "DEP0155"
8034
7641
  );
8035
7642
  }
8036
- function finalizeResolution(resolved, base, preserveSymlinks) {
8037
- if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) {
8038
- throw new ERR_INVALID_MODULE_SPECIFIER(
8039
- resolved.pathname,
8040
- 'must not include encoded "/" or "\\" characters',
8041
- fileURLToPath$1(base)
7643
+ function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
7644
+ let exports = packageConfig.exports;
7645
+ if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
7646
+ exports = { ".": exports };
7647
+ }
7648
+ if (own.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
7649
+ const target2 = exports[packageSubpath];
7650
+ const resolveResult = resolvePackageTarget(
7651
+ packageJsonUrl,
7652
+ target2,
7653
+ "",
7654
+ packageSubpath,
7655
+ base,
7656
+ false,
7657
+ false,
7658
+ false,
7659
+ conditions
8042
7660
  );
7661
+ if (resolveResult === null || resolveResult === void 0) {
7662
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7663
+ }
7664
+ return resolveResult;
8043
7665
  }
8044
- let filePath;
8045
- try {
8046
- filePath = fileURLToPath$1(resolved);
8047
- } catch (error) {
8048
- const cause = (
8049
- /** @type {ErrnoException} */
8050
- error
7666
+ let bestMatch = "";
7667
+ let bestMatchSubpath = "";
7668
+ const keys = Object.getOwnPropertyNames(exports);
7669
+ let i = -1;
7670
+ while (++i < keys.length) {
7671
+ const key = keys[i];
7672
+ const patternIndex = key.indexOf("*");
7673
+ if (patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex))) {
7674
+ if (packageSubpath.endsWith("/")) {
7675
+ emitTrailingSlashPatternDeprecation(
7676
+ packageSubpath,
7677
+ packageJsonUrl,
7678
+ base
7679
+ );
7680
+ }
7681
+ const patternTrailer = key.slice(patternIndex + 1);
7682
+ if (packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
7683
+ bestMatch = key;
7684
+ bestMatchSubpath = packageSubpath.slice(
7685
+ patternIndex,
7686
+ packageSubpath.length - patternTrailer.length
7687
+ );
7688
+ }
7689
+ }
7690
+ }
7691
+ if (bestMatch) {
7692
+ const target2 = (
7693
+ /** @type {unknown} */
7694
+ exports[bestMatch]
8051
7695
  );
8052
- Object.defineProperty(cause, "input", { value: String(resolved) });
8053
- Object.defineProperty(cause, "module", { value: String(base) });
8054
- throw cause;
7696
+ const resolveResult = resolvePackageTarget(
7697
+ packageJsonUrl,
7698
+ target2,
7699
+ bestMatchSubpath,
7700
+ bestMatch,
7701
+ base,
7702
+ true,
7703
+ false,
7704
+ packageSubpath.endsWith("/"),
7705
+ conditions
7706
+ );
7707
+ if (resolveResult === null || resolveResult === void 0) {
7708
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7709
+ }
7710
+ return resolveResult;
8055
7711
  }
8056
- const stats = tryStatSync(
8057
- filePath.endsWith("/") ? filePath.slice(-1) : filePath
8058
- );
8059
- if (stats && stats.isDirectory()) {
8060
- const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath$1(base));
8061
- error.url = String(resolved);
8062
- throw error;
7712
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7713
+ }
7714
+ function patternKeyCompare(a, b) {
7715
+ const aPatternIndex = a.indexOf("*");
7716
+ const bPatternIndex = b.indexOf("*");
7717
+ const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
7718
+ const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
7719
+ if (baseLengthA > baseLengthB) return -1;
7720
+ if (baseLengthB > baseLengthA) return 1;
7721
+ if (aPatternIndex === -1) return 1;
7722
+ if (bPatternIndex === -1) return -1;
7723
+ if (a.length > b.length) return -1;
7724
+ if (b.length > a.length) return 1;
7725
+ return 0;
7726
+ }
7727
+ function packageImportsResolve(name, base, conditions) {
7728
+ if (name === "#" || name.startsWith("#/") || name.endsWith("/")) {
7729
+ const reason = "is not a valid internal imports specifier name";
7730
+ throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath$1(base));
8063
7731
  }
8064
- if (!stats || !stats.isFile()) {
8065
- const error = new ERR_MODULE_NOT_FOUND(
8066
- filePath || resolved.pathname,
8067
- base && fileURLToPath$1(base),
8068
- true
7732
+ let packageJsonUrl;
7733
+ const packageConfig = getPackageScopeConfig(base);
7734
+ if (packageConfig.exists) {
7735
+ packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
7736
+ const imports = packageConfig.imports;
7737
+ if (imports) {
7738
+ if (own.call(imports, name) && !name.includes("*")) {
7739
+ const resolveResult = resolvePackageTarget(
7740
+ packageJsonUrl,
7741
+ imports[name],
7742
+ "",
7743
+ name,
7744
+ base,
7745
+ false,
7746
+ true,
7747
+ false,
7748
+ conditions
7749
+ );
7750
+ if (resolveResult !== null && resolveResult !== void 0) {
7751
+ return resolveResult;
7752
+ }
7753
+ } else {
7754
+ let bestMatch = "";
7755
+ let bestMatchSubpath = "";
7756
+ const keys = Object.getOwnPropertyNames(imports);
7757
+ let i = -1;
7758
+ while (++i < keys.length) {
7759
+ const key = keys[i];
7760
+ const patternIndex = key.indexOf("*");
7761
+ if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) {
7762
+ const patternTrailer = key.slice(patternIndex + 1);
7763
+ if (name.length >= key.length && name.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
7764
+ bestMatch = key;
7765
+ bestMatchSubpath = name.slice(
7766
+ patternIndex,
7767
+ name.length - patternTrailer.length
7768
+ );
7769
+ }
7770
+ }
7771
+ }
7772
+ if (bestMatch) {
7773
+ const target2 = imports[bestMatch];
7774
+ const resolveResult = resolvePackageTarget(
7775
+ packageJsonUrl,
7776
+ target2,
7777
+ bestMatchSubpath,
7778
+ bestMatch,
7779
+ base,
7780
+ true,
7781
+ true,
7782
+ false,
7783
+ conditions
7784
+ );
7785
+ if (resolveResult !== null && resolveResult !== void 0) {
7786
+ return resolveResult;
7787
+ }
7788
+ }
7789
+ }
7790
+ }
7791
+ }
7792
+ throw importNotDefined(name, packageJsonUrl, base);
7793
+ }
7794
+ function parsePackageName(specifier, base) {
7795
+ let separatorIndex = specifier.indexOf("/");
7796
+ let validPackageName = true;
7797
+ let isScoped = false;
7798
+ if (specifier[0] === "@") {
7799
+ isScoped = true;
7800
+ if (separatorIndex === -1 || specifier.length === 0) {
7801
+ validPackageName = false;
7802
+ } else {
7803
+ separatorIndex = specifier.indexOf("/", separatorIndex + 1);
7804
+ }
7805
+ }
7806
+ const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
7807
+ if (invalidPackageNameRegEx.exec(packageName) !== null) {
7808
+ validPackageName = false;
7809
+ }
7810
+ if (!validPackageName) {
7811
+ throw new ERR_INVALID_MODULE_SPECIFIER(
7812
+ specifier,
7813
+ "is not a valid package name",
7814
+ fileURLToPath$1(base)
8069
7815
  );
8070
- error.url = String(resolved);
8071
- throw error;
8072
7816
  }
8073
- {
8074
- const real = realpathSync(filePath);
8075
- const { search, hash } = resolved;
8076
- resolved = pathToFileURL$1(real + (filePath.endsWith(path4.sep) ? "/" : ""));
8077
- resolved.search = search;
8078
- resolved.hash = hash;
7817
+ const packageSubpath = "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex));
7818
+ return { packageName, packageSubpath, isScoped };
7819
+ }
7820
+ function packageResolve(specifier, base, conditions) {
7821
+ if (builtinModules.includes(specifier)) {
7822
+ return new URL$1("node:" + specifier);
8079
7823
  }
8080
- return resolved;
8081
- }
8082
- function importNotDefined(specifier, packageJsonUrl, base) {
8083
- return new ERR_PACKAGE_IMPORT_NOT_DEFINED(
7824
+ const { packageName, packageSubpath, isScoped } = parsePackageName(
8084
7825
  specifier,
8085
- packageJsonUrl && fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8086
- fileURLToPath$1(base)
7826
+ base
8087
7827
  );
8088
- }
8089
- function exportsNotFound(subpath, packageJsonUrl, base) {
8090
- return new ERR_PACKAGE_PATH_NOT_EXPORTED(
8091
- fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8092
- subpath,
8093
- base && fileURLToPath$1(base)
7828
+ const packageConfig = getPackageScopeConfig(base);
7829
+ if (packageConfig.exists) {
7830
+ const packageJsonUrl2 = pathToFileURL$1(packageConfig.pjsonPath);
7831
+ if (packageConfig.name === packageName && packageConfig.exports !== void 0 && packageConfig.exports !== null) {
7832
+ return packageExportsResolve(
7833
+ packageJsonUrl2,
7834
+ packageSubpath,
7835
+ packageConfig,
7836
+ base,
7837
+ conditions
7838
+ );
7839
+ }
7840
+ }
7841
+ let packageJsonUrl = new URL$1(
7842
+ "./node_modules/" + packageName + "/package.json",
7843
+ base
8094
7844
  );
7845
+ let packageJsonPath = fileURLToPath$1(packageJsonUrl);
7846
+ let lastPath;
7847
+ do {
7848
+ const stat = tryStatSync(packageJsonPath.slice(0, -13));
7849
+ if (!stat || !stat.isDirectory()) {
7850
+ lastPath = packageJsonPath;
7851
+ packageJsonUrl = new URL$1(
7852
+ (isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json",
7853
+ packageJsonUrl
7854
+ );
7855
+ packageJsonPath = fileURLToPath$1(packageJsonUrl);
7856
+ continue;
7857
+ }
7858
+ const packageConfig2 = read(packageJsonPath, { base, specifier });
7859
+ if (packageConfig2.exports !== void 0 && packageConfig2.exports !== null) {
7860
+ return packageExportsResolve(
7861
+ packageJsonUrl,
7862
+ packageSubpath,
7863
+ packageConfig2,
7864
+ base,
7865
+ conditions
7866
+ );
7867
+ }
7868
+ if (packageSubpath === ".") {
7869
+ return legacyMainResolve(packageJsonUrl, packageConfig2, base);
7870
+ }
7871
+ return new URL$1(packageSubpath, packageJsonUrl);
7872
+ } while (packageJsonPath.length !== lastPath.length);
7873
+ throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath$1(base), false);
8095
7874
  }
8096
- function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
8097
- const reason = `request is not a valid match in pattern "${match}" for the "${internal ? "imports" : "exports"}" resolution of ${fileURLToPath$1(packageJsonUrl)}`;
8098
- throw new ERR_INVALID_MODULE_SPECIFIER(
8099
- request,
8100
- reason,
8101
- base && fileURLToPath$1(base)
8102
- );
7875
+ function isRelativeSpecifier(specifier) {
7876
+ if (specifier[0] === ".") {
7877
+ if (specifier.length === 1 || specifier[1] === "/") return true;
7878
+ if (specifier[1] === "." && (specifier.length === 2 || specifier[2] === "/")) {
7879
+ return true;
7880
+ }
7881
+ }
7882
+ return false;
8103
7883
  }
8104
- function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
8105
- target = typeof target === "object" && target !== null ? JSON.stringify(target, null, "") : `${target}`;
8106
- return new ERR_INVALID_PACKAGE_TARGET(
8107
- fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8108
- subpath,
8109
- target,
8110
- internal,
8111
- base && fileURLToPath$1(base)
8112
- );
7884
+ function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
7885
+ if (specifier === "") return false;
7886
+ if (specifier[0] === "/") return true;
7887
+ return isRelativeSpecifier(specifier);
8113
7888
  }
8114
- function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
8115
- if (subpath !== "" && !pattern && target[target.length - 1] !== "/")
8116
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8117
- if (!target.startsWith("./")) {
8118
- if (internal && !target.startsWith("../") && !target.startsWith("/")) {
8119
- let isURL = false;
8120
- try {
8121
- new URL$1(target);
8122
- isURL = true;
8123
- } catch {
8124
- }
8125
- if (!isURL) {
8126
- const exportTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8127
- patternRegEx,
8128
- target,
8129
- () => subpath
8130
- ) : target + subpath;
8131
- return packageResolve(exportTarget, packageJsonUrl, conditions);
8132
- }
7889
+ function moduleResolve(specifier, base, conditions, preserveSymlinks) {
7890
+ const protocol = base.protocol;
7891
+ const isData = protocol === "data:";
7892
+ const isRemote = isData || protocol === "http:" || protocol === "https:";
7893
+ let resolved;
7894
+ if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
7895
+ try {
7896
+ resolved = new URL$1(specifier, base);
7897
+ } catch (error_) {
7898
+ const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
7899
+ error.cause = error_;
7900
+ throw error;
8133
7901
  }
8134
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8135
- }
8136
- if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
8137
- if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
8138
- if (!isPathMap) {
8139
- const request = pattern ? match.replace("*", () => subpath) : match + subpath;
8140
- const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8141
- patternRegEx,
8142
- target,
8143
- () => subpath
8144
- ) : target;
8145
- emitInvalidSegmentDeprecation(
8146
- resolvedTarget,
8147
- request,
8148
- match,
8149
- packageJsonUrl,
8150
- internal,
8151
- base,
8152
- true
8153
- );
7902
+ } else if (protocol === "file:" && specifier[0] === "#") {
7903
+ resolved = packageImportsResolve(specifier, base, conditions);
7904
+ } else {
7905
+ try {
7906
+ resolved = new URL$1(specifier);
7907
+ } catch (error_) {
7908
+ if (isRemote && !builtinModules.includes(specifier)) {
7909
+ const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
7910
+ error.cause = error_;
7911
+ throw error;
8154
7912
  }
8155
- } else {
8156
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
7913
+ resolved = packageResolve(specifier, base, conditions);
8157
7914
  }
8158
7915
  }
8159
- const resolved = new URL$1(target, packageJsonUrl);
8160
- const resolvedPath = resolved.pathname;
8161
- const packagePath = new URL$1(".", packageJsonUrl).pathname;
8162
- if (!resolvedPath.startsWith(packagePath))
8163
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8164
- if (subpath === "") return resolved;
8165
- if (invalidSegmentRegEx.exec(subpath) !== null) {
8166
- const request = pattern ? match.replace("*", () => subpath) : match + subpath;
8167
- if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
8168
- if (!isPathMap) {
8169
- const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8170
- patternRegEx,
8171
- target,
8172
- () => subpath
8173
- ) : target;
8174
- emitInvalidSegmentDeprecation(
8175
- resolvedTarget,
8176
- request,
8177
- match,
8178
- packageJsonUrl,
8179
- internal,
8180
- base,
8181
- false
8182
- );
8183
- }
8184
- } else {
8185
- throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
8186
- }
7916
+ assert(resolved !== void 0, "expected to be defined");
7917
+ if (resolved.protocol !== "file:") {
7918
+ return resolved;
8187
7919
  }
8188
- if (pattern) {
8189
- return new URL$1(
8190
- RegExpPrototypeSymbolReplace.call(
8191
- patternRegEx,
8192
- resolved.href,
8193
- () => subpath
8194
- )
8195
- );
7920
+ return finalizeResolution(resolved, base);
7921
+ }
7922
+ function fileURLToPath(id) {
7923
+ if (typeof id === "string" && !id.startsWith("file://")) {
7924
+ return normalizeSlash(id);
8196
7925
  }
8197
- return new URL$1(subpath, resolved);
7926
+ return normalizeSlash(fileURLToPath$1(id));
8198
7927
  }
8199
- function isArrayIndex(key) {
8200
- const keyNumber = Number(key);
8201
- if (`${keyNumber}` !== key) return false;
8202
- return keyNumber >= 0 && keyNumber < 4294967295;
7928
+ function pathToFileURL(id) {
7929
+ return pathToFileURL$1(fileURLToPath(id)).toString();
8203
7930
  }
8204
- function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
8205
- if (typeof target === "string") {
8206
- return resolvePackageTargetString(
8207
- target,
8208
- subpath,
8209
- packageSubpath,
8210
- packageJsonUrl,
8211
- base,
8212
- pattern,
8213
- internal,
8214
- isPathMap,
8215
- conditions
8216
- );
7931
+ function normalizeid(id) {
7932
+ if (typeof id !== "string") {
7933
+ id = id.toString();
8217
7934
  }
8218
- if (Array.isArray(target)) {
8219
- const targetList = target;
8220
- if (targetList.length === 0) return null;
8221
- let lastException;
8222
- let i = -1;
8223
- while (++i < targetList.length) {
8224
- const targetItem = targetList[i];
8225
- let resolveResult;
8226
- try {
8227
- resolveResult = resolvePackageTarget(
8228
- packageJsonUrl,
8229
- targetItem,
8230
- subpath,
8231
- packageSubpath,
8232
- base,
8233
- pattern,
8234
- internal,
8235
- isPathMap,
8236
- conditions
8237
- );
8238
- } catch (error) {
8239
- const exception = (
8240
- /** @type {ErrnoException} */
8241
- error
8242
- );
8243
- lastException = exception;
8244
- if (exception.code === "ERR_INVALID_PACKAGE_TARGET") continue;
8245
- throw error;
7935
+ if (/(node|data|http|https|file):/.test(id)) {
7936
+ return id;
7937
+ }
7938
+ if (BUILTIN_MODULES.has(id)) {
7939
+ return "node:" + id;
7940
+ }
7941
+ return "file://" + encodeURI(normalizeSlash(id));
7942
+ }
7943
+ var DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
7944
+ var DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
7945
+ var NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
7946
+ "ERR_MODULE_NOT_FOUND",
7947
+ "ERR_UNSUPPORTED_DIR_IMPORT",
7948
+ "MODULE_NOT_FOUND",
7949
+ "ERR_PACKAGE_PATH_NOT_EXPORTED"
7950
+ ]);
7951
+ function _tryModuleResolve(id, url, conditions) {
7952
+ try {
7953
+ return moduleResolve(id, url, conditions);
7954
+ } catch (error) {
7955
+ if (!NOT_FOUND_ERRORS.has(error?.code)) {
7956
+ throw error;
7957
+ }
7958
+ }
7959
+ }
7960
+ function _resolve(id, options = {}) {
7961
+ if (typeof id !== "string") {
7962
+ if (id instanceof URL) {
7963
+ id = fileURLToPath(id);
7964
+ } else {
7965
+ throw new TypeError("input must be a `string` or `URL`");
7966
+ }
7967
+ }
7968
+ if (/(node|data|http|https):/.test(id)) {
7969
+ return id;
7970
+ }
7971
+ if (BUILTIN_MODULES.has(id)) {
7972
+ return "node:" + id;
7973
+ }
7974
+ if (id.startsWith("file://")) {
7975
+ id = fileURLToPath(id);
7976
+ }
7977
+ if (isAbsolute(id)) {
7978
+ try {
7979
+ const stat = statSync(id);
7980
+ if (stat.isFile()) {
7981
+ return pathToFileURL(id);
8246
7982
  }
8247
- if (resolveResult === void 0) continue;
8248
- if (resolveResult === null) {
8249
- lastException = null;
8250
- continue;
7983
+ } catch (error) {
7984
+ if (error?.code !== "ENOENT") {
7985
+ throw error;
8251
7986
  }
8252
- return resolveResult;
8253
7987
  }
8254
- if (lastException === void 0 || lastException === null) {
8255
- return null;
7988
+ }
7989
+ const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
7990
+ const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString())));
7991
+ if (_urls.length === 0) {
7992
+ _urls.push(new URL(pathToFileURL(process.cwd())));
7993
+ }
7994
+ const urls = [..._urls];
7995
+ for (const url of _urls) {
7996
+ if (url.protocol === "file:") {
7997
+ urls.push(
7998
+ new URL("./", url),
7999
+ // If url is directory
8000
+ new URL(joinURL(url.pathname, "_index.js"), url),
8001
+ // TODO: Remove in next major version?
8002
+ new URL("node_modules", url)
8003
+ );
8256
8004
  }
8257
- throw lastException;
8258
8005
  }
8259
- if (typeof target === "object" && target !== null) {
8260
- const keys = Object.getOwnPropertyNames(target);
8261
- let i = -1;
8262
- while (++i < keys.length) {
8263
- const key = keys[i];
8264
- if (isArrayIndex(key)) {
8265
- throw new ERR_INVALID_PACKAGE_CONFIG(
8266
- fileURLToPath$1(packageJsonUrl),
8267
- base,
8268
- '"exports" cannot contain numeric property keys.'
8269
- );
8270
- }
8006
+ let resolved;
8007
+ for (const url of urls) {
8008
+ resolved = _tryModuleResolve(id, url, conditionsSet);
8009
+ if (resolved) {
8010
+ break;
8271
8011
  }
8272
- i = -1;
8273
- while (++i < keys.length) {
8274
- const key = keys[i];
8275
- if (key === "default" || conditions && conditions.has(key)) {
8276
- const conditionalTarget = (
8277
- /** @type {unknown} */
8278
- target[key]
8279
- );
8280
- const resolveResult = resolvePackageTarget(
8281
- packageJsonUrl,
8282
- conditionalTarget,
8283
- subpath,
8284
- packageSubpath,
8285
- base,
8286
- pattern,
8287
- internal,
8288
- isPathMap,
8289
- conditions
8012
+ for (const prefix of ["", "/index"]) {
8013
+ for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
8014
+ resolved = _tryModuleResolve(
8015
+ joinURL(id, prefix) + extension,
8016
+ url,
8017
+ conditionsSet
8290
8018
  );
8291
- if (resolveResult === void 0) continue;
8292
- return resolveResult;
8019
+ if (resolved) {
8020
+ break;
8021
+ }
8022
+ }
8023
+ if (resolved) {
8024
+ break;
8293
8025
  }
8294
8026
  }
8295
- return null;
8027
+ if (resolved) {
8028
+ break;
8029
+ }
8296
8030
  }
8297
- if (target === null) {
8298
- return null;
8031
+ if (!resolved) {
8032
+ const error = new Error(
8033
+ `Cannot find module ${id} imported from ${urls.join(", ")}`
8034
+ );
8035
+ error.code = "ERR_MODULE_NOT_FOUND";
8036
+ throw error;
8299
8037
  }
8300
- throw invalidPackageTarget(
8301
- packageSubpath,
8302
- target,
8303
- packageJsonUrl,
8304
- internal,
8305
- base
8306
- );
8038
+ return pathToFileURL(resolved);
8307
8039
  }
8308
- function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
8309
- if (typeof exports === "string" || Array.isArray(exports)) return true;
8310
- if (typeof exports !== "object" || exports === null) return false;
8311
- const keys = Object.getOwnPropertyNames(exports);
8312
- let isConditionalSugar = false;
8313
- let i = 0;
8314
- let keyIndex = -1;
8315
- while (++keyIndex < keys.length) {
8316
- const key = keys[keyIndex];
8317
- const currentIsConditionalSugar = key === "" || key[0] !== ".";
8318
- if (i++ === 0) {
8319
- isConditionalSugar = currentIsConditionalSugar;
8320
- } else if (isConditionalSugar !== currentIsConditionalSugar) {
8321
- throw new ERR_INVALID_PACKAGE_CONFIG(
8322
- fileURLToPath$1(packageJsonUrl),
8323
- base,
8324
- `"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.`
8325
- );
8326
- }
8327
- }
8328
- return isConditionalSugar;
8040
+ function resolveSync(id, options) {
8041
+ return _resolve(id, options);
8329
8042
  }
8330
- function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
8331
- if (process$1.noDeprecation) {
8332
- return;
8333
- }
8334
- const pjsonPath = fileURLToPath$1(pjsonUrl);
8335
- if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return;
8336
- emittedPackageWarnings.add(pjsonPath + "|" + match);
8337
- process$1.emitWarning(
8338
- `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.`,
8339
- "DeprecationWarning",
8340
- "DEP0155"
8341
- );
8043
+ function resolvePathSync(id, options) {
8044
+ return fileURLToPath(resolveSync(id, options));
8342
8045
  }
8343
- function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
8344
- let exports = packageConfig.exports;
8345
- if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
8346
- exports = { ".": exports };
8046
+
8047
+ // src/node-js-compat.ts
8048
+ import { defineEnv } from "unenv";
8049
+ var { env } = defineEnv({
8050
+ nodeCompat: true,
8051
+ presets: [cloudflare]
8052
+ });
8053
+ var nodeCompatExternals = new Set(env.external);
8054
+ var nodeCompatEntries = getNodeCompatEntries();
8055
+ function isNodeCompat(workerConfig) {
8056
+ if (workerConfig === void 0) {
8057
+ return false;
8347
8058
  }
8348
- if (own.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
8349
- const target = exports[packageSubpath];
8350
- const resolveResult = resolvePackageTarget(
8351
- packageJsonUrl,
8352
- target,
8353
- "",
8354
- packageSubpath,
8355
- base,
8356
- false,
8357
- false,
8358
- false,
8359
- conditions
8059
+ const nodeCompatMode = getNodeCompat(
8060
+ workerConfig.compatibility_date,
8061
+ workerConfig.compatibility_flags ?? []
8062
+ ).mode;
8063
+ if (nodeCompatMode === "v2") {
8064
+ return true;
8065
+ }
8066
+ if (nodeCompatMode === "v1") {
8067
+ throw new Error(
8068
+ `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`
8360
8069
  );
8361
- if (resolveResult === null || resolveResult === void 0) {
8362
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
8363
- }
8364
- return resolveResult;
8365
8070
  }
8366
- let bestMatch = "";
8367
- let bestMatchSubpath = "";
8368
- const keys = Object.getOwnPropertyNames(exports);
8369
- let i = -1;
8370
- while (++i < keys.length) {
8371
- const key = keys[i];
8372
- const patternIndex = key.indexOf("*");
8373
- if (patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex))) {
8374
- if (packageSubpath.endsWith("/")) {
8375
- emitTrailingSlashPatternDeprecation(
8376
- packageSubpath,
8377
- packageJsonUrl,
8378
- base
8379
- );
8380
- }
8381
- const patternTrailer = key.slice(patternIndex + 1);
8382
- if (packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
8383
- bestMatch = key;
8384
- bestMatchSubpath = packageSubpath.slice(
8385
- patternIndex,
8386
- packageSubpath.length - patternTrailer.length
8387
- );
8388
- }
8071
+ return false;
8072
+ }
8073
+ function injectGlobalCode(id, code) {
8074
+ const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
8075
+ if (typeof globalInject === "string") {
8076
+ const moduleSpecifier2 = globalInject;
8077
+ return `import var_${globalName} from "${moduleSpecifier2}";
8078
+ globalThis.${globalName} = var_${globalName};
8079
+ `;
8389
8080
  }
8390
- }
8391
- if (bestMatch) {
8392
- const target = (
8393
- /** @type {unknown} */
8394
- exports[bestMatch]
8395
- );
8396
- const resolveResult = resolvePackageTarget(
8397
- packageJsonUrl,
8398
- target,
8399
- bestMatchSubpath,
8400
- bestMatch,
8401
- base,
8402
- true,
8403
- false,
8404
- packageSubpath.endsWith("/"),
8405
- conditions
8081
+ const [moduleSpecifier, exportName] = globalInject;
8082
+ assert2(
8083
+ moduleSpecifier !== void 0,
8084
+ "Expected moduleSpecifier to be defined"
8406
8085
  );
8407
- if (resolveResult === null || resolveResult === void 0) {
8408
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
8086
+ assert2(exportName !== void 0, "Expected exportName to be defined");
8087
+ return `import var_${globalName} from "${moduleSpecifier}";
8088
+ globalThis.${globalName} = var_${globalName}.${exportName};
8089
+ `;
8090
+ }).join("\n");
8091
+ const polyfillCode = env.polyfill.map((polyfillPath) => `import "${polyfillPath}";
8092
+ `).join("");
8093
+ const modified = new MagicString(code);
8094
+ modified.prepend(injectedCode);
8095
+ modified.prepend(polyfillCode);
8096
+ return {
8097
+ code: modified.toString(),
8098
+ map: modified.generateMap({ hires: "boundary", source: id })
8099
+ };
8100
+ }
8101
+ function resolveNodeJSImport(source) {
8102
+ const alias = env.alias[source];
8103
+ if (alias) {
8104
+ return {
8105
+ unresolved: alias,
8106
+ resolved: resolvePathSync(alias, { url: import.meta.url })
8107
+ };
8108
+ }
8109
+ if (nodeCompatEntries.has(source)) {
8110
+ return {
8111
+ unresolved: source,
8112
+ resolved: resolvePathSync(source, { url: import.meta.url })
8113
+ };
8114
+ }
8115
+ }
8116
+ function getNodeCompatEntries() {
8117
+ const entries = new Set(Object.values(env.alias));
8118
+ for (const globalInject of Object.values(env.inject)) {
8119
+ if (typeof globalInject === "string") {
8120
+ entries.add(globalInject);
8121
+ } else {
8122
+ assert2(
8123
+ globalInject[0] !== void 0,
8124
+ "Expected first element of globalInject to be defined"
8125
+ );
8126
+ entries.add(globalInject[0]);
8409
8127
  }
8410
- return resolveResult;
8411
8128
  }
8412
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
8129
+ env.polyfill.forEach((polyfill) => entries.add(polyfill));
8130
+ nodeCompatExternals.forEach((external) => entries.delete(external));
8131
+ return entries;
8413
8132
  }
8414
- function patternKeyCompare(a, b) {
8415
- const aPatternIndex = a.indexOf("*");
8416
- const bPatternIndex = b.indexOf("*");
8417
- const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
8418
- const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
8419
- if (baseLengthA > baseLengthB) return -1;
8420
- if (baseLengthB > baseLengthA) return 1;
8421
- if (aPatternIndex === -1) return 1;
8422
- if (bPatternIndex === -1) return -1;
8423
- if (a.length > b.length) return -1;
8424
- if (b.length > a.length) return 1;
8425
- return 0;
8133
+
8134
+ // src/shared.ts
8135
+ var UNKNOWN_HOST = "http://localhost";
8136
+ var INIT_PATH = "/__vite_plugin_cloudflare_init__";
8137
+ var ADDITIONAL_MODULE_PATTERN = `__CLOUDFLARE_MODULE__(${ADDITIONAL_MODULE_TYPES.join("|")})__(.*?)__`;
8138
+ var additionalModuleRE = new RegExp(ADDITIONAL_MODULE_PATTERN);
8139
+ var additionalModuleGlobalRE = new RegExp(
8140
+ ADDITIONAL_MODULE_PATTERN,
8141
+ "g"
8142
+ );
8143
+ var VITE_DEV_METADATA_HEADER = "__VITE_DEV_METADATA__";
8144
+
8145
+ // src/utils.ts
8146
+ import * as path2 from "node:path";
8147
+ import { Request as MiniflareRequest } from "miniflare";
8148
+ import "vite";
8149
+ function getOutputDirectory(userConfig, environmentName) {
8150
+ const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
8151
+ return userConfig.environments?.[environmentName]?.build?.outDir ?? path2.join(rootOutputDirectory, environmentName);
8426
8152
  }
8427
- function packageImportsResolve(name2, base, conditions) {
8428
- if (name2 === "#" || name2.startsWith("#/") || name2.endsWith("/")) {
8429
- const reason = "is not a valid internal imports specifier name";
8430
- throw new ERR_INVALID_MODULE_SPECIFIER(name2, reason, fileURLToPath$1(base));
8431
- }
8432
- let packageJsonUrl;
8433
- const packageConfig = getPackageScopeConfig(base);
8434
- if (packageConfig.exists) {
8435
- packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
8436
- const imports = packageConfig.imports;
8437
- if (imports) {
8438
- if (own.call(imports, name2) && !name2.includes("*")) {
8439
- const resolveResult = resolvePackageTarget(
8440
- packageJsonUrl,
8441
- imports[name2],
8442
- "",
8443
- name2,
8444
- base,
8445
- false,
8446
- true,
8447
- false,
8448
- conditions
8449
- );
8450
- if (resolveResult !== null && resolveResult !== void 0) {
8451
- return resolveResult;
8452
- }
8453
- } else {
8454
- let bestMatch = "";
8455
- let bestMatchSubpath = "";
8456
- const keys = Object.getOwnPropertyNames(imports);
8457
- let i = -1;
8458
- while (++i < keys.length) {
8459
- const key = keys[i];
8460
- const patternIndex = key.indexOf("*");
8461
- if (patternIndex !== -1 && name2.startsWith(key.slice(0, -1))) {
8462
- const patternTrailer = key.slice(patternIndex + 1);
8463
- if (name2.length >= key.length && name2.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
8464
- bestMatch = key;
8465
- bestMatchSubpath = name2.slice(
8466
- patternIndex,
8467
- name2.length - patternTrailer.length
8468
- );
8469
- }
8470
- }
8471
- }
8472
- if (bestMatch) {
8473
- const target = imports[bestMatch];
8474
- const resolveResult = resolvePackageTarget(
8475
- packageJsonUrl,
8476
- target,
8477
- bestMatchSubpath,
8478
- bestMatch,
8479
- base,
8480
- true,
8481
- true,
8482
- false,
8483
- conditions
8484
- );
8485
- if (resolveResult !== null && resolveResult !== void 0) {
8486
- return resolveResult;
8487
- }
8488
- }
8153
+ function getRouterWorker(miniflare) {
8154
+ return miniflare.getWorker(ROUTER_WORKER_NAME);
8155
+ }
8156
+ function toMiniflareRequest(request) {
8157
+ return new MiniflareRequest(request.url, {
8158
+ method: request.method,
8159
+ headers: [["accept-encoding", "identity"], ...request.headers],
8160
+ body: request.body,
8161
+ duplex: "half"
8162
+ });
8163
+ }
8164
+ function nodeHeadersToWebHeaders(nodeHeaders) {
8165
+ const headers = new Headers();
8166
+ for (const [key, value] of Object.entries(nodeHeaders)) {
8167
+ if (typeof value === "string") {
8168
+ headers.append(key, value);
8169
+ } else if (Array.isArray(value)) {
8170
+ for (const item of value) {
8171
+ headers.append(key, item);
8489
8172
  }
8490
8173
  }
8491
8174
  }
8492
- throw importNotDefined(name2, packageJsonUrl, base);
8175
+ return headers;
8493
8176
  }
8494
- function parsePackageName(specifier, base) {
8495
- let separatorIndex = specifier.indexOf("/");
8496
- let validPackageName = true;
8497
- let isScoped = false;
8498
- if (specifier[0] === "@") {
8499
- isScoped = true;
8500
- if (separatorIndex === -1 || specifier.length === 0) {
8501
- validPackageName = false;
8502
- } else {
8503
- separatorIndex = specifier.indexOf("/", separatorIndex + 1);
8177
+ var postfixRE = /[?#].*$/;
8178
+ function cleanUrl(url) {
8179
+ return url.replace(postfixRE, "");
8180
+ }
8181
+
8182
+ // src/cloudflare-environment.ts
8183
+ var webSocketUndefinedError = "The WebSocket is undefined";
8184
+ function createHotChannel(webSocketContainer) {
8185
+ const listenersMap = /* @__PURE__ */ new Map();
8186
+ const client = {
8187
+ send(payload) {
8188
+ const webSocket = webSocketContainer.webSocket;
8189
+ assert3(webSocket, webSocketUndefinedError);
8190
+ webSocket.send(JSON.stringify(payload));
8191
+ }
8192
+ };
8193
+ function onMessage(event) {
8194
+ const payload = JSON.parse(event.data.toString());
8195
+ const listeners = listenersMap.get(payload.event) ?? /* @__PURE__ */ new Set();
8196
+ for (const listener of listeners) {
8197
+ listener(payload.data, client);
8504
8198
  }
8505
8199
  }
8506
- const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
8507
- if (invalidPackageNameRegEx.exec(packageName) !== null) {
8508
- validPackageName = false;
8200
+ return {
8201
+ send(payload) {
8202
+ const webSocket = webSocketContainer.webSocket;
8203
+ assert3(webSocket, webSocketUndefinedError);
8204
+ webSocket.send(JSON.stringify(payload));
8205
+ },
8206
+ on(event, listener) {
8207
+ const listeners = listenersMap.get(event) ?? /* @__PURE__ */ new Set();
8208
+ listeners.add(listener);
8209
+ listenersMap.set(event, listeners);
8210
+ },
8211
+ off(event, listener) {
8212
+ listenersMap.get(event)?.delete(listener);
8213
+ },
8214
+ listen() {
8215
+ const webSocket = webSocketContainer.webSocket;
8216
+ assert3(webSocket, webSocketUndefinedError);
8217
+ webSocket.addEventListener("message", onMessage);
8218
+ },
8219
+ close() {
8220
+ const webSocket = webSocketContainer.webSocket;
8221
+ assert3(webSocket, webSocketUndefinedError);
8222
+ webSocket.removeEventListener("message", onMessage);
8223
+ }
8224
+ };
8225
+ }
8226
+ var CloudflareDevEnvironment = class extends vite2.DevEnvironment {
8227
+ #webSocketContainer;
8228
+ #worker;
8229
+ constructor(name, config) {
8230
+ const webSocketContainer = {};
8231
+ super(name, config, {
8232
+ hot: true,
8233
+ transport: createHotChannel(webSocketContainer)
8234
+ });
8235
+ this.#webSocketContainer = webSocketContainer;
8509
8236
  }
8510
- if (!validPackageName) {
8511
- throw new ERR_INVALID_MODULE_SPECIFIER(
8512
- specifier,
8513
- "is not a valid package name",
8514
- fileURLToPath$1(base)
8237
+ async initRunner(worker, root, workerConfig) {
8238
+ this.#worker = worker;
8239
+ const response = await this.#worker.fetch(
8240
+ new URL(INIT_PATH, UNKNOWN_HOST),
8241
+ {
8242
+ headers: {
8243
+ [VITE_DEV_METADATA_HEADER]: JSON.stringify({
8244
+ root,
8245
+ entryPath: workerConfig.main
8246
+ }),
8247
+ upgrade: "websocket"
8248
+ }
8249
+ }
8515
8250
  );
8251
+ assert3(
8252
+ response.ok,
8253
+ `Failed to initialize module runner, error: ${await response.text()}`
8254
+ );
8255
+ const webSocket = response.webSocket;
8256
+ assert3(webSocket, "Failed to establish WebSocket");
8257
+ webSocket.accept();
8258
+ this.#webSocketContainer.webSocket = webSocket;
8516
8259
  }
8517
- const packageSubpath = "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex));
8518
- return { packageName, packageSubpath, isScoped };
8519
- }
8520
- function packageResolve(specifier, base, conditions) {
8521
- if (builtinModules.includes(specifier)) {
8522
- return new URL$1("node:" + specifier);
8523
- }
8524
- const { packageName, packageSubpath, isScoped } = parsePackageName(
8525
- specifier,
8526
- base
8527
- );
8528
- const packageConfig = getPackageScopeConfig(base);
8529
- if (packageConfig.exists) {
8530
- const packageJsonUrl2 = pathToFileURL$1(packageConfig.pjsonPath);
8531
- if (packageConfig.name === packageName && packageConfig.exports !== void 0 && packageConfig.exports !== null) {
8532
- return packageExportsResolve(
8533
- packageJsonUrl2,
8534
- packageSubpath,
8535
- packageConfig,
8536
- base,
8537
- conditions
8538
- );
8539
- }
8260
+ };
8261
+ var cloudflareBuiltInModules = [
8262
+ "cloudflare:email",
8263
+ "cloudflare:sockets",
8264
+ "cloudflare:workers",
8265
+ "cloudflare:workflows"
8266
+ ];
8267
+ var defaultConditions = ["workerd", "module", "browser"];
8268
+ var target = "es2022";
8269
+ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmentName) {
8270
+ return {
8271
+ resolve: {
8272
+ // Note: in order for ssr pre-bundling to take effect we need to ask vite to treat all
8273
+ // dependencies as not external
8274
+ noExternal: true,
8275
+ // We want to use `workerd` package exports if available (e.g. for postgres).
8276
+ conditions: [...defaultConditions, "development|production"],
8277
+ // The Cloudflare ones are proper builtins in the environment
8278
+ builtins: [...cloudflareBuiltInModules]
8279
+ },
8280
+ dev: {
8281
+ createEnvironment(name, config) {
8282
+ return new CloudflareDevEnvironment(name, config);
8283
+ }
8284
+ },
8285
+ build: {
8286
+ createEnvironment(name, config) {
8287
+ return new vite2.BuildEnvironment(name, config);
8288
+ },
8289
+ target,
8290
+ // We need to enable `emitAssets` in order to support additional modules defined by `rules`
8291
+ emitAssets: true,
8292
+ outDir: getOutputDirectory(userConfig, environmentName),
8293
+ copyPublicDir: false,
8294
+ ssr: true,
8295
+ rollupOptions: {
8296
+ // Note: vite starts dev pre-bundling crawling from either optimizeDeps.entries or rollupOptions.input
8297
+ // so the input value here serves both as the build input as well as the starting point for
8298
+ // dev pre-bundling crawling (were we not to set this input field we'd have to appropriately set
8299
+ // optimizeDeps.entries in the dev config)
8300
+ input: workerConfig.main
8301
+ }
8302
+ },
8303
+ optimizeDeps: {
8304
+ // Note: ssr pre-bundling is opt-in and we need to enable it by setting `noDiscovery` to false
8305
+ noDiscovery: false,
8306
+ entries: workerConfig.main,
8307
+ exclude: [...cloudflareBuiltInModules],
8308
+ esbuildOptions: {
8309
+ platform: "neutral",
8310
+ target,
8311
+ conditions: [...defaultConditions, "development"],
8312
+ resolveExtensions: [
8313
+ ".mjs",
8314
+ ".js",
8315
+ ".mts",
8316
+ ".ts",
8317
+ ".jsx",
8318
+ ".tsx",
8319
+ ".json",
8320
+ ".cjs",
8321
+ ".cts",
8322
+ ".ctx"
8323
+ ]
8324
+ }
8325
+ },
8326
+ // if nodeCompat is enabled then let's keep the real process.env so that workerd can manipulate it
8327
+ keepProcessEnv: isNodeCompat(workerConfig)
8328
+ };
8329
+ }
8330
+ function initRunners(resolvedPluginConfig, viteDevServer, miniflare) {
8331
+ if (resolvedPluginConfig.type === "assets-only") {
8332
+ return;
8540
8333
  }
8541
- let packageJsonUrl = new URL$1(
8542
- "./node_modules/" + packageName + "/package.json",
8543
- base
8334
+ return Promise.all(
8335
+ Object.entries(resolvedPluginConfig.workers).map(
8336
+ async ([environmentName, workerConfig]) => {
8337
+ const worker = await miniflare.getWorker(workerConfig.name);
8338
+ return viteDevServer.environments[environmentName].initRunner(worker, viteDevServer.config.root, workerConfig);
8339
+ }
8340
+ )
8544
8341
  );
8545
- let packageJsonPath = fileURLToPath$1(packageJsonUrl);
8546
- let lastPath;
8547
- do {
8548
- const stat = tryStatSync(packageJsonPath.slice(0, -13));
8549
- if (!stat || !stat.isDirectory()) {
8550
- lastPath = packageJsonPath;
8551
- packageJsonUrl = new URL$1(
8552
- (isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json",
8553
- packageJsonUrl
8554
- );
8555
- packageJsonPath = fileURLToPath$1(packageJsonUrl);
8556
- continue;
8557
- }
8558
- const packageConfig2 = read(packageJsonPath, { base, specifier });
8559
- if (packageConfig2.exports !== void 0 && packageConfig2.exports !== null) {
8560
- return packageExportsResolve(
8561
- packageJsonUrl,
8562
- packageSubpath,
8563
- packageConfig2,
8564
- base,
8565
- conditions
8566
- );
8567
- }
8568
- if (packageSubpath === ".") {
8569
- return legacyMainResolve(packageJsonUrl, packageConfig2, base);
8570
- }
8571
- return new URL$1(packageSubpath, packageJsonUrl);
8572
- } while (packageJsonPath.length !== lastPath.length);
8573
- throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath$1(base), false);
8574
8342
  }
8575
- function isRelativeSpecifier(specifier) {
8576
- if (specifier[0] === ".") {
8577
- if (specifier.length === 1 || specifier[1] === "/") return true;
8578
- if (specifier[1] === "." && (specifier.length === 2 || specifier[2] === "/")) {
8579
- return true;
8580
- }
8581
- }
8582
- return false;
8343
+
8344
+ // src/deploy-config.ts
8345
+ import assert4 from "node:assert";
8346
+ import * as fs2 from "node:fs";
8347
+ import * as path3 from "node:path";
8348
+ import "vite";
8349
+ function getDeployConfigPath(root) {
8350
+ return path3.resolve(root, ".wrangler", "deploy", "config.json");
8583
8351
  }
8584
- function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
8585
- if (specifier === "") return false;
8586
- if (specifier[0] === "/") return true;
8587
- return isRelativeSpecifier(specifier);
8352
+ function getWorkerConfigPaths(root) {
8353
+ const deployConfigPath = getDeployConfigPath(root);
8354
+ const deployConfig = JSON.parse(
8355
+ fs2.readFileSync(deployConfigPath, "utf-8")
8356
+ );
8357
+ return [
8358
+ { configPath: deployConfig.configPath },
8359
+ ...deployConfig.auxiliaryWorkers
8360
+ ].map(
8361
+ ({ configPath }) => path3.resolve(path3.dirname(deployConfigPath), configPath)
8362
+ );
8588
8363
  }
8589
- function moduleResolve(specifier, base, conditions, preserveSymlinks) {
8590
- const protocol = base.protocol;
8591
- const isData = protocol === "data:";
8592
- const isRemote = isData || protocol === "http:" || protocol === "https:";
8593
- let resolved;
8594
- if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
8595
- try {
8596
- resolved = new URL$1(specifier, base);
8597
- } catch (error_) {
8598
- const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8599
- error.cause = error_;
8600
- throw error;
8601
- }
8602
- } else if (protocol === "file:" && specifier[0] === "#") {
8603
- resolved = packageImportsResolve(specifier, base, conditions);
8364
+ function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
8365
+ return path3.relative(
8366
+ deployConfigDirectory,
8367
+ path3.resolve(root, outputDirectory, "wrangler.json")
8368
+ );
8369
+ }
8370
+ function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
8371
+ const deployConfigPath = getDeployConfigPath(resolvedViteConfig.root);
8372
+ const deployConfigDirectory = path3.dirname(deployConfigPath);
8373
+ fs2.mkdirSync(deployConfigDirectory, { recursive: true });
8374
+ if (resolvedPluginConfig.type === "assets-only") {
8375
+ const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
8376
+ assert4(
8377
+ clientOutputDirectory,
8378
+ "Unexpected error: client environment output directory is undefined"
8379
+ );
8380
+ const deployConfig = {
8381
+ configPath: getRelativePathToWorkerConfig(
8382
+ deployConfigDirectory,
8383
+ resolvedViteConfig.root,
8384
+ clientOutputDirectory
8385
+ ),
8386
+ auxiliaryWorkers: []
8387
+ };
8388
+ fs2.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
8604
8389
  } else {
8605
- try {
8606
- resolved = new URL$1(specifier);
8607
- } catch (error_) {
8608
- if (isRemote && !builtinModules.includes(specifier)) {
8609
- const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8610
- error.cause = error_;
8611
- throw error;
8390
+ let entryWorkerConfigPath;
8391
+ const auxiliaryWorkers = [];
8392
+ for (const environmentName of Object.keys(resolvedPluginConfig.workers)) {
8393
+ const outputDirectory = resolvedViteConfig.environments[environmentName]?.build.outDir;
8394
+ assert4(
8395
+ outputDirectory,
8396
+ `Unexpected error: ${environmentName} environment output directory is undefined`
8397
+ );
8398
+ const configPath = getRelativePathToWorkerConfig(
8399
+ deployConfigDirectory,
8400
+ resolvedViteConfig.root,
8401
+ outputDirectory
8402
+ );
8403
+ if (environmentName === resolvedPluginConfig.entryWorkerEnvironmentName) {
8404
+ entryWorkerConfigPath = configPath;
8405
+ } else {
8406
+ auxiliaryWorkers.push({ configPath });
8612
8407
  }
8613
- resolved = packageResolve(specifier, base, conditions);
8614
8408
  }
8409
+ assert4(
8410
+ entryWorkerConfigPath,
8411
+ `Unexpected error: entryWorkerConfigPath is undefined`
8412
+ );
8413
+ const deployConfig = {
8414
+ configPath: entryWorkerConfigPath,
8415
+ auxiliaryWorkers
8416
+ };
8417
+ fs2.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
8615
8418
  }
8616
- assert5(resolved !== void 0, "expected to be defined");
8617
- if (resolved.protocol !== "file:") {
8618
- return resolved;
8619
- }
8620
- return finalizeResolution(resolved, base);
8621
8419
  }
8622
- function fileURLToPath2(id) {
8623
- if (typeof id === "string" && !id.startsWith("file://")) {
8624
- return normalizeSlash(id);
8420
+
8421
+ // src/miniflare-options.ts
8422
+ import assert5 from "node:assert";
8423
+ import * as fs3 from "node:fs";
8424
+ import * as fsp from "node:fs/promises";
8425
+ import * as path4 from "node:path";
8426
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
8427
+ import {
8428
+ kCurrentWorker,
8429
+ Log,
8430
+ LogLevel,
8431
+ Response as MiniflareResponse
8432
+ } from "miniflare";
8433
+ import { globSync } from "tinyglobby";
8434
+ import "vite";
8435
+ import {
8436
+ unstable_getMiniflareWorkerOptions,
8437
+ unstable_readConfig
8438
+ } from "wrangler";
8439
+ function getPersistence(root, persistState) {
8440
+ if (persistState === false) {
8441
+ return {};
8625
8442
  }
8626
- return normalizeSlash(fileURLToPath$1(id));
8443
+ const defaultPersistPath = ".wrangler/state";
8444
+ const persistPath = path4.resolve(
8445
+ root,
8446
+ typeof persistState === "object" ? persistState.path : defaultPersistPath,
8447
+ "v3"
8448
+ );
8449
+ return {
8450
+ cachePersist: path4.join(persistPath, "cache"),
8451
+ d1Persist: path4.join(persistPath, "d1"),
8452
+ durableObjectsPersist: path4.join(persistPath, "do"),
8453
+ kvPersist: path4.join(persistPath, "kv"),
8454
+ r2Persist: path4.join(persistPath, "r2"),
8455
+ workflowsPersist: path4.join(persistPath, "workflows")
8456
+ };
8627
8457
  }
8628
- function pathToFileURL(id) {
8629
- return pathToFileURL$1(fileURLToPath2(id)).toString();
8458
+ function missingWorkerErrorMessage(workerName) {
8459
+ return `${workerName} does not match a worker name.`;
8630
8460
  }
8631
- function normalizeid(id) {
8632
- if (typeof id !== "string") {
8633
- id = id.toString();
8634
- }
8635
- if (/(node|data|http|https|file):/.test(id)) {
8636
- return id;
8461
+ function getWorkerToWorkerEntrypointNamesMap(workers) {
8462
+ const workerToWorkerEntrypointNamesMap = new Map(
8463
+ workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
8464
+ );
8465
+ for (const worker of workers) {
8466
+ for (const value of Object.values(worker.serviceBindings ?? {})) {
8467
+ if (typeof value === "object" && "name" in value && value.entrypoint !== void 0 && value.entrypoint !== "default") {
8468
+ const targetWorkerName = value.name === kCurrentWorker ? worker.name : value.name;
8469
+ const entrypointNames = workerToWorkerEntrypointNamesMap.get(targetWorkerName);
8470
+ assert5(entrypointNames, missingWorkerErrorMessage(targetWorkerName));
8471
+ entrypointNames.add(value.entrypoint);
8472
+ }
8473
+ }
8637
8474
  }
8638
- if (BUILTIN_MODULES.has(id)) {
8639
- return "node:" + id;
8475
+ return workerToWorkerEntrypointNamesMap;
8476
+ }
8477
+ function getWorkerToDurableObjectClassNamesMap(workers) {
8478
+ const workerToDurableObjectClassNamesMap = new Map(
8479
+ workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
8480
+ );
8481
+ for (const worker of workers) {
8482
+ for (const value of Object.values(worker.durableObjects ?? {})) {
8483
+ if (typeof value === "string") {
8484
+ const classNames = workerToDurableObjectClassNamesMap.get(worker.name);
8485
+ assert5(classNames, missingWorkerErrorMessage(worker.name));
8486
+ classNames.add(value);
8487
+ } else if (typeof value === "object") {
8488
+ if (value.scriptName) {
8489
+ const classNames = workerToDurableObjectClassNamesMap.get(
8490
+ value.scriptName
8491
+ );
8492
+ assert5(classNames, missingWorkerErrorMessage(value.scriptName));
8493
+ classNames.add(value.className);
8494
+ } else {
8495
+ const classNames = workerToDurableObjectClassNamesMap.get(
8496
+ worker.name
8497
+ );
8498
+ assert5(classNames, missingWorkerErrorMessage(worker.name));
8499
+ classNames.add(value.className);
8500
+ }
8501
+ }
8502
+ }
8640
8503
  }
8641
- return "file://" + encodeURI(normalizeSlash(id));
8504
+ return workerToDurableObjectClassNamesMap;
8642
8505
  }
8643
- var DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
8644
- var DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
8645
- var NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
8646
- "ERR_MODULE_NOT_FOUND",
8647
- "ERR_UNSUPPORTED_DIR_IMPORT",
8648
- "MODULE_NOT_FOUND",
8649
- "ERR_PACKAGE_PATH_NOT_EXPORTED"
8650
- ]);
8651
- function _tryModuleResolve(id, url, conditions) {
8652
- try {
8653
- return moduleResolve(id, url, conditions);
8654
- } catch (error) {
8655
- if (!NOT_FOUND_ERRORS.has(error?.code)) {
8656
- throw error;
8506
+ function getWorkerToWorkflowEntrypointClassNamesMap(workers) {
8507
+ const workerToWorkflowEntrypointClassNamesMap = new Map(
8508
+ workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
8509
+ );
8510
+ for (const worker of workers) {
8511
+ for (const value of Object.values(worker.workflows ?? {})) {
8512
+ if (value.scriptName) {
8513
+ const classNames = workerToWorkflowEntrypointClassNamesMap.get(
8514
+ value.scriptName
8515
+ );
8516
+ assert5(classNames, missingWorkerErrorMessage(value.scriptName));
8517
+ classNames.add(value.className);
8518
+ } else {
8519
+ const classNames = workerToWorkflowEntrypointClassNamesMap.get(
8520
+ worker.name
8521
+ );
8522
+ assert5(classNames, missingWorkerErrorMessage(worker.name));
8523
+ classNames.add(value.className);
8524
+ }
8657
8525
  }
8658
8526
  }
8527
+ return workerToWorkflowEntrypointClassNamesMap;
8659
8528
  }
8660
- function _resolve(id, options = {}) {
8661
- if (typeof id !== "string") {
8662
- if (id instanceof URL) {
8663
- id = fileURLToPath2(id);
8664
- } else {
8665
- throw new TypeError("input must be a `string` or `URL`");
8666
- }
8667
- }
8668
- if (/(node|data|http|https):/.test(id)) {
8669
- return id;
8670
- }
8671
- if (BUILTIN_MODULES.has(id)) {
8672
- return "node:" + id;
8673
- }
8674
- if (id.startsWith("file://")) {
8675
- id = fileURLToPath2(id);
8529
+ var miniflareModulesRoot = process.platform === "win32" ? "Z:\\" : "/";
8530
+ var ROUTER_WORKER_PATH = "./asset-workers/router-worker.js";
8531
+ var ASSET_WORKER_PATH = "./asset-workers/asset-worker.js";
8532
+ var WRAPPER_PATH = "__VITE_WORKER_ENTRY__";
8533
+ var RUNNER_PATH = "./runner-worker/index.js";
8534
+ function getEntryWorkerConfig(resolvedPluginConfig) {
8535
+ if (resolvedPluginConfig.type === "assets-only") {
8536
+ return;
8676
8537
  }
8677
- if (isAbsolute(id)) {
8678
- try {
8679
- const stat = statSync2(id);
8680
- if (stat.isFile()) {
8681
- return pathToFileURL(id);
8538
+ return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
8539
+ }
8540
+ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
8541
+ const resolvedViteConfig = viteDevServer.config;
8542
+ const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
8543
+ const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
8544
+ const assetWorkers = [
8545
+ {
8546
+ name: ROUTER_WORKER_NAME,
8547
+ compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
8548
+ modulesRoot: miniflareModulesRoot,
8549
+ modules: [
8550
+ {
8551
+ type: "ESModule",
8552
+ path: path4.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
8553
+ contents: fs3.readFileSync(
8554
+ fileURLToPath2(new URL(ROUTER_WORKER_PATH, import.meta.url))
8555
+ )
8556
+ }
8557
+ ],
8558
+ bindings: {
8559
+ CONFIG: {
8560
+ has_user_worker: resolvedPluginConfig.type === "workers"
8561
+ }
8562
+ },
8563
+ serviceBindings: {
8564
+ ASSET_WORKER: ASSET_WORKER_NAME,
8565
+ ...entryWorkerConfig ? { USER_WORKER: entryWorkerConfig.name } : {}
8682
8566
  }
8683
- } catch (error) {
8684
- if (error?.code !== "ENOENT") {
8685
- throw error;
8567
+ },
8568
+ {
8569
+ name: ASSET_WORKER_NAME,
8570
+ compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
8571
+ modulesRoot: miniflareModulesRoot,
8572
+ modules: [
8573
+ {
8574
+ type: "ESModule",
8575
+ path: path4.join(miniflareModulesRoot, ASSET_WORKER_PATH),
8576
+ contents: fs3.readFileSync(
8577
+ fileURLToPath2(new URL(ASSET_WORKER_PATH, import.meta.url))
8578
+ )
8579
+ }
8580
+ ],
8581
+ bindings: {
8582
+ CONFIG: {
8583
+ ...assetsConfig?.html_handling ? { html_handling: assetsConfig.html_handling } : {},
8584
+ ...assetsConfig?.not_found_handling ? { not_found_handling: assetsConfig.not_found_handling } : {}
8585
+ }
8586
+ },
8587
+ serviceBindings: {
8588
+ __VITE_ASSET_EXISTS__: async (request) => {
8589
+ const { pathname } = new URL(request.url);
8590
+ const filePath = path4.join(resolvedViteConfig.root, pathname);
8591
+ let exists;
8592
+ try {
8593
+ exists = fs3.statSync(filePath).isFile();
8594
+ } catch (error) {
8595
+ exists = false;
8596
+ }
8597
+ return MiniflareResponse.json(exists);
8598
+ },
8599
+ __VITE_FETCH_ASSET__: async (request) => {
8600
+ const { pathname } = new URL(request.url);
8601
+ const filePath = path4.join(resolvedViteConfig.root, pathname);
8602
+ try {
8603
+ let html = await fsp.readFile(filePath, "utf-8");
8604
+ html = await viteDevServer.transformIndexHtml(pathname, html);
8605
+ return new MiniflareResponse(html, {
8606
+ headers: { "Content-Type": "text/html" }
8607
+ });
8608
+ } catch (error) {
8609
+ throw new Error(`Unexpected error. Failed to load ${pathname}`);
8610
+ }
8611
+ }
8686
8612
  }
8687
8613
  }
8688
- }
8689
- const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
8690
- const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString())));
8691
- if (_urls.length === 0) {
8692
- _urls.push(new URL(pathToFileURL(process.cwd())));
8693
- }
8694
- const urls = [..._urls];
8695
- for (const url of _urls) {
8696
- if (url.protocol === "file:") {
8697
- urls.push(
8698
- new URL("./", url),
8699
- // If url is directory
8700
- new URL(joinURL(url.pathname, "_index.js"), url),
8701
- // TODO: Remove in next major version?
8702
- new URL("node_modules", url)
8614
+ ];
8615
+ const workersFromConfig = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
8616
+ ([environmentName, workerConfig]) => {
8617
+ const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
8618
+ {
8619
+ ...workerConfig,
8620
+ assets: void 0
8621
+ },
8622
+ resolvedPluginConfig.cloudflareEnv
8703
8623
  );
8624
+ const { externalWorkers: externalWorkers2 } = miniflareWorkerOptions;
8625
+ const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
8626
+ return {
8627
+ externalWorkers: externalWorkers2,
8628
+ worker: {
8629
+ ...workerOptions,
8630
+ name: workerOptions.name ?? workerConfig.name,
8631
+ modulesRoot: miniflareModulesRoot,
8632
+ unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
8633
+ serviceBindings: {
8634
+ ...workerOptions.serviceBindings,
8635
+ ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
8636
+ [workerConfig.assets.binding]: ASSET_WORKER_NAME
8637
+ } : {},
8638
+ __VITE_INVOKE_MODULE__: async (request) => {
8639
+ const payload = await request.json();
8640
+ const invokePayloadData = payload.data;
8641
+ assert5(
8642
+ invokePayloadData.name === "fetchModule",
8643
+ `Invalid invoke event: ${invokePayloadData.name}`
8644
+ );
8645
+ const [moduleId] = invokePayloadData.data;
8646
+ if (additionalModuleRE.test(moduleId)) {
8647
+ const result2 = {
8648
+ externalize: moduleId,
8649
+ type: "module"
8650
+ };
8651
+ return MiniflareResponse.json({ result: result2 });
8652
+ }
8653
+ const devEnvironment = viteDevServer.environments[environmentName];
8654
+ const result = await devEnvironment.hot.handleInvoke(payload);
8655
+ return MiniflareResponse.json(result);
8656
+ }
8657
+ }
8658
+ }
8659
+ };
8704
8660
  }
8705
- }
8706
- let resolved;
8707
- for (const url of urls) {
8708
- resolved = _tryModuleResolve(id, url, conditionsSet);
8709
- if (resolved) {
8710
- break;
8711
- }
8712
- for (const prefix of ["", "/index"]) {
8713
- for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
8714
- resolved = _tryModuleResolve(
8715
- joinURL(id, prefix) + extension,
8716
- url,
8717
- conditionsSet
8661
+ ) : [];
8662
+ const userWorkers = workersFromConfig.map((options) => options.worker);
8663
+ const externalWorkers = workersFromConfig.flatMap(
8664
+ (options) => options.externalWorkers
8665
+ );
8666
+ const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
8667
+ const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
8668
+ const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
8669
+ const logger = new ViteMiniflareLogger(resolvedViteConfig);
8670
+ return {
8671
+ log: logger,
8672
+ handleRuntimeStdio(stdout, stderr) {
8673
+ const decoder = new TextDecoder();
8674
+ stdout.forEach((data2) => logger.info(decoder.decode(data2)));
8675
+ stderr.forEach(
8676
+ (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
8677
+ );
8678
+ },
8679
+ ...getPersistence(
8680
+ resolvedViteConfig.root,
8681
+ resolvedPluginConfig.persistState
8682
+ ),
8683
+ workers: [
8684
+ ...assetWorkers,
8685
+ ...externalWorkers,
8686
+ ...userWorkers.map((workerOptions) => {
8687
+ const wrappers = [
8688
+ `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
8689
+ `export default createWorkerEntrypointWrapper('default');`
8690
+ ];
8691
+ const workerEntrypointNames = workerToWorkerEntrypointNamesMap.get(
8692
+ workerOptions.name
8693
+ );
8694
+ assert5(
8695
+ workerEntrypointNames,
8696
+ `WorkerEntrypoint names not found for worker ${workerOptions.name}`
8697
+ );
8698
+ for (const entrypointName of [...workerEntrypointNames].sort()) {
8699
+ wrappers.push(
8700
+ `export const ${entrypointName} = createWorkerEntrypointWrapper('${entrypointName}');`
8701
+ );
8702
+ }
8703
+ const durableObjectClassNames = workerToDurableObjectClassNamesMap.get(
8704
+ workerOptions.name
8705
+ );
8706
+ assert5(
8707
+ durableObjectClassNames,
8708
+ `DurableObject class names not found for worker ${workerOptions.name}`
8709
+ );
8710
+ for (const className of [...durableObjectClassNames].sort()) {
8711
+ wrappers.push(
8712
+ `export const ${className} = createDurableObjectWrapper('${className}');`
8713
+ );
8714
+ }
8715
+ const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
8716
+ assert5(
8717
+ workflowEntrypointClassNames,
8718
+ `WorkflowEntrypoint class names not found for worker: ${workerOptions.name}`
8719
+ );
8720
+ for (const className of [...workflowEntrypointClassNames].sort()) {
8721
+ wrappers.push(
8722
+ `export const ${className} = createWorkflowEntrypointWrapper('${className}');`
8723
+ );
8724
+ }
8725
+ return {
8726
+ ...workerOptions,
8727
+ modules: [
8728
+ {
8729
+ type: "ESModule",
8730
+ path: path4.join(miniflareModulesRoot, WRAPPER_PATH),
8731
+ contents: wrappers.join("\n")
8732
+ },
8733
+ {
8734
+ type: "ESModule",
8735
+ path: path4.join(miniflareModulesRoot, RUNNER_PATH),
8736
+ contents: fs3.readFileSync(
8737
+ fileURLToPath2(new URL(RUNNER_PATH, import.meta.url))
8738
+ )
8739
+ }
8740
+ ],
8741
+ unsafeUseModuleFallbackService: true
8742
+ };
8743
+ })
8744
+ ],
8745
+ async unsafeModuleFallbackService(request) {
8746
+ const url = new URL(request.url);
8747
+ const rawSpecifier = url.searchParams.get("rawSpecifier");
8748
+ assert5(
8749
+ rawSpecifier,
8750
+ `Unexpected error: no specifier in request to module fallback service.`
8751
+ );
8752
+ const match = additionalModuleRE.exec(rawSpecifier);
8753
+ assert5(match, `Unexpected error: no match for module: ${rawSpecifier}.`);
8754
+ const [full, moduleType, modulePath] = match;
8755
+ assert5(
8756
+ moduleType,
8757
+ `Unexpected error: module type not found in reference: ${full}.`
8758
+ );
8759
+ assert5(
8760
+ modulePath,
8761
+ `Unexpected error: module path not found in reference: ${full}.`
8762
+ );
8763
+ let contents;
8764
+ try {
8765
+ contents = await fsp.readFile(modulePath);
8766
+ } catch (error) {
8767
+ throw new Error(
8768
+ `Import "${modulePath}" not found. Does the file exist?`
8718
8769
  );
8719
- if (resolved) {
8720
- break;
8721
- }
8722
8770
  }
8723
- if (resolved) {
8724
- break;
8771
+ switch (moduleType) {
8772
+ case "CompiledWasm": {
8773
+ return MiniflareResponse.json({ wasm: Array.from(contents) });
8774
+ }
8775
+ case "Data": {
8776
+ return MiniflareResponse.json({ data: Array.from(contents) });
8777
+ }
8778
+ case "Text": {
8779
+ return MiniflareResponse.json({ text: contents.toString() });
8780
+ }
8781
+ default: {
8782
+ return MiniflareResponse.error();
8783
+ }
8725
8784
  }
8726
8785
  }
8727
- if (resolved) {
8728
- break;
8729
- }
8730
- }
8731
- if (!resolved) {
8732
- const error = new Error(
8733
- `Cannot find module ${id} imported from ${urls.join(", ")}`
8734
- );
8735
- error.code = "ERR_MODULE_NOT_FOUND";
8736
- throw error;
8737
- }
8738
- return pathToFileURL(resolved);
8739
- }
8740
- function resolveSync(id, options) {
8741
- return _resolve(id, options);
8742
- }
8743
- function resolvePathSync(id, options) {
8744
- return fileURLToPath2(resolveSync(id, options));
8786
+ };
8745
8787
  }
8746
-
8747
- // src/node-js-compat.ts
8748
- import { defineEnv } from "unenv";
8749
- var { env } = defineEnv({
8750
- nodeCompat: true,
8751
- presets: [cloudflare]
8752
- });
8753
- var nodeCompatExternals = new Set(env.external);
8754
- var nodeCompatEntries = getNodeCompatEntries();
8755
- function isNodeCompat(workerConfig) {
8756
- if (workerConfig === void 0) {
8757
- return false;
8758
- }
8759
- const nodeCompatMode = getNodeCompat(
8760
- workerConfig.compatibility_date,
8761
- workerConfig.compatibility_flags ?? []
8762
- ).mode;
8763
- if (nodeCompatMode === "v2") {
8764
- return true;
8765
- }
8766
- if (nodeCompatMode === "legacy") {
8767
- throw new Error(
8768
- "Unsupported Node.js compat mode (legacy). Remove the `node_compat` setting and add the `nodejs_compat` flag instead."
8769
- );
8770
- }
8771
- if (nodeCompatMode === "v1") {
8772
- throw new Error(
8773
- `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`
8774
- );
8775
- }
8776
- return false;
8788
+ function getPreviewModules(main, modulesRules) {
8789
+ assert5(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
8790
+ const rootPath = path4.dirname(main);
8791
+ const entryPath = path4.basename(main);
8792
+ return {
8793
+ rootPath,
8794
+ modules: [
8795
+ {
8796
+ type: "ESModule",
8797
+ path: entryPath
8798
+ },
8799
+ ...modulesRules.flatMap(
8800
+ ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path8) => ({
8801
+ type,
8802
+ path: path8
8803
+ }))
8804
+ )
8805
+ ]
8806
+ };
8777
8807
  }
8778
- function injectGlobalCode(id, code) {
8779
- const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
8780
- if (typeof globalInject === "string") {
8781
- const moduleSpecifier2 = globalInject;
8782
- return `import var_${globalName} from "${moduleSpecifier2}";
8783
- globalThis.${globalName} = var_${globalName};
8784
- `;
8785
- }
8786
- const [moduleSpecifier, exportName] = globalInject;
8787
- assert6(
8788
- moduleSpecifier !== void 0,
8789
- "Expected moduleSpecifier to be defined"
8790
- );
8791
- assert6(exportName !== void 0, "Expected exportName to be defined");
8792
- return `import var_${globalName} from "${moduleSpecifier}";
8793
- globalThis.${globalName} = var_${globalName}.${exportName};
8794
- `;
8795
- }).join("\n");
8796
- const modified = new MagicString(code);
8797
- modified.prepend(injectedCode);
8808
+ function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
8809
+ const resolvedViteConfig = vitePreviewServer.config;
8810
+ const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
8811
+ const workerConfigs = configPaths.map(
8812
+ (configPath) => unstable_readConfig({ config: configPath })
8813
+ );
8814
+ const workers = workerConfigs.flatMap((config) => {
8815
+ const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
8816
+ const { externalWorkers } = miniflareWorkerOptions;
8817
+ const { ratelimits, modulesRules, ...workerOptions } = miniflareWorkerOptions.workerOptions;
8818
+ return [
8819
+ {
8820
+ ...workerOptions,
8821
+ name: workerOptions.name ?? config.name,
8822
+ ...miniflareWorkerOptions.main ? getPreviewModules(miniflareWorkerOptions.main, modulesRules) : { modules: true, script: "" }
8823
+ },
8824
+ ...externalWorkers
8825
+ ];
8826
+ });
8827
+ const logger = new ViteMiniflareLogger(resolvedViteConfig);
8798
8828
  return {
8799
- code: modified.toString(),
8800
- map: modified.generateMap({ hires: "boundary", source: id })
8829
+ log: logger,
8830
+ handleRuntimeStdio(stdout, stderr) {
8831
+ const decoder = new TextDecoder();
8832
+ stdout.forEach((data2) => logger.info(decoder.decode(data2)));
8833
+ stderr.forEach(
8834
+ (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
8835
+ );
8836
+ },
8837
+ ...getPersistence(resolvedViteConfig.root, persistState),
8838
+ workers
8801
8839
  };
8802
8840
  }
8803
- function resolveNodeJSImport(source) {
8804
- const alias = env.alias[source];
8805
- if (alias) {
8806
- return {
8807
- unresolved: alias,
8808
- resolved: resolvePathSync(alias, { url: import.meta.url })
8809
- };
8810
- }
8811
- if (nodeCompatEntries.has(source)) {
8812
- return {
8813
- unresolved: source,
8814
- resolved: resolvePathSync(source, { url: import.meta.url })
8815
- };
8841
+ var ViteMiniflareLogger = class extends Log {
8842
+ logger;
8843
+ constructor(config) {
8844
+ super(miniflareLogLevelFromViteLogLevel(config.logLevel));
8845
+ this.logger = config.logger;
8816
8846
  }
8817
- }
8818
- function getNodeCompatEntries() {
8819
- const entries = new Set(Object.values(env.alias));
8820
- for (const globalInject of Object.values(env.inject)) {
8821
- if (typeof globalInject === "string") {
8822
- entries.add(globalInject);
8823
- } else {
8824
- assert6(
8825
- globalInject[0] !== void 0,
8826
- "Expected first element of globalInject to be defined"
8827
- );
8828
- entries.add(globalInject[0]);
8847
+ logWithLevel(level, message) {
8848
+ if (/^Ready on http/.test(message)) {
8849
+ level = LogLevel.DEBUG;
8850
+ }
8851
+ switch (level) {
8852
+ case LogLevel.ERROR:
8853
+ return this.logger.error(message);
8854
+ case LogLevel.WARN:
8855
+ return this.logger.warn(message);
8856
+ case LogLevel.INFO:
8857
+ return this.logger.info(message);
8829
8858
  }
8830
8859
  }
8831
- nodeCompatExternals.forEach((external) => entries.delete(external));
8832
- return entries;
8860
+ };
8861
+ function miniflareLogLevelFromViteLogLevel(level = "info") {
8862
+ switch (level) {
8863
+ case "error":
8864
+ return LogLevel.ERROR;
8865
+ case "warn":
8866
+ return LogLevel.WARN;
8867
+ case "info":
8868
+ return LogLevel.INFO;
8869
+ case "silent":
8870
+ return LogLevel.NONE;
8871
+ }
8833
8872
  }
8834
8873
 
8835
8874
  // src/plugin-config.ts
8836
- import assert8 from "node:assert";
8875
+ import assert6 from "node:assert";
8837
8876
  import * as path6 from "node:path";
8838
8877
  import * as vite5 from "vite";
8839
8878
 
8840
8879
  // src/workers-configs.ts
8841
- import assert7 from "node:assert";
8842
8880
  import * as fs4 from "node:fs";
8843
8881
  import * as path5 from "node:path";
8844
8882
  import { unstable_readConfig as unstable_readConfig2 } from "wrangler";
8845
-
8846
- // package.json
8847
- var name = "@cloudflare/vite-plugin";
8848
-
8849
- // src/workers-configs.ts
8850
8883
  var nonApplicableWorkerConfigs = {
8851
8884
  /**
8852
8885
  * Object containing configs that have a vite replacement, the object's field contain details about the config's replacement
@@ -8874,16 +8907,12 @@ var nonApplicableWorkerConfigs = {
8874
8907
  "build",
8875
8908
  "find_additional_modules",
8876
8909
  "no_bundle",
8877
- "node_compat",
8878
8910
  "preserve_file_names",
8911
+ "rules",
8879
8912
  "site",
8880
8913
  "tsconfig",
8881
8914
  "upload_source_maps"
8882
- ],
8883
- /**
8884
- * All the configs that get overridden by our plugin
8885
- */
8886
- overridden: ["rules"]
8915
+ ]
8887
8916
  };
8888
8917
  var nullableNonApplicable = [
8889
8918
  "alias",
@@ -8891,7 +8920,6 @@ var nullableNonApplicable = [
8891
8920
  "find_additional_modules",
8892
8921
  "minify",
8893
8922
  "no_bundle",
8894
- "node_compat",
8895
8923
  "preserve_file_names",
8896
8924
  "site",
8897
8925
  "tsconfig",
@@ -8900,8 +8928,7 @@ var nullableNonApplicable = [
8900
8928
  function readWorkerConfig(configPath, env2) {
8901
8929
  const nonApplicable = {
8902
8930
  replacedByVite: /* @__PURE__ */ new Set(),
8903
- notRelevant: /* @__PURE__ */ new Set(),
8904
- overridden: /* @__PURE__ */ new Set()
8931
+ notRelevant: /* @__PURE__ */ new Set()
8905
8932
  };
8906
8933
  const config = unstable_readConfig2({ config: configPath, env: env2 }, {});
8907
8934
  const raw = structuredClone(config);
@@ -8913,9 +8940,6 @@ function readWorkerConfig(configPath, env2) {
8913
8940
  if (isNotRelevant(prop)) {
8914
8941
  nonApplicable.notRelevant.add(prop);
8915
8942
  }
8916
- if (isOverridden(prop)) {
8917
- nonApplicable.overridden.add(prop);
8918
- }
8919
8943
  }
8920
8944
  delete config[prop];
8921
8945
  });
@@ -8928,7 +8952,7 @@ function readWorkerConfig(configPath, env2) {
8928
8952
  }
8929
8953
  delete config["define"];
8930
8954
  if (config.rules.length > 0) {
8931
- nonApplicable.overridden.add("rules");
8955
+ nonApplicable.notRelevant.add("rules");
8932
8956
  }
8933
8957
  return {
8934
8958
  raw,
@@ -8980,7 +9004,7 @@ function getWarningForWorkersConfigs(configs) {
8980
9004
  }
8981
9005
  function getWorkerNonApplicableWarnLines(workerConfig, linePrefix) {
8982
9006
  const lines = [];
8983
- const { replacedByVite, notRelevant, overridden } = workerConfig.nonApplicable;
9007
+ const { replacedByVite, notRelevant } = workerConfig.nonApplicable;
8984
9008
  for (const config of replacedByVite) {
8985
9009
  lines.push(
8986
9010
  `${linePrefix}\`${config}\` which is replaced by Vite's \`${nonApplicableWorkerConfigs.replacedByVite[config].viteReplacement}\` (docs: ${nonApplicableWorkerConfigs.replacedByVite[config].viteDocs})`
@@ -8990,10 +9014,6 @@ function getWorkerNonApplicableWarnLines(workerConfig, linePrefix) {
8990
9014
  lines.push(
8991
9015
  `${linePrefix}${[...notRelevant].map((config) => `\`${config}\``).join(", ")} which ${notRelevant.size > 1 ? "are" : "is"} not relevant in the context of a Vite project`
8992
9016
  );
8993
- if (overridden.size > 0)
8994
- lines.push(
8995
- `${linePrefix}${[...overridden].map((config) => `\`${config}\``).join(", ")} which ${overridden.size > 1 ? "are" : "is"} overridden by \`${name}\``
8996
- );
8997
9017
  return lines;
8998
9018
  }
8999
9019
  function isReplacedByVite(configName) {
@@ -9002,9 +9022,6 @@ function isReplacedByVite(configName) {
9002
9022
  function isNotRelevant(configName) {
9003
9023
  return nonApplicableWorkerConfigs.notRelevant.includes(configName);
9004
9024
  }
9005
- function isOverridden(configName) {
9006
- return nonApplicableWorkerConfigs.overridden.includes(configName);
9007
- }
9008
9025
  function missingFieldErrorMessage(field, configPath, env2) {
9009
9026
  return `No ${field} field provided in '${configPath}'${env2 ? ` for '${env2}' environment` : ""}`;
9010
9027
  }
@@ -9014,42 +9031,55 @@ function getWorkerConfig(configPath, env2, opts) {
9014
9031
  }
9015
9032
  const { raw, config, nonApplicable } = readWorkerConfig(configPath, env2);
9016
9033
  opts?.visitedConfigPaths?.add(configPath);
9017
- assert7(
9018
- config.topLevelName,
9019
- missingFieldErrorMessage(`top-level 'name'`, configPath, env2)
9020
- );
9021
- assert7(config.name, missingFieldErrorMessage(`'name'`, configPath, env2));
9022
- assert7(
9023
- config.compatibility_date,
9024
- missingFieldErrorMessage(`'compatibility_date'`, configPath, env2)
9025
- );
9026
- if (opts?.isEntryWorker && !config.main) {
9027
- assert7(
9028
- config.assets,
9029
- missingFieldErrorMessage(`'main' or 'assets'`, configPath, env2)
9034
+ if (!config.name) {
9035
+ throw new Error(missingFieldErrorMessage(`'name'`, configPath, env2));
9036
+ }
9037
+ if (!config.topLevelName) {
9038
+ throw new Error(
9039
+ missingFieldErrorMessage(`top-level 'name'`, configPath, env2)
9040
+ );
9041
+ }
9042
+ if (!config.compatibility_date) {
9043
+ throw new Error(
9044
+ missingFieldErrorMessage(`'compatibility_date`, configPath, env2)
9030
9045
  );
9046
+ }
9047
+ const requiredFields = {
9048
+ topLevelName: config.topLevelName,
9049
+ name: config.name,
9050
+ compatibility_date: config.compatibility_date
9051
+ };
9052
+ if (opts?.isEntryWorker && !config.main) {
9031
9053
  return {
9032
9054
  type: "assets-only",
9033
9055
  raw,
9034
9056
  config: {
9035
9057
  ...config,
9036
- topLevelName: config.topLevelName,
9037
- name: config.name,
9038
- compatibility_date: config.compatibility_date,
9039
- assets: config.assets
9058
+ ...requiredFields
9040
9059
  },
9041
9060
  nonApplicable
9042
9061
  };
9043
9062
  }
9044
- assert7(config.main, missingFieldErrorMessage(`'main'`, configPath, env2));
9063
+ if (!config.main) {
9064
+ throw new Error(missingFieldErrorMessage(`'main'`, configPath, env2));
9065
+ }
9066
+ const mainStat = fs4.statSync(config.main, { throwIfNoEntry: false });
9067
+ if (!mainStat) {
9068
+ throw new Error(
9069
+ `The provided Wrangler config main field (${config.main}) doesn't point to an existing file`
9070
+ );
9071
+ }
9072
+ if (mainStat.isDirectory()) {
9073
+ throw new Error(
9074
+ `The provided Wrangler config main field (${config.main}) points to a directory, it needs to point to a file instead`
9075
+ );
9076
+ }
9045
9077
  return {
9046
9078
  type: "worker",
9047
9079
  raw,
9048
9080
  config: {
9049
9081
  ...config,
9050
- topLevelName: config.topLevelName,
9051
- name: config.name,
9052
- compatibility_date: config.compatibility_date,
9082
+ ...requiredFields,
9053
9083
  main: config.main
9054
9084
  },
9055
9085
  nonApplicable
@@ -9079,10 +9109,11 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9079
9109
  ""
9080
9110
  );
9081
9111
  const configPath = pluginConfig.configPath ? path6.resolve(root, pluginConfig.configPath) : findWranglerConfig(root);
9082
- assert8(
9083
- configPath,
9084
- `Config not found. Have you created a wrangler.json(c) or wrangler.toml file?`
9085
- );
9112
+ if (!configPath) {
9113
+ throw new Error(
9114
+ `Config not found. Have you created a wrangler.json(c) or wrangler.toml file?`
9115
+ );
9116
+ }
9086
9117
  const entryWorkerResolvedConfig = getWorkerConfig(configPath, cloudflareEnv, {
9087
9118
  visitedConfigPaths: configPaths,
9088
9119
  isEntryWorker: true
@@ -9114,7 +9145,7 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9114
9145
  }
9115
9146
  );
9116
9147
  auxiliaryWorkersResolvedConfigs.push(workerResolvedConfig);
9117
- assert8(
9148
+ assert6(
9118
9149
  workerResolvedConfig.type === "worker",
9119
9150
  "Unexpected error: received AssetsOnlyResult with auxiliary workers."
9120
9151
  );
@@ -9142,8 +9173,9 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9142
9173
  }
9143
9174
 
9144
9175
  // src/websockets.ts
9176
+ import { coupleWebSocket } from "miniflare";
9145
9177
  import { WebSocketServer } from "ws";
9146
- function handleWebSocket(httpServer, fetcher, logger) {
9178
+ function handleWebSocket(httpServer, fetcher) {
9147
9179
  const nodeWebSocket = new WebSocketServer({ noServer: true });
9148
9180
  httpServer.on(
9149
9181
  "upgrade",
@@ -9167,34 +9199,7 @@ function handleWebSocket(httpServer, fetcher, logger) {
9167
9199
  socket,
9168
9200
  head,
9169
9201
  async (clientWebSocket) => {
9170
- workerWebSocket.accept();
9171
- workerWebSocket.addEventListener("message", (event) => {
9172
- clientWebSocket.send(event.data);
9173
- });
9174
- workerWebSocket.addEventListener("error", (event) => {
9175
- logger.error(
9176
- `WebSocket error:
9177
- ${event.error?.stack || event.error?.message}`,
9178
- { error: event.error }
9179
- );
9180
- });
9181
- workerWebSocket.addEventListener("close", () => {
9182
- clientWebSocket.close();
9183
- });
9184
- clientWebSocket.on("message", (data2, isBinary) => {
9185
- workerWebSocket.send(
9186
- isBinary ? Array.isArray(data2) ? Buffer.concat(data2) : data2 : data2.toString()
9187
- );
9188
- });
9189
- clientWebSocket.on("error", (error) => {
9190
- logger.error(`WebSocket error:
9191
- ${error.stack || error.message}`, {
9192
- error
9193
- });
9194
- });
9195
- clientWebSocket.on("close", () => {
9196
- workerWebSocket.close();
9197
- });
9202
+ coupleWebSocket(clientWebSocket, workerWebSocket);
9198
9203
  nodeWebSocket.emit("connection", clientWebSocket, request);
9199
9204
  }
9200
9205
  );
@@ -9203,14 +9208,18 @@ ${error.stack || error.message}`, {
9203
9208
  }
9204
9209
 
9205
9210
  // src/index.ts
9211
+ var workersConfigsWarningShown = false;
9206
9212
  function cloudflare2(pluginConfig = {}) {
9207
9213
  let resolvedPluginConfig;
9208
9214
  let resolvedViteConfig;
9209
9215
  let miniflare;
9210
- let workersConfigsWarningShown = false;
9216
+ const additionalModulePaths = /* @__PURE__ */ new Set();
9217
+ let hasClientBuild = false;
9211
9218
  return [
9212
9219
  {
9213
9220
  name: "vite-plugin-cloudflare",
9221
+ // This only applies to this plugin so is safe to use while other plugins migrate to the Environment API
9222
+ sharedDuringBuild: true,
9214
9223
  config(userConfig, env2) {
9215
9224
  if (env2.isPreview) {
9216
9225
  return { appType: "custom" };
@@ -9267,7 +9276,7 @@ function cloudflare2(pluginConfig = {}) {
9267
9276
  resolvedPluginConfig.workers
9268
9277
  ).map((environmentName) => {
9269
9278
  const environment = builder.environments[environmentName];
9270
- assert9(
9279
+ assert7(
9271
9280
  environment,
9272
9281
  `${environmentName} environment not found`
9273
9282
  );
@@ -9283,6 +9292,9 @@ function cloudflare2(pluginConfig = {}) {
9283
9292
  }
9284
9293
  };
9285
9294
  },
9295
+ buildStart() {
9296
+ workersConfigsWarningShown = false;
9297
+ },
9286
9298
  configResolved(config) {
9287
9299
  resolvedViteConfig = config;
9288
9300
  },
@@ -9297,18 +9309,27 @@ function cloudflare2(pluginConfig = {}) {
9297
9309
  return;
9298
9310
  }
9299
9311
  workerConfig.main = entryChunk[0];
9312
+ workerConfig.no_bundle = true;
9313
+ workerConfig.rules = [
9314
+ { type: "ESModule", globs: ["**/*.js", "**/*.mjs"] }
9315
+ ];
9300
9316
  const isEntryWorker = this.environment.name === resolvedPluginConfig.entryWorkerEnvironmentName;
9301
- if (isEntryWorker && workerConfig.assets) {
9317
+ if (isEntryWorker && hasClientBuild) {
9302
9318
  const workerOutputDirectory = this.environment.config.build.outDir;
9303
9319
  const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
9304
- assert9(
9320
+ assert7(
9305
9321
  clientOutputDirectory,
9306
9322
  "Unexpected error: client output directory is undefined"
9307
9323
  );
9308
- workerConfig.assets.directory = path7.relative(
9309
- path7.resolve(resolvedViteConfig.root, workerOutputDirectory),
9310
- path7.resolve(resolvedViteConfig.root, clientOutputDirectory)
9311
- );
9324
+ workerConfig.assets = {
9325
+ ...workerConfig.assets,
9326
+ directory: path7.relative(
9327
+ path7.resolve(resolvedViteConfig.root, workerOutputDirectory),
9328
+ path7.resolve(resolvedViteConfig.root, clientOutputDirectory)
9329
+ )
9330
+ };
9331
+ } else {
9332
+ workerConfig.assets = void 0;
9312
9333
  }
9313
9334
  config = workerConfig;
9314
9335
  if (workerConfig.configPath) {
@@ -9326,7 +9347,10 @@ function cloudflare2(pluginConfig = {}) {
9326
9347
  }
9327
9348
  } else if (this.environment.name === "client") {
9328
9349
  const assetsOnlyConfig = resolvedPluginConfig.config;
9329
- assetsOnlyConfig.assets.directory = ".";
9350
+ assetsOnlyConfig.assets = {
9351
+ ...assetsOnlyConfig.assets,
9352
+ directory: "."
9353
+ };
9330
9354
  const filesToAssetsIgnore = ["wrangler.json", ".dev.vars"];
9331
9355
  this.emitFile({
9332
9356
  type: "asset",
@@ -9339,8 +9363,6 @@ function cloudflare2(pluginConfig = {}) {
9339
9363
  if (!config) {
9340
9364
  return;
9341
9365
  }
9342
- config.no_bundle = true;
9343
- config.rules = [{ type: "ESModule", globs: ["**/*.js", "**/*.mjs"] }];
9344
9366
  if (config.unsafe && Object.keys(config.unsafe).length === 0) {
9345
9367
  config.unsafe = void 0;
9346
9368
  }
@@ -9351,6 +9373,9 @@ function cloudflare2(pluginConfig = {}) {
9351
9373
  });
9352
9374
  },
9353
9375
  writeBundle() {
9376
+ if (this.environment.name === "client") {
9377
+ hasClientBuild = true;
9378
+ }
9354
9379
  if (this.environment.name === (resolvedPluginConfig.type === "assets-only" ? "client" : resolvedPluginConfig.entryWorkerEnvironmentName)) {
9355
9380
  writeDeployConfig(resolvedPluginConfig, resolvedViteConfig);
9356
9381
  }
@@ -9367,7 +9392,7 @@ function cloudflare2(pluginConfig = {}) {
9367
9392
  }
9368
9393
  },
9369
9394
  async configureServer(viteDevServer) {
9370
- assert9(
9395
+ assert7(
9371
9396
  viteDevServer.httpServer,
9372
9397
  "Unexpected error: No Vite HTTP server"
9373
9398
  );
@@ -9375,23 +9400,16 @@ function cloudflare2(pluginConfig = {}) {
9375
9400
  getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
9376
9401
  );
9377
9402
  await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
9378
- const entryWorker = await getDevEntryWorker(
9379
- resolvedPluginConfig,
9380
- miniflare
9381
- );
9403
+ const routerWorker = await getRouterWorker(miniflare);
9382
9404
  const middleware = createMiddleware(
9383
9405
  ({ request }) => {
9384
- return entryWorker.fetch(toMiniflareRequest(request), {
9406
+ return routerWorker.fetch(toMiniflareRequest(request), {
9385
9407
  redirect: "manual"
9386
9408
  });
9387
9409
  },
9388
9410
  { alwaysCallNext: false }
9389
9411
  );
9390
- handleWebSocket(
9391
- viteDevServer.httpServer,
9392
- entryWorker.fetch,
9393
- viteDevServer.config.logger
9394
- );
9412
+ handleWebSocket(viteDevServer.httpServer, routerWorker.fetch);
9395
9413
  return () => {
9396
9414
  viteDevServer.middlewares.use((req, res, next) => {
9397
9415
  middleware(req, res, next);
@@ -9413,58 +9431,61 @@ function cloudflare2(pluginConfig = {}) {
9413
9431
  },
9414
9432
  { alwaysCallNext: false }
9415
9433
  );
9416
- handleWebSocket(
9417
- vitePreviewServer.httpServer,
9418
- miniflare2.dispatchFetch,
9419
- vitePreviewServer.config.logger
9420
- );
9421
- return () => {
9422
- vitePreviewServer.middlewares.use((req, res, next) => {
9423
- middleware(req, res, next);
9424
- });
9425
- };
9434
+ handleWebSocket(vitePreviewServer.httpServer, miniflare2.dispatchFetch);
9435
+ vitePreviewServer.middlewares.use((req, res, next) => {
9436
+ middleware(req, res, next);
9437
+ });
9426
9438
  }
9427
9439
  },
9428
- // Plugin to support `CompiledWasm` modules
9440
+ // Plugin to support additional modules
9429
9441
  {
9430
- name: "vite-plugin-cloudflare:modules",
9442
+ name: "vite-plugin-cloudflare:additional-modules",
9431
9443
  // We set `enforce: "pre"` so that this plugin runs before the Vite core plugins.
9432
9444
  // Otherwise the `vite:wasm-fallback` plugin prevents the `.wasm` extension being used for module imports.
9433
9445
  enforce: "pre",
9434
9446
  applyToEnvironment(environment) {
9435
9447
  return getWorkerConfig2(environment.name) !== void 0;
9436
9448
  },
9437
- async resolveId(source, importer) {
9438
- if (!source.endsWith(".wasm")) {
9449
+ async resolveId(source, importer, options) {
9450
+ const additionalModuleType = matchAdditionalModule(source);
9451
+ if (!additionalModuleType) {
9439
9452
  return;
9440
9453
  }
9441
- const resolved = await this.resolve(source, importer);
9442
- assert9(
9443
- resolved,
9444
- `Unexpected error: could not resolve Wasm module ${source}`
9454
+ const resolved = await this.resolve(
9455
+ cleanUrl(source),
9456
+ importer,
9457
+ options
9445
9458
  );
9459
+ if (!resolved) {
9460
+ throw new Error(`Import "${source}" not found. Does the file exist?`);
9461
+ }
9462
+ additionalModulePaths.add(resolved.id);
9446
9463
  return {
9447
9464
  external: true,
9448
- id: createModuleReference("CompiledWasm", resolved.id)
9465
+ id: createModuleReference(additionalModuleType, resolved.id)
9449
9466
  };
9450
9467
  },
9451
- renderChunk(code, chunk) {
9452
- const moduleRE = new RegExp(MODULE_PATTERN, "g");
9453
- let match;
9468
+ hotUpdate(options) {
9469
+ if (additionalModulePaths.has(options.file)) {
9470
+ options.server.restart();
9471
+ }
9472
+ },
9473
+ async renderChunk(code, chunk) {
9474
+ const matches = code.matchAll(additionalModuleGlobalRE);
9454
9475
  let magicString;
9455
- while (match = moduleRE.exec(code)) {
9476
+ for (const match of matches) {
9456
9477
  magicString ??= new MagicString(code);
9457
- const [full, moduleType, modulePath] = match;
9458
- assert9(
9478
+ const [full, _, modulePath] = match;
9479
+ assert7(
9459
9480
  modulePath,
9460
9481
  `Unexpected error: module path not found in reference ${full}.`
9461
9482
  );
9462
9483
  let source;
9463
9484
  try {
9464
- source = fs5.readFileSync(modulePath);
9485
+ source = await fsp2.readFile(modulePath);
9465
9486
  } catch (error) {
9466
9487
  throw new Error(
9467
- `Import ${modulePath} not found. Does the file exist?`
9488
+ `Import "${modulePath}" not found. Does the file exist?`
9468
9489
  );
9469
9490
  }
9470
9491
  const referenceId = this.emitFile({
@@ -9498,8 +9519,8 @@ function cloudflare2(pluginConfig = {}) {
9498
9519
  apply(_config, env2) {
9499
9520
  return !env2.isPreview;
9500
9521
  },
9501
- configEnvironment(name2) {
9502
- if (isNodeCompat(getWorkerConfig2(name2))) {
9522
+ configEnvironment(name) {
9523
+ if (isNodeCompat(getWorkerConfig2(name))) {
9503
9524
  return {
9504
9525
  resolve: {
9505
9526
  builtins: [...nodeCompatExternals]
@@ -9538,7 +9559,7 @@ function cloudflare2(pluginConfig = {}) {
9538
9559
  return this.resolve(source, importer, options);
9539
9560
  }
9540
9561
  if (this.environment.mode === "dev") {
9541
- assert9(
9562
+ assert7(
9542
9563
  this.environment.depsOptimizer,
9543
9564
  "depsOptimizer is required in dev mode"
9544
9565
  );
@@ -9552,7 +9573,7 @@ function cloudflare2(pluginConfig = {}) {
9552
9573
  },
9553
9574
  async transform(code, id) {
9554
9575
  const workerConfig = getWorkerConfig2(this.environment.name);
9555
- assert9(workerConfig, "Expected a worker config");
9576
+ assert7(workerConfig, "Expected a worker config");
9556
9577
  const resolvedId = await this.resolve(workerConfig.main);
9557
9578
  if (id === resolvedId?.id) {
9558
9579
  return injectGlobalCode(id, code);
@@ -9561,7 +9582,7 @@ function cloudflare2(pluginConfig = {}) {
9561
9582
  }
9562
9583
  ];
9563
9584
  function getWorkerConfig2(environmentName) {
9564
- assert9(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
9585
+ assert7(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
9565
9586
  return resolvedPluginConfig.type !== "assets-only" ? resolvedPluginConfig.workers[environmentName] : void 0;
9566
9587
  }
9567
9588
  }
@@ -9576,9 +9597,6 @@ function getDotDevDotVarsContent(configPath, cloudflareEnv) {
9576
9597
  }
9577
9598
  return null;
9578
9599
  }
9579
- function createModuleReference(type, id) {
9580
- return `__CLOUDFLARE_MODULE__${type}__${id}__`;
9581
- }
9582
9600
  export {
9583
9601
  cloudflare2 as cloudflare
9584
9602
  };