@gytx/unplugin 3.1.0-patch.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1254 @@
1
+ import { a as toArray, i as normalizeObjectHook, n as setParseImpl, r as createBuildContextFs, t as parse } from "./parse-C8UGVJ_5.mjs";
2
+ import { n as transformUse, t as normalizeAbsolutePath } from "./webpack-like-m4jN95Ew.mjs";
3
+ import { r as normalizeMessage$1, t as createBuildContext$2 } from "./context-cZ84xoAB.mjs";
4
+ import { i as isVirtualModuleId, n as decodeVirtualModuleId, r as encodeVirtualModuleId, t as FakeVirtualModulesPlugin } from "./utils-DjVnpaM4.mjs";
5
+ import { i as normalizeMessage$2, n as createBuildContext$3, t as contextOptionsFromCompilation } from "./context-Dv7UHMCI.mjs";
6
+ import { createRequire } from "node:module";
7
+ import path, { extname, isAbsolute, resolve } from "node:path";
8
+ import fs from "node:fs";
9
+ import { Buffer as Buffer$1 } from "node:buffer";
10
+ import remapping from "@jridgewell/remapping";
11
+ import * as querystring from "node:querystring";
12
+ import process$1 from "node:process";
13
+ //#region \0rolldown/runtime.js
14
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
15
+ //#endregion
16
+ //#region package.json
17
+ var version$1 = "3.1.0-patch.1";
18
+ //#endregion
19
+ //#region src/bun/utils.ts
20
+ const ExtToLoader$1 = {
21
+ ".js": "js",
22
+ ".mjs": "js",
23
+ ".cjs": "js",
24
+ ".jsx": "jsx",
25
+ ".ts": "ts",
26
+ ".cts": "ts",
27
+ ".mts": "ts",
28
+ ".tsx": "tsx",
29
+ ".css": "css",
30
+ ".less": "css",
31
+ ".stylus": "css",
32
+ ".scss": "css",
33
+ ".sass": "css",
34
+ ".json": "json",
35
+ ".txt": "text"
36
+ };
37
+ function guessLoader$1(id) {
38
+ return ExtToLoader$1[path.extname(id).toLowerCase()] || "js";
39
+ }
40
+ function createBuildContext$1(build) {
41
+ const watchFiles = [];
42
+ return {
43
+ fs: createBuildContextFs(),
44
+ addWatchFile(file) {
45
+ watchFiles.push(file);
46
+ },
47
+ getWatchFiles() {
48
+ return watchFiles;
49
+ },
50
+ emitFile(emittedFile) {
51
+ const outFileName = emittedFile.fileName || emittedFile.name;
52
+ const outdir = build?.config?.outdir;
53
+ if (outdir && emittedFile.source && outFileName) {
54
+ const outPath = path.resolve(outdir, outFileName);
55
+ const outDir = path.dirname(outPath);
56
+ if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true });
57
+ fs.writeFileSync(outPath, emittedFile.source);
58
+ }
59
+ },
60
+ parse,
61
+ getNativeBuildContext() {
62
+ return {
63
+ framework: "bun",
64
+ build
65
+ };
66
+ }
67
+ };
68
+ }
69
+ function createPluginContext$1(buildContext) {
70
+ const errors = [];
71
+ const warnings = [];
72
+ return {
73
+ errors,
74
+ warnings,
75
+ mixedContext: {
76
+ ...buildContext,
77
+ error(error) {
78
+ errors.push(error);
79
+ },
80
+ warn(warning) {
81
+ warnings.push(warning);
82
+ }
83
+ }
84
+ };
85
+ }
86
+ //#endregion
87
+ //#region src/bun/index.ts
88
+ function getBunPlugin(factory) {
89
+ return (userOptions) => {
90
+ if (typeof Bun === "undefined") throw new ReferenceError("Bun is not supported in this environment");
91
+ if (!Bun.semver.satisfies(Bun.version, ">=1.2.22")) throw new Error("Bun 1.2.22 or higher is required, please upgrade Bun");
92
+ const meta = {
93
+ framework: "bun",
94
+ versions: {
95
+ bun: Bun.version,
96
+ unplugin: version$1
97
+ }
98
+ };
99
+ const plugins = toArray(factory(userOptions, meta));
100
+ return {
101
+ name: (plugins.length === 1 ? plugins[0].name : meta.bunHostName) ?? `unplugin-host:${plugins.map((p) => p.name).join(":")}`,
102
+ async setup(build) {
103
+ const context = createBuildContext$1(build);
104
+ if (plugins.some((plugin) => plugin.buildStart)) build.onStart(async () => {
105
+ for (const plugin of plugins) if (plugin.buildStart) await plugin.buildStart.call(context);
106
+ });
107
+ const resolveIdHooks = plugins.filter((plugin) => plugin.resolveId).map((plugin) => ({
108
+ plugin,
109
+ ...normalizeObjectHook("resolveId", plugin.resolveId)
110
+ }));
111
+ const loadHooks = plugins.filter((plugin) => plugin.load).map((plugin) => ({
112
+ plugin,
113
+ ...normalizeObjectHook("load", plugin.load)
114
+ }));
115
+ const transformHooks = plugins.filter((plugin) => plugin.transform || plugin.transformInclude).map((plugin) => ({
116
+ plugin,
117
+ ...normalizeObjectHook("transform", plugin.transform)
118
+ }));
119
+ const virtualModulePlugins = /* @__PURE__ */ new Set();
120
+ for (const plugin of plugins) if (plugin.resolveId && plugin.load) virtualModulePlugins.add(plugin.name);
121
+ if (resolveIdHooks.length) build.onResolve({ filter: /.*/ }, async (args) => {
122
+ if (build.config?.external?.includes(args.path)) return;
123
+ for (const { plugin, handler, filter } of resolveIdHooks) {
124
+ if (!filter(args.path)) continue;
125
+ const { mixedContext, errors, warnings } = createPluginContext$1(context);
126
+ const isEntry = args.kind === "entry-point-run" || args.kind === "entry-point-build";
127
+ const result = await handler.call(mixedContext, args.path, isEntry ? void 0 : args.importer, { isEntry });
128
+ for (const warning of warnings) console.warn("[unplugin]", typeof warning === "string" ? warning : warning.message);
129
+ if (errors.length > 0) {
130
+ const errorMessage = errors.map((e) => typeof e === "string" ? e : e.message).join("\n");
131
+ throw new Error(`[unplugin] ${plugin.name}: ${errorMessage}`);
132
+ }
133
+ if (typeof result === "string") {
134
+ if (!isAbsolute(result)) return {
135
+ path: result,
136
+ namespace: plugin.name
137
+ };
138
+ return { path: result };
139
+ } else if (typeof result === "object" && result !== null) {
140
+ if (!isAbsolute(result.id)) return {
141
+ path: result.id,
142
+ external: result.external,
143
+ namespace: plugin.name
144
+ };
145
+ return {
146
+ path: result.id,
147
+ external: result.external
148
+ };
149
+ }
150
+ }
151
+ });
152
+ async function processLoadTransform(id, namespace, loader) {
153
+ let code;
154
+ let hasResult = false;
155
+ const namespaceLoadHooks = namespace === "file" ? loadHooks : loadHooks.filter((h) => h.plugin.name === namespace);
156
+ for (const { plugin, handler, filter } of namespaceLoadHooks) {
157
+ if (plugin.loadInclude && !plugin.loadInclude(id)) continue;
158
+ if (!filter(id)) continue;
159
+ const { mixedContext, errors, warnings } = createPluginContext$1(context);
160
+ const result = await handler.call(mixedContext, id);
161
+ for (const warning of warnings) console.warn("[unplugin]", typeof warning === "string" ? warning : warning.message);
162
+ if (errors.length > 0) {
163
+ const errorMessage = errors.map((e) => typeof e === "string" ? e : e.message).join("\n");
164
+ throw new Error(`[unplugin] ${plugin.name}: ${errorMessage}`);
165
+ }
166
+ if (typeof result === "string") {
167
+ code = result;
168
+ hasResult = true;
169
+ break;
170
+ } else if (typeof result === "object" && result !== null) {
171
+ code = result.code;
172
+ hasResult = true;
173
+ break;
174
+ }
175
+ }
176
+ if (!hasResult && namespace === "file" && transformHooks.length > 0) code = await Bun.file(id).text();
177
+ if (code !== void 0) {
178
+ const namespaceTransformHooks = namespace === "file" ? transformHooks : transformHooks.filter((h) => h.plugin.name === namespace);
179
+ for (const { plugin, handler, filter } of namespaceTransformHooks) {
180
+ if (plugin.transformInclude && !plugin.transformInclude(id)) continue;
181
+ if (!filter(id, code)) continue;
182
+ const { mixedContext, errors, warnings } = createPluginContext$1(context);
183
+ const result = await handler.call(mixedContext, code, id);
184
+ for (const warning of warnings) console.warn("[unplugin]", typeof warning === "string" ? warning : warning.message);
185
+ if (errors.length > 0) {
186
+ const errorMessage = errors.map((e) => typeof e === "string" ? e : e.message).join("\n");
187
+ throw new Error(`[unplugin] ${plugin.name}: ${errorMessage}`);
188
+ }
189
+ if (typeof result === "string") {
190
+ code = result;
191
+ hasResult = true;
192
+ } else if (typeof result === "object" && result !== null) {
193
+ code = result.code;
194
+ hasResult = true;
195
+ }
196
+ }
197
+ }
198
+ if (hasResult && code !== void 0) return {
199
+ contents: code,
200
+ loader: loader ?? guessLoader$1(id)
201
+ };
202
+ }
203
+ if (loadHooks.length || transformHooks.length) build.onLoad({
204
+ filter: /.*/,
205
+ namespace: "file"
206
+ }, async (args) => {
207
+ return processLoadTransform(args.path, "file", args.loader);
208
+ });
209
+ for (const pluginName of virtualModulePlugins) build.onLoad({
210
+ filter: /.*/,
211
+ namespace: pluginName
212
+ }, async (args) => {
213
+ return processLoadTransform(args.path, pluginName, args.loader);
214
+ });
215
+ if (plugins.some((plugin) => plugin.buildEnd || plugin.writeBundle)) build.onEnd(async () => {
216
+ for (const plugin of plugins) {
217
+ if (plugin.buildEnd) await plugin.buildEnd.call(context);
218
+ if (plugin.writeBundle) await plugin.writeBundle();
219
+ }
220
+ });
221
+ }
222
+ };
223
+ };
224
+ }
225
+ //#endregion
226
+ //#region src/esbuild/utils.ts
227
+ const ExtToLoader = {
228
+ ".js": "js",
229
+ ".mjs": "js",
230
+ ".cjs": "js",
231
+ ".jsx": "jsx",
232
+ ".ts": "ts",
233
+ ".cts": "ts",
234
+ ".mts": "ts",
235
+ ".tsx": "tsx",
236
+ ".css": "css",
237
+ ".less": "css",
238
+ ".stylus": "css",
239
+ ".scss": "css",
240
+ ".sass": "css",
241
+ ".json": "json",
242
+ ".txt": "text"
243
+ };
244
+ function guessLoader(code, id) {
245
+ return ExtToLoader[path.extname(id).toLowerCase()] || "js";
246
+ }
247
+ function unwrapLoader(loader, code, id) {
248
+ if (typeof loader === "function") return loader(code, id);
249
+ return loader;
250
+ }
251
+ function fixSourceMap(map) {
252
+ if (!Object.hasOwn(map, "toString")) Object.defineProperty(map, "toString", {
253
+ enumerable: false,
254
+ value: function toString() {
255
+ return JSON.stringify(this);
256
+ }
257
+ });
258
+ if (!Object.hasOwn(map, "toUrl")) Object.defineProperty(map, "toUrl", {
259
+ enumerable: false,
260
+ value: function toUrl() {
261
+ return `data:application/json;charset=utf-8;base64,${Buffer$1.from(this.toString()).toString("base64")}`;
262
+ }
263
+ });
264
+ return map;
265
+ }
266
+ const nullSourceMap = {
267
+ names: [],
268
+ sources: [],
269
+ mappings: "",
270
+ version: 3
271
+ };
272
+ function combineSourcemaps(filename, sourcemapList) {
273
+ sourcemapList = sourcemapList.filter((m) => m.sources);
274
+ if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0)) return { ...nullSourceMap };
275
+ let map;
276
+ let mapIndex = 1;
277
+ if (!sourcemapList.slice(0, -1).some((m) => m.sources.length !== 1)) map = remapping(sourcemapList, () => null, true);
278
+ else map = remapping(sourcemapList[0], (sourcefile) => {
279
+ if (sourcefile === filename && sourcemapList[mapIndex]) return sourcemapList[mapIndex++];
280
+ else return { ...nullSourceMap };
281
+ }, true);
282
+ if (!map.file) delete map.file;
283
+ return map;
284
+ }
285
+ function createBuildContext(build) {
286
+ const watchFiles = [];
287
+ const { initialOptions } = build;
288
+ return {
289
+ fs: createBuildContextFs(),
290
+ parse,
291
+ addWatchFile() {
292
+ throw new Error("unplugin/esbuild: addWatchFile outside supported hooks (resolveId, load, transform)");
293
+ },
294
+ emitFile(emittedFile) {
295
+ const outFileName = emittedFile.fileName || emittedFile.name;
296
+ if (initialOptions.outdir && emittedFile.source && outFileName) {
297
+ const outPath = path.resolve(initialOptions.outdir, outFileName);
298
+ const outDir = path.dirname(outPath);
299
+ if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true });
300
+ fs.writeFileSync(outPath, emittedFile.source);
301
+ }
302
+ },
303
+ getWatchFiles() {
304
+ return watchFiles;
305
+ },
306
+ getNativeBuildContext() {
307
+ return {
308
+ framework: "esbuild",
309
+ build
310
+ };
311
+ }
312
+ };
313
+ }
314
+ function createPluginContext(context) {
315
+ const errors = [];
316
+ const warnings = [];
317
+ const pluginContext = {
318
+ error(message) {
319
+ errors.push(normalizeMessage(message));
320
+ },
321
+ warn(message) {
322
+ warnings.push(normalizeMessage(message));
323
+ }
324
+ };
325
+ return {
326
+ errors,
327
+ warnings,
328
+ mixedContext: {
329
+ ...context,
330
+ ...pluginContext,
331
+ addWatchFile(id) {
332
+ context.getWatchFiles().push(id);
333
+ }
334
+ }
335
+ };
336
+ }
337
+ function normalizeMessage(message) {
338
+ if (typeof message === "string") message = { message };
339
+ return {
340
+ id: message.id,
341
+ pluginName: message.plugin,
342
+ text: message.message,
343
+ location: message.loc ? {
344
+ file: message.loc.file,
345
+ line: message.loc.line,
346
+ column: message.loc.column
347
+ } : null,
348
+ detail: message.meta,
349
+ notes: []
350
+ };
351
+ }
352
+ function processCodeWithSourceMap(map, code) {
353
+ if (map) {
354
+ if (!map.sourcesContent || map.sourcesContent.length === 0) map.sourcesContent = [code];
355
+ map = fixSourceMap(map);
356
+ code += `\n//# sourceMappingURL=${map.toUrl()}`;
357
+ }
358
+ return code;
359
+ }
360
+ //#endregion
361
+ //#region src/esbuild/index.ts
362
+ function getEsbuildPlugin(factory) {
363
+ return (userOptions) => {
364
+ const meta = {
365
+ framework: "esbuild",
366
+ versions: { unplugin: version$1 }
367
+ };
368
+ const plugins = toArray(factory(userOptions, meta));
369
+ const setupPlugins = async (build) => {
370
+ const setup = buildSetup();
371
+ const loaders = [];
372
+ for (const plugin of plugins) {
373
+ const loader = {};
374
+ await setup(plugin)({
375
+ ...build,
376
+ onLoad(_options, callback) {
377
+ loader.options = _options;
378
+ loader.onLoadCb = callback;
379
+ },
380
+ onTransform(_options, callback) {
381
+ loader.options ||= _options;
382
+ loader.onTransformCb = callback;
383
+ }
384
+ }, build);
385
+ if (loader.onLoadCb || loader.onTransformCb) loaders.push(loader);
386
+ }
387
+ if (loaders.length) build.onLoad(loaders.length === 1 ? loaders[0].options : { filter: /.*/ }, async (args) => {
388
+ function checkFilter(options) {
389
+ return loaders.length === 1 || !options?.filter || options.filter.test(args.path);
390
+ }
391
+ let result;
392
+ for (const { options, onLoadCb } of loaders) {
393
+ if (!checkFilter(options)) continue;
394
+ if (onLoadCb) result = await onLoadCb(args);
395
+ if (result?.contents) break;
396
+ }
397
+ let fsContentsCache;
398
+ for (const { options, onTransformCb } of loaders) {
399
+ if (!checkFilter(options)) continue;
400
+ if (onTransformCb) {
401
+ const _result = await onTransformCb({
402
+ ...result,
403
+ ...args,
404
+ async getContents() {
405
+ if (result?.contents) return result.contents;
406
+ if (fsContentsCache) return fsContentsCache;
407
+ return fsContentsCache = await fs.promises.readFile(args.path, "utf8");
408
+ }
409
+ });
410
+ if (_result?.contents) result = _result;
411
+ }
412
+ }
413
+ if (result?.contents) return result;
414
+ });
415
+ };
416
+ return {
417
+ name: (plugins.length === 1 ? plugins[0].name : meta.esbuildHostName) ?? `unplugin-host:${plugins.map((p) => p.name).join(":")}`,
418
+ setup: setupPlugins
419
+ };
420
+ };
421
+ }
422
+ function buildSetup() {
423
+ return (plugin) => {
424
+ return (build, rawBuild) => {
425
+ const context = createBuildContext(rawBuild);
426
+ const { onStart, onEnd, onResolve, onLoad, onTransform, initialOptions } = build;
427
+ const onResolveFilter = plugin.esbuild?.onResolveFilter ?? /.*/;
428
+ const onLoadFilter = plugin.esbuild?.onLoadFilter ?? /.*/;
429
+ const loader = plugin.esbuild?.loader ?? guessLoader;
430
+ plugin.esbuild?.config?.call(context, initialOptions);
431
+ if (plugin.buildStart) onStart(() => plugin.buildStart.call(context));
432
+ if (plugin.buildEnd || plugin.writeBundle) onEnd(async () => {
433
+ if (plugin.buildEnd) await plugin.buildEnd.call(context);
434
+ if (plugin.writeBundle) await plugin.writeBundle();
435
+ });
436
+ if (plugin.resolveId) onResolve({ filter: onResolveFilter }, async (args) => {
437
+ const id = args.path;
438
+ if (initialOptions.external?.includes(id)) return;
439
+ const { handler, filter } = normalizeObjectHook("resolveId", plugin.resolveId);
440
+ if (!filter(id)) return;
441
+ const { errors, warnings, mixedContext } = createPluginContext(context);
442
+ const isEntry = args.kind === "entry-point";
443
+ const result = await handler.call(mixedContext, id, isEntry ? void 0 : args.importer, { isEntry });
444
+ if (typeof result === "string") return {
445
+ path: result,
446
+ namespace: plugin.name,
447
+ errors,
448
+ warnings,
449
+ watchFiles: mixedContext.getWatchFiles()
450
+ };
451
+ else if (typeof result === "object" && result !== null) return {
452
+ path: result.id,
453
+ external: result.external,
454
+ namespace: plugin.name,
455
+ errors,
456
+ warnings,
457
+ watchFiles: mixedContext.getWatchFiles()
458
+ };
459
+ });
460
+ if (plugin.load) onLoad({ filter: onLoadFilter }, async (args) => {
461
+ const { handler, filter } = normalizeObjectHook("load", plugin.load);
462
+ const id = args.path + (args.suffix || "");
463
+ if (plugin.loadInclude && !plugin.loadInclude(id)) return;
464
+ if (!filter(id)) return;
465
+ const { errors, warnings, mixedContext } = createPluginContext(context);
466
+ let code;
467
+ let map;
468
+ const result = await handler.call(mixedContext, id);
469
+ if (typeof result === "string") code = result;
470
+ else if (typeof result === "object" && result !== null) {
471
+ code = result.code;
472
+ map = result.map;
473
+ }
474
+ if (code === void 0) return null;
475
+ if (map) code = processCodeWithSourceMap(map, code);
476
+ const resolveDir = path.dirname(args.path);
477
+ return {
478
+ contents: code,
479
+ errors,
480
+ warnings,
481
+ watchFiles: mixedContext.getWatchFiles(),
482
+ loader: unwrapLoader(loader, code, args.path),
483
+ resolveDir
484
+ };
485
+ });
486
+ if (plugin.transform) onTransform({ filter: onLoadFilter }, async (args) => {
487
+ const { handler, filter } = normalizeObjectHook("transform", plugin.transform);
488
+ const id = args.path + (args.suffix || "");
489
+ if (plugin.transformInclude && !plugin.transformInclude(id)) return;
490
+ let code = await args.getContents();
491
+ if (!filter(id, code)) return;
492
+ const { mixedContext, errors, warnings } = createPluginContext(context);
493
+ const resolveDir = path.dirname(args.path);
494
+ let map;
495
+ const result = await handler.call(mixedContext, code, id);
496
+ if (typeof result === "string") code = result;
497
+ else if (typeof result === "object" && result !== null) {
498
+ code = result.code;
499
+ if (map && result.map) map = combineSourcemaps(args.path, [result.map === "string" ? JSON.parse(result.map) : result.map, map]);
500
+ else if (typeof result.map === "string") map = JSON.parse(result.map);
501
+ else map = result.map;
502
+ }
503
+ if (code) {
504
+ if (map) code = processCodeWithSourceMap(map, code);
505
+ return {
506
+ contents: code,
507
+ errors,
508
+ warnings,
509
+ watchFiles: mixedContext.getWatchFiles(),
510
+ loader: unwrapLoader(loader, code, args.path),
511
+ resolveDir
512
+ };
513
+ }
514
+ });
515
+ if (plugin.esbuild?.setup) return plugin.esbuild.setup(rawBuild);
516
+ };
517
+ };
518
+ }
519
+ //#endregion
520
+ //#region src/farm/context.ts
521
+ function createFarmContext(context, currentResolveId) {
522
+ return {
523
+ fs: createBuildContextFs(),
524
+ parse,
525
+ addWatchFile(id) {
526
+ context.addWatchFile(id, currentResolveId || id);
527
+ },
528
+ emitFile(emittedFile) {
529
+ const outFileName = emittedFile.fileName || emittedFile.name;
530
+ if (emittedFile.source && outFileName) context.emitFile({
531
+ resolvedPath: outFileName,
532
+ name: outFileName,
533
+ content: [...Buffer$1.from(emittedFile.source)],
534
+ resourceType: extname(outFileName)
535
+ });
536
+ },
537
+ getWatchFiles() {
538
+ return context.getWatchFiles();
539
+ },
540
+ getNativeBuildContext() {
541
+ return {
542
+ framework: "farm",
543
+ context
544
+ };
545
+ }
546
+ };
547
+ }
548
+ function unpluginContext(context) {
549
+ return {
550
+ error: (error) => context.error(typeof error === "string" ? new Error(error) : error),
551
+ warn: (error) => context.warn(typeof error === "string" ? new Error(error) : error)
552
+ };
553
+ }
554
+ //#endregion
555
+ //#region src/farm/utils.ts
556
+ function convertEnforceToPriority(value) {
557
+ const defaultPriority = 100;
558
+ const enforceToPriority = {
559
+ pre: 102,
560
+ post: 98
561
+ };
562
+ return enforceToPriority[value] !== void 0 ? enforceToPriority[value] : defaultPriority;
563
+ }
564
+ function convertWatchEventChange(value) {
565
+ return {
566
+ Added: "create",
567
+ Updated: "update",
568
+ Removed: "delete"
569
+ }[value];
570
+ }
571
+ function isString(variable) {
572
+ return typeof variable === "string";
573
+ }
574
+ function isObject(variable) {
575
+ return typeof variable === "object" && variable !== null;
576
+ }
577
+ function customParseQueryString(url) {
578
+ if (!url) return [];
579
+ const queryString = url.split("?")[1];
580
+ const parsedParams = querystring.parse(queryString);
581
+ const paramsArray = [];
582
+ for (const key in parsedParams) paramsArray.push([key, parsedParams[key]]);
583
+ return paramsArray;
584
+ }
585
+ function encodeStr(str) {
586
+ const len = str.length;
587
+ if (len === 0) return str;
588
+ const firstNullIndex = str.indexOf("\0");
589
+ if (firstNullIndex === -1) return str;
590
+ const result = Array.from({ length: len + countNulls(str, firstNullIndex) });
591
+ let pos = 0;
592
+ for (let i = 0; i < firstNullIndex; i++) result[pos++] = str[i];
593
+ for (let i = firstNullIndex; i < len; i++) {
594
+ const char = str[i];
595
+ if (char === "\0") {
596
+ result[pos++] = "\\";
597
+ result[pos++] = "0";
598
+ } else result[pos++] = char;
599
+ }
600
+ return path.posix.normalize(result.join(""));
601
+ }
602
+ function decodeStr(str) {
603
+ const len = str.length;
604
+ if (len === 0) return str;
605
+ const firstIndex = str.indexOf("\\0");
606
+ if (firstIndex === -1) return str;
607
+ const result = Array.from({ length: len - countBackslashZeros(str, firstIndex) });
608
+ let pos = 0;
609
+ for (let i = 0; i < firstIndex; i++) result[pos++] = str[i];
610
+ let i = firstIndex;
611
+ while (i < len) if (str[i] === "\\" && str[i + 1] === "0") {
612
+ result[pos++] = "\0";
613
+ i += 2;
614
+ } else result[pos++] = str[i++];
615
+ return path.posix.normalize(result.join(""));
616
+ }
617
+ function getContentValue(content) {
618
+ if (content === null || content === void 0) throw new Error("Content cannot be null or undefined");
619
+ return encodeStr(typeof content === "string" ? content : content.code || "");
620
+ }
621
+ function countNulls(str, startIndex) {
622
+ let count = 0;
623
+ const len = str.length;
624
+ for (let i = startIndex; i < len; i++) if (str[i] === "\0") count++;
625
+ return count;
626
+ }
627
+ function countBackslashZeros(str, startIndex) {
628
+ let count = 0;
629
+ const len = str.length;
630
+ for (let i = startIndex; i < len - 1; i++) if (str[i] === "\\" && str[i + 1] === "0") {
631
+ count++;
632
+ i++;
633
+ }
634
+ return count;
635
+ }
636
+ function removeQuery(pathe) {
637
+ const queryIndex = pathe.indexOf("?");
638
+ if (queryIndex !== -1) return path.posix.normalize(pathe.slice(0, queryIndex));
639
+ return path.posix.normalize(pathe);
640
+ }
641
+ function isStartsWithSlash(str) {
642
+ return str?.startsWith("/");
643
+ }
644
+ function appendQuery(id, query) {
645
+ if (!query.length) return id;
646
+ return `${id}?${stringifyQuery(query)}`;
647
+ }
648
+ function stringifyQuery(query) {
649
+ if (!query.length) return "";
650
+ let queryStr = "";
651
+ for (const [key, value] of query) queryStr += `${key}${value ? `=${value}` : ""}&`;
652
+ return `${queryStr.slice(0, -1)}`;
653
+ }
654
+ const CSS_LANGS_RES = [
655
+ [/\.(less)(?:$|\?)/, "less"],
656
+ [/\.(scss|sass)(?:$|\?)/, "sass"],
657
+ [/\.(styl|stylus)(?:$|\?)/, "stylus"],
658
+ [/\.(css)(?:$|\?)/, "css"]
659
+ ];
660
+ const JS_LANGS_RES = [
661
+ [/\.(js|mjs|cjs)(?:$|\?)/, "js"],
662
+ [/\.(jsx)(?:$|\?)/, "jsx"],
663
+ [/\.(ts|cts|mts)(?:$|\?)/, "ts"],
664
+ [/\.(tsx)(?:$|\?)/, "tsx"]
665
+ ];
666
+ function getCssModuleType(id) {
667
+ for (const [reg, lang] of CSS_LANGS_RES) if (reg.test(id)) return lang;
668
+ return null;
669
+ }
670
+ function getJsModuleType(id) {
671
+ for (const [reg, lang] of JS_LANGS_RES) if (reg.test(id)) return lang;
672
+ return null;
673
+ }
674
+ function formatLoadModuleType(id) {
675
+ const cssModuleType = getCssModuleType(id);
676
+ if (cssModuleType) return cssModuleType;
677
+ const jsModuleType = getJsModuleType(id);
678
+ if (jsModuleType) return jsModuleType;
679
+ return "js";
680
+ }
681
+ function formatTransformModuleType(id) {
682
+ return formatLoadModuleType(id);
683
+ }
684
+ //#endregion
685
+ //#region src/farm/index.ts
686
+ function getFarmPlugin(factory) {
687
+ return ((userOptions) => {
688
+ const plugins = toArray(factory(userOptions, {
689
+ framework: "farm",
690
+ versions: { unplugin: version$1 }
691
+ })).map((rawPlugin) => {
692
+ const plugin = toFarmPlugin(rawPlugin, userOptions);
693
+ if (rawPlugin.farm) Object.assign(plugin, rawPlugin.farm);
694
+ return plugin;
695
+ });
696
+ return plugins.length === 1 ? plugins[0] : plugins;
697
+ });
698
+ }
699
+ function toFarmPlugin(plugin, options) {
700
+ const farmPlugin = {
701
+ name: plugin.name,
702
+ priority: convertEnforceToPriority(plugin.enforce)
703
+ };
704
+ if (plugin.farm) Object.keys(plugin.farm).forEach((key) => {
705
+ const value = plugin.farm[key];
706
+ if (value) Reflect.set(farmPlugin, key, value);
707
+ });
708
+ if (plugin.buildStart) {
709
+ const _buildStart = plugin.buildStart;
710
+ farmPlugin.buildStart = { async executor(_, context) {
711
+ await _buildStart.call(createFarmContext(context));
712
+ } };
713
+ }
714
+ if (plugin.resolveId) {
715
+ const _resolveId = plugin.resolveId;
716
+ let filters = [];
717
+ if (options) filters = options?.filters ?? [];
718
+ farmPlugin.resolve = {
719
+ filters: {
720
+ sources: filters.length ? filters : [".*"],
721
+ importers: [".*"]
722
+ },
723
+ async executor(params, context) {
724
+ const resolvedIdPath = path.resolve(params.importer ?? "");
725
+ const id = decodeStr(params.source);
726
+ const { handler, filter } = normalizeObjectHook("resolveId", _resolveId);
727
+ if (!filter(id)) return null;
728
+ let isEntry = false;
729
+ if (isObject(params.kind) && "entry" in params.kind) isEntry = params.kind.entry === "index";
730
+ const farmContext = createFarmContext(context, resolvedIdPath);
731
+ const resolveIdResult = await handler.call(Object.assign(unpluginContext(context), farmContext), id, resolvedIdPath ?? null, { isEntry });
732
+ if (isString(resolveIdResult)) return {
733
+ resolvedPath: removeQuery(encodeStr(resolveIdResult)),
734
+ query: customParseQueryString(resolveIdResult),
735
+ sideEffects: true,
736
+ external: false,
737
+ meta: {}
738
+ };
739
+ if (isObject(resolveIdResult)) return {
740
+ resolvedPath: removeQuery(encodeStr(resolveIdResult?.id)),
741
+ query: customParseQueryString(resolveIdResult?.id),
742
+ sideEffects: false,
743
+ external: Boolean(resolveIdResult?.external),
744
+ meta: {}
745
+ };
746
+ if (!isStartsWithSlash(params.source)) return null;
747
+ }
748
+ };
749
+ }
750
+ if (plugin.load) {
751
+ const _load = plugin.load;
752
+ farmPlugin.load = {
753
+ filters: { resolvedPaths: [".*"] },
754
+ async executor(params, context) {
755
+ const id = appendQuery(decodeStr(params.resolvedPath), params.query);
756
+ const loader = formatTransformModuleType(id);
757
+ if (plugin.loadInclude && !plugin.loadInclude?.(id)) return null;
758
+ const { handler, filter } = normalizeObjectHook("load", _load);
759
+ if (!filter(id)) return null;
760
+ const farmContext = createFarmContext(context, id);
761
+ return {
762
+ content: getContentValue(await handler.call(Object.assign(unpluginContext(context), farmContext), id)),
763
+ moduleType: loader
764
+ };
765
+ }
766
+ };
767
+ }
768
+ if (plugin.transform) {
769
+ const _transform = plugin.transform;
770
+ farmPlugin.transform = {
771
+ filters: {
772
+ resolvedPaths: [".*"],
773
+ moduleTypes: [".*"]
774
+ },
775
+ async executor(params, context) {
776
+ const id = appendQuery(decodeStr(params.resolvedPath), params.query);
777
+ const loader = formatTransformModuleType(id);
778
+ if (plugin.transformInclude && !plugin.transformInclude(id)) return null;
779
+ const { handler, filter } = normalizeObjectHook("transform", _transform);
780
+ if (!filter(id, params.content)) return null;
781
+ const farmContext = createFarmContext(context, id);
782
+ const resource = await handler.call(Object.assign(unpluginContext(context), farmContext), params.content, id);
783
+ if (resource && typeof resource !== "string") return {
784
+ content: getContentValue(resource),
785
+ moduleType: loader,
786
+ sourceMap: typeof resource.map === "object" && resource.map !== null ? JSON.stringify(resource.map) : void 0
787
+ };
788
+ }
789
+ };
790
+ }
791
+ if (plugin.watchChange) {
792
+ const _watchChange = plugin.watchChange;
793
+ farmPlugin.updateModules = { async executor(param, context) {
794
+ const updatePathContent = param.paths[0];
795
+ const ModifiedPath = updatePathContent[0];
796
+ const eventChange = convertWatchEventChange(updatePathContent[1]);
797
+ await _watchChange.call(createFarmContext(context), ModifiedPath, { event: eventChange });
798
+ } };
799
+ }
800
+ if (plugin.buildEnd) {
801
+ const _buildEnd = plugin.buildEnd;
802
+ farmPlugin.buildEnd = { async executor(_, context) {
803
+ await _buildEnd.call(createFarmContext(context));
804
+ } };
805
+ }
806
+ if (plugin.writeBundle) {
807
+ const _writeBundle = plugin.writeBundle;
808
+ farmPlugin.finish = { async executor() {
809
+ await _writeBundle();
810
+ } };
811
+ }
812
+ return farmPlugin;
813
+ }
814
+ //#endregion
815
+ //#region src/rollup/index.ts
816
+ function getRollupPlugin(factory) {
817
+ return ((userOptions) => {
818
+ const meta = {
819
+ framework: "rollup",
820
+ versions: { unplugin: version$1 }
821
+ };
822
+ const plugins = toArray(factory(userOptions, meta)).map((plugin) => toRollupPlugin(plugin, "rollup", meta));
823
+ return plugins.length === 1 ? plugins[0] : plugins;
824
+ });
825
+ }
826
+ function toRollupPlugin(plugin, key, meta) {
827
+ const nativeFilter = key === "rolldown";
828
+ if (plugin.resolveId && !nativeFilter && typeof plugin.resolveId === "object" && plugin.resolveId.filter) {
829
+ const resolveIdHook = plugin.resolveId;
830
+ const { handler, filter } = normalizeObjectHook("load", resolveIdHook);
831
+ replaceHookHandler("resolveId", resolveIdHook, function(...args) {
832
+ const [id] = args;
833
+ if (!supportNativeFilter(this, key) && !filter(id)) return;
834
+ return handler.apply(this, args);
835
+ });
836
+ }
837
+ if (plugin.load && (plugin.loadInclude || !nativeFilter && typeof plugin.load === "object" && plugin.load.filter)) {
838
+ const loadHook = plugin.load;
839
+ const { handler, filter } = normalizeObjectHook("load", loadHook);
840
+ replaceHookHandler("load", loadHook, function(...args) {
841
+ const [id] = args;
842
+ if (plugin.loadInclude && !plugin.loadInclude(id)) return;
843
+ if (!supportNativeFilter(this, key) && !filter(id)) return;
844
+ return handler.apply(this, args);
845
+ });
846
+ }
847
+ if (plugin.transform && (plugin.transformInclude || !nativeFilter && typeof plugin.transform === "object" && plugin.transform.filter)) {
848
+ const transformHook = plugin.transform;
849
+ const { handler, filter } = normalizeObjectHook("transform", transformHook);
850
+ replaceHookHandler("transform", transformHook, function(...args) {
851
+ const [code, id] = args;
852
+ if (plugin.transformInclude && !plugin.transformInclude(id)) return;
853
+ if (!supportNativeFilter(this, key) && !filter(id, code)) return;
854
+ return handler.apply(this, args);
855
+ });
856
+ }
857
+ if (plugin[key]) Object.assign(plugin, plugin[key]);
858
+ const buildStartHook = plugin.buildStart;
859
+ const buildStartHandler = typeof buildStartHook === "object" ? buildStartHook?.handler : buildStartHook;
860
+ replaceHookHandler("buildStart", buildStartHook, function(...args) {
861
+ const versions = { unplugin: version$1 };
862
+ const viteVersion = this?.meta?.viteVersion;
863
+ if (viteVersion) versions.vite = viteVersion;
864
+ const rollupVersion = this?.meta?.rollupVersion;
865
+ if (rollupVersion) versions.rollup = rollupVersion;
866
+ const rolldownVersion = this?.meta?.rolldownVersion;
867
+ if (rolldownVersion) versions.rolldown = rolldownVersion;
868
+ const unloaderVersion = this?.meta?.unloaderVersion;
869
+ if (unloaderVersion) versions.unloader = unloaderVersion;
870
+ meta.versions = versions;
871
+ return buildStartHandler?.apply(this, args);
872
+ });
873
+ return plugin;
874
+ function replaceHookHandler(name, hook, handler) {
875
+ if (typeof hook === "object") hook.handler = handler;
876
+ else plugin[name] = handler;
877
+ }
878
+ }
879
+ function supportNativeFilter(context, framework) {
880
+ if (framework === "vite") return !!context?.meta?.viteVersion;
881
+ if (framework === "rolldown") return true;
882
+ const rollupVersion = context?.meta?.rollupVersion;
883
+ if (!rollupVersion) return false;
884
+ const [major, minor] = rollupVersion.split(".");
885
+ return Number(major) > 4 || Number(major) === 4 && Number(minor) >= 40;
886
+ }
887
+ //#endregion
888
+ //#region src/rolldown/index.ts
889
+ function getRolldownPlugin(factory) {
890
+ return ((userOptions) => {
891
+ const meta = {
892
+ framework: "rolldown",
893
+ versions: { unplugin: version$1 }
894
+ };
895
+ const plugins = toArray(factory(userOptions, meta)).map((rawPlugin) => {
896
+ return toRollupPlugin(rawPlugin, "rolldown", meta);
897
+ });
898
+ return plugins.length === 1 ? plugins[0] : plugins;
899
+ });
900
+ }
901
+ //#endregion
902
+ //#region src/rspack/index.ts
903
+ const TRANSFORM_LOADER$1 = resolve(import.meta.dirname, "rspack/loaders/transform.mjs");
904
+ const LOAD_LOADER$1 = resolve(import.meta.dirname, "rspack/loaders/load.mjs");
905
+ function getRspackPlugin(factory) {
906
+ return (userOptions) => {
907
+ return { apply(compiler) {
908
+ const VIRTUAL_MODULE_PREFIX = resolve(compiler.options.context ?? process.cwd(), "node_modules/.virtual", compiler.rspack.experiments.VirtualModulesPlugin ? "" : process.pid.toString());
909
+ const meta = {
910
+ framework: "rspack",
911
+ versions: {
912
+ rspack: compiler.rspack?.rspackVersion ?? compiler.rspack?.version,
913
+ unplugin: version$1
914
+ },
915
+ rspack: { compiler }
916
+ };
917
+ const rawPlugins = toArray(factory(userOptions, meta));
918
+ for (const rawPlugin of rawPlugins) {
919
+ const plugin = Object.assign(rawPlugin, {
920
+ __unpluginMeta: meta,
921
+ __virtualModulePrefix: VIRTUAL_MODULE_PREFIX
922
+ });
923
+ const externalModules = /* @__PURE__ */ new Set();
924
+ if (plugin.resolveId) {
925
+ const createPlugin = (plugin) => {
926
+ if (compiler.rspack.experiments.VirtualModulesPlugin) return new compiler.rspack.experiments.VirtualModulesPlugin();
927
+ return new FakeVirtualModulesPlugin(plugin);
928
+ };
929
+ const vfs = createPlugin(plugin);
930
+ vfs.apply(compiler);
931
+ const vfsModules = /* @__PURE__ */ new Map();
932
+ plugin.__vfsModules = vfsModules;
933
+ plugin.__vfs = vfs;
934
+ compiler.hooks.compilation.tap(plugin.name, (compilation, { normalModuleFactory }) => {
935
+ normalModuleFactory.hooks.resolve.tapPromise(plugin.name, async (resolveData) => {
936
+ const id = normalizeAbsolutePath(resolveData.request);
937
+ const requestContext = resolveData.contextInfo;
938
+ let importer = requestContext.issuer !== "" ? requestContext.issuer : void 0;
939
+ const isEntry = requestContext.issuer === "";
940
+ if (importer?.startsWith(plugin.__virtualModulePrefix)) importer = decodeURIComponent(importer.slice(plugin.__virtualModulePrefix.length));
941
+ const context = createBuildContext$2(compiler, compilation);
942
+ let error;
943
+ const pluginContext = {
944
+ error(msg) {
945
+ if (error == null) error = normalizeMessage$1(msg);
946
+ else console.error(`unplugin/rspack: multiple errors returned from resolveId hook: ${msg}`);
947
+ },
948
+ warn(msg) {
949
+ console.warn(`unplugin/rspack: warning from resolveId hook: ${msg}`);
950
+ }
951
+ };
952
+ const { handler, filter } = normalizeObjectHook("resolveId", plugin.resolveId);
953
+ if (!filter(id)) return;
954
+ const resolveIdResult = await handler.call({
955
+ ...context,
956
+ ...pluginContext
957
+ }, id, importer, { isEntry });
958
+ if (error != null) throw error;
959
+ if (resolveIdResult == null) return;
960
+ let resolved = typeof resolveIdResult === "string" ? resolveIdResult : resolveIdResult.id;
961
+ if (typeof resolveIdResult === "string" ? false : resolveIdResult.external === true) externalModules.add(resolved);
962
+ let isVirtual = true;
963
+ try {
964
+ (compiler.inputFileSystem?.statSync ?? fs.statSync)(resolved);
965
+ isVirtual = false;
966
+ } catch {
967
+ isVirtual = !isVirtualModuleId(resolved, plugin);
968
+ }
969
+ if (isVirtual) {
970
+ const encodedVirtualPath = encodeVirtualModuleId(resolved, plugin);
971
+ if (!vfsModules.has(resolved)) {
972
+ const fsPromise = Promise.resolve(vfs.writeModule(encodedVirtualPath, ""));
973
+ vfsModules.set(resolved, fsPromise);
974
+ await fsPromise;
975
+ } else await vfsModules.get(resolved);
976
+ resolved = encodedVirtualPath;
977
+ }
978
+ resolveData.request = resolved;
979
+ });
980
+ });
981
+ }
982
+ if (plugin.load) compiler.options.module.rules.unshift({
983
+ enforce: plugin.enforce,
984
+ include(id) {
985
+ if (isVirtualModuleId(id, plugin)) id = decodeVirtualModuleId(id, plugin);
986
+ if (plugin.loadInclude && !plugin.loadInclude(id)) return false;
987
+ const { filter } = normalizeObjectHook("load", plugin.load);
988
+ if (!filter(id)) return false;
989
+ return !externalModules.has(id);
990
+ },
991
+ use: [{
992
+ loader: LOAD_LOADER$1,
993
+ options: { plugin }
994
+ }],
995
+ type: "javascript/auto"
996
+ });
997
+ if (plugin.transform) compiler.options.module.rules.unshift({
998
+ enforce: plugin.enforce,
999
+ use(data) {
1000
+ return transformUse(data, plugin, TRANSFORM_LOADER$1);
1001
+ }
1002
+ });
1003
+ if (plugin.rspack) plugin.rspack(compiler);
1004
+ if (plugin.watchChange || plugin.buildStart) compiler.hooks.make.tapPromise(plugin.name, async (compilation) => {
1005
+ const context = createBuildContext$2(compiler, compilation);
1006
+ if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) {
1007
+ const promises = [];
1008
+ if (compiler.modifiedFiles) compiler.modifiedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "update" }))));
1009
+ if (compiler.removedFiles) compiler.removedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "delete" }))));
1010
+ await Promise.all(promises);
1011
+ }
1012
+ if (plugin.buildStart) return await plugin.buildStart.call(context);
1013
+ });
1014
+ if (plugin.buildEnd) compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => {
1015
+ await plugin.buildEnd.call(createBuildContext$2(compiler, compilation));
1016
+ });
1017
+ if (plugin.writeBundle) compiler.hooks.afterEmit.tapPromise(plugin.name, async () => {
1018
+ await plugin.writeBundle();
1019
+ });
1020
+ }
1021
+ } };
1022
+ };
1023
+ }
1024
+ //#endregion
1025
+ //#region src/unloader/index.ts
1026
+ function getUnloaderPlugin(factory) {
1027
+ return ((userOptions) => {
1028
+ const meta = {
1029
+ framework: "unloader",
1030
+ versions: { unplugin: version$1 }
1031
+ };
1032
+ const plugins = toArray(factory(userOptions, meta)).map((rawPlugin) => {
1033
+ return toRollupPlugin(rawPlugin, "unloader", meta);
1034
+ });
1035
+ return plugins.length === 1 ? plugins[0] : plugins;
1036
+ });
1037
+ }
1038
+ //#endregion
1039
+ //#region src/vite/index.ts
1040
+ function getVitePlugin(factory) {
1041
+ return ((userOptions) => {
1042
+ const meta = {
1043
+ framework: "vite",
1044
+ versions: { unplugin: version$1 }
1045
+ };
1046
+ const plugins = toArray(factory(userOptions, meta)).map((rawPlugin) => {
1047
+ return toRollupPlugin(rawPlugin, "vite", meta);
1048
+ });
1049
+ return plugins.length === 1 ? plugins[0] : plugins;
1050
+ });
1051
+ }
1052
+ //#endregion
1053
+ //#region src/webpack/index.ts
1054
+ const TRANSFORM_LOADER = resolve(import.meta.dirname, "webpack/loaders/transform.mjs");
1055
+ const LOAD_LOADER = resolve(import.meta.dirname, "webpack/loaders/load.mjs");
1056
+ function getWebpackPlugin(factory) {
1057
+ return (userOptions) => {
1058
+ const VirtualModulesPlugin = __require("webpack-virtual-modules");
1059
+ return { apply(compiler) {
1060
+ const VIRTUAL_MODULE_PREFIX = resolve(compiler.options.context ?? process$1.cwd(), "_virtual_");
1061
+ const meta = {
1062
+ framework: "webpack",
1063
+ versions: {
1064
+ webpack: compiler.webpack?.version,
1065
+ unplugin: version$1
1066
+ },
1067
+ webpack: { compiler }
1068
+ };
1069
+ const rawPlugins = toArray(factory(userOptions, meta));
1070
+ for (const rawPlugin of rawPlugins) {
1071
+ const plugin = Object.assign(rawPlugin, {
1072
+ __unpluginMeta: meta,
1073
+ __virtualModulePrefix: VIRTUAL_MODULE_PREFIX
1074
+ });
1075
+ const externalModules = /* @__PURE__ */ new Set();
1076
+ if (plugin.resolveId) {
1077
+ let vfs = compiler.options.plugins.find((i) => i instanceof VirtualModulesPlugin);
1078
+ if (!vfs) {
1079
+ vfs = new VirtualModulesPlugin();
1080
+ compiler.options.plugins.push(vfs);
1081
+ }
1082
+ const vfsModules = /* @__PURE__ */ new Set();
1083
+ plugin.__vfsModules = vfsModules;
1084
+ plugin.__vfs = vfs;
1085
+ const resolverPlugin = { apply(resolver) {
1086
+ const target = resolver.ensureHook("resolve");
1087
+ resolver.getHook("resolve").tapAsync(plugin.name, async (request, resolveContext, callback) => {
1088
+ if (!request.request) return callback();
1089
+ if (normalizeAbsolutePath(request.request).startsWith(plugin.__virtualModulePrefix)) return callback();
1090
+ const id = normalizeAbsolutePath(request.request);
1091
+ const requestContext = request.context;
1092
+ let importer = requestContext.issuer !== "" ? requestContext.issuer : void 0;
1093
+ const isEntry = requestContext.issuer === "";
1094
+ if (importer?.startsWith(plugin.__virtualModulePrefix)) importer = decodeURIComponent(importer.slice(plugin.__virtualModulePrefix.length));
1095
+ const fileDependencies = /* @__PURE__ */ new Set();
1096
+ const context = createBuildContext$3({
1097
+ addWatchFile(file) {
1098
+ fileDependencies.add(file);
1099
+ resolveContext.fileDependencies?.add(file);
1100
+ },
1101
+ getWatchFiles() {
1102
+ return Array.from(fileDependencies);
1103
+ }
1104
+ }, compiler);
1105
+ let error;
1106
+ const pluginContext = {
1107
+ error(msg) {
1108
+ if (error == null) error = normalizeMessage$2(msg);
1109
+ else console.error(`unplugin/webpack: multiple errors returned from resolveId hook: ${msg}`);
1110
+ },
1111
+ warn(msg) {
1112
+ console.warn(`unplugin/webpack: warning from resolveId hook: ${msg}`);
1113
+ }
1114
+ };
1115
+ const { handler, filter } = normalizeObjectHook("resolveId", plugin.resolveId);
1116
+ if (!filter(id)) return callback();
1117
+ const resolveIdResult = await handler.call({
1118
+ ...context,
1119
+ ...pluginContext
1120
+ }, id, importer, { isEntry });
1121
+ if (error != null) return callback(error);
1122
+ if (resolveIdResult == null) return callback();
1123
+ let resolved = typeof resolveIdResult === "string" ? resolveIdResult : resolveIdResult.id;
1124
+ if (typeof resolveIdResult === "string" ? false : resolveIdResult.external === true) externalModules.add(resolved);
1125
+ if (!fs.existsSync(resolved)) {
1126
+ resolved = normalizeAbsolutePath(plugin.__virtualModulePrefix + encodeURIComponent(resolved));
1127
+ if (!vfsModules.has(resolved)) {
1128
+ plugin.__vfs.writeModule(resolved, "");
1129
+ vfsModules.add(resolved);
1130
+ }
1131
+ }
1132
+ const newRequest = {
1133
+ ...request,
1134
+ request: resolved
1135
+ };
1136
+ resolver.doResolve(target, newRequest, null, resolveContext, callback);
1137
+ });
1138
+ } };
1139
+ compiler.options.resolve.plugins = compiler.options.resolve.plugins || [];
1140
+ compiler.options.resolve.plugins.push(resolverPlugin);
1141
+ }
1142
+ if (plugin.load) compiler.options.module.rules.unshift({
1143
+ include(id) {
1144
+ return shouldLoad(id, plugin, externalModules);
1145
+ },
1146
+ enforce: plugin.enforce,
1147
+ use: [{
1148
+ loader: LOAD_LOADER,
1149
+ options: { plugin }
1150
+ }],
1151
+ type: "javascript/auto"
1152
+ });
1153
+ if (plugin.transform) compiler.options.module.rules.unshift({
1154
+ enforce: plugin.enforce,
1155
+ use(data) {
1156
+ return transformUse(data, plugin, TRANSFORM_LOADER);
1157
+ }
1158
+ });
1159
+ if (plugin.webpack) plugin.webpack(compiler);
1160
+ if (plugin.watchChange || plugin.buildStart) compiler.hooks.make.tapPromise(plugin.name, async (compilation) => {
1161
+ const context = createBuildContext$3(contextOptionsFromCompilation(compilation), compiler, compilation);
1162
+ if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) {
1163
+ const promises = [];
1164
+ if (compiler.modifiedFiles) compiler.modifiedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "update" }))));
1165
+ if (compiler.removedFiles) compiler.removedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "delete" }))));
1166
+ await Promise.all(promises);
1167
+ }
1168
+ if (plugin.buildStart) return await plugin.buildStart.call(context);
1169
+ });
1170
+ if (plugin.buildEnd) compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => {
1171
+ await plugin.buildEnd.call(createBuildContext$3(contextOptionsFromCompilation(compilation), compiler, compilation));
1172
+ });
1173
+ if (plugin.writeBundle) compiler.hooks.afterEmit.tapPromise(plugin.name, async () => {
1174
+ await plugin.writeBundle();
1175
+ });
1176
+ }
1177
+ } };
1178
+ };
1179
+ }
1180
+ function shouldLoad(id, plugin, externalModules) {
1181
+ if (id.startsWith(plugin.__virtualModulePrefix)) id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length));
1182
+ if (plugin.loadInclude && !plugin.loadInclude(id)) return false;
1183
+ const { filter } = normalizeObjectHook("load", plugin.load);
1184
+ if (!filter(id)) return false;
1185
+ return !externalModules.has(id);
1186
+ }
1187
+ //#endregion
1188
+ //#region src/define.ts
1189
+ function createUnplugin(factory) {
1190
+ return {
1191
+ get esbuild() {
1192
+ return getEsbuildPlugin(factory);
1193
+ },
1194
+ get rollup() {
1195
+ return getRollupPlugin(factory);
1196
+ },
1197
+ get vite() {
1198
+ return getVitePlugin(factory);
1199
+ },
1200
+ get rolldown() {
1201
+ return getRolldownPlugin(factory);
1202
+ },
1203
+ get webpack() {
1204
+ return getWebpackPlugin(factory);
1205
+ },
1206
+ get rspack() {
1207
+ return getRspackPlugin(factory);
1208
+ },
1209
+ get farm() {
1210
+ return getFarmPlugin(factory);
1211
+ },
1212
+ get unloader() {
1213
+ return getUnloaderPlugin(factory);
1214
+ },
1215
+ get bun() {
1216
+ return getBunPlugin(factory);
1217
+ },
1218
+ get raw() {
1219
+ return factory;
1220
+ }
1221
+ };
1222
+ }
1223
+ function createEsbuildPlugin(factory) {
1224
+ return getEsbuildPlugin(factory);
1225
+ }
1226
+ function createRollupPlugin(factory) {
1227
+ return getRollupPlugin(factory);
1228
+ }
1229
+ function createVitePlugin(factory) {
1230
+ return getVitePlugin(factory);
1231
+ }
1232
+ function createRolldownPlugin(factory) {
1233
+ return getRolldownPlugin(factory);
1234
+ }
1235
+ function createWebpackPlugin(factory) {
1236
+ return getWebpackPlugin(factory);
1237
+ }
1238
+ function createRspackPlugin(factory) {
1239
+ return getRspackPlugin(factory);
1240
+ }
1241
+ function createFarmPlugin(factory) {
1242
+ return getFarmPlugin(factory);
1243
+ }
1244
+ function createUnloaderPlugin(factory) {
1245
+ return getUnloaderPlugin(factory);
1246
+ }
1247
+ function createBunPlugin(factory) {
1248
+ return getBunPlugin(factory);
1249
+ }
1250
+ //#endregion
1251
+ //#region src/index.ts
1252
+ const version = version$1;
1253
+ //#endregion
1254
+ export { createBunPlugin, createEsbuildPlugin, createFarmPlugin, createRolldownPlugin, createRollupPlugin, createRspackPlugin, createUnloaderPlugin, createUnplugin, createVitePlugin, createWebpackPlugin, setParseImpl, version };