1 |
|
2 | import { fileURLToPath } from "url";
|
3 | import path from "path";
|
4 | var getFilename = () => fileURLToPath(import.meta.url);
|
5 | var getDirname = () => path.dirname(getFilename());
|
6 | var __dirname = getDirname();
|
7 |
|
8 |
|
9 | import fs2 from "fs";
|
10 | import path3 from "path";
|
11 |
|
12 |
|
13 | import fs from "fs";
|
14 | import path2 from "path";
|
15 | import { Buffer as Buffer2 } from "buffer";
|
16 |
|
17 |
|
18 | var comma = ",".charCodeAt(0);
|
19 | var semicolon = ";".charCodeAt(0);
|
20 | var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
21 | var intToChar = new Uint8Array(64);
|
22 | var charToInt = new Uint8Array(128);
|
23 | for (let i = 0; i < chars.length; i++) {
|
24 | const c = chars.charCodeAt(i);
|
25 | intToChar[i] = c;
|
26 | charToInt[c] = i;
|
27 | }
|
28 | function decodeInteger(reader, relative) {
|
29 | let value = 0;
|
30 | let shift = 0;
|
31 | let integer = 0;
|
32 | do {
|
33 | const c = reader.next();
|
34 | integer = charToInt[c];
|
35 | value |= (integer & 31) << shift;
|
36 | shift += 5;
|
37 | } while (integer & 32);
|
38 | const shouldNegate = value & 1;
|
39 | value >>>= 1;
|
40 | if (shouldNegate) {
|
41 | value = -2147483648 | -value;
|
42 | }
|
43 | return relative + value;
|
44 | }
|
45 | function encodeInteger(builder, num, relative) {
|
46 | let delta = num - relative;
|
47 | delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
|
48 | do {
|
49 | let clamped = delta & 31;
|
50 | delta >>>= 5;
|
51 | if (delta > 0)
|
52 | clamped |= 32;
|
53 | builder.write(intToChar[clamped]);
|
54 | } while (delta > 0);
|
55 | return num;
|
56 | }
|
57 | function hasMoreVlq(reader, max) {
|
58 | if (reader.pos >= max)
|
59 | return false;
|
60 | return reader.peek() !== comma;
|
61 | }
|
62 | var bufLength = 1024 * 16;
|
63 | var td = typeof TextDecoder !== "undefined" ? new TextDecoder() : typeof Buffer !== "undefined" ? {
|
64 | decode(buf) {
|
65 | const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
|
66 | return out.toString();
|
67 | }
|
68 | } : {
|
69 | decode(buf) {
|
70 | let out = "";
|
71 | for (let i = 0; i < buf.length; i++) {
|
72 | out += String.fromCharCode(buf[i]);
|
73 | }
|
74 | return out;
|
75 | }
|
76 | };
|
77 | var StringWriter = class {
|
78 | constructor() {
|
79 | this.pos = 0;
|
80 | this.out = "";
|
81 | this.buffer = new Uint8Array(bufLength);
|
82 | }
|
83 | write(v) {
|
84 | const { buffer } = this;
|
85 | buffer[this.pos++] = v;
|
86 | if (this.pos === bufLength) {
|
87 | this.out += td.decode(buffer);
|
88 | this.pos = 0;
|
89 | }
|
90 | }
|
91 | flush() {
|
92 | const { buffer, out, pos } = this;
|
93 | return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
|
94 | }
|
95 | };
|
96 | var StringReader = class {
|
97 | constructor(buffer) {
|
98 | this.pos = 0;
|
99 | this.buffer = buffer;
|
100 | }
|
101 | next() {
|
102 | return this.buffer.charCodeAt(this.pos++);
|
103 | }
|
104 | peek() {
|
105 | return this.buffer.charCodeAt(this.pos);
|
106 | }
|
107 | indexOf(char) {
|
108 | const { buffer, pos } = this;
|
109 | const idx = buffer.indexOf(char, pos);
|
110 | return idx === -1 ? buffer.length : idx;
|
111 | }
|
112 | };
|
113 | function decode(mappings) {
|
114 | const { length } = mappings;
|
115 | const reader = new StringReader(mappings);
|
116 | const decoded = [];
|
117 | let genColumn = 0;
|
118 | let sourcesIndex = 0;
|
119 | let sourceLine = 0;
|
120 | let sourceColumn = 0;
|
121 | let namesIndex = 0;
|
122 | do {
|
123 | const semi = reader.indexOf(";");
|
124 | const line = [];
|
125 | let sorted = true;
|
126 | let lastCol = 0;
|
127 | genColumn = 0;
|
128 | while (reader.pos < semi) {
|
129 | let seg;
|
130 | genColumn = decodeInteger(reader, genColumn);
|
131 | if (genColumn < lastCol)
|
132 | sorted = false;
|
133 | lastCol = genColumn;
|
134 | if (hasMoreVlq(reader, semi)) {
|
135 | sourcesIndex = decodeInteger(reader, sourcesIndex);
|
136 | sourceLine = decodeInteger(reader, sourceLine);
|
137 | sourceColumn = decodeInteger(reader, sourceColumn);
|
138 | if (hasMoreVlq(reader, semi)) {
|
139 | namesIndex = decodeInteger(reader, namesIndex);
|
140 | seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
|
141 | } else {
|
142 | seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
|
143 | }
|
144 | } else {
|
145 | seg = [genColumn];
|
146 | }
|
147 | line.push(seg);
|
148 | reader.pos++;
|
149 | }
|
150 | if (!sorted)
|
151 | sort(line);
|
152 | decoded.push(line);
|
153 | reader.pos = semi + 1;
|
154 | } while (reader.pos <= length);
|
155 | return decoded;
|
156 | }
|
157 | function sort(line) {
|
158 | line.sort(sortComparator);
|
159 | }
|
160 | function sortComparator(a, b) {
|
161 | return a[0] - b[0];
|
162 | }
|
163 | function encode(decoded) {
|
164 | const writer = new StringWriter();
|
165 | let sourcesIndex = 0;
|
166 | let sourceLine = 0;
|
167 | let sourceColumn = 0;
|
168 | let namesIndex = 0;
|
169 | for (let i = 0; i < decoded.length; i++) {
|
170 | const line = decoded[i];
|
171 | if (i > 0)
|
172 | writer.write(semicolon);
|
173 | if (line.length === 0)
|
174 | continue;
|
175 | let genColumn = 0;
|
176 | for (let j = 0; j < line.length; j++) {
|
177 | const segment = line[j];
|
178 | if (j > 0)
|
179 | writer.write(comma);
|
180 | genColumn = encodeInteger(writer, segment[0], genColumn);
|
181 | if (segment.length === 1)
|
182 | continue;
|
183 | sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
|
184 | sourceLine = encodeInteger(writer, segment[2], sourceLine);
|
185 | sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
|
186 | if (segment.length === 4)
|
187 | continue;
|
188 | namesIndex = encodeInteger(writer, segment[4], namesIndex);
|
189 | }
|
190 | }
|
191 | return writer.flush();
|
192 | }
|
193 |
|
194 |
|
195 | var schemeRegex = /^[\w+.-]+:\/\//;
|
196 | var urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
|
197 | var fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
|
198 | function isAbsoluteUrl(input) {
|
199 | return schemeRegex.test(input);
|
200 | }
|
201 | function isSchemeRelativeUrl(input) {
|
202 | return input.startsWith("//");
|
203 | }
|
204 | function isAbsolutePath(input) {
|
205 | return input.startsWith("/");
|
206 | }
|
207 | function isFileUrl(input) {
|
208 | return input.startsWith("file:");
|
209 | }
|
210 | function isRelative(input) {
|
211 | return /^[.?#]/.test(input);
|
212 | }
|
213 | function parseAbsoluteUrl(input) {
|
214 | const match = urlRegex.exec(input);
|
215 | return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || "");
|
216 | }
|
217 | function parseFileUrl(input) {
|
218 | const match = fileRegex.exec(input);
|
219 | const path6 = match[2];
|
220 | return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path6) ? path6 : "/" + path6, match[3] || "", match[4] || "");
|
221 | }
|
222 | function makeUrl(scheme, user, host, port, path6, query, hash) {
|
223 | return {
|
224 | scheme,
|
225 | user,
|
226 | host,
|
227 | port,
|
228 | path: path6,
|
229 | query,
|
230 | hash,
|
231 | type: 7
|
232 | };
|
233 | }
|
234 | function parseUrl(input) {
|
235 | if (isSchemeRelativeUrl(input)) {
|
236 | const url2 = parseAbsoluteUrl("http:" + input);
|
237 | url2.scheme = "";
|
238 | url2.type = 6;
|
239 | return url2;
|
240 | }
|
241 | if (isAbsolutePath(input)) {
|
242 | const url2 = parseAbsoluteUrl("http://foo.com" + input);
|
243 | url2.scheme = "";
|
244 | url2.host = "";
|
245 | url2.type = 5;
|
246 | return url2;
|
247 | }
|
248 | if (isFileUrl(input))
|
249 | return parseFileUrl(input);
|
250 | if (isAbsoluteUrl(input))
|
251 | return parseAbsoluteUrl(input);
|
252 | const url = parseAbsoluteUrl("http://foo.com/" + input);
|
253 | url.scheme = "";
|
254 | url.host = "";
|
255 | url.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1;
|
256 | return url;
|
257 | }
|
258 | function stripPathFilename(path6) {
|
259 | if (path6.endsWith("/.."))
|
260 | return path6;
|
261 | const index = path6.lastIndexOf("/");
|
262 | return path6.slice(0, index + 1);
|
263 | }
|
264 | function mergePaths(url, base) {
|
265 | normalizePath(base, base.type);
|
266 | if (url.path === "/") {
|
267 | url.path = base.path;
|
268 | } else {
|
269 | url.path = stripPathFilename(base.path) + url.path;
|
270 | }
|
271 | }
|
272 | function normalizePath(url, type) {
|
273 | const rel = type <= 4;
|
274 | const pieces = url.path.split("/");
|
275 | let pointer = 1;
|
276 | let positive = 0;
|
277 | let addTrailingSlash = false;
|
278 | for (let i = 1; i < pieces.length; i++) {
|
279 | const piece = pieces[i];
|
280 | if (!piece) {
|
281 | addTrailingSlash = true;
|
282 | continue;
|
283 | }
|
284 | addTrailingSlash = false;
|
285 | if (piece === ".")
|
286 | continue;
|
287 | if (piece === "..") {
|
288 | if (positive) {
|
289 | addTrailingSlash = true;
|
290 | positive--;
|
291 | pointer--;
|
292 | } else if (rel) {
|
293 | pieces[pointer++] = piece;
|
294 | }
|
295 | continue;
|
296 | }
|
297 | pieces[pointer++] = piece;
|
298 | positive++;
|
299 | }
|
300 | let path6 = "";
|
301 | for (let i = 1; i < pointer; i++) {
|
302 | path6 += "/" + pieces[i];
|
303 | }
|
304 | if (!path6 || addTrailingSlash && !path6.endsWith("/..")) {
|
305 | path6 += "/";
|
306 | }
|
307 | url.path = path6;
|
308 | }
|
309 | function resolve(input, base) {
|
310 | if (!input && !base)
|
311 | return "";
|
312 | const url = parseUrl(input);
|
313 | let inputType = url.type;
|
314 | if (base && inputType !== 7) {
|
315 | const baseUrl = parseUrl(base);
|
316 | const baseType = baseUrl.type;
|
317 | switch (inputType) {
|
318 | case 1:
|
319 | url.hash = baseUrl.hash;
|
320 | case 2:
|
321 | url.query = baseUrl.query;
|
322 | case 3:
|
323 | case 4:
|
324 | mergePaths(url, baseUrl);
|
325 | case 5:
|
326 | url.user = baseUrl.user;
|
327 | url.host = baseUrl.host;
|
328 | url.port = baseUrl.port;
|
329 | case 6:
|
330 | url.scheme = baseUrl.scheme;
|
331 | }
|
332 | if (baseType > inputType)
|
333 | inputType = baseType;
|
334 | }
|
335 | normalizePath(url, inputType);
|
336 | const queryHash = url.query + url.hash;
|
337 | switch (inputType) {
|
338 | case 2:
|
339 | case 3:
|
340 | return queryHash;
|
341 | case 4: {
|
342 | const path6 = url.path.slice(1);
|
343 | if (!path6)
|
344 | return queryHash || ".";
|
345 | if (isRelative(base || input) && !isRelative(path6)) {
|
346 | return "./" + path6 + queryHash;
|
347 | }
|
348 | return path6 + queryHash;
|
349 | }
|
350 | case 5:
|
351 | return url.path + queryHash;
|
352 | default:
|
353 | return url.scheme + "//" + url.user + url.host + url.port + url.path + queryHash;
|
354 | }
|
355 | }
|
356 |
|
357 |
|
358 | function resolve2(input, base) {
|
359 | if (base && !base.endsWith("/"))
|
360 | base += "/";
|
361 | return resolve(input, base);
|
362 | }
|
363 | function stripFilename(path6) {
|
364 | if (!path6)
|
365 | return "";
|
366 | const index = path6.lastIndexOf("/");
|
367 | return path6.slice(0, index + 1);
|
368 | }
|
369 | var COLUMN = 0;
|
370 | function maybeSort(mappings, owned) {
|
371 | const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
|
372 | if (unsortedIndex === mappings.length)
|
373 | return mappings;
|
374 | if (!owned)
|
375 | mappings = mappings.slice();
|
376 | for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
|
377 | mappings[i] = sortSegments(mappings[i], owned);
|
378 | }
|
379 | return mappings;
|
380 | }
|
381 | function nextUnsortedSegmentLine(mappings, start) {
|
382 | for (let i = start; i < mappings.length; i++) {
|
383 | if (!isSorted(mappings[i]))
|
384 | return i;
|
385 | }
|
386 | return mappings.length;
|
387 | }
|
388 | function isSorted(line) {
|
389 | for (let j = 1; j < line.length; j++) {
|
390 | if (line[j][COLUMN] < line[j - 1][COLUMN]) {
|
391 | return false;
|
392 | }
|
393 | }
|
394 | return true;
|
395 | }
|
396 | function sortSegments(line, owned) {
|
397 | if (!owned)
|
398 | line = line.slice();
|
399 | return line.sort(sortComparator2);
|
400 | }
|
401 | function sortComparator2(a, b) {
|
402 | return a[COLUMN] - b[COLUMN];
|
403 | }
|
404 | var found = false;
|
405 | function binarySearch(haystack, needle, low, high) {
|
406 | while (low <= high) {
|
407 | const mid = low + (high - low >> 1);
|
408 | const cmp = haystack[mid][COLUMN] - needle;
|
409 | if (cmp === 0) {
|
410 | found = true;
|
411 | return mid;
|
412 | }
|
413 | if (cmp < 0) {
|
414 | low = mid + 1;
|
415 | } else {
|
416 | high = mid - 1;
|
417 | }
|
418 | }
|
419 | found = false;
|
420 | return low - 1;
|
421 | }
|
422 | function upperBound(haystack, needle, index) {
|
423 | for (let i = index + 1; i < haystack.length; index = i++) {
|
424 | if (haystack[i][COLUMN] !== needle)
|
425 | break;
|
426 | }
|
427 | return index;
|
428 | }
|
429 | function lowerBound(haystack, needle, index) {
|
430 | for (let i = index - 1; i >= 0; index = i--) {
|
431 | if (haystack[i][COLUMN] !== needle)
|
432 | break;
|
433 | }
|
434 | return index;
|
435 | }
|
436 | function memoizedState() {
|
437 | return {
|
438 | lastKey: -1,
|
439 | lastNeedle: -1,
|
440 | lastIndex: -1
|
441 | };
|
442 | }
|
443 | function memoizedBinarySearch(haystack, needle, state, key) {
|
444 | const { lastKey, lastNeedle, lastIndex } = state;
|
445 | let low = 0;
|
446 | let high = haystack.length - 1;
|
447 | if (key === lastKey) {
|
448 | if (needle === lastNeedle) {
|
449 | found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
|
450 | return lastIndex;
|
451 | }
|
452 | if (needle >= lastNeedle) {
|
453 | low = lastIndex === -1 ? 0 : lastIndex;
|
454 | } else {
|
455 | high = lastIndex;
|
456 | }
|
457 | }
|
458 | state.lastKey = key;
|
459 | state.lastNeedle = needle;
|
460 | return state.lastIndex = binarySearch(haystack, needle, low, high);
|
461 | }
|
462 | var LEAST_UPPER_BOUND = -1;
|
463 | var GREATEST_LOWER_BOUND = 1;
|
464 | var TraceMap = class {
|
465 | constructor(map, mapUrl) {
|
466 | const isString2 = typeof map === "string";
|
467 | if (!isString2 && map._decodedMemo)
|
468 | return map;
|
469 | const parsed = isString2 ? JSON.parse(map) : map;
|
470 | const { version, file, names, sourceRoot, sources: sources2, sourcesContent } = parsed;
|
471 | this.version = version;
|
472 | this.file = file;
|
473 | this.names = names || [];
|
474 | this.sourceRoot = sourceRoot;
|
475 | this.sources = sources2;
|
476 | this.sourcesContent = sourcesContent;
|
477 | this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0;
|
478 | const from = resolve2(sourceRoot || "", stripFilename(mapUrl));
|
479 | this.resolvedSources = sources2.map((s) => resolve2(s || "", from));
|
480 | const { mappings } = parsed;
|
481 | if (typeof mappings === "string") {
|
482 | this._encoded = mappings;
|
483 | this._decoded = void 0;
|
484 | } else {
|
485 | this._encoded = void 0;
|
486 | this._decoded = maybeSort(mappings, isString2);
|
487 | }
|
488 | this._decodedMemo = memoizedState();
|
489 | this._bySources = void 0;
|
490 | this._bySourceMemos = void 0;
|
491 | }
|
492 | };
|
493 | function cast(map) {
|
494 | return map;
|
495 | }
|
496 | function decodedMappings(map) {
|
497 | var _a;
|
498 | return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded));
|
499 | }
|
500 | function traceSegment(map, line, column) {
|
501 | const decoded = decodedMappings(map);
|
502 | if (line >= decoded.length)
|
503 | return null;
|
504 | const segments = decoded[line];
|
505 | const index = traceSegmentInternal(segments, cast(map)._decodedMemo, line, column, GREATEST_LOWER_BOUND);
|
506 | return index === -1 ? null : segments[index];
|
507 | }
|
508 | function traceSegmentInternal(segments, memo, line, column, bias) {
|
509 | let index = memoizedBinarySearch(segments, column, memo, line);
|
510 | if (found) {
|
511 | index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
|
512 | } else if (bias === LEAST_UPPER_BOUND)
|
513 | index++;
|
514 | if (index === -1 || index === segments.length)
|
515 | return -1;
|
516 | return index;
|
517 | }
|
518 |
|
519 |
|
520 | var SetArray = class {
|
521 | constructor() {
|
522 | this._indexes = { __proto__: null };
|
523 | this.array = [];
|
524 | }
|
525 | };
|
526 | function cast2(set) {
|
527 | return set;
|
528 | }
|
529 | function get(setarr, key) {
|
530 | return cast2(setarr)._indexes[key];
|
531 | }
|
532 | function put(setarr, key) {
|
533 | const index = get(setarr, key);
|
534 | if (index !== void 0)
|
535 | return index;
|
536 | const { array, _indexes: indexes } = cast2(setarr);
|
537 | const length = array.push(key);
|
538 | return indexes[key] = length - 1;
|
539 | }
|
540 | function remove(setarr, key) {
|
541 | const index = get(setarr, key);
|
542 | if (index === void 0)
|
543 | return;
|
544 | const { array, _indexes: indexes } = cast2(setarr);
|
545 | for (let i = index + 1; i < array.length; i++) {
|
546 | const k = array[i];
|
547 | array[i - 1] = k;
|
548 | indexes[k]--;
|
549 | }
|
550 | indexes[key] = void 0;
|
551 | array.pop();
|
552 | }
|
553 |
|
554 |
|
555 | var COLUMN2 = 0;
|
556 | var SOURCES_INDEX = 1;
|
557 | var SOURCE_LINE = 2;
|
558 | var SOURCE_COLUMN = 3;
|
559 | var NAMES_INDEX = 4;
|
560 | var NO_NAME = -1;
|
561 | var GenMapping = class {
|
562 | constructor({ file, sourceRoot } = {}) {
|
563 | this._names = new SetArray();
|
564 | this._sources = new SetArray();
|
565 | this._sourcesContent = [];
|
566 | this._mappings = [];
|
567 | this.file = file;
|
568 | this.sourceRoot = sourceRoot;
|
569 | this._ignoreList = new SetArray();
|
570 | }
|
571 | };
|
572 | function cast3(map) {
|
573 | return map;
|
574 | }
|
575 | var maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
|
576 | return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content);
|
577 | };
|
578 | function setSourceContent(map, source, content) {
|
579 | const { _sources: sources2, _sourcesContent: sourcesContent } = cast3(map);
|
580 | const index = put(sources2, source);
|
581 | sourcesContent[index] = content;
|
582 | }
|
583 | function setIgnore(map, source, ignore = true) {
|
584 | const { _sources: sources2, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast3(map);
|
585 | const index = put(sources2, source);
|
586 | if (index === sourcesContent.length)
|
587 | sourcesContent[index] = null;
|
588 | if (ignore)
|
589 | put(ignoreList, index);
|
590 | else
|
591 | remove(ignoreList, index);
|
592 | }
|
593 | function toDecodedMap(map) {
|
594 | const { _mappings: mappings, _sources: sources2, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList } = cast3(map);
|
595 | removeEmptyFinalLines(mappings);
|
596 | return {
|
597 | version: 3,
|
598 | file: map.file || void 0,
|
599 | names: names.array,
|
600 | sourceRoot: map.sourceRoot || void 0,
|
601 | sources: sources2.array,
|
602 | sourcesContent,
|
603 | mappings,
|
604 | ignoreList: ignoreList.array
|
605 | };
|
606 | }
|
607 | function toEncodedMap(map) {
|
608 | const decoded = toDecodedMap(map);
|
609 | return Object.assign(Object.assign({}, decoded), { mappings: encode(decoded.mappings) });
|
610 | }
|
611 | function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) {
|
612 | const { _mappings: mappings, _sources: sources2, _sourcesContent: sourcesContent, _names: names } = cast3(map);
|
613 | const line = getLine(mappings, genLine);
|
614 | const index = getColumnIndex(line, genColumn);
|
615 | if (!source) {
|
616 | if (skipable && skipSourceless(line, index))
|
617 | return;
|
618 | return insert(line, index, [genColumn]);
|
619 | }
|
620 | const sourcesIndex = put(sources2, source);
|
621 | const namesIndex = name ? put(names, name) : NO_NAME;
|
622 | if (sourcesIndex === sourcesContent.length)
|
623 | sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null;
|
624 | if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
|
625 | return;
|
626 | }
|
627 | return insert(line, index, name ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] : [genColumn, sourcesIndex, sourceLine, sourceColumn]);
|
628 | }
|
629 | function getLine(mappings, index) {
|
630 | for (let i = mappings.length; i <= index; i++) {
|
631 | mappings[i] = [];
|
632 | }
|
633 | return mappings[index];
|
634 | }
|
635 | function getColumnIndex(line, genColumn) {
|
636 | let index = line.length;
|
637 | for (let i = index - 1; i >= 0; index = i--) {
|
638 | const current = line[i];
|
639 | if (genColumn >= current[COLUMN2])
|
640 | break;
|
641 | }
|
642 | return index;
|
643 | }
|
644 | function insert(array, index, value) {
|
645 | for (let i = array.length; i > index; i--) {
|
646 | array[i] = array[i - 1];
|
647 | }
|
648 | array[index] = value;
|
649 | }
|
650 | function removeEmptyFinalLines(mappings) {
|
651 | const { length } = mappings;
|
652 | let len = length;
|
653 | for (let i = len - 1; i >= 0; len = i, i--) {
|
654 | if (mappings[i].length > 0)
|
655 | break;
|
656 | }
|
657 | if (len < length)
|
658 | mappings.length = len;
|
659 | }
|
660 | function skipSourceless(line, index) {
|
661 | if (index === 0)
|
662 | return true;
|
663 | const prev = line[index - 1];
|
664 | return prev.length === 1;
|
665 | }
|
666 | function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
|
667 | if (index === 0)
|
668 | return false;
|
669 | const prev = line[index - 1];
|
670 | if (prev.length === 1)
|
671 | return false;
|
672 | return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME);
|
673 | }
|
674 |
|
675 |
|
676 | var SOURCELESS_MAPPING = SegmentObject("", -1, -1, "", null, false);
|
677 | var EMPTY_SOURCES = [];
|
678 | function SegmentObject(source, line, column, name, content, ignore) {
|
679 | return { source, line, column, name, content, ignore };
|
680 | }
|
681 | function Source(map, sources2, source, content, ignore) {
|
682 | return {
|
683 | map,
|
684 | sources: sources2,
|
685 | source,
|
686 | content,
|
687 | ignore
|
688 | };
|
689 | }
|
690 | function MapSource(map, sources2) {
|
691 | return Source(map, sources2, "", null, false);
|
692 | }
|
693 | function OriginalSource(source, content, ignore) {
|
694 | return Source(null, EMPTY_SOURCES, source, content, ignore);
|
695 | }
|
696 | function traceMappings(tree) {
|
697 | const gen = new GenMapping({ file: tree.map.file });
|
698 | const { sources: rootSources, map } = tree;
|
699 | const rootNames = map.names;
|
700 | const rootMappings = decodedMappings(map);
|
701 | for (let i = 0; i < rootMappings.length; i++) {
|
702 | const segments = rootMappings[i];
|
703 | for (let j = 0; j < segments.length; j++) {
|
704 | const segment = segments[j];
|
705 | const genCol = segment[0];
|
706 | let traced = SOURCELESS_MAPPING;
|
707 | if (segment.length !== 1) {
|
708 | const source2 = rootSources[segment[1]];
|
709 | traced = originalPositionFor(source2, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : "");
|
710 | if (traced == null)
|
711 | continue;
|
712 | }
|
713 | const { column, line, name, content, source, ignore } = traced;
|
714 | maybeAddSegment(gen, i, genCol, source, line, column, name);
|
715 | if (source && content != null)
|
716 | setSourceContent(gen, source, content);
|
717 | if (ignore)
|
718 | setIgnore(gen, source, true);
|
719 | }
|
720 | }
|
721 | return gen;
|
722 | }
|
723 | function originalPositionFor(source, line, column, name) {
|
724 | if (!source.map) {
|
725 | return SegmentObject(source.source, line, column, name, source.content, source.ignore);
|
726 | }
|
727 | const segment = traceSegment(source.map, line, column);
|
728 | if (segment == null)
|
729 | return null;
|
730 | if (segment.length === 1)
|
731 | return SOURCELESS_MAPPING;
|
732 | return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name);
|
733 | }
|
734 | function asArray(value) {
|
735 | if (Array.isArray(value))
|
736 | return value;
|
737 | return [value];
|
738 | }
|
739 | function buildSourceMapTree(input, loader) {
|
740 | const maps = asArray(input).map((m) => new TraceMap(m, ""));
|
741 | const map = maps.pop();
|
742 | for (let i = 0; i < maps.length; i++) {
|
743 | if (maps[i].sources.length > 1) {
|
744 | throw new Error(`Transformation map ${i} must have exactly one source file.
|
745 | Did you specify these with the most recent transformation maps first?`);
|
746 | }
|
747 | }
|
748 | let tree = build(map, loader, "", 0);
|
749 | for (let i = maps.length - 1; i >= 0; i--) {
|
750 | tree = MapSource(maps[i], [tree]);
|
751 | }
|
752 | return tree;
|
753 | }
|
754 | function build(map, loader, importer, importerDepth) {
|
755 | const { resolvedSources, sourcesContent, ignoreList } = map;
|
756 | const depth = importerDepth + 1;
|
757 | const children = resolvedSources.map((sourceFile, i) => {
|
758 | const ctx = {
|
759 | importer,
|
760 | depth,
|
761 | source: sourceFile || "",
|
762 | content: void 0,
|
763 | ignore: void 0
|
764 | };
|
765 | const sourceMap = loader(ctx.source, ctx);
|
766 | const { source, content, ignore } = ctx;
|
767 | if (sourceMap)
|
768 | return build(new TraceMap(sourceMap, source), loader, source, depth);
|
769 | const sourceContent = content !== void 0 ? content : sourcesContent ? sourcesContent[i] : null;
|
770 | const ignored = ignore !== void 0 ? ignore : ignoreList ? ignoreList.includes(i) : false;
|
771 | return OriginalSource(source, sourceContent, ignored);
|
772 | });
|
773 | return MapSource(map, children);
|
774 | }
|
775 | var SourceMap = class {
|
776 | constructor(map, options) {
|
777 | const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);
|
778 | this.version = out.version;
|
779 | this.file = out.file;
|
780 | this.mappings = out.mappings;
|
781 | this.names = out.names;
|
782 | this.ignoreList = out.ignoreList;
|
783 | this.sourceRoot = out.sourceRoot;
|
784 | this.sources = out.sources;
|
785 | if (!options.excludeContent) {
|
786 | this.sourcesContent = out.sourcesContent;
|
787 | }
|
788 | }
|
789 | toString() {
|
790 | return JSON.stringify(this);
|
791 | }
|
792 | };
|
793 | function remapping(input, loader, options) {
|
794 | const opts = typeof options === "object" ? options : { excludeContent: !!options, decodedMappings: false };
|
795 | const tree = buildSourceMapTree(input, loader);
|
796 | return new SourceMap(traceMappings(tree), opts);
|
797 | }
|
798 |
|
799 |
|
800 | import { Parser } from "acorn";
|
801 |
|
802 |
|
803 | import { isAbsolute, normalize } from "path";
|
804 | function normalizeAbsolutePath(path6) {
|
805 | if (isAbsolute(path6))
|
806 | return normalize(path6);
|
807 | else
|
808 | return path6;
|
809 | }
|
810 | function toArray(array) {
|
811 | array = array || [];
|
812 | if (Array.isArray(array))
|
813 | return array;
|
814 | return [array];
|
815 | }
|
816 | function shouldLoad(id, plugin, externalModules) {
|
817 | if (id.startsWith(plugin.__virtualModulePrefix))
|
818 | id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length));
|
819 | if (plugin.loadInclude && !plugin.loadInclude(id))
|
820 | return false;
|
821 | return !externalModules.has(id);
|
822 | }
|
823 | function transformUse(data, plugin, transformLoader) {
|
824 | if (data.resource == null)
|
825 | return [];
|
826 | const id = normalizeAbsolutePath(data.resource + (data.resourceQuery || ""));
|
827 | if (!plugin.transformInclude || plugin.transformInclude(id)) {
|
828 | return [{
|
829 | loader: `${transformLoader}?unpluginName=${encodeURIComponent(plugin.name)}`
|
830 | }];
|
831 | }
|
832 | return [];
|
833 | }
|
834 |
|
835 |
|
836 | var ExtToLoader = {
|
837 | ".js": "js",
|
838 | ".mjs": "js",
|
839 | ".cjs": "js",
|
840 | ".jsx": "jsx",
|
841 | ".ts": "ts",
|
842 | ".cts": "ts",
|
843 | ".mts": "ts",
|
844 | ".tsx": "tsx",
|
845 | ".css": "css",
|
846 | ".less": "css",
|
847 | ".stylus": "css",
|
848 | ".scss": "css",
|
849 | ".sass": "css",
|
850 | ".json": "json",
|
851 | ".txt": "text"
|
852 | };
|
853 | function guessLoader(code, id) {
|
854 | return ExtToLoader[path2.extname(id).toLowerCase()] || "js";
|
855 | }
|
856 | function unwrapLoader(loader, code, id) {
|
857 | if (typeof loader === "function")
|
858 | return loader(code, id);
|
859 | return loader;
|
860 | }
|
861 | function fixSourceMap(map) {
|
862 | if (!Object.prototype.hasOwnProperty.call(map, "toString")) {
|
863 | Object.defineProperty(map, "toString", {
|
864 | enumerable: false,
|
865 | value: function toString() {
|
866 | return JSON.stringify(this);
|
867 | }
|
868 | });
|
869 | }
|
870 | if (!Object.prototype.hasOwnProperty.call(map, "toUrl")) {
|
871 | Object.defineProperty(map, "toUrl", {
|
872 | enumerable: false,
|
873 | value: function toUrl() {
|
874 | return `data:application/json;charset=utf-8;base64,${Buffer2.from(this.toString()).toString("base64")}`;
|
875 | }
|
876 | });
|
877 | }
|
878 | return map;
|
879 | }
|
880 | var nullSourceMap = {
|
881 | names: [],
|
882 | sources: [],
|
883 | mappings: "",
|
884 | version: 3
|
885 | };
|
886 | function combineSourcemaps(filename, sourcemapList) {
|
887 | sourcemapList = sourcemapList.filter((m) => m.sources);
|
888 | if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0)) {
|
889 | return { ...nullSourceMap };
|
890 | }
|
891 | let map;
|
892 | let mapIndex = 1;
|
893 | const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === void 0;
|
894 | if (useArrayInterface) {
|
895 | map = remapping(sourcemapList, () => null, true);
|
896 | } else {
|
897 | map = remapping(
|
898 | sourcemapList[0],
|
899 | (sourcefile) => {
|
900 | if (sourcefile === filename && sourcemapList[mapIndex])
|
901 | return sourcemapList[mapIndex++];
|
902 | else
|
903 | return { ...nullSourceMap };
|
904 | },
|
905 | true
|
906 | );
|
907 | }
|
908 | if (!map.file)
|
909 | delete map.file;
|
910 | return map;
|
911 | }
|
912 | function createBuildContext(initialOptions) {
|
913 | const watchFiles = [];
|
914 | return {
|
915 | parse(code, opts = {}) {
|
916 | return Parser.parse(code, {
|
917 | sourceType: "module",
|
918 | ecmaVersion: "latest",
|
919 | locations: true,
|
920 | ...opts
|
921 | });
|
922 | },
|
923 | addWatchFile() {
|
924 | throw new Error("unplugin/esbuild: addWatchFile outside supported hooks (resolveId, load, transform)");
|
925 | },
|
926 | emitFile(emittedFile) {
|
927 | const outFileName = emittedFile.fileName || emittedFile.name;
|
928 | if (initialOptions.outdir && emittedFile.source && outFileName) {
|
929 | const outPath = path2.resolve(initialOptions.outdir, outFileName);
|
930 | const outDir = path2.dirname(outPath);
|
931 | if (!fs.existsSync(outDir))
|
932 | fs.mkdirSync(outDir, { recursive: true });
|
933 | fs.writeFileSync(outPath, emittedFile.source);
|
934 | }
|
935 | },
|
936 | getWatchFiles() {
|
937 | return watchFiles;
|
938 | }
|
939 | };
|
940 | }
|
941 | function createPluginContext(context) {
|
942 | const errors = [];
|
943 | const warnings = [];
|
944 | const pluginContext = {
|
945 | error(message) {
|
946 | errors.push(normalizeMessage(message));
|
947 | },
|
948 | warn(message) {
|
949 | warnings.push(normalizeMessage(message));
|
950 | }
|
951 | };
|
952 | const mixedContext = {
|
953 | ...context,
|
954 | ...pluginContext,
|
955 | addWatchFile(id) {
|
956 | context.getWatchFiles().push(id);
|
957 | }
|
958 | };
|
959 | return {
|
960 | errors,
|
961 | warnings,
|
962 | mixedContext
|
963 | };
|
964 | }
|
965 | function normalizeMessage(message) {
|
966 | if (typeof message === "string")
|
967 | message = { message };
|
968 | return {
|
969 | id: message.id,
|
970 | pluginName: message.plugin,
|
971 | text: message.message,
|
972 | location: message.loc ? {
|
973 | file: message.loc.file,
|
974 | line: message.loc.line,
|
975 | column: message.loc.column
|
976 | } : null,
|
977 | detail: message.meta,
|
978 | notes: []
|
979 | };
|
980 | }
|
981 | function processCodeWithSourceMap(map, code) {
|
982 | if (map) {
|
983 | if (!map.sourcesContent || map.sourcesContent.length === 0)
|
984 | map.sourcesContent = [code];
|
985 | map = fixSourceMap(map);
|
986 | code += `
|
987 | //# sourceMappingURL=${map.toUrl()}`;
|
988 | }
|
989 | return code;
|
990 | }
|
991 |
|
992 |
|
993 | function getEsbuildPlugin(factory) {
|
994 | return (userOptions) => {
|
995 | const meta = {
|
996 | framework: "esbuild"
|
997 | };
|
998 | const plugins = toArray(factory(userOptions, meta));
|
999 | const setupPlugins = async (build2) => {
|
1000 | const setup = buildSetup(meta);
|
1001 | const loaders = [];
|
1002 | for (const plugin of plugins) {
|
1003 | const loader = {};
|
1004 | await setup(plugin)({
|
1005 | ...build2,
|
1006 | onLoad(_options, callback) {
|
1007 | loader.options = _options;
|
1008 | loader.onLoadCb = callback;
|
1009 | },
|
1010 | onTransform(_options, callback) {
|
1011 | loader.options || (loader.options = _options);
|
1012 | loader.onTransformCb = callback;
|
1013 | }
|
1014 | });
|
1015 | if (loader.onLoadCb || loader.onTransformCb)
|
1016 | loaders.push(loader);
|
1017 | }
|
1018 | if (loaders.length) {
|
1019 | build2.onLoad(loaders.length === 1 ? loaders[0].options : { filter: /.*/ }, async (args) => {
|
1020 | function checkFilter(options) {
|
1021 | return loaders.length === 1 || !(options == null ? void 0 : options.filter) || options.filter.test(args.path);
|
1022 | }
|
1023 | let result;
|
1024 | for (const { options, onLoadCb } of loaders) {
|
1025 | if (!checkFilter(options))
|
1026 | continue;
|
1027 | if (onLoadCb)
|
1028 | result = await onLoadCb(args);
|
1029 | if (result == null ? void 0 : result.contents)
|
1030 | break;
|
1031 | }
|
1032 | let fsContentsCache;
|
1033 | for (const { options, onTransformCb } of loaders) {
|
1034 | if (!checkFilter(options))
|
1035 | continue;
|
1036 | if (onTransformCb) {
|
1037 | const newArgs = {
|
1038 | ...result,
|
1039 | ...args,
|
1040 | async getContents() {
|
1041 | if (result == null ? void 0 : result.contents)
|
1042 | return result.contents;
|
1043 | if (fsContentsCache)
|
1044 | return fsContentsCache;
|
1045 | return fsContentsCache = await fs2.promises.readFile(args.path, "utf8");
|
1046 | }
|
1047 | };
|
1048 | const _result = await onTransformCb(newArgs);
|
1049 | if (_result == null ? void 0 : _result.contents)
|
1050 | result = _result;
|
1051 | }
|
1052 | }
|
1053 | if (result == null ? void 0 : result.contents)
|
1054 | return result;
|
1055 | });
|
1056 | }
|
1057 | };
|
1058 | return {
|
1059 | name: (plugins.length === 1 ? plugins[0].name : meta.esbuildHostName) ?? `unplugin-host:${plugins.map((p) => p.name).join(":")}`,
|
1060 | setup: setupPlugins
|
1061 | };
|
1062 | };
|
1063 | }
|
1064 | function buildSetup(meta) {
|
1065 | return (plugin) => {
|
1066 | return (build2) => {
|
1067 | var _a, _b, _c, _d, _e;
|
1068 | meta.build = build2;
|
1069 | const { onStart, onEnd, onResolve, onLoad, onTransform, initialOptions } = build2;
|
1070 | const onResolveFilter = ((_a = plugin.esbuild) == null ? void 0 : _a.onResolveFilter) ?? /.*/;
|
1071 | const onLoadFilter = ((_b = plugin.esbuild) == null ? void 0 : _b.onLoadFilter) ?? /.*/;
|
1072 | const loader = ((_c = plugin.esbuild) == null ? void 0 : _c.loader) ?? guessLoader;
|
1073 | const context = createBuildContext(initialOptions);
|
1074 | if ((_d = plugin.esbuild) == null ? void 0 : _d.config)
|
1075 | plugin.esbuild.config.call(context, initialOptions);
|
1076 | if (plugin.buildStart)
|
1077 | onStart(() => plugin.buildStart.call(context));
|
1078 | if (plugin.buildEnd || plugin.writeBundle) {
|
1079 | onEnd(async () => {
|
1080 | if (plugin.buildEnd)
|
1081 | await plugin.buildEnd.call(context);
|
1082 | if (plugin.writeBundle)
|
1083 | await plugin.writeBundle();
|
1084 | });
|
1085 | }
|
1086 | if (plugin.resolveId) {
|
1087 | onResolve({ filter: onResolveFilter }, async (args) => {
|
1088 | var _a2;
|
1089 | if ((_a2 = initialOptions.external) == null ? void 0 : _a2.includes(args.path)) {
|
1090 | return void 0;
|
1091 | }
|
1092 | const { errors, warnings, mixedContext } = createPluginContext(context);
|
1093 | const isEntry = args.kind === "entry-point";
|
1094 | const result = await plugin.resolveId.call(
|
1095 | mixedContext,
|
1096 | args.path,
|
1097 | // We explicitly have this if statement here for consistency with
|
1098 | // the integration of other bundlers.
|
1099 | // Here, `args.importer` is just an empty string on entry files
|
1100 | // whereas the equivalent on other bundlers is`undefined.`
|
1101 | isEntry ? void 0 : args.importer,
|
1102 | { isEntry }
|
1103 | );
|
1104 | if (typeof result === "string") {
|
1105 | return {
|
1106 | path: result,
|
1107 | namespace: plugin.name,
|
1108 | errors,
|
1109 | warnings,
|
1110 | watchFiles: mixedContext.getWatchFiles()
|
1111 | };
|
1112 | } else if (typeof result === "object" && result !== null) {
|
1113 | return {
|
1114 | path: result.id,
|
1115 | external: result.external,
|
1116 | namespace: plugin.name,
|
1117 | errors,
|
1118 | warnings,
|
1119 | watchFiles: mixedContext.getWatchFiles()
|
1120 | };
|
1121 | }
|
1122 | });
|
1123 | }
|
1124 | if (plugin.load) {
|
1125 | onLoad({ filter: onLoadFilter }, async (args) => {
|
1126 | const id = args.path + args.suffix;
|
1127 | const { errors, warnings, mixedContext } = createPluginContext(context);
|
1128 | const resolveDir = path3.dirname(args.path);
|
1129 | let code, map;
|
1130 | if (plugin.load && (!plugin.loadInclude || plugin.loadInclude(id))) {
|
1131 | const result = await plugin.load.call(mixedContext, id);
|
1132 | if (typeof result === "string") {
|
1133 | code = result;
|
1134 | } else if (typeof result === "object" && result !== null) {
|
1135 | code = result.code;
|
1136 | map = result.map;
|
1137 | }
|
1138 | }
|
1139 | if (code === void 0)
|
1140 | return null;
|
1141 | if (map)
|
1142 | code = processCodeWithSourceMap(map, code);
|
1143 | return {
|
1144 | contents: code,
|
1145 | errors,
|
1146 | warnings,
|
1147 | watchFiles: mixedContext.getWatchFiles(),
|
1148 | loader: unwrapLoader(loader, code, args.path),
|
1149 | resolveDir
|
1150 | };
|
1151 | });
|
1152 | }
|
1153 | if (plugin.transform) {
|
1154 | onTransform({ filter: onLoadFilter }, async (args) => {
|
1155 | const id = args.path + args.suffix;
|
1156 | if (plugin.transformInclude && !plugin.transformInclude(id))
|
1157 | return;
|
1158 | const { mixedContext, errors, warnings } = createPluginContext(context);
|
1159 | const resolveDir = path3.dirname(args.path);
|
1160 | let code = await args.getContents();
|
1161 | let map;
|
1162 | const result = await plugin.transform.call(mixedContext, code, id);
|
1163 | if (typeof result === "string") {
|
1164 | code = result;
|
1165 | } else if (typeof result === "object" && result !== null) {
|
1166 | code = result.code;
|
1167 | if (map && result.map) {
|
1168 | map = combineSourcemaps(args.path, [
|
1169 | result.map === "string" ? JSON.parse(result.map) : result.map,
|
1170 | map
|
1171 | ]);
|
1172 | } else {
|
1173 | if (typeof result.map === "string") {
|
1174 | map = JSON.parse(result.map);
|
1175 | } else {
|
1176 | map = result.map;
|
1177 | }
|
1178 | }
|
1179 | }
|
1180 | if (code) {
|
1181 | if (map)
|
1182 | code = processCodeWithSourceMap(map, code);
|
1183 | return {
|
1184 | contents: code,
|
1185 | errors,
|
1186 | warnings,
|
1187 | watchFiles: mixedContext.getWatchFiles(),
|
1188 | loader: unwrapLoader(loader, code, args.path),
|
1189 | resolveDir
|
1190 | };
|
1191 | }
|
1192 | });
|
1193 | }
|
1194 | if ((_e = plugin.esbuild) == null ? void 0 : _e.setup)
|
1195 | return plugin.esbuild.setup(meta.build);
|
1196 | };
|
1197 | };
|
1198 | }
|
1199 |
|
1200 | // src/farm/index.ts
|
1201 | import path5 from "path";
|
1202 |
|
1203 | // src/farm/context.ts
|
1204 | import { Buffer as Buffer3 } from "buffer";
|
1205 | import { extname } from "path";
|
1206 | import { Parser as Parser2 } from "acorn";
|
1207 | function createFarmContext(context, currentResolveId) {
|
1208 | return {
|
1209 | parse(code, opts = {}) {
|
1210 | return Parser2.parse(code, {
|
1211 | sourceType: "module",
|
1212 | ecmaVersion: "latest",
|
1213 | locations: true,
|
1214 | ...opts
|
1215 | });
|
1216 | },
|
1217 | addWatchFile(id) {
|
1218 | context.addWatchFile(currentResolveId || id, id);
|
1219 | },
|
1220 | emitFile(emittedFile) {
|
1221 | const outFileName = emittedFile.fileName || emittedFile.name;
|
1222 | if (emittedFile.source && outFileName) {
|
1223 | context.emitFile({
|
1224 | resolvedPath: outFileName,
|
1225 | name: outFileName,
|
1226 | content: [...Buffer3.from(emittedFile.source)],
|
1227 | resourceType: extname(outFileName)
|
1228 | });
|
1229 | }
|
1230 | },
|
1231 | getWatchFiles() {
|
1232 | return context.getWatchFiles();
|
1233 | }
|
1234 | };
|
1235 | }
|
1236 | function unpluginContext(context) {
|
1237 | return {
|
1238 | error: (error) => context.error(
|
1239 | typeof error === "string" ? new Error(error) : error
|
1240 | ),
|
1241 | warn: (error) => context.warn(typeof error === "string" ? new Error(error) : error)
|
1242 | };
|
1243 | }
|
1244 |
|
1245 | // src/farm/utils.ts
|
1246 | import path4 from "path";
|
1247 | import * as querystring from "querystring";
|
1248 | var ExtToLoader2 = {
|
1249 | ".js": "js",
|
1250 | ".mjs": "js",
|
1251 | ".cjs": "js",
|
1252 | ".jsx": "jsx",
|
1253 | ".ts": "ts",
|
1254 | ".cts": "ts",
|
1255 | ".mts": "ts",
|
1256 | ".tsx": "tsx",
|
1257 | ".json": "json",
|
1258 | ".toml": "toml",
|
1259 | ".text": "text",
|
1260 | ".wasm": "wasm",
|
1261 | ".napi": "napi",
|
1262 | ".node": "napi"
|
1263 | };
|
1264 | function guessIdLoader(id) {
|
1265 | return ExtToLoader2[path4.extname(id).toLowerCase()] || "js";
|
1266 | }
|
1267 | function transformQuery(context) {
|
1268 | const queryParamsObject = {};
|
1269 | context.query.forEach(([param, value]) => {
|
1270 | queryParamsObject[param] = value;
|
1271 | });
|
1272 | const transformQuery2 = querystring.stringify(queryParamsObject);
|
1273 | context.resolvedPath = `${context.resolvedPath}?${transformQuery2}`;
|
1274 | }
|
1275 | function convertEnforceToPriority(value) {
|
1276 | const defaultPriority = 100;
|
1277 | const enforceToPriority = {
|
1278 | pre: 101,
|
1279 | post: 99
|
1280 | };
|
1281 | return enforceToPriority[value] !== void 0 ? enforceToPriority[value] : defaultPriority;
|
1282 | }
|
1283 | function convertWatchEventChange(value) {
|
1284 | const watchEventChange = {
|
1285 | Added: "create",
|
1286 | Updated: "update",
|
1287 | Removed: "delete"
|
1288 | };
|
1289 | return watchEventChange[value];
|
1290 | }
|
1291 | function getContentValue(content) {
|
1292 | return typeof content === "string" ? content : content.code;
|
1293 | }
|
1294 | function isString(variable) {
|
1295 | return typeof variable === "string";
|
1296 | }
|
1297 | function isObject(variable) {
|
1298 | return typeof variable === "object" && variable !== null;
|
1299 | }
|
1300 | function customParseQueryString(url) {
|
1301 | if (!url)
|
1302 | return [];
|
1303 | const queryString = url.split("?")[1];
|
1304 | const parsedParams = querystring.parse(queryString);
|
1305 | const paramsArray = [];
|
1306 | for (const key in parsedParams)
|
1307 | paramsArray.push([key, parsedParams[key]]);
|
1308 | return paramsArray;
|
1309 | }
|
1310 |
|
1311 | // src/farm/index.ts
|
1312 | function getFarmPlugin(factory) {
|
1313 | return (userOptions) => {
|
1314 | const meta = {
|
1315 | framework: "farm"
|
1316 | };
|
1317 | const rawPlugins = toArray(factory(userOptions, meta));
|
1318 | const plugins = rawPlugins.map((rawPlugin) => {
|
1319 | const plugin = toFarmPlugin(rawPlugin, userOptions);
|
1320 | if (rawPlugin.farm)
|
1321 | Object.assign(plugin, rawPlugin.farm);
|
1322 | return plugin;
|
1323 | });
|
1324 | return plugins.length === 1 ? plugins[0] : plugins;
|
1325 | };
|
1326 | }
|
1327 | function toFarmPlugin(plugin, options) {
|
1328 | const farmPlugin = {
|
1329 | name: plugin.name,
|
1330 | priority: convertEnforceToPriority(plugin.enforce)
|
1331 | };
|
1332 | if (plugin.farm) {
|
1333 | Object.keys(plugin.farm).forEach((key) => {
|
1334 | const value = plugin.farm[key];
|
1335 | if (value)
|
1336 | Reflect.set(farmPlugin, key, value);
|
1337 | });
|
1338 | }
|
1339 | if (plugin.buildStart) {
|
1340 | const _buildStart = plugin.buildStart;
|
1341 | farmPlugin.buildStart = {
|
1342 | async executor(_, context) {
|
1343 | await _buildStart.call(createFarmContext(context));
|
1344 | }
|
1345 | };
|
1346 | }
|
1347 | if (plugin.resolveId) {
|
1348 | const _resolveId = plugin.resolveId;
|
1349 | let filters = [];
|
1350 | if (options)
|
1351 | filters = (options == null ? void 0 : options.filters) ?? [];
|
1352 | farmPlugin.resolve = {
|
1353 | filters: { sources: [".*", ...filters], importers: [".*"] },
|
1354 | async executor(params, context) {
|
1355 | const resolvedIdPath = path5.resolve(
|
1356 | process.cwd(),
|
1357 | params.importer ?? ""
|
1358 | );
|
1359 | let isEntry = false;
|
1360 | if (isObject(params.kind) && "entry" in params.kind) {
|
1361 | const kindWithEntry = params.kind;
|
1362 | isEntry = kindWithEntry.entry === "index";
|
1363 | }
|
1364 | const farmContext = createFarmContext(context, resolvedIdPath);
|
1365 | const resolveIdResult = await _resolveId.call(
|
1366 | Object.assign(unpluginContext(context), farmContext),
|
1367 | params.source,
|
1368 | resolvedIdPath ?? null,
|
1369 | { isEntry }
|
1370 | );
|
1371 | if (isString(resolveIdResult)) {
|
1372 | return {
|
1373 | resolvedPath: resolveIdResult,
|
1374 | query: customParseQueryString(resolveIdResult),
|
1375 | sideEffects: false,
|
1376 | external: false,
|
1377 | meta: {}
|
1378 | };
|
1379 | } else if (isObject(resolveIdResult)) {
|
1380 | return {
|
1381 | resolvedPath: resolveIdResult == null ? void 0 : resolveIdResult.id,
|
1382 | query: customParseQueryString(resolveIdResult.id),
|
1383 | sideEffects: false,
|
1384 | external: resolveIdResult == null ? void 0 : resolveIdResult.external,
|
1385 | meta: {}
|
1386 | };
|
1387 | }
|
1388 | return null;
|
1389 | }
|
1390 | };
|
1391 | }
|
1392 | if (plugin.load) {
|
1393 | const _load = plugin.load;
|
1394 | farmPlugin.load = {
|
1395 | filters: {
|
1396 | resolvedPaths: [".*"]
|
1397 | },
|
1398 | async executor(id, context) {
|
1399 | if (plugin.loadInclude && !plugin.loadInclude(id.resolvedPath))
|
1400 | return null;
|
1401 | const loader = guessIdLoader(id.resolvedPath);
|
1402 | const shouldLoadInclude = plugin.loadInclude && plugin.loadInclude(id.resolvedPath);
|
1403 | const farmContext = createFarmContext(context, id.resolvedPath);
|
1404 | const content = await _load.call(
|
1405 | Object.assign(unpluginContext(context), farmContext),
|
1406 | id.resolvedPath
|
1407 | );
|
1408 | const loadFarmResult = {
|
1409 | content: getContentValue(content),
|
1410 | moduleType: loader
|
1411 | };
|
1412 | if (shouldLoadInclude)
|
1413 | return loadFarmResult;
|
1414 | return null;
|
1415 | }
|
1416 | };
|
1417 | }
|
1418 | if (plugin.transform) {
|
1419 | const _transform = plugin.transform;
|
1420 | farmPlugin.transform = {
|
1421 | filters: { resolvedPaths: [".*"], moduleTypes: [".*"] },
|
1422 | async executor(params, context) {
|
1423 | if (params.query.length)
|
1424 | transformQuery(params);
|
1425 | if (plugin.transformInclude && !plugin.transformInclude(params.resolvedPath)) {
|
1426 | return null;
|
1427 | }
|
1428 | const loader = params.moduleType ?? guessIdLoader(params.resolvedPath);
|
1429 | const shouldTransformInclude = plugin.transformInclude && plugin.transformInclude(params.resolvedPath);
|
1430 | const farmContext = createFarmContext(context, params.resolvedPath);
|
1431 | const resource = await _transform.call(
|
1432 | Object.assign(unpluginContext(context), farmContext),
|
1433 | params.content,
|
1434 | params.resolvedPath
|
1435 | );
|
1436 | if (resource && typeof resource !== "string") {
|
1437 | const transformFarmResult = {
|
1438 | content: getContentValue(resource),
|
1439 | moduleType: loader,
|
1440 | sourceMap: JSON.stringify(resource.map)
|
1441 | };
|
1442 | if (shouldTransformInclude)
|
1443 | return transformFarmResult;
|
1444 | return transformFarmResult;
|
1445 | }
|
1446 | }
|
1447 | };
|
1448 | }
|
1449 | if (plugin.watchChange) {
|
1450 | const _watchChange = plugin.watchChange;
|
1451 | farmPlugin.updateModules = {
|
1452 | async executor(param, context) {
|
1453 | const updatePathContent = param.paths[0];
|
1454 | const ModifiedPath = updatePathContent[0];
|
1455 | const eventChange = convertWatchEventChange(
|
1456 | updatePathContent[1]
|
1457 | );
|
1458 | await _watchChange.call(createFarmContext(context), ModifiedPath, {
|
1459 | event: eventChange
|
1460 | });
|
1461 | }
|
1462 | };
|
1463 | }
|
1464 | if (plugin.buildEnd) {
|
1465 | const _buildEnd = plugin.buildEnd;
|
1466 | farmPlugin.buildEnd = {
|
1467 | async executor(_, context) {
|
1468 | await _buildEnd.call(createFarmContext(context));
|
1469 | }
|
1470 | };
|
1471 | }
|
1472 | if (plugin.writeBundle) {
|
1473 | const _writeBundle = plugin.writeBundle;
|
1474 | farmPlugin.finish = {
|
1475 | async executor() {
|
1476 | await _writeBundle();
|
1477 | }
|
1478 | };
|
1479 | }
|
1480 | return farmPlugin;
|
1481 | }
|
1482 |
|
1483 | // src/rollup/index.ts
|
1484 | function getRollupPlugin(factory) {
|
1485 | return (userOptions) => {
|
1486 | const meta = {
|
1487 | framework: "rollup"
|
1488 | };
|
1489 | const rawPlugins = toArray(factory(userOptions, meta));
|
1490 | const plugins = rawPlugins.map((plugin) => toRollupPlugin(plugin));
|
1491 | return plugins.length === 1 ? plugins[0] : plugins;
|
1492 | };
|
1493 | }
|
1494 | function toRollupPlugin(plugin, containRollupOptions = true) {
|
1495 | if (plugin.transform && plugin.transformInclude) {
|
1496 | const _transform = plugin.transform;
|
1497 | plugin.transform = function(code, id) {
|
1498 | if (plugin.transformInclude && !plugin.transformInclude(id))
|
1499 | return null;
|
1500 | return _transform.call(this, code, id);
|
1501 | };
|
1502 | }
|
1503 | if (plugin.load && plugin.loadInclude) {
|
1504 | const _load = plugin.load;
|
1505 | plugin.load = function(id) {
|
1506 | if (plugin.loadInclude && !plugin.loadInclude(id))
|
1507 | return null;
|
1508 | return _load.call(this, id);
|
1509 | };
|
1510 | }
|
1511 | if (plugin.rollup && containRollupOptions)
|
1512 | Object.assign(plugin, plugin.rollup);
|
1513 | return plugin;
|
1514 | }
|
1515 |
|
1516 | // src/rolldown/index.ts
|
1517 | function getRolldownPlugin(factory) {
|
1518 | return (userOptions) => {
|
1519 | const meta = {
|
1520 | framework: "rolldown"
|
1521 | };
|
1522 | const rawPlugins = toArray(factory(userOptions, meta));
|
1523 | const plugins = rawPlugins.map((rawPlugin) => {
|
1524 | const plugin = toRollupPlugin(rawPlugin, false);
|
1525 | if (rawPlugin.rolldown)
|
1526 | Object.assign(plugin, rawPlugin.rolldown);
|
1527 | return plugin;
|
1528 | });
|
1529 | return plugins.length === 1 ? plugins[0] : plugins;
|
1530 | };
|
1531 | }
|
1532 |
|
1533 | // src/rspack/index.ts
|
1534 | import fs3 from "fs";
|
1535 | import { resolve as resolve4 } from "path";
|
1536 |
|
1537 | // src/rspack/context.ts
|
1538 | import { resolve as resolve3 } from "path";
|
1539 | import { Buffer as Buffer4 } from "buffer";
|
1540 | import { Parser as Parser3 } from "acorn";
|
1541 | function contextOptionsFromCompilation(compilation) {
|
1542 | return {
|
1543 | addWatchFile(file) {
|
1544 | compilation.fileDependencies.add(file);
|
1545 | },
|
1546 | getWatchFiles() {
|
1547 | return Array.from(compilation.fileDependencies);
|
1548 | }
|
1549 | };
|
1550 | }
|
1551 | function createBuildContext2(options, compilation) {
|
1552 | return {
|
1553 | parse(code, opts = {}) {
|
1554 | return Parser3.parse(code, {
|
1555 | sourceType: "module",
|
1556 | ecmaVersion: "latest",
|
1557 | locations: true,
|
1558 | ...opts
|
1559 | });
|
1560 | },
|
1561 | addWatchFile(id) {
|
1562 | options.addWatchFile(resolve3(process.cwd(), id));
|
1563 | },
|
1564 | emitFile(emittedFile) {
|
1565 | const outFileName = emittedFile.fileName || emittedFile.name;
|
1566 | if (emittedFile.source && outFileName) {
|
1567 | const { sources: sources2 } = compilation.compiler.webpack;
|
1568 | compilation.emitAsset(
|
1569 | outFileName,
|
1570 | new sources2.RawSource(
|
1571 | typeof emittedFile.source === "string" ? emittedFile.source : Buffer4.from(emittedFile.source)
|
1572 | )
|
1573 | );
|
1574 | }
|
1575 | },
|
1576 | getWatchFiles() {
|
1577 | return options.getWatchFiles();
|
1578 | }
|
1579 | };
|
1580 | }
|
1581 | function normalizeMessage2(error) {
|
1582 | const err = new Error(typeof error === "string" ? error : error.message);
|
1583 | if (typeof error === "object") {
|
1584 | err.stack = error.stack;
|
1585 | err.cause = error.meta;
|
1586 | }
|
1587 | return err;
|
1588 | }
|
1589 |
|
1590 | // src/rspack/utils.ts
|
1591 | function encodeVirtualModuleId(id, plugin) {
|
1592 | return plugin.__virtualModulePrefix + encodeURIComponent(id);
|
1593 | }
|
1594 | function decodeVirtualModuleId(encoded, plugin) {
|
1595 | return decodeURIComponent(encoded.slice(plugin.__virtualModulePrefix.length));
|
1596 | }
|
1597 |
|
1598 | // src/rspack/index.ts
|
1599 | var TRANSFORM_LOADER = resolve4(
|
1600 | __dirname,
|
1601 | false ? "../../dist/rspack/loaders/transform.js" : "rspack/loaders/transform"
|
1602 | );
|
1603 | var LOAD_LOADER = resolve4(
|
1604 | __dirname,
|
1605 | false ? "../../dist/rspack/loaders/load.js" : "rspack/loaders/load"
|
1606 | );
|
1607 | var VIRTUAL_MODULE_PATH = resolve4(__dirname, false ? "../../dist/rspack/virtual.js" : "rspack/virtual.js");
|
1608 | var VIRTUAL_MODULE_QUERY_PREFIX = "?unplugin_rspack_virtual=";
|
1609 | var VIRTUAL_MODULE_PREFIX = VIRTUAL_MODULE_PATH + VIRTUAL_MODULE_QUERY_PREFIX;
|
1610 | function getRspackPlugin(factory) {
|
1611 | return (userOptions) => {
|
1612 | return {
|
1613 | apply(compiler) {
|
1614 | const injected = compiler.$unpluginContext || {};
|
1615 | compiler.$unpluginContext = injected;
|
1616 | const meta = {
|
1617 | framework: "rspack",
|
1618 | rspack: {
|
1619 | compiler
|
1620 | }
|
1621 | };
|
1622 | const rawPlugins = toArray(factory(userOptions, meta));
|
1623 | for (const rawPlugin of rawPlugins) {
|
1624 | const plugin = Object.assign(
|
1625 | rawPlugin,
|
1626 | {
|
1627 | __unpluginMeta: meta,
|
1628 | __virtualModulePrefix: VIRTUAL_MODULE_PREFIX
|
1629 | }
|
1630 | );
|
1631 | injected[plugin.name] = plugin;
|
1632 | compiler.hooks.thisCompilation.tap(plugin.name, (compilation) => {
|
1633 | if (typeof compilation.hooks.childCompiler === "undefined")
|
1634 | throw new Error("`compilation.hooks.childCompiler` only support by @rspack/core>=0.4.1");
|
1635 | compilation.hooks.childCompiler.tap(plugin.name, (childCompiler) => {
|
1636 | childCompiler.$unpluginContext = injected;
|
1637 | });
|
1638 | });
|
1639 | const externalModules = /* @__PURE__ */ new Set();
|
1640 | if (plugin.resolveId) {
|
1641 | compiler.hooks.compilation.tap(plugin.name, (compilation, { normalModuleFactory }) => {
|
1642 | normalModuleFactory.hooks.resolve.tapPromise(plugin.name, async (resolveData) => {
|
1643 | const id = normalizeAbsolutePath(resolveData.request);
|
1644 | const requestContext = resolveData.contextInfo;
|
1645 | const importer = requestContext.issuer !== "" ? requestContext.issuer : void 0;
|
1646 | const isEntry = requestContext.issuer === "";
|
1647 | const context = createBuildContext2(contextOptionsFromCompilation(compilation), compilation);
|
1648 | let error;
|
1649 | const pluginContext = {
|
1650 | error(msg) {
|
1651 | if (error == null)
|
1652 | error = normalizeMessage2(msg);
|
1653 | else
|
1654 | console.error(`unplugin/rspack: multiple errors returned from resolveId hook: ${msg}`);
|
1655 | },
|
1656 | warn(msg) {
|
1657 | console.warn(`unplugin/rspack: warning from resolveId hook: ${msg}`);
|
1658 | }
|
1659 | };
|
1660 | const resolveIdResult = await plugin.resolveId.call({ ...context, ...pluginContext }, id, importer, { isEntry });
|
1661 | if (error != null)
|
1662 | throw error;
|
1663 | if (resolveIdResult == null)
|
1664 | return;
|
1665 | let resolved = typeof resolveIdResult === "string" ? resolveIdResult : resolveIdResult.id;
|
1666 | const isExternal = typeof resolveIdResult === "string" ? false : resolveIdResult.external === true;
|
1667 | if (isExternal)
|
1668 | externalModules.add(resolved);
|
1669 | if (!fs3.existsSync(resolved))
|
1670 | resolved = encodeVirtualModuleId(resolved, plugin);
|
1671 | resolveData.request = resolved;
|
1672 | });
|
1673 | });
|
1674 | }
|
1675 | if (plugin.load) {
|
1676 | compiler.options.module.rules.unshift({
|
1677 | enforce: plugin.enforce,
|
1678 | include(id) {
|
1679 | if (id === VIRTUAL_MODULE_PATH)
|
1680 | return true;
|
1681 | if (plugin.loadInclude && !plugin.loadInclude(id))
|
1682 | return false;
|
1683 | return !externalModules.has(id);
|
1684 | },
|
1685 | resourceQuery(query) {
|
1686 | if (!query.startsWith(VIRTUAL_MODULE_QUERY_PREFIX))
|
1687 | return true;
|
1688 | const id = decodeVirtualModuleId(VIRTUAL_MODULE_PATH + query, plugin);
|
1689 | if (plugin.loadInclude && !plugin.loadInclude(id))
|
1690 | return false;
|
1691 | return !externalModules.has(id);
|
1692 | },
|
1693 | use: [{
|
1694 | loader: LOAD_LOADER,
|
1695 | options: {
|
1696 | unpluginName: plugin.name
|
1697 | }
|
1698 | }],
|
1699 | type: "javascript/auto"
|
1700 | });
|
1701 | }
|
1702 | if (plugin.transform) {
|
1703 | compiler.options.module.rules.unshift({
|
1704 | enforce: plugin.enforce,
|
1705 | use(data) {
|
1706 | return transformUse(data, plugin, TRANSFORM_LOADER);
|
1707 | }
|
1708 | });
|
1709 | }
|
1710 | if (plugin.rspack)
|
1711 | plugin.rspack(compiler);
|
1712 | if (plugin.watchChange || plugin.buildStart) {
|
1713 | compiler.hooks.make.tapPromise(plugin.name, async (compilation) => {
|
1714 | const context = createBuildContext2(contextOptionsFromCompilation(compilation), compilation);
|
1715 | if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) {
|
1716 | const promises = [];
|
1717 | if (compiler.modifiedFiles) {
|
1718 | compiler.modifiedFiles.forEach(
|
1719 | (file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "update" })))
|
1720 | );
|
1721 | }
|
1722 | if (compiler.removedFiles) {
|
1723 | compiler.removedFiles.forEach(
|
1724 | (file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "delete" })))
|
1725 | );
|
1726 | }
|
1727 | await Promise.all(promises);
|
1728 | }
|
1729 | if (plugin.buildStart)
|
1730 | return await plugin.buildStart.call(context);
|
1731 | });
|
1732 | }
|
1733 | if (plugin.buildEnd) {
|
1734 | compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => {
|
1735 | await plugin.buildEnd.call(createBuildContext2(contextOptionsFromCompilation(compilation), compilation));
|
1736 | });
|
1737 | }
|
1738 | if (plugin.writeBundle) {
|
1739 | compiler.hooks.afterEmit.tapPromise(plugin.name, async () => {
|
1740 | await plugin.writeBundle();
|
1741 | });
|
1742 | }
|
1743 | }
|
1744 | }
|
1745 | };
|
1746 | };
|
1747 | }
|
1748 |
|
1749 | // src/vite/index.ts
|
1750 | function getVitePlugin(factory) {
|
1751 | return (userOptions) => {
|
1752 | const meta = {
|
1753 | framework: "vite"
|
1754 | };
|
1755 | const rawPlugins = toArray(factory(userOptions, meta));
|
1756 | const plugins = rawPlugins.map((rawPlugin) => {
|
1757 | const plugin = toRollupPlugin(rawPlugin, false);
|
1758 | if (rawPlugin.vite)
|
1759 | Object.assign(plugin, rawPlugin.vite);
|
1760 | return plugin;
|
1761 | });
|
1762 | return plugins.length === 1 ? plugins[0] : plugins;
|
1763 | };
|
1764 | }
|
1765 |
|
1766 | // src/webpack/index.ts
|
1767 | import fs4 from "fs";
|
1768 | import { resolve as resolve6 } from "path";
|
1769 | import process3 from "process";
|
1770 | import VirtualModulesPlugin from "webpack-virtual-modules";
|
1771 |
|
1772 | // src/webpack/context.ts
|
1773 | import { resolve as resolve5 } from "path";
|
1774 | import { Buffer as Buffer5 } from "buffer";
|
1775 | import process2 from "process";
|
1776 | import sources from "webpack-sources";
|
1777 | import { Parser as Parser4 } from "acorn";
|
1778 | function contextOptionsFromCompilation2(compilation) {
|
1779 | return {
|
1780 | addWatchFile(file) {
|
1781 | (compilation.fileDependencies ?? compilation.compilationDependencies).add(file);
|
1782 | },
|
1783 | getWatchFiles() {
|
1784 | return Array.from(compilation.fileDependencies ?? compilation.compilationDependencies);
|
1785 | }
|
1786 | };
|
1787 | }
|
1788 | function createBuildContext3(options, compilation) {
|
1789 | return {
|
1790 | parse(code, opts = {}) {
|
1791 | return Parser4.parse(code, {
|
1792 | sourceType: "module",
|
1793 | ecmaVersion: "latest",
|
1794 | locations: true,
|
1795 | ...opts
|
1796 | });
|
1797 | },
|
1798 | addWatchFile(id) {
|
1799 | options.addWatchFile(resolve5(process2.cwd(), id));
|
1800 | },
|
1801 | emitFile(emittedFile) {
|
1802 | const outFileName = emittedFile.fileName || emittedFile.name;
|
1803 | if (emittedFile.source && outFileName) {
|
1804 | if (!compilation)
|
1805 | throw new Error("unplugin/webpack: emitFile outside supported hooks (buildStart, buildEnd, load, transform, watchChange)");
|
1806 | compilation.emitAsset(
|
1807 | outFileName,
|
1808 | sources ? new sources.RawSource(
|
1809 | // @ts-expect-error types mismatch
|
1810 | typeof emittedFile.source === "string" ? emittedFile.source : Buffer5.from(emittedFile.source)
|
1811 | ) : {
|
1812 | source: () => emittedFile.source,
|
1813 | size: () => emittedFile.source.length
|
1814 | }
|
1815 | );
|
1816 | }
|
1817 | },
|
1818 | getWatchFiles() {
|
1819 | return options.getWatchFiles();
|
1820 | }
|
1821 | };
|
1822 | }
|
1823 | function normalizeMessage3(error) {
|
1824 | const err = new Error(typeof error === "string" ? error : error.message);
|
1825 | if (typeof error === "object") {
|
1826 | err.stack = error.stack;
|
1827 | err.cause = error.meta;
|
1828 | }
|
1829 | return err;
|
1830 | }
|
1831 |
|
1832 | // src/webpack/index.ts
|
1833 | var TRANSFORM_LOADER2 = resolve6(
|
1834 | __dirname,
|
1835 | false ? "../../dist/webpack/loaders/transform" : "webpack/loaders/transform"
|
1836 | );
|
1837 | var LOAD_LOADER2 = resolve6(
|
1838 | __dirname,
|
1839 | false ? "../../dist/webpack/loaders/load" : "webpack/loaders/load"
|
1840 | );
|
1841 | function getWebpackPlugin(factory) {
|
1842 | return (userOptions) => {
|
1843 | return {
|
1844 | apply(compiler) {
|
1845 | const VIRTUAL_MODULE_PREFIX2 = resolve6(compiler.options.context ?? process3.cwd(), "_virtual_");
|
1846 | const injected = compiler.$unpluginContext || {};
|
1847 | compiler.$unpluginContext = injected;
|
1848 | const meta = {
|
1849 | framework: "webpack",
|
1850 | webpack: {
|
1851 | compiler
|
1852 | }
|
1853 | };
|
1854 | const rawPlugins = toArray(factory(userOptions, meta));
|
1855 | for (const rawPlugin of rawPlugins) {
|
1856 | const plugin = Object.assign(
|
1857 | rawPlugin,
|
1858 | {
|
1859 | __unpluginMeta: meta,
|
1860 | __virtualModulePrefix: VIRTUAL_MODULE_PREFIX2
|
1861 | }
|
1862 | );
|
1863 | injected[plugin.name] = plugin;
|
1864 | compiler.hooks.thisCompilation.tap(plugin.name, (compilation) => {
|
1865 | compilation.hooks.childCompiler.tap(plugin.name, (childCompiler) => {
|
1866 | childCompiler.$unpluginContext = injected;
|
1867 | });
|
1868 | });
|
1869 | const externalModules = /* @__PURE__ */ new Set();
|
1870 | if (plugin.resolveId) {
|
1871 | let vfs = compiler.options.plugins.find((i) => i instanceof VirtualModulesPlugin);
|
1872 | if (!vfs) {
|
1873 | vfs = new VirtualModulesPlugin();
|
1874 | compiler.options.plugins.push(vfs);
|
1875 | }
|
1876 | plugin.__vfsModules = /* @__PURE__ */ new Set();
|
1877 | plugin.__vfs = vfs;
|
1878 | const resolverPlugin = {
|
1879 | apply(resolver) {
|
1880 | const target = resolver.ensureHook("resolve");
|
1881 | resolver.getHook("resolve").tapAsync(plugin.name, async (request, resolveContext, callback) => {
|
1882 | if (!request.request)
|
1883 | return callback();
|
1884 | if (normalizeAbsolutePath(request.request).startsWith(plugin.__virtualModulePrefix))
|
1885 | return callback();
|
1886 | const id = normalizeAbsolutePath(request.request);
|
1887 | const requestContext = request.context;
|
1888 | const importer = requestContext.issuer !== "" ? requestContext.issuer : void 0;
|
1889 | const isEntry = requestContext.issuer === "";
|
1890 | const fileDependencies = /* @__PURE__ */ new Set();
|
1891 | const context = createBuildContext3({
|
1892 | addWatchFile(file) {
|
1893 | var _a;
|
1894 | fileDependencies.add(file);
|
1895 | (_a = resolveContext.fileDependencies) == null ? void 0 : _a.add(file);
|
1896 | },
|
1897 | getWatchFiles() {
|
1898 | return Array.from(fileDependencies);
|
1899 | }
|
1900 | });
|
1901 | let error;
|
1902 | const pluginContext = {
|
1903 | error(msg) {
|
1904 | if (error == null)
|
1905 | error = normalizeMessage3(msg);
|
1906 | else
|
1907 | console.error(`unplugin/webpack: multiple errors returned from resolveId hook: ${msg}`);
|
1908 | },
|
1909 | warn(msg) {
|
1910 | console.warn(`unplugin/webpack: warning from resolveId hook: ${msg}`);
|
1911 | }
|
1912 | };
|
1913 | const resolveIdResult = await plugin.resolveId.call({ ...context, ...pluginContext }, id, importer, { isEntry });
|
1914 | if (error != null)
|
1915 | return callback(error);
|
1916 | if (resolveIdResult == null)
|
1917 | return callback();
|
1918 | let resolved = typeof resolveIdResult === "string" ? resolveIdResult : resolveIdResult.id;
|
1919 | const isExternal = typeof resolveIdResult === "string" ? false : resolveIdResult.external === true;
|
1920 | if (isExternal)
|
1921 | externalModules.add(resolved);
|
1922 | if (!fs4.existsSync(resolved)) {
|
1923 | resolved = normalizeAbsolutePath(
|
1924 | plugin.__virtualModulePrefix + encodeURIComponent(resolved)
|
1925 | // URI encode id so webpack doesn't think it's part of the path
|
1926 | );
|
1927 | if (!plugin.__vfsModules.has(resolved)) {
|
1928 | plugin.__vfs.writeModule(resolved, "");
|
1929 | plugin.__vfsModules.add(resolved);
|
1930 | }
|
1931 | }
|
1932 | const newRequest = {
|
1933 | ...request,
|
1934 | request: resolved
|
1935 | };
|
1936 | resolver.doResolve(target, newRequest, null, resolveContext, callback);
|
1937 | });
|
1938 | }
|
1939 | };
|
1940 | compiler.options.resolve.plugins = compiler.options.resolve.plugins || [];
|
1941 | compiler.options.resolve.plugins.push(resolverPlugin);
|
1942 | }
|
1943 | if (plugin.load) {
|
1944 | compiler.options.module.rules.unshift({
|
1945 | include(id) {
|
1946 | return shouldLoad(id, plugin, externalModules);
|
1947 | },
|
1948 | enforce: plugin.enforce,
|
1949 | use: [{
|
1950 | loader: LOAD_LOADER2,
|
1951 | options: {
|
1952 | unpluginName: plugin.name
|
1953 | }
|
1954 | }],
|
1955 | type: "javascript/auto"
|
1956 | });
|
1957 | }
|
1958 | if (plugin.transform) {
|
1959 | compiler.options.module.rules.unshift({
|
1960 | enforce: plugin.enforce,
|
1961 | use(data) {
|
1962 | return transformUse(data, plugin, TRANSFORM_LOADER2);
|
1963 | }
|
1964 | });
|
1965 | }
|
1966 | if (plugin.webpack)
|
1967 | plugin.webpack(compiler);
|
1968 | if (plugin.watchChange || plugin.buildStart) {
|
1969 | compiler.hooks.make.tapPromise(plugin.name, async (compilation) => {
|
1970 | const context = createBuildContext3(contextOptionsFromCompilation2(compilation), compilation);
|
1971 | if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) {
|
1972 | const promises = [];
|
1973 | if (compiler.modifiedFiles) {
|
1974 | compiler.modifiedFiles.forEach(
|
1975 | (file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "update" })))
|
1976 | );
|
1977 | }
|
1978 | if (compiler.removedFiles) {
|
1979 | compiler.removedFiles.forEach(
|
1980 | (file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "delete" })))
|
1981 | );
|
1982 | }
|
1983 | await Promise.all(promises);
|
1984 | }
|
1985 | if (plugin.buildStart)
|
1986 | return await plugin.buildStart.call(context);
|
1987 | });
|
1988 | }
|
1989 | if (plugin.buildEnd) {
|
1990 | compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => {
|
1991 | await plugin.buildEnd.call(createBuildContext3(contextOptionsFromCompilation2(compilation), compilation));
|
1992 | });
|
1993 | }
|
1994 | if (plugin.writeBundle) {
|
1995 | compiler.hooks.afterEmit.tapPromise(plugin.name, async () => {
|
1996 | await plugin.writeBundle();
|
1997 | });
|
1998 | }
|
1999 | }
|
2000 | }
|
2001 | };
|
2002 | };
|
2003 | }
|
2004 |
|
2005 | // src/define.ts
|
2006 | function createUnplugin(factory) {
|
2007 | return {
|
2008 | get esbuild() {
|
2009 | return getEsbuildPlugin(factory);
|
2010 | },
|
2011 | get rollup() {
|
2012 | return getRollupPlugin(factory);
|
2013 | },
|
2014 | get vite() {
|
2015 | return getVitePlugin(factory);
|
2016 | },
|
2017 | /** @experimental do not use it in production */
|
2018 | get rolldown() {
|
2019 | return getRolldownPlugin(factory);
|
2020 | },
|
2021 | get webpack() {
|
2022 | return getWebpackPlugin(factory);
|
2023 | },
|
2024 | get rspack() {
|
2025 | return getRspackPlugin(factory);
|
2026 | },
|
2027 | get farm() {
|
2028 | return getFarmPlugin(factory);
|
2029 | },
|
2030 | get raw() {
|
2031 | return factory;
|
2032 | }
|
2033 | };
|
2034 | }
|
2035 | function createEsbuildPlugin(factory) {
|
2036 | return getEsbuildPlugin(factory);
|
2037 | }
|
2038 | function createRollupPlugin(factory) {
|
2039 | return getRollupPlugin(factory);
|
2040 | }
|
2041 | function createVitePlugin(factory) {
|
2042 | return getVitePlugin(factory);
|
2043 | }
|
2044 | function createRolldownPlugin(factory) {
|
2045 | return getRolldownPlugin(factory);
|
2046 | }
|
2047 | function createWebpackPlugin(factory) {
|
2048 | return getWebpackPlugin(factory);
|
2049 | }
|
2050 | function createRspackPlugin(factory) {
|
2051 | return getRspackPlugin(factory);
|
2052 | }
|
2053 | function createFarmPlugin(factory) {
|
2054 | return getFarmPlugin(factory);
|
2055 | }
|
2056 | export {
|
2057 | createEsbuildPlugin,
|
2058 | createFarmPlugin,
|
2059 | createRolldownPlugin,
|
2060 | createRollupPlugin,
|
2061 | createRspackPlugin,
|
2062 | createUnplugin,
|
2063 | createVitePlugin,
|
2064 | createWebpackPlugin
|
2065 | };
|
2066 |
|
\ | No newline at end of file |