@markless/bundler 0.8.0 → 0.10.0

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.
@@ -0,0 +1,2691 @@
1
+ import { S as withoutMachinePaths, d as startupPackOfLazy, g as rootRelativeId, l as packOfPiece, m as warmPacksSuffix } from "./route-pack-groups-ByQmKKom.js";
2
+ import { _ as spansAnyOffset, a as chunkLocalExportSpecifiers, c as knowsChunkDynamicImports, d as prefetchChunkParses, f as readChunkDynamicImports, g as renderedChunkCount, h as rememberChunkLocalExportSpecifiers, i as chunkDynamicImports, l as mayContainDynamicImport, m as rememberChunkDynamicImports, o as clearChunkFactCaches, p as readChunkLocalExportSpecifiers, r as calleeOffsets, u as parseChunkCode, v as textOffsets } from "./chunk-ast-pN_P5wIo.js";
3
+ import { deserialize } from "node:v8";
4
+ import { Worker } from "node:worker_threads";
5
+ import { callsImportedOrFreeName, parseJavaScriptModule } from "@markless/compiler";
6
+ import { basename, dirname, join, normalize, relative } from "pathe";
7
+ import { RolldownMagicString } from "rolldown";
8
+ import { availableParallelism } from "node:os";
9
+ //#region src/build/async-import-wrappers.ts
10
+ /**
11
+ * Vite rewrites `(await import(x)).a` and `const {a} = await import(x)` into
12
+ * `(async()=>{let{a:e}=await import(x);return{a:e}})()` so it can preload
13
+ * around it. Once the preload call is stripped, that wrapper is only a detour:
14
+ * a reader that takes named keys off the awaited wrapper reads them off
15
+ * `await import(x)` instead, and any other reader gets
16
+ * `import(x).then(m=>({a:m.a}))`, which resolves to the same snapshot object.
17
+ */
18
+ async function unwrapAsyncImportWrappers(bundle) {
19
+ const chunks = Object.values(bundle).filter((output) => isChunk(output) && output.code.includes("async()=>{"));
20
+ const unwrapped = await Promise.all(chunks.map((chunk) => runChunkTask("unwrappedAsyncImports", chunk.fileName ?? "chunk.js", chunk.code)));
21
+ for (const [index, chunk] of chunks.entries()) chunk.code = unwrapped[index];
22
+ }
23
+ const GAP = String.raw`(?:\s|/\*[\s\S]*?\*/|//[^\n]*\n)*`;
24
+ const WRAPPER_OPENING = new RegExp(`async${GAP}\\(${GAP}\\)${GAP}=>${GAP}\\{${GAP}(?:let|const)${GAP}\\{`);
25
+ function unwrapAsyncImportWrappersInCode(code) {
26
+ if (!WRAPPER_OPENING.test(code)) return code;
27
+ let program;
28
+ try {
29
+ const parsed = parseChunkCode("chunk.js", code);
30
+ if (parsed.errors.length) return code;
31
+ program = parsed.program;
32
+ } catch {
33
+ return code;
34
+ }
35
+ const edits = [];
36
+ walk$3(program, [], textOffsets(code, "async"), (node, parents) => {
37
+ const wrapper = asyncImportWrapper(node);
38
+ if (!wrapper) return true;
39
+ const source = code.slice(wrapper.awaited.start, wrapper.awaited.end);
40
+ const readerEdits = keyReaderEdits(node, parents, wrapper.keys);
41
+ if (readerEdits) edits.push({
42
+ start: node.start,
43
+ end: node.end,
44
+ text: source
45
+ }, ...readerEdits);
46
+ else {
47
+ const entries = [...wrapper.keys].map(([key, imported]) => `${propertyKey(key)}:${member(imported)}`);
48
+ edits.push({
49
+ start: node.start,
50
+ end: node.end,
51
+ text: `${source}.then(m=>({${entries.join(",")}}))`
52
+ });
53
+ }
54
+ return false;
55
+ });
56
+ let next = code;
57
+ for (const edit of edits.sort((a, b) => b.start - a.start)) next = next.slice(0, edit.start) + edit.text + next.slice(edit.end);
58
+ return next;
59
+ }
60
+ function asyncImportWrapper(call) {
61
+ if (call.type !== "CallExpression" || call.arguments.length > 0 || call.optional) return void 0;
62
+ let callee = call.callee;
63
+ while (callee.type === "ParenthesizedExpression") callee = callee.expression;
64
+ if (callee.type !== "ArrowFunctionExpression" || callee.async !== true || callee.params.length > 0) return void 0;
65
+ const body = callee.body;
66
+ const statements = body.type === "BlockStatement" ? body.body : [];
67
+ const [declaration, returned] = statements;
68
+ if (statements.length !== 2 || declaration?.type !== "VariableDeclaration" || declaration.kind === "var" || declaration.declarations.length !== 1 || returned?.type !== "ReturnStatement") return void 0;
69
+ const declarator = declaration.declarations[0];
70
+ const pattern = declarator.id;
71
+ const awaited = declarator.init;
72
+ const object = returned.argument;
73
+ if (pattern.type !== "ObjectPattern" || awaited?.type !== "AwaitExpression" || object?.type !== "ObjectExpression") return void 0;
74
+ const bound = /* @__PURE__ */ new Map();
75
+ for (const property of pattern.properties) {
76
+ const key = plainKey(property);
77
+ const value = property.value;
78
+ if (key === void 0 || value.type !== "Identifier") return void 0;
79
+ bound.set(value.name, key);
80
+ }
81
+ const keys = /* @__PURE__ */ new Map();
82
+ for (const property of object.properties) {
83
+ const key = plainKey(property);
84
+ const value = property.value;
85
+ if (key === void 0 || property.method || value.type !== "Identifier" || keys.has(key)) return void 0;
86
+ const imported = bound.get(value.name);
87
+ if (imported === void 0) return void 0;
88
+ keys.set(key, imported);
89
+ }
90
+ return {
91
+ awaited: awaited.argument,
92
+ keys
93
+ };
94
+ }
95
+ function keyReaderEdits(call, parents, keys) {
96
+ let index = parents.length - 1;
97
+ while (parents[index]?.type === "ParenthesizedExpression") index--;
98
+ if (parents[index]?.type !== "AwaitExpression") return void 0;
99
+ index--;
100
+ while (parents[index]?.type === "ParenthesizedExpression") index--;
101
+ const reader = parents[index];
102
+ const called = parents[index - 1]?.type === "CallExpression" && parents[index - 1].callee === reader;
103
+ if (reader?.type === "MemberExpression" && !reader.computed && !reader.optional && !called) {
104
+ const property = reader.property;
105
+ const imported = keys.get(property.name);
106
+ return imported !== void 0 && IDENTIFIER.test(imported) ? [{
107
+ start: property.start,
108
+ end: property.end,
109
+ text: imported
110
+ }] : void 0;
111
+ }
112
+ const pattern = reader?.type === "VariableDeclarator" ? reader.id : void 0;
113
+ if (pattern?.type !== "ObjectPattern") return void 0;
114
+ const edits = [];
115
+ for (const property of pattern.properties) {
116
+ const key = plainKey(property);
117
+ const imported = key === void 0 ? void 0 : keys.get(key);
118
+ if (imported === void 0) return void 0;
119
+ const node = property.key;
120
+ edits.push(property.shorthand ? {
121
+ start: node.start,
122
+ end: node.start,
123
+ text: `${propertyKey(imported)}:`
124
+ } : {
125
+ start: node.start,
126
+ end: node.end,
127
+ text: propertyKey(imported)
128
+ });
129
+ }
130
+ return edits;
131
+ }
132
+ const IDENTIFIER = /^[$A-Z_a-z][$\w]*$/;
133
+ function member(name) {
134
+ return IDENTIFIER.test(name) ? `m.${name}` : `m[${JSON.stringify(name)}]`;
135
+ }
136
+ function propertyKey(name) {
137
+ return IDENTIFIER.test(name) ? name : JSON.stringify(name);
138
+ }
139
+ function plainKey(property) {
140
+ if (property.type !== "Property" || property.computed || property.kind !== "init") return void 0;
141
+ const key = property.key;
142
+ if (key.type === "Identifier") return key.name;
143
+ if (key.type === "Literal" && typeof key.value === "string") return key.value;
144
+ }
145
+ function walk$3(node, parents, offsets, visit) {
146
+ if (!visit(node, parents)) return;
147
+ parents.push(node);
148
+ const descend = (child) => {
149
+ if (isSyntax(child) && spansAnyOffset(offsets, child)) walk$3(child, parents, offsets, visit);
150
+ };
151
+ for (const key in node) {
152
+ const value = node[key];
153
+ if (key === "parent") continue;
154
+ if (Array.isArray(value)) for (const item of value) descend(item);
155
+ else descend(value);
156
+ }
157
+ parents.pop();
158
+ }
159
+ function isSyntax(value) {
160
+ return typeof value === "object" && value !== null && typeof value.type === "string";
161
+ }
162
+ function isChunk(value) {
163
+ return typeof value === "object" && value !== null && value.type === "chunk" && typeof value.code === "string";
164
+ }
165
+ //#endregion
166
+ //#region src/build/pack-top-level.ts
167
+ const NAMESPACE_HELPER = "__exportAll";
168
+ function lazyNamespaceObjects(fileName, code) {
169
+ if (!code.includes(NAMESPACE_HELPER)) return [];
170
+ const parsed = parseChunkCode(fileName, code);
171
+ if (parsed.errors.length) return [];
172
+ const body = parsed.program.body;
173
+ const helpers = /* @__PURE__ */ new Set();
174
+ const exported = /* @__PURE__ */ new Set();
175
+ for (const node of body) if (node.type === "ImportDeclaration") for (const specifier of node.specifiers) {
176
+ const imported = specifier.imported;
177
+ if (specifier.type === "ImportSpecifier" && (imported?.name ?? imported?.value) === NAMESPACE_HELPER) helpers.add(specifier.local.name);
178
+ }
179
+ else if (node.type === "ExportNamedDeclaration") {
180
+ const declaration = node.declaration;
181
+ if (declaration?.type === "VariableDeclaration") for (const declarator of declaration.declarations) exported.add(declarator.id.name ?? "");
182
+ else if (declaration) exported.add(declaration.id?.name ?? "");
183
+ for (const specifier of node.specifiers) exported.add(specifier.local.name ?? specifier.local.value);
184
+ } else if (node.type === "ExportDefaultDeclaration" || node.type === "ExportAllDeclaration") return [];
185
+ for (const node of body) for (const declarator of declaratorsOf(node)) if (declarator.id.name === NAMESPACE_HELPER && declarator.init?.type === "ArrowFunctionExpression") helpers.add(NAMESPACE_HELPER);
186
+ if (!helpers.size) return [];
187
+ const candidates = /* @__PURE__ */ new Map();
188
+ for (const node of body) {
189
+ if (node.type !== "VariableDeclaration" || node.kind !== "var") continue;
190
+ const declarations = node.declarations;
191
+ if (declarations.length !== 1) continue;
192
+ const declarator = declarations[0];
193
+ const id = declarator.id;
194
+ const init = declarator.init;
195
+ if (id.type !== "Identifier" || init?.type !== "CallExpression" || init.callee.type !== "Identifier" || !helpers.has(init.callee.name) || exported.has(id.name)) continue;
196
+ candidates.set(id.name, node);
197
+ }
198
+ if (!candidates.size) return [];
199
+ const bindings = /* @__PURE__ */ new Map();
200
+ const references = /* @__PURE__ */ new Map();
201
+ const names = /* @__PURE__ */ new Set();
202
+ const written = /* @__PURE__ */ new Set();
203
+ walk$2(parsed.program, (node, parent, grandparent) => {
204
+ if (node.type !== "Identifier") return;
205
+ const name = node.name;
206
+ names.add(name);
207
+ if (!candidates.has(name)) return;
208
+ if (isWrite(node, parent, grandparent)) written.add(name);
209
+ else if (isBinding(node, parent)) bindings.set(name, (bindings.get(name) ?? 0) + 1);
210
+ else if (isReference$1(node, parent)) {
211
+ const list = references.get(name) ?? [];
212
+ list.push({
213
+ node,
214
+ ...parent?.type === "Property" && parent.shorthand ? { shorthand: parent } : {}
215
+ });
216
+ references.set(name, list);
217
+ }
218
+ });
219
+ const getters = /* @__PURE__ */ new Map();
220
+ for (const name of candidates.keys()) {
221
+ if (bindings.get(name) !== 1 || written.has(name)) continue;
222
+ let getter = `${name}$namespace`;
223
+ for (let attempt = 1; names.has(getter); attempt++) getter = `${name}$namespace${attempt}`;
224
+ names.add(getter);
225
+ getters.set(name, getter);
226
+ }
227
+ const referenceEdits = [...getters].flatMap(([name, getter]) => (references.get(name) ?? []).map((reference) => reference.shorthand ? {
228
+ start: reference.shorthand.start,
229
+ end: reference.shorthand.end,
230
+ source: `${name}:${getter}()`
231
+ } : {
232
+ start: reference.node.start,
233
+ end: reference.node.end,
234
+ source: `${getter}()`
235
+ }));
236
+ const edits = [];
237
+ const folded = /* @__PURE__ */ new Set();
238
+ for (const [name, getter] of getters) {
239
+ const declaration = candidates.get(name);
240
+ const init = declaration.declarations[0].init;
241
+ const inner = referenceEdits.filter((edit) => edit.start >= init.start && edit.end <= init.end).sort((a, b) => b.start - a.start);
242
+ let value = code.slice(init.start, init.end);
243
+ for (const edit of inner) {
244
+ value = value.slice(0, edit.start - init.start) + edit.source + value.slice(edit.end - init.start);
245
+ folded.add(edit);
246
+ }
247
+ edits.push({
248
+ start: declaration.start,
249
+ end: declaration.end,
250
+ source: `function ${getter}(){return ${getter}.value||(${getter}.value=${value})}`
251
+ });
252
+ }
253
+ for (const edit of referenceEdits) if (!folded.has(edit)) edits.push(edit);
254
+ return edits;
255
+ }
256
+ function mergedBareVarDeclarations(fileName, code) {
257
+ if (!hasTwoBareVarStatements(code)) return [];
258
+ const parsed = parseChunkCode(fileName, code);
259
+ if (parsed.errors.length) return [];
260
+ const bare = parsed.program.body.filter((node) => node.type === "VariableDeclaration" && node.kind === "var" && node.declarations.every((item) => item.init === null && item.id.type === "Identifier"));
261
+ if (bare.length < 2) return [];
262
+ const names = bare.flatMap((node) => node.declarations.map((item) => item.id.name));
263
+ return bare.map((node, index) => ({
264
+ start: node.start,
265
+ end: node.end,
266
+ source: index === 0 ? `var ${names.join(",")};` : ""
267
+ }));
268
+ }
269
+ const BARE_VAR_TEXT = /\bvar\s+[^\s,;=(){}[\]]+\s*(?:[,;\n\r}]|$)/g;
270
+ function hasTwoBareVarStatements(code) {
271
+ BARE_VAR_TEXT.lastIndex = 0;
272
+ return BARE_VAR_TEXT.test(code) && BARE_VAR_TEXT.test(code);
273
+ }
274
+ function packTopLevelEdits(fileName, code) {
275
+ return [...lazyNamespaceObjects(fileName, code), ...mergedBareVarDeclarations(fileName, code)];
276
+ }
277
+ function packTopLevelPlugin() {
278
+ return {
279
+ name: "markless-pack-top-level",
280
+ async renderChunk(code, chunk, options) {
281
+ if (!code.includes(NAMESPACE_HELPER) && !hasTwoBareVarStatements(code)) return null;
282
+ const edits = await runChunkTask("packTopLevelEdits", chunk.fileName, code);
283
+ if (!edits.length) return null;
284
+ const source = new RolldownMagicString(code);
285
+ for (const edit of edits) if (edit.source) source.overwrite(edit.start, edit.end, edit.source);
286
+ else source.remove(edit.start, edit.end);
287
+ return {
288
+ code: source.toString(),
289
+ map: options.sourcemap ? source.generateMap({ hires: true }).toString() : null
290
+ };
291
+ }
292
+ };
293
+ }
294
+ function declaratorsOf(node) {
295
+ return node.type === "VariableDeclaration" ? node.declarations : [];
296
+ }
297
+ function walk$2(root, visit) {
298
+ const pending = [[
299
+ root,
300
+ void 0,
301
+ void 0
302
+ ]];
303
+ while (pending.length) {
304
+ const [item, parent, grandparent] = pending.pop();
305
+ if (!item || typeof item !== "object") continue;
306
+ if (Array.isArray(item)) {
307
+ for (const child of item) pending.push([
308
+ child,
309
+ parent,
310
+ grandparent
311
+ ]);
312
+ continue;
313
+ }
314
+ const node = item;
315
+ const typed = typeof node.type === "string";
316
+ if (typed) visit(node, parent, grandparent);
317
+ for (const key in node) {
318
+ const value = node[key];
319
+ if (key !== "type" && value && typeof value === "object") pending.push(typed ? [
320
+ value,
321
+ node,
322
+ parent
323
+ ] : [
324
+ value,
325
+ parent,
326
+ grandparent
327
+ ]);
328
+ }
329
+ }
330
+ }
331
+ function isBinding(node, parent) {
332
+ if (!parent) return false;
333
+ switch (parent.type) {
334
+ case "VariableDeclarator": return parent.id === node;
335
+ case "FunctionDeclaration":
336
+ case "FunctionExpression":
337
+ case "ArrowFunctionExpression": return parent.id === node || parent.params.includes(node);
338
+ case "ClassDeclaration":
339
+ case "ClassExpression": return parent.id === node;
340
+ case "CatchClause": return parent.param === node;
341
+ case "ImportSpecifier":
342
+ case "ImportDefaultSpecifier":
343
+ case "ImportNamespaceSpecifier": return parent.local === node;
344
+ default: return false;
345
+ }
346
+ }
347
+ function isWrite(node, parent, grandparent) {
348
+ switch (parent?.type) {
349
+ case "ArrayPattern":
350
+ case "RestElement": return true;
351
+ case "AssignmentPattern": return parent.left === node;
352
+ case "Property": return parent.value === node && grandparent?.type === "ObjectPattern";
353
+ case "AssignmentExpression": return parent.left === node;
354
+ case "UpdateExpression": return true;
355
+ case "ForInStatement":
356
+ case "ForOfStatement": return parent.left === node;
357
+ default: return false;
358
+ }
359
+ }
360
+ function isReference$1(node, parent) {
361
+ if (!parent) return true;
362
+ switch (parent.type) {
363
+ case "MemberExpression": return parent.object === node || !!parent.computed;
364
+ case "Property": return parent.value === node || !!parent.computed && parent.key === node;
365
+ case "MethodDefinition":
366
+ case "PropertyDefinition": return !!parent.computed && parent.key === node;
367
+ case "ExportSpecifier":
368
+ case "ImportSpecifier":
369
+ case "LabeledStatement":
370
+ case "BreakStatement":
371
+ case "ContinueStatement": return false;
372
+ default: return true;
373
+ }
374
+ }
375
+ //#endregion
376
+ //#region src/build/preload-helper-removal.ts
377
+ async function stripUnusedVitePreloadHelperFromBundle(chunks) {
378
+ for (const helperChunk of chunks) {
379
+ if (!helperChunk.code.includes("vite:preloadError")) continue;
380
+ const rewrites = await planHelperRemoval(helperChunk, chunks);
381
+ if (!rewrites) continue;
382
+ for (const [chunk, rewrite] of rewrites) {
383
+ chunk.code = rewrite.code;
384
+ if (rewrite.droppedImport && Array.isArray(chunk.imports)) chunk.imports = chunk.imports.filter((fileName) => fileName !== helperChunk.fileName);
385
+ }
386
+ }
387
+ }
388
+ async function planHelperRemoval(helperChunk, chunks) {
389
+ const code = helperChunk.code;
390
+ const program = parse(code);
391
+ if (!program) return void 0;
392
+ const helper = findHelperModule(program, code, code.indexOf("vite:preloadError"));
393
+ if (!helper) return void 0;
394
+ const edits = [...helper.removals];
395
+ const exported = /* @__PURE__ */ new Map();
396
+ const removedLocals = /* @__PURE__ */ new Set([helper.initName, ...helper.helperVars]);
397
+ for (const statement of asNodes$1(program.body)) {
398
+ if (statement.type !== "ExportNamedDeclaration") continue;
399
+ if (statement.source) return void 0;
400
+ if (statement.declaration) {
401
+ const declared = /* @__PURE__ */ new Set();
402
+ collectBindingNames$1(statement.declaration.id, declared);
403
+ for (const declarator of asNodes$1(statement.declaration.declarations)) collectBindingNames$1(declarator.id, declared);
404
+ if ([...declared].some((name) => removedLocals.has(name))) return void 0;
405
+ continue;
406
+ }
407
+ const specifiers = asNodes$1(statement.specifiers);
408
+ const removed = /* @__PURE__ */ new Set();
409
+ for (const specifier of specifiers) {
410
+ const local = moduleExportName(specifier.local);
411
+ if (local === void 0 || !removedLocals.has(local)) continue;
412
+ if (local !== helper.initName && local !== helper.preloadName) return void 0;
413
+ exported.set(moduleExportName(specifier.exported), local === helper.initName ? "init" : "preload");
414
+ removed.add(specifier);
415
+ }
416
+ edits.push(...listRemoval(code, statement, specifiers, removed));
417
+ }
418
+ const initCalls = [];
419
+ for (const [name, found] of freeReferences(program, removedLocals)) for (const reference of found) {
420
+ if (insideAny(reference.node, helper.removals)) continue;
421
+ if (reference.parents.at(-1)?.type === "ExportSpecifier") continue;
422
+ if (name !== helper.initName) return void 0;
423
+ initCalls.push(reference);
424
+ }
425
+ const callEdits = initCallRemovals(initCalls);
426
+ if (!callEdits) return void 0;
427
+ const helperCode = applyEdits(code, [...edits, ...callEdits]);
428
+ if (helperCode === void 0) return void 0;
429
+ const rewrites = /* @__PURE__ */ new Map();
430
+ rewrites.set(helperChunk, {
431
+ code: helperCode,
432
+ droppedImport: false
433
+ });
434
+ if (exported.size === 0) return rewrites;
435
+ const helperBase = basename(helperChunk.fileName);
436
+ const importers = chunks.filter((chunk) => chunk !== helperChunk && chunk.code.includes(helperBase));
437
+ const context = {
438
+ helperFileName: helperChunk.fileName,
439
+ exported
440
+ };
441
+ const pending = [];
442
+ const launch = (index) => {
443
+ const chunk = importers[index];
444
+ const rewrite = runChunkTask("helperImporterRewrite", chunk.fileName, chunk.code, context);
445
+ rewrite.catch(() => {});
446
+ pending[index] = rewrite;
447
+ };
448
+ let next = 0;
449
+ for (; next < Math.min(IMPORTER_WINDOW, importers.length); next++) launch(next);
450
+ for (const [index, chunk] of importers.entries()) {
451
+ const rewrite = await pending[index];
452
+ if (rewrite === false) return void 0;
453
+ if (next < importers.length) launch(next++);
454
+ if (rewrite) rewrites.set(chunk, rewrite);
455
+ }
456
+ return rewrites;
457
+ }
458
+ const IMPORTER_WINDOW = 16;
459
+ function helperImporterRewrite(fileName, code, context) {
460
+ return rewriteImporter({
461
+ fileName,
462
+ code
463
+ }, context.helperFileName, context.exported);
464
+ }
465
+ function findHelperModule(program, code, marker) {
466
+ let found;
467
+ walk$1(program, [], (node, parents) => {
468
+ if (found || node.type !== "AssignmentExpression") return;
469
+ const right = node.right;
470
+ if (right?.type !== "FunctionExpression" || marker < right.start || marker > right.end) return;
471
+ if (node.left.type !== "Identifier") return;
472
+ found = {
473
+ assignment: node,
474
+ parents: [...parents]
475
+ };
476
+ });
477
+ if (!found) return void 0;
478
+ const parents = [...found.parents];
479
+ let cursor = parents.pop();
480
+ const assignments = cursor?.type === "SequenceExpression" ? asNodes$1(cursor.expressions) : [found.assignment];
481
+ if (cursor?.type === "SequenceExpression") cursor = parents.pop();
482
+ if (cursor?.type !== "ExpressionStatement") return void 0;
483
+ const block = parents.pop();
484
+ if (block?.type !== "BlockStatement" || asNodes$1(block.body).length !== 1) return void 0;
485
+ const arrow = parents.pop();
486
+ if (arrow?.type !== "ArrowFunctionExpression" || asNodes$1(arrow.params).length > 0) return void 0;
487
+ const call = skipParens(parents);
488
+ if (call?.type !== "CallExpression" || asNodes$1(call.arguments).length !== 1) return void 0;
489
+ const helperVars = [];
490
+ for (const assignment of assignments) {
491
+ const name = assignment.type === "AssignmentExpression" && assignment.operator === "=" ? identifierName$1(assignment.left) : void 0;
492
+ if (!name) return void 0;
493
+ helperVars.push(name);
494
+ }
495
+ const preloadName = identifierName$1(found.assignment.left);
496
+ const owner = skipParens(parents);
497
+ let initName;
498
+ let initDeclarator;
499
+ const removals = [];
500
+ if (owner?.type === "AssignmentExpression") {
501
+ initName = identifierName$1(owner.left);
502
+ const invoke = skipParens(parents);
503
+ const returned = parents.pop();
504
+ const body = parents.pop();
505
+ const declaration = parents.pop();
506
+ if (invoke?.type !== "CallExpression" || asNodes$1(invoke.arguments).length > 0 || returned?.type !== "ReturnStatement" || body?.type !== "BlockStatement" || asNodes$1(body.body).length !== 1 || declaration?.type !== "FunctionDeclaration" || asNodes$1(declaration.params).length > 0 || identifierName$1(declaration.id) !== initName || parents.at(-1)?.type !== "Program") return void 0;
507
+ removals.push({
508
+ start: declaration.start,
509
+ end: declaration.end,
510
+ text: ""
511
+ });
512
+ } else if (owner?.type === "VariableDeclarator") {
513
+ initName = identifierName$1(owner.id);
514
+ initDeclarator = owner;
515
+ if (parents.pop()?.type !== "VariableDeclaration" || parents.at(-1)?.type !== "Program") return void 0;
516
+ }
517
+ if (!initName) return void 0;
518
+ const declared = /* @__PURE__ */ new Set();
519
+ for (const statement of asNodes$1(program.body)) {
520
+ if (statement.type !== "VariableDeclaration") continue;
521
+ const declarators = asNodes$1(statement.declarations);
522
+ const removed = /* @__PURE__ */ new Set();
523
+ for (const declarator of declarators) {
524
+ const name = identifierName$1(declarator.id);
525
+ if (declarator === initDeclarator) removed.add(declarator);
526
+ else if (name !== void 0 && helperVars.includes(name) && !declarator.init) {
527
+ removed.add(declarator);
528
+ declared.add(name);
529
+ }
530
+ }
531
+ removals.push(...listRemoval(code, statement, declarators, removed));
532
+ }
533
+ if (helperVars.some((name) => !declared.has(name))) return void 0;
534
+ return {
535
+ initName,
536
+ preloadName,
537
+ helperVars,
538
+ removals
539
+ };
540
+ }
541
+ function rewriteImporter(chunk, helperFileName, exported) {
542
+ const program = parse(chunk.code);
543
+ if (!program) return false;
544
+ const helperBase = basename(helperFileName);
545
+ const resolvesToHelper = (source) => {
546
+ const specifier = source?.type === "Literal" ? source.value : void 0;
547
+ if (typeof specifier !== "string" || basename(specifier) !== helperBase) return false;
548
+ if (!specifier.startsWith(".")) return void 0;
549
+ return join(dirname(chunk.fileName), specifier) === helperFileName;
550
+ };
551
+ const edits = [];
552
+ const locals = /* @__PURE__ */ new Map();
553
+ let droppedImport = false;
554
+ for (const statement of asNodes$1(program.body)) {
555
+ if (statement.type === "ExportAllDeclaration" || statement.type === "ExportNamedDeclaration") {
556
+ if (resolvesToHelper(statement.source) !== false) return false;
557
+ continue;
558
+ }
559
+ if (statement.type !== "ImportDeclaration") continue;
560
+ const target = resolvesToHelper(statement.source);
561
+ if (target === void 0) return false;
562
+ if (!target) continue;
563
+ const specifiers = asNodes$1(statement.specifiers);
564
+ const removed = /* @__PURE__ */ new Set();
565
+ for (const specifier of specifiers) {
566
+ if (specifier.type !== "ImportSpecifier") return false;
567
+ const role = exported.get(moduleExportName(specifier.imported) ?? "");
568
+ if (!role) continue;
569
+ locals.set(identifierName$1(specifier.local), role);
570
+ removed.add(specifier);
571
+ }
572
+ if (removed.size > 0 && removed.size === specifiers.length) droppedImport = true;
573
+ edits.push(...listRemoval(chunk.code, statement, specifiers, removed));
574
+ }
575
+ let unsafeDynamicImport = false;
576
+ walk$1(program, [], (node, parents) => {
577
+ if (node.type !== "ImportExpression" || unsafeDynamicImport) return;
578
+ const target = resolvesToHelper(node.source);
579
+ if (target === false) return;
580
+ unsafeDynamicImport = target === void 0 || readsRemovedExport(parents, exported);
581
+ });
582
+ if (unsafeDynamicImport) return false;
583
+ if (locals.size === 0) return void 0;
584
+ const initCalls = [];
585
+ for (const [name, found] of freeReferences(program, new Set(locals.keys()))) {
586
+ if (found.length > 0 && locals.get(name) !== "init") return false;
587
+ initCalls.push(...found);
588
+ }
589
+ const callEdits = initCallRemovals(initCalls);
590
+ if (!callEdits) return false;
591
+ const next = applyEdits(chunk.code, [...edits, ...callEdits]);
592
+ return next === void 0 ? false : {
593
+ code: next,
594
+ droppedImport
595
+ };
596
+ }
597
+ function readsRemovedExport(parents, exported) {
598
+ const member = parents.at(-1);
599
+ const call = parents.at(-2);
600
+ if (member?.type !== "MemberExpression" || member.computed || identifierName$1(member.property) !== "then" || call?.type !== "CallExpression" || call.callee !== member) return true;
601
+ const callback = asNodes$1(call.arguments)[0];
602
+ const params = asNodes$1(callback?.params);
603
+ if (callback?.type !== "ArrowFunctionExpression" || params.length !== 1) return true;
604
+ const namespace = identifierName$1(params[0]);
605
+ if (!namespace) return true;
606
+ for (const [, found] of freeReferences(callback.body, /* @__PURE__ */ new Set([namespace]))) for (const reference of found) {
607
+ const parent = reference.parents.at(-1);
608
+ const property = parent?.type === "MemberExpression" && !parent.computed && parent.object === reference.node ? identifierName$1(parent.property) : void 0;
609
+ if (property === void 0 || exported.has(property)) return true;
610
+ }
611
+ return false;
612
+ }
613
+ function initCallRemovals(references) {
614
+ const bySequence = /* @__PURE__ */ new Map();
615
+ const edits = [];
616
+ for (const reference of references) {
617
+ const parents = [...reference.parents];
618
+ const call = parents.pop();
619
+ if (call?.type !== "CallExpression" || call.callee !== reference.node || call.optional || asNodes$1(call.arguments).length > 0) return void 0;
620
+ const parent = parents.pop();
621
+ if (parent?.type === "SequenceExpression") {
622
+ const entry = bySequence.get(parent) ?? {
623
+ statement: [...parents],
624
+ calls: /* @__PURE__ */ new Set()
625
+ };
626
+ entry.calls.add(call);
627
+ bySequence.set(parent, entry);
628
+ continue;
629
+ }
630
+ if (parent?.type !== "ExpressionStatement") return void 0;
631
+ const removal = statementRemoval(parent, parents.at(-1));
632
+ if (!removal) return void 0;
633
+ edits.push(removal);
634
+ }
635
+ for (const [sequence, { statement, calls }] of bySequence) {
636
+ const expressions = asNodes$1(sequence.expressions);
637
+ if (calls.size < expressions.length) {
638
+ edits.push(...commaListRemovals(expressions, calls));
639
+ continue;
640
+ }
641
+ const holder = statement.at(-1);
642
+ if (holder?.type !== "ExpressionStatement") return void 0;
643
+ const removal = statementRemoval(holder, statement.at(-2));
644
+ if (!removal) return void 0;
645
+ edits.push(removal);
646
+ }
647
+ return edits;
648
+ }
649
+ function statementRemoval(statement, container) {
650
+ if (container?.type !== "BlockStatement" && container?.type !== "Program") return void 0;
651
+ return {
652
+ start: statement.start,
653
+ end: statement.end,
654
+ text: ""
655
+ };
656
+ }
657
+ function listRemoval(code, statement, items, removed) {
658
+ if (removed.size === 0) return [];
659
+ if (removed.size < items.length) return commaListRemovals(items, removed);
660
+ const end = code[statement.end] === ";" ? statement.end + 1 : statement.end;
661
+ return [{
662
+ start: statement.start,
663
+ end,
664
+ text: ""
665
+ }];
666
+ }
667
+ function commaListRemovals(items, removed) {
668
+ const edits = [];
669
+ for (let index = 0; index < items.length; index++) {
670
+ if (!removed.has(items[index])) continue;
671
+ let last = index;
672
+ while (last + 1 < items.length && removed.has(items[last + 1])) last++;
673
+ edits.push(last + 1 < items.length ? {
674
+ start: items[index].start,
675
+ end: items[last + 1].start,
676
+ text: ""
677
+ } : {
678
+ start: items[index - 1].end,
679
+ end: items[last].end,
680
+ text: ""
681
+ });
682
+ index = last;
683
+ }
684
+ return edits;
685
+ }
686
+ function applyEdits(code, edits) {
687
+ const ordered = [...edits].sort((left, right) => right.start - left.start);
688
+ let next = code;
689
+ let floor = Number.POSITIVE_INFINITY;
690
+ for (const edit of ordered) {
691
+ if (edit.end > floor) return void 0;
692
+ next = next.slice(0, edit.start) + edit.text + next.slice(edit.end);
693
+ floor = edit.start;
694
+ }
695
+ return parse(next) ? next : void 0;
696
+ }
697
+ function insideAny(node, ranges) {
698
+ return ranges.some((range) => node.start >= range.start && node.end <= range.end);
699
+ }
700
+ function skipParens(parents) {
701
+ let node = parents.pop();
702
+ while (node?.type === "ParenthesizedExpression") node = parents.pop();
703
+ return node;
704
+ }
705
+ function freeReferences(root, names) {
706
+ const found = /* @__PURE__ */ new Map();
707
+ const scopes = [];
708
+ const visit = (node, parents) => {
709
+ const scope = declaredIn(node);
710
+ if (scope) scopes.push(scope);
711
+ if (node.type === "Identifier") {
712
+ const name = node.name;
713
+ if (names.has(name) && isReference(node, parents.at(-1)) && !scopes.some((declared) => declared.has(name))) {
714
+ const list = found.get(name) ?? [];
715
+ list.push({
716
+ node,
717
+ parents: [...parents]
718
+ });
719
+ found.set(name, list);
720
+ }
721
+ }
722
+ parents.push(node);
723
+ for (const child of childNodes$1(node)) if (isBindingSlot(node, child)) visitPattern(child, parents);
724
+ else visit(child, parents);
725
+ parents.pop();
726
+ if (scope) scopes.pop();
727
+ };
728
+ const visitPattern = (pattern, parents) => {
729
+ parents.push(pattern);
730
+ if (pattern.type === "AssignmentPattern") {
731
+ visitPattern(pattern.left, parents);
732
+ visit(pattern.right, parents);
733
+ } else if (pattern.type === "ArrayPattern") for (const element of asNodes$1(pattern.elements)) visitPattern(element, parents);
734
+ else if (pattern.type === "ObjectPattern") for (const property of asNodes$1(pattern.properties)) {
735
+ if (property.type === "RestElement") {
736
+ visitPattern(property.argument, parents);
737
+ continue;
738
+ }
739
+ if (property.computed) visit(property.key, parents);
740
+ visitPattern(property.value, parents);
741
+ }
742
+ else if (pattern.type === "RestElement") visitPattern(pattern.argument, parents);
743
+ else if (pattern.type !== "Identifier") {
744
+ parents.pop();
745
+ visit(pattern, parents);
746
+ return;
747
+ }
748
+ parents.pop();
749
+ };
750
+ visit(root, []);
751
+ return found;
752
+ }
753
+ function isBindingSlot(node, child) {
754
+ switch (node.type) {
755
+ case "VariableDeclarator": return child === node.id;
756
+ case "FunctionDeclaration":
757
+ case "FunctionExpression":
758
+ case "ArrowFunctionExpression": return child === node.id || asNodes$1(node.params).includes(child);
759
+ case "ClassDeclaration":
760
+ case "ClassExpression": return child === node.id;
761
+ case "CatchClause": return child === node.param;
762
+ default: return false;
763
+ }
764
+ }
765
+ function isReference(node, parent) {
766
+ if (!parent) return true;
767
+ switch (parent.type) {
768
+ case "MemberExpression": return parent.object === node || parent.computed === true;
769
+ case "Property":
770
+ case "MethodDefinition":
771
+ case "PropertyDefinition": return parent.key !== node || parent.computed === true;
772
+ case "LabeledStatement":
773
+ case "BreakStatement":
774
+ case "ContinueStatement": return false;
775
+ case "ExportSpecifier": return parent.local === node;
776
+ case "ImportSpecifier":
777
+ case "ImportDefaultSpecifier":
778
+ case "ImportNamespaceSpecifier": return false;
779
+ default: return true;
780
+ }
781
+ }
782
+ function declaredIn(node) {
783
+ switch (node.type) {
784
+ case "FunctionDeclaration":
785
+ case "FunctionExpression":
786
+ case "ArrowFunctionExpression": {
787
+ const names = /* @__PURE__ */ new Set();
788
+ if (node.type === "FunctionExpression") collectBindingNames$1(node.id, names);
789
+ for (const param of asNodes$1(node.params)) collectBindingNames$1(param, names);
790
+ collectVarNames(node.body, names);
791
+ return names;
792
+ }
793
+ case "ClassExpression": {
794
+ const names = /* @__PURE__ */ new Set();
795
+ collectBindingNames$1(node.id, names);
796
+ return names;
797
+ }
798
+ case "BlockStatement":
799
+ case "StaticBlock": return lexicalNames(asNodes$1(node.body));
800
+ case "SwitchStatement": return lexicalNames(asNodes$1(node.cases).flatMap((item) => asNodes$1(item.consequent)));
801
+ case "ForStatement":
802
+ case "ForInStatement":
803
+ case "ForOfStatement": {
804
+ const head = node.type === "ForStatement" ? node.init : node.left;
805
+ return head?.type === "VariableDeclaration" ? lexicalNames([head]) : void 0;
806
+ }
807
+ case "CatchClause": {
808
+ const names = /* @__PURE__ */ new Set();
809
+ collectBindingNames$1(node.param, names);
810
+ return names;
811
+ }
812
+ default: return;
813
+ }
814
+ }
815
+ function lexicalNames(statements) {
816
+ const names = /* @__PURE__ */ new Set();
817
+ for (const statement of statements) if (statement.type === "VariableDeclaration" && statement.kind !== "var") for (const declarator of asNodes$1(statement.declarations)) collectBindingNames$1(declarator.id, names);
818
+ else if (statement.type === "FunctionDeclaration" || statement.type === "ClassDeclaration") collectBindingNames$1(statement.id, names);
819
+ return names;
820
+ }
821
+ function collectVarNames(node, names) {
822
+ if (!node) return;
823
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") return;
824
+ if (node.type === "VariableDeclaration" && node.kind === "var") for (const declarator of asNodes$1(node.declarations)) collectBindingNames$1(declarator.id, names);
825
+ for (const child of childNodes$1(node)) collectVarNames(child, names);
826
+ }
827
+ function collectBindingNames$1(pattern, names) {
828
+ if (!pattern) return;
829
+ switch (pattern.type) {
830
+ case "Identifier":
831
+ names.add(pattern.name);
832
+ return;
833
+ case "AssignmentPattern":
834
+ collectBindingNames$1(pattern.left, names);
835
+ return;
836
+ case "RestElement":
837
+ collectBindingNames$1(pattern.argument, names);
838
+ return;
839
+ case "ArrayPattern":
840
+ for (const element of asNodes$1(pattern.elements)) collectBindingNames$1(element, names);
841
+ return;
842
+ case "ObjectPattern":
843
+ for (const property of asNodes$1(pattern.properties)) collectBindingNames$1(property.type === "RestElement" ? property.argument : property.value, names);
844
+ return;
845
+ }
846
+ }
847
+ function walk$1(node, parents, visit) {
848
+ visit(node, parents);
849
+ parents.push(node);
850
+ for (const child of childNodes$1(node)) walk$1(child, parents, visit);
851
+ parents.pop();
852
+ }
853
+ function parse(code) {
854
+ try {
855
+ const parsed = parseChunkCode("chunk.js", code);
856
+ if (parsed.errors.length) return void 0;
857
+ return parsed.program;
858
+ } catch {
859
+ return;
860
+ }
861
+ }
862
+ function childNodes$1(node) {
863
+ const children = [];
864
+ for (const key in node) {
865
+ const value = node[key];
866
+ if (key === "parent") continue;
867
+ if (Array.isArray(value)) {
868
+ for (const item of value) if (isNode(item)) children.push(item);
869
+ } else if (isNode(value)) children.push(value);
870
+ }
871
+ return children;
872
+ }
873
+ function asNodes$1(value) {
874
+ return Array.isArray(value) ? value.filter(isNode) : [];
875
+ }
876
+ function isNode(value) {
877
+ return typeof value === "object" && value !== null && typeof value.type === "string";
878
+ }
879
+ function identifierName$1(node) {
880
+ return node?.type === "Identifier" && typeof node.name === "string" ? node.name : void 0;
881
+ }
882
+ function moduleExportName(node) {
883
+ if (node?.type === "Literal" && typeof node.value === "string") return node.value;
884
+ return identifierName$1(node);
885
+ }
886
+ //#endregion
887
+ //#region src/build/pack-loader-names.ts
888
+ const PACK_LOAD = "__marklessPackLoad";
889
+ //#endregion
890
+ //#region src/build/preload-cleanup.ts
891
+ function stripEmptyVitePreloadWrappers(code) {
892
+ return stripImportedVitePreloadHelper(stripEmptyVitePreloadWrapperCalls(code));
893
+ }
894
+ function stripEmptyVitePreloadWrapperCalls(code) {
895
+ return stripUnusedVitePreloadHelper(stripAsyncEmptyPreloadWrappers(stripDirectEmptyPreloadWrappers(code)));
896
+ }
897
+ const PRELOADED_IMPORT_BODIES = [
898
+ "import(",
899
+ "Promise.resolve().then(",
900
+ "(async()=>"
901
+ ];
902
+ const PACK_LOAD_BODY_RE = new RegExp(`[$A-Z_a-z][$\\w]*\\(\\s*(["'\`])[^"'\`]+\\1\\s*,\\s*(["'\`])${"$ml".replaceAll("$", "\\$")}[$\\w]+\\2\\s*,\\s*\\(\\)\\s*=>\\s*import\\(`, "y");
903
+ function startsWithPackLoad(code, start) {
904
+ PACK_LOAD_BODY_RE.lastIndex = start;
905
+ return PACK_LOAD_BODY_RE.test(code);
906
+ }
907
+ const IMPORT_DECLARATION_CANDIDATE_RE = /\bimport\s*\{[\s\S]*?\}\s*from\s*["'][^"']+["'];?/g;
908
+ function stripDirectEmptyPreloadWrappers(code) {
909
+ let next = "";
910
+ let cursor = 0;
911
+ let changed = false;
912
+ const wrapperRE = /\b[$A-Z_a-z][$\w]*\(\(\)\s*=>\s*/g;
913
+ for (let match = wrapperRE.exec(code); match; match = wrapperRE.exec(code)) {
914
+ const callStart = match.index;
915
+ const bodyStart = match.index + match[0].length;
916
+ if (!PRELOADED_IMPORT_BODIES.some((body) => code.startsWith(body, bodyStart)) && !startsWithPackLoad(code, bodyStart)) continue;
917
+ const wrapper = findEmptyPreloadWrapper(code, callStart, bodyStart);
918
+ if (!wrapper) continue;
919
+ next += code.slice(cursor, callStart);
920
+ next += code.slice(bodyStart, wrapper.firstArgumentEnd);
921
+ cursor = wrapper.callEnd + 1;
922
+ wrapperRE.lastIndex = cursor;
923
+ changed = true;
924
+ }
925
+ if (!changed) return code;
926
+ return next + code.slice(cursor);
927
+ }
928
+ function stripAsyncEmptyPreloadWrappers(code) {
929
+ let next = "";
930
+ let cursor = 0;
931
+ let changed = false;
932
+ const wrapperRE = /\b[$A-Z_a-z][$\w]*\(\s*async\s*\(\)\s*=>\s*\{/g;
933
+ for (let match = wrapperRE.exec(code); match; match = wrapperRE.exec(code)) {
934
+ const callStart = match.index;
935
+ const callOpen = code.indexOf("(", callStart);
936
+ if (callOpen < 0) continue;
937
+ const firstArgumentEnd = findTopLevelComma(code, callOpen + 1);
938
+ if (firstArgumentEnd < 0) continue;
939
+ const wrapper = findEmptyPreloadWrapper(code, callStart, callOpen + 1);
940
+ if (!wrapper) continue;
941
+ const loader = code.slice(callOpen + 1, firstArgumentEnd);
942
+ next += code.slice(cursor, callStart);
943
+ next += `(${loader})()`;
944
+ cursor = wrapper.callEnd + 1;
945
+ wrapperRE.lastIndex = cursor;
946
+ changed = true;
947
+ }
948
+ if (!changed) return code;
949
+ return next + code.slice(cursor);
950
+ }
951
+ function findEmptyPreloadWrapper(code, callStart, bodyStart) {
952
+ const callOpen = code.indexOf("(", callStart);
953
+ if (callOpen < 0 || callOpen >= bodyStart) return void 0;
954
+ const firstArgumentEnd = findTopLevelComma(code, callOpen + 1);
955
+ if (firstArgumentEnd < 0) return void 0;
956
+ let cursor = skipSpaces(code, firstArgumentEnd + 1);
957
+ if (code.startsWith("void 0", cursor)) cursor = skipSpaces(code, cursor + 6);
958
+ else if (code[cursor] === "[" && code[cursor + 1] === "]") cursor = skipSpaces(code, cursor + 2);
959
+ else return void 0;
960
+ if (code[cursor] === ")") return {
961
+ firstArgumentEnd,
962
+ callEnd: cursor
963
+ };
964
+ if (code[cursor] !== ",") return void 0;
965
+ cursor = skipSpaces(code, cursor + 1);
966
+ if (!code.startsWith("import.meta.url", cursor)) return void 0;
967
+ cursor = skipSpaces(code, cursor + 15);
968
+ if (code[cursor] !== ")") return void 0;
969
+ return {
970
+ firstArgumentEnd,
971
+ callEnd: cursor
972
+ };
973
+ }
974
+ function findTopLevelComma(code, start) {
975
+ let depth = 1;
976
+ let quote = null;
977
+ let escaped = false;
978
+ for (let index = start; index < code.length; index++) {
979
+ const char = code[index];
980
+ if (quote) {
981
+ if (escaped) {
982
+ escaped = false;
983
+ continue;
984
+ }
985
+ if (char === "\\") {
986
+ escaped = true;
987
+ continue;
988
+ }
989
+ if (char === quote) quote = null;
990
+ continue;
991
+ }
992
+ if (char === "\"" || char === "'" || char === "`") {
993
+ quote = char;
994
+ continue;
995
+ }
996
+ if (char === "(" || char === "[" || char === "{") {
997
+ depth++;
998
+ continue;
999
+ }
1000
+ if (char === ")" || char === "]" || char === "}") {
1001
+ depth--;
1002
+ if (depth === 0) return -1;
1003
+ continue;
1004
+ }
1005
+ if (char === "," && depth === 1) return index;
1006
+ }
1007
+ return -1;
1008
+ }
1009
+ function skipSpaces(code, start) {
1010
+ let cursor = start;
1011
+ while (/\s/.test(code[cursor] ?? "")) cursor++;
1012
+ return cursor;
1013
+ }
1014
+ function stripImportedVitePreloadHelper(code) {
1015
+ const helper = findImportedVitePreloadHelper(code);
1016
+ if (!helper) return code;
1017
+ const withoutImport = code.slice(0, helper.importStart) + helper.keptImport + code.slice(helper.importEnd);
1018
+ if (preloadStillCalled(code, withoutImport, helper)) return code;
1019
+ const initCall = `${escapeRegExp(helper.initFunction)}\\(\\)`;
1020
+ return withoutInitStatements(withoutImport.replace(new RegExp(String.raw`,${initCall},`, "g"), ",").replace(new RegExp(String.raw`\{${initCall},`, "g"), "{").replace(new RegExp(String.raw`,${initCall},`, "g"), ",").replace(new RegExp(String.raw`,${initCall}\}`, "g"), "}").replace(new RegExp(String.raw`\{${initCall}\}`, "g"), "{}"), helper.initFunction) ?? code;
1021
+ }
1022
+ function withoutInitStatements(code, name) {
1023
+ const offsets = calleeOffsets(code, name);
1024
+ if (offsets.length === 0) return code;
1025
+ const program = tryParseJavaScriptModule(code);
1026
+ if (!program) return void 0;
1027
+ const statements = [];
1028
+ walkReferenceScopes(program, [], {
1029
+ removedImports: /* @__PURE__ */ new Set(),
1030
+ offsets
1031
+ }, (node, scopes) => {
1032
+ const call = node.type === "ExpressionStatement" ? node.expression : void 0;
1033
+ if (call?.type !== "CallExpression" || identifierName(call.callee) !== name || asNodes(call.arguments).length > 0 || isDeclaredInScope(name, scopes)) return;
1034
+ statements.push(node);
1035
+ });
1036
+ let next = code;
1037
+ for (const { start, end } of statements.sort((left, right) => right.start - left.start)) {
1038
+ const before = next.slice(0, start).trimEnd();
1039
+ const own = before === "" || /[;{]$/.test(before);
1040
+ next = next.slice(0, start) + (own ? "" : ";") + next.slice(end);
1041
+ }
1042
+ const after = tryParseJavaScriptModule(next);
1043
+ return after && !callsFreeName(next, after, name, /* @__PURE__ */ new Set()) ? next : void 0;
1044
+ }
1045
+ function findImportedVitePreloadHelper(code) {
1046
+ if (!code.includes("__vitePreload") || !code.includes("init_preload_helper")) return void 0;
1047
+ for (const match of code.matchAll(IMPORT_DECLARATION_CANDIDATE_RE)) {
1048
+ const importStart = match.index ?? -1;
1049
+ if (importStart < 0) continue;
1050
+ const statement = match[0];
1051
+ const declaration = asNodes(tryParseJavaScriptModule(statement)?.body).find((node) => node.type === "ImportDeclaration");
1052
+ if (!declaration) continue;
1053
+ let preloadFunction;
1054
+ let initFunction;
1055
+ const kept = [];
1056
+ const keptSpecifiers = /* @__PURE__ */ new Set();
1057
+ for (const [index, specifier] of asNodes(declaration.specifiers).entries()) {
1058
+ if (specifier.type !== "ImportSpecifier") return void 0;
1059
+ const imported = identifierName(specifier.imported);
1060
+ const local = identifierName(specifier.local);
1061
+ if (!imported || !local) continue;
1062
+ if (imported === "__vitePreload") preloadFunction = local;
1063
+ else if (imported === "init_preload_helper") initFunction = local;
1064
+ else {
1065
+ kept.push(sourceText(statement, specifier));
1066
+ keptSpecifiers.add(index);
1067
+ }
1068
+ }
1069
+ const source = declaration.source;
1070
+ if (preloadFunction && initFunction) return {
1071
+ importStart,
1072
+ importEnd: importStart + statement.length,
1073
+ keptImport: kept.length && source ? `import{${kept.join(",")}}from${sourceText(statement, source)};` : "",
1074
+ preloadFunction,
1075
+ initFunction,
1076
+ keptSpecifiers
1077
+ };
1078
+ }
1079
+ }
1080
+ function stripUnusedVitePreloadHelper(code) {
1081
+ const marker = code.indexOf("vite:preloadError");
1082
+ if (marker < 0) return code;
1083
+ const helper = findVitePreloadHelperModule(code, marker);
1084
+ if (!helper) return code;
1085
+ const statementEnd = code[helper.removeStart] === "," && code[helper.removeEnd - 1] === ";" ? ";" : "";
1086
+ const outsideHelper = code.slice(0, helper.removeStart) + statementEnd + code.slice(helper.removeEnd);
1087
+ if (hasCallableReference(outsideHelper, helper.preloadFunction)) return code;
1088
+ let withoutHelper = outsideHelper;
1089
+ const chain = findVitePreloadHelperInitChain(withoutHelper, helper.moduleVariable);
1090
+ if (chain) withoutHelper = removeInitCall(withoutHelper.slice(0, chain.removeStart) + withoutHelper.slice(chain.removeEnd), chain.entryVariable);
1091
+ return removeInitCall(withoutHelper, helper.moduleVariable);
1092
+ }
1093
+ function findVitePreloadHelperModule(code, marker) {
1094
+ const initStart = code.lastIndexOf("=e((()=>{", marker);
1095
+ if (initStart < 0) return void 0;
1096
+ const moduleVariable = readIdentifierBefore(code, initStart);
1097
+ if (!moduleVariable) return void 0;
1098
+ const bodyStart = initStart + 9;
1099
+ const bodyEnd = findModuleInitEnd(code, initStart);
1100
+ if (bodyEnd < 0) return void 0;
1101
+ const helperBody = code.slice(bodyStart, bodyEnd);
1102
+ const preloadFunction = helperBody.match(/,([$A-Z_a-z][$\w]*)=function\([^)]*\)\{let\s+[$A-Z_a-z][$\w]*=Promise\.resolve\(\)/)?.[1];
1103
+ if (!preloadFunction) return void 0;
1104
+ const firstHelperVariable = helperBody.match(/^([$A-Z_a-z][$\w]*)=/)?.[1];
1105
+ if (!firstHelperVariable) return void 0;
1106
+ const removeStart = findHelperDeclarationStart(code, initStart, firstHelperVariable);
1107
+ if (removeStart < 0) return void 0;
1108
+ return {
1109
+ moduleVariable,
1110
+ preloadFunction,
1111
+ removeStart,
1112
+ removeEnd: bodyEnd + 4
1113
+ };
1114
+ }
1115
+ function findVitePreloadHelperInitChain(code, moduleVariable) {
1116
+ const match = new RegExp(`var\\s+([$A-Z_a-z][$\\w]*)=e\\(\\(\\(\\)=>\\{${escapeRegExp(moduleVariable)}\\(\\)\\}\\)\\),([$A-Z_a-z][$\\w]*)=e\\(\\(\\(\\)=>\\{\\1\\(\\)\\}\\)\\);`).exec(code);
1117
+ if (!match) return void 0;
1118
+ return {
1119
+ entryVariable: match[2],
1120
+ removeStart: match.index,
1121
+ removeEnd: match.index + match[0].length
1122
+ };
1123
+ }
1124
+ function removeInitCall(code, entryVariable) {
1125
+ return code.replace(new RegExp(`,${escapeRegExp(entryVariable)}\\(\\)`), "").replace(new RegExp(`${escapeRegExp(entryVariable)}\\(\\),`), "").replace(new RegExp(`\\{${escapeRegExp(entryVariable)}\\(\\)\\}`), "{}");
1126
+ }
1127
+ function readIdentifierBefore(code, index) {
1128
+ let end = index;
1129
+ while (/\s/.test(code[end - 1] ?? "")) end--;
1130
+ let start = end;
1131
+ while (/[$\w]/.test(code[start - 1] ?? "")) start--;
1132
+ const value = code.slice(start, end);
1133
+ return /^[$A-Z_a-z][$\w]*$/.test(value) ? value : void 0;
1134
+ }
1135
+ function findModuleInitEnd(code, initStart) {
1136
+ return code.indexOf("}));", initStart);
1137
+ }
1138
+ function findHelperDeclarationStart(code, initStart, firstHelperVariable) {
1139
+ const commaStart = code.lastIndexOf(`,${firstHelperVariable},`, initStart);
1140
+ if (commaStart >= 0) return commaStart;
1141
+ const varStart = code.lastIndexOf(`var ${firstHelperVariable},`, initStart);
1142
+ if (varStart >= 0) return varStart;
1143
+ return -1;
1144
+ }
1145
+ function escapeRegExp(value) {
1146
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1147
+ }
1148
+ function preloadStillCalled(code, withoutImport, helper) {
1149
+ if (calleeOffsets(code, helper.preloadFunction).length === 0 && calleeOffsets(withoutImport, helper.preloadFunction).length === 0 && parsesCleanly(code) && parsesCleanly(withoutImport)) return false;
1150
+ if (parsesCleanly(code) && importIsWholeStatement(code, helper)) {
1151
+ const called = callsImportedOrFreeName(code, helper.preloadFunction);
1152
+ if (called !== void 0) return called;
1153
+ }
1154
+ const program = tryParseChunk(code);
1155
+ const body = asNodes(program?.body);
1156
+ const index = body.findIndex((node) => node.start === helper.importStart && node.end === helper.importEnd);
1157
+ const declaration = body[index];
1158
+ const previous = body[index - 1];
1159
+ if (!program || declaration?.type !== "ImportDeclaration" || previous !== void 0 && code[(previous.end ?? 0) - 1] !== ";") return hasCallableReference(withoutImport, helper.preloadFunction);
1160
+ const specifiers = asNodes(declaration.specifiers);
1161
+ const removed = new Set(specifiers.filter((_, index) => helper.keptImport === "" || !helper.keptSpecifiers.has(index)));
1162
+ return callsFreeName(code, program, helper.preloadFunction, removed);
1163
+ }
1164
+ function importIsWholeStatement(code, helper) {
1165
+ if (!parseChunkCode("chunk.js", code).module.staticImports.some((entry) => entry.start === helper.importStart && entry.end === helper.importEnd)) return false;
1166
+ const lines = code.slice(0, helper.importStart).split("\n");
1167
+ let last = "";
1168
+ while (lines.length && (last === "" || last.startsWith("//"))) last = lines.pop().trim();
1169
+ if (last === "" || last.startsWith("//")) return true;
1170
+ return last.endsWith(";") && !last.includes("//") && !last.includes("/*");
1171
+ }
1172
+ function parsesCleanly(code) {
1173
+ try {
1174
+ return parseChunkCode("chunk.js", code).errors.length === 0;
1175
+ } catch {
1176
+ return false;
1177
+ }
1178
+ }
1179
+ function tryParseChunk(code) {
1180
+ try {
1181
+ const parsed = parseChunkCode("chunk.js", code);
1182
+ return parsed.errors.length ? void 0 : parsed.program;
1183
+ } catch {
1184
+ return;
1185
+ }
1186
+ }
1187
+ function hasCallableReference(code, name) {
1188
+ const ast = tryParseJavaScriptModule(code);
1189
+ return ast ? callsFreeName(code, ast, name, /* @__PURE__ */ new Set()) : true;
1190
+ }
1191
+ function callsFreeName(code, ast, name, removedImports) {
1192
+ let found = false;
1193
+ walkReferenceScopes(ast, [], {
1194
+ removedImports,
1195
+ offsets: calleeOffsets(code, name)
1196
+ }, (node, scopes) => {
1197
+ if (node.type !== "CallExpression") return;
1198
+ const callee = node.callee;
1199
+ if (identifierName(callee) !== name) return;
1200
+ if (isDeclaredInScope(name, scopes)) return;
1201
+ found = true;
1202
+ });
1203
+ return found;
1204
+ }
1205
+ function walkReferenceScopes(node, scopes, scan, visit) {
1206
+ if (!node || typeof node !== "object") return;
1207
+ if (node.type === "Program") {
1208
+ const scope = collectScopeDeclarations(asNodes(node.body), scan.removedImports);
1209
+ visit(node, [scope]);
1210
+ for (const child of asNodes(node.body)) if (spansAnyOffset(scan.offsets, child)) walkReferenceScopes(child, [scope], scan, visit);
1211
+ return;
1212
+ }
1213
+ if (isFunctionNode(node)) {
1214
+ const scope = /* @__PURE__ */ new Set();
1215
+ collectBindingNames(node.id, scope);
1216
+ for (const parameter of asNodes(node.params)) collectBindingNames(parameter, scope);
1217
+ const nextScopes = [...scopes, scope];
1218
+ visit(node, nextScopes);
1219
+ walkReferenceScopes(node.body, nextScopes, scan, visit);
1220
+ return;
1221
+ }
1222
+ if (node.type === "BlockStatement") {
1223
+ const scope = collectScopeDeclarations(asNodes(node.body));
1224
+ const nextScopes = [...scopes, scope];
1225
+ visit(node, nextScopes);
1226
+ for (const child of asNodes(node.body)) if (spansAnyOffset(scan.offsets, child)) walkReferenceScopes(child, nextScopes, scan, visit);
1227
+ return;
1228
+ }
1229
+ visit(node, scopes);
1230
+ for (const child of childNodes(node)) if (spansAnyOffset(scan.offsets, child)) walkReferenceScopes(child, scopes, scan, visit);
1231
+ }
1232
+ function collectScopeDeclarations(nodes, removedImports = /* @__PURE__ */ new Set()) {
1233
+ const declarations = /* @__PURE__ */ new Set();
1234
+ for (const node of nodes) {
1235
+ if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
1236
+ collectBindingNames(node.id, declarations);
1237
+ continue;
1238
+ }
1239
+ if (node.type === "ImportDeclaration") {
1240
+ for (const specifier of asNodes(node.specifiers)) {
1241
+ if (removedImports.has(specifier)) continue;
1242
+ collectBindingNames(specifier.local, declarations);
1243
+ }
1244
+ continue;
1245
+ }
1246
+ if (node.type === "VariableDeclaration") for (const declaration of asNodes(node.declarations)) collectBindingNames(declaration.id, declarations);
1247
+ }
1248
+ return declarations;
1249
+ }
1250
+ function collectBindingNames(node, names) {
1251
+ if (!node) return;
1252
+ const name = identifierName(node);
1253
+ if (name) {
1254
+ names.add(name);
1255
+ return;
1256
+ }
1257
+ for (const child of childNodes(node)) collectBindingNames(child, names);
1258
+ }
1259
+ function isDeclaredInScope(name, scopes) {
1260
+ return scopes.some((scope) => scope.has(name));
1261
+ }
1262
+ function isFunctionNode(node) {
1263
+ return node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
1264
+ }
1265
+ function sourceText(code, node) {
1266
+ const { start, end } = node;
1267
+ return code.slice(start, end);
1268
+ }
1269
+ function tryParseJavaScriptModule(code) {
1270
+ try {
1271
+ return parseJavaScriptModule(code, "chunk.js");
1272
+ } catch {
1273
+ return;
1274
+ }
1275
+ }
1276
+ function childNodes(node) {
1277
+ const children = [];
1278
+ for (const key in node) {
1279
+ const value = node[key];
1280
+ if (ignoredAstKeys.has(key)) continue;
1281
+ if (Array.isArray(value)) {
1282
+ for (const item of value) if (isAstNode(item)) children.push(item);
1283
+ continue;
1284
+ }
1285
+ if (isAstNode(value)) children.push(value);
1286
+ }
1287
+ return children;
1288
+ }
1289
+ function asNodes(value) {
1290
+ return Array.isArray(value) ? value.filter(isAstNode) : [];
1291
+ }
1292
+ function isAstNode(value) {
1293
+ return typeof value === "object" && value !== null && typeof value.type === "string";
1294
+ }
1295
+ function identifierName(node) {
1296
+ return node?.type === "Identifier" && typeof node.name === "string" ? node.name : void 0;
1297
+ }
1298
+ const ignoredAstKeys = /* @__PURE__ */ new Set([
1299
+ "closingElement",
1300
+ "id",
1301
+ "leadingComments",
1302
+ "loc",
1303
+ "metadata",
1304
+ "openingElement",
1305
+ "parent",
1306
+ "range",
1307
+ "trailingComments"
1308
+ ]);
1309
+ //#endregion
1310
+ //#region src/build/short-export-names.ts
1311
+ const MIN_LENGTH = 2;
1312
+ const READ_BY_LATER_PASSES = /^(?:__vitePreload|init_preload_helper)$/;
1313
+ const SYMBOL_INIT = /^init__virtual_markless_symbol/;
1314
+ const START = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$";
1315
+ const PART = `${START}0123456789`;
1316
+ const WORD = /[A-Za-z_$][\w$]*/g;
1317
+ const RESERVED = new Set("await break case catch class const continue debugger default delete do else enum eval export extends false finally for function if implements import in instanceof interface let new null package private protected public return static super switch then this throw true try typeof undefined var void while with yield arguments".split(" "));
1318
+ function shortNameChunkFacts(fileName, code) {
1319
+ const parsed = parseChunkCode(fileName, code);
1320
+ if (parsed.errors.length) return { errors: true };
1321
+ const imports = [];
1322
+ const exports = [];
1323
+ const pins = [];
1324
+ for (const node of parsed.program.body) {
1325
+ if (node.type === "ImportDeclaration" || node.type === "ExportAllDeclaration") {
1326
+ imports.push({
1327
+ source: sourceOf(node),
1328
+ exportAll: node.type === "ExportAllDeclaration",
1329
+ specifiers: node.type === "ExportAllDeclaration" ? [] : (node.specifiers ?? []).map((specifier) => {
1330
+ if (specifier.type !== "ImportSpecifier") return void 0;
1331
+ const imported = specifier.imported;
1332
+ return {
1333
+ name: nameOf(imported),
1334
+ start: imported.start,
1335
+ end: imported.end,
1336
+ shorthand: imported.start === specifier.local.start
1337
+ };
1338
+ })
1339
+ });
1340
+ continue;
1341
+ }
1342
+ if (node.type === "ExportDefaultDeclaration") {
1343
+ pins.push("default");
1344
+ continue;
1345
+ }
1346
+ if (node.type !== "ExportNamedDeclaration") continue;
1347
+ if (node.declaration) {
1348
+ pins.push(...declaredNames(node.declaration));
1349
+ continue;
1350
+ }
1351
+ exports.push({
1352
+ source: node.source ? sourceOf(node) : void 0,
1353
+ reExport: !!node.source,
1354
+ clause: {
1355
+ start: node.start,
1356
+ end: node.end
1357
+ },
1358
+ specifiers: node.specifiers.map((specifier) => {
1359
+ const local = specifier.local;
1360
+ const exported = specifier.exported;
1361
+ return {
1362
+ local: {
1363
+ name: nameOf(local),
1364
+ start: local.start,
1365
+ end: local.end
1366
+ },
1367
+ exported: {
1368
+ name: nameOf(exported),
1369
+ start: exported.start,
1370
+ end: exported.end
1371
+ },
1372
+ shorthand: local.start === exported.start
1373
+ };
1374
+ })
1375
+ });
1376
+ }
1377
+ const words = /* @__PURE__ */ new Set();
1378
+ const strings = [];
1379
+ const dynamicImports = [];
1380
+ scanReads(parsed.program, words, (source, members) => {
1381
+ dynamicImports.push({
1382
+ source,
1383
+ members: members?.map((node) => ({
1384
+ name: node.name,
1385
+ start: node.start,
1386
+ end: node.end
1387
+ }))
1388
+ });
1389
+ }, strings);
1390
+ return {
1391
+ errors: false,
1392
+ imports,
1393
+ pins,
1394
+ exports,
1395
+ dynamicImports,
1396
+ words: [...words],
1397
+ strings
1398
+ };
1399
+ }
1400
+ function planShortExportNames(chunks, factsOf = (chunk) => shortNameChunkFacts(chunk.fileName, chunk.code)) {
1401
+ const byName = new Map(chunks.map((chunk) => [chunk.fileName, chunk]));
1402
+ const references = [];
1403
+ const own = /* @__PURE__ */ new Map();
1404
+ const pinned = /* @__PURE__ */ new Map();
1405
+ const opaque = /* @__PURE__ */ new Set();
1406
+ const words = /* @__PURE__ */ new Set();
1407
+ const escaping = /* @__PURE__ */ new Set();
1408
+ const strings = [];
1409
+ const pin = (fileName, name) => {
1410
+ const set = pinned.get(fileName) ?? /* @__PURE__ */ new Set();
1411
+ set.add(name);
1412
+ pinned.set(fileName, set);
1413
+ };
1414
+ for (const chunk of chunks) {
1415
+ const facts = factsOf(chunk);
1416
+ if (facts.errors) return {
1417
+ renames: /* @__PURE__ */ new Map(),
1418
+ edits: /* @__PURE__ */ new Map(),
1419
+ pruned: /* @__PURE__ */ new Map(),
1420
+ exports: /* @__PURE__ */ new Map()
1421
+ };
1422
+ const removed = !!chunk.removed;
1423
+ const exports = [];
1424
+ for (const item of facts.imports) {
1425
+ const target = targetOf(chunk.fileName, item.source, byName);
1426
+ if (!target) continue;
1427
+ if (item.exportAll) {
1428
+ opaque.add(target);
1429
+ continue;
1430
+ }
1431
+ for (const specifier of item.specifiers) {
1432
+ if (!specifier) {
1433
+ opaque.add(target);
1434
+ continue;
1435
+ }
1436
+ references.push({
1437
+ chunk: chunk.fileName,
1438
+ target,
1439
+ name: specifier.name,
1440
+ node: specifier,
1441
+ shorthand: specifier.shorthand,
1442
+ removed
1443
+ });
1444
+ }
1445
+ }
1446
+ for (const name of facts.pins) pin(chunk.fileName, name);
1447
+ for (const item of facts.exports) {
1448
+ const target = item.reExport ? targetOf(chunk.fileName, item.source, byName) : void 0;
1449
+ for (const specifier of item.specifiers) {
1450
+ const { local, exported, shorthand } = specifier;
1451
+ if (item.reExport) {
1452
+ if (target) references.push({
1453
+ chunk: chunk.fileName,
1454
+ target,
1455
+ name: local.name,
1456
+ node: local,
1457
+ shorthand,
1458
+ removed
1459
+ });
1460
+ if (shorthand && target) pin(chunk.fileName, exported.name);
1461
+ else exports.push({
1462
+ name: exported.name,
1463
+ node: exported,
1464
+ local,
1465
+ shorthand: false,
1466
+ clause: void 0
1467
+ });
1468
+ } else exports.push({
1469
+ name: exported.name,
1470
+ node: exported,
1471
+ local,
1472
+ shorthand,
1473
+ clause: item.clause
1474
+ });
1475
+ }
1476
+ }
1477
+ own.set(chunk.fileName, exports);
1478
+ for (const word of facts.words) words.add(word);
1479
+ for (const { source, members } of facts.dynamicImports) {
1480
+ const target = resolveChunk(chunk.fileName, source, byName);
1481
+ if (!target) {
1482
+ strings.push(source);
1483
+ continue;
1484
+ }
1485
+ if (!members) {
1486
+ escaping.add(target);
1487
+ continue;
1488
+ }
1489
+ for (const node of members) references.push({
1490
+ chunk: chunk.fileName,
1491
+ target,
1492
+ name: node.name,
1493
+ node,
1494
+ shorthand: false,
1495
+ removed
1496
+ });
1497
+ }
1498
+ strings.push(...facts.strings);
1499
+ }
1500
+ for (const fileName of namedInStrings(strings, chunks.map((chunk) => chunk.fileName))) escaping.add(fileName);
1501
+ const renames = /* @__PURE__ */ new Map();
1502
+ const pruned = /* @__PURE__ */ new Map();
1503
+ const finalNames = /* @__PURE__ */ new Map();
1504
+ const survivingReads = new Set(references.filter((item) => !item.removed).map((item) => `${item.target}\0${item.name}`));
1505
+ for (const chunk of chunks) {
1506
+ if (opaque.has(chunk.fileName) || chunk.removed) continue;
1507
+ const keep = new Set(pinned.get(chunk.fileName));
1508
+ if (chunk.isEntry || chunk.isDynamicEntry) {
1509
+ if (!chunk.signature) continue;
1510
+ for (const name of chunk.signature) keep.add(name);
1511
+ }
1512
+ const candidates = [];
1513
+ const ownNames = /* @__PURE__ */ new Set([...(own.get(chunk.fileName) ?? []).map((item) => item.name), ...pinned.get(chunk.fileName) ?? []]);
1514
+ for (const name of ownNames) if (keep.has(name) || READ_BY_LATER_PASSES.test(name) || escaping.has(chunk.fileName) && (words.has(name) || SYMBOL_INIT.test(name))) keep.add(name);
1515
+ else candidates.push(name);
1516
+ const names = shortNames(candidates, keep);
1517
+ if (names.size) renames.set(chunk.fileName, names);
1518
+ finalNames.set(chunk.fileName, [...ownNames]);
1519
+ if (escaping.has(chunk.fileName)) continue;
1520
+ const unused = new Set([...ownNames].filter((name) => !keep.has(name) && !survivingReads.has(`${chunk.fileName}\0${name}`)));
1521
+ if (unused.size) pruned.set(chunk.fileName, unused);
1522
+ }
1523
+ const code = new Map(chunks.map((chunk) => [chunk.fileName, chunk.code]));
1524
+ const edits = /* @__PURE__ */ new Map();
1525
+ const edit = (fileName, item) => {
1526
+ const list = edits.get(fileName) ?? [];
1527
+ list.push(item);
1528
+ edits.set(fileName, list);
1529
+ };
1530
+ for (const reference of references) {
1531
+ const next = renames.get(reference.target)?.get(reference.name);
1532
+ if (!next || reference.removed) continue;
1533
+ edit(reference.chunk, {
1534
+ start: reference.node.start,
1535
+ end: reference.node.end,
1536
+ source: reference.shorthand ? `${next} as ${reference.name}` : next
1537
+ });
1538
+ }
1539
+ for (const [fileName, exports] of own) {
1540
+ const names = renames.get(fileName) ?? /* @__PURE__ */ new Map();
1541
+ const unused = pruned.get(fileName);
1542
+ const rewritten = /* @__PURE__ */ new Set();
1543
+ for (const item of exports) {
1544
+ if (!item.clause || !unused?.has(item.name) || rewritten.has(item.clause)) continue;
1545
+ rewritten.add(item.clause);
1546
+ const kept = exports.filter((other) => other.clause === item.clause && !unused.has(other.name)).map((other) => {
1547
+ const local = code.get(fileName).slice(other.local.start, other.local.end);
1548
+ const name = names.get(other.name) ?? other.name;
1549
+ const exported = /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name);
1550
+ return local === exported ? local : `${local} as ${exported}`;
1551
+ });
1552
+ edit(fileName, {
1553
+ start: item.clause.start,
1554
+ end: item.clause.end,
1555
+ source: kept.length ? `export{${kept.join(",")}};` : ""
1556
+ });
1557
+ }
1558
+ for (const item of exports) {
1559
+ const next = names.get(item.name);
1560
+ if (!next || item.clause && rewritten.has(item.clause)) continue;
1561
+ edit(fileName, {
1562
+ start: item.node.start,
1563
+ end: item.node.end,
1564
+ source: item.shorthand ? `${item.name} as ${next}` : next
1565
+ });
1566
+ }
1567
+ }
1568
+ return {
1569
+ renames,
1570
+ edits,
1571
+ pruned,
1572
+ exports: new Map([...finalNames].map(([fileName, list]) => [fileName, list.filter((name) => !pruned.get(fileName)?.has(name)).map((name) => renames.get(fileName)?.get(name) ?? name)]))
1573
+ };
1574
+ }
1575
+ function namedInStrings(strings, fileNames) {
1576
+ const baseOf = (fileName) => fileName.slice(fileName.lastIndexOf("/") + 1);
1577
+ const byExtension = /* @__PURE__ */ new Map();
1578
+ const bare = [];
1579
+ for (const fileName of fileNames) {
1580
+ const base = baseOf(fileName);
1581
+ if (!base.includes(".")) {
1582
+ bare.push(base);
1583
+ continue;
1584
+ }
1585
+ const extension = base.slice(base.lastIndexOf("."));
1586
+ const bases = byExtension.get(extension) ?? /* @__PURE__ */ new Set();
1587
+ bases.add(base);
1588
+ byExtension.set(extension, bases);
1589
+ }
1590
+ const found = /* @__PURE__ */ new Set();
1591
+ for (const [extension, bases] of byExtension) {
1592
+ const lengths = [...new Set([...bases].map((base) => base.length))];
1593
+ for (const value of strings) for (let at = value.indexOf(extension); at !== -1; at = value.indexOf(extension, at + 1)) {
1594
+ const end = at + extension.length;
1595
+ for (const length of lengths) {
1596
+ if (length > end) continue;
1597
+ const candidate = value.slice(end - length, end);
1598
+ if (bases.has(candidate)) found.add(candidate);
1599
+ }
1600
+ }
1601
+ }
1602
+ if (bare.length) {
1603
+ const text = strings.join("\n");
1604
+ for (const base of bare) if (text.includes(base)) found.add(base);
1605
+ }
1606
+ return fileNames.filter((fileName) => found.has(baseOf(fileName)));
1607
+ }
1608
+ /** Deterministic: each name is the shortest prefix of its own hash that no other name in the set shares. */
1609
+ function shortNames(names, taken = /* @__PURE__ */ new Set()) {
1610
+ const hashes = [...new Set(names)].map((name) => [name, identifierHash(name)]);
1611
+ hashes.sort(([, a], [, b]) => a < b ? -1 : a > b ? 1 : 0);
1612
+ const result = /* @__PURE__ */ new Map();
1613
+ for (let index = 0; index < hashes.length; index++) {
1614
+ const [name, hash] = hashes[index];
1615
+ const shared = Math.max(commonPrefix(hash, hashes[index - 1]?.[1] ?? ""), commonPrefix(hash, hashes[index + 1]?.[1] ?? ""));
1616
+ let length = Math.max(MIN_LENGTH, shared + 1);
1617
+ while (length < hash.length && (RESERVED.has(hash.slice(0, length)) || taken.has(hash.slice(0, length)))) length++;
1618
+ const next = hash.slice(0, length);
1619
+ if (taken.has(next) || RESERVED.has(next) || hash.length === shared) throw new Error(`Markless could not give cross-chunk export ${name} a unique short name.`);
1620
+ result.set(name, next);
1621
+ }
1622
+ return result;
1623
+ }
1624
+ function shortExportNamesPlugin(removedChunks = () => /* @__PURE__ */ new Set()) {
1625
+ let pending = /* @__PURE__ */ new Map();
1626
+ let exports = /* @__PURE__ */ new Map();
1627
+ const planWhenAnalyzed = async (batch, options) => {
1628
+ pending = /* @__PURE__ */ new Map();
1629
+ try {
1630
+ const facts = /* @__PURE__ */ new Map();
1631
+ for (const [fileName, item] of batch) facts.set(fileName, await item.facts);
1632
+ const plan = planShortExportNames([...batch.values()].map((item) => item.chunk), (chunk) => facts.get(chunk.fileName));
1633
+ exports = new Map(plan.exports);
1634
+ for (const [fileName, item] of batch) {
1635
+ const list = plan.edits.get(fileName);
1636
+ if (!list?.length) {
1637
+ item.resolve(null);
1638
+ continue;
1639
+ }
1640
+ const source = new RolldownMagicString(item.chunk.code);
1641
+ for (const change of list) source.overwrite(change.start, change.end, change.source);
1642
+ item.resolve({
1643
+ code: source.toString(),
1644
+ map: options.sourcemap ? source.generateMap({ hires: true }).toString() : null
1645
+ });
1646
+ }
1647
+ } catch (error) {
1648
+ for (const item of batch.values()) item.reject(error);
1649
+ }
1650
+ };
1651
+ return {
1652
+ name: "markless-short-export-names",
1653
+ renderStart() {
1654
+ pending = /* @__PURE__ */ new Map();
1655
+ exports = /* @__PURE__ */ new Map();
1656
+ },
1657
+ renderChunk(code, chunk, options, meta) {
1658
+ const facade = chunk.facadeModuleId ? this.getModuleInfo(chunk.facadeModuleId) : null;
1659
+ return new Promise((resolve, reject) => {
1660
+ pending.set(chunk.fileName, {
1661
+ chunk: {
1662
+ fileName: chunk.fileName,
1663
+ code,
1664
+ exports: [...chunk.exports],
1665
+ isEntry: chunk.isEntry,
1666
+ isDynamicEntry: chunk.isDynamicEntry,
1667
+ signature: facade?.exports,
1668
+ removed: removedChunks().has(chunk.fileName)
1669
+ },
1670
+ facts: handled(runChunkTask("shortNameChunkFacts", chunk.fileName, code)),
1671
+ resolve,
1672
+ reject
1673
+ });
1674
+ if (pending.size !== renderedChunkCount(meta.chunks)) return;
1675
+ planWhenAnalyzed(pending, options);
1676
+ });
1677
+ },
1678
+ renderError(error) {
1679
+ for (const item of pending.values()) item.reject(error);
1680
+ pending.clear();
1681
+ },
1682
+ generateBundle: {
1683
+ order: "pre",
1684
+ handler(_, bundle) {
1685
+ for (const output of Object.values(bundle)) {
1686
+ if (output.type !== "chunk") continue;
1687
+ const final = exports.get(output.preliminaryFileName);
1688
+ if (final) output.exports = [...final];
1689
+ }
1690
+ }
1691
+ }
1692
+ };
1693
+ }
1694
+ function targetOf(importer, source, chunks) {
1695
+ return source === void 0 ? void 0 : resolveChunk(importer, source, chunks);
1696
+ }
1697
+ function sourceOf(node) {
1698
+ const value = node.source?.value;
1699
+ return typeof value === "string" ? value : void 0;
1700
+ }
1701
+ function resolveChunk(importer, specifier, chunks) {
1702
+ if (!specifier.startsWith(".")) return void 0;
1703
+ const target = normalize(join(dirname(importer), specifier));
1704
+ return chunks.has(target) ? target : void 0;
1705
+ }
1706
+ function nameOf(node) {
1707
+ return node.type === "Identifier" ? node.name : String(node.value);
1708
+ }
1709
+ function declaredNames(declaration) {
1710
+ if (declaration.type === "VariableDeclaration") return declaration.declarations.flatMap((item) => bindingNames(item.id));
1711
+ const id = declaration.id;
1712
+ return id ? [id.name] : [];
1713
+ }
1714
+ function bindingNames(pattern) {
1715
+ if (pattern.type === "Identifier") return [pattern.name];
1716
+ if (pattern.type === "ObjectPattern") return pattern.properties.flatMap((property) => bindingNames(property.type === "RestElement" ? property.argument : property.value));
1717
+ if (pattern.type === "ArrayPattern") return pattern.elements.flatMap((element) => element ? bindingNames(element) : []);
1718
+ if (pattern.type === "AssignmentPattern") return bindingNames(pattern.left);
1719
+ if (pattern.type === "RestElement") return bindingNames(pattern.argument);
1720
+ return [];
1721
+ }
1722
+ function scanReads(root, words, imports, strings) {
1723
+ const pending = [[
1724
+ root,
1725
+ void 0,
1726
+ void 0
1727
+ ]];
1728
+ while (pending.length) {
1729
+ const [item, parent, grandparent] = pending.pop();
1730
+ if (!item || typeof item !== "object") continue;
1731
+ if (Array.isArray(item)) {
1732
+ for (const child of item) pending.push([
1733
+ child,
1734
+ parent,
1735
+ grandparent
1736
+ ]);
1737
+ continue;
1738
+ }
1739
+ const syntax = item;
1740
+ if (typeof syntax.type !== "string") continue;
1741
+ switch (syntax.type) {
1742
+ case "ImportDeclaration":
1743
+ case "ExportAllDeclaration": continue;
1744
+ case "ExportNamedDeclaration":
1745
+ pending.push([
1746
+ syntax.declaration,
1747
+ syntax,
1748
+ parent
1749
+ ]);
1750
+ continue;
1751
+ case "ImportExpression": {
1752
+ const source = syntax.source;
1753
+ const value = source.type === "Literal" ? source.value : source.type === "TemplateLiteral" && !source.expressions.length ? (source.quasis[0]?.value)?.cooked : void 0;
1754
+ if (typeof value === "string" && !packerImport(syntax, parent, grandparent)) imports(value, namespaceReads(syntax, parent, grandparent));
1755
+ if (typeof value !== "string") pending.push([
1756
+ source,
1757
+ syntax,
1758
+ parent
1759
+ ]);
1760
+ pending.push([
1761
+ syntax.options,
1762
+ syntax,
1763
+ parent
1764
+ ]);
1765
+ continue;
1766
+ }
1767
+ case "CallExpression":
1768
+ if (syntax.callee.type === "Identifier" && syntax.callee.name === "__marklessPackLoad") {
1769
+ pending.push([
1770
+ syntax.arguments[2],
1771
+ syntax,
1772
+ parent
1773
+ ]);
1774
+ continue;
1775
+ }
1776
+ break;
1777
+ case "MemberExpression":
1778
+ case "Property":
1779
+ case "MethodDefinition":
1780
+ case "PropertyDefinition":
1781
+ case "AccessorProperty": {
1782
+ const key = syntax.property ?? syntax.key;
1783
+ if (key?.type === "Identifier" && !syntax.computed) words.add(key.name);
1784
+ break;
1785
+ }
1786
+ case "Literal":
1787
+ if (typeof syntax.value === "string") {
1788
+ collectWords(syntax.value, words);
1789
+ strings.push(syntax.value);
1790
+ }
1791
+ continue;
1792
+ case "TemplateElement": {
1793
+ const text = String(syntax.value.raw ?? "");
1794
+ collectWords(text, words);
1795
+ strings.push(text);
1796
+ continue;
1797
+ }
1798
+ }
1799
+ for (const key in syntax) {
1800
+ const value = syntax[key];
1801
+ if (key !== "type" && value && typeof value === "object") pending.push([
1802
+ value,
1803
+ syntax,
1804
+ parent
1805
+ ]);
1806
+ }
1807
+ }
1808
+ }
1809
+ function namespaceReads(node, parent, grandparent) {
1810
+ if (parent?.type !== "MemberExpression" || parent.object !== node || parent.computed || parent.property.name !== "then" || grandparent?.type !== "CallExpression" || grandparent.callee !== parent || grandparent.arguments.length !== 1) return void 0;
1811
+ const callback = grandparent.arguments[0];
1812
+ const params = callback.params;
1813
+ if (callback.type !== "ArrowFunctionExpression" || params?.length !== 1 || params[0].type !== "Identifier") return void 0;
1814
+ const namespace = params[0].name;
1815
+ let body = callback.body;
1816
+ while (body.type === "ParenthesizedExpression") body = body.expression;
1817
+ const reads = [];
1818
+ for (const expression of body.type === "SequenceExpression" ? body.expressions : [body]) {
1819
+ const member = expression.type === "CallExpression" && !expression.arguments.length ? expression.callee : expression;
1820
+ if (member.type !== "MemberExpression" || member.computed || member.object.type !== "Identifier" || member.object.name !== namespace) return void 0;
1821
+ reads.push(member.property);
1822
+ }
1823
+ return reads;
1824
+ }
1825
+ function packerImport(node, parent, grandparent) {
1826
+ if (parent?.type === "ArrowFunctionExpression" && grandparent?.type === "CallExpression" && grandparent.callee.type === "Identifier" && grandparent.callee.name === "__marklessPackLoad") return true;
1827
+ if (parent?.type === "MemberExpression" && parent.object === node && parent.property.name === "then" && grandparent?.type === "CallExpression") {
1828
+ const callback = grandparent.arguments[0];
1829
+ const call = callback?.type === "ArrowFunctionExpression" ? callback.body : void 0;
1830
+ const callee = call?.type === "CallExpression" ? call.callee : void 0;
1831
+ return grandparent.arguments.length === 1 && callee?.type === "MemberExpression" && !callee.computed && String(callee.property.name).startsWith("$ml");
1832
+ }
1833
+ if (parent?.type === "ArrayExpression" && grandparent?.type === "ForOfStatement") {
1834
+ const body = grandparent.body;
1835
+ const call = body.type === "ExpressionStatement" ? body.expression : void 0;
1836
+ const callee = call?.type === "CallExpression" ? call.callee : void 0;
1837
+ return callee?.type === "MemberExpression" && callee.property.name === "catch" && callee.object.type === "Identifier";
1838
+ }
1839
+ return false;
1840
+ }
1841
+ function collectWords(text, words) {
1842
+ for (const match of text.matchAll(WORD)) words.add(match[0]);
1843
+ }
1844
+ function commonPrefix(a, b) {
1845
+ let index = 0;
1846
+ while (index < a.length && a[index] === b[index]) index++;
1847
+ return index;
1848
+ }
1849
+ function identifierHash(text) {
1850
+ let hash = 14695981039346656037n;
1851
+ for (let index = 0; index < text.length; index++) {
1852
+ hash ^= BigInt(text.charCodeAt(index));
1853
+ hash = hash * 1099511628211n & 18446744073709551615n;
1854
+ }
1855
+ let name = START[Number(hash % BigInt(54))];
1856
+ hash /= BigInt(54);
1857
+ while (hash > 0n) {
1858
+ name += PART[Number(hash % BigInt(PART.length))];
1859
+ hash /= BigInt(PART.length);
1860
+ }
1861
+ return name;
1862
+ }
1863
+ function handled(promise) {
1864
+ promise.catch(() => {});
1865
+ return promise;
1866
+ }
1867
+ //#endregion
1868
+ //#region src/build/chunk-tasks.ts
1869
+ const CHUNK_TASKS = {
1870
+ packTopLevelEdits,
1871
+ shortNameChunkFacts,
1872
+ chunkDynamicImports: readChunkDynamicImports,
1873
+ facadeChunkFacts,
1874
+ strippedPreloadHelper: (_fileName, code) => stripEmptyVitePreloadWrappers(code),
1875
+ unwrappedAsyncImports: (_fileName, code) => unwrapAsyncImportWrappersInCode(code),
1876
+ helperImporterRewrite
1877
+ };
1878
+ function runChunkTaskInline(task, fileName, code, context) {
1879
+ return CHUNK_TASKS[task](fileName, code, context);
1880
+ }
1881
+ //#endregion
1882
+ //#region src/build-workers.ts
1883
+ const workers = [];
1884
+ const queue = [];
1885
+ let size = 0;
1886
+ let unavailable = false;
1887
+ let nextId = 0;
1888
+ function workerUrl() {
1889
+ return new URL(import.meta.url.endsWith(".ts") ? "./build-worker.ts" : "./build-worker.js", import.meta.url);
1890
+ }
1891
+ function addWorker() {
1892
+ if (unavailable || workers.length >= size) return;
1893
+ let worker;
1894
+ try {
1895
+ worker = new Worker(workerUrl());
1896
+ } catch {
1897
+ if (!workers.length) {
1898
+ unavailable = true;
1899
+ for (const queued of queue.splice(0)) giveBack(queued);
1900
+ }
1901
+ return;
1902
+ }
1903
+ const entry = {
1904
+ worker,
1905
+ writes: /* @__PURE__ */ new Map(),
1906
+ job: void 0,
1907
+ online: false
1908
+ };
1909
+ workers.push(entry);
1910
+ worker.unref();
1911
+ worker.once("online", () => {
1912
+ entry.online = true;
1913
+ addWorker();
1914
+ dispatch();
1915
+ });
1916
+ worker.on("message", (message) => {
1917
+ if (message.written) {
1918
+ entry.writes.get(message.id)?.();
1919
+ entry.writes.delete(message.id);
1920
+ return;
1921
+ }
1922
+ const job = entry.job;
1923
+ entry.job = void 0;
1924
+ if (job?.kind === "chunk") {
1925
+ if (message.error !== void 0) job.reject(new Error(message.error));
1926
+ else job.resolve(message.result);
1927
+ } else if (job && (message.failed || !message.buffer)) job.resolve(void 0);
1928
+ else if (job) {
1929
+ if (job.store) job.written(new Promise((resolve) => entry.writes.set(job.id, resolve)));
1930
+ job.resolve(deserialize(new Uint8Array(message.buffer, message.offset, message.length)));
1931
+ }
1932
+ dispatch();
1933
+ });
1934
+ const retire = () => {
1935
+ const index = workers.indexOf(entry);
1936
+ if (index === -1) return;
1937
+ workers.splice(index, 1);
1938
+ const job = entry.job;
1939
+ entry.job = void 0;
1940
+ if (job) giveBack(job);
1941
+ for (const written of entry.writes.values()) written();
1942
+ entry.writes.clear();
1943
+ if (!workers.some((item) => item.online)) for (const queued of queue.splice(0)) giveBack(queued);
1944
+ dispatch();
1945
+ };
1946
+ worker.on("error", retire);
1947
+ worker.on("exit", retire);
1948
+ }
1949
+ function dispatch() {
1950
+ for (const entry of workers) {
1951
+ if (!entry.online || entry.job) continue;
1952
+ const job = queue.shift();
1953
+ if (!job) break;
1954
+ entry.job = job;
1955
+ entry.worker.ref();
1956
+ try {
1957
+ entry.worker.postMessage(job.kind === "chunk" ? {
1958
+ kind: "chunk",
1959
+ id: job.id,
1960
+ task: job.task,
1961
+ fileName: job.fileName,
1962
+ code: job.code,
1963
+ context: job.context
1964
+ } : {
1965
+ kind: "compile",
1966
+ id: job.id,
1967
+ input: job.input,
1968
+ key: job.key,
1969
+ store: job.store
1970
+ });
1971
+ } catch {
1972
+ entry.job = void 0;
1973
+ giveBack(job);
1974
+ }
1975
+ }
1976
+ for (const entry of workers) if (!entry.job) entry.worker.unref();
1977
+ }
1978
+ function giveBack(job) {
1979
+ if (job.kind === "compile") {
1980
+ job.resolve(void 0);
1981
+ return;
1982
+ }
1983
+ try {
1984
+ job.resolve(runChunkTaskInline(job.task, job.fileName, job.code, job.context));
1985
+ } catch (error) {
1986
+ job.reject(error);
1987
+ }
1988
+ }
1989
+ /** How many build workers a process starts: one per core but one, at most seven, or `MARKLESS_COMPILE_WORKERS`. */
1990
+ function buildWorkerCount() {
1991
+ const configured = Number(process.env.MARKLESS_COMPILE_WORKERS);
1992
+ if (Number.isInteger(configured) && configured >= 0) return configured;
1993
+ return Math.max(0, Math.min(availableParallelism() - 1, 7));
1994
+ }
1995
+ /** Runs a chunk read on a build worker, or on the calling thread when the process starts none. */
1996
+ function runChunkJob(task, fileName, code, context) {
1997
+ size = Math.max(size, buildWorkerCount());
1998
+ if (unavailable || size === 0) try {
1999
+ return Promise.resolve(runChunkTaskInline(task, fileName, code, context));
2000
+ } catch (error) {
2001
+ return Promise.reject(error);
2002
+ }
2003
+ if (!workers.length || workers.length < size && workers.every((entry) => entry.online)) addWorker();
2004
+ return new Promise((resolve, reject) => {
2005
+ queue.push({
2006
+ kind: "chunk",
2007
+ id: nextId++,
2008
+ task,
2009
+ fileName,
2010
+ code,
2011
+ context,
2012
+ resolve,
2013
+ reject
2014
+ });
2015
+ dispatch();
2016
+ });
2017
+ }
2018
+ /** Compiles on worker threads; a compile no worker can take yet runs on the calling thread. */
2019
+ function createCompileWorkerPool(options) {
2020
+ size = Math.max(size, options.size);
2021
+ const store = options.store && {
2022
+ directory: options.store.directory,
2023
+ fingerprint: options.store.fingerprint
2024
+ };
2025
+ const writes = /* @__PURE__ */ new Set();
2026
+ const runs = /* @__PURE__ */ new Set();
2027
+ let closed = false;
2028
+ return {
2029
+ run(input, key) {
2030
+ if (closed || options.size === 0) return void 0;
2031
+ if (!workers.length || workers.length < size && workers.every((entry) => entry.online)) addWorker();
2032
+ if (!workers.some((entry) => entry.online)) return void 0;
2033
+ const run = new Promise((resolve) => {
2034
+ queue.push({
2035
+ kind: "compile",
2036
+ id: nextId++,
2037
+ input,
2038
+ key,
2039
+ store,
2040
+ resolve,
2041
+ written: (write) => {
2042
+ writes.add(write);
2043
+ write.finally(() => writes.delete(write));
2044
+ options.store?.cache.track(write);
2045
+ }
2046
+ });
2047
+ dispatch();
2048
+ });
2049
+ runs.add(run);
2050
+ run.finally(() => runs.delete(run));
2051
+ return run;
2052
+ },
2053
+ async close() {
2054
+ closed = true;
2055
+ while (runs.size || writes.size) await Promise.all([...runs, ...writes]);
2056
+ }
2057
+ };
2058
+ }
2059
+ //#endregion
2060
+ //#region src/build/chunk-workers.ts
2061
+ const CHUNK_WORKER_MIN_CODE_LENGTH = 32768;
2062
+ /** Runs a chunk analysis on a build worker when the chunk is large enough to pay for the trip. */
2063
+ function runChunkTask(task, fileName, code, context) {
2064
+ if (code.length >= 32768) return runChunkJob(task, fileName, code, context);
2065
+ try {
2066
+ return Promise.resolve(runChunkTaskInline(task, fileName, code, context));
2067
+ } catch (error) {
2068
+ return Promise.reject(error);
2069
+ }
2070
+ }
2071
+ /** Reads the dynamic imports of every large chunk on the workers, so later passes find them cached. */
2072
+ async function prefetchChunkDynamicImports(chunks) {
2073
+ await Promise.all([...chunks].filter((chunk) => chunk.code.length >= 32768 && mayContainDynamicImport(chunk.code) && !knowsChunkDynamicImports(chunk.fileName, chunk.code)).map((chunk) => runChunkTask("chunkDynamicImports", chunk.fileName, chunk.code).then((found) => rememberChunkDynamicImports(chunk.fileName, chunk.code, found), () => {})));
2074
+ }
2075
+ //#endregion
2076
+ //#region src/build/lazy-module-facades.ts
2077
+ function lazyModuleFacadesPlugin(root = () => "", packOf, packRoutes, eagerLazyRoutes) {
2078
+ let chunks = {};
2079
+ let removed = /* @__PURE__ */ new Set();
2080
+ let pending = /* @__PURE__ */ new Map();
2081
+ const reset = () => {
2082
+ chunks = {};
2083
+ removed = /* @__PURE__ */ new Set();
2084
+ pending = /* @__PURE__ */ new Map();
2085
+ };
2086
+ return {
2087
+ name: "markless-lazy-module-facades",
2088
+ api: { removedChunks: () => removed },
2089
+ renderStart: reset,
2090
+ renderChunk(code, chunk, options, meta) {
2091
+ chunks[chunk.fileName] = {
2092
+ type: "chunk",
2093
+ fileName: chunk.fileName,
2094
+ isEntry: chunk.isEntry,
2095
+ facadeModuleId: chunk.facadeModuleId,
2096
+ code,
2097
+ imports: [...chunk.imports],
2098
+ dynamicImports: [...chunk.dynamicImports],
2099
+ moduleIds: [...chunk.moduleIds],
2100
+ exports: [...chunk.exports]
2101
+ };
2102
+ return new Promise((resolve, reject) => {
2103
+ pending.set(chunk.fileName, {
2104
+ resolve,
2105
+ reject
2106
+ });
2107
+ if (pending.size !== renderedChunkCount(meta.chunks)) return;
2108
+ const collapse = () => {
2109
+ try {
2110
+ const results = /* @__PURE__ */ new Map();
2111
+ chunks = Object.fromEntries(Object.entries(chunks).sort(([a], [b]) => localeOrder(a, b)));
2112
+ const originals = new Map(Object.values(chunks).map((item) => [item.fileName, item.code]));
2113
+ const edits = /* @__PURE__ */ new Map();
2114
+ removed = new Set(collapseLazyModuleFacades(chunks, (chunk, replacements, suffix) => edits.set(chunk.fileName, {
2115
+ replacements,
2116
+ suffix
2117
+ }), {
2118
+ root: root(),
2119
+ packOf,
2120
+ packRoutes,
2121
+ eagerLazyRoutes
2122
+ }).removed);
2123
+ const prefixes = buildPathIdentifierPrefixes(root());
2124
+ const strip = (text) => prefixes.reduce((result, prefix) => result.replaceAll(prefix, ""), text);
2125
+ for (const [fileName, original] of originals) {
2126
+ if (removed.has(fileName)) continue;
2127
+ const edit = edits.get(fileName);
2128
+ const replacements = edit?.replacements ?? [];
2129
+ const rootless = [];
2130
+ for (const prefix of prefixes) for (let start = original.indexOf(prefix); start !== -1; start = original.indexOf(prefix, start + prefix.length)) {
2131
+ const end = start + prefix.length;
2132
+ if (![...replacements, ...rootless].some((item) => start < item.end && item.start < end)) rootless.push({
2133
+ start,
2134
+ end,
2135
+ source: ""
2136
+ });
2137
+ }
2138
+ if (!edit && rootless.length === 0) continue;
2139
+ const source = new RolldownMagicString(original);
2140
+ for (const replacement of replacements) source.overwrite(replacement.start, replacement.end, strip(replacement.source));
2141
+ for (const range of rootless) source.remove(range.start, range.end);
2142
+ source.append(strip(edit?.suffix ?? ""));
2143
+ results.set(fileName, {
2144
+ code: source.toString(),
2145
+ map: options.sourcemap ? source.generateMap({ hires: true }).toString() : null
2146
+ });
2147
+ }
2148
+ for (const [name, wait] of pending) wait.resolve(results.get(name) ?? null);
2149
+ pending.clear();
2150
+ } catch (error) {
2151
+ for (const wait of pending.values()) wait.reject(error);
2152
+ pending.clear();
2153
+ }
2154
+ };
2155
+ Promise.all([prefetchChunkParses(Object.values(chunks).filter((item) => !item.moduleIds.length || mayContainDynamicImport(item.code))), prefetchFacadeChunkFacts(Object.values(chunks))]).then(() => {
2156
+ collapse();
2157
+ clearFacadeChunkFacts();
2158
+ clearChunkFactCaches();
2159
+ });
2160
+ });
2161
+ },
2162
+ renderError(error) {
2163
+ for (const wait of pending.values()) wait.reject(error);
2164
+ reset();
2165
+ },
2166
+ generateBundle: {
2167
+ order: "pre",
2168
+ handler(_, bundle) {
2169
+ const filenames = new Map(Object.values(bundle).filter((chunk) => chunk.type === "chunk").map((chunk) => [chunk.preliminaryFileName, chunk.fileName]));
2170
+ for (const [name, chunk] of Object.entries(bundle)) {
2171
+ if (chunk.type !== "chunk") continue;
2172
+ if (removed.has(chunk.preliminaryFileName)) {
2173
+ delete bundle[name];
2174
+ if (chunk.sourcemapFileName) delete bundle[chunk.sourcemapFileName];
2175
+ continue;
2176
+ }
2177
+ const updated = chunks[chunk.preliminaryFileName];
2178
+ if (!updated) continue;
2179
+ chunk.dynamicImports = updated.dynamicImports.map((name) => filenames.get(name) ?? name);
2180
+ chunk.imports = updated.imports.map((name) => filenames.get(name) ?? name);
2181
+ chunk.exports = updated.exports;
2182
+ chunk.moduleIds = updated.moduleIds;
2183
+ }
2184
+ }
2185
+ }
2186
+ };
2187
+ }
2188
+ const localeOrder = new Intl.Collator().compare;
2189
+ function buildPathIdentifierPrefixes(root) {
2190
+ const segments = root.split("/").filter(Boolean);
2191
+ const prefixes = [];
2192
+ for (let length = segments.length; length >= 2; length--) prefixes.push(encodeURIComponent(`/${segments.slice(0, length).join("/")}/`).replace(/[^\w$]/g, "_"));
2193
+ return prefixes;
2194
+ }
2195
+ function collapseLazyModuleFacades(bundle, onEdit, options = {}) {
2196
+ const chunks = new Map(Object.values(bundle).filter((item) => !!item && typeof item === "object" && item.type === "chunk").map((chunk) => [chunk.fileName, chunk]));
2197
+ const packs = new Map([...chunks.values()].map((chunk) => [chunk.fileName, chunkPack(chunk, options.packOf)]));
2198
+ const staticallyImported = new Set([...chunks.values()].flatMap((chunk) => chunk.imports));
2199
+ const inert = /* @__PURE__ */ new Map();
2200
+ const renderedCode = new Map([...chunks.values()].map((chunk) => [chunk.fileName, chunk.code]));
2201
+ const inertClosure = (fileName, seen = /* @__PURE__ */ new Set()) => {
2202
+ if (seen.has(fileName)) return true;
2203
+ seen.add(fileName);
2204
+ const chunk = chunks.get(fileName);
2205
+ if (!chunk) return false;
2206
+ let own = inert.get(fileName);
2207
+ if (own === void 0) {
2208
+ const facts = chunkInertness(chunk.fileName, renderedCode.get(fileName));
2209
+ own = facts.inert && facts.leafSources.every((source) => {
2210
+ const from = chunks.get(resolve$1(fileName, source));
2211
+ return !!from && !from.imports.length && inertClosure(from.fileName, /* @__PURE__ */ new Set());
2212
+ });
2213
+ inert.set(fileName, own);
2214
+ }
2215
+ return own && chunk.imports.every((name) => inertClosure(name, seen));
2216
+ };
2217
+ const referenced = /* @__PURE__ */ new Set();
2218
+ const unsupported = /* @__PURE__ */ new Set();
2219
+ const imports = /* @__PURE__ */ new Map();
2220
+ const awaitChecked = /* @__PURE__ */ new Map();
2221
+ const awaiting = { has(fileName) {
2222
+ let result = awaitChecked.get(fileName);
2223
+ if (result === void 0) {
2224
+ const code = renderedCode.get(fileName);
2225
+ result = code !== void 0 && chunkTopLevelAwait(fileName, code);
2226
+ awaitChecked.set(fileName, result);
2227
+ }
2228
+ return result;
2229
+ } };
2230
+ for (const chunk of chunks.values()) {
2231
+ const expressions = mayContainDynamicImport(chunk.code) ? chunkDynamicImports(chunk.fileName, chunk.code) ?? dynamicImportsFromTree(chunk) : [];
2232
+ imports.set(chunk.fileName, expressions);
2233
+ const resolved = /* @__PURE__ */ new Set();
2234
+ for (const expression of expressions) {
2235
+ const value = expression.specifier;
2236
+ if (value === void 0) continue;
2237
+ const target = resolve$1(chunk.fileName, value);
2238
+ resolved.add(target);
2239
+ referenced.add(target);
2240
+ if (!expression.plain) unsupported.add(target);
2241
+ }
2242
+ for (const target of chunk.dynamicImports) if (!resolved.has(target)) unsupported.add(target);
2243
+ }
2244
+ const facades = /* @__PURE__ */ new Map();
2245
+ const exportBindings = /* @__PURE__ */ new Map();
2246
+ const pending = [];
2247
+ for (const chunk of chunks.values()) {
2248
+ if (chunk.isEntry || chunk.moduleIds.length || !referenced.has(chunk.fileName) || unsupported.has(chunk.fileName) || chunk.exports.includes("then") || staticallyImported.has(chunk.fileName)) continue;
2249
+ const candidates = chunk.imports.filter((name) => chunk.imports.every((other) => other === name || !!chunks.get(name)?.imports.includes(other)));
2250
+ if (candidates.length !== 1) continue;
2251
+ const target = chunks.get(candidates[0]);
2252
+ if (!target || target === chunk || target.exports.includes("then") || !target.moduleIds.length && !target.exports.length) continue;
2253
+ const parsed = parseChunkCode(chunk.fileName, chunk.code);
2254
+ if (parsed.errors.length) continue;
2255
+ const bindings = /* @__PURE__ */ new Map();
2256
+ const calls = [];
2257
+ const exports = [];
2258
+ let supported = true;
2259
+ for (const node of parsed.program.body) {
2260
+ const from = node.type === "ImportDeclaration" ? resolve$1(chunk.fileName, node.source.value) : "";
2261
+ if (node.type === "ImportDeclaration" && !node.attributes?.length && (from === target.fileName || target.imports.includes(from))) for (const specifier of node.specifiers) {
2262
+ if (specifier.type !== "ImportSpecifier") {
2263
+ supported = false;
2264
+ break;
2265
+ }
2266
+ bindings.set(specifier.local.name, {
2267
+ from,
2268
+ name: specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value
2269
+ });
2270
+ }
2271
+ else if (node.type === "ExpressionStatement" && node.expression.type === "CallExpression" && node.expression.callee.type === "Identifier" && node.expression.arguments.length === 0) {
2272
+ const imported = bindings.get(node.expression.callee.name);
2273
+ if (!imported) {
2274
+ supported = false;
2275
+ break;
2276
+ }
2277
+ calls.push(imported);
2278
+ } else if (node.type === "ExportNamedDeclaration" && !node.declaration && !node.source) for (const specifier of node.specifiers) {
2279
+ const local = specifier.local.type === "Identifier" ? specifier.local.name : specifier.local.value;
2280
+ const imported = bindings.get(local);
2281
+ if (!imported) {
2282
+ supported = false;
2283
+ break;
2284
+ }
2285
+ exports.push([specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value, imported]);
2286
+ }
2287
+ else if (node.type !== "EmptyStatement") {
2288
+ supported = false;
2289
+ break;
2290
+ }
2291
+ }
2292
+ if (!supported || !exports.length || exports.some(([name]) => name === "then" || /^(0|[1-9]\d*)$/.test(name))) continue;
2293
+ exports.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
2294
+ let targetBindings = exportBindings.get(target.fileName);
2295
+ if (!targetBindings) {
2296
+ targetBindings = chunkLocalExportSpecifiers(target.fileName, target.code) ?? exportSpecifiersFromTree(target);
2297
+ exportBindings.set(target.fileName, targetBindings);
2298
+ }
2299
+ if ([...calls, ...exports.map(([, imported]) => imported)].some(({ from, name }) => from === target.fileName ? !targetBindings.has(name) : !chunks.get(from)?.exports.includes(name))) continue;
2300
+ pending.push({
2301
+ fileName: chunk.fileName,
2302
+ target,
2303
+ targetBindings,
2304
+ calls,
2305
+ exports,
2306
+ identity: facadeIdentity(chunk, exports, calls, options.root)
2307
+ });
2308
+ }
2309
+ pending.sort((a, b) => compareText(a.target.fileName, b.target.fileName) || compareText(a.identity, b.identity));
2310
+ const reservedNames = /* @__PURE__ */ new Map();
2311
+ const reserve = (target, base) => {
2312
+ let reserved = reservedNames.get(target.fileName);
2313
+ if (!reserved) {
2314
+ reserved = [...new Set(target.code.match(PACKED_NAME_PATTERN) ?? [])];
2315
+ reservedNames.set(target.fileName, reserved);
2316
+ }
2317
+ let name = base;
2318
+ for (let attempt = 1; reserved.some((taken) => taken.startsWith(name)); attempt++) name = `${base}_${attempt}`;
2319
+ reserved.push(name);
2320
+ return name;
2321
+ };
2322
+ const namespaces = /* @__PURE__ */ new Map();
2323
+ for (const facade of pending) {
2324
+ if (!namespaces.has(facade.target.fileName)) namespaces.set(facade.target.fileName, reserve(facade.target, "__marklessNamespace"));
2325
+ const loader = reserve(facade.target, `\$ml${shortHash(facade.identity)}`);
2326
+ const imports = [];
2327
+ const local = ({ from, name }) => {
2328
+ if (from === facade.target.fileName) return facade.targetBindings.get(name);
2329
+ let entry = imports.find((item) => item.from === from && item.name === name);
2330
+ if (!entry) imports.push(entry = {
2331
+ from,
2332
+ name,
2333
+ alias: `${loader}Import${imports.length}`
2334
+ });
2335
+ return entry.alias;
2336
+ };
2337
+ facades.set(facade.fileName, {
2338
+ target: facade.target,
2339
+ calls: facade.calls.map(local),
2340
+ exports: facade.exports.map(([name, imported]) => [name, local(imported)]),
2341
+ loader,
2342
+ imports
2343
+ });
2344
+ }
2345
+ const additions = /* @__PURE__ */ new Map();
2346
+ const usesRegistry = (chunk) => !chunk.isEntry && !chunk.code.includes("__marklessPackLoad");
2347
+ const registered = /* @__PURE__ */ new Map();
2348
+ for (const chunk of chunks.values()) {
2349
+ if (facades.has(chunk.fileName) || !usesRegistry(chunk)) continue;
2350
+ for (const node of imports.get(chunk.fileName) ?? []) {
2351
+ const value = node.specifier;
2352
+ const facade = typeof value === "string" && facades.get(resolve$1(chunk.fileName, value));
2353
+ if (!facade || facade.target === chunk && !awaiting.has(chunk.fileName)) continue;
2354
+ const loaders = registered.get(facade.target.fileName) ?? /* @__PURE__ */ new Set();
2355
+ loaders.add(facade.loader);
2356
+ registered.set(facade.target.fileName, loaders);
2357
+ }
2358
+ }
2359
+ for (const [fileName, facade] of facades) {
2360
+ const namespace = namespaces.get(facade.target.fileName);
2361
+ const declarations = additions.get(facade.target.fileName) ?? [`const ${namespace}=(${createPackedNamespace.toString()});`];
2362
+ const { loader } = facade;
2363
+ for (const { from, name, alias } of facade.imports) {
2364
+ const path = relative(dirname(facade.target.fileName), from);
2365
+ declarations.push(`import{${/^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name)} as ${alias}}from${JSON.stringify(path.startsWith(".") ? path : `./${path}`)};`);
2366
+ }
2367
+ declarations.push(`export function ${loader}(){const state=${loader}.state;if(state){if(state.failed)throw state.error;return state.value}try{${facade.calls.map((name) => `${name}();`).join("")}return(${loader}.state={value:${namespace}({__proto__:null,${facade.exports.map(([name, local]) => `get ${JSON.stringify(name)}(){return ${local}}`).join(",")}})}).value}catch(error){throw(${loader}.state={failed:true,error}).error}}`);
2368
+ additions.set(facade.target.fileName, declarations);
2369
+ facade.target.exports.push(loader);
2370
+ const original = chunks.get(fileName);
2371
+ if (original.facadeModuleId && !facade.target.moduleIds.includes(original.facadeModuleId)) facade.target.moduleIds.push(original.facadeModuleId);
2372
+ }
2373
+ const routeChunks = /* @__PURE__ */ new Map();
2374
+ for (const chunk of chunks.values()) {
2375
+ const pack = packs.get(chunk.fileName);
2376
+ if (pack?.startsWith("route:") && !facades.has(chunk.fileName)) routeChunks.set(pack.slice(6), [...routeChunks.get(pack.slice(6)) ?? [], chunk]);
2377
+ }
2378
+ const evaluatedByRoute = /* @__PURE__ */ new Map();
2379
+ for (const chunk of chunks.values()) {
2380
+ if (facades.has(chunk.fileName) || !usesRegistry(chunk)) continue;
2381
+ for (const node of imports.get(chunk.fileName) ?? []) {
2382
+ const value = node.specifier;
2383
+ const facade = typeof value === "string" && facades.get(resolve$1(chunk.fileName, value));
2384
+ if (!facade || facade.target === chunk || awaiting.has(facade.target.fileName) || evaluatesWith(chunk, facade.target, packs, awaiting, options.packRoutes) || !inertClosure(facade.target.fileName)) continue;
2385
+ const to = packs.get(facade.target.fileName);
2386
+ const toRoutes = to?.startsWith("shared:") ? options.packRoutes?.(to) : void 0;
2387
+ for (const route of toRoutes ?? []) for (const evaluator of routeChunks.get(route) ?? []) if (evaluator !== facade.target) evaluatedByRoute.set(evaluator.fileName, /* @__PURE__ */ new Set([...evaluatedByRoute.get(evaluator.fileName) ?? [], facade.target]));
2388
+ }
2389
+ }
2390
+ const eagerImports = /* @__PURE__ */ new Map();
2391
+ for (const target of chunks.values()) {
2392
+ const name = options.eagerLazyRoutes && ownPack(target, options.packOf);
2393
+ if (!name || startupPackOfLazy(name) === name || facades.has(target.fileName)) continue;
2394
+ const routes = options.eagerLazyRoutes(name);
2395
+ if (!routes?.length || !inertClosure(target.fileName)) continue;
2396
+ for (const route of routes) for (const evaluator of routeChunks.get(route) ?? []) {
2397
+ const own = ownPack(evaluator, options.packOf);
2398
+ if (evaluator === target || !own || startupPackOfLazy(own) !== own) continue;
2399
+ eagerImports.set(evaluator.fileName, [...eagerImports.get(evaluator.fileName) ?? [], target]);
2400
+ }
2401
+ }
2402
+ for (const [fileName, loaders] of registered) additions.get(fileName).push(`${PACK_REGISTRATION}={${[...loaders].join(",")}};`);
2403
+ for (const chunk of chunks.values()) {
2404
+ if (facades.has(chunk.fileName)) continue;
2405
+ const replacements = [];
2406
+ const lookup = usesRegistry(chunk);
2407
+ const evaluated = new Set(evaluatedByRoute.get(chunk.fileName));
2408
+ for (const node of imports.get(chunk.fileName) ?? []) {
2409
+ const value = node.specifier;
2410
+ if (typeof value !== "string") continue;
2411
+ const facade = facades.get(resolve$1(chunk.fileName, value));
2412
+ if (!facade) continue;
2413
+ const path = relative(dirname(chunk.fileName), facade.target.fileName);
2414
+ const specifier = JSON.stringify(path.startsWith(".") ? path : `./${path}`);
2415
+ if (lookup && evaluatesWith(chunk, facade.target, packs, awaiting, options.packRoutes) && inertClosure(facade.target.fileName)) evaluated.add(facade.target);
2416
+ replacements.push({
2417
+ start: node.start,
2418
+ end: node.end,
2419
+ source: facade.target === chunk && !awaiting.has(chunk.fileName) ? `(async()=>{await 0;return ${facade.loader}()})()` : lookup ? `${PACK_LOAD}(${specifier},"${facade.loader}",()=>import(${specifier}))` : `import(${specifier}).then(module=>module.${facade.loader}())`
2420
+ });
2421
+ }
2422
+ const eager = eagerImports.get(chunk.fileName) ?? [];
2423
+ for (const target of eager) {
2424
+ evaluated.delete(target);
2425
+ if (!chunk.imports.includes(target.fileName)) chunk.imports.push(target.fileName);
2426
+ }
2427
+ const suffix = [
2428
+ ...eager.map((target) => {
2429
+ const path = relative(dirname(chunk.fileName), target.fileName);
2430
+ return `import${JSON.stringify(path.startsWith(".") ? path : `./${path}`)};`;
2431
+ }),
2432
+ ...additions.get(chunk.fileName) ?? [],
2433
+ ...lookup && replacements.some(({ source }) => source.startsWith("__marklessPackLoad")) ? [PACK_LOAD_SOURCE] : [],
2434
+ ...evaluated.size ? [warmPacksSuffix([...evaluated].map((target) => {
2435
+ const path = relative(dirname(chunk.fileName), target.fileName);
2436
+ return path.startsWith(".") ? path : `./${path}`;
2437
+ }))] : []
2438
+ ].join("\n");
2439
+ if (replacements.length || suffix) onEdit?.(chunk, replacements, suffix);
2440
+ const pieces = [];
2441
+ let cursor = 0;
2442
+ for (const replacement of replacements.sort((a, b) => a.start - b.start)) {
2443
+ pieces.push(chunk.code.slice(cursor, replacement.start), replacement.source);
2444
+ cursor = replacement.end;
2445
+ }
2446
+ pieces.push(chunk.code.slice(cursor), suffix);
2447
+ chunk.code = pieces.join("");
2448
+ chunk.dynamicImports = [...new Set(chunk.dynamicImports.flatMap((id) => {
2449
+ const facade = facades.get(id);
2450
+ return facade?.target === chunk && !awaiting.has(chunk.fileName) ? [] : [facade?.target.fileName ?? id];
2451
+ }))];
2452
+ }
2453
+ for (const [key, value] of Object.entries(bundle)) if (facades.has(value?.fileName)) delete bundle[key];
2454
+ return { removed: [...facades.keys()] };
2455
+ }
2456
+ const PACK_REGISTRY = "__marklessPacks";
2457
+ const PACK_REGISTRATION = `(globalThis.${PACK_REGISTRY}??={})[import.meta.url]`;
2458
+ const PACKED_NAME_PATTERN = /\$ml[\w$]*|__marklessNamespace[\w$]*/g;
2459
+ const PACK_LOAD_SOURCE = `function ${PACK_LOAD}(specifier,loader,load){const pack=globalThis.${PACK_REGISTRY}?.[import.meta.resolve?.(specifier)];return pack?Promise.resolve().then(pack[loader]):load().then(module=>module[loader]())}`;
2460
+ function evaluatesWith(importer, target, packs, awaiting, packRoutes) {
2461
+ const from = packs.get(importer.fileName);
2462
+ const to = packs.get(target.fileName);
2463
+ const routes = (pack) => pack.startsWith("route:") ? [pack.slice(6)] : packRoutes?.(pack);
2464
+ const toRoutes = to && routes(to);
2465
+ return !!from && !!to && (to === "shared" || to === from || from !== "shared" && !!toRoutes && !!routes(from)?.every((route) => toRoutes.includes(route))) && target !== importer && !awaiting.has(target.fileName);
2466
+ }
2467
+ function chunkPack(chunk, packOf) {
2468
+ const names = new Set(chunk.moduleIds.map((id) => startupPackOfLazy(packOf?.(id) ?? "")));
2469
+ const [name] = names;
2470
+ return names.size === 1 ? /^(route:.+|shared(?::[0-9a-z]+)?)$/.exec(packOfPiece(name ?? ""))?.[1] : void 0;
2471
+ }
2472
+ function ownPack(chunk, packOf) {
2473
+ const names = new Set(chunk.moduleIds.map((id) => {
2474
+ const pack = packOf?.(id);
2475
+ return pack === void 0 ? void 0 : packOfPiece(pack);
2476
+ }));
2477
+ const [name] = names;
2478
+ return names.size === 1 ? name : void 0;
2479
+ }
2480
+ const inertnessByCode = /* @__PURE__ */ new Map();
2481
+ const topLevelAwaitByCode = /* @__PURE__ */ new Map();
2482
+ function chunkInertness(fileName, code) {
2483
+ return inertnessByCode.get(code) ?? readChunkInertness(fileName, code);
2484
+ }
2485
+ function chunkTopLevelAwait(fileName, code) {
2486
+ return topLevelAwaitByCode.get(code) ?? readChunkTopLevelAwait(fileName, code);
2487
+ }
2488
+ function readChunkInertness(fileName, code) {
2489
+ const parsed = parseChunkCode(fileName, code);
2490
+ if (parsed.errors.length) return { inert: false };
2491
+ const body = parsed.program.body;
2492
+ const leafSources = /* @__PURE__ */ new Set();
2493
+ const scope = topLevelScope(body, leafSources);
2494
+ return body.every((node) => inertStatement(node, scope)) ? {
2495
+ inert: true,
2496
+ leafSources: [...leafSources]
2497
+ } : { inert: false };
2498
+ }
2499
+ function readChunkTopLevelAwait(fileName, code) {
2500
+ return code.includes("await") && mayContainDynamicImport(code) && hasTopLevelAwait(parseChunkCode(fileName, code).program);
2501
+ }
2502
+ /** Everything the facade collapse reads from one chunk's code, from a single parse. */
2503
+ function facadeChunkFacts(fileName, code) {
2504
+ return {
2505
+ dynamicImports: mayContainDynamicImport(code) ? readChunkDynamicImports(fileName, code) : void 0,
2506
+ localExportSpecifiers: readChunkLocalExportSpecifiers(fileName, code),
2507
+ inertness: readChunkInertness(fileName, code),
2508
+ topLevelAwait: readChunkTopLevelAwait(fileName, code)
2509
+ };
2510
+ }
2511
+ /** Reads every large chunk's facade facts on the chunk workers, so the collapse finds them cached. */
2512
+ async function prefetchFacadeChunkFacts(chunks) {
2513
+ await Promise.all([...chunks].filter((chunk) => chunk.code.length >= CHUNK_WORKER_MIN_CODE_LENGTH).map((chunk) => runChunkTask("facadeChunkFacts", chunk.fileName, chunk.code).then((facts) => {
2514
+ if (facts.dynamicImports !== void 0 || mayContainDynamicImport(chunk.code)) rememberChunkDynamicImports(chunk.fileName, chunk.code, facts.dynamicImports);
2515
+ rememberChunkLocalExportSpecifiers(chunk.fileName, chunk.code, facts.localExportSpecifiers);
2516
+ inertnessByCode.set(chunk.code, facts.inertness);
2517
+ topLevelAwaitByCode.set(chunk.code, facts.topLevelAwait);
2518
+ }, () => {})));
2519
+ }
2520
+ function clearFacadeChunkFacts() {
2521
+ inertnessByCode.clear();
2522
+ topLevelAwaitByCode.clear();
2523
+ }
2524
+ function topLevelScope(body, leafSources) {
2525
+ const declared = /* @__PURE__ */ new Set();
2526
+ const importSources = /* @__PURE__ */ new Map();
2527
+ for (const node of body) {
2528
+ const declaration = node.type === "ExportNamedDeclaration" ? node.declaration : node;
2529
+ if (node.type === "ImportDeclaration") {
2530
+ const source = node.source.value;
2531
+ for (const specifier of node.specifiers) {
2532
+ declared.add(specifier.local.name);
2533
+ importSources.set(specifier.local.name, source);
2534
+ }
2535
+ } else if (declaration?.type === "FunctionDeclaration" || declaration?.type === "ClassDeclaration") declared.add(declaration.id.name);
2536
+ else if (declaration?.type === "VariableDeclaration") {
2537
+ for (const declarator of declaration.declarations) if (declarator.id.type === "Identifier") declared.add(declarator.id.name);
2538
+ }
2539
+ }
2540
+ return {
2541
+ declared,
2542
+ leafImports: { has(name) {
2543
+ const source = importSources.get(name);
2544
+ if (source === void 0) return false;
2545
+ leafSources.add(source);
2546
+ return true;
2547
+ } }
2548
+ };
2549
+ }
2550
+ function inertStatement(node, scope) {
2551
+ switch (node.type) {
2552
+ case "ImportDeclaration":
2553
+ case "ExportAllDeclaration":
2554
+ case "FunctionDeclaration":
2555
+ case "EmptyStatement": return true;
2556
+ case "ExportNamedDeclaration": return !node.declaration || inertStatement(node.declaration, scope);
2557
+ case "VariableDeclaration": return node.declarations.every((declarator) => declarator.id.type === "Identifier" && (!declarator.init || inertValue(declarator.init, scope)));
2558
+ case "ExpressionStatement": return typeof node.directive === "string";
2559
+ default: return false;
2560
+ }
2561
+ }
2562
+ function inertValue(node, scope) {
2563
+ switch (node.type) {
2564
+ case "Literal":
2565
+ case "FunctionExpression":
2566
+ case "ArrowFunctionExpression": return true;
2567
+ case "TemplateLiteral": return !node.expressions.length;
2568
+ case "ParenthesizedExpression": return inertValue(node.expression, scope);
2569
+ case "MemberExpression": {
2570
+ let object = node;
2571
+ while (object.type === "MemberExpression" && !object.computed) object = object.object;
2572
+ return object.type === "Identifier" && !scope.declared.has(object.name);
2573
+ }
2574
+ case "ObjectExpression": return node.properties.every((property) => property.type === "Property" && !property.computed && inertValue(property.value, scope));
2575
+ case "CallExpression": return node.callee.type === "Identifier" && scope.leafImports.has(node.callee.name) && node.arguments.every((argument) => inertValue(argument, scope));
2576
+ default: return false;
2577
+ }
2578
+ }
2579
+ function createPackedNamespace(bindings) {
2580
+ const keys = Object.keys(bindings).sort();
2581
+ const target = Object.create(null);
2582
+ for (const key of keys) Object.defineProperty(target, key, {
2583
+ writable: true,
2584
+ enumerable: true,
2585
+ configurable: false
2586
+ });
2587
+ Object.defineProperty(target, Symbol.toStringTag, { value: "Module" });
2588
+ Object.preventExtensions(target);
2589
+ return new Proxy(target, {
2590
+ get(target, key) {
2591
+ return key in bindings ? Reflect.get(bindings, key) : Reflect.get(target, key);
2592
+ },
2593
+ getOwnPropertyDescriptor(target, key) {
2594
+ const descriptor = Reflect.getOwnPropertyDescriptor(target, key);
2595
+ if (descriptor && typeof key === "string") descriptor.value = Reflect.get(bindings, key);
2596
+ return descriptor;
2597
+ },
2598
+ defineProperty(target, key, descriptor) {
2599
+ if (!(key in bindings)) return Reflect.defineProperty(target, key, descriptor);
2600
+ return descriptor.configurable !== true && descriptor.enumerable !== false && descriptor.writable !== false && !("get" in descriptor) && !("set" in descriptor) && (!("value" in descriptor) || Object.is(descriptor.value, Reflect.get(bindings, key)));
2601
+ },
2602
+ set() {
2603
+ return false;
2604
+ },
2605
+ ownKeys() {
2606
+ return [...keys, Symbol.toStringTag];
2607
+ }
2608
+ });
2609
+ }
2610
+ function facadeIdentity(chunk, exports, calls, root) {
2611
+ const module = chunk.facadeModuleId ? rootRelativeId(chunk.facadeModuleId, root) : "";
2612
+ return withoutMachinePaths([
2613
+ module,
2614
+ exports.map(([name, binding]) => `${name}=${binding.name}`).join(","),
2615
+ calls.map((binding) => binding.name).join(",")
2616
+ ].join("\0"), root);
2617
+ }
2618
+ function shortHash(text) {
2619
+ let hash = 2166136261;
2620
+ for (let index = 0; index < text.length; index++) {
2621
+ hash ^= text.charCodeAt(index);
2622
+ hash = Math.imul(hash, 16777619);
2623
+ }
2624
+ hash >>>= 0;
2625
+ let name = "";
2626
+ for (let index = 0; index < 4; index++) {
2627
+ name += HASH_ALPHABET[hash % HASH_ALPHABET.length];
2628
+ hash = Math.floor(hash / HASH_ALPHABET.length);
2629
+ }
2630
+ return name;
2631
+ }
2632
+ const HASH_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2633
+ function compareText(a, b) {
2634
+ return a < b ? -1 : a > b ? 1 : 0;
2635
+ }
2636
+ function dynamicImportsFromTree(chunk) {
2637
+ const expressions = [];
2638
+ const program = parseChunkCode(chunk.fileName, chunk.code).program;
2639
+ walk(program, textOffsets(chunk.code, "import"), (node) => {
2640
+ if (node.type !== "ImportExpression") return;
2641
+ const value = importSource(node);
2642
+ expressions.push({
2643
+ start: node.start,
2644
+ end: node.end,
2645
+ specifier: typeof value === "string" ? value : void 0,
2646
+ plain: !(node.options || node.phase && node.phase !== "evaluation")
2647
+ });
2648
+ });
2649
+ return expressions;
2650
+ }
2651
+ function exportSpecifiersFromTree(chunk) {
2652
+ const bindings = /* @__PURE__ */ new Map();
2653
+ for (const node of parseChunkCode(chunk.fileName, chunk.code).program.body) {
2654
+ if (node.type !== "ExportNamedDeclaration" || node.source) continue;
2655
+ for (const specifier of node.specifiers) {
2656
+ if (specifier.local.type !== "Identifier") continue;
2657
+ bindings.set(specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value, specifier.local.name);
2658
+ }
2659
+ }
2660
+ return bindings;
2661
+ }
2662
+ function importSource(node) {
2663
+ const source = node.source;
2664
+ return source.type === "Literal" ? source.value : source.type === "TemplateLiteral" && source.expressions.length === 0 ? (source.quasis[0]?.value)?.cooked : void 0;
2665
+ }
2666
+ function resolve$1(importer, source) {
2667
+ return source.startsWith(".") ? normalize(join(dirname(importer), source)) : source;
2668
+ }
2669
+ function hasTopLevelAwait(value) {
2670
+ if (!value || typeof value !== "object") return false;
2671
+ if (Array.isArray(value)) return value.some(hasTopLevelAwait);
2672
+ const node = value;
2673
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") return false;
2674
+ if (node.type === "AwaitExpression" || node.type === "ForOfStatement" && node.await) return true;
2675
+ return Object.values(node).some(hasTopLevelAwait);
2676
+ }
2677
+ function walk(value, offsets, visit) {
2678
+ if (!value || typeof value !== "object") return;
2679
+ if (Array.isArray(value)) {
2680
+ for (const item of value) if (mayHold(offsets, item)) walk(item, offsets, visit);
2681
+ return;
2682
+ }
2683
+ const node = value;
2684
+ visit(node);
2685
+ for (const item of Object.values(node)) if (mayHold(offsets, item)) walk(item, offsets, visit);
2686
+ }
2687
+ function mayHold(offsets, value) {
2688
+ return !value || typeof value !== "object" || Array.isArray(value) || spansAnyOffset(offsets, value);
2689
+ }
2690
+ //#endregion
2691
+ export { createCompileWorkerPool as a, stripUnusedVitePreloadHelperFromBundle as c, buildWorkerCount as i, packTopLevelPlugin as l, prefetchChunkDynamicImports as n, runChunkTaskInline as o, runChunkTask as r, shortExportNamesPlugin as s, lazyModuleFacadesPlugin as t, unwrapAsyncImportWrappers as u };