@vite-hub/rate-limit 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +68 -0
- package/dist/cloudflare-BYZQ2tim.js +42 -0
- package/dist/drivers/cloudflare.d.ts +19 -0
- package/dist/drivers/cloudflare.js +2 -0
- package/dist/drivers/memory.d.ts +14 -0
- package/dist/drivers/memory.js +54 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +76 -0
- package/dist/limiter-CHaHluMr.js +118 -0
- package/dist/runtime.d.ts +7 -0
- package/dist/runtime.js +2 -0
- package/dist/state-DB4uJN5P.js +15 -0
- package/dist/types-BX4hSfYX.d.ts +97 -0
- package/dist/vite.d.ts +14 -0
- package/dist/vite.js +3954 -0
- package/package.json +65 -0
package/dist/vite.js
ADDED
|
@@ -0,0 +1,3954 @@
|
|
|
1
|
+
import { i as rateLimitPolicyKeys, n as declaredRateLimitPolicy, r as normalizeRateLimitPolicy, t as createRateLimiter } from "./limiter-CHaHluMr.js";
|
|
2
|
+
import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "./cloudflare-BYZQ2tim.js";
|
|
3
|
+
import { memoryRateLimitDriver } from "./drivers/memory.js";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import { cp, mkdir, readFile, readdir, rm, rmdir, stat, writeFile } from "node:fs/promises";
|
|
6
|
+
import { basename, dirname, relative, resolve } from "node:path";
|
|
7
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { isDeepStrictEqual } from "node:util";
|
|
10
|
+
import { Visitor, normalizePath, parseSync } from "vite";
|
|
11
|
+
//#region \0rolldown/runtime.js
|
|
12
|
+
var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
|
|
13
|
+
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
14
|
+
const VITEHUB_MODES = {
|
|
15
|
+
e2e: "e2e",
|
|
16
|
+
blob: "blob",
|
|
17
|
+
chat: "chat",
|
|
18
|
+
db: "db",
|
|
19
|
+
env: "env",
|
|
20
|
+
kv: "kv",
|
|
21
|
+
queue: "queue",
|
|
22
|
+
schedule: "schedule",
|
|
23
|
+
sandbox: "sandbox",
|
|
24
|
+
workspace: "workspace",
|
|
25
|
+
workflow: "workflow"
|
|
26
|
+
};
|
|
27
|
+
function isViteCli(argv) {
|
|
28
|
+
return argv.some((arg) => /(?:^|[/\\])vite(?:\.[cm]?js)?$/.test(arg) || arg === "vite");
|
|
29
|
+
}
|
|
30
|
+
function getViteCliMode(argv = process.argv) {
|
|
31
|
+
if (!isViteCli(argv)) return;
|
|
32
|
+
const modes = new Set(Object.values(VITEHUB_MODES));
|
|
33
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
34
|
+
const arg = argv[index];
|
|
35
|
+
const mode = arg === "--mode" || arg === "-m" ? argv[index + 1] : arg.startsWith("--mode=") ? arg.slice(7) : void 0;
|
|
36
|
+
if (mode && modes.has(mode)) return mode;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function getViteMode(env = process.env) {
|
|
40
|
+
return env["VITEHUB_VITE_MODE"] ?? getViteCliMode();
|
|
41
|
+
}
|
|
42
|
+
//#endregion
|
|
43
|
+
//#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
|
|
44
|
+
const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
|
|
45
|
+
function normalizeWindowsPath(input = "") {
|
|
46
|
+
if (!input) return input;
|
|
47
|
+
return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
|
|
48
|
+
}
|
|
49
|
+
const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
|
|
50
|
+
const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
|
|
51
|
+
const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
|
|
52
|
+
function cwd() {
|
|
53
|
+
if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
|
|
54
|
+
return "/";
|
|
55
|
+
}
|
|
56
|
+
const resolve$1 = function(...arguments_) {
|
|
57
|
+
arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
|
|
58
|
+
let resolvedPath = "";
|
|
59
|
+
let resolvedAbsolute = false;
|
|
60
|
+
for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
|
|
61
|
+
const path = index >= 0 ? arguments_[index] : cwd();
|
|
62
|
+
if (!path || path.length === 0) continue;
|
|
63
|
+
resolvedPath = `${path}/${resolvedPath}`;
|
|
64
|
+
resolvedAbsolute = isAbsolute(path);
|
|
65
|
+
}
|
|
66
|
+
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
|
|
67
|
+
if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
|
|
68
|
+
return resolvedPath.length > 0 ? resolvedPath : ".";
|
|
69
|
+
};
|
|
70
|
+
function normalizeString(path, allowAboveRoot) {
|
|
71
|
+
let res = "";
|
|
72
|
+
let lastSegmentLength = 0;
|
|
73
|
+
let lastSlash = -1;
|
|
74
|
+
let dots = 0;
|
|
75
|
+
let char = null;
|
|
76
|
+
for (let index = 0; index <= path.length; ++index) {
|
|
77
|
+
if (index < path.length) char = path[index];
|
|
78
|
+
else if (char === "/") break;
|
|
79
|
+
else char = "/";
|
|
80
|
+
if (char === "/") {
|
|
81
|
+
if (lastSlash === index - 1 || dots === 1);
|
|
82
|
+
else if (dots === 2) {
|
|
83
|
+
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
|
|
84
|
+
if (res.length > 2) {
|
|
85
|
+
const lastSlashIndex = res.lastIndexOf("/");
|
|
86
|
+
if (lastSlashIndex === -1) {
|
|
87
|
+
res = "";
|
|
88
|
+
lastSegmentLength = 0;
|
|
89
|
+
} else {
|
|
90
|
+
res = res.slice(0, lastSlashIndex);
|
|
91
|
+
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
|
|
92
|
+
}
|
|
93
|
+
lastSlash = index;
|
|
94
|
+
dots = 0;
|
|
95
|
+
continue;
|
|
96
|
+
} else if (res.length > 0) {
|
|
97
|
+
res = "";
|
|
98
|
+
lastSegmentLength = 0;
|
|
99
|
+
lastSlash = index;
|
|
100
|
+
dots = 0;
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (allowAboveRoot) {
|
|
105
|
+
res += res.length > 0 ? "/.." : "..";
|
|
106
|
+
lastSegmentLength = 2;
|
|
107
|
+
}
|
|
108
|
+
} else {
|
|
109
|
+
if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
|
|
110
|
+
else res = path.slice(lastSlash + 1, index);
|
|
111
|
+
lastSegmentLength = index - lastSlash - 1;
|
|
112
|
+
}
|
|
113
|
+
lastSlash = index;
|
|
114
|
+
dots = 0;
|
|
115
|
+
} else if (char === "." && dots !== -1) ++dots;
|
|
116
|
+
else dots = -1;
|
|
117
|
+
}
|
|
118
|
+
return res;
|
|
119
|
+
}
|
|
120
|
+
const isAbsolute = function(p) {
|
|
121
|
+
return _IS_ABSOLUTE_RE.test(p);
|
|
122
|
+
};
|
|
123
|
+
const relative$1 = function(from, to) {
|
|
124
|
+
const _from = resolve$1(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
|
|
125
|
+
const _to = resolve$1(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
|
|
126
|
+
if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
|
|
127
|
+
const _fromCopy = [..._from];
|
|
128
|
+
for (const segment of _fromCopy) {
|
|
129
|
+
if (_to[0] !== segment) break;
|
|
130
|
+
_from.shift();
|
|
131
|
+
_to.shift();
|
|
132
|
+
}
|
|
133
|
+
return [..._from.map(() => ".."), ..._to].join("/");
|
|
134
|
+
};
|
|
135
|
+
const dirname$1 = function(p) {
|
|
136
|
+
const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
|
|
137
|
+
if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
|
|
138
|
+
return segments.join("/") || (isAbsolute(p) ? "/" : ".");
|
|
139
|
+
};
|
|
140
|
+
//#endregion
|
|
141
|
+
//#region ../internal/src/build/client-output.ts
|
|
142
|
+
function hasStaticIndex(clientDir) {
|
|
143
|
+
return existsSync(resolve$1(clientDir, "index.html"));
|
|
144
|
+
}
|
|
145
|
+
async function copyClientOutput(clientDir, targetDir) {
|
|
146
|
+
const resolvedClientDir = resolve$1(clientDir);
|
|
147
|
+
const resolvedTargetDir = resolve$1(targetDir);
|
|
148
|
+
if (resolvedClientDir === resolvedTargetDir) return;
|
|
149
|
+
await rm(resolvedTargetDir, {
|
|
150
|
+
force: true,
|
|
151
|
+
recursive: true
|
|
152
|
+
});
|
|
153
|
+
await mkdir(dirname$1(resolvedTargetDir), { recursive: true });
|
|
154
|
+
const targetRelativePath = relative$1(resolvedClientDir, resolvedTargetDir);
|
|
155
|
+
if (targetRelativePath && !targetRelativePath.startsWith("../")) {
|
|
156
|
+
const [targetRootEntry] = targetRelativePath.split("/", 1);
|
|
157
|
+
await mkdir(resolvedTargetDir, { recursive: true });
|
|
158
|
+
await Promise.all((await readdir(resolvedClientDir)).filter((entry) => entry !== targetRootEntry).map((entry) => cp(resolve$1(resolvedClientDir, entry), resolve$1(resolvedTargetDir, entry), { recursive: true })));
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
await cp(resolvedClientDir, resolvedTargetDir, { recursive: true });
|
|
162
|
+
}
|
|
163
|
+
//#endregion
|
|
164
|
+
//#region ../internal/src/build/provider-output-config.ts
|
|
165
|
+
function isProviderJsonArray(value, ancestors) {
|
|
166
|
+
if (Object.getPrototypeOf(value) !== Array.prototype || ancestors.has(value)) return false;
|
|
167
|
+
if (Reflect.ownKeys(value).length !== value.length + 1) return false;
|
|
168
|
+
ancestors.add(value);
|
|
169
|
+
try {
|
|
170
|
+
for (let index = 0; index < value.length; index++) {
|
|
171
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
|
|
172
|
+
if (!descriptor?.enumerable || !("value" in descriptor) || !isProviderJsonValue(descriptor.value, ancestors)) return false;
|
|
173
|
+
}
|
|
174
|
+
return true;
|
|
175
|
+
} finally {
|
|
176
|
+
ancestors.delete(value);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
function isProviderJsonRecordValue(value, ancestors) {
|
|
180
|
+
const prototype = Object.getPrototypeOf(value);
|
|
181
|
+
if (prototype !== Object.prototype && prototype !== null || ancestors.has(value)) return false;
|
|
182
|
+
ancestors.add(value);
|
|
183
|
+
try {
|
|
184
|
+
return Reflect.ownKeys(value).every((key) => {
|
|
185
|
+
if (typeof key !== "string") return false;
|
|
186
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
187
|
+
return descriptor?.enumerable === true && "value" in descriptor && isProviderJsonValue(descriptor.value, ancestors);
|
|
188
|
+
});
|
|
189
|
+
} finally {
|
|
190
|
+
ancestors.delete(value);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
function isProviderJsonValue(value, ancestors) {
|
|
194
|
+
if (value === null || typeof value === "boolean" || typeof value === "string") return true;
|
|
195
|
+
if (typeof value === "number") return Number.isFinite(value);
|
|
196
|
+
if (Array.isArray(value)) return isProviderJsonArray(value, ancestors);
|
|
197
|
+
return typeof value === "object" && isProviderJsonRecordValue(value, ancestors);
|
|
198
|
+
}
|
|
199
|
+
function isProviderJsonRecord(value) {
|
|
200
|
+
try {
|
|
201
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && isProviderJsonRecordValue(value, /* @__PURE__ */ new Set());
|
|
202
|
+
} catch {
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
function assertProviderJsonRecord(value) {
|
|
207
|
+
if (!isProviderJsonRecord(value)) throw new TypeError("[vitehub] Provider output config must be a JSON object.");
|
|
208
|
+
}
|
|
209
|
+
function isFileNotFoundError(error) {
|
|
210
|
+
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
211
|
+
}
|
|
212
|
+
async function readProviderJsonRecord(file) {
|
|
213
|
+
try {
|
|
214
|
+
const parsed = JSON.parse(await readFile(file, "utf8"));
|
|
215
|
+
assertProviderJsonRecord(parsed);
|
|
216
|
+
return parsed;
|
|
217
|
+
} catch (error) {
|
|
218
|
+
if (isFileNotFoundError(error)) return;
|
|
219
|
+
throw error;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
function deleteOwnedFields(value, ownership) {
|
|
223
|
+
const next = { ...value };
|
|
224
|
+
for (const key of ownership.keys ?? []) delete next[key];
|
|
225
|
+
for (const field of Object.keys(ownership.arrays ?? {})) delete next[field];
|
|
226
|
+
return next;
|
|
227
|
+
}
|
|
228
|
+
function getKeyedArrayEntryValue(value, key) {
|
|
229
|
+
if (!isProviderJsonRecord(value)) return;
|
|
230
|
+
const entryValue = value[key];
|
|
231
|
+
return entryValue === null || typeof entryValue === "boolean" || typeof entryValue === "number" || typeof entryValue === "string" ? entryValue : void 0;
|
|
232
|
+
}
|
|
233
|
+
function preserveUnownedKeyedArrayEntries(value, ownership, replacements = []) {
|
|
234
|
+
const current = Array.isArray(value) ? value : [];
|
|
235
|
+
const replacementKeys = replacements.flatMap((entry) => {
|
|
236
|
+
const key = getKeyedArrayEntryValue(entry, ownership.key);
|
|
237
|
+
return key === void 0 ? [] : [key];
|
|
238
|
+
});
|
|
239
|
+
const ownedKeys = new Set([...ownership.values ?? [], ...replacementKeys]);
|
|
240
|
+
return current.filter((entry) => {
|
|
241
|
+
const key = getKeyedArrayEntryValue(entry, ownership.key);
|
|
242
|
+
return key === void 0 || !ownedKeys.has(key);
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
function mergeOwnedArrays(existing, value, arrays) {
|
|
246
|
+
const next = { ...value };
|
|
247
|
+
for (const [field, ownership] of Object.entries(arrays ?? {})) {
|
|
248
|
+
const incoming = Array.isArray(value[field]) ? value[field] : [];
|
|
249
|
+
const merged = [...preserveUnownedKeyedArrayEntries(existing[field], ownership, incoming), ...incoming];
|
|
250
|
+
if (merged.length) next[field] = merged;
|
|
251
|
+
else delete next[field];
|
|
252
|
+
}
|
|
253
|
+
return next;
|
|
254
|
+
}
|
|
255
|
+
async function persistProviderJsonRecord(file, value, removeIfEmpty) {
|
|
256
|
+
if (removeIfEmpty && !Object.keys(value).length) {
|
|
257
|
+
await rm(file, { force: true });
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, "utf8");
|
|
261
|
+
}
|
|
262
|
+
async function writeProviderOutputConfig(file, value, ownership = {}, options = {}) {
|
|
263
|
+
await persistProviderJsonRecord(file, mergeProviderOutputConfig(await readProviderJsonRecord(file) ?? {}, value, ownership), options.removeIfEmpty === true);
|
|
264
|
+
}
|
|
265
|
+
function mergeProviderOutputConfig(existing, value, ownership = {}) {
|
|
266
|
+
assertProviderJsonRecord(existing);
|
|
267
|
+
assertProviderJsonRecord(value);
|
|
268
|
+
return {
|
|
269
|
+
...deleteOwnedFields(existing, ownership),
|
|
270
|
+
...mergeOwnedArrays(existing, value, ownership.arrays)
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
function stringifyProviderOutputConfig(value) {
|
|
274
|
+
assertProviderJsonRecord(value);
|
|
275
|
+
return JSON.stringify(value, null, 2);
|
|
276
|
+
}
|
|
277
|
+
async function cleanProviderOutputConfig(file, ownership) {
|
|
278
|
+
if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length) return;
|
|
279
|
+
const existing = await readProviderJsonRecord(file);
|
|
280
|
+
if (!existing) return;
|
|
281
|
+
const next = deleteOwnedFields(existing, ownership);
|
|
282
|
+
let changed = (ownership.keys ?? []).some((key) => key in existing);
|
|
283
|
+
for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) {
|
|
284
|
+
if (!(field in existing)) continue;
|
|
285
|
+
const current = existing[field];
|
|
286
|
+
const preserved = preserveUnownedKeyedArrayEntries(current, arrayOwnership);
|
|
287
|
+
changed ||= !Array.isArray(current) || preserved.length !== current.length || preserved.length === 0;
|
|
288
|
+
if (preserved.length) next[field] = preserved;
|
|
289
|
+
}
|
|
290
|
+
if (!changed) return;
|
|
291
|
+
await persistProviderJsonRecord(file, next, true);
|
|
292
|
+
}
|
|
293
|
+
//#endregion
|
|
294
|
+
//#region ../internal/src/build/user-entry.ts
|
|
295
|
+
function toSafeAppName(rootDir) {
|
|
296
|
+
return basename(rootDir).replace(/[^a-z0-9-]+/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
|
|
297
|
+
}
|
|
298
|
+
//#endregion
|
|
299
|
+
//#region ../internal/src/build/cloudflare.ts
|
|
300
|
+
function createDefaultCloudflareOutputRoot(rootDir) {
|
|
301
|
+
return resolve(rootDir, "dist", toSafeAppName(rootDir));
|
|
302
|
+
}
|
|
303
|
+
async function writeCloudflareWranglerConfig(options) {
|
|
304
|
+
const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
|
|
305
|
+
const configFile = resolve(outputRoot, "wrangler.json");
|
|
306
|
+
if (!options.wranglerConfig) {
|
|
307
|
+
await cleanProviderOutputConfig(configFile, options.wranglerConfigOwnership ?? {});
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
await mkdir(outputRoot, { recursive: true });
|
|
311
|
+
await writeProviderOutputConfig(configFile, options.wranglerConfig, options.wranglerConfigOwnership, { removeIfEmpty: true });
|
|
312
|
+
}
|
|
313
|
+
//#endregion
|
|
314
|
+
//#region ../internal/src/build/vite.ts
|
|
315
|
+
var import_main = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
316
|
+
var __defProp = Object.defineProperty;
|
|
317
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
318
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
319
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
320
|
+
var __export = (target, all) => {
|
|
321
|
+
for (var name in all) __defProp(target, name, {
|
|
322
|
+
get: all[name],
|
|
323
|
+
enumerable: true
|
|
324
|
+
});
|
|
325
|
+
};
|
|
326
|
+
var __copyProps = (to, from, except, desc) => {
|
|
327
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
328
|
+
for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
329
|
+
get: () => from[key],
|
|
330
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
return to;
|
|
334
|
+
};
|
|
335
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
336
|
+
var node_exports = {};
|
|
337
|
+
__export(node_exports, {
|
|
338
|
+
analyzeMetafile: () => analyzeMetafile,
|
|
339
|
+
analyzeMetafileSync: () => analyzeMetafileSync,
|
|
340
|
+
build: () => build,
|
|
341
|
+
buildSync: () => buildSync,
|
|
342
|
+
context: () => context,
|
|
343
|
+
default: () => node_default,
|
|
344
|
+
formatMessages: () => formatMessages,
|
|
345
|
+
formatMessagesSync: () => formatMessagesSync,
|
|
346
|
+
initialize: () => initialize,
|
|
347
|
+
stop: () => stop,
|
|
348
|
+
transform: () => transform,
|
|
349
|
+
transformSync: () => transformSync,
|
|
350
|
+
version: () => version
|
|
351
|
+
});
|
|
352
|
+
module.exports = __toCommonJS(node_exports);
|
|
353
|
+
function encodePacket(packet) {
|
|
354
|
+
let visit = (value) => {
|
|
355
|
+
if (value === null) bb.write8(0);
|
|
356
|
+
else if (typeof value === "boolean") {
|
|
357
|
+
bb.write8(1);
|
|
358
|
+
bb.write8(+value);
|
|
359
|
+
} else if (typeof value === "number") {
|
|
360
|
+
bb.write8(2);
|
|
361
|
+
bb.write32(value | 0);
|
|
362
|
+
} else if (typeof value === "string") {
|
|
363
|
+
bb.write8(3);
|
|
364
|
+
bb.write(encodeUTF8(value));
|
|
365
|
+
} else if (value instanceof Uint8Array) {
|
|
366
|
+
bb.write8(4);
|
|
367
|
+
bb.write(value);
|
|
368
|
+
} else if (value instanceof Array) {
|
|
369
|
+
bb.write8(5);
|
|
370
|
+
bb.write32(value.length);
|
|
371
|
+
for (let item of value) visit(item);
|
|
372
|
+
} else {
|
|
373
|
+
let keys = Object.keys(value);
|
|
374
|
+
bb.write8(6);
|
|
375
|
+
bb.write32(keys.length);
|
|
376
|
+
for (let key of keys) {
|
|
377
|
+
bb.write(encodeUTF8(key));
|
|
378
|
+
visit(value[key]);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
let bb = new ByteBuffer();
|
|
383
|
+
bb.write32(0);
|
|
384
|
+
bb.write32(packet.id << 1 | +!packet.isRequest);
|
|
385
|
+
visit(packet.value);
|
|
386
|
+
writeUInt32LE(bb.buf, bb.len - 4, 0);
|
|
387
|
+
return bb.buf.subarray(0, bb.len);
|
|
388
|
+
}
|
|
389
|
+
function decodePacket(bytes) {
|
|
390
|
+
let visit = () => {
|
|
391
|
+
switch (bb.read8()) {
|
|
392
|
+
case 0: return null;
|
|
393
|
+
case 1: return !!bb.read8();
|
|
394
|
+
case 2: return bb.read32();
|
|
395
|
+
case 3: return decodeUTF8(bb.read());
|
|
396
|
+
case 4: return bb.read();
|
|
397
|
+
case 5: {
|
|
398
|
+
let count = bb.read32();
|
|
399
|
+
let value2 = [];
|
|
400
|
+
for (let i = 0; i < count; i++) value2.push(visit());
|
|
401
|
+
return value2;
|
|
402
|
+
}
|
|
403
|
+
case 6: {
|
|
404
|
+
let count = bb.read32();
|
|
405
|
+
let value2 = {};
|
|
406
|
+
for (let i = 0; i < count; i++) value2[decodeUTF8(bb.read())] = visit();
|
|
407
|
+
return value2;
|
|
408
|
+
}
|
|
409
|
+
default: throw new Error("Invalid packet");
|
|
410
|
+
}
|
|
411
|
+
};
|
|
412
|
+
let bb = new ByteBuffer(bytes);
|
|
413
|
+
let id = bb.read32();
|
|
414
|
+
let isRequest = (id & 1) === 0;
|
|
415
|
+
id >>>= 1;
|
|
416
|
+
let value = visit();
|
|
417
|
+
if (bb.ptr !== bytes.length) throw new Error("Invalid packet");
|
|
418
|
+
return {
|
|
419
|
+
id,
|
|
420
|
+
isRequest,
|
|
421
|
+
value
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
var ByteBuffer = class {
|
|
425
|
+
constructor(buf = new Uint8Array(1024)) {
|
|
426
|
+
this.buf = buf;
|
|
427
|
+
this.len = 0;
|
|
428
|
+
this.ptr = 0;
|
|
429
|
+
}
|
|
430
|
+
_write(delta) {
|
|
431
|
+
if (this.len + delta > this.buf.length) {
|
|
432
|
+
let clone = new Uint8Array((this.len + delta) * 2);
|
|
433
|
+
clone.set(this.buf);
|
|
434
|
+
this.buf = clone;
|
|
435
|
+
}
|
|
436
|
+
this.len += delta;
|
|
437
|
+
return this.len - delta;
|
|
438
|
+
}
|
|
439
|
+
write8(value) {
|
|
440
|
+
let offset = this._write(1);
|
|
441
|
+
this.buf[offset] = value;
|
|
442
|
+
}
|
|
443
|
+
write32(value) {
|
|
444
|
+
let offset = this._write(4);
|
|
445
|
+
writeUInt32LE(this.buf, value, offset);
|
|
446
|
+
}
|
|
447
|
+
write(bytes) {
|
|
448
|
+
let offset = this._write(4 + bytes.length);
|
|
449
|
+
writeUInt32LE(this.buf, bytes.length, offset);
|
|
450
|
+
this.buf.set(bytes, offset + 4);
|
|
451
|
+
}
|
|
452
|
+
_read(delta) {
|
|
453
|
+
if (this.ptr + delta > this.buf.length) throw new Error("Invalid packet");
|
|
454
|
+
this.ptr += delta;
|
|
455
|
+
return this.ptr - delta;
|
|
456
|
+
}
|
|
457
|
+
read8() {
|
|
458
|
+
return this.buf[this._read(1)];
|
|
459
|
+
}
|
|
460
|
+
read32() {
|
|
461
|
+
return readUInt32LE(this.buf, this._read(4));
|
|
462
|
+
}
|
|
463
|
+
read() {
|
|
464
|
+
let length = this.read32();
|
|
465
|
+
let bytes = new Uint8Array(length);
|
|
466
|
+
let ptr = this._read(bytes.length);
|
|
467
|
+
bytes.set(this.buf.subarray(ptr, ptr + length));
|
|
468
|
+
return bytes;
|
|
469
|
+
}
|
|
470
|
+
};
|
|
471
|
+
var encodeUTF8;
|
|
472
|
+
var decodeUTF8;
|
|
473
|
+
var encodeInvariant;
|
|
474
|
+
if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
|
|
475
|
+
let encoder = new TextEncoder();
|
|
476
|
+
let decoder = new TextDecoder();
|
|
477
|
+
encodeUTF8 = (text) => encoder.encode(text);
|
|
478
|
+
decodeUTF8 = (bytes) => decoder.decode(bytes);
|
|
479
|
+
encodeInvariant = "new TextEncoder().encode(\"\")";
|
|
480
|
+
} else if (typeof Buffer !== "undefined") {
|
|
481
|
+
encodeUTF8 = (text) => Buffer.from(text);
|
|
482
|
+
decodeUTF8 = (bytes) => {
|
|
483
|
+
let { buffer, byteOffset, byteLength } = bytes;
|
|
484
|
+
return Buffer.from(buffer, byteOffset, byteLength).toString();
|
|
485
|
+
};
|
|
486
|
+
encodeInvariant = "Buffer.from(\"\")";
|
|
487
|
+
} else throw new Error("No UTF-8 codec found");
|
|
488
|
+
if (!(encodeUTF8("") instanceof Uint8Array)) throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false
|
|
489
|
+
|
|
490
|
+
This indicates that your JavaScript environment is broken. You cannot use
|
|
491
|
+
esbuild in this environment because esbuild relies on this invariant. This
|
|
492
|
+
is not a problem with esbuild. You need to fix your environment instead.
|
|
493
|
+
`);
|
|
494
|
+
function readUInt32LE(buffer, offset) {
|
|
495
|
+
return (buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24) >>> 0;
|
|
496
|
+
}
|
|
497
|
+
function writeUInt32LE(buffer, value, offset) {
|
|
498
|
+
buffer[offset++] = value;
|
|
499
|
+
buffer[offset++] = value >> 8;
|
|
500
|
+
buffer[offset++] = value >> 16;
|
|
501
|
+
buffer[offset++] = value >> 24;
|
|
502
|
+
}
|
|
503
|
+
var fromCharCode = String.fromCharCode;
|
|
504
|
+
function throwSyntaxError(bytes, index, message) {
|
|
505
|
+
const c = bytes[index];
|
|
506
|
+
let line = 1;
|
|
507
|
+
let column = 0;
|
|
508
|
+
for (let i = 0; i < index; i++) if (bytes[i] === 10) {
|
|
509
|
+
line++;
|
|
510
|
+
column = 0;
|
|
511
|
+
} else column++;
|
|
512
|
+
throw new SyntaxError(message ? message : index === bytes.length ? "Unexpected end of input while parsing JSON" : c >= 32 && c <= 126 ? `Unexpected character ${fromCharCode(c)} in JSON at position ${index} (line ${line}, column ${column})` : `Unexpected byte 0x${c.toString(16)} in JSON at position ${index} (line ${line}, column ${column})`);
|
|
513
|
+
}
|
|
514
|
+
function JSON_parse(bytes) {
|
|
515
|
+
if (!(bytes instanceof Uint8Array)) throw new Error(`JSON input must be a Uint8Array`);
|
|
516
|
+
const propertyStack = [];
|
|
517
|
+
const objectStack = [];
|
|
518
|
+
const stateStack = [];
|
|
519
|
+
const length = bytes.length;
|
|
520
|
+
let property = null;
|
|
521
|
+
let state = 0;
|
|
522
|
+
let object;
|
|
523
|
+
let i = 0;
|
|
524
|
+
while (i < length) {
|
|
525
|
+
let c = bytes[i++];
|
|
526
|
+
if (c <= 32) continue;
|
|
527
|
+
let value;
|
|
528
|
+
if (state === 2 && property === null && c !== 34 && c !== 125) throwSyntaxError(bytes, --i);
|
|
529
|
+
switch (c) {
|
|
530
|
+
case 116:
|
|
531
|
+
if (bytes[i++] !== 114 || bytes[i++] !== 117 || bytes[i++] !== 101) throwSyntaxError(bytes, --i);
|
|
532
|
+
value = true;
|
|
533
|
+
break;
|
|
534
|
+
case 102:
|
|
535
|
+
if (bytes[i++] !== 97 || bytes[i++] !== 108 || bytes[i++] !== 115 || bytes[i++] !== 101) throwSyntaxError(bytes, --i);
|
|
536
|
+
value = false;
|
|
537
|
+
break;
|
|
538
|
+
case 110:
|
|
539
|
+
if (bytes[i++] !== 117 || bytes[i++] !== 108 || bytes[i++] !== 108) throwSyntaxError(bytes, --i);
|
|
540
|
+
value = null;
|
|
541
|
+
break;
|
|
542
|
+
case 45:
|
|
543
|
+
case 46:
|
|
544
|
+
case 48:
|
|
545
|
+
case 49:
|
|
546
|
+
case 50:
|
|
547
|
+
case 51:
|
|
548
|
+
case 52:
|
|
549
|
+
case 53:
|
|
550
|
+
case 54:
|
|
551
|
+
case 55:
|
|
552
|
+
case 56:
|
|
553
|
+
case 57: {
|
|
554
|
+
let index = i;
|
|
555
|
+
value = fromCharCode(c);
|
|
556
|
+
c = bytes[i];
|
|
557
|
+
while (true) {
|
|
558
|
+
switch (c) {
|
|
559
|
+
case 43:
|
|
560
|
+
case 45:
|
|
561
|
+
case 46:
|
|
562
|
+
case 48:
|
|
563
|
+
case 49:
|
|
564
|
+
case 50:
|
|
565
|
+
case 51:
|
|
566
|
+
case 52:
|
|
567
|
+
case 53:
|
|
568
|
+
case 54:
|
|
569
|
+
case 55:
|
|
570
|
+
case 56:
|
|
571
|
+
case 57:
|
|
572
|
+
case 101:
|
|
573
|
+
case 69:
|
|
574
|
+
value += fromCharCode(c);
|
|
575
|
+
c = bytes[++i];
|
|
576
|
+
continue;
|
|
577
|
+
}
|
|
578
|
+
break;
|
|
579
|
+
}
|
|
580
|
+
value = +value;
|
|
581
|
+
if (isNaN(value)) throwSyntaxError(bytes, --index, "Invalid number");
|
|
582
|
+
break;
|
|
583
|
+
}
|
|
584
|
+
case 34:
|
|
585
|
+
value = "";
|
|
586
|
+
while (true) {
|
|
587
|
+
if (i >= length) throwSyntaxError(bytes, length);
|
|
588
|
+
c = bytes[i++];
|
|
589
|
+
if (c === 34) break;
|
|
590
|
+
else if (c === 92) switch (bytes[i++]) {
|
|
591
|
+
case 34:
|
|
592
|
+
value += "\"";
|
|
593
|
+
break;
|
|
594
|
+
case 47:
|
|
595
|
+
value += "/";
|
|
596
|
+
break;
|
|
597
|
+
case 92:
|
|
598
|
+
value += "\\";
|
|
599
|
+
break;
|
|
600
|
+
case 98:
|
|
601
|
+
value += "\b";
|
|
602
|
+
break;
|
|
603
|
+
case 102:
|
|
604
|
+
value += "\f";
|
|
605
|
+
break;
|
|
606
|
+
case 110:
|
|
607
|
+
value += "\n";
|
|
608
|
+
break;
|
|
609
|
+
case 114:
|
|
610
|
+
value += "\r";
|
|
611
|
+
break;
|
|
612
|
+
case 116:
|
|
613
|
+
value += " ";
|
|
614
|
+
break;
|
|
615
|
+
case 117: {
|
|
616
|
+
let code = 0;
|
|
617
|
+
for (let j = 0; j < 4; j++) {
|
|
618
|
+
c = bytes[i++];
|
|
619
|
+
code <<= 4;
|
|
620
|
+
if (c >= 48 && c <= 57) code |= c - 48;
|
|
621
|
+
else if (c >= 97 && c <= 102) code |= c + -87;
|
|
622
|
+
else if (c >= 65 && c <= 70) code |= c + -55;
|
|
623
|
+
else throwSyntaxError(bytes, --i);
|
|
624
|
+
}
|
|
625
|
+
value += fromCharCode(code);
|
|
626
|
+
break;
|
|
627
|
+
}
|
|
628
|
+
default:
|
|
629
|
+
throwSyntaxError(bytes, --i);
|
|
630
|
+
break;
|
|
631
|
+
}
|
|
632
|
+
else if (c <= 127) value += fromCharCode(c);
|
|
633
|
+
else if ((c & 224) === 192) value += fromCharCode((c & 31) << 6 | bytes[i++] & 63);
|
|
634
|
+
else if ((c & 240) === 224) value += fromCharCode((c & 15) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63);
|
|
635
|
+
else if ((c & 248) == 240) {
|
|
636
|
+
let codePoint = (c & 7) << 18 | (bytes[i++] & 63) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63;
|
|
637
|
+
if (codePoint > 65535) {
|
|
638
|
+
codePoint -= 65536;
|
|
639
|
+
value += fromCharCode(codePoint >> 10 & 1023 | 55296);
|
|
640
|
+
codePoint = 56320 | codePoint & 1023;
|
|
641
|
+
}
|
|
642
|
+
value += fromCharCode(codePoint);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
value[0];
|
|
646
|
+
break;
|
|
647
|
+
case 91:
|
|
648
|
+
value = [];
|
|
649
|
+
propertyStack.push(property);
|
|
650
|
+
objectStack.push(object);
|
|
651
|
+
stateStack.push(state);
|
|
652
|
+
property = null;
|
|
653
|
+
object = value;
|
|
654
|
+
state = 1;
|
|
655
|
+
continue;
|
|
656
|
+
case 123:
|
|
657
|
+
value = {};
|
|
658
|
+
propertyStack.push(property);
|
|
659
|
+
objectStack.push(object);
|
|
660
|
+
stateStack.push(state);
|
|
661
|
+
property = null;
|
|
662
|
+
object = value;
|
|
663
|
+
state = 2;
|
|
664
|
+
continue;
|
|
665
|
+
case 93:
|
|
666
|
+
if (state !== 1) throwSyntaxError(bytes, --i);
|
|
667
|
+
value = object;
|
|
668
|
+
property = propertyStack.pop();
|
|
669
|
+
object = objectStack.pop();
|
|
670
|
+
state = stateStack.pop();
|
|
671
|
+
break;
|
|
672
|
+
case 125:
|
|
673
|
+
if (state !== 2) throwSyntaxError(bytes, --i);
|
|
674
|
+
value = object;
|
|
675
|
+
property = propertyStack.pop();
|
|
676
|
+
object = objectStack.pop();
|
|
677
|
+
state = stateStack.pop();
|
|
678
|
+
break;
|
|
679
|
+
default: throwSyntaxError(bytes, --i);
|
|
680
|
+
}
|
|
681
|
+
c = bytes[i];
|
|
682
|
+
while (c <= 32) c = bytes[++i];
|
|
683
|
+
switch (state) {
|
|
684
|
+
case 0:
|
|
685
|
+
if (i === length) return value;
|
|
686
|
+
break;
|
|
687
|
+
case 1:
|
|
688
|
+
object.push(value);
|
|
689
|
+
if (c === 44) {
|
|
690
|
+
i++;
|
|
691
|
+
continue;
|
|
692
|
+
}
|
|
693
|
+
if (c === 93) continue;
|
|
694
|
+
break;
|
|
695
|
+
case 2:
|
|
696
|
+
if (property === null) {
|
|
697
|
+
property = value;
|
|
698
|
+
if (c === 58) {
|
|
699
|
+
i++;
|
|
700
|
+
continue;
|
|
701
|
+
}
|
|
702
|
+
} else {
|
|
703
|
+
object[property] = value;
|
|
704
|
+
property = null;
|
|
705
|
+
if (c === 44) {
|
|
706
|
+
i++;
|
|
707
|
+
continue;
|
|
708
|
+
}
|
|
709
|
+
if (c === 125) continue;
|
|
710
|
+
}
|
|
711
|
+
break;
|
|
712
|
+
}
|
|
713
|
+
break;
|
|
714
|
+
}
|
|
715
|
+
throwSyntaxError(bytes, i);
|
|
716
|
+
}
|
|
717
|
+
var quote = JSON.stringify;
|
|
718
|
+
var buildLogLevelDefault = "warning";
|
|
719
|
+
var transformLogLevelDefault = "silent";
|
|
720
|
+
function validateAndJoinStringArray(values, what) {
|
|
721
|
+
const toJoin = [];
|
|
722
|
+
for (const value of values) {
|
|
723
|
+
validateStringValue(value, what);
|
|
724
|
+
if (value.indexOf(",") >= 0) throw new Error(`Invalid ${what}: ${value}`);
|
|
725
|
+
toJoin.push(value);
|
|
726
|
+
}
|
|
727
|
+
return toJoin.join(",");
|
|
728
|
+
}
|
|
729
|
+
var canBeAnything = () => null;
|
|
730
|
+
var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
|
|
731
|
+
var mustBeString = (value) => typeof value === "string" ? null : "a string";
|
|
732
|
+
var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
|
|
733
|
+
var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
|
|
734
|
+
var mustBeValidPortNumber = (value) => typeof value === "number" && value === (value | 0) && value >= 0 && value <= 65535 ? null : "a valid port number";
|
|
735
|
+
var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
|
|
736
|
+
var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
|
|
737
|
+
var mustBeArrayOfStrings = (value) => Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "an array of strings";
|
|
738
|
+
var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
|
|
739
|
+
var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
|
|
740
|
+
var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
|
|
741
|
+
var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
|
|
742
|
+
var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
|
|
743
|
+
var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
|
|
744
|
+
var mustBeStringOrArrayOfStrings = (value) => typeof value === "string" || Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "a string or an array of strings";
|
|
745
|
+
var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
|
|
746
|
+
var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL";
|
|
747
|
+
function getFlag(object, keys, key, mustBeFn) {
|
|
748
|
+
let value = object[key];
|
|
749
|
+
keys[key + ""] = true;
|
|
750
|
+
if (value === void 0) return void 0;
|
|
751
|
+
let mustBe = mustBeFn(value);
|
|
752
|
+
if (mustBe !== null) throw new Error(`${quote(key)} must be ${mustBe}`);
|
|
753
|
+
return value;
|
|
754
|
+
}
|
|
755
|
+
function checkForInvalidFlags(object, keys, where) {
|
|
756
|
+
for (let key in object) if (!(key in keys)) throw new Error(`Invalid option ${where}: ${quote(key)}`);
|
|
757
|
+
}
|
|
758
|
+
function validateInitializeOptions(options) {
|
|
759
|
+
let keys = /* @__PURE__ */ Object.create(null);
|
|
760
|
+
let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL);
|
|
761
|
+
let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule);
|
|
762
|
+
let worker = getFlag(options, keys, "worker", mustBeBoolean);
|
|
763
|
+
checkForInvalidFlags(options, keys, "in initialize() call");
|
|
764
|
+
return {
|
|
765
|
+
wasmURL,
|
|
766
|
+
wasmModule,
|
|
767
|
+
worker
|
|
768
|
+
};
|
|
769
|
+
}
|
|
770
|
+
function validateMangleCache(mangleCache) {
|
|
771
|
+
let validated;
|
|
772
|
+
if (mangleCache !== void 0) {
|
|
773
|
+
validated = /* @__PURE__ */ Object.create(null);
|
|
774
|
+
for (let key in mangleCache) {
|
|
775
|
+
let value = mangleCache[key];
|
|
776
|
+
if (typeof value === "string" || value === false) validated[key] = value;
|
|
777
|
+
else throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`);
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
return validated;
|
|
781
|
+
}
|
|
782
|
+
function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) {
|
|
783
|
+
let color = getFlag(options, keys, "color", mustBeBoolean);
|
|
784
|
+
let logLevel = getFlag(options, keys, "logLevel", mustBeString);
|
|
785
|
+
let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
|
|
786
|
+
if (color !== void 0) flags.push(`--color=${color}`);
|
|
787
|
+
else if (isTTY2) flags.push(`--color=true`);
|
|
788
|
+
flags.push(`--log-level=${logLevel || logLevelDefault}`);
|
|
789
|
+
flags.push(`--log-limit=${logLimit || 0}`);
|
|
790
|
+
}
|
|
791
|
+
function validateStringValue(value, what, key) {
|
|
792
|
+
if (typeof value !== "string") throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`);
|
|
793
|
+
return value;
|
|
794
|
+
}
|
|
795
|
+
function pushCommonFlags(flags, options, keys) {
|
|
796
|
+
let legalComments = getFlag(options, keys, "legalComments", mustBeString);
|
|
797
|
+
let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
|
|
798
|
+
let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
|
|
799
|
+
let target = getFlag(options, keys, "target", mustBeStringOrArrayOfStrings);
|
|
800
|
+
let format = getFlag(options, keys, "format", mustBeString);
|
|
801
|
+
let globalName = getFlag(options, keys, "globalName", mustBeString);
|
|
802
|
+
let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp);
|
|
803
|
+
let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp);
|
|
804
|
+
let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean);
|
|
805
|
+
let minify = getFlag(options, keys, "minify", mustBeBoolean);
|
|
806
|
+
let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
|
|
807
|
+
let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
|
|
808
|
+
let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
|
|
809
|
+
let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger);
|
|
810
|
+
let drop = getFlag(options, keys, "drop", mustBeArrayOfStrings);
|
|
811
|
+
let dropLabels = getFlag(options, keys, "dropLabels", mustBeArrayOfStrings);
|
|
812
|
+
let charset = getFlag(options, keys, "charset", mustBeString);
|
|
813
|
+
let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
|
|
814
|
+
let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
|
|
815
|
+
let jsx = getFlag(options, keys, "jsx", mustBeString);
|
|
816
|
+
let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
|
|
817
|
+
let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
|
|
818
|
+
let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString);
|
|
819
|
+
let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean);
|
|
820
|
+
let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean);
|
|
821
|
+
let define = getFlag(options, keys, "define", mustBeObject);
|
|
822
|
+
let logOverride = getFlag(options, keys, "logOverride", mustBeObject);
|
|
823
|
+
let supported = getFlag(options, keys, "supported", mustBeObject);
|
|
824
|
+
let pure = getFlag(options, keys, "pure", mustBeArrayOfStrings);
|
|
825
|
+
let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
|
|
826
|
+
let platform = getFlag(options, keys, "platform", mustBeString);
|
|
827
|
+
let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
|
|
828
|
+
let absPaths = getFlag(options, keys, "absPaths", mustBeArrayOfStrings);
|
|
829
|
+
if (legalComments) flags.push(`--legal-comments=${legalComments}`);
|
|
830
|
+
if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`);
|
|
831
|
+
if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`);
|
|
832
|
+
if (target) flags.push(`--target=${validateAndJoinStringArray(Array.isArray(target) ? target : [target], "target")}`);
|
|
833
|
+
if (format) flags.push(`--format=${format}`);
|
|
834
|
+
if (globalName) flags.push(`--global-name=${globalName}`);
|
|
835
|
+
if (platform) flags.push(`--platform=${platform}`);
|
|
836
|
+
if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
|
|
837
|
+
if (minify) flags.push("--minify");
|
|
838
|
+
if (minifySyntax) flags.push("--minify-syntax");
|
|
839
|
+
if (minifyWhitespace) flags.push("--minify-whitespace");
|
|
840
|
+
if (minifyIdentifiers) flags.push("--minify-identifiers");
|
|
841
|
+
if (lineLimit) flags.push(`--line-limit=${lineLimit}`);
|
|
842
|
+
if (charset) flags.push(`--charset=${charset}`);
|
|
843
|
+
if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`);
|
|
844
|
+
if (ignoreAnnotations) flags.push(`--ignore-annotations`);
|
|
845
|
+
if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`);
|
|
846
|
+
if (dropLabels) flags.push(`--drop-labels=${validateAndJoinStringArray(dropLabels, "drop label")}`);
|
|
847
|
+
if (absPaths) flags.push(`--abs-paths=${validateAndJoinStringArray(absPaths, "abs paths")}`);
|
|
848
|
+
if (mangleProps) flags.push(`--mangle-props=${jsRegExpToGoRegExp(mangleProps)}`);
|
|
849
|
+
if (reserveProps) flags.push(`--reserve-props=${jsRegExpToGoRegExp(reserveProps)}`);
|
|
850
|
+
if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`);
|
|
851
|
+
if (jsx) flags.push(`--jsx=${jsx}`);
|
|
852
|
+
if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`);
|
|
853
|
+
if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`);
|
|
854
|
+
if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`);
|
|
855
|
+
if (jsxDev) flags.push(`--jsx-dev`);
|
|
856
|
+
if (jsxSideEffects) flags.push(`--jsx-side-effects`);
|
|
857
|
+
if (define) for (let key in define) {
|
|
858
|
+
if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`);
|
|
859
|
+
flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`);
|
|
860
|
+
}
|
|
861
|
+
if (logOverride) for (let key in logOverride) {
|
|
862
|
+
if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`);
|
|
863
|
+
flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`);
|
|
864
|
+
}
|
|
865
|
+
if (supported) for (let key in supported) {
|
|
866
|
+
if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`);
|
|
867
|
+
const value = supported[key];
|
|
868
|
+
if (typeof value !== "boolean") throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`);
|
|
869
|
+
flags.push(`--supported:${key}=${value}`);
|
|
870
|
+
}
|
|
871
|
+
if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`);
|
|
872
|
+
if (keepNames) flags.push(`--keep-names`);
|
|
873
|
+
}
|
|
874
|
+
function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) {
|
|
875
|
+
var _a2;
|
|
876
|
+
let flags = [];
|
|
877
|
+
let entries = [];
|
|
878
|
+
let keys = /* @__PURE__ */ Object.create(null);
|
|
879
|
+
let stdinContents = null;
|
|
880
|
+
let stdinResolveDir = null;
|
|
881
|
+
pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
|
|
882
|
+
pushCommonFlags(flags, options, keys);
|
|
883
|
+
let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
|
|
884
|
+
let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
|
|
885
|
+
let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
|
|
886
|
+
let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
|
|
887
|
+
let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
|
|
888
|
+
let outfile = getFlag(options, keys, "outfile", mustBeString);
|
|
889
|
+
let outdir = getFlag(options, keys, "outdir", mustBeString);
|
|
890
|
+
let outbase = getFlag(options, keys, "outbase", mustBeString);
|
|
891
|
+
let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
|
|
892
|
+
let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArrayOfStrings);
|
|
893
|
+
let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArrayOfStrings);
|
|
894
|
+
let mainFields = getFlag(options, keys, "mainFields", mustBeArrayOfStrings);
|
|
895
|
+
let conditions = getFlag(options, keys, "conditions", mustBeArrayOfStrings);
|
|
896
|
+
let external = getFlag(options, keys, "external", mustBeArrayOfStrings);
|
|
897
|
+
let packages = getFlag(options, keys, "packages", mustBeString);
|
|
898
|
+
let alias = getFlag(options, keys, "alias", mustBeObject);
|
|
899
|
+
let loader = getFlag(options, keys, "loader", mustBeObject);
|
|
900
|
+
let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
|
|
901
|
+
let publicPath = getFlag(options, keys, "publicPath", mustBeString);
|
|
902
|
+
let entryNames = getFlag(options, keys, "entryNames", mustBeString);
|
|
903
|
+
let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
|
|
904
|
+
let assetNames = getFlag(options, keys, "assetNames", mustBeString);
|
|
905
|
+
let inject = getFlag(options, keys, "inject", mustBeArrayOfStrings);
|
|
906
|
+
let banner = getFlag(options, keys, "banner", mustBeObject);
|
|
907
|
+
let footer = getFlag(options, keys, "footer", mustBeObject);
|
|
908
|
+
let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints);
|
|
909
|
+
let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
|
|
910
|
+
let stdin = getFlag(options, keys, "stdin", mustBeObject);
|
|
911
|
+
let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault;
|
|
912
|
+
let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
|
|
913
|
+
let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
|
|
914
|
+
keys.plugins = true;
|
|
915
|
+
checkForInvalidFlags(options, keys, `in ${callName}() call`);
|
|
916
|
+
if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
|
|
917
|
+
if (bundle) flags.push("--bundle");
|
|
918
|
+
if (allowOverwrite) flags.push("--allow-overwrite");
|
|
919
|
+
if (splitting) flags.push("--splitting");
|
|
920
|
+
if (preserveSymlinks) flags.push("--preserve-symlinks");
|
|
921
|
+
if (metafile) flags.push(`--metafile`);
|
|
922
|
+
if (outfile) flags.push(`--outfile=${outfile}`);
|
|
923
|
+
if (outdir) flags.push(`--outdir=${outdir}`);
|
|
924
|
+
if (outbase) flags.push(`--outbase=${outbase}`);
|
|
925
|
+
if (tsconfig) flags.push(`--tsconfig=${tsconfig}`);
|
|
926
|
+
if (packages) flags.push(`--packages=${packages}`);
|
|
927
|
+
if (resolveExtensions) flags.push(`--resolve-extensions=${validateAndJoinStringArray(resolveExtensions, "resolve extension")}`);
|
|
928
|
+
if (publicPath) flags.push(`--public-path=${publicPath}`);
|
|
929
|
+
if (entryNames) flags.push(`--entry-names=${entryNames}`);
|
|
930
|
+
if (chunkNames) flags.push(`--chunk-names=${chunkNames}`);
|
|
931
|
+
if (assetNames) flags.push(`--asset-names=${assetNames}`);
|
|
932
|
+
if (mainFields) flags.push(`--main-fields=${validateAndJoinStringArray(mainFields, "main field")}`);
|
|
933
|
+
if (conditions) flags.push(`--conditions=${validateAndJoinStringArray(conditions, "condition")}`);
|
|
934
|
+
if (external) for (let name of external) flags.push(`--external:${validateStringValue(name, "external")}`);
|
|
935
|
+
if (alias) for (let old in alias) {
|
|
936
|
+
if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`);
|
|
937
|
+
flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`);
|
|
938
|
+
}
|
|
939
|
+
if (banner) for (let type in banner) {
|
|
940
|
+
if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`);
|
|
941
|
+
flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`);
|
|
942
|
+
}
|
|
943
|
+
if (footer) for (let type in footer) {
|
|
944
|
+
if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`);
|
|
945
|
+
flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`);
|
|
946
|
+
}
|
|
947
|
+
if (inject) for (let path3 of inject) flags.push(`--inject:${validateStringValue(path3, "inject")}`);
|
|
948
|
+
if (loader) for (let ext in loader) {
|
|
949
|
+
if (ext.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext}`);
|
|
950
|
+
flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`);
|
|
951
|
+
}
|
|
952
|
+
if (outExtension) for (let ext in outExtension) {
|
|
953
|
+
if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`);
|
|
954
|
+
flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
|
|
955
|
+
}
|
|
956
|
+
if (entryPoints) if (Array.isArray(entryPoints)) for (let i = 0, n = entryPoints.length; i < n; i++) {
|
|
957
|
+
let entryPoint = entryPoints[i];
|
|
958
|
+
if (typeof entryPoint === "object" && entryPoint !== null) {
|
|
959
|
+
let entryPointKeys = /* @__PURE__ */ Object.create(null);
|
|
960
|
+
let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
|
|
961
|
+
let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
|
|
962
|
+
checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
|
|
963
|
+
if (input === void 0) throw new Error("Missing property \"in\" for entry point at index " + i);
|
|
964
|
+
if (output === void 0) throw new Error("Missing property \"out\" for entry point at index " + i);
|
|
965
|
+
entries.push([output, input]);
|
|
966
|
+
} else entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
|
|
967
|
+
}
|
|
968
|
+
else for (let key in entryPoints) entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
|
|
969
|
+
if (stdin) {
|
|
970
|
+
let stdinKeys = /* @__PURE__ */ Object.create(null);
|
|
971
|
+
let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
|
|
972
|
+
let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
|
|
973
|
+
let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
|
|
974
|
+
let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
|
|
975
|
+
checkForInvalidFlags(stdin, stdinKeys, "in \"stdin\" object");
|
|
976
|
+
if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
|
|
977
|
+
if (loader2) flags.push(`--loader=${loader2}`);
|
|
978
|
+
if (resolveDir) stdinResolveDir = resolveDir;
|
|
979
|
+
if (typeof contents === "string") stdinContents = encodeUTF8(contents);
|
|
980
|
+
else if (contents instanceof Uint8Array) stdinContents = contents;
|
|
981
|
+
}
|
|
982
|
+
let nodePaths = [];
|
|
983
|
+
if (nodePathsInput) for (let value of nodePathsInput) {
|
|
984
|
+
value += "";
|
|
985
|
+
nodePaths.push(value);
|
|
986
|
+
}
|
|
987
|
+
return {
|
|
988
|
+
entries,
|
|
989
|
+
flags,
|
|
990
|
+
write,
|
|
991
|
+
stdinContents,
|
|
992
|
+
stdinResolveDir,
|
|
993
|
+
absWorkingDir,
|
|
994
|
+
nodePaths,
|
|
995
|
+
mangleCache: validateMangleCache(mangleCache)
|
|
996
|
+
};
|
|
997
|
+
}
|
|
998
|
+
function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) {
|
|
999
|
+
let flags = [];
|
|
1000
|
+
let keys = /* @__PURE__ */ Object.create(null);
|
|
1001
|
+
pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
|
|
1002
|
+
pushCommonFlags(flags, options, keys);
|
|
1003
|
+
let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
|
|
1004
|
+
let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
|
|
1005
|
+
let loader = getFlag(options, keys, "loader", mustBeString);
|
|
1006
|
+
let banner = getFlag(options, keys, "banner", mustBeString);
|
|
1007
|
+
let footer = getFlag(options, keys, "footer", mustBeString);
|
|
1008
|
+
let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
|
|
1009
|
+
checkForInvalidFlags(options, keys, `in ${callName}() call`);
|
|
1010
|
+
if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
|
|
1011
|
+
if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
|
|
1012
|
+
if (loader) flags.push(`--loader=${loader}`);
|
|
1013
|
+
if (banner) flags.push(`--banner=${banner}`);
|
|
1014
|
+
if (footer) flags.push(`--footer=${footer}`);
|
|
1015
|
+
return {
|
|
1016
|
+
flags,
|
|
1017
|
+
mangleCache: validateMangleCache(mangleCache)
|
|
1018
|
+
};
|
|
1019
|
+
}
|
|
1020
|
+
function createChannel(streamIn) {
|
|
1021
|
+
const requestCallbacksByKey = {};
|
|
1022
|
+
const closeData = {
|
|
1023
|
+
didClose: false,
|
|
1024
|
+
reason: ""
|
|
1025
|
+
};
|
|
1026
|
+
let responseCallbacks = {};
|
|
1027
|
+
let nextRequestID = 0;
|
|
1028
|
+
let nextBuildKey = 0;
|
|
1029
|
+
let stdout = new Uint8Array(16 * 1024);
|
|
1030
|
+
let stdoutUsed = 0;
|
|
1031
|
+
let readFromStdout = (chunk) => {
|
|
1032
|
+
let limit = stdoutUsed + chunk.length;
|
|
1033
|
+
if (limit > stdout.length) {
|
|
1034
|
+
let swap = new Uint8Array(limit * 2);
|
|
1035
|
+
swap.set(stdout);
|
|
1036
|
+
stdout = swap;
|
|
1037
|
+
}
|
|
1038
|
+
stdout.set(chunk, stdoutUsed);
|
|
1039
|
+
stdoutUsed += chunk.length;
|
|
1040
|
+
let offset = 0;
|
|
1041
|
+
while (offset + 4 <= stdoutUsed) {
|
|
1042
|
+
let length = readUInt32LE(stdout, offset);
|
|
1043
|
+
if (offset + 4 + length > stdoutUsed) break;
|
|
1044
|
+
offset += 4;
|
|
1045
|
+
handleIncomingPacket(stdout.subarray(offset, offset + length));
|
|
1046
|
+
offset += length;
|
|
1047
|
+
}
|
|
1048
|
+
if (offset > 0) {
|
|
1049
|
+
stdout.copyWithin(0, offset, stdoutUsed);
|
|
1050
|
+
stdoutUsed -= offset;
|
|
1051
|
+
}
|
|
1052
|
+
};
|
|
1053
|
+
let afterClose = (error) => {
|
|
1054
|
+
closeData.didClose = true;
|
|
1055
|
+
if (error) closeData.reason = ": " + (error.message || error);
|
|
1056
|
+
const text = "The service was stopped" + closeData.reason;
|
|
1057
|
+
for (let id in responseCallbacks) responseCallbacks[id](text, null);
|
|
1058
|
+
responseCallbacks = {};
|
|
1059
|
+
};
|
|
1060
|
+
let sendRequest = (refs, value, callback) => {
|
|
1061
|
+
if (closeData.didClose) return callback("The service is no longer running" + closeData.reason, null);
|
|
1062
|
+
let id = nextRequestID++;
|
|
1063
|
+
responseCallbacks[id] = (error, response) => {
|
|
1064
|
+
try {
|
|
1065
|
+
callback(error, response);
|
|
1066
|
+
} finally {
|
|
1067
|
+
if (refs) refs.unref();
|
|
1068
|
+
}
|
|
1069
|
+
};
|
|
1070
|
+
if (refs) refs.ref();
|
|
1071
|
+
streamIn.writeToStdin(encodePacket({
|
|
1072
|
+
id,
|
|
1073
|
+
isRequest: true,
|
|
1074
|
+
value
|
|
1075
|
+
}));
|
|
1076
|
+
};
|
|
1077
|
+
let sendResponse = (id, value) => {
|
|
1078
|
+
if (closeData.didClose) throw new Error("The service is no longer running" + closeData.reason);
|
|
1079
|
+
streamIn.writeToStdin(encodePacket({
|
|
1080
|
+
id,
|
|
1081
|
+
isRequest: false,
|
|
1082
|
+
value
|
|
1083
|
+
}));
|
|
1084
|
+
};
|
|
1085
|
+
let handleRequest = async (id, request) => {
|
|
1086
|
+
try {
|
|
1087
|
+
if (request.command === "ping") {
|
|
1088
|
+
sendResponse(id, {});
|
|
1089
|
+
return;
|
|
1090
|
+
}
|
|
1091
|
+
if (typeof request.key === "number") {
|
|
1092
|
+
const requestCallbacks = requestCallbacksByKey[request.key];
|
|
1093
|
+
if (!requestCallbacks) return;
|
|
1094
|
+
const callback = requestCallbacks[request.command];
|
|
1095
|
+
if (callback) {
|
|
1096
|
+
await callback(id, request);
|
|
1097
|
+
return;
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
throw new Error(`Invalid command: ` + request.command);
|
|
1101
|
+
} catch (e) {
|
|
1102
|
+
const errors = [extractErrorMessageV8(e, streamIn, null, void 0, "")];
|
|
1103
|
+
try {
|
|
1104
|
+
sendResponse(id, { errors });
|
|
1105
|
+
} catch {}
|
|
1106
|
+
}
|
|
1107
|
+
};
|
|
1108
|
+
let isFirstPacket = true;
|
|
1109
|
+
let handleIncomingPacket = (bytes) => {
|
|
1110
|
+
if (isFirstPacket) {
|
|
1111
|
+
isFirstPacket = false;
|
|
1112
|
+
let binaryVersion = String.fromCharCode(...bytes);
|
|
1113
|
+
if (binaryVersion !== "0.27.7") throw new Error(`Cannot start service: Host version "0.27.7" does not match binary version ${quote(binaryVersion)}`);
|
|
1114
|
+
return;
|
|
1115
|
+
}
|
|
1116
|
+
let packet = decodePacket(bytes);
|
|
1117
|
+
if (packet.isRequest) handleRequest(packet.id, packet.value);
|
|
1118
|
+
else {
|
|
1119
|
+
let callback = responseCallbacks[packet.id];
|
|
1120
|
+
delete responseCallbacks[packet.id];
|
|
1121
|
+
if (packet.value.error) callback(packet.value.error, {});
|
|
1122
|
+
else callback(null, packet.value);
|
|
1123
|
+
}
|
|
1124
|
+
};
|
|
1125
|
+
let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => {
|
|
1126
|
+
let refCount = 0;
|
|
1127
|
+
const buildKey = nextBuildKey++;
|
|
1128
|
+
const requestCallbacks = {};
|
|
1129
|
+
const buildRefs = {
|
|
1130
|
+
ref() {
|
|
1131
|
+
if (++refCount === 1) {
|
|
1132
|
+
if (refs) refs.ref();
|
|
1133
|
+
}
|
|
1134
|
+
},
|
|
1135
|
+
unref() {
|
|
1136
|
+
if (--refCount === 0) {
|
|
1137
|
+
delete requestCallbacksByKey[buildKey];
|
|
1138
|
+
if (refs) refs.unref();
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
};
|
|
1142
|
+
requestCallbacksByKey[buildKey] = requestCallbacks;
|
|
1143
|
+
buildRefs.ref();
|
|
1144
|
+
buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, buildRefs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, (err, res) => {
|
|
1145
|
+
try {
|
|
1146
|
+
callback(err, res);
|
|
1147
|
+
} finally {
|
|
1148
|
+
buildRefs.unref();
|
|
1149
|
+
}
|
|
1150
|
+
});
|
|
1151
|
+
};
|
|
1152
|
+
let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => {
|
|
1153
|
+
const details = createObjectStash();
|
|
1154
|
+
let start = (inputPath) => {
|
|
1155
|
+
try {
|
|
1156
|
+
if (typeof input !== "string" && !(input instanceof Uint8Array)) throw new Error("The input to \"transform\" must be a string or a Uint8Array");
|
|
1157
|
+
let { flags, mangleCache } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault);
|
|
1158
|
+
let request = {
|
|
1159
|
+
command: "transform",
|
|
1160
|
+
flags,
|
|
1161
|
+
inputFS: inputPath !== null,
|
|
1162
|
+
input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input
|
|
1163
|
+
};
|
|
1164
|
+
if (mangleCache) request.mangleCache = mangleCache;
|
|
1165
|
+
sendRequest(refs, request, (error, response) => {
|
|
1166
|
+
if (error) return callback(new Error(error), null);
|
|
1167
|
+
let errors = replaceDetailsInMessages(response.errors, details);
|
|
1168
|
+
let warnings = replaceDetailsInMessages(response.warnings, details);
|
|
1169
|
+
let outstanding = 1;
|
|
1170
|
+
let next = () => {
|
|
1171
|
+
if (--outstanding === 0) {
|
|
1172
|
+
let result = {
|
|
1173
|
+
warnings,
|
|
1174
|
+
code: response.code,
|
|
1175
|
+
map: response.map,
|
|
1176
|
+
mangleCache: void 0,
|
|
1177
|
+
legalComments: void 0
|
|
1178
|
+
};
|
|
1179
|
+
if ("legalComments" in response) result.legalComments = response == null ? void 0 : response.legalComments;
|
|
1180
|
+
if (response.mangleCache) result.mangleCache = response == null ? void 0 : response.mangleCache;
|
|
1181
|
+
callback(null, result);
|
|
1182
|
+
}
|
|
1183
|
+
};
|
|
1184
|
+
if (errors.length > 0) return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
|
|
1185
|
+
if (response.codeFS) {
|
|
1186
|
+
outstanding++;
|
|
1187
|
+
fs3.readFile(response.code, (err, contents) => {
|
|
1188
|
+
if (err !== null) callback(err, null);
|
|
1189
|
+
else {
|
|
1190
|
+
response.code = contents;
|
|
1191
|
+
next();
|
|
1192
|
+
}
|
|
1193
|
+
});
|
|
1194
|
+
}
|
|
1195
|
+
if (response.mapFS) {
|
|
1196
|
+
outstanding++;
|
|
1197
|
+
fs3.readFile(response.map, (err, contents) => {
|
|
1198
|
+
if (err !== null) callback(err, null);
|
|
1199
|
+
else {
|
|
1200
|
+
response.map = contents;
|
|
1201
|
+
next();
|
|
1202
|
+
}
|
|
1203
|
+
});
|
|
1204
|
+
}
|
|
1205
|
+
next();
|
|
1206
|
+
});
|
|
1207
|
+
} catch (e) {
|
|
1208
|
+
let flags = [];
|
|
1209
|
+
try {
|
|
1210
|
+
pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault);
|
|
1211
|
+
} catch {}
|
|
1212
|
+
const error = extractErrorMessageV8(e, streamIn, details, void 0, "");
|
|
1213
|
+
sendRequest(refs, {
|
|
1214
|
+
command: "error",
|
|
1215
|
+
flags,
|
|
1216
|
+
error
|
|
1217
|
+
}, () => {
|
|
1218
|
+
error.detail = details.load(error.detail);
|
|
1219
|
+
callback(failureErrorWithLog("Transform failed", [error], []), null);
|
|
1220
|
+
});
|
|
1221
|
+
}
|
|
1222
|
+
};
|
|
1223
|
+
if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) {
|
|
1224
|
+
let next = start;
|
|
1225
|
+
start = () => fs3.writeFile(input, next);
|
|
1226
|
+
}
|
|
1227
|
+
start(null);
|
|
1228
|
+
};
|
|
1229
|
+
let formatMessages2 = ({ callName, refs, messages, options, callback }) => {
|
|
1230
|
+
if (!options) throw new Error(`Missing second argument in ${callName}() call`);
|
|
1231
|
+
let keys = {};
|
|
1232
|
+
let kind = getFlag(options, keys, "kind", mustBeString);
|
|
1233
|
+
let color = getFlag(options, keys, "color", mustBeBoolean);
|
|
1234
|
+
let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
|
|
1235
|
+
checkForInvalidFlags(options, keys, `in ${callName}() call`);
|
|
1236
|
+
if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`);
|
|
1237
|
+
if (kind !== "error" && kind !== "warning") throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
|
|
1238
|
+
let request = {
|
|
1239
|
+
command: "format-msgs",
|
|
1240
|
+
messages: sanitizeMessages(messages, "messages", null, "", terminalWidth),
|
|
1241
|
+
isWarning: kind === "warning"
|
|
1242
|
+
};
|
|
1243
|
+
if (color !== void 0) request.color = color;
|
|
1244
|
+
if (terminalWidth !== void 0) request.terminalWidth = terminalWidth;
|
|
1245
|
+
sendRequest(refs, request, (error, response) => {
|
|
1246
|
+
if (error) return callback(new Error(error), null);
|
|
1247
|
+
callback(null, response.messages);
|
|
1248
|
+
});
|
|
1249
|
+
};
|
|
1250
|
+
let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => {
|
|
1251
|
+
if (options === void 0) options = {};
|
|
1252
|
+
let keys = {};
|
|
1253
|
+
let color = getFlag(options, keys, "color", mustBeBoolean);
|
|
1254
|
+
let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
|
|
1255
|
+
checkForInvalidFlags(options, keys, `in ${callName}() call`);
|
|
1256
|
+
let request = {
|
|
1257
|
+
command: "analyze-metafile",
|
|
1258
|
+
metafile
|
|
1259
|
+
};
|
|
1260
|
+
if (color !== void 0) request.color = color;
|
|
1261
|
+
if (verbose !== void 0) request.verbose = verbose;
|
|
1262
|
+
sendRequest(refs, request, (error, response) => {
|
|
1263
|
+
if (error) return callback(new Error(error), null);
|
|
1264
|
+
callback(null, response.result);
|
|
1265
|
+
});
|
|
1266
|
+
};
|
|
1267
|
+
return {
|
|
1268
|
+
readFromStdout,
|
|
1269
|
+
afterClose,
|
|
1270
|
+
service: {
|
|
1271
|
+
buildOrContext,
|
|
1272
|
+
transform: transform2,
|
|
1273
|
+
formatMessages: formatMessages2,
|
|
1274
|
+
analyzeMetafile: analyzeMetafile2
|
|
1275
|
+
}
|
|
1276
|
+
};
|
|
1277
|
+
}
|
|
1278
|
+
function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) {
|
|
1279
|
+
const details = createObjectStash();
|
|
1280
|
+
const isContext = callName === "context";
|
|
1281
|
+
const handleError = (e, pluginName) => {
|
|
1282
|
+
const flags = [];
|
|
1283
|
+
try {
|
|
1284
|
+
pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault);
|
|
1285
|
+
} catch {}
|
|
1286
|
+
const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName);
|
|
1287
|
+
sendRequest(refs, {
|
|
1288
|
+
command: "error",
|
|
1289
|
+
flags,
|
|
1290
|
+
error: message
|
|
1291
|
+
}, () => {
|
|
1292
|
+
message.detail = details.load(message.detail);
|
|
1293
|
+
callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
|
|
1294
|
+
});
|
|
1295
|
+
};
|
|
1296
|
+
let plugins;
|
|
1297
|
+
if (typeof options === "object") {
|
|
1298
|
+
const value = options.plugins;
|
|
1299
|
+
if (value !== void 0) {
|
|
1300
|
+
if (!Array.isArray(value)) return handleError(/* @__PURE__ */ new Error(`"plugins" must be an array`), "");
|
|
1301
|
+
plugins = value;
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
if (plugins && plugins.length > 0) {
|
|
1305
|
+
if (streamIn.isSync) return handleError(/* @__PURE__ */ new Error("Cannot use plugins in synchronous API calls"), "");
|
|
1306
|
+
handlePlugins(buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, plugins, details).then((result) => {
|
|
1307
|
+
if (!result.ok) return handleError(result.error, result.pluginName);
|
|
1308
|
+
try {
|
|
1309
|
+
buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
|
|
1310
|
+
} catch (e) {
|
|
1311
|
+
handleError(e, "");
|
|
1312
|
+
}
|
|
1313
|
+
}, (e) => handleError(e, ""));
|
|
1314
|
+
return;
|
|
1315
|
+
}
|
|
1316
|
+
try {
|
|
1317
|
+
buildOrContextContinue(null, (result, done) => done([], []), () => {});
|
|
1318
|
+
} catch (e) {
|
|
1319
|
+
handleError(e, "");
|
|
1320
|
+
}
|
|
1321
|
+
function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
|
|
1322
|
+
const writeDefault = streamIn.hasFS;
|
|
1323
|
+
const { entries, flags, write, stdinContents, stdinResolveDir, absWorkingDir, nodePaths, mangleCache } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault);
|
|
1324
|
+
if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`);
|
|
1325
|
+
const request = {
|
|
1326
|
+
command: "build",
|
|
1327
|
+
key: buildKey,
|
|
1328
|
+
entries,
|
|
1329
|
+
flags,
|
|
1330
|
+
write,
|
|
1331
|
+
stdinContents,
|
|
1332
|
+
stdinResolveDir,
|
|
1333
|
+
absWorkingDir: absWorkingDir || defaultWD2,
|
|
1334
|
+
nodePaths,
|
|
1335
|
+
context: isContext
|
|
1336
|
+
};
|
|
1337
|
+
if (requestPlugins) request.plugins = requestPlugins;
|
|
1338
|
+
if (mangleCache) request.mangleCache = mangleCache;
|
|
1339
|
+
const buildResponseToResult = (response, callback2) => {
|
|
1340
|
+
const result = {
|
|
1341
|
+
errors: replaceDetailsInMessages(response.errors, details),
|
|
1342
|
+
warnings: replaceDetailsInMessages(response.warnings, details),
|
|
1343
|
+
outputFiles: void 0,
|
|
1344
|
+
metafile: void 0,
|
|
1345
|
+
mangleCache: void 0
|
|
1346
|
+
};
|
|
1347
|
+
const originalErrors = result.errors.slice();
|
|
1348
|
+
const originalWarnings = result.warnings.slice();
|
|
1349
|
+
if (response.outputFiles) result.outputFiles = response.outputFiles.map(convertOutputFiles);
|
|
1350
|
+
if (response.metafile && response.metafile.length) result.metafile = parseJSON(response.metafile);
|
|
1351
|
+
if (response.mangleCache) result.mangleCache = response.mangleCache;
|
|
1352
|
+
if (response.writeToStdout !== void 0) console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
|
|
1353
|
+
runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
|
|
1354
|
+
if (originalErrors.length > 0 || onEndErrors.length > 0) return callback2(failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings)), null, onEndErrors, onEndWarnings);
|
|
1355
|
+
callback2(null, result, onEndErrors, onEndWarnings);
|
|
1356
|
+
});
|
|
1357
|
+
};
|
|
1358
|
+
let latestResultPromise;
|
|
1359
|
+
let provideLatestResult;
|
|
1360
|
+
if (isContext) requestCallbacks["on-end"] = (id, request2) => new Promise((resolve) => {
|
|
1361
|
+
buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => {
|
|
1362
|
+
const response = {
|
|
1363
|
+
errors: onEndErrors,
|
|
1364
|
+
warnings: onEndWarnings
|
|
1365
|
+
};
|
|
1366
|
+
if (provideLatestResult) provideLatestResult(err, result);
|
|
1367
|
+
latestResultPromise = void 0;
|
|
1368
|
+
provideLatestResult = void 0;
|
|
1369
|
+
sendResponse(id, response);
|
|
1370
|
+
resolve();
|
|
1371
|
+
});
|
|
1372
|
+
});
|
|
1373
|
+
sendRequest(refs, request, (error, response) => {
|
|
1374
|
+
if (error) return callback(new Error(error), null);
|
|
1375
|
+
if (!isContext) return buildResponseToResult(response, (err, res) => {
|
|
1376
|
+
scheduleOnDisposeCallbacks();
|
|
1377
|
+
return callback(err, res);
|
|
1378
|
+
});
|
|
1379
|
+
if (response.errors.length > 0) return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
|
|
1380
|
+
let didDispose = false;
|
|
1381
|
+
const result = {
|
|
1382
|
+
rebuild: () => {
|
|
1383
|
+
if (!latestResultPromise) latestResultPromise = new Promise((resolve, reject) => {
|
|
1384
|
+
let settlePromise;
|
|
1385
|
+
provideLatestResult = (err, result2) => {
|
|
1386
|
+
if (!settlePromise) settlePromise = () => err ? reject(err) : resolve(result2);
|
|
1387
|
+
};
|
|
1388
|
+
const triggerAnotherBuild = () => {
|
|
1389
|
+
sendRequest(refs, {
|
|
1390
|
+
command: "rebuild",
|
|
1391
|
+
key: buildKey
|
|
1392
|
+
}, (error2, response2) => {
|
|
1393
|
+
if (error2) reject(new Error(error2));
|
|
1394
|
+
else if (settlePromise) settlePromise();
|
|
1395
|
+
else triggerAnotherBuild();
|
|
1396
|
+
});
|
|
1397
|
+
};
|
|
1398
|
+
triggerAnotherBuild();
|
|
1399
|
+
});
|
|
1400
|
+
return latestResultPromise;
|
|
1401
|
+
},
|
|
1402
|
+
watch: (options2 = {}) => new Promise((resolve, reject) => {
|
|
1403
|
+
if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`);
|
|
1404
|
+
const keys = {};
|
|
1405
|
+
const delay = getFlag(options2, keys, "delay", mustBeInteger);
|
|
1406
|
+
checkForInvalidFlags(options2, keys, `in watch() call`);
|
|
1407
|
+
const request2 = {
|
|
1408
|
+
command: "watch",
|
|
1409
|
+
key: buildKey
|
|
1410
|
+
};
|
|
1411
|
+
if (delay) request2.delay = delay;
|
|
1412
|
+
sendRequest(refs, request2, (error2) => {
|
|
1413
|
+
if (error2) reject(new Error(error2));
|
|
1414
|
+
else resolve(void 0);
|
|
1415
|
+
});
|
|
1416
|
+
}),
|
|
1417
|
+
serve: (options2 = {}) => new Promise((resolve, reject) => {
|
|
1418
|
+
if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`);
|
|
1419
|
+
const keys = {};
|
|
1420
|
+
const port = getFlag(options2, keys, "port", mustBeValidPortNumber);
|
|
1421
|
+
const host = getFlag(options2, keys, "host", mustBeString);
|
|
1422
|
+
const servedir = getFlag(options2, keys, "servedir", mustBeString);
|
|
1423
|
+
const keyfile = getFlag(options2, keys, "keyfile", mustBeString);
|
|
1424
|
+
const certfile = getFlag(options2, keys, "certfile", mustBeString);
|
|
1425
|
+
const fallback = getFlag(options2, keys, "fallback", mustBeString);
|
|
1426
|
+
const cors = getFlag(options2, keys, "cors", mustBeObject);
|
|
1427
|
+
const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction);
|
|
1428
|
+
checkForInvalidFlags(options2, keys, `in serve() call`);
|
|
1429
|
+
const request2 = {
|
|
1430
|
+
command: "serve",
|
|
1431
|
+
key: buildKey,
|
|
1432
|
+
onRequest: !!onRequest
|
|
1433
|
+
};
|
|
1434
|
+
if (port !== void 0) request2.port = port;
|
|
1435
|
+
if (host !== void 0) request2.host = host;
|
|
1436
|
+
if (servedir !== void 0) request2.servedir = servedir;
|
|
1437
|
+
if (keyfile !== void 0) request2.keyfile = keyfile;
|
|
1438
|
+
if (certfile !== void 0) request2.certfile = certfile;
|
|
1439
|
+
if (fallback !== void 0) request2.fallback = fallback;
|
|
1440
|
+
if (cors) {
|
|
1441
|
+
const corsKeys = {};
|
|
1442
|
+
const origin = getFlag(cors, corsKeys, "origin", mustBeStringOrArrayOfStrings);
|
|
1443
|
+
checkForInvalidFlags(cors, corsKeys, `on "cors" object`);
|
|
1444
|
+
if (Array.isArray(origin)) request2.corsOrigin = origin;
|
|
1445
|
+
else if (origin !== void 0) request2.corsOrigin = [origin];
|
|
1446
|
+
}
|
|
1447
|
+
sendRequest(refs, request2, (error2, response2) => {
|
|
1448
|
+
if (error2) return reject(new Error(error2));
|
|
1449
|
+
if (onRequest) requestCallbacks["serve-request"] = (id, request3) => {
|
|
1450
|
+
onRequest(request3.args);
|
|
1451
|
+
sendResponse(id, {});
|
|
1452
|
+
};
|
|
1453
|
+
resolve(response2);
|
|
1454
|
+
});
|
|
1455
|
+
}),
|
|
1456
|
+
cancel: () => new Promise((resolve) => {
|
|
1457
|
+
if (didDispose) return resolve();
|
|
1458
|
+
sendRequest(refs, {
|
|
1459
|
+
command: "cancel",
|
|
1460
|
+
key: buildKey
|
|
1461
|
+
}, () => {
|
|
1462
|
+
resolve();
|
|
1463
|
+
});
|
|
1464
|
+
}),
|
|
1465
|
+
dispose: () => new Promise((resolve) => {
|
|
1466
|
+
if (didDispose) return resolve();
|
|
1467
|
+
didDispose = true;
|
|
1468
|
+
sendRequest(refs, {
|
|
1469
|
+
command: "dispose",
|
|
1470
|
+
key: buildKey
|
|
1471
|
+
}, () => {
|
|
1472
|
+
resolve();
|
|
1473
|
+
scheduleOnDisposeCallbacks();
|
|
1474
|
+
refs.unref();
|
|
1475
|
+
});
|
|
1476
|
+
})
|
|
1477
|
+
};
|
|
1478
|
+
refs.ref();
|
|
1479
|
+
callback(null, result);
|
|
1480
|
+
});
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => {
|
|
1484
|
+
let onStartCallbacks = [];
|
|
1485
|
+
let onEndCallbacks = [];
|
|
1486
|
+
let onResolveCallbacks = {};
|
|
1487
|
+
let onLoadCallbacks = {};
|
|
1488
|
+
let onDisposeCallbacks = [];
|
|
1489
|
+
let nextCallbackID = 0;
|
|
1490
|
+
let i = 0;
|
|
1491
|
+
let requestPlugins = [];
|
|
1492
|
+
let isSetupDone = false;
|
|
1493
|
+
plugins = [...plugins];
|
|
1494
|
+
for (let item of plugins) {
|
|
1495
|
+
let keys = {};
|
|
1496
|
+
if (typeof item !== "object") throw new Error(`Plugin at index ${i} must be an object`);
|
|
1497
|
+
const name = getFlag(item, keys, "name", mustBeString);
|
|
1498
|
+
if (typeof name !== "string" || name === "") throw new Error(`Plugin at index ${i} is missing a name`);
|
|
1499
|
+
try {
|
|
1500
|
+
let setup = getFlag(item, keys, "setup", mustBeFunction);
|
|
1501
|
+
if (typeof setup !== "function") throw new Error(`Plugin is missing a setup function`);
|
|
1502
|
+
checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`);
|
|
1503
|
+
let plugin = {
|
|
1504
|
+
name,
|
|
1505
|
+
onStart: false,
|
|
1506
|
+
onEnd: false,
|
|
1507
|
+
onResolve: [],
|
|
1508
|
+
onLoad: []
|
|
1509
|
+
};
|
|
1510
|
+
i++;
|
|
1511
|
+
let resolve = (path3, options = {}) => {
|
|
1512
|
+
if (!isSetupDone) throw new Error("Cannot call \"resolve\" before plugin setup has completed");
|
|
1513
|
+
if (typeof path3 !== "string") throw new Error(`The path to resolve must be a string`);
|
|
1514
|
+
let keys2 = /* @__PURE__ */ Object.create(null);
|
|
1515
|
+
let pluginName = getFlag(options, keys2, "pluginName", mustBeString);
|
|
1516
|
+
let importer = getFlag(options, keys2, "importer", mustBeString);
|
|
1517
|
+
let namespace = getFlag(options, keys2, "namespace", mustBeString);
|
|
1518
|
+
let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString);
|
|
1519
|
+
let kind = getFlag(options, keys2, "kind", mustBeString);
|
|
1520
|
+
let pluginData = getFlag(options, keys2, "pluginData", canBeAnything);
|
|
1521
|
+
let importAttributes = getFlag(options, keys2, "with", mustBeObject);
|
|
1522
|
+
checkForInvalidFlags(options, keys2, "in resolve() call");
|
|
1523
|
+
return new Promise((resolve2, reject) => {
|
|
1524
|
+
const request = {
|
|
1525
|
+
command: "resolve",
|
|
1526
|
+
path: path3,
|
|
1527
|
+
key: buildKey,
|
|
1528
|
+
pluginName: name
|
|
1529
|
+
};
|
|
1530
|
+
if (pluginName != null) request.pluginName = pluginName;
|
|
1531
|
+
if (importer != null) request.importer = importer;
|
|
1532
|
+
if (namespace != null) request.namespace = namespace;
|
|
1533
|
+
if (resolveDir != null) request.resolveDir = resolveDir;
|
|
1534
|
+
if (kind != null) request.kind = kind;
|
|
1535
|
+
else throw new Error(`Must specify "kind" when calling "resolve"`);
|
|
1536
|
+
if (pluginData != null) request.pluginData = details.store(pluginData);
|
|
1537
|
+
if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, "with");
|
|
1538
|
+
sendRequest(refs, request, (error, response) => {
|
|
1539
|
+
if (error !== null) reject(new Error(error));
|
|
1540
|
+
else resolve2({
|
|
1541
|
+
errors: replaceDetailsInMessages(response.errors, details),
|
|
1542
|
+
warnings: replaceDetailsInMessages(response.warnings, details),
|
|
1543
|
+
path: response.path,
|
|
1544
|
+
external: response.external,
|
|
1545
|
+
sideEffects: response.sideEffects,
|
|
1546
|
+
namespace: response.namespace,
|
|
1547
|
+
suffix: response.suffix,
|
|
1548
|
+
pluginData: details.load(response.pluginData)
|
|
1549
|
+
});
|
|
1550
|
+
});
|
|
1551
|
+
});
|
|
1552
|
+
};
|
|
1553
|
+
let promise = setup({
|
|
1554
|
+
initialOptions,
|
|
1555
|
+
resolve,
|
|
1556
|
+
onStart(callback) {
|
|
1557
|
+
let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onStart" callback registered here:`), streamIn, "onStart");
|
|
1558
|
+
onStartCallbacks.push({
|
|
1559
|
+
name,
|
|
1560
|
+
callback,
|
|
1561
|
+
note: registeredNote
|
|
1562
|
+
});
|
|
1563
|
+
plugin.onStart = true;
|
|
1564
|
+
},
|
|
1565
|
+
onEnd(callback) {
|
|
1566
|
+
let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onEnd" callback registered here:`), streamIn, "onEnd");
|
|
1567
|
+
onEndCallbacks.push({
|
|
1568
|
+
name,
|
|
1569
|
+
callback,
|
|
1570
|
+
note: registeredNote
|
|
1571
|
+
});
|
|
1572
|
+
plugin.onEnd = true;
|
|
1573
|
+
},
|
|
1574
|
+
onResolve(options, callback) {
|
|
1575
|
+
let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onResolve" callback registered here:`), streamIn, "onResolve");
|
|
1576
|
+
let keys2 = {};
|
|
1577
|
+
let filter = getFlag(options, keys2, "filter", mustBeRegExp);
|
|
1578
|
+
let namespace = getFlag(options, keys2, "namespace", mustBeString);
|
|
1579
|
+
checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`);
|
|
1580
|
+
if (filter == null) throw new Error(`onResolve() call is missing a filter`);
|
|
1581
|
+
let id = nextCallbackID++;
|
|
1582
|
+
onResolveCallbacks[id] = {
|
|
1583
|
+
name,
|
|
1584
|
+
callback,
|
|
1585
|
+
note: registeredNote
|
|
1586
|
+
};
|
|
1587
|
+
plugin.onResolve.push({
|
|
1588
|
+
id,
|
|
1589
|
+
filter: jsRegExpToGoRegExp(filter),
|
|
1590
|
+
namespace: namespace || ""
|
|
1591
|
+
});
|
|
1592
|
+
},
|
|
1593
|
+
onLoad(options, callback) {
|
|
1594
|
+
let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onLoad" callback registered here:`), streamIn, "onLoad");
|
|
1595
|
+
let keys2 = {};
|
|
1596
|
+
let filter = getFlag(options, keys2, "filter", mustBeRegExp);
|
|
1597
|
+
let namespace = getFlag(options, keys2, "namespace", mustBeString);
|
|
1598
|
+
checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`);
|
|
1599
|
+
if (filter == null) throw new Error(`onLoad() call is missing a filter`);
|
|
1600
|
+
let id = nextCallbackID++;
|
|
1601
|
+
onLoadCallbacks[id] = {
|
|
1602
|
+
name,
|
|
1603
|
+
callback,
|
|
1604
|
+
note: registeredNote
|
|
1605
|
+
};
|
|
1606
|
+
plugin.onLoad.push({
|
|
1607
|
+
id,
|
|
1608
|
+
filter: jsRegExpToGoRegExp(filter),
|
|
1609
|
+
namespace: namespace || ""
|
|
1610
|
+
});
|
|
1611
|
+
},
|
|
1612
|
+
onDispose(callback) {
|
|
1613
|
+
onDisposeCallbacks.push(callback);
|
|
1614
|
+
},
|
|
1615
|
+
esbuild: streamIn.esbuild
|
|
1616
|
+
});
|
|
1617
|
+
if (promise) await promise;
|
|
1618
|
+
requestPlugins.push(plugin);
|
|
1619
|
+
} catch (e) {
|
|
1620
|
+
return {
|
|
1621
|
+
ok: false,
|
|
1622
|
+
error: e,
|
|
1623
|
+
pluginName: name
|
|
1624
|
+
};
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
requestCallbacks["on-start"] = async (id, request) => {
|
|
1628
|
+
details.clear();
|
|
1629
|
+
let response = {
|
|
1630
|
+
errors: [],
|
|
1631
|
+
warnings: []
|
|
1632
|
+
};
|
|
1633
|
+
await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => {
|
|
1634
|
+
try {
|
|
1635
|
+
let result = await callback();
|
|
1636
|
+
if (result != null) {
|
|
1637
|
+
if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`);
|
|
1638
|
+
let keys = {};
|
|
1639
|
+
let errors = getFlag(result, keys, "errors", mustBeArray);
|
|
1640
|
+
let warnings = getFlag(result, keys, "warnings", mustBeArray);
|
|
1641
|
+
checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`);
|
|
1642
|
+
if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0));
|
|
1643
|
+
if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0));
|
|
1644
|
+
}
|
|
1645
|
+
} catch (e) {
|
|
1646
|
+
response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name));
|
|
1647
|
+
}
|
|
1648
|
+
}));
|
|
1649
|
+
sendResponse(id, response);
|
|
1650
|
+
};
|
|
1651
|
+
requestCallbacks["on-resolve"] = async (id, request) => {
|
|
1652
|
+
let response = {}, name = "", callback, note;
|
|
1653
|
+
for (let id2 of request.ids) try {
|
|
1654
|
+
({name, callback, note} = onResolveCallbacks[id2]);
|
|
1655
|
+
let result = await callback({
|
|
1656
|
+
path: request.path,
|
|
1657
|
+
importer: request.importer,
|
|
1658
|
+
namespace: request.namespace,
|
|
1659
|
+
resolveDir: request.resolveDir,
|
|
1660
|
+
kind: request.kind,
|
|
1661
|
+
pluginData: details.load(request.pluginData),
|
|
1662
|
+
with: request.with
|
|
1663
|
+
});
|
|
1664
|
+
if (result != null) {
|
|
1665
|
+
if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`);
|
|
1666
|
+
let keys = {};
|
|
1667
|
+
let pluginName = getFlag(result, keys, "pluginName", mustBeString);
|
|
1668
|
+
let path3 = getFlag(result, keys, "path", mustBeString);
|
|
1669
|
+
let namespace = getFlag(result, keys, "namespace", mustBeString);
|
|
1670
|
+
let suffix = getFlag(result, keys, "suffix", mustBeString);
|
|
1671
|
+
let external = getFlag(result, keys, "external", mustBeBoolean);
|
|
1672
|
+
let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
|
|
1673
|
+
let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
|
|
1674
|
+
let errors = getFlag(result, keys, "errors", mustBeArray);
|
|
1675
|
+
let warnings = getFlag(result, keys, "warnings", mustBeArray);
|
|
1676
|
+
let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
|
|
1677
|
+
let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
|
|
1678
|
+
checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`);
|
|
1679
|
+
response.id = id2;
|
|
1680
|
+
if (pluginName != null) response.pluginName = pluginName;
|
|
1681
|
+
if (path3 != null) response.path = path3;
|
|
1682
|
+
if (namespace != null) response.namespace = namespace;
|
|
1683
|
+
if (suffix != null) response.suffix = suffix;
|
|
1684
|
+
if (external != null) response.external = external;
|
|
1685
|
+
if (sideEffects != null) response.sideEffects = sideEffects;
|
|
1686
|
+
if (pluginData != null) response.pluginData = details.store(pluginData);
|
|
1687
|
+
if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
|
|
1688
|
+
if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
|
|
1689
|
+
if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
|
|
1690
|
+
if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
|
|
1691
|
+
break;
|
|
1692
|
+
}
|
|
1693
|
+
} catch (e) {
|
|
1694
|
+
response = {
|
|
1695
|
+
id: id2,
|
|
1696
|
+
errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)]
|
|
1697
|
+
};
|
|
1698
|
+
break;
|
|
1699
|
+
}
|
|
1700
|
+
sendResponse(id, response);
|
|
1701
|
+
};
|
|
1702
|
+
requestCallbacks["on-load"] = async (id, request) => {
|
|
1703
|
+
let response = {}, name = "", callback, note;
|
|
1704
|
+
for (let id2 of request.ids) try {
|
|
1705
|
+
({name, callback, note} = onLoadCallbacks[id2]);
|
|
1706
|
+
let result = await callback({
|
|
1707
|
+
path: request.path,
|
|
1708
|
+
namespace: request.namespace,
|
|
1709
|
+
suffix: request.suffix,
|
|
1710
|
+
pluginData: details.load(request.pluginData),
|
|
1711
|
+
with: request.with
|
|
1712
|
+
});
|
|
1713
|
+
if (result != null) {
|
|
1714
|
+
if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`);
|
|
1715
|
+
let keys = {};
|
|
1716
|
+
let pluginName = getFlag(result, keys, "pluginName", mustBeString);
|
|
1717
|
+
let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
|
|
1718
|
+
let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
|
|
1719
|
+
let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
|
|
1720
|
+
let loader = getFlag(result, keys, "loader", mustBeString);
|
|
1721
|
+
let errors = getFlag(result, keys, "errors", mustBeArray);
|
|
1722
|
+
let warnings = getFlag(result, keys, "warnings", mustBeArray);
|
|
1723
|
+
let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
|
|
1724
|
+
let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
|
|
1725
|
+
checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`);
|
|
1726
|
+
response.id = id2;
|
|
1727
|
+
if (pluginName != null) response.pluginName = pluginName;
|
|
1728
|
+
if (contents instanceof Uint8Array) response.contents = contents;
|
|
1729
|
+
else if (contents != null) response.contents = encodeUTF8(contents);
|
|
1730
|
+
if (resolveDir != null) response.resolveDir = resolveDir;
|
|
1731
|
+
if (pluginData != null) response.pluginData = details.store(pluginData);
|
|
1732
|
+
if (loader != null) response.loader = loader;
|
|
1733
|
+
if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
|
|
1734
|
+
if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
|
|
1735
|
+
if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
|
|
1736
|
+
if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
|
|
1737
|
+
break;
|
|
1738
|
+
}
|
|
1739
|
+
} catch (e) {
|
|
1740
|
+
response = {
|
|
1741
|
+
id: id2,
|
|
1742
|
+
errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)]
|
|
1743
|
+
};
|
|
1744
|
+
break;
|
|
1745
|
+
}
|
|
1746
|
+
sendResponse(id, response);
|
|
1747
|
+
};
|
|
1748
|
+
let runOnEndCallbacks = (result, done) => done([], []);
|
|
1749
|
+
if (onEndCallbacks.length > 0) runOnEndCallbacks = (result, done) => {
|
|
1750
|
+
(async () => {
|
|
1751
|
+
const onEndErrors = [];
|
|
1752
|
+
const onEndWarnings = [];
|
|
1753
|
+
for (const { name, callback, note } of onEndCallbacks) {
|
|
1754
|
+
let newErrors;
|
|
1755
|
+
let newWarnings;
|
|
1756
|
+
try {
|
|
1757
|
+
const value = await callback(result);
|
|
1758
|
+
if (value != null) {
|
|
1759
|
+
if (typeof value !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
|
|
1760
|
+
let keys = {};
|
|
1761
|
+
let errors = getFlag(value, keys, "errors", mustBeArray);
|
|
1762
|
+
let warnings = getFlag(value, keys, "warnings", mustBeArray);
|
|
1763
|
+
checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
|
|
1764
|
+
if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name, void 0);
|
|
1765
|
+
if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
|
|
1766
|
+
}
|
|
1767
|
+
} catch (e) {
|
|
1768
|
+
newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
|
|
1769
|
+
}
|
|
1770
|
+
if (newErrors) {
|
|
1771
|
+
onEndErrors.push(...newErrors);
|
|
1772
|
+
try {
|
|
1773
|
+
result.errors.push(...newErrors);
|
|
1774
|
+
} catch {}
|
|
1775
|
+
}
|
|
1776
|
+
if (newWarnings) {
|
|
1777
|
+
onEndWarnings.push(...newWarnings);
|
|
1778
|
+
try {
|
|
1779
|
+
result.warnings.push(...newWarnings);
|
|
1780
|
+
} catch {}
|
|
1781
|
+
}
|
|
1782
|
+
}
|
|
1783
|
+
done(onEndErrors, onEndWarnings);
|
|
1784
|
+
})();
|
|
1785
|
+
};
|
|
1786
|
+
let scheduleOnDisposeCallbacks = () => {
|
|
1787
|
+
for (const cb of onDisposeCallbacks) setTimeout(() => cb(), 0);
|
|
1788
|
+
};
|
|
1789
|
+
isSetupDone = true;
|
|
1790
|
+
return {
|
|
1791
|
+
ok: true,
|
|
1792
|
+
requestPlugins,
|
|
1793
|
+
runOnEndCallbacks,
|
|
1794
|
+
scheduleOnDisposeCallbacks
|
|
1795
|
+
};
|
|
1796
|
+
};
|
|
1797
|
+
function createObjectStash() {
|
|
1798
|
+
const map = /* @__PURE__ */ new Map();
|
|
1799
|
+
let nextID = 0;
|
|
1800
|
+
return {
|
|
1801
|
+
clear() {
|
|
1802
|
+
map.clear();
|
|
1803
|
+
},
|
|
1804
|
+
load(id) {
|
|
1805
|
+
return map.get(id);
|
|
1806
|
+
},
|
|
1807
|
+
store(value) {
|
|
1808
|
+
if (value === void 0) return -1;
|
|
1809
|
+
const id = nextID++;
|
|
1810
|
+
map.set(id, value);
|
|
1811
|
+
return id;
|
|
1812
|
+
}
|
|
1813
|
+
};
|
|
1814
|
+
}
|
|
1815
|
+
function extractCallerV8(e, streamIn, ident) {
|
|
1816
|
+
let note;
|
|
1817
|
+
let tried = false;
|
|
1818
|
+
return () => {
|
|
1819
|
+
if (tried) return note;
|
|
1820
|
+
tried = true;
|
|
1821
|
+
try {
|
|
1822
|
+
let lines = (e.stack + "").split("\n");
|
|
1823
|
+
lines.splice(1, 1);
|
|
1824
|
+
let location = parseStackLinesV8(streamIn, lines, ident);
|
|
1825
|
+
if (location) {
|
|
1826
|
+
note = {
|
|
1827
|
+
text: e.message,
|
|
1828
|
+
location
|
|
1829
|
+
};
|
|
1830
|
+
return note;
|
|
1831
|
+
}
|
|
1832
|
+
} catch {}
|
|
1833
|
+
};
|
|
1834
|
+
}
|
|
1835
|
+
function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
|
|
1836
|
+
let text = "Internal error";
|
|
1837
|
+
let location = null;
|
|
1838
|
+
try {
|
|
1839
|
+
text = (e && e.message || e) + "";
|
|
1840
|
+
} catch {}
|
|
1841
|
+
try {
|
|
1842
|
+
location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), "");
|
|
1843
|
+
} catch {}
|
|
1844
|
+
return {
|
|
1845
|
+
id: "",
|
|
1846
|
+
pluginName,
|
|
1847
|
+
text,
|
|
1848
|
+
location,
|
|
1849
|
+
notes: note ? [note] : [],
|
|
1850
|
+
detail: stash ? stash.store(e) : -1
|
|
1851
|
+
};
|
|
1852
|
+
}
|
|
1853
|
+
function parseStackLinesV8(streamIn, lines, ident) {
|
|
1854
|
+
let at = " at ";
|
|
1855
|
+
if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) for (let i = 1; i < lines.length; i++) {
|
|
1856
|
+
let line = lines[i];
|
|
1857
|
+
if (!line.startsWith(at)) continue;
|
|
1858
|
+
line = line.slice(7);
|
|
1859
|
+
while (true) {
|
|
1860
|
+
let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
|
|
1861
|
+
if (match) {
|
|
1862
|
+
line = match[1];
|
|
1863
|
+
continue;
|
|
1864
|
+
}
|
|
1865
|
+
match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
|
|
1866
|
+
if (match) {
|
|
1867
|
+
line = match[1];
|
|
1868
|
+
continue;
|
|
1869
|
+
}
|
|
1870
|
+
match = /^(\S+):(\d+):(\d+)$/.exec(line);
|
|
1871
|
+
if (match) {
|
|
1872
|
+
let contents;
|
|
1873
|
+
try {
|
|
1874
|
+
contents = streamIn.readFileSync(match[1], "utf8");
|
|
1875
|
+
} catch {
|
|
1876
|
+
break;
|
|
1877
|
+
}
|
|
1878
|
+
let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
|
|
1879
|
+
let column = +match[3] - 1;
|
|
1880
|
+
let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
|
|
1881
|
+
return {
|
|
1882
|
+
file: match[1],
|
|
1883
|
+
namespace: "file",
|
|
1884
|
+
line: +match[2],
|
|
1885
|
+
column: encodeUTF8(lineText.slice(0, column)).length,
|
|
1886
|
+
length: encodeUTF8(lineText.slice(column, column + length)).length,
|
|
1887
|
+
lineText: lineText + "\n" + lines.slice(1).join("\n"),
|
|
1888
|
+
suggestion: ""
|
|
1889
|
+
};
|
|
1890
|
+
}
|
|
1891
|
+
break;
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
return null;
|
|
1895
|
+
}
|
|
1896
|
+
function failureErrorWithLog(text, errors, warnings) {
|
|
1897
|
+
let limit = 5;
|
|
1898
|
+
text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, 6).map((e, i) => {
|
|
1899
|
+
if (i === limit) return "\n...";
|
|
1900
|
+
if (!e.location) return `
|
|
1901
|
+
error: ${e.text}`;
|
|
1902
|
+
let { file, line, column } = e.location;
|
|
1903
|
+
return `
|
|
1904
|
+
${file}:${line}:${column}: ERROR: ${e.pluginName ? `[plugin: ${e.pluginName}] ` : ""}${e.text}`;
|
|
1905
|
+
}).join("");
|
|
1906
|
+
let error = new Error(text);
|
|
1907
|
+
for (const [key, value] of [["errors", errors], ["warnings", warnings]]) Object.defineProperty(error, key, {
|
|
1908
|
+
configurable: true,
|
|
1909
|
+
enumerable: true,
|
|
1910
|
+
get: () => value,
|
|
1911
|
+
set: (value2) => Object.defineProperty(error, key, {
|
|
1912
|
+
configurable: true,
|
|
1913
|
+
enumerable: true,
|
|
1914
|
+
value: value2
|
|
1915
|
+
})
|
|
1916
|
+
});
|
|
1917
|
+
return error;
|
|
1918
|
+
}
|
|
1919
|
+
function replaceDetailsInMessages(messages, stash) {
|
|
1920
|
+
for (const message of messages) message.detail = stash.load(message.detail);
|
|
1921
|
+
return messages;
|
|
1922
|
+
}
|
|
1923
|
+
function sanitizeLocation(location, where, terminalWidth) {
|
|
1924
|
+
if (location == null) return null;
|
|
1925
|
+
let keys = {};
|
|
1926
|
+
let file = getFlag(location, keys, "file", mustBeString);
|
|
1927
|
+
let namespace = getFlag(location, keys, "namespace", mustBeString);
|
|
1928
|
+
let line = getFlag(location, keys, "line", mustBeInteger);
|
|
1929
|
+
let column = getFlag(location, keys, "column", mustBeInteger);
|
|
1930
|
+
let length = getFlag(location, keys, "length", mustBeInteger);
|
|
1931
|
+
let lineText = getFlag(location, keys, "lineText", mustBeString);
|
|
1932
|
+
let suggestion = getFlag(location, keys, "suggestion", mustBeString);
|
|
1933
|
+
checkForInvalidFlags(location, keys, where);
|
|
1934
|
+
if (lineText) {
|
|
1935
|
+
const relevantASCII = lineText.slice(0, (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80));
|
|
1936
|
+
if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) lineText = relevantASCII;
|
|
1937
|
+
}
|
|
1938
|
+
return {
|
|
1939
|
+
file: file || "",
|
|
1940
|
+
namespace: namespace || "",
|
|
1941
|
+
line: line || 0,
|
|
1942
|
+
column: column || 0,
|
|
1943
|
+
length: length || 0,
|
|
1944
|
+
lineText: lineText || "",
|
|
1945
|
+
suggestion: suggestion || ""
|
|
1946
|
+
};
|
|
1947
|
+
}
|
|
1948
|
+
function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) {
|
|
1949
|
+
let messagesClone = [];
|
|
1950
|
+
let index = 0;
|
|
1951
|
+
for (const message of messages) {
|
|
1952
|
+
let keys = {};
|
|
1953
|
+
let id = getFlag(message, keys, "id", mustBeString);
|
|
1954
|
+
let pluginName = getFlag(message, keys, "pluginName", mustBeString);
|
|
1955
|
+
let text = getFlag(message, keys, "text", mustBeString);
|
|
1956
|
+
let location = getFlag(message, keys, "location", mustBeObjectOrNull);
|
|
1957
|
+
let notes = getFlag(message, keys, "notes", mustBeArray);
|
|
1958
|
+
let detail = getFlag(message, keys, "detail", canBeAnything);
|
|
1959
|
+
let where = `in element ${index} of "${property}"`;
|
|
1960
|
+
checkForInvalidFlags(message, keys, where);
|
|
1961
|
+
let notesClone = [];
|
|
1962
|
+
if (notes) for (const note of notes) {
|
|
1963
|
+
let noteKeys = {};
|
|
1964
|
+
let noteText = getFlag(note, noteKeys, "text", mustBeString);
|
|
1965
|
+
let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
|
|
1966
|
+
checkForInvalidFlags(note, noteKeys, where);
|
|
1967
|
+
notesClone.push({
|
|
1968
|
+
text: noteText || "",
|
|
1969
|
+
location: sanitizeLocation(noteLocation, where, terminalWidth)
|
|
1970
|
+
});
|
|
1971
|
+
}
|
|
1972
|
+
messagesClone.push({
|
|
1973
|
+
id: id || "",
|
|
1974
|
+
pluginName: pluginName || fallbackPluginName,
|
|
1975
|
+
text: text || "",
|
|
1976
|
+
location: sanitizeLocation(location, where, terminalWidth),
|
|
1977
|
+
notes: notesClone,
|
|
1978
|
+
detail: stash ? stash.store(detail) : -1
|
|
1979
|
+
});
|
|
1980
|
+
index++;
|
|
1981
|
+
}
|
|
1982
|
+
return messagesClone;
|
|
1983
|
+
}
|
|
1984
|
+
function sanitizeStringArray(values, property) {
|
|
1985
|
+
const result = [];
|
|
1986
|
+
for (const value of values) {
|
|
1987
|
+
if (typeof value !== "string") throw new Error(`${quote(property)} must be an array of strings`);
|
|
1988
|
+
result.push(value);
|
|
1989
|
+
}
|
|
1990
|
+
return result;
|
|
1991
|
+
}
|
|
1992
|
+
function sanitizeStringMap(map, property) {
|
|
1993
|
+
const result = /* @__PURE__ */ Object.create(null);
|
|
1994
|
+
for (const key in map) {
|
|
1995
|
+
const value = map[key];
|
|
1996
|
+
if (typeof value !== "string") throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`);
|
|
1997
|
+
result[key] = value;
|
|
1998
|
+
}
|
|
1999
|
+
return result;
|
|
2000
|
+
}
|
|
2001
|
+
function convertOutputFiles({ path: path3, contents, hash }) {
|
|
2002
|
+
let text = null;
|
|
2003
|
+
return {
|
|
2004
|
+
path: path3,
|
|
2005
|
+
contents,
|
|
2006
|
+
hash,
|
|
2007
|
+
get text() {
|
|
2008
|
+
const binary = this.contents;
|
|
2009
|
+
if (text === null || binary !== contents) {
|
|
2010
|
+
contents = binary;
|
|
2011
|
+
text = decodeUTF8(binary);
|
|
2012
|
+
}
|
|
2013
|
+
return text;
|
|
2014
|
+
}
|
|
2015
|
+
};
|
|
2016
|
+
}
|
|
2017
|
+
function jsRegExpToGoRegExp(regexp) {
|
|
2018
|
+
let result = regexp.source;
|
|
2019
|
+
if (regexp.flags) result = `(?${regexp.flags})${result}`;
|
|
2020
|
+
return result;
|
|
2021
|
+
}
|
|
2022
|
+
function parseJSON(bytes) {
|
|
2023
|
+
let text;
|
|
2024
|
+
try {
|
|
2025
|
+
text = decodeUTF8(bytes);
|
|
2026
|
+
} catch {
|
|
2027
|
+
return JSON_parse(bytes);
|
|
2028
|
+
}
|
|
2029
|
+
return JSON.parse(text);
|
|
2030
|
+
}
|
|
2031
|
+
var fs = __require("fs");
|
|
2032
|
+
var os = __require("os");
|
|
2033
|
+
var path = __require("path");
|
|
2034
|
+
var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
|
|
2035
|
+
var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
|
|
2036
|
+
var packageDarwin_arm64 = "@esbuild/darwin-arm64";
|
|
2037
|
+
var packageDarwin_x64 = "@esbuild/darwin-x64";
|
|
2038
|
+
var knownWindowsPackages = {
|
|
2039
|
+
"win32 arm64 LE": "@esbuild/win32-arm64",
|
|
2040
|
+
"win32 ia32 LE": "@esbuild/win32-ia32",
|
|
2041
|
+
"win32 x64 LE": "@esbuild/win32-x64"
|
|
2042
|
+
};
|
|
2043
|
+
var knownUnixlikePackages = {
|
|
2044
|
+
"aix ppc64 BE": "@esbuild/aix-ppc64",
|
|
2045
|
+
"android arm64 LE": "@esbuild/android-arm64",
|
|
2046
|
+
"darwin arm64 LE": "@esbuild/darwin-arm64",
|
|
2047
|
+
"darwin x64 LE": "@esbuild/darwin-x64",
|
|
2048
|
+
"freebsd arm64 LE": "@esbuild/freebsd-arm64",
|
|
2049
|
+
"freebsd x64 LE": "@esbuild/freebsd-x64",
|
|
2050
|
+
"linux arm LE": "@esbuild/linux-arm",
|
|
2051
|
+
"linux arm64 LE": "@esbuild/linux-arm64",
|
|
2052
|
+
"linux ia32 LE": "@esbuild/linux-ia32",
|
|
2053
|
+
"linux mips64el LE": "@esbuild/linux-mips64el",
|
|
2054
|
+
"linux ppc64 LE": "@esbuild/linux-ppc64",
|
|
2055
|
+
"linux riscv64 LE": "@esbuild/linux-riscv64",
|
|
2056
|
+
"linux s390x BE": "@esbuild/linux-s390x",
|
|
2057
|
+
"linux x64 LE": "@esbuild/linux-x64",
|
|
2058
|
+
"linux loong64 LE": "@esbuild/linux-loong64",
|
|
2059
|
+
"netbsd arm64 LE": "@esbuild/netbsd-arm64",
|
|
2060
|
+
"netbsd x64 LE": "@esbuild/netbsd-x64",
|
|
2061
|
+
"openbsd arm64 LE": "@esbuild/openbsd-arm64",
|
|
2062
|
+
"openbsd x64 LE": "@esbuild/openbsd-x64",
|
|
2063
|
+
"sunos x64 LE": "@esbuild/sunos-x64"
|
|
2064
|
+
};
|
|
2065
|
+
var knownWebAssemblyFallbackPackages = {
|
|
2066
|
+
"android arm LE": "@esbuild/android-arm",
|
|
2067
|
+
"android x64 LE": "@esbuild/android-x64",
|
|
2068
|
+
"openharmony arm64 LE": "@esbuild/openharmony-arm64"
|
|
2069
|
+
};
|
|
2070
|
+
function pkgAndSubpathForCurrentPlatform() {
|
|
2071
|
+
let pkg;
|
|
2072
|
+
let subpath;
|
|
2073
|
+
let isWASM = false;
|
|
2074
|
+
let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
|
|
2075
|
+
if (platformKey in knownWindowsPackages) {
|
|
2076
|
+
pkg = knownWindowsPackages[platformKey];
|
|
2077
|
+
subpath = "esbuild.exe";
|
|
2078
|
+
} else if (platformKey in knownUnixlikePackages) {
|
|
2079
|
+
pkg = knownUnixlikePackages[platformKey];
|
|
2080
|
+
subpath = "bin/esbuild";
|
|
2081
|
+
} else if (platformKey in knownWebAssemblyFallbackPackages) {
|
|
2082
|
+
pkg = knownWebAssemblyFallbackPackages[platformKey];
|
|
2083
|
+
subpath = "bin/esbuild";
|
|
2084
|
+
isWASM = true;
|
|
2085
|
+
} else throw new Error(`Unsupported platform: ${platformKey}`);
|
|
2086
|
+
return {
|
|
2087
|
+
pkg,
|
|
2088
|
+
subpath,
|
|
2089
|
+
isWASM
|
|
2090
|
+
};
|
|
2091
|
+
}
|
|
2092
|
+
function pkgForSomeOtherPlatform() {
|
|
2093
|
+
const libMainJS = __require.resolve("esbuild");
|
|
2094
|
+
const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS)));
|
|
2095
|
+
if (path.basename(nodeModulesDirectory) === "node_modules") {
|
|
2096
|
+
for (const unixKey in knownUnixlikePackages) try {
|
|
2097
|
+
const pkg = knownUnixlikePackages[unixKey];
|
|
2098
|
+
if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
|
|
2099
|
+
} catch {}
|
|
2100
|
+
for (const windowsKey in knownWindowsPackages) try {
|
|
2101
|
+
const pkg = knownWindowsPackages[windowsKey];
|
|
2102
|
+
if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
|
|
2103
|
+
} catch {}
|
|
2104
|
+
}
|
|
2105
|
+
return null;
|
|
2106
|
+
}
|
|
2107
|
+
function downloadedBinPath(pkg, subpath) {
|
|
2108
|
+
const esbuildLibDir = path.dirname(__require.resolve("esbuild"));
|
|
2109
|
+
return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
|
|
2110
|
+
}
|
|
2111
|
+
function generateBinPath() {
|
|
2112
|
+
if (isValidBinaryPath(ESBUILD_BINARY_PATH)) if (!fs.existsSync(ESBUILD_BINARY_PATH)) console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
|
|
2113
|
+
else return {
|
|
2114
|
+
binPath: ESBUILD_BINARY_PATH,
|
|
2115
|
+
isWASM: false
|
|
2116
|
+
};
|
|
2117
|
+
const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
|
|
2118
|
+
let binPath;
|
|
2119
|
+
try {
|
|
2120
|
+
binPath = __require.resolve(`${pkg}/${subpath}`);
|
|
2121
|
+
} catch (e) {
|
|
2122
|
+
binPath = downloadedBinPath(pkg, subpath);
|
|
2123
|
+
if (!fs.existsSync(binPath)) {
|
|
2124
|
+
try {
|
|
2125
|
+
__require.resolve(pkg);
|
|
2126
|
+
} catch {
|
|
2127
|
+
const otherPkg = pkgForSomeOtherPlatform();
|
|
2128
|
+
if (otherPkg) {
|
|
2129
|
+
let suggestions = `
|
|
2130
|
+
Specifically the "${otherPkg}" package is present but this platform
|
|
2131
|
+
needs the "${pkg}" package instead. People often get into this
|
|
2132
|
+
situation by installing esbuild on Windows or macOS and copying "node_modules"
|
|
2133
|
+
into a Docker image that runs Linux, or by copying "node_modules" between
|
|
2134
|
+
Windows and WSL environments.
|
|
2135
|
+
|
|
2136
|
+
If you are installing with npm, you can try not copying the "node_modules"
|
|
2137
|
+
directory when you copy the files over, and running "npm ci" or "npm install"
|
|
2138
|
+
on the destination platform after the copy. Or you could consider using yarn
|
|
2139
|
+
instead of npm which has built-in support for installing a package on multiple
|
|
2140
|
+
platforms simultaneously.
|
|
2141
|
+
|
|
2142
|
+
If you are installing with yarn, you can try listing both this platform and the
|
|
2143
|
+
other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
|
|
2144
|
+
feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
|
|
2145
|
+
Keep in mind that this means multiple copies of esbuild will be present.
|
|
2146
|
+
`;
|
|
2147
|
+
if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) suggestions = `
|
|
2148
|
+
Specifically the "${otherPkg}" package is present but this platform
|
|
2149
|
+
needs the "${pkg}" package instead. People often get into this
|
|
2150
|
+
situation by installing esbuild with npm running inside of Rosetta 2 and then
|
|
2151
|
+
trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
|
|
2152
|
+
2 is Apple's on-the-fly x86_64-to-arm64 translation service).
|
|
2153
|
+
|
|
2154
|
+
If you are installing with npm, you can try ensuring that both npm and node are
|
|
2155
|
+
not running under Rosetta 2 and then reinstalling esbuild. This likely involves
|
|
2156
|
+
changing how you installed npm and/or node. For example, installing node with
|
|
2157
|
+
the universal installer here should work: https://nodejs.org/en/download/. Or
|
|
2158
|
+
you could consider using yarn instead of npm which has built-in support for
|
|
2159
|
+
installing a package on multiple platforms simultaneously.
|
|
2160
|
+
|
|
2161
|
+
If you are installing with yarn, you can try listing both "arm64" and "x64"
|
|
2162
|
+
in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
|
|
2163
|
+
https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
|
|
2164
|
+
Keep in mind that this means multiple copies of esbuild will be present.
|
|
2165
|
+
`;
|
|
2166
|
+
throw new Error(`
|
|
2167
|
+
You installed esbuild for another platform than the one you're currently using.
|
|
2168
|
+
This won't work because esbuild is written with native code and needs to
|
|
2169
|
+
install a platform-specific binary executable.
|
|
2170
|
+
${suggestions}
|
|
2171
|
+
Another alternative is to use the "esbuild-wasm" package instead, which works
|
|
2172
|
+
the same way on all platforms. But it comes with a heavy performance cost and
|
|
2173
|
+
can sometimes be 10x slower than the "esbuild" package, so you may also not
|
|
2174
|
+
want to do that.
|
|
2175
|
+
`);
|
|
2176
|
+
}
|
|
2177
|
+
throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
|
|
2178
|
+
|
|
2179
|
+
If you are installing esbuild with npm, make sure that you don't specify the
|
|
2180
|
+
"--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
|
|
2181
|
+
of "package.json" is used by esbuild to install the correct binary executable
|
|
2182
|
+
for your current platform.`);
|
|
2183
|
+
}
|
|
2184
|
+
throw e;
|
|
2185
|
+
}
|
|
2186
|
+
}
|
|
2187
|
+
if (/\.zip\//.test(binPath)) {
|
|
2188
|
+
let pnpapi;
|
|
2189
|
+
try {
|
|
2190
|
+
pnpapi = __require("pnpapi");
|
|
2191
|
+
} catch (e) {}
|
|
2192
|
+
if (pnpapi) {
|
|
2193
|
+
const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
|
|
2194
|
+
const binTargetPath = path.join(root, "node_modules", ".cache", "esbuild", `pnpapi-${pkg.replace("/", "-")}-0.27.7-${path.basename(subpath)}`);
|
|
2195
|
+
if (!fs.existsSync(binTargetPath)) {
|
|
2196
|
+
fs.mkdirSync(path.dirname(binTargetPath), { recursive: true });
|
|
2197
|
+
fs.copyFileSync(binPath, binTargetPath);
|
|
2198
|
+
fs.chmodSync(binTargetPath, 493);
|
|
2199
|
+
}
|
|
2200
|
+
return {
|
|
2201
|
+
binPath: binTargetPath,
|
|
2202
|
+
isWASM
|
|
2203
|
+
};
|
|
2204
|
+
}
|
|
2205
|
+
}
|
|
2206
|
+
return {
|
|
2207
|
+
binPath,
|
|
2208
|
+
isWASM
|
|
2209
|
+
};
|
|
2210
|
+
}
|
|
2211
|
+
var child_process = __require("child_process");
|
|
2212
|
+
var crypto = __require("crypto");
|
|
2213
|
+
var path2 = __require("path");
|
|
2214
|
+
var fs2 = __require("fs");
|
|
2215
|
+
var os2 = __require("os");
|
|
2216
|
+
var tty = __require("tty");
|
|
2217
|
+
var worker_threads;
|
|
2218
|
+
if (process.env.ESBUILD_WORKER_THREADS !== "0") {
|
|
2219
|
+
try {
|
|
2220
|
+
worker_threads = __require("worker_threads");
|
|
2221
|
+
} catch {}
|
|
2222
|
+
let [major, minor] = process.versions.node.split(".");
|
|
2223
|
+
if (+major < 12 || +major === 12 && +minor < 17 || +major === 13 && +minor < 13) worker_threads = void 0;
|
|
2224
|
+
}
|
|
2225
|
+
var _a;
|
|
2226
|
+
var isInternalWorkerThread = ((_a = worker_threads == null ? void 0 : worker_threads.workerData) == null ? void 0 : _a.esbuildVersion) === "0.27.7";
|
|
2227
|
+
var esbuildCommandAndArgs = () => {
|
|
2228
|
+
if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) throw new Error(`The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle.
|
|
2229
|
+
|
|
2230
|
+
More information: The file containing the code for esbuild's JavaScript API (${__filename}) does not appear to be inside the esbuild package on the file system, which usually means that the esbuild package was bundled into another file. This is problematic because the API needs to run a binary executable inside the esbuild package which is located using a relative path from the API code to the executable. If the esbuild package is bundled, the relative path will be incorrect and the executable won't be found.`);
|
|
2231
|
+
{
|
|
2232
|
+
const { binPath, isWASM } = generateBinPath();
|
|
2233
|
+
if (isWASM) return ["node", [binPath]];
|
|
2234
|
+
else return [binPath, []];
|
|
2235
|
+
}
|
|
2236
|
+
};
|
|
2237
|
+
var isTTY = () => tty.isatty(2);
|
|
2238
|
+
var fsSync = {
|
|
2239
|
+
readFile(tempFile, callback) {
|
|
2240
|
+
try {
|
|
2241
|
+
let contents = fs2.readFileSync(tempFile, "utf8");
|
|
2242
|
+
try {
|
|
2243
|
+
fs2.unlinkSync(tempFile);
|
|
2244
|
+
} catch {}
|
|
2245
|
+
callback(null, contents);
|
|
2246
|
+
} catch (err) {
|
|
2247
|
+
callback(err, null);
|
|
2248
|
+
}
|
|
2249
|
+
},
|
|
2250
|
+
writeFile(contents, callback) {
|
|
2251
|
+
try {
|
|
2252
|
+
let tempFile = randomFileName();
|
|
2253
|
+
fs2.writeFileSync(tempFile, contents);
|
|
2254
|
+
callback(tempFile);
|
|
2255
|
+
} catch {
|
|
2256
|
+
callback(null);
|
|
2257
|
+
}
|
|
2258
|
+
}
|
|
2259
|
+
};
|
|
2260
|
+
var fsAsync = {
|
|
2261
|
+
readFile(tempFile, callback) {
|
|
2262
|
+
try {
|
|
2263
|
+
fs2.readFile(tempFile, "utf8", (err, contents) => {
|
|
2264
|
+
try {
|
|
2265
|
+
fs2.unlink(tempFile, () => callback(err, contents));
|
|
2266
|
+
} catch {
|
|
2267
|
+
callback(err, contents);
|
|
2268
|
+
}
|
|
2269
|
+
});
|
|
2270
|
+
} catch (err) {
|
|
2271
|
+
callback(err, null);
|
|
2272
|
+
}
|
|
2273
|
+
},
|
|
2274
|
+
writeFile(contents, callback) {
|
|
2275
|
+
try {
|
|
2276
|
+
let tempFile = randomFileName();
|
|
2277
|
+
fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile));
|
|
2278
|
+
} catch {
|
|
2279
|
+
callback(null);
|
|
2280
|
+
}
|
|
2281
|
+
}
|
|
2282
|
+
};
|
|
2283
|
+
var version = "0.27.7";
|
|
2284
|
+
var build = (options) => ensureServiceIsRunning().build(options);
|
|
2285
|
+
var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions);
|
|
2286
|
+
var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
|
|
2287
|
+
var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
|
|
2288
|
+
var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options);
|
|
2289
|
+
var buildSync = (options) => {
|
|
2290
|
+
if (worker_threads && !isInternalWorkerThread) {
|
|
2291
|
+
if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
|
|
2292
|
+
return workerThreadService.buildSync(options);
|
|
2293
|
+
}
|
|
2294
|
+
let result;
|
|
2295
|
+
runServiceSync((service) => service.buildOrContext({
|
|
2296
|
+
callName: "buildSync",
|
|
2297
|
+
refs: null,
|
|
2298
|
+
options,
|
|
2299
|
+
isTTY: isTTY(),
|
|
2300
|
+
defaultWD,
|
|
2301
|
+
callback: (err, res) => {
|
|
2302
|
+
if (err) throw err;
|
|
2303
|
+
result = res;
|
|
2304
|
+
}
|
|
2305
|
+
}));
|
|
2306
|
+
return result;
|
|
2307
|
+
};
|
|
2308
|
+
var transformSync = (input, options) => {
|
|
2309
|
+
if (worker_threads && !isInternalWorkerThread) {
|
|
2310
|
+
if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
|
|
2311
|
+
return workerThreadService.transformSync(input, options);
|
|
2312
|
+
}
|
|
2313
|
+
let result;
|
|
2314
|
+
runServiceSync((service) => service.transform({
|
|
2315
|
+
callName: "transformSync",
|
|
2316
|
+
refs: null,
|
|
2317
|
+
input,
|
|
2318
|
+
options: options || {},
|
|
2319
|
+
isTTY: isTTY(),
|
|
2320
|
+
fs: fsSync,
|
|
2321
|
+
callback: (err, res) => {
|
|
2322
|
+
if (err) throw err;
|
|
2323
|
+
result = res;
|
|
2324
|
+
}
|
|
2325
|
+
}));
|
|
2326
|
+
return result;
|
|
2327
|
+
};
|
|
2328
|
+
var formatMessagesSync = (messages, options) => {
|
|
2329
|
+
if (worker_threads && !isInternalWorkerThread) {
|
|
2330
|
+
if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
|
|
2331
|
+
return workerThreadService.formatMessagesSync(messages, options);
|
|
2332
|
+
}
|
|
2333
|
+
let result;
|
|
2334
|
+
runServiceSync((service) => service.formatMessages({
|
|
2335
|
+
callName: "formatMessagesSync",
|
|
2336
|
+
refs: null,
|
|
2337
|
+
messages,
|
|
2338
|
+
options,
|
|
2339
|
+
callback: (err, res) => {
|
|
2340
|
+
if (err) throw err;
|
|
2341
|
+
result = res;
|
|
2342
|
+
}
|
|
2343
|
+
}));
|
|
2344
|
+
return result;
|
|
2345
|
+
};
|
|
2346
|
+
var analyzeMetafileSync = (metafile, options) => {
|
|
2347
|
+
if (worker_threads && !isInternalWorkerThread) {
|
|
2348
|
+
if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
|
|
2349
|
+
return workerThreadService.analyzeMetafileSync(metafile, options);
|
|
2350
|
+
}
|
|
2351
|
+
let result;
|
|
2352
|
+
runServiceSync((service) => service.analyzeMetafile({
|
|
2353
|
+
callName: "analyzeMetafileSync",
|
|
2354
|
+
refs: null,
|
|
2355
|
+
metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
|
|
2356
|
+
options,
|
|
2357
|
+
callback: (err, res) => {
|
|
2358
|
+
if (err) throw err;
|
|
2359
|
+
result = res;
|
|
2360
|
+
}
|
|
2361
|
+
}));
|
|
2362
|
+
return result;
|
|
2363
|
+
};
|
|
2364
|
+
var stop = () => {
|
|
2365
|
+
if (stopService) stopService();
|
|
2366
|
+
if (workerThreadService) workerThreadService.stop();
|
|
2367
|
+
return Promise.resolve();
|
|
2368
|
+
};
|
|
2369
|
+
var initializeWasCalled = false;
|
|
2370
|
+
var initialize = (options) => {
|
|
2371
|
+
options = validateInitializeOptions(options || {});
|
|
2372
|
+
if (options.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`);
|
|
2373
|
+
if (options.wasmModule) throw new Error(`The "wasmModule" option only works in the browser`);
|
|
2374
|
+
if (options.worker) throw new Error(`The "worker" option only works in the browser`);
|
|
2375
|
+
if (initializeWasCalled) throw new Error("Cannot call \"initialize\" more than once");
|
|
2376
|
+
ensureServiceIsRunning();
|
|
2377
|
+
initializeWasCalled = true;
|
|
2378
|
+
return Promise.resolve();
|
|
2379
|
+
};
|
|
2380
|
+
var defaultWD = process.cwd();
|
|
2381
|
+
var longLivedService;
|
|
2382
|
+
var stopService;
|
|
2383
|
+
var ensureServiceIsRunning = () => {
|
|
2384
|
+
if (longLivedService) return longLivedService;
|
|
2385
|
+
let [command, args] = esbuildCommandAndArgs();
|
|
2386
|
+
let child = child_process.spawn(command, args.concat(`--service=0.27.7`, "--ping"), {
|
|
2387
|
+
windowsHide: true,
|
|
2388
|
+
stdio: [
|
|
2389
|
+
"pipe",
|
|
2390
|
+
"pipe",
|
|
2391
|
+
"inherit"
|
|
2392
|
+
],
|
|
2393
|
+
cwd: defaultWD
|
|
2394
|
+
});
|
|
2395
|
+
let { readFromStdout, afterClose, service } = createChannel({
|
|
2396
|
+
writeToStdin(bytes) {
|
|
2397
|
+
child.stdin.write(bytes, (err) => {
|
|
2398
|
+
if (err) afterClose(err);
|
|
2399
|
+
});
|
|
2400
|
+
},
|
|
2401
|
+
readFileSync: fs2.readFileSync,
|
|
2402
|
+
isSync: false,
|
|
2403
|
+
hasFS: true,
|
|
2404
|
+
esbuild: node_exports
|
|
2405
|
+
});
|
|
2406
|
+
child.stdin.on("error", afterClose);
|
|
2407
|
+
child.on("error", afterClose);
|
|
2408
|
+
const stdin = child.stdin;
|
|
2409
|
+
const stdout = child.stdout;
|
|
2410
|
+
stdout.on("data", readFromStdout);
|
|
2411
|
+
stdout.on("end", afterClose);
|
|
2412
|
+
stopService = () => {
|
|
2413
|
+
stdin.destroy();
|
|
2414
|
+
stdout.destroy();
|
|
2415
|
+
child.kill();
|
|
2416
|
+
initializeWasCalled = false;
|
|
2417
|
+
longLivedService = void 0;
|
|
2418
|
+
stopService = void 0;
|
|
2419
|
+
};
|
|
2420
|
+
let refCount = 0;
|
|
2421
|
+
child.unref();
|
|
2422
|
+
if (stdin.unref) stdin.unref();
|
|
2423
|
+
if (stdout.unref) stdout.unref();
|
|
2424
|
+
const refs = {
|
|
2425
|
+
ref() {
|
|
2426
|
+
if (++refCount === 1) child.ref();
|
|
2427
|
+
},
|
|
2428
|
+
unref() {
|
|
2429
|
+
if (--refCount === 0) child.unref();
|
|
2430
|
+
}
|
|
2431
|
+
};
|
|
2432
|
+
longLivedService = {
|
|
2433
|
+
build: (options) => new Promise((resolve, reject) => {
|
|
2434
|
+
service.buildOrContext({
|
|
2435
|
+
callName: "build",
|
|
2436
|
+
refs,
|
|
2437
|
+
options,
|
|
2438
|
+
isTTY: isTTY(),
|
|
2439
|
+
defaultWD,
|
|
2440
|
+
callback: (err, res) => err ? reject(err) : resolve(res)
|
|
2441
|
+
});
|
|
2442
|
+
}),
|
|
2443
|
+
context: (options) => new Promise((resolve, reject) => service.buildOrContext({
|
|
2444
|
+
callName: "context",
|
|
2445
|
+
refs,
|
|
2446
|
+
options,
|
|
2447
|
+
isTTY: isTTY(),
|
|
2448
|
+
defaultWD,
|
|
2449
|
+
callback: (err, res) => err ? reject(err) : resolve(res)
|
|
2450
|
+
})),
|
|
2451
|
+
transform: (input, options) => new Promise((resolve, reject) => service.transform({
|
|
2452
|
+
callName: "transform",
|
|
2453
|
+
refs,
|
|
2454
|
+
input,
|
|
2455
|
+
options: options || {},
|
|
2456
|
+
isTTY: isTTY(),
|
|
2457
|
+
fs: fsAsync,
|
|
2458
|
+
callback: (err, res) => err ? reject(err) : resolve(res)
|
|
2459
|
+
})),
|
|
2460
|
+
formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({
|
|
2461
|
+
callName: "formatMessages",
|
|
2462
|
+
refs,
|
|
2463
|
+
messages,
|
|
2464
|
+
options,
|
|
2465
|
+
callback: (err, res) => err ? reject(err) : resolve(res)
|
|
2466
|
+
})),
|
|
2467
|
+
analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => service.analyzeMetafile({
|
|
2468
|
+
callName: "analyzeMetafile",
|
|
2469
|
+
refs,
|
|
2470
|
+
metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
|
|
2471
|
+
options,
|
|
2472
|
+
callback: (err, res) => err ? reject(err) : resolve(res)
|
|
2473
|
+
}))
|
|
2474
|
+
};
|
|
2475
|
+
return longLivedService;
|
|
2476
|
+
};
|
|
2477
|
+
var runServiceSync = (callback) => {
|
|
2478
|
+
let [command, args] = esbuildCommandAndArgs();
|
|
2479
|
+
let stdin = new Uint8Array();
|
|
2480
|
+
let { readFromStdout, afterClose, service } = createChannel({
|
|
2481
|
+
writeToStdin(bytes) {
|
|
2482
|
+
if (stdin.length !== 0) throw new Error("Must run at most one command");
|
|
2483
|
+
stdin = bytes;
|
|
2484
|
+
},
|
|
2485
|
+
isSync: true,
|
|
2486
|
+
hasFS: true,
|
|
2487
|
+
esbuild: node_exports
|
|
2488
|
+
});
|
|
2489
|
+
callback(service);
|
|
2490
|
+
readFromStdout(child_process.execFileSync(command, args.concat(`--service=0.27.7`), {
|
|
2491
|
+
cwd: defaultWD,
|
|
2492
|
+
windowsHide: true,
|
|
2493
|
+
input: stdin,
|
|
2494
|
+
maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
|
|
2495
|
+
}));
|
|
2496
|
+
afterClose(null);
|
|
2497
|
+
};
|
|
2498
|
+
var randomFileName = () => {
|
|
2499
|
+
return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`);
|
|
2500
|
+
};
|
|
2501
|
+
var workerThreadService = null;
|
|
2502
|
+
var startWorkerThreadService = (worker_threads2) => {
|
|
2503
|
+
let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel();
|
|
2504
|
+
let worker = new worker_threads2.Worker(__filename, {
|
|
2505
|
+
workerData: {
|
|
2506
|
+
workerPort,
|
|
2507
|
+
defaultWD,
|
|
2508
|
+
esbuildVersion: "0.27.7"
|
|
2509
|
+
},
|
|
2510
|
+
transferList: [workerPort],
|
|
2511
|
+
execArgv: []
|
|
2512
|
+
});
|
|
2513
|
+
let nextID = 0;
|
|
2514
|
+
let fakeBuildError = (text) => {
|
|
2515
|
+
let error = /* @__PURE__ */ new Error(`Build failed with 1 error:
|
|
2516
|
+
error: ${text}`);
|
|
2517
|
+
error.errors = [{
|
|
2518
|
+
id: "",
|
|
2519
|
+
pluginName: "",
|
|
2520
|
+
text,
|
|
2521
|
+
location: null,
|
|
2522
|
+
notes: [],
|
|
2523
|
+
detail: void 0
|
|
2524
|
+
}];
|
|
2525
|
+
error.warnings = [];
|
|
2526
|
+
return error;
|
|
2527
|
+
};
|
|
2528
|
+
let validateBuildSyncOptions = (options) => {
|
|
2529
|
+
if (!options) return;
|
|
2530
|
+
let plugins = options.plugins;
|
|
2531
|
+
if (plugins && plugins.length > 0) throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
|
|
2532
|
+
};
|
|
2533
|
+
let applyProperties = (object, properties) => {
|
|
2534
|
+
for (let key in properties) object[key] = properties[key];
|
|
2535
|
+
};
|
|
2536
|
+
let runCallSync = (command, args) => {
|
|
2537
|
+
let id = nextID++;
|
|
2538
|
+
let sharedBuffer = new SharedArrayBuffer(8);
|
|
2539
|
+
let sharedBufferView = new Int32Array(sharedBuffer);
|
|
2540
|
+
let msg = {
|
|
2541
|
+
sharedBuffer,
|
|
2542
|
+
id,
|
|
2543
|
+
command,
|
|
2544
|
+
args
|
|
2545
|
+
};
|
|
2546
|
+
worker.postMessage(msg);
|
|
2547
|
+
let status = Atomics.wait(sharedBufferView, 0, 0);
|
|
2548
|
+
if (status !== "ok" && status !== "not-equal") throw new Error("Internal error: Atomics.wait() failed: " + status);
|
|
2549
|
+
let { message: { id: id2, resolve, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort);
|
|
2550
|
+
if (id !== id2) throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
|
|
2551
|
+
if (reject) {
|
|
2552
|
+
applyProperties(reject, properties);
|
|
2553
|
+
throw reject;
|
|
2554
|
+
}
|
|
2555
|
+
return resolve;
|
|
2556
|
+
};
|
|
2557
|
+
worker.unref();
|
|
2558
|
+
return {
|
|
2559
|
+
buildSync(options) {
|
|
2560
|
+
validateBuildSyncOptions(options);
|
|
2561
|
+
return runCallSync("build", [options]);
|
|
2562
|
+
},
|
|
2563
|
+
transformSync(input, options) {
|
|
2564
|
+
return runCallSync("transform", [input, options]);
|
|
2565
|
+
},
|
|
2566
|
+
formatMessagesSync(messages, options) {
|
|
2567
|
+
return runCallSync("formatMessages", [messages, options]);
|
|
2568
|
+
},
|
|
2569
|
+
analyzeMetafileSync(metafile, options) {
|
|
2570
|
+
return runCallSync("analyzeMetafile", [metafile, options]);
|
|
2571
|
+
},
|
|
2572
|
+
stop() {
|
|
2573
|
+
worker.terminate();
|
|
2574
|
+
workerThreadService = null;
|
|
2575
|
+
}
|
|
2576
|
+
};
|
|
2577
|
+
};
|
|
2578
|
+
var startSyncServiceWorker = () => {
|
|
2579
|
+
let workerPort = worker_threads.workerData.workerPort;
|
|
2580
|
+
let parentPort = worker_threads.parentPort;
|
|
2581
|
+
let extractProperties = (object) => {
|
|
2582
|
+
let properties = {};
|
|
2583
|
+
if (object && typeof object === "object") for (let key in object) properties[key] = object[key];
|
|
2584
|
+
return properties;
|
|
2585
|
+
};
|
|
2586
|
+
try {
|
|
2587
|
+
let service = ensureServiceIsRunning();
|
|
2588
|
+
defaultWD = worker_threads.workerData.defaultWD;
|
|
2589
|
+
parentPort.on("message", (msg) => {
|
|
2590
|
+
(async () => {
|
|
2591
|
+
let { sharedBuffer, id, command, args } = msg;
|
|
2592
|
+
let sharedBufferView = new Int32Array(sharedBuffer);
|
|
2593
|
+
try {
|
|
2594
|
+
switch (command) {
|
|
2595
|
+
case "build":
|
|
2596
|
+
workerPort.postMessage({
|
|
2597
|
+
id,
|
|
2598
|
+
resolve: await service.build(args[0])
|
|
2599
|
+
});
|
|
2600
|
+
break;
|
|
2601
|
+
case "transform":
|
|
2602
|
+
workerPort.postMessage({
|
|
2603
|
+
id,
|
|
2604
|
+
resolve: await service.transform(args[0], args[1])
|
|
2605
|
+
});
|
|
2606
|
+
break;
|
|
2607
|
+
case "formatMessages":
|
|
2608
|
+
workerPort.postMessage({
|
|
2609
|
+
id,
|
|
2610
|
+
resolve: await service.formatMessages(args[0], args[1])
|
|
2611
|
+
});
|
|
2612
|
+
break;
|
|
2613
|
+
case "analyzeMetafile":
|
|
2614
|
+
workerPort.postMessage({
|
|
2615
|
+
id,
|
|
2616
|
+
resolve: await service.analyzeMetafile(args[0], args[1])
|
|
2617
|
+
});
|
|
2618
|
+
break;
|
|
2619
|
+
default: throw new Error(`Invalid command: ${command}`);
|
|
2620
|
+
}
|
|
2621
|
+
} catch (reject) {
|
|
2622
|
+
workerPort.postMessage({
|
|
2623
|
+
id,
|
|
2624
|
+
reject,
|
|
2625
|
+
properties: extractProperties(reject)
|
|
2626
|
+
});
|
|
2627
|
+
}
|
|
2628
|
+
Atomics.add(sharedBufferView, 0, 1);
|
|
2629
|
+
Atomics.notify(sharedBufferView, 0, Infinity);
|
|
2630
|
+
})();
|
|
2631
|
+
});
|
|
2632
|
+
} catch (reject) {
|
|
2633
|
+
parentPort.on("message", (msg) => {
|
|
2634
|
+
let { sharedBuffer, id } = msg;
|
|
2635
|
+
let sharedBufferView = new Int32Array(sharedBuffer);
|
|
2636
|
+
workerPort.postMessage({
|
|
2637
|
+
id,
|
|
2638
|
+
reject,
|
|
2639
|
+
properties: extractProperties(reject)
|
|
2640
|
+
});
|
|
2641
|
+
Atomics.add(sharedBufferView, 0, 1);
|
|
2642
|
+
Atomics.notify(sharedBufferView, 0, Infinity);
|
|
2643
|
+
});
|
|
2644
|
+
}
|
|
2645
|
+
};
|
|
2646
|
+
if (isInternalWorkerThread) startSyncServiceWorker();
|
|
2647
|
+
var node_default = node_exports;
|
|
2648
|
+
0 && (module.exports = {
|
|
2649
|
+
analyzeMetafile,
|
|
2650
|
+
analyzeMetafileSync,
|
|
2651
|
+
build,
|
|
2652
|
+
buildSync,
|
|
2653
|
+
context,
|
|
2654
|
+
formatMessages,
|
|
2655
|
+
formatMessagesSync,
|
|
2656
|
+
initialize,
|
|
2657
|
+
stop,
|
|
2658
|
+
transform,
|
|
2659
|
+
transformSync,
|
|
2660
|
+
version
|
|
2661
|
+
});
|
|
2662
|
+
})))();
|
|
2663
|
+
const projectRootDirectoryMarkers = [
|
|
2664
|
+
["server", "agents"],
|
|
2665
|
+
["server", "schedules"],
|
|
2666
|
+
["server", "templates"],
|
|
2667
|
+
["server", "workspaces"]
|
|
2668
|
+
];
|
|
2669
|
+
const projectRootDefinitionFileMarkers = [
|
|
2670
|
+
".ts",
|
|
2671
|
+
".mts",
|
|
2672
|
+
".cts",
|
|
2673
|
+
".js",
|
|
2674
|
+
".mjs",
|
|
2675
|
+
".cjs"
|
|
2676
|
+
].flatMap((extension) => [["server", `email${extension}`], [`server.email${extension}`]]);
|
|
2677
|
+
const projectRootFileMarkers = [["package.json"]];
|
|
2678
|
+
function createNoExternalMerger(packageName) {
|
|
2679
|
+
return (current) => {
|
|
2680
|
+
if (current === true) return true;
|
|
2681
|
+
if (!current) return [packageName];
|
|
2682
|
+
const values = Array.isArray(current) ? current : [current];
|
|
2683
|
+
return values.includes(packageName) ? values : [...values, packageName];
|
|
2684
|
+
};
|
|
2685
|
+
}
|
|
2686
|
+
function isServerEnvironment(name, config) {
|
|
2687
|
+
return name === "ssr" || config.consumer === "server";
|
|
2688
|
+
}
|
|
2689
|
+
function includesNitroVitePlugin(value) {
|
|
2690
|
+
if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
|
|
2691
|
+
if (!value || typeof value !== "object") return false;
|
|
2692
|
+
return "name" in value && value.name === "nitro:main";
|
|
2693
|
+
}
|
|
2694
|
+
function hasNitroVitePlugin(config) {
|
|
2695
|
+
return includesNitroVitePlugin(config.plugins);
|
|
2696
|
+
}
|
|
2697
|
+
function shouldSkipViteProviderBuild(command, mode) {
|
|
2698
|
+
return command === "serve" || mode === "e2e";
|
|
2699
|
+
}
|
|
2700
|
+
function resolveViteHubProjectRoot(root, options = {}) {
|
|
2701
|
+
const resolvedRoot = resolve(root);
|
|
2702
|
+
if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
|
|
2703
|
+
if (basename(resolvedRoot) === "app") {
|
|
2704
|
+
const parent = dirname(resolvedRoot);
|
|
2705
|
+
if (hasProjectRootDirectoryMarker(parent) || hasProjectRootDefinitionFileMarker(parent)) return parent;
|
|
2706
|
+
}
|
|
2707
|
+
let current = resolvedRoot;
|
|
2708
|
+
while (true) {
|
|
2709
|
+
if (hasProjectRootMarker(current)) return current;
|
|
2710
|
+
const parent = dirname(current);
|
|
2711
|
+
if (parent === current) return resolvedRoot;
|
|
2712
|
+
current = parent;
|
|
2713
|
+
}
|
|
2714
|
+
}
|
|
2715
|
+
function hasProjectRootDirectoryMarker(root) {
|
|
2716
|
+
for (const marker of projectRootDirectoryMarkers) try {
|
|
2717
|
+
if (statSync(resolve(root, ...marker)).isDirectory()) return true;
|
|
2718
|
+
} catch (error) {
|
|
2719
|
+
if (error.code !== "ENOENT") throw error;
|
|
2720
|
+
}
|
|
2721
|
+
return false;
|
|
2722
|
+
}
|
|
2723
|
+
function hasProjectRootMarker(root) {
|
|
2724
|
+
if (hasProjectRootDirectoryMarker(root)) return true;
|
|
2725
|
+
if (hasProjectRootDefinitionFileMarker(root)) return true;
|
|
2726
|
+
for (const marker of projectRootFileMarkers) try {
|
|
2727
|
+
if (statSync(resolve(root, ...marker)).isFile()) return true;
|
|
2728
|
+
} catch (error) {
|
|
2729
|
+
if (error.code !== "ENOENT") throw error;
|
|
2730
|
+
}
|
|
2731
|
+
return false;
|
|
2732
|
+
}
|
|
2733
|
+
function hasProjectRootDefinitionFileMarker(root) {
|
|
2734
|
+
for (const marker of projectRootDefinitionFileMarkers) try {
|
|
2735
|
+
if (statSync(resolve(root, ...marker)).isFile()) return true;
|
|
2736
|
+
} catch (error) {
|
|
2737
|
+
if (error.code !== "ENOENT") throw error;
|
|
2738
|
+
}
|
|
2739
|
+
return false;
|
|
2740
|
+
}
|
|
2741
|
+
//#endregion
|
|
2742
|
+
//#region ../internal/src/build/esbuild.ts
|
|
2743
|
+
const viteRawNamespace = "vitehub-vite-raw";
|
|
2744
|
+
const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
|
|
2745
|
+
const markdownTemplateFileSuffix = ".template.md";
|
|
2746
|
+
const markdownTemplateModuleQuery = "markdown-template";
|
|
2747
|
+
const markdownTemplateRegistryId = "#vitehub/templates";
|
|
2748
|
+
const markdownTemplateRegistryPath = ".vitehub/markdown-template/templates.mjs";
|
|
2749
|
+
const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
|
|
2750
|
+
const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
|
|
2751
|
+
function resolveEsbuildAliases(aliases) {
|
|
2752
|
+
if (!aliases) return;
|
|
2753
|
+
return Object.fromEntries(Object.entries(aliases).filter(([specifier]) => !specifier.endsWith("/")));
|
|
2754
|
+
}
|
|
2755
|
+
function stripMarkdownCode(template) {
|
|
2756
|
+
let fence;
|
|
2757
|
+
let inList = false;
|
|
2758
|
+
let previousLineBlank = true;
|
|
2759
|
+
return template.split("\n").map((line) => {
|
|
2760
|
+
const content = line.replace(/^(?: {0,3}> ?)+/, "");
|
|
2761
|
+
if (!fence) {
|
|
2762
|
+
const listIndented = inList && /^ {4}(?:`{3,}|~{3,})/.test(content);
|
|
2763
|
+
const opening = (listIndented ? content.slice(4) : content).match(/^ {0,3}(`{3,}|~{3,})/);
|
|
2764
|
+
if (!opening) {
|
|
2765
|
+
if (/^ {0,3}(?:[-+*]|\d+[.)])\s+/.test(content)) inList = true;
|
|
2766
|
+
else if (content.trim() && !/^ {2,}/.test(content)) inList = false;
|
|
2767
|
+
const indentedCode = !inList && previousLineBlank && /^(?: {4}|\t)/.test(content) || inList && previousLineBlank && /^(?: {8}| {4}\t|\t{2})/.test(content);
|
|
2768
|
+
previousLineBlank = content.trim() === "";
|
|
2769
|
+
return indentedCode ? "" : line;
|
|
2770
|
+
}
|
|
2771
|
+
fence = {
|
|
2772
|
+
marker: opening[1][0],
|
|
2773
|
+
length: opening[1].length,
|
|
2774
|
+
listIndented
|
|
2775
|
+
};
|
|
2776
|
+
previousLineBlank = false;
|
|
2777
|
+
return "";
|
|
2778
|
+
}
|
|
2779
|
+
const closing = (fence.listIndented ? content.replace(/^ {4}/, "") : content).match(/^ {0,3}(`+|~+)\s*$/)?.[1];
|
|
2780
|
+
if (closing?.[0] === fence.marker && closing.length >= fence.length) fence = void 0;
|
|
2781
|
+
previousLineBlank = false;
|
|
2782
|
+
return "";
|
|
2783
|
+
}).join("\n");
|
|
2784
|
+
}
|
|
2785
|
+
function extractMarkdownTemplateImportSpecifiers(template) {
|
|
2786
|
+
const visible = stripMarkdownCode(template).replace(/(`+)[\s\S]*?\1/g, "").replace(/(!?\[[^\]]*\])\([^)]*\)/g, "$1").replace(/^ {0,3}\[[^\]]+\]:\s*\S+/gm, "").replace(/<[^>]*>/g, "");
|
|
2787
|
+
const specifiers = /* @__PURE__ */ new Set();
|
|
2788
|
+
for (const match of visible.matchAll(/@(\.\.?\/[^\s<>{}[\]]+)/g)) {
|
|
2789
|
+
const token = match[1];
|
|
2790
|
+
const trailing = token.match(/[.,;:!?)]*$/)?.[0] || "";
|
|
2791
|
+
specifiers.add(token.slice(0, token.length - trailing.length));
|
|
2792
|
+
}
|
|
2793
|
+
return [...specifiers];
|
|
2794
|
+
}
|
|
2795
|
+
function parseMarkdownTemplateRequest(id) {
|
|
2796
|
+
const queryIndex = id.indexOf("?");
|
|
2797
|
+
const path = id.split(/[?#]/, 1)[0];
|
|
2798
|
+
if (queryIndex === -1) return path.endsWith(markdownTemplateFileSuffix) ? { path } : void 0;
|
|
2799
|
+
const query = id.slice(queryIndex + 1).split("#", 1)[0];
|
|
2800
|
+
if (!new URLSearchParams(query).has(markdownTemplateModuleQuery)) return;
|
|
2801
|
+
return { path };
|
|
2802
|
+
}
|
|
2803
|
+
function renderMarkdownTemplateModule(template, sourceId, imports = {}) {
|
|
2804
|
+
return [
|
|
2805
|
+
`import { renderMarkdownTemplate as vitehubRenderMarkdownTemplate } from ${JSON.stringify(markdownTemplateRuntimeSpecifier)}`,
|
|
2806
|
+
`const vitehubMarkdownTemplate = ${JSON.stringify(template)}`,
|
|
2807
|
+
`const vitehubMarkdownTemplateSourceId = ${JSON.stringify(sourceId)}`,
|
|
2808
|
+
`const vitehubMarkdownTemplateImports = ${JSON.stringify(imports)}`,
|
|
2809
|
+
"export default function render(data = {}) {",
|
|
2810
|
+
" return vitehubRenderMarkdownTemplate(vitehubMarkdownTemplate, { data, sourceId: vitehubMarkdownTemplateSourceId, resolveImport: (specifier, importer) => vitehubMarkdownTemplateImports[`${importer}\\0${specifier}`] })",
|
|
2811
|
+
"}",
|
|
2812
|
+
""
|
|
2813
|
+
].join("\n");
|
|
2814
|
+
}
|
|
2815
|
+
function hasViteRawQuery(path) {
|
|
2816
|
+
const queryIndex = path.indexOf("?");
|
|
2817
|
+
return queryIndex !== -1 && /(?:^|&)raw(?:&|$)/.test(path.slice(queryIndex + 1));
|
|
2818
|
+
}
|
|
2819
|
+
async function resolveViteRawSpecifier(path, rootDir) {
|
|
2820
|
+
if (path.startsWith("/@fs/")) return path.slice(5);
|
|
2821
|
+
if (!rootDir || !path.startsWith("/")) return path;
|
|
2822
|
+
const rootRelativePath = path.slice(1);
|
|
2823
|
+
const publicPath = resolve(rootDir, "public", rootRelativePath);
|
|
2824
|
+
try {
|
|
2825
|
+
await stat(publicPath);
|
|
2826
|
+
return publicPath;
|
|
2827
|
+
} catch (error) {
|
|
2828
|
+
if (error.code !== "ENOENT") throw error;
|
|
2829
|
+
return resolve(rootDir, rootRelativePath);
|
|
2830
|
+
}
|
|
2831
|
+
}
|
|
2832
|
+
function createViteRawPlugin(rootDir, frameworkRuntime) {
|
|
2833
|
+
return {
|
|
2834
|
+
name: "vitehub-vite-raw",
|
|
2835
|
+
setup(build) {
|
|
2836
|
+
build.onResolve({
|
|
2837
|
+
filter: /^@vite-hub\/markdown-template$/,
|
|
2838
|
+
namespace: viteMarkdownTemplateNamespace
|
|
2839
|
+
}, async (args) => {
|
|
2840
|
+
if (!frameworkRuntime) return { path: fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier)) };
|
|
2841
|
+
return build.resolve("vite-hub/_internal/markdown-template", {
|
|
2842
|
+
importer: args.importer,
|
|
2843
|
+
kind: args.kind,
|
|
2844
|
+
resolveDir: args.resolveDir
|
|
2845
|
+
});
|
|
2846
|
+
});
|
|
2847
|
+
build.onResolve({ filter: /\?|\.template\.md$/ }, async (args) => {
|
|
2848
|
+
if (args.pluginData?.[skipMarkdownTemplateResolve]) return;
|
|
2849
|
+
const markdownTemplate = parseMarkdownTemplateRequest(args.path);
|
|
2850
|
+
const raw = hasViteRawQuery(args.path);
|
|
2851
|
+
if (!markdownTemplate && !raw) return;
|
|
2852
|
+
const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? args.path.slice(0, args.path.indexOf("?")), rootDir);
|
|
2853
|
+
const resolved = await build.resolve(specifier, {
|
|
2854
|
+
importer: args.importer,
|
|
2855
|
+
kind: args.kind,
|
|
2856
|
+
namespace: args.namespace,
|
|
2857
|
+
pluginData: markdownTemplate ? {
|
|
2858
|
+
...args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {},
|
|
2859
|
+
[skipMarkdownTemplateResolve]: true
|
|
2860
|
+
} : args.pluginData,
|
|
2861
|
+
resolveDir: args.resolveDir,
|
|
2862
|
+
with: args.with
|
|
2863
|
+
});
|
|
2864
|
+
if (resolved.errors.length) return {
|
|
2865
|
+
errors: resolved.errors,
|
|
2866
|
+
warnings: resolved.warnings
|
|
2867
|
+
};
|
|
2868
|
+
if (resolved.external) return {
|
|
2869
|
+
external: true,
|
|
2870
|
+
namespace: resolved.namespace,
|
|
2871
|
+
path: resolved.path,
|
|
2872
|
+
pluginData: resolved.pluginData,
|
|
2873
|
+
sideEffects: resolved.sideEffects,
|
|
2874
|
+
suffix: resolved.suffix,
|
|
2875
|
+
warnings: resolved.warnings
|
|
2876
|
+
};
|
|
2877
|
+
if (resolved.namespace !== "file") return {
|
|
2878
|
+
errors: [{ text: markdownTemplate ? `[vitehub] Markdown template fallback cannot load ${JSON.stringify(args.path)} from the ${JSON.stringify(resolved.namespace)} namespace. Handle this template import in a caller plugin.` : `[vitehub] Vite raw fallback cannot load ${JSON.stringify(args.path)} from the ${JSON.stringify(resolved.namespace)} namespace. Handle this raw import in a caller plugin.` }],
|
|
2879
|
+
warnings: resolved.warnings
|
|
2880
|
+
};
|
|
2881
|
+
return {
|
|
2882
|
+
namespace: markdownTemplate ? viteMarkdownTemplateNamespace : viteRawNamespace,
|
|
2883
|
+
path: resolved.path,
|
|
2884
|
+
pluginData: resolved.pluginData,
|
|
2885
|
+
sideEffects: resolved.sideEffects,
|
|
2886
|
+
suffix: resolved.suffix,
|
|
2887
|
+
warnings: resolved.warnings
|
|
2888
|
+
};
|
|
2889
|
+
});
|
|
2890
|
+
build.onLoad({
|
|
2891
|
+
filter: /.*/,
|
|
2892
|
+
namespace: viteRawNamespace
|
|
2893
|
+
}, async (args) => ({
|
|
2894
|
+
contents: await readFile(args.path),
|
|
2895
|
+
loader: "text"
|
|
2896
|
+
}));
|
|
2897
|
+
build.onLoad({
|
|
2898
|
+
filter: /.*/,
|
|
2899
|
+
namespace: viteMarkdownTemplateNamespace
|
|
2900
|
+
}, async (args) => ({
|
|
2901
|
+
contents: await (async () => {
|
|
2902
|
+
const template = await readFile(args.path, "utf8");
|
|
2903
|
+
const imports = {};
|
|
2904
|
+
const visited = new Set([args.path]);
|
|
2905
|
+
const visit = async (source, importer) => {
|
|
2906
|
+
for (const specifier of extractMarkdownTemplateImportSpecifiers(source)) {
|
|
2907
|
+
const key = `${importer}\0${specifier}`;
|
|
2908
|
+
if (imports[key]) continue;
|
|
2909
|
+
const resolved = await build.resolve(specifier, {
|
|
2910
|
+
importer,
|
|
2911
|
+
kind: "import-statement",
|
|
2912
|
+
pluginData: {
|
|
2913
|
+
...args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {},
|
|
2914
|
+
[skipMarkdownTemplateResolve]: true
|
|
2915
|
+
},
|
|
2916
|
+
resolveDir: dirname(importer)
|
|
2917
|
+
});
|
|
2918
|
+
if (resolved.errors.length) return Promise.reject(new Error(resolved.errors.map((error) => error.text).join("\n")));
|
|
2919
|
+
if (resolved.external || resolved.namespace !== "file") throw new Error(`[vitehub] Could not resolve Markdown template import ${JSON.stringify(specifier)} from ${JSON.stringify(importer)} to a file.`);
|
|
2920
|
+
const imported = {
|
|
2921
|
+
id: resolved.path,
|
|
2922
|
+
template: await readFile(resolved.path, "utf8")
|
|
2923
|
+
};
|
|
2924
|
+
imports[key] = imported;
|
|
2925
|
+
if (!visited.has(imported.id)) {
|
|
2926
|
+
visited.add(imported.id);
|
|
2927
|
+
await visit(imported.template, imported.id);
|
|
2928
|
+
}
|
|
2929
|
+
}
|
|
2930
|
+
};
|
|
2931
|
+
await visit(template, args.path);
|
|
2932
|
+
return renderMarkdownTemplateModule(template, args.path, imports);
|
|
2933
|
+
})(),
|
|
2934
|
+
loader: "js",
|
|
2935
|
+
resolveDir: dirname(args.path)
|
|
2936
|
+
}));
|
|
2937
|
+
}
|
|
2938
|
+
};
|
|
2939
|
+
}
|
|
2940
|
+
async function bundleEsmEntry(entryFile, outfile, options = {}) {
|
|
2941
|
+
const format = options.format || "esm";
|
|
2942
|
+
const platform = options.platform || "neutral";
|
|
2943
|
+
const markdownTemplateRoot = options.rootDir && resolveViteHubProjectRoot(options.rootDir);
|
|
2944
|
+
const aliases = resolveEsbuildAliases({
|
|
2945
|
+
...markdownTemplateRoot ? { [markdownTemplateRegistryId]: resolve(markdownTemplateRoot, markdownTemplateRegistryPath) } : {},
|
|
2946
|
+
...options.alias
|
|
2947
|
+
});
|
|
2948
|
+
const frameworkRuntime = Object.keys(aliases || {}).some((specifier) => specifier === "vite-hub" || specifier.startsWith("vite-hub/"));
|
|
2949
|
+
await (0, import_main.build)({
|
|
2950
|
+
alias: aliases,
|
|
2951
|
+
banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
|
|
2952
|
+
"import { createRequire as __createRequire } from \"node:module\";",
|
|
2953
|
+
"import { dirname as __vitehubDirname } from \"node:path\";",
|
|
2954
|
+
"import { fileURLToPath as __vitehubFileURLToPath } from \"node:url\";",
|
|
2955
|
+
"globalThis.require = __createRequire(import.meta.url);",
|
|
2956
|
+
"globalThis.__filename = __vitehubFileURLToPath(import.meta.url);",
|
|
2957
|
+
"globalThis.__dirname = __vitehubDirname(globalThis.__filename);"
|
|
2958
|
+
] : []].filter(Boolean).join("\n") } : void 0,
|
|
2959
|
+
bundle: true,
|
|
2960
|
+
conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
|
|
2961
|
+
entryPoints: [entryFile],
|
|
2962
|
+
external: options.external,
|
|
2963
|
+
format,
|
|
2964
|
+
logLevel: "silent",
|
|
2965
|
+
mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
|
|
2966
|
+
minifyIdentifiers: options.minifyIdentifiers,
|
|
2967
|
+
outfile,
|
|
2968
|
+
platform,
|
|
2969
|
+
plugins: [...options.plugins ?? [], createViteRawPlugin(options.rootDir, frameworkRuntime)],
|
|
2970
|
+
sourcemap: false,
|
|
2971
|
+
target: "es2022",
|
|
2972
|
+
write: true
|
|
2973
|
+
});
|
|
2974
|
+
}
|
|
2975
|
+
//#endregion
|
|
2976
|
+
//#region ../internal/src/build/vercel-config.ts
|
|
2977
|
+
function createVercelConfigJson() {
|
|
2978
|
+
return {
|
|
2979
|
+
routes: [{ handle: "filesystem" }, {
|
|
2980
|
+
src: "/(.*)",
|
|
2981
|
+
dest: "/__server"
|
|
2982
|
+
}],
|
|
2983
|
+
version: 3
|
|
2984
|
+
};
|
|
2985
|
+
}
|
|
2986
|
+
function createNodeFunctionConfig(extra = {}) {
|
|
2987
|
+
return {
|
|
2988
|
+
handler: "index.mjs",
|
|
2989
|
+
launcherType: "Nodejs",
|
|
2990
|
+
runtime: "nodejs22.x",
|
|
2991
|
+
shouldAddHelpers: false,
|
|
2992
|
+
supportsResponseStreaming: true,
|
|
2993
|
+
...extra
|
|
2994
|
+
};
|
|
2995
|
+
}
|
|
2996
|
+
//#endregion
|
|
2997
|
+
//#region ../internal/src/build/cloudflare-provider-output.ts
|
|
2998
|
+
const cloudflareProviderOutputKey = Symbol.for("vitehub.cloudflareProviderOutput");
|
|
2999
|
+
const cloudflareProviderOutputByNitro = /* @__PURE__ */ new WeakMap();
|
|
3000
|
+
function cloneRecord(value) {
|
|
3001
|
+
return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
|
|
3002
|
+
}
|
|
3003
|
+
function cloneProviderRecord(value) {
|
|
3004
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
|
|
3005
|
+
return Object.fromEntries(Object.entries(value).flatMap(([key, entry]) => typeof entry === "undefined" ? [] : [[key, cloneProviderValue(entry)]]));
|
|
3006
|
+
}
|
|
3007
|
+
function cloneProviderValue(value) {
|
|
3008
|
+
if (Array.isArray(value)) return value.map((entry) => typeof entry === "undefined" ? null : cloneProviderValue(entry));
|
|
3009
|
+
if (value && typeof value === "object") return cloneProviderRecord(value);
|
|
3010
|
+
return value;
|
|
3011
|
+
}
|
|
3012
|
+
function useCloudflareProviderOutput(config) {
|
|
3013
|
+
const owner = config;
|
|
3014
|
+
return owner[cloudflareProviderOutputKey] ??= {
|
|
3015
|
+
appliedByOwner: /* @__PURE__ */ new Map(),
|
|
3016
|
+
contributionsByOwner: /* @__PURE__ */ new Map()
|
|
3017
|
+
};
|
|
3018
|
+
}
|
|
3019
|
+
function registerCloudflareProviderOutput(config, owner, contribution) {
|
|
3020
|
+
useCloudflareProviderOutput(config).contributionsByOwner.set(owner, contribution);
|
|
3021
|
+
}
|
|
3022
|
+
function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner) {
|
|
3023
|
+
const current = Array.isArray(existing) ? existing.map(cloneProviderRecord) : [];
|
|
3024
|
+
return (incoming ?? []).filter((entry) => {
|
|
3025
|
+
const identity = entry[identityKey];
|
|
3026
|
+
const match = current.find((candidate) => candidate[identityKey] === identity);
|
|
3027
|
+
if (!match) {
|
|
3028
|
+
current.push(entry);
|
|
3029
|
+
return true;
|
|
3030
|
+
}
|
|
3031
|
+
if (conflictKeys.some((key) => !isDeepStrictEqual(match[key], entry[key]))) throw new Error(`[vitehub] Cloudflare ${identityKey} ${JSON.stringify(identity)} from ${owner} is already assigned to an incompatible resource.`);
|
|
3032
|
+
return false;
|
|
3033
|
+
});
|
|
3034
|
+
}
|
|
3035
|
+
function removeEntries(existing, entries) {
|
|
3036
|
+
if (!Array.isArray(existing) || !entries?.length) return Array.isArray(existing) ? existing : [];
|
|
3037
|
+
return existing.filter((entry) => !entries.some((previous) => isDeepStrictEqual(entry, previous)));
|
|
3038
|
+
}
|
|
3039
|
+
function removeContribution(wrangler, contribution) {
|
|
3040
|
+
const queues = cloneProviderRecord(wrangler.queues);
|
|
3041
|
+
const hasQueues = Boolean(contribution.queues?.consumers?.length || contribution.queues?.producers?.length);
|
|
3042
|
+
if (contribution.queues?.consumers?.length) {
|
|
3043
|
+
const consumers = removeEntries(queues.consumers, contribution.queues.consumers);
|
|
3044
|
+
if (consumers.length) queues.consumers = consumers;
|
|
3045
|
+
else delete queues.consumers;
|
|
3046
|
+
}
|
|
3047
|
+
if (contribution.queues?.producers?.length) {
|
|
3048
|
+
const producers = removeEntries(queues.producers, contribution.queues.producers);
|
|
3049
|
+
if (producers.length) queues.producers = producers;
|
|
3050
|
+
else delete queues.producers;
|
|
3051
|
+
}
|
|
3052
|
+
const { queues: _queues, ...withoutQueues } = wrangler;
|
|
3053
|
+
return {
|
|
3054
|
+
...hasQueues ? withoutQueues : wrangler,
|
|
3055
|
+
...hasQueues && Object.keys(queues).length ? { queues } : {},
|
|
3056
|
+
...contribution.r2Buckets?.length ? { r2_buckets: removeEntries(wrangler.r2_buckets, contribution.r2Buckets) } : {},
|
|
3057
|
+
...contribution.rateLimits?.length ? { ratelimits: removeEntries(wrangler.ratelimits, contribution.rateLimits) } : {}
|
|
3058
|
+
};
|
|
3059
|
+
}
|
|
3060
|
+
function mergeContribution(wrangler, owner, contribution) {
|
|
3061
|
+
const queues = cloneProviderRecord(wrangler.queues);
|
|
3062
|
+
const consumers = compatibleEntries(queues.consumers, contribution.queues?.consumers, "queue", [], owner);
|
|
3063
|
+
const producers = compatibleEntries(queues.producers, contribution.queues?.producers, "binding", ["queue"], owner);
|
|
3064
|
+
const r2Buckets = compatibleEntries(wrangler.r2_buckets, contribution.r2Buckets, "binding", ["bucket_name"], owner);
|
|
3065
|
+
const rateLimits = compatibleEntries(wrangler.ratelimits, contribution.rateLimits, "name", ["namespace_id", "simple"], owner);
|
|
3066
|
+
const nextQueues = mergeProviderOutputConfig(queues, {
|
|
3067
|
+
...consumers.length ? { consumers } : {},
|
|
3068
|
+
...producers.length ? { producers } : {}
|
|
3069
|
+
}, { arrays: {
|
|
3070
|
+
consumers: { key: "queue" },
|
|
3071
|
+
producers: { key: "binding" }
|
|
3072
|
+
} });
|
|
3073
|
+
return [mergeProviderOutputConfig(wrangler, {
|
|
3074
|
+
...Object.keys(nextQueues).length ? { queues: nextQueues } : {},
|
|
3075
|
+
...r2Buckets.length ? { r2_buckets: r2Buckets } : {},
|
|
3076
|
+
...rateLimits.length ? { ratelimits: rateLimits } : {}
|
|
3077
|
+
}, { arrays: {
|
|
3078
|
+
r2_buckets: { key: "binding" },
|
|
3079
|
+
ratelimits: { key: "name" }
|
|
3080
|
+
} }), {
|
|
3081
|
+
queues: {
|
|
3082
|
+
consumers,
|
|
3083
|
+
producers
|
|
3084
|
+
},
|
|
3085
|
+
r2Buckets,
|
|
3086
|
+
rateLimits
|
|
3087
|
+
}];
|
|
3088
|
+
}
|
|
3089
|
+
function composeNitroCloudflareProviderOutput(config, value) {
|
|
3090
|
+
const nitro = cloneRecord(value);
|
|
3091
|
+
const cloudflare = cloneRecord(nitro.cloudflare);
|
|
3092
|
+
const catalog = useCloudflareProviderOutput(config);
|
|
3093
|
+
const inherited = value && typeof value === "object" ? value[cloudflareProviderOutputKey] ?? cloudflareProviderOutputByNitro.get(value) : void 0;
|
|
3094
|
+
if (inherited && inherited !== catalog) {
|
|
3095
|
+
for (const [owner, contribution] of inherited.appliedByOwner) catalog.appliedByOwner.set(owner, contribution);
|
|
3096
|
+
catalog.contributionsByOwner = new Map([...inherited.contributionsByOwner, ...catalog.contributionsByOwner]);
|
|
3097
|
+
}
|
|
3098
|
+
let wrangler = cloneProviderRecord(cloudflare.wrangler);
|
|
3099
|
+
for (const contribution of catalog.appliedByOwner.values()) wrangler = removeContribution(wrangler, contribution);
|
|
3100
|
+
catalog.appliedByOwner.clear();
|
|
3101
|
+
for (const [owner, contribution] of catalog.contributionsByOwner) {
|
|
3102
|
+
const [merged, applied] = mergeContribution(wrangler, owner, contribution);
|
|
3103
|
+
wrangler = merged;
|
|
3104
|
+
catalog.appliedByOwner.set(owner, applied);
|
|
3105
|
+
}
|
|
3106
|
+
const output = !Object.keys(cloudflare).length && !Object.keys(wrangler).length ? nitro : {
|
|
3107
|
+
...nitro,
|
|
3108
|
+
cloudflare: {
|
|
3109
|
+
...cloudflare,
|
|
3110
|
+
wrangler
|
|
3111
|
+
}
|
|
3112
|
+
};
|
|
3113
|
+
Object.defineProperty(output, cloudflareProviderOutputKey, {
|
|
3114
|
+
enumerable: true,
|
|
3115
|
+
value: catalog
|
|
3116
|
+
});
|
|
3117
|
+
cloudflareProviderOutputByNitro.set(output, catalog);
|
|
3118
|
+
return output;
|
|
3119
|
+
}
|
|
3120
|
+
//#endregion
|
|
3121
|
+
//#region ../internal/src/build/deployment-output.ts
|
|
3122
|
+
const composedProviderOutputKey = Symbol.for("vitehub.composedProviderOutput");
|
|
3123
|
+
const providerDeploymentOutputWrites = /* @__PURE__ */ new Map();
|
|
3124
|
+
function useComposedProviderOutput(config) {
|
|
3125
|
+
const owner = config;
|
|
3126
|
+
return owner[composedProviderOutputKey] ??= {
|
|
3127
|
+
runtimeModuleFilesByProduct: {},
|
|
3128
|
+
vercelRuntimePackagesByProduct: {}
|
|
3129
|
+
};
|
|
3130
|
+
}
|
|
3131
|
+
function registerProviderRuntimeModules(composed, product, runtimeModuleFiles) {
|
|
3132
|
+
if (composed) composed.runtimeModuleFilesByProduct[product] = runtimeModuleFiles;
|
|
3133
|
+
}
|
|
3134
|
+
function resolveClientOutput(rootDir, clientOutDir) {
|
|
3135
|
+
const clientDir = resolve(rootDir, clientOutDir);
|
|
3136
|
+
return {
|
|
3137
|
+
clientDir,
|
|
3138
|
+
staticIndex: hasStaticIndex(clientDir)
|
|
3139
|
+
};
|
|
3140
|
+
}
|
|
3141
|
+
function createDefaultCloudflareStaticOutputDir(rootDir) {
|
|
3142
|
+
return resolve(rootDir, "dist", "client");
|
|
3143
|
+
}
|
|
3144
|
+
function createDefaultVercelOutputRoot(rootDir) {
|
|
3145
|
+
return resolve(rootDir, ".vercel", "output");
|
|
3146
|
+
}
|
|
3147
|
+
function createDefaultNetlifyOutputRoot(rootDir) {
|
|
3148
|
+
return resolve(rootDir, ".netlify", "v1");
|
|
3149
|
+
}
|
|
3150
|
+
function assertNetlifyFunctionName(functionName) {
|
|
3151
|
+
if (!functionName || functionName.includes("\\") || functionName.split("/").some((part) => !part || part === "." || part === "..")) throw new Error(`Invalid Netlify function name: ${functionName}`);
|
|
3152
|
+
}
|
|
3153
|
+
function resolveNetlifyFunctionFile(functionsRoot, functionName) {
|
|
3154
|
+
assertNetlifyFunctionName(functionName);
|
|
3155
|
+
return resolve(functionsRoot, `${functionName}.mjs`);
|
|
3156
|
+
}
|
|
3157
|
+
async function appendNetlifyFunctionConfig(outfile, config) {
|
|
3158
|
+
if (!config) return;
|
|
3159
|
+
await writeFile(outfile, `${(await readFile(outfile, "utf8")).trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
|
|
3160
|
+
}
|
|
3161
|
+
async function writeCloudflareDeploymentOutput(options) {
|
|
3162
|
+
const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
|
|
3163
|
+
const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
|
|
3164
|
+
const files = Object.entries(options.files ?? {});
|
|
3165
|
+
const workerOutfile = options.bundleEntry ? resolve(outputRoot, options.bundleOutfileName ?? "index.js") : void 0;
|
|
3166
|
+
if (workerOutfile && files.some(([fileName]) => resolve(outputRoot, fileName) === workerOutfile)) throw new Error(`Cloudflare output file conflicts with bundle outfile: ${workerOutfile}`);
|
|
3167
|
+
await mkdir(outputRoot, { recursive: true });
|
|
3168
|
+
const writes = [
|
|
3169
|
+
writeCloudflareWranglerConfig({
|
|
3170
|
+
outputRoot,
|
|
3171
|
+
rootDir: options.rootDir,
|
|
3172
|
+
wranglerConfig: options.wranglerConfig,
|
|
3173
|
+
wranglerConfigOwnership: options.wranglerConfigOwnership ?? { keys: options.wranglerConfigKeys }
|
|
3174
|
+
}),
|
|
3175
|
+
options.bundleEntry && staticIndex ? copyClientOutput(clientDir, options.staticOutputDir ?? createDefaultCloudflareStaticOutputDir(options.rootDir)) : Promise.resolve(),
|
|
3176
|
+
...files.map(([fileName, contents]) => writeFile(resolve(outputRoot, fileName), contents, "utf8"))
|
|
3177
|
+
];
|
|
3178
|
+
if (options.bundleEntry && workerOutfile) {
|
|
3179
|
+
await rm(workerOutfile, {
|
|
3180
|
+
force: true,
|
|
3181
|
+
recursive: true
|
|
3182
|
+
});
|
|
3183
|
+
writes.push(bundleEsmEntry(options.bundleEntry, workerOutfile, {
|
|
3184
|
+
...options.bundleOptions,
|
|
3185
|
+
rootDir: options.rootDir
|
|
3186
|
+
}));
|
|
3187
|
+
}
|
|
3188
|
+
await Promise.all(writes);
|
|
3189
|
+
}
|
|
3190
|
+
async function writeVercelDeploymentOutput(options) {
|
|
3191
|
+
const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
|
|
3192
|
+
const outputRoot = options.outputRoot ?? createDefaultVercelOutputRoot(options.rootDir);
|
|
3193
|
+
const functionOutput = options.function ?? { kind: "root" };
|
|
3194
|
+
const serverFunctionName = functionOutput.kind === "root" ? "__server.func" : functionOutput.name;
|
|
3195
|
+
const config = options.config ?? (functionOutput.kind === "root" ? createVercelConfigJson() : {});
|
|
3196
|
+
const serverDir = resolve(outputRoot, "functions", serverFunctionName);
|
|
3197
|
+
const serverEntry = resolve(serverDir, "index.mjs");
|
|
3198
|
+
await mkdir(serverDir, { recursive: true });
|
|
3199
|
+
const staleFiles = (await readdir(serverDir)).filter((file) => file !== "node_modules");
|
|
3200
|
+
await Promise.all(staleFiles.map((file) => rm(resolve(serverDir, file), {
|
|
3201
|
+
force: true,
|
|
3202
|
+
recursive: true
|
|
3203
|
+
})));
|
|
3204
|
+
await Promise.all([
|
|
3205
|
+
bundleEsmEntry(options.bundleEntry, serverEntry, {
|
|
3206
|
+
...options.bundleOptions,
|
|
3207
|
+
rootDir: options.rootDir
|
|
3208
|
+
}),
|
|
3209
|
+
writeFile(resolve(serverDir, ".vc-config.json"), `${stringifyProviderOutputConfig(options.functionConfig ?? createNodeFunctionConfig())}\n`, "utf8"),
|
|
3210
|
+
writeProviderOutputConfig(resolve(outputRoot, "config.json"), config, { keys: options.configKeys }),
|
|
3211
|
+
staticIndex ? copyClientOutput(clientDir, options.staticOutputDir ?? resolve(outputRoot, "static")) : Promise.resolve()
|
|
3212
|
+
]);
|
|
3213
|
+
}
|
|
3214
|
+
async function writeNetlifyDeploymentOutput(options) {
|
|
3215
|
+
const outputRoot = options.outputRoot ?? createDefaultNetlifyOutputRoot(options.rootDir);
|
|
3216
|
+
const functionsRoot = resolve(outputRoot, "functions");
|
|
3217
|
+
const functionWrites = (options.functions ?? []).map(async (func) => {
|
|
3218
|
+
const outfile = resolveNetlifyFunctionFile(functionsRoot, func.functionName);
|
|
3219
|
+
await rm(outfile, {
|
|
3220
|
+
force: true,
|
|
3221
|
+
recursive: true
|
|
3222
|
+
});
|
|
3223
|
+
await mkdir(dirname(outfile), { recursive: true });
|
|
3224
|
+
await bundleEsmEntry(func.bundleEntry, outfile, {
|
|
3225
|
+
...func.bundleOptions,
|
|
3226
|
+
minifyIdentifiers: func.config ? true : func.bundleOptions.minifyIdentifiers,
|
|
3227
|
+
rootDir: options.rootDir
|
|
3228
|
+
});
|
|
3229
|
+
await appendNetlifyFunctionConfig(outfile, func.config);
|
|
3230
|
+
});
|
|
3231
|
+
await mkdir(outputRoot, { recursive: true });
|
|
3232
|
+
await Promise.all([writeProviderOutputConfig(resolve(outputRoot, "config.json"), options.config ?? {}, { keys: options.configKeys }), ...functionWrites]);
|
|
3233
|
+
}
|
|
3234
|
+
async function cleanupCloudflareDeploymentOutput(rootDir, cleanupInput) {
|
|
3235
|
+
const cleanup = typeof cleanupInput === "function" ? await cleanupInput() : cleanupInput;
|
|
3236
|
+
const outputRoot = cleanup.outputRoot ?? createDefaultCloudflareOutputRoot(rootDir);
|
|
3237
|
+
const writes = (cleanup.fileNames ?? []).map((fileName) => rm(resolve(outputRoot, fileName), {
|
|
3238
|
+
force: true,
|
|
3239
|
+
recursive: true
|
|
3240
|
+
}));
|
|
3241
|
+
writes.push(writeCloudflareWranglerConfig({
|
|
3242
|
+
outputRoot,
|
|
3243
|
+
rootDir,
|
|
3244
|
+
wranglerConfigOwnership: cleanup.wranglerConfigOwnership
|
|
3245
|
+
}));
|
|
3246
|
+
await Promise.all(writes);
|
|
3247
|
+
try {
|
|
3248
|
+
await rmdir(outputRoot);
|
|
3249
|
+
} catch (error) {
|
|
3250
|
+
const code = error.code;
|
|
3251
|
+
if (code !== "ENOENT" && code !== "ENOTEMPTY") throw error;
|
|
3252
|
+
}
|
|
3253
|
+
}
|
|
3254
|
+
async function cleanupVercelDeploymentOutput(rootDir, cleanup) {
|
|
3255
|
+
const outputRoot = cleanup.outputRoot ?? createDefaultVercelOutputRoot(rootDir);
|
|
3256
|
+
const writes = [];
|
|
3257
|
+
if (cleanup.serverFunctionName) writes.push(rm(resolve(outputRoot, "functions", cleanup.serverFunctionName), {
|
|
3258
|
+
force: true,
|
|
3259
|
+
recursive: true
|
|
3260
|
+
}));
|
|
3261
|
+
writes.push(cleanProviderOutputConfig(resolve(outputRoot, "config.json"), { keys: cleanup.configKeys }));
|
|
3262
|
+
await Promise.all(writes);
|
|
3263
|
+
}
|
|
3264
|
+
async function cleanupVercelDeploymentOutputs(rootDir, cleanup) {
|
|
3265
|
+
await Promise.all((Array.isArray(cleanup) ? cleanup : [cleanup]).map((item) => cleanupVercelDeploymentOutput(rootDir, item)));
|
|
3266
|
+
}
|
|
3267
|
+
async function cleanupNetlifyDeploymentOutput(rootDir, cleanup) {
|
|
3268
|
+
const outputRoot = cleanup.outputRoot ?? createDefaultNetlifyOutputRoot(rootDir);
|
|
3269
|
+
const functionsRoot = resolve(outputRoot, "functions");
|
|
3270
|
+
const writes = (cleanup.functionNames ?? []).map((functionName) => rm(resolveNetlifyFunctionFile(functionsRoot, functionName), {
|
|
3271
|
+
force: true,
|
|
3272
|
+
recursive: true
|
|
3273
|
+
}));
|
|
3274
|
+
writes.push(cleanProviderOutputConfig(resolve(outputRoot, "config.json"), { keys: cleanup.configKeys }));
|
|
3275
|
+
await Promise.all(writes);
|
|
3276
|
+
}
|
|
3277
|
+
async function writeProviderDeploymentOutputsNow(options) {
|
|
3278
|
+
const writes = [];
|
|
3279
|
+
if (options.cloudflare) writes.push(writeCloudflareDeploymentOutput({
|
|
3280
|
+
...options.cloudflare,
|
|
3281
|
+
clientOutDir: options.clientOutDir,
|
|
3282
|
+
rootDir: options.rootDir
|
|
3283
|
+
}));
|
|
3284
|
+
else if (options.cleanup?.cloudflare) writes.push(cleanupCloudflareDeploymentOutput(options.rootDir, options.cleanup.cloudflare));
|
|
3285
|
+
if (options.netlify) writes.push(writeNetlifyDeploymentOutput({
|
|
3286
|
+
...options.netlify,
|
|
3287
|
+
clientOutDir: options.clientOutDir,
|
|
3288
|
+
rootDir: options.rootDir
|
|
3289
|
+
}));
|
|
3290
|
+
else if (options.cleanup?.netlify) writes.push(cleanupNetlifyDeploymentOutput(options.rootDir, options.cleanup.netlify));
|
|
3291
|
+
if (options.vercel) writes.push(writeVercelDeploymentOutput({
|
|
3292
|
+
...options.vercel,
|
|
3293
|
+
clientOutDir: options.clientOutDir,
|
|
3294
|
+
rootDir: options.rootDir
|
|
3295
|
+
}));
|
|
3296
|
+
else if (options.cleanup?.vercel) {
|
|
3297
|
+
const cleanup = typeof options.cleanup.vercel === "function" ? await options.cleanup.vercel() : options.cleanup.vercel;
|
|
3298
|
+
if (cleanup) writes.push(cleanupVercelDeploymentOutputs(options.rootDir, cleanup));
|
|
3299
|
+
}
|
|
3300
|
+
await Promise.all(writes);
|
|
3301
|
+
await options.afterWrite?.();
|
|
3302
|
+
}
|
|
3303
|
+
async function writeProviderDeploymentOutputs(options) {
|
|
3304
|
+
const key = resolve(options.rootDir);
|
|
3305
|
+
const write = (providerDeploymentOutputWrites.get(key) ?? Promise.resolve()).catch(() => void 0).then(() => writeProviderDeploymentOutputsNow(options));
|
|
3306
|
+
providerDeploymentOutputWrites.set(key, write);
|
|
3307
|
+
try {
|
|
3308
|
+
await write;
|
|
3309
|
+
} finally {
|
|
3310
|
+
if (providerDeploymentOutputWrites.get(key) === write) providerDeploymentOutputWrites.delete(key);
|
|
3311
|
+
}
|
|
3312
|
+
}
|
|
3313
|
+
//#endregion
|
|
3314
|
+
//#region ../internal/src/definition-catalog.ts
|
|
3315
|
+
const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
|
|
3316
|
+
const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
|
|
3317
|
+
const ignoredDirs = new Set([
|
|
3318
|
+
"node_modules",
|
|
3319
|
+
"dist",
|
|
3320
|
+
".output",
|
|
3321
|
+
".nuxt",
|
|
3322
|
+
".vercel",
|
|
3323
|
+
".git",
|
|
3324
|
+
".vitehub"
|
|
3325
|
+
]);
|
|
3326
|
+
function resolveDefinitionScanRoots(rootDir, scanDirs = []) {
|
|
3327
|
+
return [...new Set([rootDir, ...scanDirs].filter(Boolean))];
|
|
3328
|
+
}
|
|
3329
|
+
function readDirEntries(root) {
|
|
3330
|
+
try {
|
|
3331
|
+
return readdirSync(root, { withFileTypes: true });
|
|
3332
|
+
} catch (error) {
|
|
3333
|
+
if (error.code === "ENOENT") return [];
|
|
3334
|
+
throw error;
|
|
3335
|
+
}
|
|
3336
|
+
}
|
|
3337
|
+
function listMatchingFiles(root, predicate, options = {}) {
|
|
3338
|
+
const files = [];
|
|
3339
|
+
for (const entry of readDirEntries(root)) {
|
|
3340
|
+
const absolute = resolve$1(root, entry.name);
|
|
3341
|
+
if (entry.isDirectory() && !entry.isSymbolicLink()) {
|
|
3342
|
+
if (entry.name.startsWith(".")) continue;
|
|
3343
|
+
if (ignoredDirs.has(entry.name)) continue;
|
|
3344
|
+
files.push(...listMatchingFiles(absolute, predicate, options));
|
|
3345
|
+
continue;
|
|
3346
|
+
}
|
|
3347
|
+
if (entry.name.startsWith(".") && !options.includeHidden) continue;
|
|
3348
|
+
if (entry.isFile() && predicate(entry.name)) files.push(absolute);
|
|
3349
|
+
}
|
|
3350
|
+
return files.sort();
|
|
3351
|
+
}
|
|
3352
|
+
function listSourceFiles(root, options = {}) {
|
|
3353
|
+
return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
|
|
3354
|
+
}
|
|
3355
|
+
async function writeFileIfChanged(file, contents) {
|
|
3356
|
+
if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
|
|
3357
|
+
await mkdir(resolve$1(file, ".."), { recursive: true });
|
|
3358
|
+
await writeFile(file, contents, "utf8");
|
|
3359
|
+
}
|
|
3360
|
+
function deploymentPresetFromNitro(value) {
|
|
3361
|
+
const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
|
|
3362
|
+
if (!normalized) return;
|
|
3363
|
+
if (normalized.startsWith("cloudflare")) return "cloudflare";
|
|
3364
|
+
if (normalized.startsWith("deno")) return "deno";
|
|
3365
|
+
if (normalized.startsWith("netlify")) return "netlify";
|
|
3366
|
+
if (normalized === "node" || normalized.startsWith("node-")) return "node";
|
|
3367
|
+
if (normalized.startsWith("vercel")) return "vercel";
|
|
3368
|
+
}
|
|
3369
|
+
//#endregion
|
|
3370
|
+
//#region ../internal/src/hosting.ts
|
|
3371
|
+
function getHostingProvider(hosting) {
|
|
3372
|
+
const preset = deploymentPresetFromNitro(hosting);
|
|
3373
|
+
if (preset === "cloudflare" || preset === "netlify" || preset === "vercel") return preset;
|
|
3374
|
+
}
|
|
3375
|
+
//#endregion
|
|
3376
|
+
//#region src/discovery.ts
|
|
3377
|
+
const rateLimitImports = new Set(["@vite-hub/rate-limit", "vite-hub/rate-limit"]);
|
|
3378
|
+
const ignoredSourceDirectories = new Set([
|
|
3379
|
+
"__tests__",
|
|
3380
|
+
"test",
|
|
3381
|
+
"tests"
|
|
3382
|
+
]);
|
|
3383
|
+
const nestedIgnoredSourceDirectories = new Set(["__tests__", "tests"]);
|
|
3384
|
+
function isApplicationSource(root, file) {
|
|
3385
|
+
const segments = relative(root, file).split(/[\\/]/);
|
|
3386
|
+
if (segments.length > 1 && ignoredSourceDirectories.has(segments[0])) return false;
|
|
3387
|
+
if (segments.slice(1, -1).some((segment) => nestedIgnoredSourceDirectories.has(segment))) return false;
|
|
3388
|
+
return !/\.(?:spec|test)\.(?:c|m)?[jt]sx?$/i.test(basename(file));
|
|
3389
|
+
}
|
|
3390
|
+
function location(source, offset) {
|
|
3391
|
+
const lines = source.slice(0, offset).split("\n");
|
|
3392
|
+
return {
|
|
3393
|
+
column: (lines.at(-1)?.length ?? 0) + 1,
|
|
3394
|
+
line: lines.length
|
|
3395
|
+
};
|
|
3396
|
+
}
|
|
3397
|
+
function declarationError(file, source, node, message) {
|
|
3398
|
+
const { column, line } = location(source, node.start);
|
|
3399
|
+
return /* @__PURE__ */ new Error(`[vitehub] ${message}\n at ${file}:${line}:${column}`);
|
|
3400
|
+
}
|
|
3401
|
+
function requireRateLimitBindings(program) {
|
|
3402
|
+
const bindings = {
|
|
3403
|
+
direct: /* @__PURE__ */ new Set(),
|
|
3404
|
+
namespaces: /* @__PURE__ */ new Set()
|
|
3405
|
+
};
|
|
3406
|
+
for (const statement of program.body) {
|
|
3407
|
+
if (statement.type !== "ImportDeclaration" || !rateLimitImports.has(statement.source.value)) continue;
|
|
3408
|
+
for (const specifier of statement.specifiers) {
|
|
3409
|
+
if (specifier.type === "ImportSpecifier" && specifier.imported.type === "Identifier" && specifier.imported.name === "requireRateLimit") bindings.direct.add(specifier.local.name);
|
|
3410
|
+
if (specifier.type === "ImportNamespaceSpecifier") bindings.namespaces.add(specifier.local.name);
|
|
3411
|
+
}
|
|
3412
|
+
}
|
|
3413
|
+
return bindings;
|
|
3414
|
+
}
|
|
3415
|
+
function resolveRateLimitBinding(name, kind, scopes) {
|
|
3416
|
+
for (let index = scopes.length - 1; index >= 0; index -= 1) {
|
|
3417
|
+
const scope = scopes[index];
|
|
3418
|
+
if (scope[kind].has(name)) return true;
|
|
3419
|
+
if (scope.shadows.has(name)) return false;
|
|
3420
|
+
}
|
|
3421
|
+
return false;
|
|
3422
|
+
}
|
|
3423
|
+
function rateLimitBindingName(callee, scopes) {
|
|
3424
|
+
if (callee.type === "Identifier" && resolveRateLimitBinding(callee.name, "direct", scopes)) return callee.name;
|
|
3425
|
+
if (callee.type !== "MemberExpression" || callee.object.type !== "Identifier" || !resolveRateLimitBinding(callee.object.name, "namespaces", scopes)) return;
|
|
3426
|
+
return (callee.computed ? callee.property.type === "Literal" ? callee.property.value : void 0 : callee.property.type === "Identifier" ? callee.property.name : void 0) === "requireRateLimit" ? callee.object.name : void 0;
|
|
3427
|
+
}
|
|
3428
|
+
function rateLimitDynamicImport(expression) {
|
|
3429
|
+
if (!expression) return false;
|
|
3430
|
+
const value = unwrapStaticExpression(expression);
|
|
3431
|
+
if (value.type !== "AwaitExpression") return false;
|
|
3432
|
+
const imported = unwrapStaticExpression(value.argument);
|
|
3433
|
+
const source = imported.type === "ImportExpression" ? staticString(imported.source)?.trim() : void 0;
|
|
3434
|
+
return Boolean(source && rateLimitImports.has(source));
|
|
3435
|
+
}
|
|
3436
|
+
function addDynamicRateLimitBindings(declaration, scope) {
|
|
3437
|
+
if (declaration.kind !== "const") return;
|
|
3438
|
+
for (const declarator of declaration.declarations) {
|
|
3439
|
+
if (!rateLimitDynamicImport(declarator.init)) continue;
|
|
3440
|
+
if (declarator.id.type === "Identifier") {
|
|
3441
|
+
scope.shadows.delete(declarator.id.name);
|
|
3442
|
+
scope.namespaces.add(declarator.id.name);
|
|
3443
|
+
continue;
|
|
3444
|
+
}
|
|
3445
|
+
if (declarator.id.type !== "ObjectPattern") continue;
|
|
3446
|
+
for (const property of declarator.id.properties) {
|
|
3447
|
+
if (property.type !== "Property") continue;
|
|
3448
|
+
if ((property.computed ? property.key.type === "Literal" ? property.key.value : void 0 : property.key.type === "Identifier" ? property.key.name : void 0) !== "requireRateLimit") continue;
|
|
3449
|
+
const value = property.value.type === "AssignmentPattern" ? property.value.left : property.value;
|
|
3450
|
+
if (value.type !== "Identifier") continue;
|
|
3451
|
+
scope.shadows.delete(value.name);
|
|
3452
|
+
scope.direct.add(value.name);
|
|
3453
|
+
}
|
|
3454
|
+
}
|
|
3455
|
+
}
|
|
3456
|
+
function variableDeclaration(statement) {
|
|
3457
|
+
if (statement.type === "VariableDeclaration") return statement;
|
|
3458
|
+
if (statement.type === "ExportNamedDeclaration" && statement.declaration?.type === "VariableDeclaration") return statement.declaration;
|
|
3459
|
+
}
|
|
3460
|
+
function addDynamicRateLimitBindingsFromStatements(statements, scope) {
|
|
3461
|
+
for (const statement of statements) {
|
|
3462
|
+
const declaration = variableDeclaration(statement);
|
|
3463
|
+
if (declaration) addDynamicRateLimitBindings(declaration, scope);
|
|
3464
|
+
}
|
|
3465
|
+
}
|
|
3466
|
+
function addBindingNames(pattern, names) {
|
|
3467
|
+
if (pattern.type === "Identifier") {
|
|
3468
|
+
names.add(pattern.name);
|
|
3469
|
+
return;
|
|
3470
|
+
}
|
|
3471
|
+
if (pattern.type === "TSParameterProperty") {
|
|
3472
|
+
addBindingNames(pattern.parameter, names);
|
|
3473
|
+
return;
|
|
3474
|
+
}
|
|
3475
|
+
if (pattern.type === "RestElement") {
|
|
3476
|
+
addBindingNames(pattern.argument, names);
|
|
3477
|
+
return;
|
|
3478
|
+
}
|
|
3479
|
+
if (pattern.type === "AssignmentPattern") {
|
|
3480
|
+
addBindingNames(pattern.left, names);
|
|
3481
|
+
return;
|
|
3482
|
+
}
|
|
3483
|
+
if (pattern.type === "ArrayPattern") {
|
|
3484
|
+
for (const element of pattern.elements) if (element) addBindingNames(element, names);
|
|
3485
|
+
return;
|
|
3486
|
+
}
|
|
3487
|
+
for (const property of pattern.properties) addBindingNames(property.type === "RestElement" ? property.argument : property.value, names);
|
|
3488
|
+
}
|
|
3489
|
+
function functionBindings(params) {
|
|
3490
|
+
const names = /* @__PURE__ */ new Set();
|
|
3491
|
+
for (const parameter of params) addBindingNames(parameter, names);
|
|
3492
|
+
return names;
|
|
3493
|
+
}
|
|
3494
|
+
function variableBindings(declaration) {
|
|
3495
|
+
const names = /* @__PURE__ */ new Set();
|
|
3496
|
+
for (const declarator of declaration?.declarations ?? []) addBindingNames(declarator.id, names);
|
|
3497
|
+
return names;
|
|
3498
|
+
}
|
|
3499
|
+
function blockBindings(block) {
|
|
3500
|
+
const names = /* @__PURE__ */ new Set();
|
|
3501
|
+
for (const statement of block.body) {
|
|
3502
|
+
if ((statement.type === "FunctionDeclaration" || statement.type === "ClassDeclaration") && statement.id) names.add(statement.id.name);
|
|
3503
|
+
const declaration = statement.type === "VariableDeclaration" ? statement : statement.type === "ExportNamedDeclaration" && statement.declaration?.type === "VariableDeclaration" ? statement.declaration : void 0;
|
|
3504
|
+
for (const declarator of declaration?.declarations ?? []) addBindingNames(declarator.id, names);
|
|
3505
|
+
}
|
|
3506
|
+
return names;
|
|
3507
|
+
}
|
|
3508
|
+
function switchBindings(statement) {
|
|
3509
|
+
const names = /* @__PURE__ */ new Set();
|
|
3510
|
+
for (const switchCase of statement.cases) for (const child of switchCase.consequent) {
|
|
3511
|
+
if ((child.type === "FunctionDeclaration" || child.type === "ClassDeclaration") && child.id) names.add(child.id.name);
|
|
3512
|
+
if (child.type === "VariableDeclaration") for (const name of variableBindings(child)) names.add(name);
|
|
3513
|
+
}
|
|
3514
|
+
return names;
|
|
3515
|
+
}
|
|
3516
|
+
function staticPropertyName(property) {
|
|
3517
|
+
if (property.computed || property.kind !== "init" || property.method) return;
|
|
3518
|
+
if (property.key.type === "Identifier") return property.key.name;
|
|
3519
|
+
if (property.key.type === "Literal" && typeof property.key.value === "string") return property.key.value;
|
|
3520
|
+
}
|
|
3521
|
+
function unwrapStaticExpression(expression) {
|
|
3522
|
+
while (expression.type === "TSAsExpression" || expression.type === "TSSatisfiesExpression" || expression.type === "TSNonNullExpression") expression = expression.expression;
|
|
3523
|
+
return expression;
|
|
3524
|
+
}
|
|
3525
|
+
function staticString(expression) {
|
|
3526
|
+
const value = unwrapStaticExpression(expression);
|
|
3527
|
+
if (value.type === "Literal" && typeof value.value === "string") return value.value;
|
|
3528
|
+
if (value.type === "TemplateLiteral" && value.expressions.length === 0) return value.quasis[0]?.value.cooked ?? value.quasis[0]?.value.raw;
|
|
3529
|
+
}
|
|
3530
|
+
function staticPolicy(call, file, source) {
|
|
3531
|
+
const policyArgument = call.arguments[2];
|
|
3532
|
+
const policyNode = policyArgument?.type === "SpreadElement" ? policyArgument : policyArgument && unwrapStaticExpression(policyArgument);
|
|
3533
|
+
if (!policyNode || policyNode.type !== "ObjectExpression") throw declarationError(file, source, call, "`requireRateLimit()` requires a static options object as its third argument.");
|
|
3534
|
+
const values = /* @__PURE__ */ new Map();
|
|
3535
|
+
for (const property of policyNode.properties) {
|
|
3536
|
+
if (property.type !== "Property") throw declarationError(file, source, property, "`requireRateLimit()` options cannot use object spreads.");
|
|
3537
|
+
const name = staticPropertyName(property);
|
|
3538
|
+
if (name === "key") continue;
|
|
3539
|
+
if (!name || !rateLimitPolicyKeys.has(name)) throw declarationError(file, source, property, `\`requireRateLimit()\` does not support the ${name ? `"${name}"` : "dynamic"} option.`);
|
|
3540
|
+
const value = unwrapStaticExpression(property.value);
|
|
3541
|
+
const literal = value.type === "Literal" && typeof value.value === "number" ? value.value : staticString(value);
|
|
3542
|
+
if (literal === void 0) throw declarationError(file, source, property.value, `\`requireRateLimit()\` policy option "${name}" must be a static literal.`);
|
|
3543
|
+
values.set(name, literal);
|
|
3544
|
+
}
|
|
3545
|
+
const policy = {
|
|
3546
|
+
...values.has("enforcement") ? { enforcement: values.get("enforcement") } : {},
|
|
3547
|
+
...values.has("failure") ? { failure: values.get("failure") } : {},
|
|
3548
|
+
limit: values.get("limit"),
|
|
3549
|
+
window: values.get("window")
|
|
3550
|
+
};
|
|
3551
|
+
try {
|
|
3552
|
+
return declaredRateLimitPolicy(normalizeRateLimitPolicy(policy));
|
|
3553
|
+
} catch (error) {
|
|
3554
|
+
throw declarationError(file, source, policyNode, error instanceof Error ? error.message : String(error));
|
|
3555
|
+
}
|
|
3556
|
+
}
|
|
3557
|
+
function extractRateLimitDeclarations(file, source) {
|
|
3558
|
+
if (!source.includes("requireRateLimit")) return [];
|
|
3559
|
+
const parsed = parseSync(file, source);
|
|
3560
|
+
if (parsed.errors.length > 0) throw new Error(`[vitehub] Could not parse ${file} while collecting Rate Limits: ${parsed.errors[0]?.message}`);
|
|
3561
|
+
const bindings = requireRateLimitBindings(parsed.program);
|
|
3562
|
+
const declarations = [];
|
|
3563
|
+
const scopes = [{
|
|
3564
|
+
...bindings,
|
|
3565
|
+
shadows: /* @__PURE__ */ new Set()
|
|
3566
|
+
}];
|
|
3567
|
+
addDynamicRateLimitBindingsFromStatements(parsed.program.body, scopes[0]);
|
|
3568
|
+
const enterScope = (shadows) => {
|
|
3569
|
+
scopes.push({
|
|
3570
|
+
direct: /* @__PURE__ */ new Set(),
|
|
3571
|
+
namespaces: /* @__PURE__ */ new Set(),
|
|
3572
|
+
shadows
|
|
3573
|
+
});
|
|
3574
|
+
};
|
|
3575
|
+
const enterFunction = (node) => {
|
|
3576
|
+
const shadows = functionBindings(node.params);
|
|
3577
|
+
if (node.type === "FunctionExpression" && node.id) shadows.add(node.id.name);
|
|
3578
|
+
enterScope(shadows);
|
|
3579
|
+
};
|
|
3580
|
+
const exitScope = () => {
|
|
3581
|
+
scopes.pop();
|
|
3582
|
+
};
|
|
3583
|
+
new Visitor({
|
|
3584
|
+
ArrowFunctionExpression: enterFunction,
|
|
3585
|
+
"ArrowFunctionExpression:exit": exitScope,
|
|
3586
|
+
BlockStatement(block) {
|
|
3587
|
+
enterScope(blockBindings(block));
|
|
3588
|
+
addDynamicRateLimitBindingsFromStatements(block.body, scopes.at(-1));
|
|
3589
|
+
},
|
|
3590
|
+
"BlockStatement:exit": exitScope,
|
|
3591
|
+
CatchClause(clause) {
|
|
3592
|
+
const names = /* @__PURE__ */ new Set();
|
|
3593
|
+
if (clause.param) addBindingNames(clause.param, names);
|
|
3594
|
+
enterScope(names);
|
|
3595
|
+
},
|
|
3596
|
+
"CatchClause:exit": exitScope,
|
|
3597
|
+
ClassExpression(node) {
|
|
3598
|
+
enterScope(new Set(node.id ? [node.id.name] : []));
|
|
3599
|
+
},
|
|
3600
|
+
"ClassExpression:exit": exitScope,
|
|
3601
|
+
CallExpression(call) {
|
|
3602
|
+
if (!rateLimitBindingName(call.callee, scopes)) return;
|
|
3603
|
+
if (call.arguments.length !== 3) throw declarationError(file, source, call, "`requireRateLimit()` requires an event, a stable ID, and a static options object.");
|
|
3604
|
+
const idNode = call.arguments[1];
|
|
3605
|
+
const staticId = idNode?.type === "SpreadElement" ? void 0 : idNode && staticString(idNode);
|
|
3606
|
+
if (!staticId?.trim()) throw declarationError(file, source, idNode ?? call, "`requireRateLimit()` requires a non-empty static string ID.");
|
|
3607
|
+
const id = staticId.trim();
|
|
3608
|
+
const sourceLocation = location(source, call.start);
|
|
3609
|
+
declarations.push({
|
|
3610
|
+
name: id,
|
|
3611
|
+
policy: staticPolicy(call, file, source),
|
|
3612
|
+
source: {
|
|
3613
|
+
file,
|
|
3614
|
+
...sourceLocation
|
|
3615
|
+
}
|
|
3616
|
+
});
|
|
3617
|
+
},
|
|
3618
|
+
FunctionDeclaration: enterFunction,
|
|
3619
|
+
"FunctionDeclaration:exit": exitScope,
|
|
3620
|
+
FunctionExpression: enterFunction,
|
|
3621
|
+
"FunctionExpression:exit": exitScope,
|
|
3622
|
+
ForInStatement(node) {
|
|
3623
|
+
enterScope(node.left.type === "VariableDeclaration" ? variableBindings(node.left) : /* @__PURE__ */ new Set());
|
|
3624
|
+
},
|
|
3625
|
+
"ForInStatement:exit": exitScope,
|
|
3626
|
+
ForOfStatement(node) {
|
|
3627
|
+
enterScope(node.left.type === "VariableDeclaration" ? variableBindings(node.left) : /* @__PURE__ */ new Set());
|
|
3628
|
+
},
|
|
3629
|
+
"ForOfStatement:exit": exitScope,
|
|
3630
|
+
ForStatement(node) {
|
|
3631
|
+
enterScope(node.init?.type === "VariableDeclaration" ? variableBindings(node.init) : /* @__PURE__ */ new Set());
|
|
3632
|
+
},
|
|
3633
|
+
"ForStatement:exit": exitScope,
|
|
3634
|
+
SwitchStatement(node) {
|
|
3635
|
+
enterScope(switchBindings(node));
|
|
3636
|
+
for (const switchCase of node.cases) addDynamicRateLimitBindingsFromStatements(switchCase.consequent, scopes.at(-1));
|
|
3637
|
+
},
|
|
3638
|
+
"SwitchStatement:exit": exitScope
|
|
3639
|
+
}).visit(parsed.program);
|
|
3640
|
+
return declarations;
|
|
3641
|
+
}
|
|
3642
|
+
function discoverRateLimitCatalog(options) {
|
|
3643
|
+
const declarations = /* @__PURE__ */ new Map();
|
|
3644
|
+
const sourceFiles = new Set(resolveDefinitionScanRoots(options.rootDir, options.scanDirs).flatMap((root) => listSourceFiles(root).filter((file) => isApplicationSource(root, file))));
|
|
3645
|
+
const declarationFiles = /* @__PURE__ */ new Set();
|
|
3646
|
+
for (const file of sourceFiles) {
|
|
3647
|
+
const extracted = extractRateLimitDeclarations(file, readFileSync(file, "utf8"));
|
|
3648
|
+
if (extracted.length > 0) declarationFiles.add(file);
|
|
3649
|
+
for (const declaration of extracted) {
|
|
3650
|
+
const existing = declarations.get(declaration.name);
|
|
3651
|
+
if (existing && JSON.stringify(existing.policy) !== JSON.stringify(declaration.policy)) throw new Error([
|
|
3652
|
+
`[vitehub] Conflicting Rate Limit policies for ID "${declaration.name}":`,
|
|
3653
|
+
` - ${existing.source.file}:${existing.source.line}:${existing.source.column} ${JSON.stringify(existing.policy)}`,
|
|
3654
|
+
` - ${declaration.source.file}:${declaration.source.line}:${declaration.source.column} ${JSON.stringify(declaration.policy)}`
|
|
3655
|
+
].join("\n"));
|
|
3656
|
+
if (!existing) declarations.set(declaration.name, declaration);
|
|
3657
|
+
}
|
|
3658
|
+
}
|
|
3659
|
+
return {
|
|
3660
|
+
declarationFiles,
|
|
3661
|
+
declarations: [...declarations.values()].sort((left, right) => left.name.localeCompare(right.name))
|
|
3662
|
+
};
|
|
3663
|
+
}
|
|
3664
|
+
//#endregion
|
|
3665
|
+
//#region src/internal/manifest.ts
|
|
3666
|
+
const rateLimitManifestPath = ".vitehub/rate-limit/manifest.json";
|
|
3667
|
+
function resolveProviderCapabilities(provider) {
|
|
3668
|
+
return createRateLimiter({
|
|
3669
|
+
driver: provider === "cloudflare" ? cloudflareRateLimitDriver({ binding: { limit: async () => ({ success: true }) } }) : memoryRateLimitDriver(),
|
|
3670
|
+
limit: 1,
|
|
3671
|
+
window: "1m"
|
|
3672
|
+
}).capabilities;
|
|
3673
|
+
}
|
|
3674
|
+
function createRateLimitManifest(declarations, provider) {
|
|
3675
|
+
const capabilities = resolveProviderCapabilities(provider);
|
|
3676
|
+
return {
|
|
3677
|
+
schemaVersion: 2,
|
|
3678
|
+
rateLimits: [...declarations].sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0).map((definition) => ({
|
|
3679
|
+
name: definition.name,
|
|
3680
|
+
provider,
|
|
3681
|
+
capabilities
|
|
3682
|
+
}))
|
|
3683
|
+
};
|
|
3684
|
+
}
|
|
3685
|
+
async function writeRateLimitManifest(rootDir, declarations, provider) {
|
|
3686
|
+
const manifest = createRateLimitManifest(declarations, provider);
|
|
3687
|
+
await writeFileIfChanged(resolve(rootDir, rateLimitManifestPath), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
3688
|
+
}
|
|
3689
|
+
//#endregion
|
|
3690
|
+
//#region src/internal/provider-output.ts
|
|
3691
|
+
function outputStateFile(rootDir) {
|
|
3692
|
+
return resolve(rootDir, ".vitehub", "rate-limit", "cloudflare-output.json");
|
|
3693
|
+
}
|
|
3694
|
+
async function readOutputState(rootDir) {
|
|
3695
|
+
try {
|
|
3696
|
+
const parsed = JSON.parse(await readFile(outputStateFile(rootDir), "utf8"));
|
|
3697
|
+
return {
|
|
3698
|
+
bindings: Array.isArray(parsed.bindings) ? parsed.bindings.filter((value) => typeof value === "string") : [],
|
|
3699
|
+
standalone: parsed.standalone !== false && Array.isArray(parsed.bindings) && parsed.bindings.length > 0
|
|
3700
|
+
};
|
|
3701
|
+
} catch (error) {
|
|
3702
|
+
if (error.code === "ENOENT") return {
|
|
3703
|
+
bindings: [],
|
|
3704
|
+
standalone: false
|
|
3705
|
+
};
|
|
3706
|
+
throw error;
|
|
3707
|
+
}
|
|
3708
|
+
}
|
|
3709
|
+
async function writeOutputState(rootDir, bindings, standalone = false) {
|
|
3710
|
+
const file = outputStateFile(rootDir);
|
|
3711
|
+
if (bindings.length === 0) {
|
|
3712
|
+
await rm(file, { force: true });
|
|
3713
|
+
return;
|
|
3714
|
+
}
|
|
3715
|
+
await mkdir(dirname(file), { recursive: true });
|
|
3716
|
+
await writeFile(file, `${JSON.stringify({
|
|
3717
|
+
bindings,
|
|
3718
|
+
standalone
|
|
3719
|
+
}, null, 2)}\n`, "utf8");
|
|
3720
|
+
}
|
|
3721
|
+
function namespaceId(namespace, rateLimitId) {
|
|
3722
|
+
let hash = 2166136261;
|
|
3723
|
+
for (const character of `${namespace}:${rateLimitId}`) {
|
|
3724
|
+
hash ^= character.charCodeAt(0);
|
|
3725
|
+
hash = Math.imul(hash, 16777619);
|
|
3726
|
+
}
|
|
3727
|
+
return String(hash >>> 0 || 1);
|
|
3728
|
+
}
|
|
3729
|
+
function createCloudflareRateLimitBindings(declarations, namespace) {
|
|
3730
|
+
return declarations.map((declaration) => {
|
|
3731
|
+
const policy = normalizeRateLimitPolicy(declaration.policy);
|
|
3732
|
+
if (policy.enforcement === "strict") throw new Error(`Rate Limit "${declaration.name}" requires strict enforcement, but Cloudflare's native Rate Limiting binding is best-effort.`);
|
|
3733
|
+
const period = policy.windowMs / 1e3;
|
|
3734
|
+
if (period !== 10 && period !== 60) throw new Error(`Rate Limit "${declaration.name}" uses ${policy.window}, but Cloudflare Rate Limiting supports only 10s and 1m windows.`);
|
|
3735
|
+
return {
|
|
3736
|
+
name: getCloudflareRateLimitBindingName(declaration.name),
|
|
3737
|
+
namespace_id: namespaceId(namespace, declaration.name),
|
|
3738
|
+
simple: {
|
|
3739
|
+
limit: policy.limit,
|
|
3740
|
+
period
|
|
3741
|
+
}
|
|
3742
|
+
};
|
|
3743
|
+
});
|
|
3744
|
+
}
|
|
3745
|
+
function resolveRateLimitNamespace(configured) {
|
|
3746
|
+
return configured?.trim() || void 0;
|
|
3747
|
+
}
|
|
3748
|
+
async function writeRateLimitProviderOutput(options) {
|
|
3749
|
+
const state = await readOutputState(options.rootDir);
|
|
3750
|
+
const currentBindings = options.declarations.map((declaration) => getCloudflareRateLimitBindingName(declaration.name));
|
|
3751
|
+
const previousBindings = options.previousDeclarations?.map((declaration) => getCloudflareRateLimitBindingName(declaration.name)) ?? [];
|
|
3752
|
+
const ownership = { arrays: { ratelimits: {
|
|
3753
|
+
key: "name",
|
|
3754
|
+
values: [...new Set([
|
|
3755
|
+
...state.bindings,
|
|
3756
|
+
...previousBindings,
|
|
3757
|
+
...currentBindings
|
|
3758
|
+
])]
|
|
3759
|
+
} } };
|
|
3760
|
+
if (options.cloudflareOwnedByNitro) {
|
|
3761
|
+
if (options.provider === "cloudflare" && options.declarations.length > 0 && !options.namespace) throw new Error("[vitehub] Cloudflare Rate Limit requires rateLimit.namespace to isolate counters between deployments.");
|
|
3762
|
+
if (state.standalone && state.bindings.length > 0) await writeProviderDeploymentOutputs({
|
|
3763
|
+
clientOutDir: options.clientOutDir,
|
|
3764
|
+
cleanup: { cloudflare: {
|
|
3765
|
+
outputRoot: createDefaultCloudflareOutputRoot(options.rootDir),
|
|
3766
|
+
wranglerConfigOwnership: { arrays: { ratelimits: {
|
|
3767
|
+
key: "name",
|
|
3768
|
+
values: state.bindings
|
|
3769
|
+
} } }
|
|
3770
|
+
} },
|
|
3771
|
+
rootDir: options.rootDir
|
|
3772
|
+
});
|
|
3773
|
+
await writeOutputState(options.rootDir, []);
|
|
3774
|
+
await writeRateLimitManifest(options.rootDir, options.declarations, options.provider);
|
|
3775
|
+
return;
|
|
3776
|
+
}
|
|
3777
|
+
if (options.provider === "cloudflare" && options.declarations.length > 0) {
|
|
3778
|
+
if (!options.namespace) throw new Error("[vitehub] Cloudflare Rate Limit requires rateLimit.namespace to isolate counters between deployments.");
|
|
3779
|
+
await writeProviderDeploymentOutputs({
|
|
3780
|
+
clientOutDir: options.clientOutDir,
|
|
3781
|
+
cloudflare: {
|
|
3782
|
+
outputRoot: createDefaultCloudflareOutputRoot(options.rootDir),
|
|
3783
|
+
wranglerConfig: { ratelimits: createCloudflareRateLimitBindings(options.declarations, options.namespace) },
|
|
3784
|
+
wranglerConfigOwnership: ownership
|
|
3785
|
+
},
|
|
3786
|
+
rootDir: options.rootDir
|
|
3787
|
+
});
|
|
3788
|
+
await writeOutputState(options.rootDir, currentBindings, true);
|
|
3789
|
+
await writeRateLimitManifest(options.rootDir, options.declarations, options.provider);
|
|
3790
|
+
return;
|
|
3791
|
+
}
|
|
3792
|
+
await writeProviderDeploymentOutputs({
|
|
3793
|
+
clientOutDir: options.clientOutDir,
|
|
3794
|
+
cleanup: { cloudflare: {
|
|
3795
|
+
outputRoot: createDefaultCloudflareOutputRoot(options.rootDir),
|
|
3796
|
+
wranglerConfigOwnership: ownership
|
|
3797
|
+
} },
|
|
3798
|
+
rootDir: options.rootDir
|
|
3799
|
+
});
|
|
3800
|
+
await writeOutputState(options.rootDir, []);
|
|
3801
|
+
await writeRateLimitManifest(options.rootDir, options.declarations, options.provider);
|
|
3802
|
+
}
|
|
3803
|
+
//#endregion
|
|
3804
|
+
//#region src/vite.ts
|
|
3805
|
+
const packageName = "@vite-hub/rate-limit";
|
|
3806
|
+
const pluginName = "@vite-hub/rate-limit/vite";
|
|
3807
|
+
const generatedNitroPlugin = ".vitehub/nitro/rate-limit/plugin.ts";
|
|
3808
|
+
const legacyGeneratedNitroMiddleware = ".vitehub/nitro/rate-limit/middleware.ts";
|
|
3809
|
+
const generatedRuntimeModule = ".vitehub/rate-limit/cloudflare-runtime.mjs";
|
|
3810
|
+
const legacyGeneratedRegistry = ".vitehub/nitro/rate-limit/registry.mjs";
|
|
3811
|
+
const mergeNoExternal = createNoExternalMerger(packageName);
|
|
3812
|
+
function cloneNitroConfig(value) {
|
|
3813
|
+
return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
|
|
3814
|
+
}
|
|
3815
|
+
function mergeNitroConfig(config, value, declarations, namespace, provider, nitroCloudflare) {
|
|
3816
|
+
const nitro = cloneNitroConfig(value);
|
|
3817
|
+
const plugins = Array.isArray(nitro.plugins) ? [...nitro.plugins] : [];
|
|
3818
|
+
if (!plugins.includes(generatedNitroPlugin)) plugins.unshift(generatedNitroPlugin);
|
|
3819
|
+
const baseNitro = {
|
|
3820
|
+
...nitro,
|
|
3821
|
+
plugins
|
|
3822
|
+
};
|
|
3823
|
+
if (!nitroCloudflare || provider !== "cloudflare" || declarations.length === 0) {
|
|
3824
|
+
registerCloudflareProviderOutput(config, "rate-limit", {});
|
|
3825
|
+
return composeNitroCloudflareProviderOutput(config, baseNitro);
|
|
3826
|
+
}
|
|
3827
|
+
if (!namespace) throw new Error("[vitehub] Cloudflare Rate Limit requires rateLimit.namespace to isolate counters between deployments.");
|
|
3828
|
+
registerCloudflareProviderOutput(config, "rate-limit", { rateLimits: createCloudflareRateLimitBindings(declarations, namespace) });
|
|
3829
|
+
return composeNitroCloudflareProviderOutput(config, baseNitro);
|
|
3830
|
+
}
|
|
3831
|
+
function renderRuntimeInstaller(runtimeConfig, importBase, nitro) {
|
|
3832
|
+
return [
|
|
3833
|
+
...nitro ? ["import { definePlugin } from 'nitro'"] : [],
|
|
3834
|
+
`import { setRateLimitRuntimeConfig } from ${JSON.stringify(`${importBase}/runtime`)}`,
|
|
3835
|
+
"",
|
|
3836
|
+
`const config = ${JSON.stringify(runtimeConfig)}`,
|
|
3837
|
+
...nitro ? [
|
|
3838
|
+
"export default definePlugin(() => {",
|
|
3839
|
+
" setRateLimitRuntimeConfig(config)",
|
|
3840
|
+
"})"
|
|
3841
|
+
] : ["setRateLimitRuntimeConfig(config)", "export default config"],
|
|
3842
|
+
""
|
|
3843
|
+
].join("\n");
|
|
3844
|
+
}
|
|
3845
|
+
function resolveProvider(options, command, nitro, deferUnknown = false) {
|
|
3846
|
+
if (options.provider && options.provider !== "auto") return options.provider;
|
|
3847
|
+
if (command === "serve") return "memory";
|
|
3848
|
+
const hosting = resolveNitroHosting(nitro);
|
|
3849
|
+
if (hosting === "cloudflare") return "cloudflare";
|
|
3850
|
+
if (hosting) throw new Error(`[vitehub] Rate Limit has no native ${hosting} driver. Configure a custom Rate Limiter instead of falling back to per-instance memory.`);
|
|
3851
|
+
if (deferUnknown) return;
|
|
3852
|
+
throw new Error("[vitehub] Rate Limit provider cannot be inferred for a production build. Set rateLimit.provider to \"cloudflare\" or explicitly choose \"memory\" for a known single-process deployment.");
|
|
3853
|
+
}
|
|
3854
|
+
function resolveNitroHosting(nitro) {
|
|
3855
|
+
const preset = cloneNitroConfig(nitro).preset;
|
|
3856
|
+
return getHostingProvider(typeof preset === "string" ? preset : process.env.NITRO_PRESET || process.env.SERVER_PRESET || process.env.VITEHUB_HOSTING);
|
|
3857
|
+
}
|
|
3858
|
+
function hubRateLimit(options = {}) {
|
|
3859
|
+
const importBase = options.importBase ?? packageName;
|
|
3860
|
+
let rateLimit = options;
|
|
3861
|
+
let composedOutput;
|
|
3862
|
+
let declarations = [];
|
|
3863
|
+
let declarationFiles = /* @__PURE__ */ new Set();
|
|
3864
|
+
let cloudflareOwnedByNitro = false;
|
|
3865
|
+
let previousDeclarations = [];
|
|
3866
|
+
let provider = "memory";
|
|
3867
|
+
let projectRoot;
|
|
3868
|
+
let resolved;
|
|
3869
|
+
const collectDeclarations = () => {
|
|
3870
|
+
if (!projectRoot) return;
|
|
3871
|
+
const catalog = discoverRateLimitCatalog({
|
|
3872
|
+
rootDir: projectRoot,
|
|
3873
|
+
scanDirs: rateLimit.scanDirs
|
|
3874
|
+
});
|
|
3875
|
+
declarations = catalog.declarations;
|
|
3876
|
+
declarationFiles = catalog.declarationFiles;
|
|
3877
|
+
};
|
|
3878
|
+
const refreshDeclarations = async () => {
|
|
3879
|
+
if (!projectRoot || !resolved) return;
|
|
3880
|
+
collectDeclarations();
|
|
3881
|
+
await writeRateLimitManifest(resolved.root, declarations, provider);
|
|
3882
|
+
};
|
|
3883
|
+
return {
|
|
3884
|
+
name: pluginName,
|
|
3885
|
+
config(config, env) {
|
|
3886
|
+
rateLimit = config.rateLimit ?? rateLimit;
|
|
3887
|
+
const configuredNitro = config.nitro;
|
|
3888
|
+
projectRoot = resolveViteHubProjectRoot(config.root || process.cwd(), { projectRoot: rateLimit.projectRoot });
|
|
3889
|
+
const configuredProvider = resolveProvider(rateLimit, env?.command ?? "serve", configuredNitro, true);
|
|
3890
|
+
if (configuredProvider) provider = configuredProvider;
|
|
3891
|
+
collectDeclarations();
|
|
3892
|
+
config.nitro = mergeNitroConfig(config, configuredNitro, declarations, resolveRateLimitNamespace(rateLimit.namespace), configuredProvider, resolveNitroHosting(configuredNitro) === "cloudflare");
|
|
3893
|
+
},
|
|
3894
|
+
async configResolved(config) {
|
|
3895
|
+
resolved = config;
|
|
3896
|
+
rateLimit = config.rateLimit ?? rateLimit;
|
|
3897
|
+
composedOutput = useComposedProviderOutput(config);
|
|
3898
|
+
projectRoot = resolveViteHubProjectRoot(config.root, { projectRoot: rateLimit.projectRoot });
|
|
3899
|
+
const configuredNitro = config.nitro;
|
|
3900
|
+
const nitroCloudflare = resolveNitroHosting(configuredNitro) === "cloudflare";
|
|
3901
|
+
cloudflareOwnedByNitro = hasNitroVitePlugin(config) && nitroCloudflare;
|
|
3902
|
+
provider = resolveProvider(rateLimit, config.command, configuredNitro);
|
|
3903
|
+
collectDeclarations();
|
|
3904
|
+
config.nitro = mergeNitroConfig(config, configuredNitro, declarations, resolveRateLimitNamespace(rateLimit.namespace), provider, nitroCloudflare);
|
|
3905
|
+
await writeRateLimitManifest(config.root, declarations, provider);
|
|
3906
|
+
const pluginFile = resolve(config.root, generatedNitroPlugin);
|
|
3907
|
+
const middlewareFile = resolve(config.root, legacyGeneratedNitroMiddleware);
|
|
3908
|
+
const runtimeFile = resolve(config.root, generatedRuntimeModule);
|
|
3909
|
+
const runtimeConfig = { provider };
|
|
3910
|
+
await Promise.all([
|
|
3911
|
+
rm(resolve(config.root, legacyGeneratedRegistry), { force: true }),
|
|
3912
|
+
rm(middlewareFile, { force: true }),
|
|
3913
|
+
writeFileIfChanged(pluginFile, renderRuntimeInstaller(runtimeConfig, importBase, true)),
|
|
3914
|
+
writeFileIfChanged(runtimeFile, renderRuntimeInstaller(runtimeConfig, importBase, false))
|
|
3915
|
+
]);
|
|
3916
|
+
registerProviderRuntimeModules(composedOutput, "rate-limit", { cloudflare: runtimeFile });
|
|
3917
|
+
},
|
|
3918
|
+
configEnvironment(name, config) {
|
|
3919
|
+
if (!isServerEnvironment(name, config)) return;
|
|
3920
|
+
return { resolve: { noExternal: mergeNoExternal(config.resolve?.noExternal) } };
|
|
3921
|
+
},
|
|
3922
|
+
async handleHotUpdate(context) {
|
|
3923
|
+
if (!/\.(?:c|m)?[jt]sx?$/i.test(context.file)) return;
|
|
3924
|
+
resolved = context.server.config;
|
|
3925
|
+
await refreshDeclarations();
|
|
3926
|
+
},
|
|
3927
|
+
transform(code, id) {
|
|
3928
|
+
if (provider !== "cloudflare" || !resolved?.build.ssr || !declarationFiles.has(id.split("?", 1)[0])) return;
|
|
3929
|
+
return `import ${JSON.stringify(normalizePath(resolve(resolved.root, generatedRuntimeModule)))}\n${code}`;
|
|
3930
|
+
},
|
|
3931
|
+
async closeBundle() {
|
|
3932
|
+
if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
|
|
3933
|
+
if (cloudflareOwnedByNitro && provider === "cloudflare") {
|
|
3934
|
+
const configuredDeclarations = declarations;
|
|
3935
|
+
collectDeclarations();
|
|
3936
|
+
if (JSON.stringify(declarations) !== JSON.stringify(configuredDeclarations)) throw new Error("[vitehub] Nitro Cloudflare Rate Limit declarations changed after config resolution. Generate Rate Limit source files before Vite config resolves.");
|
|
3937
|
+
await writeRateLimitManifest(resolved.root, declarations, provider);
|
|
3938
|
+
} else await refreshDeclarations();
|
|
3939
|
+
const namespace = resolveRateLimitNamespace(rateLimit.namespace);
|
|
3940
|
+
await writeRateLimitProviderOutput({
|
|
3941
|
+
clientOutDir: resolved.build.outDir,
|
|
3942
|
+
cloudflareOwnedByNitro,
|
|
3943
|
+
declarations,
|
|
3944
|
+
namespace,
|
|
3945
|
+
previousDeclarations,
|
|
3946
|
+
provider,
|
|
3947
|
+
rootDir: resolved.root
|
|
3948
|
+
});
|
|
3949
|
+
previousDeclarations = declarations;
|
|
3950
|
+
}
|
|
3951
|
+
};
|
|
3952
|
+
}
|
|
3953
|
+
//#endregion
|
|
3954
|
+
export { hubRateLimit };
|