nitro-nightly 3.1.0-20251028-004953-57503e42 → 3.1.0-20251028-110430-e607b753

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.
Files changed (155) hide show
  1. package/dist/_build/assets.mjs +235 -0
  2. package/dist/_build/build.mjs +21 -0
  3. package/dist/_build/config.mjs +124 -0
  4. package/dist/_build/info.mjs +39 -0
  5. package/dist/_build/plugins.mjs +1041 -0
  6. package/dist/_build/prepare.mjs +17 -0
  7. package/dist/{_chunks/build2.mjs → _build/rolldown.mjs} +238 -64
  8. package/dist/_build/rollup.mjs +404 -0
  9. package/dist/_build/snapshot.mjs +61 -0
  10. package/dist/_build/types.mjs +268 -0
  11. package/dist/_build/vite.mjs +3266 -0
  12. package/dist/{cli → _cli}/build.mjs +2 -3
  13. package/dist/_cli/dev.mjs +205 -0
  14. package/dist/{cli/index2.mjs → _cli/index.mjs} +1 -2
  15. package/dist/{cli → _cli}/list.mjs +2 -3
  16. package/dist/{cli → _cli}/prepare.mjs +2 -3
  17. package/dist/{cli → _cli}/run.mjs +2 -3
  18. package/dist/_deps/@jridgewell/gen-mapping.mjs +189 -0
  19. package/dist/_deps/@jridgewell/remapping.mjs +137 -0
  20. package/dist/_deps/@jridgewell/resolve-uri.mjs +231 -0
  21. package/dist/_deps/@jridgewell/sourcemap-codec.mjs +173 -0
  22. package/dist/_deps/@jridgewell/trace-mapping.mjs +170 -0
  23. package/dist/_deps/@pi0/vite-plugin-fullstack.mjs +575 -0
  24. package/dist/_deps/@rollup/plugin-alias.mjs +89 -0
  25. package/dist/_deps/@rollup/plugin-commonjs.mjs +2376 -0
  26. package/dist/{_chunks/index2.mjs → _deps/@rollup/plugin-inject.mjs} +5 -90
  27. package/dist/_deps/@rollup/plugin-json.mjs +37 -0
  28. package/dist/_deps/@rollup/plugin-node-resolve.mjs +1386 -0
  29. package/dist/_deps/@rollup/plugin-replace.mjs +133 -0
  30. package/dist/_deps/@rollup/pluginutils.mjs +346 -0
  31. package/dist/_deps/acorn.mjs +6225 -0
  32. package/dist/_deps/c12.mjs +510 -0
  33. package/dist/_deps/chokidar.mjs +1428 -0
  34. package/dist/_deps/citty.mjs +460 -0
  35. package/dist/_deps/commondir.mjs +77 -0
  36. package/dist/_deps/compatx.mjs +76 -0
  37. package/dist/_deps/confbox.mjs +300 -0
  38. package/dist/_deps/debug.mjs +885 -0
  39. package/dist/_deps/deepmerge.mjs +147 -0
  40. package/dist/_deps/depd.mjs +550 -0
  41. package/dist/_deps/dot-prop.mjs +282 -0
  42. package/dist/_deps/dotenv.mjs +555 -0
  43. package/dist/_deps/duplexer.mjs +1 -0
  44. package/dist/_deps/ee-first.mjs +104 -0
  45. package/dist/_deps/encodeurl.mjs +69 -0
  46. package/dist/_deps/escape-html.mjs +87 -0
  47. package/dist/_deps/escape-string-regexp.mjs +13 -0
  48. package/dist/_deps/estree-walker.mjs +433 -0
  49. package/dist/_deps/etag.mjs +147 -0
  50. package/dist/_deps/exsolve.mjs +1416 -0
  51. package/dist/_deps/fdir.mjs +569 -0
  52. package/dist/_deps/fresh.mjs +145 -0
  53. package/dist/_deps/function-bind.mjs +106 -0
  54. package/dist/{_chunks/index4.mjs → _deps/giget.mjs} +21 -776
  55. package/dist/_deps/gzip-size.mjs +19 -0
  56. package/dist/_deps/hasown.mjs +19 -0
  57. package/dist/_deps/http-errors.mjs +307 -0
  58. package/dist/_deps/httpxy.mjs +580 -0
  59. package/dist/_deps/inherits.mjs +57 -0
  60. package/dist/_deps/is-core-module.mjs +596 -0
  61. package/dist/_deps/is-module.mjs +25 -0
  62. package/dist/_deps/is-reference.mjs +31 -0
  63. package/dist/_deps/js-tokens.mjs +411 -0
  64. package/dist/_deps/knitwork.mjs +172 -0
  65. package/dist/_deps/local-pkg.mjs +163 -0
  66. package/dist/_deps/magic-string.mjs +1296 -0
  67. package/dist/_deps/mime-db.mjs +11685 -0
  68. package/dist/_deps/mime-types.mjs +287 -0
  69. package/dist/_deps/mime.mjs +1172 -0
  70. package/dist/_deps/mlly.mjs +2413 -0
  71. package/dist/_deps/ms.mjs +172 -0
  72. package/dist/_deps/node-fetch-native.mjs +3 -0
  73. package/dist/_deps/nypm.mjs +219 -0
  74. package/dist/_deps/on-finished.mjs +246 -0
  75. package/dist/_deps/parseurl.mjs +168 -0
  76. package/dist/_deps/path-parse.mjs +85 -0
  77. package/dist/{_chunks/pathe.M-eThtNZ.mjs → _deps/pathe.mjs} +48 -1
  78. package/dist/_deps/perfect-debounce.mjs +88 -0
  79. package/dist/_deps/picomatch.mjs +2144 -0
  80. package/dist/_deps/pkg-types.mjs +247 -0
  81. package/dist/_deps/pretty-bytes.mjs +180 -0
  82. package/dist/_deps/quansync.mjs +99 -0
  83. package/dist/_deps/range-parser.mjs +171 -0
  84. package/dist/_deps/rc9.mjs +219 -0
  85. package/dist/_deps/readdirp.mjs +245 -0
  86. package/dist/_deps/resolve.mjs +1260 -0
  87. package/dist/_deps/rou3.mjs +326 -0
  88. package/dist/_deps/send.mjs +1022 -0
  89. package/dist/_deps/serve-static.mjs +228 -0
  90. package/dist/_deps/setprototypeof.mjs +26 -0
  91. package/dist/_deps/statuses.mjs +457 -0
  92. package/dist/_deps/strip-literal.mjs +67 -0
  93. package/dist/_deps/supports-color.mjs +44 -0
  94. package/dist/_deps/tinyexec.mjs +552 -0
  95. package/dist/_deps/tinyglobby.mjs +293 -0
  96. package/dist/_deps/toidentifier.mjs +41 -0
  97. package/dist/_deps/ultrahtml.mjs +3 -0
  98. package/dist/_deps/unimport.mjs +2267 -0
  99. package/dist/_deps/unplugin-utils.mjs +65 -0
  100. package/dist/_deps/unplugin.mjs +1294 -0
  101. package/dist/_deps/untyped.mjs +375 -0
  102. package/dist/{_chunks/info.mjs → _deps/unwasm.mjs} +8 -4122
  103. package/dist/_deps/webpack-virtual-modules.mjs +360 -0
  104. package/dist/_presets/_all.mjs +59 -0
  105. package/dist/_presets/_nitro.mjs +74 -0
  106. package/dist/_presets/_resolve.mjs +64 -0
  107. package/dist/_presets/_static.mjs +69 -0
  108. package/dist/_presets/_types.mjs +3 -0
  109. package/dist/_presets/_utils.mjs +31 -0
  110. package/dist/_presets/alwaysdata.mjs +17 -0
  111. package/dist/_presets/aws-amplify.mjs +111 -0
  112. package/dist/_presets/aws-lambda.mjs +23 -0
  113. package/dist/_presets/azure.mjs +162 -0
  114. package/dist/_presets/bun.mjs +19 -0
  115. package/dist/_presets/cleavr.mjs +15 -0
  116. package/dist/_presets/cloudflare.mjs +608 -0
  117. package/dist/_presets/deno.mjs +196 -0
  118. package/dist/_presets/digitalocean.mjs +14 -0
  119. package/dist/_presets/firebase.mjs +47 -0
  120. package/dist/_presets/flightcontrol.mjs +14 -0
  121. package/dist/_presets/genezio.mjs +13 -0
  122. package/dist/_presets/heroku.mjs +14 -0
  123. package/dist/_presets/iis.mjs +194 -0
  124. package/dist/_presets/index.mjs +62 -0
  125. package/dist/_presets/koyeb.mjs +14 -0
  126. package/dist/_presets/netlify.mjs +241 -0
  127. package/dist/_presets/node.mjs +54 -0
  128. package/dist/_presets/platform.mjs +14 -0
  129. package/dist/_presets/render.mjs +14 -0
  130. package/dist/_presets/standard.mjs +23 -0
  131. package/dist/_presets/stormkit.mjs +18 -0
  132. package/dist/_presets/vercel.mjs +365 -0
  133. package/dist/_presets/winterjs.mjs +22 -0
  134. package/dist/_presets/zeabur.mjs +69 -0
  135. package/dist/_presets/zerops.mjs +27 -0
  136. package/dist/cli/index.mjs +7 -464
  137. package/dist/index.mjs +122 -34
  138. package/dist/vite.mjs +118 -44
  139. package/package.json +1 -1
  140. package/dist/_chunks/app.mjs +0 -19797
  141. package/dist/_chunks/build.mjs +0 -86
  142. package/dist/_chunks/build3.mjs +0 -6538
  143. package/dist/_chunks/detect-acorn.mjs +0 -503
  144. package/dist/_chunks/index.mjs +0 -22256
  145. package/dist/_chunks/index3.mjs +0 -1062
  146. package/dist/_chunks/json5.mjs +0 -68
  147. package/dist/_chunks/jsonc.mjs +0 -51
  148. package/dist/_chunks/plugin.mjs +0 -1560
  149. package/dist/_chunks/server.mjs +0 -254
  150. package/dist/_chunks/snapshot.mjs +0 -376
  151. package/dist/_chunks/toml.mjs +0 -259
  152. package/dist/_chunks/yaml.mjs +0 -86
  153. package/dist/cli/dev.mjs +0 -95
  154. package/dist/presets.mjs +0 -2494
  155. /package/dist/{cli → _cli}/common.mjs +0 -0
@@ -1,3286 +1,9 @@
1
- import { G as pm, M as MagicString, P as Parser, H as decode, I as encode, J as createUnimport, K as genSafeVariableName, L as genImport, O as genString, Q as genObjectFromRaw, b as glob, m as mime, r as resolveModulePath, w as writeFile } from './index.mjs';
2
- import sysPath__default, { win32, posix, isAbsolute, resolve as resolve$1 } from 'path';
3
- import { defineEnv } from 'unenv';
4
- import { runtimeDir, runtimeDependencies } from 'nitro/runtime/meta';
5
- import { j as join, r as resolve$2, i as isAbsolute$3, b as basename$1, d as dirname$1, e as extname$1, a as relative } from './pathe.M-eThtNZ.mjs';
6
- import { fileURLToPath, pathToFileURL } from 'node:url';
7
- import { createRequire, builtinModules } from 'node:module';
8
- import { hash } from 'ohash';
9
- import { defu } from 'defu';
10
- import fs, { promises, existsSync } from 'node:fs';
11
- import path, { resolve as resolve$3, isAbsolute as isAbsolute$2, normalize, dirname, basename, extname } from 'node:path';
12
- import { Buffer as Buffer$1 } from 'node:buffer';
13
- import process$1 from 'node:process';
14
- import * as querystring from 'node:querystring';
15
- import { g as getDefaultExportFromCjs, r as requireEtag } from './app.mjs';
16
- import require$$0 from 'constants';
17
- import { camelCase } from 'scule';
18
- import { readFile, mkdir, unlink, symlink } from 'node:fs/promises';
19
- import 'node:os';
1
+ import { existsSync, promises } from 'node:fs';
2
+ import { M as MagicString } from './magic-string.mjs';
3
+ import { c as createUnplugin } from './unplugin.mjs';
20
4
  import { createHash } from 'node:crypto';
21
- import { connectors } from 'db0';
22
- import { transform } from 'esbuild';
23
- import { withTrailingSlash } from 'ufo';
24
- import { normalizeKey, builtinDrivers } from 'unstorage';
25
- import { rollupNodeFileTrace } from 'nf3';
26
- import { hasTemplateSyntax, compileTemplateToString, RENDER_CONTEXT_KEYS } from 'rendu';
27
- import { version } from 'nitro/meta';
28
-
29
- // @ts-check
30
- /** @typedef { import('estree').BaseNode} BaseNode */
31
-
32
- /** @typedef {{
33
- skip: () => void;
34
- remove: () => void;
35
- replace: (node: BaseNode) => void;
36
- }} WalkerContext */
37
-
38
- class WalkerBase {
39
- constructor() {
40
- /** @type {boolean} */
41
- this.should_skip = false;
42
-
43
- /** @type {boolean} */
44
- this.should_remove = false;
45
-
46
- /** @type {BaseNode | null} */
47
- this.replacement = null;
48
-
49
- /** @type {WalkerContext} */
50
- this.context = {
51
- skip: () => (this.should_skip = true),
52
- remove: () => (this.should_remove = true),
53
- replace: (node) => (this.replacement = node)
54
- };
55
- }
56
-
57
- /**
58
- *
59
- * @param {any} parent
60
- * @param {string} prop
61
- * @param {number} index
62
- * @param {BaseNode} node
63
- */
64
- replace(parent, prop, index, node) {
65
- if (parent) {
66
- if (index !== null) {
67
- parent[prop][index] = node;
68
- } else {
69
- parent[prop] = node;
70
- }
71
- }
72
- }
73
-
74
- /**
75
- *
76
- * @param {any} parent
77
- * @param {string} prop
78
- * @param {number} index
79
- */
80
- remove(parent, prop, index) {
81
- if (parent) {
82
- if (index !== null) {
83
- parent[prop].splice(index, 1);
84
- } else {
85
- delete parent[prop];
86
- }
87
- }
88
- }
89
- }
90
-
91
- // @ts-check
92
-
93
- /** @typedef { import('estree').BaseNode} BaseNode */
94
- /** @typedef { import('./walker.js').WalkerContext} WalkerContext */
95
-
96
- /** @typedef {(
97
- * this: WalkerContext,
98
- * node: BaseNode,
99
- * parent: BaseNode,
100
- * key: string,
101
- * index: number
102
- * ) => void} SyncHandler */
103
-
104
- class SyncWalker extends WalkerBase {
105
- /**
106
- *
107
- * @param {SyncHandler} enter
108
- * @param {SyncHandler} leave
109
- */
110
- constructor(enter, leave) {
111
- super();
112
-
113
- /** @type {SyncHandler} */
114
- this.enter = enter;
115
-
116
- /** @type {SyncHandler} */
117
- this.leave = leave;
118
- }
119
-
120
- /**
121
- *
122
- * @param {BaseNode} node
123
- * @param {BaseNode} parent
124
- * @param {string} [prop]
125
- * @param {number} [index]
126
- * @returns {BaseNode}
127
- */
128
- visit(node, parent, prop, index) {
129
- if (node) {
130
- if (this.enter) {
131
- const _should_skip = this.should_skip;
132
- const _should_remove = this.should_remove;
133
- const _replacement = this.replacement;
134
- this.should_skip = false;
135
- this.should_remove = false;
136
- this.replacement = null;
137
-
138
- this.enter.call(this.context, node, parent, prop, index);
139
-
140
- if (this.replacement) {
141
- node = this.replacement;
142
- this.replace(parent, prop, index, node);
143
- }
144
-
145
- if (this.should_remove) {
146
- this.remove(parent, prop, index);
147
- }
148
-
149
- const skipped = this.should_skip;
150
- const removed = this.should_remove;
151
-
152
- this.should_skip = _should_skip;
153
- this.should_remove = _should_remove;
154
- this.replacement = _replacement;
155
-
156
- if (skipped) return node;
157
- if (removed) return null;
158
- }
159
-
160
- for (const key in node) {
161
- const value = node[key];
162
-
163
- if (typeof value !== "object") {
164
- continue;
165
- } else if (Array.isArray(value)) {
166
- for (let i = 0; i < value.length; i += 1) {
167
- if (value[i] !== null && typeof value[i].type === 'string') {
168
- if (!this.visit(value[i], node, key, i)) {
169
- // removed
170
- i--;
171
- }
172
- }
173
- }
174
- } else if (value !== null && typeof value.type === "string") {
175
- this.visit(value, node, key, null);
176
- }
177
- }
178
-
179
- if (this.leave) {
180
- const _replacement = this.replacement;
181
- const _should_remove = this.should_remove;
182
- this.replacement = null;
183
- this.should_remove = false;
184
-
185
- this.leave.call(this.context, node, parent, prop, index);
186
-
187
- if (this.replacement) {
188
- node = this.replacement;
189
- this.replace(parent, prop, index, node);
190
- }
191
-
192
- if (this.should_remove) {
193
- this.remove(parent, prop, index);
194
- }
195
-
196
- const removed = this.should_remove;
197
-
198
- this.replacement = _replacement;
199
- this.should_remove = _should_remove;
200
-
201
- if (removed) return null;
202
- }
203
- }
204
-
205
- return node;
206
- }
207
- }
208
-
209
- // @ts-check
210
-
211
- /** @typedef { import('estree').BaseNode} BaseNode */
212
- /** @typedef { import('./sync.js').SyncHandler} SyncHandler */
213
- /** @typedef { import('./async.js').AsyncHandler} AsyncHandler */
214
-
215
- /**
216
- *
217
- * @param {BaseNode} ast
218
- * @param {{
219
- * enter?: SyncHandler
220
- * leave?: SyncHandler
221
- * }} walker
222
- * @returns {BaseNode}
223
- */
224
- function walk(ast, { enter, leave }) {
225
- const instance = new SyncWalker(enter, leave);
226
- return instance.visit(ast, null);
227
- }
228
-
229
- const extractors = {
230
- ArrayPattern(names, param) {
231
- for (const element of param.elements) {
232
- if (element)
233
- extractors[element.type](names, element);
234
- }
235
- },
236
- AssignmentPattern(names, param) {
237
- extractors[param.left.type](names, param.left);
238
- },
239
- Identifier(names, param) {
240
- names.push(param.name);
241
- },
242
- MemberExpression() { },
243
- ObjectPattern(names, param) {
244
- for (const prop of param.properties) {
245
- // @ts-ignore Typescript reports that this is not a valid type
246
- if (prop.type === 'RestElement') {
247
- extractors.RestElement(names, prop);
248
- }
249
- else {
250
- extractors[prop.value.type](names, prop.value);
251
- }
252
- }
253
- },
254
- RestElement(names, param) {
255
- extractors[param.argument.type](names, param.argument);
256
- }
257
- };
258
- const extractAssignedNames = function extractAssignedNames(param) {
259
- const names = [];
260
- extractors[param.type](names, param);
261
- return names;
262
- };
263
-
264
- const blockDeclarations = {
265
- const: true,
266
- let: true
267
- };
268
- class Scope {
269
- constructor(options = {}) {
270
- this.parent = options.parent;
271
- this.isBlockScope = !!options.block;
272
- this.declarations = Object.create(null);
273
- if (options.params) {
274
- options.params.forEach((param) => {
275
- extractAssignedNames(param).forEach((name) => {
276
- this.declarations[name] = true;
277
- });
278
- });
279
- }
280
- }
281
- addDeclaration(node, isBlockDeclaration, isVar) {
282
- if (!isBlockDeclaration && this.isBlockScope) {
283
- // it's a `var` or function node, and this
284
- // is a block scope, so we need to go up
285
- this.parent.addDeclaration(node, isBlockDeclaration, isVar);
286
- }
287
- else if (node.id) {
288
- extractAssignedNames(node.id).forEach((name) => {
289
- this.declarations[name] = true;
290
- });
291
- }
292
- }
293
- contains(name) {
294
- return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
295
- }
296
- }
297
- const attachScopes = function attachScopes(ast, propertyName = 'scope') {
298
- let scope = new Scope();
299
- walk(ast, {
300
- enter(n, parent) {
301
- const node = n;
302
- // function foo () {...}
303
- // class Foo {...}
304
- if (/(?:Function|Class)Declaration/.test(node.type)) {
305
- scope.addDeclaration(node, false, false);
306
- }
307
- // var foo = 1
308
- if (node.type === 'VariableDeclaration') {
309
- const { kind } = node;
310
- const isBlockDeclaration = blockDeclarations[kind];
311
- node.declarations.forEach((declaration) => {
312
- scope.addDeclaration(declaration, isBlockDeclaration, true);
313
- });
314
- }
315
- let newScope;
316
- // create new function scope
317
- if (node.type.includes('Function')) {
318
- const func = node;
319
- newScope = new Scope({
320
- parent: scope,
321
- block: false,
322
- params: func.params
323
- });
324
- // named function expressions - the name is considered
325
- // part of the function's scope
326
- if (func.type === 'FunctionExpression' && func.id) {
327
- newScope.addDeclaration(func, false, false);
328
- }
329
- }
330
- // create new for scope
331
- if (/For(?:In|Of)?Statement/.test(node.type)) {
332
- newScope = new Scope({
333
- parent: scope,
334
- block: true
335
- });
336
- }
337
- // create new block scope
338
- if (node.type === 'BlockStatement' && !parent.type.includes('Function')) {
339
- newScope = new Scope({
340
- parent: scope,
341
- block: true
342
- });
343
- }
344
- // catch clause has its own block scope
345
- if (node.type === 'CatchClause') {
346
- newScope = new Scope({
347
- parent: scope,
348
- params: node.param ? [node.param] : [],
349
- block: true
350
- });
351
- }
352
- if (newScope) {
353
- Object.defineProperty(node, propertyName, {
354
- value: newScope,
355
- configurable: true
356
- });
357
- scope = newScope;
358
- }
359
- },
360
- leave(n) {
361
- const node = n;
362
- if (node[propertyName])
363
- scope = scope.parent;
364
- }
365
- });
366
- return scope;
367
- };
368
-
369
- // Helper since Typescript can't detect readonly arrays with Array.isArray
370
- function isArray$1(arg) {
371
- return Array.isArray(arg);
372
- }
373
- function ensureArray(thing) {
374
- if (isArray$1(thing))
375
- return thing;
376
- if (thing == null)
377
- return [];
378
- return [thing];
379
- }
380
-
381
- const normalizePathRegExp = new RegExp(`\\${win32.sep}`, 'g');
382
- const normalizePath$2 = function normalizePath(filename) {
383
- return filename.replace(normalizePathRegExp, posix.sep);
384
- };
385
-
386
- function getMatcherString$2(id, resolutionBase) {
387
- if (resolutionBase === false || isAbsolute(id) || id.startsWith('**')) {
388
- return normalizePath$2(id);
389
- }
390
- // resolve('') is valid and will default to process.cwd()
391
- const basePath = normalizePath$2(resolve$1(resolutionBase || ''))
392
- // escape all possible (posix + win) path characters that might interfere with regex
393
- .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
394
- // Note that we use posix.join because:
395
- // 1. the basePath has been normalized to use /
396
- // 2. the incoming glob (id) matcher, also uses /
397
- // otherwise Node will force backslash (\) on windows
398
- return posix.join(basePath, normalizePath$2(id));
399
- }
400
- const createFilter$2 = function createFilter(include, exclude, options) {
401
- const resolutionBase = options && options.resolve;
402
- const getMatcher = (id) => id instanceof RegExp
403
- ? id
404
- : {
405
- test: (what) => {
406
- // this refactor is a tad overly verbose but makes for easy debugging
407
- const pattern = getMatcherString$2(id, resolutionBase);
408
- const fn = pm(pattern, { dot: true });
409
- const result = fn(what);
410
- return result;
411
- }
412
- };
413
- const includeMatchers = ensureArray(include).map(getMatcher);
414
- const excludeMatchers = ensureArray(exclude).map(getMatcher);
415
- if (!includeMatchers.length && !excludeMatchers.length)
416
- return (id) => typeof id === 'string' && !id.includes('\0');
417
- return function result(id) {
418
- if (typeof id !== 'string')
419
- return false;
420
- if (id.includes('\0'))
421
- return false;
422
- const pathId = normalizePath$2(id);
423
- for (let i = 0; i < excludeMatchers.length; ++i) {
424
- const matcher = excludeMatchers[i];
425
- if (matcher instanceof RegExp) {
426
- matcher.lastIndex = 0;
427
- }
428
- if (matcher.test(pathId))
429
- return false;
430
- }
431
- for (let i = 0; i < includeMatchers.length; ++i) {
432
- const matcher = includeMatchers[i];
433
- if (matcher instanceof RegExp) {
434
- matcher.lastIndex = 0;
435
- }
436
- if (matcher.test(pathId))
437
- return true;
438
- }
439
- return !includeMatchers.length;
440
- };
441
- };
442
-
443
- const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
444
- const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
445
- const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
446
- forbiddenIdentifiers.add('');
447
- const makeLegalIdentifier = function makeLegalIdentifier(str) {
448
- let identifier = str
449
- .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
450
- .replace(/[^$_a-zA-Z0-9]/g, '_');
451
- if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) {
452
- identifier = `_${identifier}`;
453
- }
454
- return identifier || '_';
455
- };
456
-
457
- function stringify(obj) {
458
- return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
459
- }
460
- function serializeArray(arr, indent, baseIndent) {
461
- let output = '[';
462
- const separator = indent ? `\n${baseIndent}${indent}` : '';
463
- for (let i = 0; i < arr.length; i++) {
464
- const key = arr[i];
465
- output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`;
466
- }
467
- return `${output}${indent ? `\n${baseIndent}` : ''}]`;
468
- }
469
- function serializeObject(obj, indent, baseIndent) {
470
- let output = '{';
471
- const separator = indent ? `\n${baseIndent}${indent}` : '';
472
- const entries = Object.entries(obj);
473
- for (let i = 0; i < entries.length; i++) {
474
- const [key, value] = entries[i];
475
- const stringKey = makeLegalIdentifier(key) === key ? key : stringify(key);
476
- output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`;
477
- }
478
- return `${output}${indent ? `\n${baseIndent}` : ''}}`;
479
- }
480
- function serialize(obj, indent, baseIndent) {
481
- if (typeof obj === 'object' && obj !== null) {
482
- if (Array.isArray(obj))
483
- return serializeArray(obj, indent, baseIndent);
484
- if (obj instanceof Date)
485
- return `new Date(${obj.getTime()})`;
486
- if (obj instanceof RegExp)
487
- return obj.toString();
488
- return serializeObject(obj, indent, baseIndent);
489
- }
490
- if (typeof obj === 'number') {
491
- if (obj === Infinity)
492
- return 'Infinity';
493
- if (obj === -Infinity)
494
- return '-Infinity';
495
- if (obj === 0)
496
- return 1 / obj === Infinity ? '0' : '-0';
497
- if (obj !== obj)
498
- return 'NaN'; // eslint-disable-line no-self-compare
499
- }
500
- if (typeof obj === 'symbol') {
501
- const key = Symbol.keyFor(obj);
502
- // eslint-disable-next-line no-undefined
503
- if (key !== undefined)
504
- return `Symbol.for(${stringify(key)})`;
505
- }
506
- if (typeof obj === 'bigint')
507
- return `${obj}n`;
508
- return stringify(obj);
509
- }
510
- // isWellFormed exists from Node.js 20
511
- const hasStringIsWellFormed = 'isWellFormed' in String.prototype;
512
- function isWellFormedString(input) {
513
- // @ts-expect-error String::isWellFormed exists from ES2024. tsconfig lib is set to ES6
514
- if (hasStringIsWellFormed)
515
- return input.isWellFormed();
516
- // https://github.com/tc39/proposal-is-usv-string/blob/main/README.md#algorithm
517
- return !/\p{Surrogate}/u.test(input);
518
- }
519
- const dataToEsm = function dataToEsm(data, options = {}) {
520
- var _a, _b;
521
- const t = options.compact ? '' : 'indent' in options ? options.indent : '\t';
522
- const _ = options.compact ? '' : ' ';
523
- const n = options.compact ? '' : '\n';
524
- const declarationType = options.preferConst ? 'const' : 'var';
525
- if (options.namedExports === false ||
526
- typeof data !== 'object' ||
527
- Array.isArray(data) ||
528
- data instanceof Date ||
529
- data instanceof RegExp ||
530
- data === null) {
531
- const code = serialize(data, options.compact ? null : t, '');
532
- const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape
533
- return `export default${magic}${code};`;
534
- }
535
- let maxUnderbarPrefixLength = 0;
536
- for (const key of Object.keys(data)) {
537
- const underbarPrefixLength = (_b = (_a = /^(_+)/.exec(key)) === null || _a === void 0 ? void 0 : _a[0].length) !== null && _b !== void 0 ? _b : 0;
538
- if (underbarPrefixLength > maxUnderbarPrefixLength) {
539
- maxUnderbarPrefixLength = underbarPrefixLength;
540
- }
541
- }
542
- const arbitraryNamePrefix = `${'_'.repeat(maxUnderbarPrefixLength + 1)}arbitrary`;
543
- let namedExportCode = '';
544
- const defaultExportRows = [];
545
- const arbitraryNameExportRows = [];
546
- for (const [key, value] of Object.entries(data)) {
547
- if (key === makeLegalIdentifier(key)) {
548
- if (options.objectShorthand)
549
- defaultExportRows.push(key);
550
- else
551
- defaultExportRows.push(`${key}:${_}${key}`);
552
- namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
553
- }
554
- else {
555
- defaultExportRows.push(`${stringify(key)}:${_}${serialize(value, options.compact ? null : t, '')}`);
556
- if (options.includeArbitraryNames && isWellFormedString(key)) {
557
- const variableName = `${arbitraryNamePrefix}${arbitraryNameExportRows.length}`;
558
- namedExportCode += `${declarationType} ${variableName}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
559
- arbitraryNameExportRows.push(`${variableName} as ${JSON.stringify(key)}`);
560
- }
561
- }
562
- }
563
- const arbitraryExportCode = arbitraryNameExportRows.length > 0
564
- ? `export${_}{${n}${t}${arbitraryNameExportRows.join(`,${n}${t}`)}${n}};${n}`
565
- : '';
566
- const defaultExportCode = `export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
567
- return `${namedExportCode}${arbitraryExportCode}${defaultExportCode}`;
568
- };
569
-
570
- function escape(str) {
571
- return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
572
- }
573
-
574
- function ensureFunction(functionOrValue) {
575
- if (typeof functionOrValue === 'function') { return functionOrValue; }
576
- return function () { return functionOrValue; };
577
- }
578
-
579
- function longest(a, b) {
580
- return b.length - a.length;
581
- }
582
-
583
- function getReplacements(options) {
584
- if (options.values) {
585
- return Object.assign({}, options.values);
586
- }
587
- var values = Object.assign({}, options);
588
- delete values.delimiters;
589
- delete values.include;
590
- delete values.exclude;
591
- delete values.sourcemap;
592
- delete values.sourceMap;
593
- delete values.objectGuards;
594
- delete values.preventAssignment;
595
- return values;
596
- }
597
-
598
- function mapToFunctions(object) {
599
- return Object.keys(object).reduce(function (fns, key) {
600
- var functions = Object.assign({}, fns);
601
- functions[key] = ensureFunction(object[key]);
602
- return functions;
603
- }, {});
604
- }
605
-
606
- var objKeyRegEx =
607
- /^([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)(\.([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*))+$/;
608
- function expandTypeofReplacements(replacements) {
609
- Object.keys(replacements).forEach(function (key) {
610
- var objMatch = key.match(objKeyRegEx);
611
- if (!objMatch) { return; }
612
- var dotIndex = objMatch[1].length;
613
- do {
614
- // eslint-disable-next-line no-param-reassign
615
- replacements[("typeof " + (key.slice(0, dotIndex)))] = '"object"';
616
- dotIndex = key.indexOf('.', dotIndex + 1);
617
- } while (dotIndex !== -1);
618
- });
619
- }
620
-
621
- function replace$1(options) {
622
- if ( options === void 0 ) options = {};
623
-
624
- var filter = createFilter$2(options.include, options.exclude);
625
- var delimiters = options.delimiters; if ( delimiters === void 0 ) delimiters = ['\\b', '\\b(?!\\.)'];
626
- var preventAssignment = options.preventAssignment;
627
- var objectGuards = options.objectGuards;
628
- var replacements = getReplacements(options);
629
- if (objectGuards) { expandTypeofReplacements(replacements); }
630
- var functionValues = mapToFunctions(replacements);
631
- var keys = Object.keys(functionValues).sort(longest).map(escape);
632
- var lookbehind = preventAssignment ? '(?<!\\b(?:const|let|var)\\s*)' : '';
633
- var lookahead = preventAssignment ? '(?!\\s*=[^=])' : '';
634
- var pattern = new RegExp(
635
- ("" + lookbehind + (delimiters[0]) + "(" + (keys.join('|')) + ")" + (delimiters[1]) + lookahead),
636
- 'g'
637
- );
638
-
639
- return {
640
- name: 'replace',
641
-
642
- buildStart: function buildStart() {
643
- if (![true, false].includes(preventAssignment)) {
644
- this.warn({
645
- message:
646
- "@rollup/plugin-replace: 'preventAssignment' currently defaults to false. It is recommended to set this option to `true`, as the next major version will default this option to `true`."
647
- });
648
- }
649
- },
650
-
651
- renderChunk: function renderChunk(code, chunk) {
652
- var id = chunk.fileName;
653
- if (!keys.length) { return null; }
654
- if (!filter(id)) { return null; }
655
- return executeReplacement(code, id);
656
- },
657
-
658
- transform: function transform(code, id) {
659
- if (!keys.length) { return null; }
660
- if (!filter(id)) { return null; }
661
- return executeReplacement(code, id);
662
- }
663
- };
664
-
665
- function executeReplacement(code, id) {
666
- var magicString = new MagicString(code);
667
- if (!codeHasReplacements(code, id, magicString)) {
668
- return null;
669
- }
670
-
671
- var result = { code: magicString.toString() };
672
- if (isSourceMapEnabled()) {
673
- result.map = magicString.generateMap({ hires: true });
674
- }
675
- return result;
676
- }
677
-
678
- function codeHasReplacements(code, id, magicString) {
679
- var result = false;
680
- var match;
681
-
682
- // eslint-disable-next-line no-cond-assign
683
- while ((match = pattern.exec(code))) {
684
- result = true;
685
-
686
- var start = match.index;
687
- var end = start + match[0].length;
688
- var replacement = String(functionValues[match[1]](id));
689
- magicString.overwrite(start, end, replacement);
690
- }
691
- return result;
692
- }
693
-
694
- function isSourceMapEnabled() {
695
- return options.sourceMap !== false && options.sourcemap !== false;
696
- }
697
- }
698
-
699
- const NO_REPLACE_RE = /ROLLUP_NO_REPLACE|\\0raw:/;
700
- function replace(options) {
701
- const _plugin = replace$1(options);
702
- return {
703
- ..._plugin,
704
- // https://github.com/rollup/plugins/blob/master/packages/replace/src/index.js#L94
705
- renderChunk(code, chunk, options2) {
706
- if (!NO_REPLACE_RE.test(code)) {
707
- return _plugin.renderChunk.call(this, code, chunk, options2);
708
- }
709
- }
710
- };
711
- }
712
-
713
- function baseBuildConfig(nitro) {
714
- const buildServerDir = join(nitro.options.buildDir, "dist/server");
715
- const presetsDir = resolve$2(runtimeDir, "../presets");
716
- const extensions = [".ts", ".mjs", ".js", ".json", ".node", ".tsx", ".jsx"];
717
- const isNodeless = nitro.options.node === false;
718
- let NODE_ENV = nitro.options.dev ? "development" : "production";
719
- if (nitro.options.preset === "nitro-prerender") {
720
- NODE_ENV = "prerender";
721
- }
722
- const buildEnvVars = {
723
- NODE_ENV,
724
- prerender: nitro.options.preset === "nitro-prerender",
725
- server: true,
726
- client: false,
727
- dev: String(nitro.options.dev),
728
- DEBUG: nitro.options.dev
729
- };
730
- const staticFlags = {
731
- dev: nitro.options.dev,
732
- preset: nitro.options.preset,
733
- prerender: nitro.options.preset === "nitro-prerender",
734
- server: true,
735
- client: false,
736
- nitro: true,
737
- baseURL: nitro.options.baseURL,
738
- // @ts-expect-error
739
- "versions.nitro": "",
740
- "versions?.nitro": "",
741
- // Internal
742
- _asyncContext: nitro.options.experimental.asyncContext,
743
- _websocket: nitro.options.experimental.websocket,
744
- _tasks: nitro.options.experimental.tasks
745
- };
746
- const replaceDelimiters = [
747
- String.raw`\b`,
748
- String.raw`(?![\w.$])`
749
- ];
750
- const replacements = {
751
- "typeof window": '"undefined"',
752
- _import_meta_url_: "import.meta.url",
753
- "globalThis.process.": "process.",
754
- "process.env.RUNTIME_CONFIG": () => JSON.stringify(nitro.options.runtimeConfig, null, 2),
755
- ...Object.fromEntries(
756
- Object.entries(buildEnvVars).map(([key, val]) => [
757
- `process.env.${key}`,
758
- JSON.stringify(val)
759
- ])
760
- ),
761
- ...Object.fromEntries(
762
- Object.entries(buildEnvVars).map(([key, val]) => [
763
- `import.meta.env.${key}`,
764
- JSON.stringify(val)
765
- ])
766
- ),
767
- ...Object.fromEntries(
768
- Object.entries(staticFlags).map(([key, val]) => [
769
- `process.${key}`,
770
- JSON.stringify(val)
771
- ])
772
- ),
773
- ...Object.fromEntries(
774
- Object.entries(staticFlags).map(([key, val]) => [
775
- `import.meta.${key}`,
776
- JSON.stringify(val)
777
- ])
778
- ),
779
- ...nitro.options.replace
780
- };
781
- const { env } = defineEnv({
782
- nodeCompat: isNodeless,
783
- npmShims: true,
784
- resolve: true,
785
- presets: nitro.options.unenv,
786
- overrides: {
787
- alias: nitro.options.alias
788
- }
789
- });
790
- const aliases = resolveAliases({
791
- "#internal/nitro": runtimeDir,
792
- "nitro/runtime": runtimeDir,
793
- "nitropack/runtime": runtimeDir,
794
- // Backwards compatibility
795
- ...env.alias
796
- });
797
- return {
798
- buildServerDir,
799
- presetsDir,
800
- extensions,
801
- isNodeless,
802
- buildEnvVars,
803
- staticFlags,
804
- replaceDelimiters,
805
- replacements,
806
- env,
807
- aliases
808
- };
809
- }
810
- function resolveAliases(_aliases) {
811
- const aliases = Object.fromEntries(
812
- Object.entries(_aliases).sort(
813
- ([a], [b]) => b.split("/").length - a.split("/").length || b.length - a.length
814
- )
815
- );
816
- for (const key in aliases) {
817
- for (const alias in aliases) {
818
- if (!["~", "@", "#"].includes(alias[0])) {
819
- continue;
820
- }
821
- if (alias === "@" && !aliases[key].startsWith("@/")) {
822
- continue;
823
- }
824
- if (aliases[key].startsWith(alias)) {
825
- aliases[key] = aliases[alias] + aliases[key].slice(alias.length);
826
- }
827
- }
828
- }
829
- return aliases;
830
- }
831
-
832
- //#region src/utils/general.ts
833
- function toArray$2(array) {
834
- array = array || [];
835
- if (Array.isArray(array)) return array;
836
- return [array];
837
- }
838
-
839
- //#endregion
840
- //#region src/utils/filter.ts
841
- const BACKSLASH_REGEX = /\\/g;
842
- function normalize$1(path$1) {
843
- return path$1.replace(BACKSLASH_REGEX, "/");
844
- }
845
- const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Z]:)?[/\\|])/i;
846
- function isAbsolute$1(path$1) {
847
- return ABSOLUTE_PATH_REGEX.test(path$1);
848
- }
849
- function getMatcherString$1(glob, cwd) {
850
- if (glob.startsWith("**") || isAbsolute$1(glob)) return normalize$1(glob);
851
- const resolved = resolve$3(cwd, glob);
852
- return normalize$1(resolved);
853
- }
854
- function patternToIdFilter(pattern) {
855
- if (pattern instanceof RegExp) return (id) => {
856
- const normalizedId = normalize$1(id);
857
- const result = pattern.test(normalizedId);
858
- pattern.lastIndex = 0;
859
- return result;
860
- };
861
- const cwd = process.cwd();
862
- const glob = getMatcherString$1(pattern, cwd);
863
- const matcher = pm(glob, { dot: true });
864
- return (id) => {
865
- const normalizedId = normalize$1(id);
866
- return matcher(normalizedId);
867
- };
868
- }
869
- function patternToCodeFilter(pattern) {
870
- if (pattern instanceof RegExp) return (code) => {
871
- const result = pattern.test(code);
872
- pattern.lastIndex = 0;
873
- return result;
874
- };
875
- return (code) => code.includes(pattern);
876
- }
877
- function createFilter$1(exclude, include) {
878
- if (!exclude && !include) return;
879
- return (input) => {
880
- if (exclude?.some((filter) => filter(input))) return false;
881
- if (include?.some((filter) => filter(input))) return true;
882
- return !(include && include.length > 0);
883
- };
884
- }
885
- function normalizeFilter(filter) {
886
- if (typeof filter === "string" || filter instanceof RegExp) return { include: [filter] };
887
- if (Array.isArray(filter)) return { include: filter };
888
- return {
889
- exclude: filter.exclude ? toArray$2(filter.exclude) : void 0,
890
- include: filter.include ? toArray$2(filter.include) : void 0
891
- };
892
- }
893
- function createIdFilter(filter) {
894
- if (!filter) return;
895
- const { exclude, include } = normalizeFilter(filter);
896
- const excludeFilter = exclude?.map(patternToIdFilter);
897
- const includeFilter = include?.map(patternToIdFilter);
898
- return createFilter$1(excludeFilter, includeFilter);
899
- }
900
- function createCodeFilter(filter) {
901
- if (!filter) return;
902
- const { exclude, include } = normalizeFilter(filter);
903
- const excludeFilter = exclude?.map(patternToCodeFilter);
904
- const includeFilter = include?.map(patternToCodeFilter);
905
- return createFilter$1(excludeFilter, includeFilter);
906
- }
907
- function createFilterForId(filter) {
908
- const filterFunction = createIdFilter(filter);
909
- return filterFunction ? (id) => !!filterFunction(id) : void 0;
910
- }
911
- function createFilterForTransform(idFilter, codeFilter) {
912
- if (!idFilter && !codeFilter) return;
913
- const idFilterFunction = createIdFilter(idFilter);
914
- const codeFilterFunction = createCodeFilter(codeFilter);
915
- return (id, code) => {
916
- let fallback = true;
917
- if (idFilterFunction) fallback &&= idFilterFunction(id);
918
- if (!fallback) return false;
919
- if (codeFilterFunction) fallback &&= codeFilterFunction(code);
920
- return fallback;
921
- };
922
- }
923
- function normalizeObjectHook(name, hook) {
924
- let handler;
925
- let filter;
926
- if (typeof hook === "function") handler = hook;
927
- else {
928
- handler = hook.handler;
929
- const hookFilter = hook.filter;
930
- if (name === "resolveId" || name === "load") filter = createFilterForId(hookFilter?.id);
931
- else filter = createFilterForTransform(hookFilter?.id, hookFilter?.code);
932
- }
933
- return {
934
- handler,
935
- filter: filter || (() => true)
936
- };
937
- }
938
-
939
- //#endregion
940
- //#region src/utils/context.ts
941
- function parse$1(code, opts = {}) {
942
- return Parser.parse(code, {
943
- sourceType: "module",
944
- ecmaVersion: "latest",
945
- locations: true,
946
- ...opts
947
- });
948
- }
949
-
950
- //#region src/utils/webpack-like.ts
951
- function transformUse(data, plugin, transformLoader) {
952
- if (data.resource == null) return [];
953
- const id = normalizeAbsolutePath(data.resource + (data.resourceQuery || ""));
954
- if (plugin.transformInclude && !plugin.transformInclude(id)) return [];
955
- const { filter } = normalizeObjectHook("load", plugin.transform);
956
- if (!filter(id)) return [];
957
- return [{
958
- loader: transformLoader,
959
- options: { plugin },
960
- ident: plugin.name
961
- }];
962
- }
963
- /**
964
- * Normalizes a given path when it's absolute. Normalizing means returning a new path by converting
965
- * the input path to the native os format. This is useful in cases where we want to normalize
966
- * the `id` argument of a hook. Any absolute ids should be in the default format
967
- * of the operating system. Any relative imports or node_module imports should remain
968
- * untouched.
969
- *
970
- * @param path - Path to normalize.
971
- * @returns a new normalized path.
972
- */
973
- function normalizeAbsolutePath(path$1) {
974
- if (isAbsolute$2(path$1)) return normalize(path$1);
975
- else return path$1;
976
- }
977
-
978
- //#region src/rspack/context.ts
979
- function createBuildContext$1(compiler, compilation, loaderContext) {
980
- return {
981
- getNativeBuildContext() {
982
- return {
983
- framework: "rspack",
984
- compiler,
985
- compilation,
986
- loaderContext
987
- };
988
- },
989
- addWatchFile(file) {
990
- const cwd = process.cwd();
991
- compilation.fileDependencies.add(resolve$3(cwd, file));
992
- },
993
- getWatchFiles() {
994
- return Array.from(compilation.fileDependencies);
995
- },
996
- parse: parse$1,
997
- emitFile(emittedFile) {
998
- const outFileName = emittedFile.fileName || emittedFile.name;
999
- if (emittedFile.source && outFileName) {
1000
- const { sources } = compilation.compiler.webpack;
1001
- compilation.emitAsset(outFileName, new sources.RawSource(typeof emittedFile.source === "string" ? emittedFile.source : Buffer$1.from(emittedFile.source)));
1002
- }
1003
- }
1004
- };
1005
- }
1006
- function normalizeMessage$1(error) {
1007
- const err = new Error(typeof error === "string" ? error : error.message);
1008
- if (typeof error === "object") {
1009
- err.stack = error.stack;
1010
- err.cause = error.meta;
1011
- }
1012
- return err;
1013
- }
1014
-
1015
- //#region src/rspack/utils.ts
1016
- function encodeVirtualModuleId(id, plugin) {
1017
- return resolve$3(plugin.__virtualModulePrefix, encodeURIComponent(id));
1018
- }
1019
- function decodeVirtualModuleId(encoded, _plugin) {
1020
- return decodeURIComponent(basename(encoded));
1021
- }
1022
- function isVirtualModuleId(encoded, plugin) {
1023
- return dirname(encoded) === plugin.__virtualModulePrefix;
1024
- }
1025
- var FakeVirtualModulesPlugin = class FakeVirtualModulesPlugin {
1026
- name = "FakeVirtualModulesPlugin";
1027
- static counters = /* @__PURE__ */ new Map();
1028
- static initCleanup = false;
1029
- constructor(plugin) {
1030
- this.plugin = plugin;
1031
- if (!FakeVirtualModulesPlugin.initCleanup) {
1032
- FakeVirtualModulesPlugin.initCleanup = true;
1033
- process.once("exit", () => {
1034
- FakeVirtualModulesPlugin.counters.forEach((_, dir) => {
1035
- fs.rmSync(dir, {
1036
- recursive: true,
1037
- force: true
1038
- });
1039
- });
1040
- });
1041
- }
1042
- }
1043
- apply(compiler) {
1044
- const dir = this.plugin.__virtualModulePrefix;
1045
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
1046
- const counter = FakeVirtualModulesPlugin.counters.get(dir) ?? 0;
1047
- FakeVirtualModulesPlugin.counters.set(dir, counter + 1);
1048
- compiler.hooks.shutdown.tap(this.name, () => {
1049
- const counter$1 = (FakeVirtualModulesPlugin.counters.get(dir) ?? 1) - 1;
1050
- if (counter$1 === 0) {
1051
- FakeVirtualModulesPlugin.counters.delete(dir);
1052
- fs.rmSync(dir, {
1053
- recursive: true,
1054
- force: true
1055
- });
1056
- } else FakeVirtualModulesPlugin.counters.set(dir, counter$1);
1057
- });
1058
- }
1059
- async writeModule(file) {
1060
- return fs.promises.writeFile(file, "");
1061
- }
1062
- };
1063
-
1064
- //#region src/webpack/context.ts
1065
- function contextOptionsFromCompilation(compilation) {
1066
- return {
1067
- addWatchFile(file) {
1068
- (compilation.fileDependencies ?? compilation.compilationDependencies).add(file);
1069
- },
1070
- getWatchFiles() {
1071
- return Array.from(compilation.fileDependencies ?? compilation.compilationDependencies);
1072
- }
1073
- };
1074
- }
1075
- const require = createRequire(import.meta.url);
1076
- function getSource(fileSource) {
1077
- const webpack = require("webpack");
1078
- return new webpack.sources.RawSource(typeof fileSource === "string" ? fileSource : Buffer$1.from(fileSource.buffer));
1079
- }
1080
- function createBuildContext(options, compiler, compilation, loaderContext) {
1081
- return {
1082
- parse: parse$1,
1083
- addWatchFile(id) {
1084
- options.addWatchFile(resolve$3(process$1.cwd(), id));
1085
- },
1086
- emitFile(emittedFile) {
1087
- const outFileName = emittedFile.fileName || emittedFile.name;
1088
- if (emittedFile.source && outFileName) {
1089
- if (!compilation) throw new Error("unplugin/webpack: emitFile outside supported hooks (buildStart, buildEnd, load, transform, watchChange)");
1090
- compilation.emitAsset(outFileName, getSource(emittedFile.source));
1091
- }
1092
- },
1093
- getWatchFiles() {
1094
- return options.getWatchFiles();
1095
- },
1096
- getNativeBuildContext() {
1097
- return {
1098
- framework: "webpack",
1099
- compiler,
1100
- compilation,
1101
- loaderContext
1102
- };
1103
- }
1104
- };
1105
- }
1106
- function normalizeMessage(error) {
1107
- const err = new Error(typeof error === "string" ? error : error.message);
1108
- if (typeof error === "object") {
1109
- err.stack = error.stack;
1110
- err.cause = error.meta;
1111
- }
1112
- return err;
1113
- }
1114
-
1115
- // Matches the scheme of a URL, eg "http://"
1116
- const schemeRegex = /^[\w+.-]+:\/\//;
1117
- /**
1118
- * Matches the parts of a URL:
1119
- * 1. Scheme, including ":", guaranteed.
1120
- * 2. User/password, including "@", optional.
1121
- * 3. Host, guaranteed.
1122
- * 4. Port, including ":", optional.
1123
- * 5. Path, including "/", optional.
1124
- * 6. Query, including "?", optional.
1125
- * 7. Hash, including "#", optional.
1126
- */
1127
- const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
1128
- /**
1129
- * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
1130
- * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
1131
- *
1132
- * 1. Host, optional.
1133
- * 2. Path, which may include "/", guaranteed.
1134
- * 3. Query, including "?", optional.
1135
- * 4. Hash, including "#", optional.
1136
- */
1137
- const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
1138
- function isAbsoluteUrl(input) {
1139
- return schemeRegex.test(input);
1140
- }
1141
- function isSchemeRelativeUrl(input) {
1142
- return input.startsWith('//');
1143
- }
1144
- function isAbsolutePath(input) {
1145
- return input.startsWith('/');
1146
- }
1147
- function isFileUrl(input) {
1148
- return input.startsWith('file:');
1149
- }
1150
- function isRelative(input) {
1151
- return /^[.?#]/.test(input);
1152
- }
1153
- function parseAbsoluteUrl(input) {
1154
- const match = urlRegex.exec(input);
1155
- return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || '');
1156
- }
1157
- function parseFileUrl(input) {
1158
- const match = fileRegex.exec(input);
1159
- const path = match[2];
1160
- return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || '');
1161
- }
1162
- function makeUrl(scheme, user, host, port, path, query, hash) {
1163
- return {
1164
- scheme,
1165
- user,
1166
- host,
1167
- port,
1168
- path,
1169
- query,
1170
- hash,
1171
- type: 7 /* Absolute */,
1172
- };
1173
- }
1174
- function parseUrl(input) {
1175
- if (isSchemeRelativeUrl(input)) {
1176
- const url = parseAbsoluteUrl('http:' + input);
1177
- url.scheme = '';
1178
- url.type = 6 /* SchemeRelative */;
1179
- return url;
1180
- }
1181
- if (isAbsolutePath(input)) {
1182
- const url = parseAbsoluteUrl('http://foo.com' + input);
1183
- url.scheme = '';
1184
- url.host = '';
1185
- url.type = 5 /* AbsolutePath */;
1186
- return url;
1187
- }
1188
- if (isFileUrl(input))
1189
- return parseFileUrl(input);
1190
- if (isAbsoluteUrl(input))
1191
- return parseAbsoluteUrl(input);
1192
- const url = parseAbsoluteUrl('http://foo.com/' + input);
1193
- url.scheme = '';
1194
- url.host = '';
1195
- url.type = input
1196
- ? input.startsWith('?')
1197
- ? 3 /* Query */
1198
- : input.startsWith('#')
1199
- ? 2 /* Hash */
1200
- : 4 /* RelativePath */
1201
- : 1 /* Empty */;
1202
- return url;
1203
- }
1204
- function stripPathFilename(path) {
1205
- // If a path ends with a parent directory "..", then it's a relative path with excess parent
1206
- // paths. It's not a file, so we can't strip it.
1207
- if (path.endsWith('/..'))
1208
- return path;
1209
- const index = path.lastIndexOf('/');
1210
- return path.slice(0, index + 1);
1211
- }
1212
- function mergePaths(url, base) {
1213
- normalizePath$1(base, base.type);
1214
- // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
1215
- // path).
1216
- if (url.path === '/') {
1217
- url.path = base.path;
1218
- }
1219
- else {
1220
- // Resolution happens relative to the base path's directory, not the file.
1221
- url.path = stripPathFilename(base.path) + url.path;
1222
- }
1223
- }
1224
- /**
1225
- * The path can have empty directories "//", unneeded parents "foo/..", or current directory
1226
- * "foo/.". We need to normalize to a standard representation.
1227
- */
1228
- function normalizePath$1(url, type) {
1229
- const rel = type <= 4 /* RelativePath */;
1230
- const pieces = url.path.split('/');
1231
- // We need to preserve the first piece always, so that we output a leading slash. The item at
1232
- // pieces[0] is an empty string.
1233
- let pointer = 1;
1234
- // Positive is the number of real directories we've output, used for popping a parent directory.
1235
- // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
1236
- let positive = 0;
1237
- // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
1238
- // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
1239
- // real directory, we won't need to append, unless the other conditions happen again.
1240
- let addTrailingSlash = false;
1241
- for (let i = 1; i < pieces.length; i++) {
1242
- const piece = pieces[i];
1243
- // An empty directory, could be a trailing slash, or just a double "//" in the path.
1244
- if (!piece) {
1245
- addTrailingSlash = true;
1246
- continue;
1247
- }
1248
- // If we encounter a real directory, then we don't need to append anymore.
1249
- addTrailingSlash = false;
1250
- // A current directory, which we can always drop.
1251
- if (piece === '.')
1252
- continue;
1253
- // A parent directory, we need to see if there are any real directories we can pop. Else, we
1254
- // have an excess of parents, and we'll need to keep the "..".
1255
- if (piece === '..') {
1256
- if (positive) {
1257
- addTrailingSlash = true;
1258
- positive--;
1259
- pointer--;
1260
- }
1261
- else if (rel) {
1262
- // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
1263
- // URL, protocol relative URL, or an absolute path, we don't need to keep excess.
1264
- pieces[pointer++] = piece;
1265
- }
1266
- continue;
1267
- }
1268
- // We've encountered a real directory. Move it to the next insertion pointer, which accounts for
1269
- // any popped or dropped directories.
1270
- pieces[pointer++] = piece;
1271
- positive++;
1272
- }
1273
- let path = '';
1274
- for (let i = 1; i < pointer; i++) {
1275
- path += '/' + pieces[i];
1276
- }
1277
- if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
1278
- path += '/';
1279
- }
1280
- url.path = path;
1281
- }
1282
- /**
1283
- * Attempts to resolve `input` URL/path relative to `base`.
1284
- */
1285
- function resolve(input, base) {
1286
- if (!input && !base)
1287
- return '';
1288
- const url = parseUrl(input);
1289
- let inputType = url.type;
1290
- if (base && inputType !== 7 /* Absolute */) {
1291
- const baseUrl = parseUrl(base);
1292
- const baseType = baseUrl.type;
1293
- switch (inputType) {
1294
- case 1 /* Empty */:
1295
- url.hash = baseUrl.hash;
1296
- // fall through
1297
- case 2 /* Hash */:
1298
- url.query = baseUrl.query;
1299
- // fall through
1300
- case 3 /* Query */:
1301
- case 4 /* RelativePath */:
1302
- mergePaths(url, baseUrl);
1303
- // fall through
1304
- case 5 /* AbsolutePath */:
1305
- // The host, user, and port are joined, you can't copy one without the others.
1306
- url.user = baseUrl.user;
1307
- url.host = baseUrl.host;
1308
- url.port = baseUrl.port;
1309
- // fall through
1310
- case 6 /* SchemeRelative */:
1311
- // The input doesn't have a schema at least, so we need to copy at least that over.
1312
- url.scheme = baseUrl.scheme;
1313
- }
1314
- if (baseType > inputType)
1315
- inputType = baseType;
1316
- }
1317
- normalizePath$1(url, inputType);
1318
- const queryHash = url.query + url.hash;
1319
- switch (inputType) {
1320
- // This is impossible, because of the empty checks at the start of the function.
1321
- // case UrlType.Empty:
1322
- case 2 /* Hash */:
1323
- case 3 /* Query */:
1324
- return queryHash;
1325
- case 4 /* RelativePath */: {
1326
- // The first char is always a "/", and we need it to be relative.
1327
- const path = url.path.slice(1);
1328
- if (!path)
1329
- return queryHash || '.';
1330
- if (isRelative(base || input) && !isRelative(path)) {
1331
- // If base started with a leading ".", or there is no base and input started with a ".",
1332
- // then we need to ensure that the relative path starts with a ".". We don't know if
1333
- // relative starts with a "..", though, so check before prepending.
1334
- return './' + path + queryHash;
1335
- }
1336
- return path + queryHash;
1337
- }
1338
- case 5 /* AbsolutePath */:
1339
- return url.path + queryHash;
1340
- default:
1341
- return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;
1342
- }
1343
- }
1344
-
1345
- // src/trace-mapping.ts
1346
-
1347
- // src/strip-filename.ts
1348
- function stripFilename(path) {
1349
- if (!path) return "";
1350
- const index = path.lastIndexOf("/");
1351
- return path.slice(0, index + 1);
1352
- }
1353
-
1354
- // src/resolve.ts
1355
- function resolver(mapUrl, sourceRoot) {
1356
- const from = stripFilename(mapUrl);
1357
- const prefix = sourceRoot ? sourceRoot + "/" : "";
1358
- return (source) => resolve(prefix + (source || ""), from);
1359
- }
1360
-
1361
- // src/sourcemap-segment.ts
1362
- var COLUMN$1 = 0;
1363
-
1364
- // src/sort.ts
1365
- function maybeSort(mappings, owned) {
1366
- const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
1367
- if (unsortedIndex === mappings.length) return mappings;
1368
- if (!owned) mappings = mappings.slice();
1369
- for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
1370
- mappings[i] = sortSegments(mappings[i], owned);
1371
- }
1372
- return mappings;
1373
- }
1374
- function nextUnsortedSegmentLine(mappings, start) {
1375
- for (let i = start; i < mappings.length; i++) {
1376
- if (!isSorted(mappings[i])) return i;
1377
- }
1378
- return mappings.length;
1379
- }
1380
- function isSorted(line) {
1381
- for (let j = 1; j < line.length; j++) {
1382
- if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) {
1383
- return false;
1384
- }
1385
- }
1386
- return true;
1387
- }
1388
- function sortSegments(line, owned) {
1389
- if (!owned) line = line.slice();
1390
- return line.sort(sortComparator);
1391
- }
1392
- function sortComparator(a, b) {
1393
- return a[COLUMN$1] - b[COLUMN$1];
1394
- }
1395
-
1396
- // src/binary-search.ts
1397
- var found = false;
1398
- function binarySearch(haystack, needle, low, high) {
1399
- while (low <= high) {
1400
- const mid = low + (high - low >> 1);
1401
- const cmp = haystack[mid][COLUMN$1] - needle;
1402
- if (cmp === 0) {
1403
- found = true;
1404
- return mid;
1405
- }
1406
- if (cmp < 0) {
1407
- low = mid + 1;
1408
- } else {
1409
- high = mid - 1;
1410
- }
1411
- }
1412
- found = false;
1413
- return low - 1;
1414
- }
1415
- function lowerBound(haystack, needle, index) {
1416
- for (let i = index - 1; i >= 0; index = i--) {
1417
- if (haystack[i][COLUMN$1] !== needle) break;
1418
- }
1419
- return index;
1420
- }
1421
- function memoizedState() {
1422
- return {
1423
- lastKey: -1,
1424
- lastNeedle: -1,
1425
- lastIndex: -1
1426
- };
1427
- }
1428
- function memoizedBinarySearch(haystack, needle, state, key) {
1429
- const { lastKey, lastNeedle, lastIndex } = state;
1430
- let low = 0;
1431
- let high = haystack.length - 1;
1432
- if (key === lastKey) {
1433
- if (needle === lastNeedle) {
1434
- found = lastIndex !== -1 && haystack[lastIndex][COLUMN$1] === needle;
1435
- return lastIndex;
1436
- }
1437
- if (needle >= lastNeedle) {
1438
- low = lastIndex === -1 ? 0 : lastIndex;
1439
- } else {
1440
- high = lastIndex;
1441
- }
1442
- }
1443
- state.lastKey = key;
1444
- state.lastNeedle = needle;
1445
- return state.lastIndex = binarySearch(haystack, needle, low, high);
1446
- }
1447
-
1448
- // src/types.ts
1449
- function parse(map) {
1450
- return typeof map === "string" ? JSON.parse(map) : map;
1451
- }
1452
- var TraceMap = class {
1453
- constructor(map, mapUrl) {
1454
- const isString = typeof map === "string";
1455
- if (!isString && map._decodedMemo) return map;
1456
- const parsed = parse(map);
1457
- const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
1458
- this.version = version;
1459
- this.file = file;
1460
- this.names = names || [];
1461
- this.sourceRoot = sourceRoot;
1462
- this.sources = sources;
1463
- this.sourcesContent = sourcesContent;
1464
- this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0;
1465
- const resolve = resolver(mapUrl, sourceRoot);
1466
- this.resolvedSources = sources.map(resolve);
1467
- const { mappings } = parsed;
1468
- if (typeof mappings === "string") {
1469
- this._encoded = mappings;
1470
- this._decoded = void 0;
1471
- } else if (Array.isArray(mappings)) {
1472
- this._encoded = void 0;
1473
- this._decoded = maybeSort(mappings, isString);
1474
- } else if (parsed.sections) {
1475
- throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);
1476
- } else {
1477
- throw new Error(`invalid source map: ${JSON.stringify(parsed)}`);
1478
- }
1479
- this._decodedMemo = memoizedState();
1480
- this._bySources = void 0;
1481
- this._bySourceMemos = void 0;
1482
- }
1483
- };
1484
- function cast$1(map) {
1485
- return map;
1486
- }
1487
- function decodedMappings(map) {
1488
- var _a;
1489
- return (_a = cast$1(map))._decoded || (_a._decoded = decode(cast$1(map)._encoded));
1490
- }
1491
- function traceSegment(map, line, column) {
1492
- const decoded = decodedMappings(map);
1493
- if (line >= decoded.length) return null;
1494
- const segments = decoded[line];
1495
- const index = traceSegmentInternal(
1496
- segments,
1497
- cast$1(map)._decodedMemo,
1498
- line,
1499
- column);
1500
- return index === -1 ? null : segments[index];
1501
- }
1502
- function traceSegmentInternal(segments, memo, line, column, bias) {
1503
- let index = memoizedBinarySearch(segments, column, memo, line);
1504
- if (found) {
1505
- index = (lowerBound)(segments, column, index);
1506
- }
1507
- if (index === -1 || index === segments.length) return -1;
1508
- return index;
1509
- }
1510
-
1511
- // src/set-array.ts
1512
- var SetArray = class {
1513
- constructor() {
1514
- this._indexes = { __proto__: null };
1515
- this.array = [];
1516
- }
1517
- };
1518
- function cast(set) {
1519
- return set;
1520
- }
1521
- function get(setarr, key) {
1522
- return cast(setarr)._indexes[key];
1523
- }
1524
- function put(setarr, key) {
1525
- const index = get(setarr, key);
1526
- if (index !== void 0) return index;
1527
- const { array, _indexes: indexes } = cast(setarr);
1528
- const length = array.push(key);
1529
- return indexes[key] = length - 1;
1530
- }
1531
- function remove(setarr, key) {
1532
- const index = get(setarr, key);
1533
- if (index === void 0) return;
1534
- const { array, _indexes: indexes } = cast(setarr);
1535
- for (let i = index + 1; i < array.length; i++) {
1536
- const k = array[i];
1537
- array[i - 1] = k;
1538
- indexes[k]--;
1539
- }
1540
- indexes[key] = void 0;
1541
- array.pop();
1542
- }
1543
-
1544
- // src/sourcemap-segment.ts
1545
- var COLUMN = 0;
1546
- var SOURCES_INDEX = 1;
1547
- var SOURCE_LINE = 2;
1548
- var SOURCE_COLUMN = 3;
1549
- var NAMES_INDEX = 4;
1550
-
1551
- // src/gen-mapping.ts
1552
- var NO_NAME = -1;
1553
- var GenMapping = class {
1554
- constructor({ file, sourceRoot } = {}) {
1555
- this._names = new SetArray();
1556
- this._sources = new SetArray();
1557
- this._sourcesContent = [];
1558
- this._mappings = [];
1559
- this.file = file;
1560
- this.sourceRoot = sourceRoot;
1561
- this._ignoreList = new SetArray();
1562
- }
1563
- };
1564
- function cast2(map) {
1565
- return map;
1566
- }
1567
- var maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
1568
- return addSegmentInternal(
1569
- true,
1570
- map,
1571
- genLine,
1572
- genColumn,
1573
- source,
1574
- sourceLine,
1575
- sourceColumn,
1576
- name);
1577
- };
1578
- function setSourceContent(map, source, content) {
1579
- const {
1580
- _sources: sources,
1581
- _sourcesContent: sourcesContent
1582
- // _originalScopes: originalScopes,
1583
- } = cast2(map);
1584
- const index = put(sources, source);
1585
- sourcesContent[index] = content;
1586
- }
1587
- function setIgnore(map, source, ignore = true) {
1588
- const {
1589
- _sources: sources,
1590
- _sourcesContent: sourcesContent,
1591
- _ignoreList: ignoreList
1592
- // _originalScopes: originalScopes,
1593
- } = cast2(map);
1594
- const index = put(sources, source);
1595
- if (index === sourcesContent.length) sourcesContent[index] = null;
1596
- if (ignore) put(ignoreList, index);
1597
- else remove(ignoreList, index);
1598
- }
1599
- function toDecodedMap(map) {
1600
- const {
1601
- _mappings: mappings,
1602
- _sources: sources,
1603
- _sourcesContent: sourcesContent,
1604
- _names: names,
1605
- _ignoreList: ignoreList
1606
- // _originalScopes: originalScopes,
1607
- // _generatedRanges: generatedRanges,
1608
- } = cast2(map);
1609
- removeEmptyFinalLines(mappings);
1610
- return {
1611
- version: 3,
1612
- file: map.file || void 0,
1613
- names: names.array,
1614
- sourceRoot: map.sourceRoot || void 0,
1615
- sources: sources.array,
1616
- sourcesContent,
1617
- mappings,
1618
- // originalScopes,
1619
- // generatedRanges,
1620
- ignoreList: ignoreList.array
1621
- };
1622
- }
1623
- function toEncodedMap(map) {
1624
- const decoded = toDecodedMap(map);
1625
- return Object.assign({}, decoded, {
1626
- // originalScopes: decoded.originalScopes.map((os) => encodeOriginalScopes(os)),
1627
- // generatedRanges: encodeGeneratedRanges(decoded.generatedRanges as GeneratedRange[]),
1628
- mappings: encode(decoded.mappings)
1629
- });
1630
- }
1631
- function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) {
1632
- const {
1633
- _mappings: mappings,
1634
- _sources: sources,
1635
- _sourcesContent: sourcesContent,
1636
- _names: names
1637
- // _originalScopes: originalScopes,
1638
- } = cast2(map);
1639
- const line = getIndex(mappings, genLine);
1640
- const index = getColumnIndex(line, genColumn);
1641
- if (!source) {
1642
- if (skipSourceless(line, index)) return;
1643
- return insert(line, index, [genColumn]);
1644
- }
1645
- const sourcesIndex = put(sources, source);
1646
- const namesIndex = name ? put(names, name) : NO_NAME;
1647
- if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = null;
1648
- if (skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
1649
- return;
1650
- }
1651
- return insert(
1652
- line,
1653
- index,
1654
- name ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] : [genColumn, sourcesIndex, sourceLine, sourceColumn]
1655
- );
1656
- }
1657
- function getIndex(arr, index) {
1658
- for (let i = arr.length; i <= index; i++) {
1659
- arr[i] = [];
1660
- }
1661
- return arr[index];
1662
- }
1663
- function getColumnIndex(line, genColumn) {
1664
- let index = line.length;
1665
- for (let i = index - 1; i >= 0; index = i--) {
1666
- const current = line[i];
1667
- if (genColumn >= current[COLUMN]) break;
1668
- }
1669
- return index;
1670
- }
1671
- function insert(array, index, value) {
1672
- for (let i = array.length; i > index; i--) {
1673
- array[i] = array[i - 1];
1674
- }
1675
- array[index] = value;
1676
- }
1677
- function removeEmptyFinalLines(mappings) {
1678
- const { length } = mappings;
1679
- let len = length;
1680
- for (let i = len - 1; i >= 0; len = i, i--) {
1681
- if (mappings[i].length > 0) break;
1682
- }
1683
- if (len < length) mappings.length = len;
1684
- }
1685
- function skipSourceless(line, index) {
1686
- if (index === 0) return true;
1687
- const prev = line[index - 1];
1688
- return prev.length === 1;
1689
- }
1690
- function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
1691
- if (index === 0) return false;
1692
- const prev = line[index - 1];
1693
- if (prev.length === 1) return false;
1694
- return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME);
1695
- }
1696
-
1697
- // src/build-source-map-tree.ts
1698
- var SOURCELESS_MAPPING = /* @__PURE__ */ SegmentObject("", -1, -1, "", null, false);
1699
- var EMPTY_SOURCES = [];
1700
- function SegmentObject(source, line, column, name, content, ignore) {
1701
- return { source, line, column, name, content, ignore };
1702
- }
1703
- function Source(map, sources, source, content, ignore) {
1704
- return {
1705
- map,
1706
- sources,
1707
- source,
1708
- content,
1709
- ignore
1710
- };
1711
- }
1712
- function MapSource(map, sources) {
1713
- return Source(map, sources, "", null, false);
1714
- }
1715
- function OriginalSource(source, content, ignore) {
1716
- return Source(null, EMPTY_SOURCES, source, content, ignore);
1717
- }
1718
- function traceMappings(tree) {
1719
- const gen = new GenMapping({ file: tree.map.file });
1720
- const { sources: rootSources, map } = tree;
1721
- const rootNames = map.names;
1722
- const rootMappings = decodedMappings(map);
1723
- for (let i = 0; i < rootMappings.length; i++) {
1724
- const segments = rootMappings[i];
1725
- for (let j = 0; j < segments.length; j++) {
1726
- const segment = segments[j];
1727
- const genCol = segment[0];
1728
- let traced = SOURCELESS_MAPPING;
1729
- if (segment.length !== 1) {
1730
- const source2 = rootSources[segment[1]];
1731
- traced = originalPositionFor(
1732
- source2,
1733
- segment[2],
1734
- segment[3],
1735
- segment.length === 5 ? rootNames[segment[4]] : ""
1736
- );
1737
- if (traced == null) continue;
1738
- }
1739
- const { column, line, name, content, source, ignore } = traced;
1740
- maybeAddSegment(gen, i, genCol, source, line, column, name);
1741
- if (source && content != null) setSourceContent(gen, source, content);
1742
- if (ignore) setIgnore(gen, source, true);
1743
- }
1744
- }
1745
- return gen;
1746
- }
1747
- function originalPositionFor(source, line, column, name) {
1748
- if (!source.map) {
1749
- return SegmentObject(source.source, line, column, name, source.content, source.ignore);
1750
- }
1751
- const segment = traceSegment(source.map, line, column);
1752
- if (segment == null) return null;
1753
- if (segment.length === 1) return SOURCELESS_MAPPING;
1754
- return originalPositionFor(
1755
- source.sources[segment[1]],
1756
- segment[2],
1757
- segment[3],
1758
- segment.length === 5 ? source.map.names[segment[4]] : name
1759
- );
1760
- }
1761
-
1762
- // src/build-source-map-tree.ts
1763
- function asArray(value) {
1764
- if (Array.isArray(value)) return value;
1765
- return [value];
1766
- }
1767
- function buildSourceMapTree(input, loader) {
1768
- const maps = asArray(input).map((m) => new TraceMap(m, ""));
1769
- const map = maps.pop();
1770
- for (let i = 0; i < maps.length; i++) {
1771
- if (maps[i].sources.length > 1) {
1772
- throw new Error(
1773
- `Transformation map ${i} must have exactly one source file.
1774
- Did you specify these with the most recent transformation maps first?`
1775
- );
1776
- }
1777
- }
1778
- let tree = build(map, loader, "", 0);
1779
- for (let i = maps.length - 1; i >= 0; i--) {
1780
- tree = MapSource(maps[i], [tree]);
1781
- }
1782
- return tree;
1783
- }
1784
- function build(map, loader, importer, importerDepth) {
1785
- const { resolvedSources, sourcesContent, ignoreList } = map;
1786
- const depth = importerDepth + 1;
1787
- const children = resolvedSources.map((sourceFile, i) => {
1788
- const ctx = {
1789
- importer,
1790
- depth,
1791
- source: sourceFile || "",
1792
- content: void 0,
1793
- ignore: void 0
1794
- };
1795
- const sourceMap = loader(ctx.source, ctx);
1796
- const { source} = ctx;
1797
- if (sourceMap) return build(new TraceMap(sourceMap, source), loader, source, depth);
1798
- const sourceContent = sourcesContent ? sourcesContent[i] : null;
1799
- const ignored = ignoreList ? ignoreList.includes(i) : false;
1800
- return OriginalSource(source, sourceContent, ignored);
1801
- });
1802
- return MapSource(map, children);
1803
- }
1804
- var SourceMap = class {
1805
- constructor(map, options) {
1806
- const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);
1807
- this.version = out.version;
1808
- this.file = out.file;
1809
- this.mappings = out.mappings;
1810
- this.names = out.names;
1811
- this.ignoreList = out.ignoreList;
1812
- this.sourceRoot = out.sourceRoot;
1813
- this.sources = out.sources;
1814
- if (!options.excludeContent) {
1815
- this.sourcesContent = out.sourcesContent;
1816
- }
1817
- }
1818
- toString() {
1819
- return JSON.stringify(this);
1820
- }
1821
- };
1822
-
1823
- // src/remapping.ts
1824
- function remapping(input, loader, options) {
1825
- const opts = { excludeContent: true, decodedMappings: false };
1826
- const tree = buildSourceMapTree(input, loader);
1827
- return new SourceMap(traceMappings(tree), opts);
1828
- }
1829
-
1830
- var virtualStats = {};
1831
-
1832
- var hasRequiredVirtualStats;
1833
-
1834
- function requireVirtualStats () {
1835
- if (hasRequiredVirtualStats) return virtualStats;
1836
- hasRequiredVirtualStats = 1;
1837
- var __importDefault = (virtualStats && virtualStats.__importDefault) || function (mod) {
1838
- return (mod && mod.__esModule) ? mod : { "default": mod };
1839
- };
1840
- Object.defineProperty(virtualStats, "__esModule", { value: true });
1841
- virtualStats.VirtualStats = void 0;
1842
- const constants_1 = __importDefault(require$$0);
1843
- class VirtualStats {
1844
- constructor(config) {
1845
- for (const key in config) {
1846
- if (!Object.prototype.hasOwnProperty.call(config, key)) {
1847
- continue;
1848
- }
1849
- this[key] = config[key];
1850
- }
1851
- }
1852
- _checkModeProperty(property) {
1853
- return (this.mode & constants_1.default.S_IFMT) === property;
1854
- }
1855
- isDirectory() {
1856
- return this._checkModeProperty(constants_1.default.S_IFDIR);
1857
- }
1858
- isFile() {
1859
- return this._checkModeProperty(constants_1.default.S_IFREG);
1860
- }
1861
- isBlockDevice() {
1862
- return this._checkModeProperty(constants_1.default.S_IFBLK);
1863
- }
1864
- isCharacterDevice() {
1865
- return this._checkModeProperty(constants_1.default.S_IFCHR);
1866
- }
1867
- isSymbolicLink() {
1868
- return this._checkModeProperty(constants_1.default.S_IFLNK);
1869
- }
1870
- isFIFO() {
1871
- return this._checkModeProperty(constants_1.default.S_IFIFO);
1872
- }
1873
- isSocket() {
1874
- return this._checkModeProperty(constants_1.default.S_IFSOCK);
1875
- }
1876
- }
1877
- virtualStats.VirtualStats = VirtualStats;
1878
-
1879
- return virtualStats;
1880
- }
1881
-
1882
- var lib;
1883
- var hasRequiredLib;
1884
-
1885
- function requireLib () {
1886
- if (hasRequiredLib) return lib;
1887
- hasRequiredLib = 1;
1888
- var __importDefault = (lib && lib.__importDefault) || function (mod) {
1889
- return (mod && mod.__esModule) ? mod : { "default": mod };
1890
- };
1891
- const path_1 = __importDefault(sysPath__default);
1892
- const virtual_stats_1 = requireVirtualStats();
1893
- let inode = 45000000;
1894
- const ALL = 'all';
1895
- const STATIC = 'static';
1896
- const DYNAMIC = 'dynamic';
1897
- function checkActivation(instance) {
1898
- if (!instance._compiler) {
1899
- throw new Error('You must use this plugin only after creating webpack instance!');
1900
- }
1901
- }
1902
- function getModulePath(filePath, compiler) {
1903
- return path_1.default.isAbsolute(filePath) ? filePath : path_1.default.join(compiler.context, filePath);
1904
- }
1905
- function createWebpackData(result) {
1906
- return (backendOrStorage) => {
1907
- if (backendOrStorage._data) {
1908
- const curLevelIdx = backendOrStorage._currentLevel;
1909
- const curLevel = backendOrStorage._levels[curLevelIdx];
1910
- return {
1911
- result,
1912
- level: curLevel,
1913
- };
1914
- }
1915
- return [null, result];
1916
- };
1917
- }
1918
- function getData(storage, key) {
1919
- if (storage._data instanceof Map) {
1920
- return storage._data.get(key);
1921
- }
1922
- else if (storage._data) {
1923
- return storage.data[key];
1924
- }
1925
- else if (storage.data instanceof Map) {
1926
- return storage.data.get(key);
1927
- }
1928
- else {
1929
- return storage.data[key];
1930
- }
1931
- }
1932
- function setData(backendOrStorage, key, valueFactory) {
1933
- const value = valueFactory(backendOrStorage);
1934
- if (backendOrStorage._data instanceof Map) {
1935
- backendOrStorage._data.set(key, value);
1936
- }
1937
- else if (backendOrStorage._data) {
1938
- backendOrStorage.data[key] = value;
1939
- }
1940
- else if (backendOrStorage.data instanceof Map) {
1941
- backendOrStorage.data.set(key, value);
1942
- }
1943
- else {
1944
- backendOrStorage.data[key] = value;
1945
- }
1946
- }
1947
- function getStatStorage(fileSystem) {
1948
- if (fileSystem._statStorage) {
1949
- return fileSystem._statStorage;
1950
- }
1951
- else if (fileSystem._statBackend) {
1952
- return fileSystem._statBackend;
1953
- }
1954
- else {
1955
- throw new Error("Couldn't find a stat storage");
1956
- }
1957
- }
1958
- function getFileStorage(fileSystem) {
1959
- if (fileSystem._readFileStorage) {
1960
- return fileSystem._readFileStorage;
1961
- }
1962
- else if (fileSystem._readFileBackend) {
1963
- return fileSystem._readFileBackend;
1964
- }
1965
- else {
1966
- throw new Error("Couldn't find a readFileStorage");
1967
- }
1968
- }
1969
- function getReadDirBackend(fileSystem) {
1970
- if (fileSystem._readdirBackend) {
1971
- return fileSystem._readdirBackend;
1972
- }
1973
- else if (fileSystem._readdirStorage) {
1974
- return fileSystem._readdirStorage;
1975
- }
1976
- else {
1977
- throw new Error("Couldn't find a readDirStorage from Webpack Internals");
1978
- }
1979
- }
1980
- function getRealpathBackend(fileSystem) {
1981
- if (fileSystem._realpathBackend) {
1982
- return fileSystem._realpathBackend;
1983
- }
1984
- }
1985
- class VirtualModulesPlugin {
1986
- constructor(modules) {
1987
- this._compiler = null;
1988
- this._watcher = null;
1989
- this._staticModules = modules || null;
1990
- }
1991
- getModuleList(filter = ALL) {
1992
- var _a, _b;
1993
- let modules = {};
1994
- const shouldGetStaticModules = filter === ALL || filter === STATIC;
1995
- const shouldGetDynamicModules = filter === ALL || filter === DYNAMIC;
1996
- if (shouldGetStaticModules) {
1997
- modules = Object.assign(Object.assign({}, modules), this._staticModules);
1998
- }
1999
- if (shouldGetDynamicModules) {
2000
- const finalInputFileSystem = (_a = this._compiler) === null || _a === void 0 ? void 0 : _a.inputFileSystem;
2001
- const virtualFiles = (_b = finalInputFileSystem === null || finalInputFileSystem === void 0 ? void 0 : finalInputFileSystem._virtualFiles) !== null && _b !== void 0 ? _b : {};
2002
- const dynamicModules = {};
2003
- Object.keys(virtualFiles).forEach((key) => {
2004
- dynamicModules[key] = virtualFiles[key].contents;
2005
- });
2006
- modules = Object.assign(Object.assign({}, modules), dynamicModules);
2007
- }
2008
- return modules;
2009
- }
2010
- writeModule(filePath, contents) {
2011
- if (!this._compiler) {
2012
- throw new Error(`Plugin has not been initialized`);
2013
- }
2014
- checkActivation(this);
2015
- const len = contents ? contents.length : 0;
2016
- const time = Date.now();
2017
- const date = new Date(time);
2018
- const stats = new virtual_stats_1.VirtualStats({
2019
- dev: 8675309,
2020
- nlink: 0,
2021
- uid: 1000,
2022
- gid: 1000,
2023
- rdev: 0,
2024
- blksize: 4096,
2025
- ino: inode++,
2026
- mode: 33188,
2027
- size: len,
2028
- blocks: Math.floor(len / 4096),
2029
- atime: date,
2030
- mtime: date,
2031
- ctime: date,
2032
- birthtime: date,
2033
- });
2034
- const modulePath = getModulePath(filePath, this._compiler);
2035
- if (process.env.WVM_DEBUG)
2036
- console.log(this._compiler.name, 'Write virtual module:', modulePath, contents);
2037
- let finalWatchFileSystem = this._watcher && this._watcher.watchFileSystem;
2038
- while (finalWatchFileSystem && finalWatchFileSystem.wfs) {
2039
- finalWatchFileSystem = finalWatchFileSystem.wfs;
2040
- }
2041
- let finalInputFileSystem = this._compiler.inputFileSystem;
2042
- while (finalInputFileSystem && finalInputFileSystem._inputFileSystem) {
2043
- finalInputFileSystem = finalInputFileSystem._inputFileSystem;
2044
- }
2045
- finalInputFileSystem._writeVirtualFile(modulePath, stats, contents);
2046
- if (finalWatchFileSystem &&
2047
- finalWatchFileSystem.watcher &&
2048
- (finalWatchFileSystem.watcher.fileWatchers.size || finalWatchFileSystem.watcher.fileWatchers.length)) {
2049
- const fileWatchers = finalWatchFileSystem.watcher.fileWatchers instanceof Map
2050
- ? Array.from(finalWatchFileSystem.watcher.fileWatchers.values())
2051
- : finalWatchFileSystem.watcher.fileWatchers;
2052
- for (let fileWatcher of fileWatchers) {
2053
- if ('watcher' in fileWatcher) {
2054
- fileWatcher = fileWatcher.watcher;
2055
- }
2056
- if (fileWatcher.path === modulePath) {
2057
- if (process.env.DEBUG)
2058
- console.log(this._compiler.name, 'Emit file change:', modulePath, time);
2059
- delete fileWatcher.directoryWatcher._cachedTimeInfoEntries;
2060
- fileWatcher.emit('change', time, null);
2061
- }
2062
- }
2063
- }
2064
- }
2065
- apply(compiler) {
2066
- this._compiler = compiler;
2067
- const afterEnvironmentHook = () => {
2068
- let finalInputFileSystem = compiler.inputFileSystem;
2069
- while (finalInputFileSystem && finalInputFileSystem._inputFileSystem) {
2070
- finalInputFileSystem = finalInputFileSystem._inputFileSystem;
2071
- }
2072
- if (!finalInputFileSystem._writeVirtualFile) {
2073
- const originalPurge = finalInputFileSystem.purge;
2074
- finalInputFileSystem.purge = () => {
2075
- originalPurge.apply(finalInputFileSystem, []);
2076
- if (finalInputFileSystem._virtualFiles) {
2077
- Object.keys(finalInputFileSystem._virtualFiles).forEach((file) => {
2078
- const data = finalInputFileSystem._virtualFiles[file];
2079
- finalInputFileSystem._writeVirtualFile(file, data.stats, data.contents);
2080
- });
2081
- }
2082
- };
2083
- finalInputFileSystem._writeVirtualFile = (file, stats, contents) => {
2084
- const statStorage = getStatStorage(finalInputFileSystem);
2085
- const fileStorage = getFileStorage(finalInputFileSystem);
2086
- const readDirStorage = getReadDirBackend(finalInputFileSystem);
2087
- const realPathStorage = getRealpathBackend(finalInputFileSystem);
2088
- finalInputFileSystem._virtualFiles = finalInputFileSystem._virtualFiles || {};
2089
- finalInputFileSystem._virtualFiles[file] = { stats: stats, contents: contents };
2090
- setData(statStorage, file, createWebpackData(stats));
2091
- setData(fileStorage, file, createWebpackData(contents));
2092
- const segments = file.split(/[\\/]/);
2093
- let count = segments.length - 1;
2094
- const minCount = segments[0] ? 1 : 0;
2095
- while (count > minCount) {
2096
- const dir = segments.slice(0, count).join(path_1.default.sep) || path_1.default.sep;
2097
- try {
2098
- finalInputFileSystem.readdirSync(dir);
2099
- }
2100
- catch (e) {
2101
- const time = Date.now();
2102
- const dirStats = new virtual_stats_1.VirtualStats({
2103
- dev: 8675309,
2104
- nlink: 0,
2105
- uid: 1000,
2106
- gid: 1000,
2107
- rdev: 0,
2108
- blksize: 4096,
2109
- ino: inode++,
2110
- mode: 16877,
2111
- size: stats.size,
2112
- blocks: Math.floor(stats.size / 4096),
2113
- atime: time,
2114
- mtime: time,
2115
- ctime: time,
2116
- birthtime: time,
2117
- });
2118
- setData(readDirStorage, dir, createWebpackData([]));
2119
- if (realPathStorage) {
2120
- setData(realPathStorage, dir, createWebpackData(dir));
2121
- }
2122
- setData(statStorage, dir, createWebpackData(dirStats));
2123
- }
2124
- let dirData = getData(getReadDirBackend(finalInputFileSystem), dir);
2125
- dirData = dirData[1] || dirData.result;
2126
- const filename = segments[count];
2127
- if (dirData.indexOf(filename) < 0) {
2128
- const files = dirData.concat([filename]).sort();
2129
- setData(getReadDirBackend(finalInputFileSystem), dir, createWebpackData(files));
2130
- }
2131
- else {
2132
- break;
2133
- }
2134
- count--;
2135
- }
2136
- };
2137
- }
2138
- };
2139
- const afterResolversHook = () => {
2140
- if (this._staticModules) {
2141
- for (const [filePath, contents] of Object.entries(this._staticModules)) {
2142
- this.writeModule(filePath, contents);
2143
- }
2144
- this._staticModules = null;
2145
- }
2146
- };
2147
- const version = typeof compiler.webpack === 'undefined' ? 4 : 5;
2148
- const watchRunHook = (watcher, callback) => {
2149
- this._watcher = watcher.compiler || watcher;
2150
- const virtualFiles = compiler.inputFileSystem._virtualFiles;
2151
- const fts = compiler.fileTimestamps;
2152
- if (virtualFiles && fts && typeof fts.set === 'function') {
2153
- Object.keys(virtualFiles).forEach((file) => {
2154
- const mtime = +virtualFiles[file].stats.mtime;
2155
- fts.set(file, version === 4
2156
- ? mtime
2157
- : {
2158
- safeTime: mtime,
2159
- timestamp: mtime,
2160
- });
2161
- });
2162
- }
2163
- callback();
2164
- };
2165
- if (compiler.hooks) {
2166
- compiler.hooks.afterEnvironment.tap('VirtualModulesPlugin', afterEnvironmentHook);
2167
- compiler.hooks.afterResolvers.tap('VirtualModulesPlugin', afterResolversHook);
2168
- compiler.hooks.watchRun.tapAsync('VirtualModulesPlugin', watchRunHook);
2169
- }
2170
- else {
2171
- compiler.plugin('after-environment', afterEnvironmentHook);
2172
- compiler.plugin('after-resolvers', afterResolversHook);
2173
- compiler.plugin('watch-run', watchRunHook);
2174
- }
2175
- }
2176
- }
2177
- lib = VirtualModulesPlugin;
2178
-
2179
- return lib;
2180
- }
2181
-
2182
- var libExports = requireLib();
2183
- const VirtualModulesPlugin = /*@__PURE__*/getDefaultExportFromCjs(libExports);
2184
-
2185
- //#region src/esbuild/utils.ts
2186
- const ExtToLoader = {
2187
- ".js": "js",
2188
- ".mjs": "js",
2189
- ".cjs": "js",
2190
- ".jsx": "jsx",
2191
- ".ts": "ts",
2192
- ".cts": "ts",
2193
- ".mts": "ts",
2194
- ".tsx": "tsx",
2195
- ".css": "css",
2196
- ".less": "css",
2197
- ".stylus": "css",
2198
- ".scss": "css",
2199
- ".sass": "css",
2200
- ".json": "json",
2201
- ".txt": "text"
2202
- };
2203
- function guessLoader(code, id) {
2204
- return ExtToLoader[path.extname(id).toLowerCase()] || "js";
2205
- }
2206
- function unwrapLoader(loader, code, id) {
2207
- if (typeof loader === "function") return loader(code, id);
2208
- return loader;
2209
- }
2210
- function fixSourceMap(map) {
2211
- if (!Object.prototype.hasOwnProperty.call(map, "toString")) Object.defineProperty(map, "toString", {
2212
- enumerable: false,
2213
- value: function toString() {
2214
- return JSON.stringify(this);
2215
- }
2216
- });
2217
- if (!Object.prototype.hasOwnProperty.call(map, "toUrl")) Object.defineProperty(map, "toUrl", {
2218
- enumerable: false,
2219
- value: function toUrl() {
2220
- return `data:application/json;charset=utf-8;base64,${Buffer$1.from(this.toString()).toString("base64")}`;
2221
- }
2222
- });
2223
- return map;
2224
- }
2225
- const nullSourceMap = {
2226
- names: [],
2227
- sources: [],
2228
- mappings: "",
2229
- version: 3
2230
- };
2231
- function combineSourcemaps(filename, sourcemapList) {
2232
- sourcemapList = sourcemapList.filter((m) => m.sources);
2233
- if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0)) return { ...nullSourceMap };
2234
- let map;
2235
- let mapIndex = 1;
2236
- const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === void 0;
2237
- if (useArrayInterface) map = remapping(sourcemapList, () => null);
2238
- else map = remapping(sourcemapList[0], (sourcefile) => {
2239
- if (sourcefile === filename && sourcemapList[mapIndex]) return sourcemapList[mapIndex++];
2240
- else return { ...nullSourceMap };
2241
- });
2242
- if (!map.file) delete map.file;
2243
- return map;
2244
- }
2245
- function createBuildContext$2(build) {
2246
- const watchFiles = [];
2247
- const { initialOptions } = build;
2248
- return {
2249
- parse: parse$1,
2250
- addWatchFile() {
2251
- throw new Error("unplugin/esbuild: addWatchFile outside supported hooks (resolveId, load, transform)");
2252
- },
2253
- emitFile(emittedFile) {
2254
- const outFileName = emittedFile.fileName || emittedFile.name;
2255
- if (initialOptions.outdir && emittedFile.source && outFileName) {
2256
- const outPath = path.resolve(initialOptions.outdir, outFileName);
2257
- const outDir = path.dirname(outPath);
2258
- if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true });
2259
- fs.writeFileSync(outPath, emittedFile.source);
2260
- }
2261
- },
2262
- getWatchFiles() {
2263
- return watchFiles;
2264
- },
2265
- getNativeBuildContext() {
2266
- return {
2267
- framework: "esbuild",
2268
- build
2269
- };
2270
- }
2271
- };
2272
- }
2273
- function createPluginContext(context) {
2274
- const errors = [];
2275
- const warnings = [];
2276
- const pluginContext = {
2277
- error(message) {
2278
- errors.push(normalizeMessage$2(message));
2279
- },
2280
- warn(message) {
2281
- warnings.push(normalizeMessage$2(message));
2282
- }
2283
- };
2284
- const mixedContext = {
2285
- ...context,
2286
- ...pluginContext,
2287
- addWatchFile(id) {
2288
- context.getWatchFiles().push(id);
2289
- }
2290
- };
2291
- return {
2292
- errors,
2293
- warnings,
2294
- mixedContext
2295
- };
2296
- }
2297
- function normalizeMessage$2(message) {
2298
- if (typeof message === "string") message = { message };
2299
- return {
2300
- id: message.id,
2301
- pluginName: message.plugin,
2302
- text: message.message,
2303
- location: message.loc ? {
2304
- file: message.loc.file,
2305
- line: message.loc.line,
2306
- column: message.loc.column
2307
- } : null,
2308
- detail: message.meta,
2309
- notes: []
2310
- };
2311
- }
2312
- function processCodeWithSourceMap(map, code) {
2313
- if (map) {
2314
- if (!map.sourcesContent || map.sourcesContent.length === 0) map.sourcesContent = [code];
2315
- map = fixSourceMap(map);
2316
- code += `\n//# sourceMappingURL=${map.toUrl()}`;
2317
- }
2318
- return code;
2319
- }
2320
-
2321
- //#endregion
2322
- //#region src/esbuild/index.ts
2323
- function getEsbuildPlugin(factory) {
2324
- return (userOptions) => {
2325
- const meta = { framework: "esbuild" };
2326
- const plugins = toArray$2(factory(userOptions, meta));
2327
- const setupPlugins = async (build) => {
2328
- const setup = buildSetup();
2329
- const loaders = [];
2330
- for (const plugin of plugins) {
2331
- const loader = {};
2332
- await setup(plugin)({
2333
- ...build,
2334
- onLoad(_options, callback) {
2335
- loader.options = _options;
2336
- loader.onLoadCb = callback;
2337
- },
2338
- onTransform(_options, callback) {
2339
- loader.options ||= _options;
2340
- loader.onTransformCb = callback;
2341
- }
2342
- }, build);
2343
- if (loader.onLoadCb || loader.onTransformCb) loaders.push(loader);
2344
- }
2345
- if (loaders.length) build.onLoad(loaders.length === 1 ? loaders[0].options : { filter: /.*/ }, async (args) => {
2346
- function checkFilter(options) {
2347
- return loaders.length === 1 || !options?.filter || options.filter.test(args.path);
2348
- }
2349
- let result;
2350
- for (const { options, onLoadCb } of loaders) {
2351
- if (!checkFilter(options)) continue;
2352
- if (onLoadCb) result = await onLoadCb(args);
2353
- if (result?.contents) break;
2354
- }
2355
- let fsContentsCache;
2356
- for (const { options, onTransformCb } of loaders) {
2357
- if (!checkFilter(options)) continue;
2358
- if (onTransformCb) {
2359
- const newArgs = {
2360
- ...result,
2361
- ...args,
2362
- async getContents() {
2363
- if (result?.contents) return result.contents;
2364
- if (fsContentsCache) return fsContentsCache;
2365
- return fsContentsCache = await fs.promises.readFile(args.path, "utf8");
2366
- }
2367
- };
2368
- const _result = await onTransformCb(newArgs);
2369
- if (_result?.contents) result = _result;
2370
- }
2371
- }
2372
- if (result?.contents) return result;
2373
- });
2374
- };
2375
- return {
2376
- name: (plugins.length === 1 ? plugins[0].name : meta.esbuildHostName) ?? `unplugin-host:${plugins.map((p) => p.name).join(":")}`,
2377
- setup: setupPlugins
2378
- };
2379
- };
2380
- }
2381
- function buildSetup() {
2382
- return (plugin) => {
2383
- return (build, rawBuild) => {
2384
- const context = createBuildContext$2(rawBuild);
2385
- const { onStart, onEnd, onResolve, onLoad, onTransform, initialOptions } = build;
2386
- const onResolveFilter = plugin.esbuild?.onResolveFilter ?? /.*/;
2387
- const onLoadFilter = plugin.esbuild?.onLoadFilter ?? /.*/;
2388
- const loader = plugin.esbuild?.loader ?? guessLoader;
2389
- plugin.esbuild?.config?.call(context, initialOptions);
2390
- if (plugin.buildStart) onStart(() => plugin.buildStart.call(context));
2391
- if (plugin.buildEnd || plugin.writeBundle) onEnd(async () => {
2392
- if (plugin.buildEnd) await plugin.buildEnd.call(context);
2393
- if (plugin.writeBundle) await plugin.writeBundle();
2394
- });
2395
- if (plugin.resolveId) onResolve({ filter: onResolveFilter }, async (args) => {
2396
- const id = args.path;
2397
- if (initialOptions.external?.includes(id)) return;
2398
- const { handler, filter } = normalizeObjectHook("resolveId", plugin.resolveId);
2399
- if (!filter(id)) return;
2400
- const { errors, warnings, mixedContext } = createPluginContext(context);
2401
- const isEntry = args.kind === "entry-point";
2402
- const result = await handler.call(mixedContext, id, isEntry ? void 0 : args.importer, { isEntry });
2403
- if (typeof result === "string") return {
2404
- path: result,
2405
- namespace: plugin.name,
2406
- errors,
2407
- warnings,
2408
- watchFiles: mixedContext.getWatchFiles()
2409
- };
2410
- else if (typeof result === "object" && result !== null) return {
2411
- path: result.id,
2412
- external: result.external,
2413
- namespace: plugin.name,
2414
- errors,
2415
- warnings,
2416
- watchFiles: mixedContext.getWatchFiles()
2417
- };
2418
- });
2419
- if (plugin.load) onLoad({ filter: onLoadFilter }, async (args) => {
2420
- const { handler, filter } = normalizeObjectHook("load", plugin.load);
2421
- const id = args.path + (args.suffix || "");
2422
- if (plugin.loadInclude && !plugin.loadInclude(id)) return;
2423
- if (!filter(id)) return;
2424
- const { errors, warnings, mixedContext } = createPluginContext(context);
2425
- let code;
2426
- let map;
2427
- const result = await handler.call(mixedContext, id);
2428
- if (typeof result === "string") code = result;
2429
- else if (typeof result === "object" && result !== null) {
2430
- code = result.code;
2431
- map = result.map;
2432
- }
2433
- if (code === void 0) return null;
2434
- if (map) code = processCodeWithSourceMap(map, code);
2435
- const resolveDir = path.dirname(args.path);
2436
- return {
2437
- contents: code,
2438
- errors,
2439
- warnings,
2440
- watchFiles: mixedContext.getWatchFiles(),
2441
- loader: unwrapLoader(loader, code, args.path),
2442
- resolveDir
2443
- };
2444
- });
2445
- if (plugin.transform) onTransform({ filter: onLoadFilter }, async (args) => {
2446
- const { handler, filter } = normalizeObjectHook("transform", plugin.transform);
2447
- const id = args.path + (args.suffix || "");
2448
- if (plugin.transformInclude && !plugin.transformInclude(id)) return;
2449
- let code = await args.getContents();
2450
- if (!filter(id, code)) return;
2451
- const { mixedContext, errors, warnings } = createPluginContext(context);
2452
- const resolveDir = path.dirname(args.path);
2453
- let map;
2454
- const result = await handler.call(mixedContext, code, id);
2455
- if (typeof result === "string") code = result;
2456
- else if (typeof result === "object" && result !== null) {
2457
- code = result.code;
2458
- if (map && result.map) map = combineSourcemaps(args.path, [result.map === "string" ? JSON.parse(result.map) : result.map, map]);
2459
- else if (typeof result.map === "string") map = JSON.parse(result.map);
2460
- else map = result.map;
2461
- }
2462
- if (code) {
2463
- if (map) code = processCodeWithSourceMap(map, code);
2464
- return {
2465
- contents: code,
2466
- errors,
2467
- warnings,
2468
- watchFiles: mixedContext.getWatchFiles(),
2469
- loader: unwrapLoader(loader, code, args.path),
2470
- resolveDir
2471
- };
2472
- }
2473
- });
2474
- if (plugin.esbuild?.setup) return plugin.esbuild.setup(rawBuild);
2475
- };
2476
- };
2477
- }
2478
-
2479
- //#endregion
2480
- //#region src/farm/context.ts
2481
- function createFarmContext(context, currentResolveId) {
2482
- return {
2483
- parse: parse$1,
2484
- addWatchFile(id) {
2485
- context.addWatchFile(id, currentResolveId || id);
2486
- },
2487
- emitFile(emittedFile) {
2488
- const outFileName = emittedFile.fileName || emittedFile.name;
2489
- if (emittedFile.source && outFileName) context.emitFile({
2490
- resolvedPath: outFileName,
2491
- name: outFileName,
2492
- content: [...Buffer$1.from(emittedFile.source)],
2493
- resourceType: extname(outFileName)
2494
- });
2495
- },
2496
- getWatchFiles() {
2497
- return context.getWatchFiles();
2498
- },
2499
- getNativeBuildContext() {
2500
- return {
2501
- framework: "farm",
2502
- context
2503
- };
2504
- }
2505
- };
2506
- }
2507
- function unpluginContext(context) {
2508
- return {
2509
- error: (error) => context.error(typeof error === "string" ? new Error(error) : error),
2510
- warn: (error) => context.warn(typeof error === "string" ? new Error(error) : error)
2511
- };
2512
- }
2513
-
2514
- //#endregion
2515
- //#region src/farm/utils.ts
2516
- function convertEnforceToPriority(value) {
2517
- const defaultPriority = 100;
2518
- const enforceToPriority = {
2519
- pre: 102,
2520
- post: 98
2521
- };
2522
- return enforceToPriority[value] !== void 0 ? enforceToPriority[value] : defaultPriority;
2523
- }
2524
- function convertWatchEventChange(value) {
2525
- const watchEventChange = {
2526
- Added: "create",
2527
- Updated: "update",
2528
- Removed: "delete"
2529
- };
2530
- return watchEventChange[value];
2531
- }
2532
- function isString(variable) {
2533
- return typeof variable === "string";
2534
- }
2535
- function isObject(variable) {
2536
- return typeof variable === "object" && variable !== null;
2537
- }
2538
- function customParseQueryString(url) {
2539
- if (!url) return [];
2540
- const queryString = url.split("?")[1];
2541
- const parsedParams = querystring.parse(queryString);
2542
- const paramsArray = [];
2543
- for (const key in parsedParams) paramsArray.push([key, parsedParams[key]]);
2544
- return paramsArray;
2545
- }
2546
- function encodeStr(str) {
2547
- const len = str.length;
2548
- if (len === 0) return str;
2549
- const firstNullIndex = str.indexOf("\0");
2550
- if (firstNullIndex === -1) return str;
2551
- const result = Array.from({ length: len + countNulls(str, firstNullIndex) });
2552
- let pos = 0;
2553
- for (let i = 0; i < firstNullIndex; i++) result[pos++] = str[i];
2554
- for (let i = firstNullIndex; i < len; i++) {
2555
- const char = str[i];
2556
- if (char === "\0") {
2557
- result[pos++] = "\\";
2558
- result[pos++] = "0";
2559
- } else result[pos++] = char;
2560
- }
2561
- return path.posix.normalize(result.join(""));
2562
- }
2563
- function decodeStr(str) {
2564
- const len = str.length;
2565
- if (len === 0) return str;
2566
- const firstIndex = str.indexOf("\\0");
2567
- if (firstIndex === -1) return str;
2568
- const result = Array.from({ length: len - countBackslashZeros(str, firstIndex) });
2569
- let pos = 0;
2570
- for (let i$1 = 0; i$1 < firstIndex; i$1++) result[pos++] = str[i$1];
2571
- let i = firstIndex;
2572
- while (i < len) if (str[i] === "\\" && str[i + 1] === "0") {
2573
- result[pos++] = "\0";
2574
- i += 2;
2575
- } else result[pos++] = str[i++];
2576
- return path.posix.normalize(result.join(""));
2577
- }
2578
- function getContentValue(content) {
2579
- if (content === null || content === void 0) throw new Error("Content cannot be null or undefined");
2580
- const strContent = typeof content === "string" ? content : content.code || "";
2581
- return encodeStr(strContent);
2582
- }
2583
- function countNulls(str, startIndex) {
2584
- let count = 0;
2585
- const len = str.length;
2586
- for (let i = startIndex; i < len; i++) if (str[i] === "\0") count++;
2587
- return count;
2588
- }
2589
- function countBackslashZeros(str, startIndex) {
2590
- let count = 0;
2591
- const len = str.length;
2592
- for (let i = startIndex; i < len - 1; i++) if (str[i] === "\\" && str[i + 1] === "0") {
2593
- count++;
2594
- i++;
2595
- }
2596
- return count;
2597
- }
2598
- function removeQuery(pathe) {
2599
- const queryIndex = pathe.indexOf("?");
2600
- if (queryIndex !== -1) return path.posix.normalize(pathe.slice(0, queryIndex));
2601
- return path.posix.normalize(pathe);
2602
- }
2603
- function isStartsWithSlash(str) {
2604
- return str?.startsWith("/");
2605
- }
2606
- function appendQuery(id, query) {
2607
- if (!query.length) return id;
2608
- return `${id}?${stringifyQuery(query)}`;
2609
- }
2610
- function stringifyQuery(query) {
2611
- if (!query.length) return "";
2612
- let queryStr = "";
2613
- for (const [key, value] of query) queryStr += `${key}${value ? `=${value}` : ""}&`;
2614
- return `${queryStr.slice(0, -1)}`;
2615
- }
2616
- const CSS_LANGS_RES = [
2617
- [/\.(less)(?:$|\?)/, "less"],
2618
- [/\.(scss|sass)(?:$|\?)/, "sass"],
2619
- [/\.(styl|stylus)(?:$|\?)/, "stylus"],
2620
- [/\.(css)(?:$|\?)/, "css"]
2621
- ];
2622
- const JS_LANGS_RES = [
2623
- [/\.(js|mjs|cjs)(?:$|\?)/, "js"],
2624
- [/\.(jsx)(?:$|\?)/, "jsx"],
2625
- [/\.(ts|cts|mts)(?:$|\?)/, "ts"],
2626
- [/\.(tsx)(?:$|\?)/, "tsx"]
2627
- ];
2628
- function getCssModuleType(id) {
2629
- for (const [reg, lang] of CSS_LANGS_RES) if (reg.test(id)) return lang;
2630
- return null;
2631
- }
2632
- function getJsModuleType(id) {
2633
- for (const [reg, lang] of JS_LANGS_RES) if (reg.test(id)) return lang;
2634
- return null;
2635
- }
2636
- function formatLoadModuleType(id) {
2637
- const cssModuleType = getCssModuleType(id);
2638
- if (cssModuleType) return cssModuleType;
2639
- const jsModuleType = getJsModuleType(id);
2640
- if (jsModuleType) return jsModuleType;
2641
- return "js";
2642
- }
2643
- function formatTransformModuleType(id) {
2644
- return formatLoadModuleType(id);
2645
- }
2646
-
2647
- //#endregion
2648
- //#region src/farm/index.ts
2649
- function getFarmPlugin(factory) {
2650
- return ((userOptions) => {
2651
- const meta = { framework: "farm" };
2652
- const rawPlugins = toArray$2(factory(userOptions, meta));
2653
- const plugins = rawPlugins.map((rawPlugin) => {
2654
- const plugin = toFarmPlugin(rawPlugin, userOptions);
2655
- if (rawPlugin.farm) Object.assign(plugin, rawPlugin.farm);
2656
- return plugin;
2657
- });
2658
- return plugins.length === 1 ? plugins[0] : plugins;
2659
- });
2660
- }
2661
- function toFarmPlugin(plugin, options) {
2662
- const farmPlugin = {
2663
- name: plugin.name,
2664
- priority: convertEnforceToPriority(plugin.enforce)
2665
- };
2666
- if (plugin.farm) Object.keys(plugin.farm).forEach((key) => {
2667
- const value = plugin.farm[key];
2668
- if (value) Reflect.set(farmPlugin, key, value);
2669
- });
2670
- if (plugin.buildStart) {
2671
- const _buildStart = plugin.buildStart;
2672
- farmPlugin.buildStart = { async executor(_, context) {
2673
- await _buildStart.call(createFarmContext(context));
2674
- } };
2675
- }
2676
- if (plugin.resolveId) {
2677
- const _resolveId = plugin.resolveId;
2678
- let filters = [];
2679
- if (options) filters = options?.filters ?? [];
2680
- farmPlugin.resolve = {
2681
- filters: {
2682
- sources: filters.length ? filters : [".*"],
2683
- importers: [".*"]
2684
- },
2685
- async executor(params, context) {
2686
- const resolvedIdPath = path.resolve(params.importer ?? "");
2687
- const id = decodeStr(params.source);
2688
- const { handler, filter } = normalizeObjectHook("resolveId", _resolveId);
2689
- if (!filter(id)) return null;
2690
- let isEntry = false;
2691
- if (isObject(params.kind) && "entry" in params.kind) {
2692
- const kindWithEntry = params.kind;
2693
- isEntry = kindWithEntry.entry === "index";
2694
- }
2695
- const farmContext = createFarmContext(context, resolvedIdPath);
2696
- const resolveIdResult = await handler.call(Object.assign(unpluginContext(context), farmContext), id, resolvedIdPath ?? null, { isEntry });
2697
- if (isString(resolveIdResult)) return {
2698
- resolvedPath: removeQuery(encodeStr(resolveIdResult)),
2699
- query: customParseQueryString(resolveIdResult),
2700
- sideEffects: true,
2701
- external: false,
2702
- meta: {}
2703
- };
2704
- if (isObject(resolveIdResult)) return {
2705
- resolvedPath: removeQuery(encodeStr(resolveIdResult?.id)),
2706
- query: customParseQueryString(resolveIdResult?.id),
2707
- sideEffects: false,
2708
- external: Boolean(resolveIdResult?.external),
2709
- meta: {}
2710
- };
2711
- if (!isStartsWithSlash(params.source)) return null;
2712
- }
2713
- };
2714
- }
2715
- if (plugin.load) {
2716
- const _load = plugin.load;
2717
- farmPlugin.load = {
2718
- filters: { resolvedPaths: [".*"] },
2719
- async executor(params, context) {
2720
- const resolvedPath = decodeStr(params.resolvedPath);
2721
- const id = appendQuery(resolvedPath, params.query);
2722
- const loader = formatTransformModuleType(id);
2723
- if (plugin.loadInclude && !plugin.loadInclude?.(id)) return null;
2724
- const { handler, filter } = normalizeObjectHook("load", _load);
2725
- if (!filter(id)) return null;
2726
- const farmContext = createFarmContext(context, id);
2727
- const content = await handler.call(Object.assign(unpluginContext(context), farmContext), id);
2728
- const loadFarmResult = {
2729
- content: getContentValue(content),
2730
- moduleType: loader
2731
- };
2732
- return loadFarmResult;
2733
- }
2734
- };
2735
- }
2736
- if (plugin.transform) {
2737
- const _transform = plugin.transform;
2738
- farmPlugin.transform = {
2739
- filters: {
2740
- resolvedPaths: [".*"],
2741
- moduleTypes: [".*"]
2742
- },
2743
- async executor(params, context) {
2744
- const resolvedPath = decodeStr(params.resolvedPath);
2745
- const id = appendQuery(resolvedPath, params.query);
2746
- const loader = formatTransformModuleType(id);
2747
- if (plugin.transformInclude && !plugin.transformInclude(id)) return null;
2748
- const { handler, filter } = normalizeObjectHook("transform", _transform);
2749
- if (!filter(id, params.content)) return null;
2750
- const farmContext = createFarmContext(context, id);
2751
- const resource = await handler.call(Object.assign(unpluginContext(context), farmContext), params.content, id);
2752
- if (resource && typeof resource !== "string") {
2753
- const transformFarmResult = {
2754
- content: getContentValue(resource),
2755
- moduleType: loader,
2756
- sourceMap: typeof resource.map === "object" && resource.map !== null ? JSON.stringify(resource.map) : void 0
2757
- };
2758
- return transformFarmResult;
2759
- }
2760
- }
2761
- };
2762
- }
2763
- if (plugin.watchChange) {
2764
- const _watchChange = plugin.watchChange;
2765
- farmPlugin.updateModules = { async executor(param, context) {
2766
- const updatePathContent = param.paths[0];
2767
- const ModifiedPath = updatePathContent[0];
2768
- const eventChange = convertWatchEventChange(updatePathContent[1]);
2769
- await _watchChange.call(createFarmContext(context), ModifiedPath, { event: eventChange });
2770
- } };
2771
- }
2772
- if (plugin.buildEnd) {
2773
- const _buildEnd = plugin.buildEnd;
2774
- farmPlugin.buildEnd = { async executor(_, context) {
2775
- await _buildEnd.call(createFarmContext(context));
2776
- } };
2777
- }
2778
- if (plugin.writeBundle) {
2779
- const _writeBundle = plugin.writeBundle;
2780
- farmPlugin.finish = { async executor() {
2781
- await _writeBundle();
2782
- } };
2783
- }
2784
- return farmPlugin;
2785
- }
2786
-
2787
- //#endregion
2788
- //#region src/rollup/index.ts
2789
- function getRollupPlugin(factory) {
2790
- return ((userOptions) => {
2791
- const meta = { framework: "rollup" };
2792
- const rawPlugins = toArray$2(factory(userOptions, meta));
2793
- const plugins = rawPlugins.map((plugin) => toRollupPlugin(plugin, "rollup"));
2794
- return plugins.length === 1 ? plugins[0] : plugins;
2795
- });
2796
- }
2797
- function toRollupPlugin(plugin, key) {
2798
- const nativeFilter = key === "rolldown";
2799
- if (plugin.resolveId && !nativeFilter && typeof plugin.resolveId === "object" && plugin.resolveId.filter) {
2800
- const resolveIdHook = plugin.resolveId;
2801
- const { handler, filter } = normalizeObjectHook("load", resolveIdHook);
2802
- replaceHookHandler("resolveId", resolveIdHook, function(...args) {
2803
- const [id] = args;
2804
- const supportFilter = supportNativeFilter(this, key);
2805
- if (!supportFilter && !filter(id)) return;
2806
- return handler.apply(this, args);
2807
- });
2808
- }
2809
- if (plugin.load && (plugin.loadInclude || !nativeFilter && typeof plugin.load === "object" && plugin.load.filter)) {
2810
- const loadHook = plugin.load;
2811
- const { handler, filter } = normalizeObjectHook("load", loadHook);
2812
- replaceHookHandler("load", loadHook, function(...args) {
2813
- const [id] = args;
2814
- if (plugin.loadInclude && !plugin.loadInclude(id)) return;
2815
- const supportFilter = supportNativeFilter(this, key);
2816
- if (!supportFilter && !filter(id)) return;
2817
- return handler.apply(this, args);
2818
- });
2819
- }
2820
- if (plugin.transform && (plugin.transformInclude || !nativeFilter && typeof plugin.transform === "object" && plugin.transform.filter)) {
2821
- const transformHook = plugin.transform;
2822
- const { handler, filter } = normalizeObjectHook("transform", transformHook);
2823
- replaceHookHandler("transform", transformHook, function(...args) {
2824
- const [code, id] = args;
2825
- if (plugin.transformInclude && !plugin.transformInclude(id)) return;
2826
- const supportFilter = supportNativeFilter(this, key);
2827
- if (!supportFilter && !filter(id, code)) return;
2828
- return handler.apply(this, args);
2829
- });
2830
- }
2831
- if (plugin[key]) Object.assign(plugin, plugin[key]);
2832
- return plugin;
2833
- function replaceHookHandler(name, hook, handler) {
2834
- if (typeof hook === "function") plugin[name] = handler;
2835
- else hook.handler = handler;
2836
- }
2837
- }
2838
- function supportNativeFilter(context, framework) {
2839
- if (framework === "unloader") return false;
2840
- if (framework === "vite") return !!context?.meta?.viteVersion;
2841
- if (framework === "rolldown") return true;
2842
- const rollupVersion = context?.meta?.rollupVersion;
2843
- if (!rollupVersion) return false;
2844
- const [major, minor] = rollupVersion.split(".");
2845
- return Number(major) > 4 || Number(major) === 4 && Number(minor) >= 40;
2846
- }
2847
-
2848
- //#endregion
2849
- //#region src/rolldown/index.ts
2850
- function getRolldownPlugin(factory) {
2851
- return ((userOptions) => {
2852
- const meta = { framework: "rolldown" };
2853
- const rawPlugins = toArray$2(factory(userOptions, meta));
2854
- const plugins = rawPlugins.map((rawPlugin) => {
2855
- const plugin = toRollupPlugin(rawPlugin, "rolldown");
2856
- return plugin;
2857
- });
2858
- return plugins.length === 1 ? plugins[0] : plugins;
2859
- });
2860
- }
2861
-
2862
- //#endregion
2863
- //#region node_modules/.pnpm/tsdown@0.14.1_publint@0.3.5_typescript@5.9.2_unplugin-unused@0.5.2_vue-tsc@3.0.6_typescript@5.9.2_/node_modules/tsdown/esm-shims.js
2864
- const getFilename = () => fileURLToPath(import.meta.url);
2865
- const getDirname = () => path.dirname(getFilename());
2866
- const __dirname = /* @__PURE__ */ getDirname();
2867
-
2868
- //#endregion
2869
- //#region src/rspack/index.ts
2870
- const TRANSFORM_LOADER$1 = resolve$3(__dirname, "rspack/loaders/transform");
2871
- const LOAD_LOADER$1 = resolve$3(__dirname, "rspack/loaders/load");
2872
- function getRspackPlugin(factory) {
2873
- return (userOptions) => {
2874
- return { apply(compiler) {
2875
- const VIRTUAL_MODULE_PREFIX = resolve$3(compiler.options.context ?? process.cwd(), "node_modules/.virtual", process.pid.toString());
2876
- const meta = {
2877
- framework: "rspack",
2878
- rspack: { compiler }
2879
- };
2880
- const rawPlugins = toArray$2(factory(userOptions, meta));
2881
- for (const rawPlugin of rawPlugins) {
2882
- const plugin = Object.assign(rawPlugin, {
2883
- __unpluginMeta: meta,
2884
- __virtualModulePrefix: VIRTUAL_MODULE_PREFIX
2885
- });
2886
- const externalModules = /* @__PURE__ */ new Set();
2887
- if (plugin.resolveId) {
2888
- const createPlugin = (plugin$1) => {
2889
- if (compiler.rspack.experiments.VirtualModulesPlugin) return new compiler.rspack.experiments.VirtualModulesPlugin();
2890
- return new FakeVirtualModulesPlugin(plugin$1);
2891
- };
2892
- const vfs = createPlugin(plugin);
2893
- vfs.apply(compiler);
2894
- const vfsModules = /* @__PURE__ */ new Map();
2895
- plugin.__vfsModules = vfsModules;
2896
- plugin.__vfs = vfs;
2897
- compiler.hooks.compilation.tap(plugin.name, (compilation, { normalModuleFactory }) => {
2898
- normalModuleFactory.hooks.resolve.tapPromise(plugin.name, async (resolveData) => {
2899
- const id = normalizeAbsolutePath(resolveData.request);
2900
- const requestContext = resolveData.contextInfo;
2901
- let importer = requestContext.issuer !== "" ? requestContext.issuer : void 0;
2902
- const isEntry = requestContext.issuer === "";
2903
- if (importer?.startsWith(plugin.__virtualModulePrefix)) importer = decodeURIComponent(importer.slice(plugin.__virtualModulePrefix.length));
2904
- const context = createBuildContext$1(compiler, compilation);
2905
- let error;
2906
- const pluginContext = {
2907
- error(msg) {
2908
- if (error == null) error = normalizeMessage$1(msg);
2909
- else console.error(`unplugin/rspack: multiple errors returned from resolveId hook: ${msg}`);
2910
- },
2911
- warn(msg) {
2912
- console.warn(`unplugin/rspack: warning from resolveId hook: ${msg}`);
2913
- }
2914
- };
2915
- const { handler, filter } = normalizeObjectHook("resolveId", plugin.resolveId);
2916
- if (!filter(id)) return;
2917
- const resolveIdResult = await handler.call({
2918
- ...context,
2919
- ...pluginContext
2920
- }, id, importer, { isEntry });
2921
- if (error != null) throw error;
2922
- if (resolveIdResult == null) return;
2923
- let resolved = typeof resolveIdResult === "string" ? resolveIdResult : resolveIdResult.id;
2924
- const isExternal = typeof resolveIdResult === "string" ? false : resolveIdResult.external === true;
2925
- if (isExternal) externalModules.add(resolved);
2926
- let isVirtual = true;
2927
- try {
2928
- (compiler.inputFileSystem?.statSync ?? fs.statSync)(resolved);
2929
- isVirtual = false;
2930
- } catch {
2931
- isVirtual = !isVirtualModuleId(resolved, plugin);
2932
- }
2933
- if (isVirtual) {
2934
- const encodedVirtualPath = encodeVirtualModuleId(resolved, plugin);
2935
- if (!vfsModules.has(resolved)) {
2936
- const fsPromise = Promise.resolve(vfs.writeModule(encodedVirtualPath, ""));
2937
- vfsModules.set(resolved, fsPromise);
2938
- await fsPromise;
2939
- } else await vfsModules.get(resolved);
2940
- resolved = encodedVirtualPath;
2941
- }
2942
- resolveData.request = resolved;
2943
- });
2944
- });
2945
- }
2946
- if (plugin.load) compiler.options.module.rules.unshift({
2947
- enforce: plugin.enforce,
2948
- include(id) {
2949
- if (isVirtualModuleId(id, plugin)) id = decodeVirtualModuleId(id);
2950
- if (plugin.loadInclude && !plugin.loadInclude(id)) return false;
2951
- const { filter } = normalizeObjectHook("load", plugin.load);
2952
- if (!filter(id)) return false;
2953
- return !externalModules.has(id);
2954
- },
2955
- use: [{
2956
- loader: LOAD_LOADER$1,
2957
- options: { plugin }
2958
- }],
2959
- type: "javascript/auto"
2960
- });
2961
- if (plugin.transform) compiler.options.module.rules.unshift({
2962
- enforce: plugin.enforce,
2963
- use(data) {
2964
- return transformUse(data, plugin, TRANSFORM_LOADER$1);
2965
- }
2966
- });
2967
- if (plugin.rspack) plugin.rspack(compiler);
2968
- if (plugin.watchChange || plugin.buildStart) compiler.hooks.make.tapPromise(plugin.name, async (compilation) => {
2969
- const context = createBuildContext$1(compiler, compilation);
2970
- if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) {
2971
- const promises = [];
2972
- if (compiler.modifiedFiles) compiler.modifiedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "update" }))));
2973
- if (compiler.removedFiles) compiler.removedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "delete" }))));
2974
- await Promise.all(promises);
2975
- }
2976
- if (plugin.buildStart) return await plugin.buildStart.call(context);
2977
- });
2978
- if (plugin.buildEnd) compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => {
2979
- await plugin.buildEnd.call(createBuildContext$1(compiler, compilation));
2980
- });
2981
- if (plugin.writeBundle) compiler.hooks.afterEmit.tapPromise(plugin.name, async () => {
2982
- await plugin.writeBundle();
2983
- });
2984
- }
2985
- } };
2986
- };
2987
- }
2988
-
2989
- //#endregion
2990
- //#region src/unloader/index.ts
2991
- function getUnloaderPlugin(factory) {
2992
- return ((userOptions) => {
2993
- const meta = { framework: "unloader" };
2994
- const rawPlugins = toArray$2(factory(userOptions, meta));
2995
- const plugins = rawPlugins.map((rawPlugin) => {
2996
- const plugin = toRollupPlugin(rawPlugin, "unloader");
2997
- return plugin;
2998
- });
2999
- return plugins.length === 1 ? plugins[0] : plugins;
3000
- });
3001
- }
3002
-
3003
- //#endregion
3004
- //#region src/vite/index.ts
3005
- function getVitePlugin(factory) {
3006
- return ((userOptions) => {
3007
- const meta = { framework: "vite" };
3008
- const rawPlugins = toArray$2(factory(userOptions, meta));
3009
- const plugins = rawPlugins.map((rawPlugin) => {
3010
- const plugin = toRollupPlugin(rawPlugin, "vite");
3011
- return plugin;
3012
- });
3013
- return plugins.length === 1 ? plugins[0] : plugins;
3014
- });
3015
- }
3016
-
3017
- //#endregion
3018
- //#region src/webpack/index.ts
3019
- const TRANSFORM_LOADER = resolve$3(__dirname, "webpack/loaders/transform");
3020
- const LOAD_LOADER = resolve$3(__dirname, "webpack/loaders/load");
3021
- function getWebpackPlugin(factory) {
3022
- return (userOptions) => {
3023
- return { apply(compiler) {
3024
- const VIRTUAL_MODULE_PREFIX = resolve$3(compiler.options.context ?? process$1.cwd(), "_virtual_");
3025
- const meta = {
3026
- framework: "webpack",
3027
- webpack: { compiler }
3028
- };
3029
- const rawPlugins = toArray$2(factory(userOptions, meta));
3030
- for (const rawPlugin of rawPlugins) {
3031
- const plugin = Object.assign(rawPlugin, {
3032
- __unpluginMeta: meta,
3033
- __virtualModulePrefix: VIRTUAL_MODULE_PREFIX
3034
- });
3035
- const externalModules = /* @__PURE__ */ new Set();
3036
- if (plugin.resolveId) {
3037
- let vfs = compiler.options.plugins.find((i) => i instanceof VirtualModulesPlugin);
3038
- if (!vfs) {
3039
- vfs = new VirtualModulesPlugin();
3040
- compiler.options.plugins.push(vfs);
3041
- }
3042
- const vfsModules = /* @__PURE__ */ new Set();
3043
- plugin.__vfsModules = vfsModules;
3044
- plugin.__vfs = vfs;
3045
- const resolverPlugin = { apply(resolver) {
3046
- const target = resolver.ensureHook("resolve");
3047
- resolver.getHook("resolve").tapAsync(plugin.name, async (request, resolveContext, callback) => {
3048
- if (!request.request) return callback();
3049
- if (normalizeAbsolutePath(request.request).startsWith(plugin.__virtualModulePrefix)) return callback();
3050
- const id = normalizeAbsolutePath(request.request);
3051
- const requestContext = request.context;
3052
- let importer = requestContext.issuer !== "" ? requestContext.issuer : void 0;
3053
- const isEntry = requestContext.issuer === "";
3054
- if (importer?.startsWith(plugin.__virtualModulePrefix)) importer = decodeURIComponent(importer.slice(plugin.__virtualModulePrefix.length));
3055
- const fileDependencies = /* @__PURE__ */ new Set();
3056
- const context = createBuildContext({
3057
- addWatchFile(file) {
3058
- fileDependencies.add(file);
3059
- resolveContext.fileDependencies?.add(file);
3060
- },
3061
- getWatchFiles() {
3062
- return Array.from(fileDependencies);
3063
- }
3064
- }, compiler);
3065
- let error;
3066
- const pluginContext = {
3067
- error(msg) {
3068
- if (error == null) error = normalizeMessage(msg);
3069
- else console.error(`unplugin/webpack: multiple errors returned from resolveId hook: ${msg}`);
3070
- },
3071
- warn(msg) {
3072
- console.warn(`unplugin/webpack: warning from resolveId hook: ${msg}`);
3073
- }
3074
- };
3075
- const { handler, filter } = normalizeObjectHook("resolveId", plugin.resolveId);
3076
- if (!filter(id)) return callback();
3077
- const resolveIdResult = await handler.call({
3078
- ...context,
3079
- ...pluginContext
3080
- }, id, importer, { isEntry });
3081
- if (error != null) return callback(error);
3082
- if (resolveIdResult == null) return callback();
3083
- let resolved = typeof resolveIdResult === "string" ? resolveIdResult : resolveIdResult.id;
3084
- const isExternal = typeof resolveIdResult === "string" ? false : resolveIdResult.external === true;
3085
- if (isExternal) externalModules.add(resolved);
3086
- if (!fs.existsSync(resolved)) {
3087
- resolved = normalizeAbsolutePath(plugin.__virtualModulePrefix + encodeURIComponent(resolved));
3088
- if (!vfsModules.has(resolved)) {
3089
- plugin.__vfs.writeModule(resolved, "");
3090
- vfsModules.add(resolved);
3091
- }
3092
- }
3093
- const newRequest = {
3094
- ...request,
3095
- request: resolved
3096
- };
3097
- resolver.doResolve(target, newRequest, null, resolveContext, callback);
3098
- });
3099
- } };
3100
- compiler.options.resolve.plugins = compiler.options.resolve.plugins || [];
3101
- compiler.options.resolve.plugins.push(resolverPlugin);
3102
- }
3103
- if (plugin.load) compiler.options.module.rules.unshift({
3104
- include(id) {
3105
- return shouldLoad(id, plugin, externalModules);
3106
- },
3107
- enforce: plugin.enforce,
3108
- use: [{
3109
- loader: LOAD_LOADER,
3110
- options: { plugin }
3111
- }],
3112
- type: "javascript/auto"
3113
- });
3114
- if (plugin.transform) compiler.options.module.rules.unshift({
3115
- enforce: plugin.enforce,
3116
- use(data) {
3117
- return transformUse(data, plugin, TRANSFORM_LOADER);
3118
- }
3119
- });
3120
- if (plugin.webpack) plugin.webpack(compiler);
3121
- if (plugin.watchChange || plugin.buildStart) compiler.hooks.make.tapPromise(plugin.name, async (compilation) => {
3122
- const context = createBuildContext(contextOptionsFromCompilation(compilation), compiler, compilation);
3123
- if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) {
3124
- const promises = [];
3125
- if (compiler.modifiedFiles) compiler.modifiedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "update" }))));
3126
- if (compiler.removedFiles) compiler.removedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "delete" }))));
3127
- await Promise.all(promises);
3128
- }
3129
- if (plugin.buildStart) return await plugin.buildStart.call(context);
3130
- });
3131
- if (plugin.buildEnd) compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => {
3132
- await plugin.buildEnd.call(createBuildContext(contextOptionsFromCompilation(compilation), compiler, compilation));
3133
- });
3134
- if (plugin.writeBundle) compiler.hooks.afterEmit.tapPromise(plugin.name, async () => {
3135
- await plugin.writeBundle();
3136
- });
3137
- }
3138
- } };
3139
- };
3140
- }
3141
- function shouldLoad(id, plugin, externalModules) {
3142
- if (id.startsWith(plugin.__virtualModulePrefix)) id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length));
3143
- if (plugin.loadInclude && !plugin.loadInclude(id)) return false;
3144
- const { filter } = normalizeObjectHook("load", plugin.load);
3145
- if (!filter(id)) return false;
3146
- return !externalModules.has(id);
3147
- }
3148
-
3149
- //#endregion
3150
- //#region src/define.ts
3151
- function createUnplugin(factory) {
3152
- return {
3153
- get esbuild() {
3154
- return getEsbuildPlugin(factory);
3155
- },
3156
- get rollup() {
3157
- return getRollupPlugin(factory);
3158
- },
3159
- get vite() {
3160
- return getVitePlugin(factory);
3161
- },
3162
- get rolldown() {
3163
- return getRolldownPlugin(factory);
3164
- },
3165
- get webpack() {
3166
- return getWebpackPlugin(factory);
3167
- },
3168
- get rspack() {
3169
- return getRspackPlugin(factory);
3170
- },
3171
- get farm() {
3172
- return getFarmPlugin(factory);
3173
- },
3174
- get unloader() {
3175
- return getUnloaderPlugin(factory);
3176
- },
3177
- get raw() {
3178
- return factory;
3179
- }
3180
- };
3181
- }
3182
-
3183
- //#region src/path.ts
3184
- /**
3185
- * Converts path separators to forward slash.
3186
- */
3187
- function normalizePath(filename) {
3188
- return filename.replaceAll("\\", "/");
3189
- }
3190
-
3191
- //#endregion
3192
- //#region src/utils.ts
3193
- const isArray = Array.isArray;
3194
- function toArray$1(thing) {
3195
- if (isArray(thing)) return thing;
3196
- if (thing == null) return [];
3197
- return [thing];
3198
- }
3199
-
3200
- //#endregion
3201
- //#region src/filter.ts
3202
- const escapeMark = "[_#EsCaPe#_]";
3203
- function getMatcherString(id, resolutionBase) {
3204
- if (isAbsolute$3(id) || id.startsWith("**")) return normalizePath(id);
3205
- const basePath = normalizePath(resolve$2("")).replaceAll(/[-^$*+?.()|[\]{}]/g, `${escapeMark}$&`);
3206
- return join(basePath, normalizePath(id)).replaceAll(escapeMark, "\\");
3207
- }
3208
- /**
3209
- * Constructs a filter function which can be used to determine whether or not
3210
- * certain modules should be operated upon.
3211
- * @param include If `include` is omitted or has zero length, filter will return `true` by default.
3212
- * @param exclude ID must not match any of the `exclude` patterns.
3213
- * @param options Additional options.
3214
- * @param options.resolve Optionally resolves the patterns against a directory other than `process.cwd()`.
3215
- * If a `string` is specified, then the value will be used as the base directory.
3216
- * Relative paths will be resolved against `process.cwd()` first.
3217
- * If `false`, then the patterns will not be resolved against any directory.
3218
- * This can be useful if you want to create a filter for virtual module names.
3219
- */
3220
- function createFilter(include, exclude, options) {
3221
- const getMatcher = (id) => id instanceof RegExp ? id : { test: (what) => {
3222
- const pattern = getMatcherString(id);
3223
- return pm(pattern, { dot: true })(what);
3224
- } };
3225
- const includeMatchers = toArray$1(include).map(getMatcher);
3226
- const excludeMatchers = toArray$1(exclude).map(getMatcher);
3227
- if (!includeMatchers.length && !excludeMatchers.length) return (id) => typeof id === "string" && !id.includes("\0");
3228
- return function result(id) {
3229
- if (typeof id !== "string") return false;
3230
- if (id.includes("\0")) return false;
3231
- const pathId = normalizePath(id);
3232
- for (const matcher of excludeMatchers) {
3233
- if (matcher instanceof RegExp) matcher.lastIndex = 0;
3234
- if (matcher.test(pathId)) return false;
3235
- }
3236
- for (const matcher of includeMatchers) {
3237
- if (matcher instanceof RegExp) matcher.lastIndex = 0;
3238
- if (matcher.test(pathId)) return true;
3239
- }
3240
- return !includeMatchers.length;
3241
- };
3242
- }
3243
-
3244
- const defaultIncludes = [/\.[jt]sx?$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/];
3245
- const defaultExcludes = [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/];
3246
- function toArray(x) {
3247
- return x == null ? [] : Array.isArray(x) ? x : [x];
3248
- }
3249
- const unplugin$1 = createUnplugin((options = {}) => {
3250
- const ctx = createUnimport(options);
3251
- const filter = createFilter(
3252
- toArray(options.include || []).length ? options.include : defaultIncludes,
3253
- options.exclude || defaultExcludes
3254
- );
3255
- const dts = options.dts === true ? "unimport.d.ts" : options.dts;
3256
- const {
3257
- autoImport = true
3258
- } = options;
3259
- return {
3260
- name: "unimport",
3261
- enforce: "post",
3262
- transformInclude(id) {
3263
- return filter(id);
3264
- },
3265
- async transform(code, id) {
3266
- const s = new MagicString(code);
3267
- await ctx.injectImports(s, id, {
3268
- autoImport
3269
- });
3270
- if (!s.hasChanged())
3271
- return;
3272
- return {
3273
- code: s.toString(),
3274
- map: s.generateMap()
3275
- };
3276
- },
3277
- async buildStart() {
3278
- await ctx.init();
3279
- if (dts)
3280
- return promises.writeFile(dts, await ctx.generateTypeDeclarations(), "utf-8");
3281
- }
3282
- };
3283
- });
5
+ import { a as genSafeVariableName, g as genImport, c as genString, d as genObjectFromRaw } from './knitwork.mjs';
6
+ import { c as basename } from './pathe.mjs';
3284
7
 
3285
8
  var __create = Object.create;
3286
9
  var __defProp = Object.defineProperty;
@@ -9892,7 +6615,7 @@ async function getWasmImports(asset, _opts) {
9892
6615
  resolved: true
9893
6616
  };
9894
6617
  }
9895
- const { readPackageJSON } = await import('./index.mjs').then(function (n) { return n.X; });
6618
+ const { readPackageJSON } = await import('./pkg-types.mjs').then(function (n) { return n.i; });
9896
6619
  const pkgJSON = await readPackageJSON(asset.id);
9897
6620
  let resolved = true;
9898
6621
  const imports = [];
@@ -10170,7 +6893,7 @@ const unplugin = createUnplugin((opts) => {
10170
6893
  }
10171
6894
  const buff = Buffer.from(code, "binary");
10172
6895
  const isModule = id.endsWith("?module");
10173
- const name = `wasm/${basename$1(id.split("?")[0], ".wasm")}-${sha1(buff)}.wasm`;
6896
+ const name = `wasm/${basename(id.split("?")[0], ".wasm")}-${sha1(buff)}.wasm`;
10174
6897
  const parsed = isModule ? { imports: [], exports: ["default"] } : parse(name, buff);
10175
6898
  const asset = assets[name] = {
10176
6899
  name,
@@ -10233,841 +6956,4 @@ const unplugin = createUnplugin((opts) => {
10233
6956
  });
10234
6957
  const rollup = unplugin.rollup;
10235
6958
 
10236
- const PREFIX = "\0virtual:";
10237
- function virtual(modules, cache = {}) {
10238
- const _modules = /* @__PURE__ */ new Map();
10239
- for (const [id, mod] of Object.entries(modules)) {
10240
- cache[id] = mod;
10241
- _modules.set(id, mod);
10242
- _modules.set(resolve$2(id), mod);
10243
- }
10244
- return {
10245
- name: "virtual",
10246
- resolveId(id, importer) {
10247
- if (id in modules) {
10248
- return PREFIX + id;
10249
- }
10250
- if (importer) {
10251
- const importerNoPrefix = importer.startsWith(PREFIX) ? importer.slice(PREFIX.length) : importer;
10252
- const resolved = resolve$2(dirname$1(importerNoPrefix), id);
10253
- if (_modules.has(resolved)) {
10254
- return PREFIX + resolved;
10255
- }
10256
- }
10257
- return null;
10258
- },
10259
- async load(id) {
10260
- if (!id.startsWith(PREFIX)) {
10261
- return null;
10262
- }
10263
- const idNoPrefix = id.slice(PREFIX.length);
10264
- if (!_modules.has(idNoPrefix)) {
10265
- return null;
10266
- }
10267
- let m = _modules.get(idNoPrefix);
10268
- if (typeof m === "function") {
10269
- m = await m();
10270
- }
10271
- if (!m) {
10272
- return null;
10273
- }
10274
- cache[id.replace(PREFIX, "")] = m;
10275
- return {
10276
- code: m,
10277
- map: null
10278
- };
10279
- }
10280
- };
10281
- }
10282
-
10283
- function database(nitro) {
10284
- if (!nitro.options.experimental.database) {
10285
- return virtual(
10286
- {
10287
- "#nitro-internal-virtual/database": () => {
10288
- return (
10289
- /* js */
10290
- `export const connectionConfigs = {};`
10291
- );
10292
- }
10293
- },
10294
- nitro.vfs
10295
- );
10296
- }
10297
- const dbConfigs = nitro.options.dev && nitro.options.devDatabase || nitro.options.database;
10298
- const connectorsNames = [
10299
- ...new Set(
10300
- Object.values(dbConfigs || {}).map((config) => config?.connector)
10301
- )
10302
- ].filter(Boolean);
10303
- for (const name of connectorsNames) {
10304
- if (!connectors[name]) {
10305
- throw new Error(`Database connector "${name}" is invalid.`);
10306
- }
10307
- }
10308
- return virtual(
10309
- {
10310
- "#nitro-internal-virtual/database": () => {
10311
- return `
10312
- ${connectorsNames.map(
10313
- (name) => `import ${camelCase(name)}Connector from "${connectors[name]}";`
10314
- ).join("\n")}
10315
-
10316
- export const connectionConfigs = {
10317
- ${Object.entries(dbConfigs || {}).map(
10318
- ([name, { connector, options }]) => `${name}: {
10319
- connector: ${camelCase(connector)}Connector,
10320
- options: ${JSON.stringify(options)}
10321
- }`
10322
- ).join(",\n")}
10323
- };
10324
- `;
10325
- }
10326
- },
10327
- nitro.vfs
10328
- );
10329
- }
10330
-
10331
- const RuntimeRouteRules = [
10332
- "headers",
10333
- "redirect",
10334
- "proxy",
10335
- "cache"
10336
- ];
10337
- function routing(nitro) {
10338
- return virtual(
10339
- {
10340
- // --- routing (routes, routeRules and middleware) ---
10341
- "#nitro-internal-virtual/routing": () => {
10342
- const allHandlers = uniqueBy(
10343
- [
10344
- ...Object.values(nitro.routing.routes.routes).map((h) => h.data),
10345
- ...Object.values(nitro.routing.routedMiddleware.routes).map(
10346
- (h) => h.data
10347
- ),
10348
- ...nitro.routing.globalMiddleware
10349
- ],
10350
- "_importHash"
10351
- );
10352
- const h3Imports = [
10353
- allHandlers.some((h) => !h.lazy) && "toEventHandler",
10354
- nitro.options.serverEntry && "toMiddleware",
10355
- allHandlers.some((h) => h.lazy) && "defineLazyEventHandler"
10356
- ].filter(Boolean);
10357
- return (
10358
- /* js */
10359
- `
10360
- import * as __routeRules__ from "nitro/runtime/internal/route-rules";
10361
- ${nitro.options.serverEntry ? `import __serverEntry__ from ${JSON.stringify(nitro.options.serverEntry)};` : ""}
10362
- import {${h3Imports.join(", ")}} from "nitro/deps/h3";
10363
-
10364
- export const hasRouteRules = ${nitro.routing.routeRules.hasRoutes() ? "true" : "false"};
10365
- export const findRouteRules = ${nitro.routing.routeRules.compileToString({ serialize: serializeRouteRule, matchAll: true })}
10366
-
10367
- ${allHandlers.filter((h) => !h.lazy).map((h) => (
10368
- /* js */
10369
- `import ${h._importHash} from "${h.handler}";`
10370
- )).join("\n")}
10371
-
10372
- ${allHandlers.filter((h) => h.lazy).map(
10373
- (h) => (
10374
- /* js */
10375
- `const ${h._importHash} = defineLazyEventHandler(() => import("${h.handler}"));`
10376
- )
10377
- ).join("\n")}
10378
-
10379
- export const hasRoutes = ${nitro.routing.routes.hasRoutes() ? "true" : "false"};
10380
- export const findRoute = ${nitro.routing.routes.compileToString({ serialize: serializeHandler })}
10381
-
10382
- export const hasRoutedMiddleware = ${nitro.routing.routedMiddleware.hasRoutes() ? "true" : "false"};
10383
- export const findRoutedMiddleware = ${nitro.routing.routedMiddleware.compileToString({ serialize: serializeHandler, matchAll: true })};
10384
-
10385
- export const hasGlobalMiddleware = ${nitro.routing.globalMiddleware.length > 0 || nitro.options.serverEntry ? "true" : "false"};
10386
- export const globalMiddleware = [
10387
- ${nitro.routing.globalMiddleware.map((h) => h.lazy ? h._importHash : `toEventHandler(${h._importHash})`).join(",")}
10388
- ${nitro.options.serverEntry ? `,toMiddleware(__serverEntry__)` : ""}
10389
- ].filter(Boolean);
10390
- `
10391
- );
10392
- },
10393
- // --- routing-meta ---
10394
- "#nitro-internal-virtual/routing-meta": () => {
10395
- const routeHandlers = uniqueBy(
10396
- Object.values(nitro.routing.routes.routes).map((h) => h.data),
10397
- "_importHash"
10398
- );
10399
- return (
10400
- /* js */
10401
- `
10402
- ${routeHandlers.map(
10403
- (h) => (
10404
- /* js */
10405
- `import ${h._importHash}Meta from "${h.handler}?meta";`
10406
- )
10407
- ).join("\n")}
10408
- export const handlersMeta = [
10409
- ${routeHandlers.map(
10410
- (h) => (
10411
- /* js */
10412
- `{ route: ${JSON.stringify(h.route)}, method: ${JSON.stringify(
10413
- h.method?.toLowerCase()
10414
- )}, meta: ${h._importHash}Meta }`
10415
- )
10416
- ).join(",\n")}
10417
- ];
10418
- `.trim()
10419
- );
10420
- }
10421
- },
10422
- nitro.vfs
10423
- );
10424
- }
10425
- function uniqueBy(arr, key) {
10426
- return [...new Map(arr.map((item) => [item[key], item])).values()];
10427
- }
10428
- function serializeHandler(h) {
10429
- return `{${[
10430
- `route:${JSON.stringify(h.route)}`,
10431
- h.method && `method:${JSON.stringify(h.method)}`,
10432
- h.meta && `meta:${JSON.stringify(h.meta)}`,
10433
- `handler:${h.lazy ? h._importHash : `toEventHandler(${h._importHash})`}`
10434
- ].filter(Boolean).join(",")}}`;
10435
- }
10436
- function serializeRouteRule(h) {
10437
- return `[${Object.entries(h).filter(([name, options]) => options !== void 0 && name[0] !== "_").map(([name, options]) => {
10438
- return `{${[
10439
- `name:${JSON.stringify(name)}`,
10440
- `route:${JSON.stringify(h._route)}`,
10441
- h._method && `method:${JSON.stringify(h._method)}`,
10442
- RuntimeRouteRules.includes(name) && `handler:__routeRules__.${name}`,
10443
- `options:${JSON.stringify(options)}`
10444
- ].filter(Boolean).join(",")}}`;
10445
- }).join(",")}]`;
10446
- }
10447
-
10448
- const virtualPrefix = "\0nitro-handler-meta:";
10449
- const esbuildLoaders = {
10450
- ".ts": "ts",
10451
- ".js": "js",
10452
- ".tsx": "tsx",
10453
- ".jsx": "jsx"
10454
- };
10455
- function routeMeta(nitro) {
10456
- return {
10457
- name: "nitro:route-meta",
10458
- async resolveId(id, importer, resolveOpts) {
10459
- if (id.startsWith("\0")) {
10460
- return;
10461
- }
10462
- if (id.endsWith(`?meta`)) {
10463
- const resolved = await this.resolve(
10464
- id.replace(`?meta`, ``),
10465
- importer,
10466
- resolveOpts
10467
- );
10468
- if (!resolved) {
10469
- return;
10470
- }
10471
- return virtualPrefix + resolved.id;
10472
- }
10473
- },
10474
- load(id) {
10475
- if (id.startsWith(virtualPrefix)) {
10476
- const fullPath = id.slice(virtualPrefix.length);
10477
- return readFile(fullPath, { encoding: "utf8" });
10478
- }
10479
- },
10480
- async transform(code, id) {
10481
- if (!id.startsWith(virtualPrefix)) {
10482
- return;
10483
- }
10484
- let meta = null;
10485
- try {
10486
- const ext = extname$1(id);
10487
- const jsCode = await transform(code, {
10488
- loader: esbuildLoaders[ext]
10489
- }).then((r) => r.code);
10490
- const ast = this.parse(jsCode);
10491
- for (const node of ast.body) {
10492
- if (node.type === "ExpressionStatement" && node.expression.type === "CallExpression" && node.expression.callee.type === "Identifier" && node.expression.callee.name === "defineRouteMeta" && node.expression.arguments.length === 1) {
10493
- meta = astToObject(node.expression.arguments[0]);
10494
- break;
10495
- }
10496
- }
10497
- } catch (error) {
10498
- nitro.logger.warn(
10499
- `[handlers-meta] Cannot extra route meta for: ${id}: ${error}`
10500
- );
10501
- }
10502
- return {
10503
- code: `export default ${JSON.stringify(meta)};`,
10504
- map: null
10505
- };
10506
- }
10507
- };
10508
- }
10509
- function astToObject(node) {
10510
- switch (node.type) {
10511
- case "ObjectExpression": {
10512
- const obj = {};
10513
- for (const prop of node.properties) {
10514
- if (prop.type === "Property") {
10515
- const key = prop.key.name ?? prop.key.value;
10516
- obj[key] = astToObject(prop.value);
10517
- }
10518
- }
10519
- return obj;
10520
- }
10521
- case "ArrayExpression": {
10522
- return node.elements.map((el) => astToObject(el)).filter(Boolean);
10523
- }
10524
- case "Literal": {
10525
- return node.value;
10526
- }
10527
- }
10528
- }
10529
-
10530
- function serverMain(nitro) {
10531
- return {
10532
- name: "nitro:server-main",
10533
- renderChunk(code, chunk) {
10534
- if (chunk.isEntry) {
10535
- return {
10536
- code: `globalThis.__nitro_main__ = import.meta.url; ${code}`,
10537
- map: null
10538
- };
10539
- }
10540
- }
10541
- };
10542
- }
10543
-
10544
- var etagExports = requireEtag();
10545
- const createEtag = /*@__PURE__*/getDefaultExportFromCjs(etagExports);
10546
-
10547
- const readAssetHandler = {
10548
- true: "node",
10549
- node: "node",
10550
- false: "null",
10551
- deno: "deno",
10552
- inline: "inline"
10553
- };
10554
- function publicAssets(nitro) {
10555
- return virtual(
10556
- {
10557
- // #nitro-internal-virtual/public-assets-data
10558
- "#nitro-internal-virtual/public-assets-data": async () => {
10559
- const assets = {};
10560
- const files = await glob("**", {
10561
- cwd: nitro.options.output.publicDir,
10562
- absolute: false,
10563
- dot: true
10564
- });
10565
- for (const id of files) {
10566
- let mimeType = mime.getType(id.replace(/\.(gz|br)$/, "")) || "text/plain";
10567
- if (mimeType.startsWith("text")) {
10568
- mimeType += "; charset=utf-8";
10569
- }
10570
- const fullPath = resolve$2(nitro.options.output.publicDir, id);
10571
- const assetData = await promises.readFile(fullPath);
10572
- const etag = createEtag(assetData);
10573
- const stat = await promises.stat(fullPath);
10574
- const assetId = "/" + decodeURIComponent(id);
10575
- let encoding;
10576
- if (id.endsWith(".gz")) {
10577
- encoding = "gzip";
10578
- } else if (id.endsWith(".br")) {
10579
- encoding = "br";
10580
- }
10581
- assets[assetId] = {
10582
- type: nitro._prerenderMeta?.[assetId]?.contentType || mimeType,
10583
- encoding,
10584
- etag,
10585
- mtime: stat.mtime.toJSON(),
10586
- size: stat.size,
10587
- path: relative(nitro.options.output.serverDir, fullPath),
10588
- data: nitro.options.serveStatic === "inline" ? assetData.toString("base64") : void 0
10589
- };
10590
- }
10591
- return `export default ${JSON.stringify(assets, null, 2)};`;
10592
- },
10593
- // #nitro-internal-virtual/public-assets-node
10594
- "#nitro-internal-virtual/public-assets-node": () => {
10595
- return `
10596
- import { promises as fsp } from 'node:fs'
10597
- import { fileURLToPath } from 'node:url'
10598
- import { resolve, dirname } from 'node:path'
10599
- import assets from '#nitro-internal-virtual/public-assets-data'
10600
- export function readAsset (id) {
10601
- const serverDir = dirname(fileURLToPath(globalThis.__nitro_main__))
10602
- return fsp.readFile(resolve(serverDir, assets[id].path))
10603
- }`;
10604
- },
10605
- // #nitro-internal-virtual/public-assets-deno
10606
- "#nitro-internal-virtual/public-assets-deno": () => {
10607
- return `
10608
- import assets from '#nitro-internal-virtual/public-assets-data'
10609
- export function readAsset (id) {
10610
- // https://deno.com/deploy/docs/serve-static-assets
10611
- const path = '.' + decodeURIComponent(new URL(\`../public\${id}\`, 'file://').pathname)
10612
- return Deno.readFile(path);
10613
- }`;
10614
- },
10615
- // #nitro-internal-virtual/public-assets-null
10616
- "#nitro-internal-virtual/public-assets-null": () => {
10617
- return `
10618
- export function readAsset (id) {
10619
- return Promise.resolve(null);
10620
- }`;
10621
- },
10622
- // #nitro-internal-virtual/public-assets-inline
10623
- "#nitro-internal-virtual/public-assets-inline": () => {
10624
- return `
10625
- import assets from '#nitro-internal-virtual/public-assets-data'
10626
- export function readAsset (id) {
10627
- if (!assets[id]) { return undefined }
10628
- if (assets[id]._data) { return assets[id]._data }
10629
- if (!assets[id].data) { return assets[id].data }
10630
- assets[id]._data = Uint8Array.from(atob(assets[id].data), (c) => c.charCodeAt(0))
10631
- return assets[id]._data
10632
- }`;
10633
- },
10634
- // #nitro-internal-virtual/public-assets
10635
- "#nitro-internal-virtual/public-assets": () => {
10636
- const publicAssetBases = Object.fromEntries(
10637
- nitro.options.publicAssets.filter((dir) => !dir.fallthrough && dir.baseURL !== "/").map((dir) => [
10638
- withTrailingSlash(dir.baseURL),
10639
- { maxAge: dir.maxAge }
10640
- ])
10641
- );
10642
- const handlerName = readAssetHandler[nitro.options.serveStatic] || "null";
10643
- const readAssetImport = `#nitro-internal-virtual/public-assets-${handlerName}`;
10644
- return `
10645
- import assets from '#nitro-internal-virtual/public-assets-data'
10646
- export { readAsset } from "${readAssetImport}"
10647
- export const publicAssetBases = ${JSON.stringify(publicAssetBases)}
10648
-
10649
- export function isPublicAssetURL(id = '') {
10650
- if (assets[id]) {
10651
- return true
10652
- }
10653
- for (const base in publicAssetBases) {
10654
- if (id.startsWith(base)) { return true }
10655
- }
10656
- return false
10657
- }
10658
-
10659
- export function getPublicAssetMeta(id = '') {
10660
- for (const base in publicAssetBases) {
10661
- if (id.startsWith(base)) { return publicAssetBases[base] }
10662
- }
10663
- return {}
10664
- }
10665
-
10666
- export function getAsset (id) {
10667
- return assets[id]
10668
- }
10669
- `;
10670
- }
10671
- },
10672
- nitro.vfs
10673
- );
10674
- }
10675
-
10676
- function serverAssets(nitro) {
10677
- if (nitro.options.dev || nitro.options.preset === "nitro-prerender") {
10678
- return virtual(
10679
- { "#nitro-internal-virtual/server-assets": getAssetsDev(nitro) },
10680
- nitro.vfs
10681
- );
10682
- }
10683
- return virtual(
10684
- {
10685
- "#nitro-internal-virtual/server-assets": async () => {
10686
- const assets = {};
10687
- for (const asset of nitro.options.serverAssets) {
10688
- const files = await glob(asset.pattern || "**/*", {
10689
- cwd: asset.dir,
10690
- absolute: false,
10691
- ignore: asset.ignore
10692
- });
10693
- for (const _id of files) {
10694
- const fsPath = resolve$2(asset.dir, _id);
10695
- const id = asset.baseName + "/" + _id;
10696
- assets[id] = { fsPath, meta: {} };
10697
- let type = mime.getType(id) || "text/plain";
10698
- if (type.startsWith("text")) {
10699
- type += "; charset=utf-8";
10700
- }
10701
- const etag = createEtag(await promises.readFile(fsPath));
10702
- const mtime = await promises.stat(fsPath).then((s) => s.mtime.toJSON());
10703
- assets[id].meta = { type, etag, mtime };
10704
- }
10705
- }
10706
- return getAssetProd(assets);
10707
- }
10708
- },
10709
- nitro.vfs
10710
- );
10711
- }
10712
- function getAssetsDev(nitro) {
10713
- return `
10714
- import { createStorage } from 'unstorage'
10715
- import fsDriver from 'unstorage/drivers/fs'
10716
-
10717
- const serverAssets = ${JSON.stringify(nitro.options.serverAssets)}
10718
-
10719
- export const assets = createStorage()
10720
-
10721
- for (const asset of serverAssets) {
10722
- assets.mount(asset.baseName, fsDriver({ base: asset.dir, ignore: (asset?.ignore || []) }))
10723
- }`;
10724
- }
10725
- function getAssetProd(assets) {
10726
- return `
10727
- const _assets = {
10728
- ${Object.entries(assets).map(
10729
- ([id, asset]) => ` [${JSON.stringify(
10730
- normalizeKey(id)
10731
- )}]: {
10732
- import: () => import(${JSON.stringify(
10733
- "raw:" + asset.fsPath
10734
- )}).then(r => r.default || r),
10735
- meta: ${JSON.stringify(
10736
- asset.meta
10737
- )}
10738
- }`
10739
- ).join(",\n")}
10740
- }
10741
-
10742
- const normalizeKey = ${normalizeKey.toString()}
10743
-
10744
- export const assets = {
10745
- getKeys() {
10746
- return Promise.resolve(Object.keys(_assets))
10747
- },
10748
- hasItem (id) {
10749
- id = normalizeKey(id)
10750
- return Promise.resolve(id in _assets)
10751
- },
10752
- getItem (id) {
10753
- id = normalizeKey(id)
10754
- return Promise.resolve(_assets[id] ? _assets[id].import() : null)
10755
- },
10756
- getMeta (id) {
10757
- id = normalizeKey(id)
10758
- return Promise.resolve(_assets[id] ? _assets[id].meta : {})
10759
- }
10760
- }
10761
- `;
10762
- }
10763
-
10764
- function storage(nitro) {
10765
- const mounts = [];
10766
- const isDevOrPrerender = nitro.options.dev || nitro.options.preset === "nitro-prerender";
10767
- const storageMounts = isDevOrPrerender ? { ...nitro.options.storage, ...nitro.options.devStorage } : nitro.options.storage;
10768
- for (const path in storageMounts) {
10769
- const mount = storageMounts[path];
10770
- mounts.push({
10771
- path,
10772
- driver: builtinDrivers[mount.driver] || mount.driver,
10773
- opts: mount
10774
- });
10775
- }
10776
- const driverImports = [...new Set(mounts.map((m) => m.driver))];
10777
- const bundledStorageCode = `
10778
- import { prefixStorage } from 'unstorage'
10779
- import overlay from 'unstorage/drivers/overlay'
10780
- import memory from 'unstorage/drivers/memory'
10781
-
10782
- const bundledStorage = ${JSON.stringify(nitro.options.bundledStorage)}
10783
- for (const base of bundledStorage) {
10784
- storage.mount(base, overlay({
10785
- layers: [
10786
- memory(),
10787
- // TODO
10788
- // prefixStorage(storage, base),
10789
- prefixStorage(storage, 'assets:nitro:bundled:' + base)
10790
- ]
10791
- }))
10792
- }`;
10793
- return virtual(
10794
- {
10795
- "#nitro-internal-virtual/storage": (
10796
- /* js */
10797
- `
10798
- import { createStorage } from 'unstorage'
10799
- import { assets } from '#nitro-internal-virtual/server-assets'
10800
-
10801
- ${driverImports.map((i) => genImport(i, genSafeVariableName(i))).join("\n")}
10802
-
10803
- export function initStorage() {
10804
- const storage = createStorage({})
10805
- storage.mount('/assets', assets)
10806
- ${mounts.map(
10807
- (m) => `storage.mount('${m.path}', ${genSafeVariableName(
10808
- m.driver
10809
- )}(${JSON.stringify(m.opts)}))`
10810
- ).join("\n")}
10811
-
10812
- ${!isDevOrPrerender && nitro.options.bundledStorage.length > 0 ? bundledStorageCode : ""}
10813
- return storage
10814
- }
10815
- `
10816
- )
10817
- },
10818
- nitro.vfs
10819
- );
10820
- }
10821
-
10822
- function errorHandler(nitro) {
10823
- return virtual(
10824
- {
10825
- "#nitro-internal-virtual/error-handler": () => {
10826
- const errorHandlers = Array.isArray(nitro.options.errorHandler) ? nitro.options.errorHandler : [nitro.options.errorHandler];
10827
- const builtinHandler = join(
10828
- runtimeDir,
10829
- `internal/error/${nitro.options.dev ? "dev" : "prod"}`
10830
- );
10831
- return (
10832
- /* js */
10833
- `
10834
- ${errorHandlers.map((h, i) => `import errorHandler$${i} from "${h}";`).join("\n")}
10835
-
10836
- const errorHandlers = [${errorHandlers.map((_, i) => `errorHandler$${i}`).join(", ")}];
10837
-
10838
- import { defaultHandler } from "${builtinHandler}";
10839
-
10840
- export default async function(error, event) {
10841
- for (const handler of errorHandlers) {
10842
- try {
10843
- const response = await handler(error, event, { defaultHandler });
10844
- if (response) {
10845
- return response;
10846
- }
10847
- } catch(error) {
10848
- // Handler itself thrown, log and continue
10849
- console.error(error);
10850
- }
10851
- }
10852
- // H3 will handle fallback
10853
- }
10854
- `
10855
- );
10856
- }
10857
- },
10858
- nitro.vfs
10859
- );
10860
- }
10861
-
10862
- function rendererTemplate(nitro) {
10863
- return virtual(
10864
- {
10865
- "#nitro-internal-virtual/renderer-template": async () => {
10866
- if (typeof nitro.options.renderer?.template !== "string") {
10867
- return `export const rendererTemplate = () => '<!-- renderer.template is not set -->'; export const rendererTemplateFile = undefined;`;
10868
- }
10869
- if (nitro.options.dev) {
10870
- return `import { readFile } from 'node:fs/promises';export const rendererTemplate = () => readFile(${JSON.stringify(nitro.options.renderer?.template)}, "utf8"); export const rendererTemplateFile = ${JSON.stringify(
10871
- nitro.options.renderer?.template
10872
- )};`;
10873
- } else {
10874
- const html = await readFile(nitro.options.renderer?.template, "utf8");
10875
- if (hasTemplateSyntax(html)) {
10876
- const template = compileTemplateToString(html, {
10877
- contextKeys: [...RENDER_CONTEXT_KEYS]
10878
- });
10879
- return (
10880
- /* js */
10881
- `
10882
- import { renderToResponse } from 'rendu'
10883
- const template = ${template};
10884
- export const rendererTemplate = (request) => renderToResponse(template, { request })
10885
- `
10886
- );
10887
- } else {
10888
- return (
10889
- /* js */
10890
- `
10891
- import { HTTPResponse } from "nitro/deps/h3";
10892
- export const rendererTemplate = () => new HTTPResponse(${JSON.stringify(html)}, { headers: { "content-type": "text/html; charset=utf-8" } });
10893
- `
10894
- );
10895
- }
10896
- }
10897
- }
10898
- },
10899
- nitro.vfs
10900
- );
10901
- }
10902
-
10903
- function baseBuildPlugins(nitro, base) {
10904
- const plugins = [];
10905
- if (nitro.options.imports) {
10906
- plugins.push(unplugin$1.rollup(nitro.options.imports));
10907
- }
10908
- if (nitro.options.experimental.wasm) {
10909
- plugins.push(rollup(nitro.options.wasm || {}));
10910
- }
10911
- plugins.push(serverMain());
10912
- const nitroPlugins = [...new Set(nitro.options.plugins)];
10913
- plugins.push(
10914
- virtual(
10915
- {
10916
- "#nitro-internal-virtual/plugins": (
10917
- /* js */
10918
- `
10919
- ${nitroPlugins.map(
10920
- (plugin) => `import _${hash(plugin).replace(/-/g, "")} from '${plugin}';`
10921
- ).join("\n")}
10922
-
10923
- export const plugins = [
10924
- ${nitroPlugins.map((plugin) => `_${hash(plugin).replace(/-/g, "")}`).join(",\n")}
10925
- ]
10926
- `
10927
- )
10928
- },
10929
- nitro.vfs
10930
- )
10931
- );
10932
- plugins.push(serverAssets(nitro));
10933
- plugins.push(publicAssets(nitro));
10934
- plugins.push(storage(nitro));
10935
- plugins.push(database(nitro));
10936
- plugins.push(routing(nitro));
10937
- if (nitro.options.experimental.openAPI) {
10938
- plugins.push(routeMeta(nitro));
10939
- }
10940
- plugins.push(errorHandler(nitro));
10941
- plugins.push(
10942
- virtual(
10943
- {
10944
- "#nitro-internal-pollyfills": base.env.polyfill.map((p) => (
10945
- /* js */
10946
- `import '${p}';`
10947
- )).join("\n") || /* js */
10948
- `/* No polyfills */`
10949
- },
10950
- nitro.vfs
10951
- )
10952
- );
10953
- plugins.push(virtual(nitro.options.virtual, nitro.vfs));
10954
- if (nitro.options.renderer?.template) {
10955
- plugins.push(rendererTemplate(nitro));
10956
- }
10957
- if (nitro.options.noExternals) {
10958
- plugins.push({
10959
- name: "no-externals",
10960
- async resolveId(id, importer, resolveOpts) {
10961
- if (resolveOpts.custom?.skipNoExternals) {
10962
- return;
10963
- }
10964
- id = base.aliases[id] || id;
10965
- if (base.env.external.includes(id) || nitro.options.node && (id.startsWith("node:") || builtinModules.includes(id))) {
10966
- return { id, external: true };
10967
- }
10968
- const resolved = await this.resolve(id, importer, resolveOpts);
10969
- if (!resolved) {
10970
- const _resolved = resolveModulePath(id, {
10971
- try: true,
10972
- from: importer && isAbsolute$3(importer) ? [pathToFileURL(importer), ...nitro.options.nodeModulesDirs] : nitro.options.nodeModulesDirs,
10973
- suffixes: ["", "/index"],
10974
- extensions: [".mjs", ".cjs", ".js", ".mts", ".cts", ".ts", ".json"],
10975
- conditions: [
10976
- "default",
10977
- nitro.options.dev ? "development" : "production",
10978
- "node",
10979
- "import",
10980
- "require"
10981
- ]
10982
- });
10983
- if (_resolved) {
10984
- return { id: _resolved, external: false };
10985
- }
10986
- }
10987
- if (!resolved || resolved.external && !id.endsWith(".wasm")) {
10988
- throw new Error(
10989
- `Cannot resolve ${JSON.stringify(id)} from ${JSON.stringify(
10990
- importer
10991
- )} and externals are not allowed!`
10992
- );
10993
- }
10994
- }
10995
- });
10996
- } else if (!nitro.options.dev) {
10997
- plugins.push(
10998
- rollupNodeFileTrace(
10999
- defu(nitro.options.externals, {
11000
- outDir: nitro.options.output.serverDir,
11001
- moduleDirectories: nitro.options.nodeModulesDirs,
11002
- external: [
11003
- ...nitro.options.dev ? [nitro.options.buildDir] : [],
11004
- ...nitro.options.nodeModulesDirs
11005
- ],
11006
- inline: [
11007
- "#",
11008
- "~",
11009
- "@/",
11010
- "~~",
11011
- "@@/",
11012
- "virtual:",
11013
- "nitro/runtime",
11014
- "nitro/runtime",
11015
- dirname$1(nitro.options.entry),
11016
- ...nitro.options.experimental.wasm ? [(id) => id?.endsWith(".wasm")] : [],
11017
- runtimeDir,
11018
- nitro.options.srcDir,
11019
- ...nitro.options.handlers.map((m) => m.handler).filter((i) => typeof i === "string"),
11020
- ...nitro.options.dev || nitro.options.preset === "nitro-prerender" || nitro.options.experimental.bundleRuntimeDependencies === false ? [] : runtimeDependencies
11021
- ],
11022
- traceOptions: {
11023
- base: "/",
11024
- processCwd: nitro.options.rootDir,
11025
- exportsOnly: true
11026
- },
11027
- traceAlias: {
11028
- "h3-nightly": "h3",
11029
- ...nitro.options.externals?.traceAlias
11030
- },
11031
- exportConditions: nitro.options.exportConditions,
11032
- writePackageJson: true
11033
- })
11034
- )
11035
- );
11036
- }
11037
- return plugins;
11038
- }
11039
-
11040
- const presetsWithConfig = ["awsAmplify", "awsLambda", "azure", "cloudflare", "firebase", "netlify", "vercel"];
11041
-
11042
- async function writeBuildInfo(nitro) {
11043
- const buildInfoPath = resolve$2(nitro.options.output.dir, "nitro.json");
11044
- const buildInfo = {
11045
- date: (/* @__PURE__ */ new Date()).toJSON(),
11046
- preset: nitro.options.preset,
11047
- framework: nitro.options.framework,
11048
- versions: {
11049
- nitro: version
11050
- },
11051
- commands: {
11052
- preview: nitro.options.commands.preview,
11053
- deploy: nitro.options.commands.deploy
11054
- },
11055
- config: {
11056
- ...Object.fromEntries(
11057
- presetsWithConfig.map((key) => [key, nitro.options[key]])
11058
- )
11059
- }
11060
- };
11061
- await writeFile(buildInfoPath, JSON.stringify(buildInfo, null, 2), true);
11062
- const lastBuild = resolve$2(
11063
- nitro.options.rootDir,
11064
- "node_modules/.nitro/last-build"
11065
- );
11066
- await mkdir(dirname(lastBuild), { recursive: true });
11067
- await unlink(lastBuild).catch(() => {
11068
- });
11069
- await symlink(nitro.options.output.dir, lastBuild).catch(console.warn);
11070
- return buildInfo;
11071
- }
11072
-
11073
- export { attachScopes as a, baseBuildConfig as b, createFilter$2 as c, baseBuildPlugins as d, writeBuildInfo as e, extractAssignedNames as f, dataToEsm as g, createFilter as h, makeLegalIdentifier as m, replace as r, walk as w };
6959
+ export { rollup as r };