index.mjs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441
  1. // src/esbuild/index.ts
  2. import fs from "fs";
  3. import path from "path";
  4. import chokidar from "chokidar";
  5. import { Parser } from "acorn";
  6. // src/esbuild/utils.ts
  7. import { extname } from "path";
  8. // node_modules/.pnpm/@jridgewell+sourcemap-codec@1.4.11/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
  9. var comma = ",".charCodeAt(0);
  10. var semicolon = ";".charCodeAt(0);
  11. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  12. var intToChar = new Uint8Array(64);
  13. var charToInteger = new Uint8Array(128);
  14. for (let i2 = 0; i2 < chars.length; i2++) {
  15. const c = chars.charCodeAt(i2);
  16. charToInteger[c] = i2;
  17. intToChar[i2] = c;
  18. }
  19. var td = typeof TextDecoder !== "undefined" ? new TextDecoder() : typeof Buffer !== "undefined" ? {
  20. decode(buf) {
  21. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  22. return out.toString();
  23. }
  24. } : {
  25. decode(buf) {
  26. let out = "";
  27. for (let i2 = 0; i2 < buf.length; i2++) {
  28. out += String.fromCharCode(buf[i2]);
  29. }
  30. return out;
  31. }
  32. };
  33. function decode(mappings) {
  34. const state = new Int32Array(5);
  35. const decoded = [];
  36. let line = [];
  37. let sorted = true;
  38. let lastCol = 0;
  39. for (let i2 = 0; i2 < mappings.length; ) {
  40. const c = mappings.charCodeAt(i2);
  41. if (c === comma) {
  42. i2++;
  43. } else if (c === semicolon) {
  44. state[0] = lastCol = 0;
  45. if (!sorted)
  46. sort(line);
  47. sorted = true;
  48. decoded.push(line);
  49. line = [];
  50. i2++;
  51. } else {
  52. i2 = decodeInteger(mappings, i2, state, 0);
  53. const col = state[0];
  54. if (col < lastCol)
  55. sorted = false;
  56. lastCol = col;
  57. if (!hasMoreSegments(mappings, i2)) {
  58. line.push([col]);
  59. continue;
  60. }
  61. i2 = decodeInteger(mappings, i2, state, 1);
  62. i2 = decodeInteger(mappings, i2, state, 2);
  63. i2 = decodeInteger(mappings, i2, state, 3);
  64. if (!hasMoreSegments(mappings, i2)) {
  65. line.push([col, state[1], state[2], state[3]]);
  66. continue;
  67. }
  68. i2 = decodeInteger(mappings, i2, state, 4);
  69. line.push([col, state[1], state[2], state[3], state[4]]);
  70. }
  71. }
  72. if (!sorted)
  73. sort(line);
  74. decoded.push(line);
  75. return decoded;
  76. }
  77. function decodeInteger(mappings, pos, state, j) {
  78. let value = 0;
  79. let shift = 0;
  80. let integer = 0;
  81. do {
  82. const c = mappings.charCodeAt(pos++);
  83. integer = charToInteger[c];
  84. value |= (integer & 31) << shift;
  85. shift += 5;
  86. } while (integer & 32);
  87. const shouldNegate = value & 1;
  88. value >>>= 1;
  89. if (shouldNegate) {
  90. value = -2147483648 | -value;
  91. }
  92. state[j] += value;
  93. return pos;
  94. }
  95. function hasMoreSegments(mappings, i2) {
  96. if (i2 >= mappings.length)
  97. return false;
  98. const c = mappings.charCodeAt(i2);
  99. if (c === comma || c === semicolon)
  100. return false;
  101. return true;
  102. }
  103. function sort(line) {
  104. line.sort(sortComparator);
  105. }
  106. function sortComparator(a, b) {
  107. return a[0] - b[0];
  108. }
  109. function encode(decoded) {
  110. const state = new Int32Array(5);
  111. let buf = new Uint8Array(1024);
  112. let pos = 0;
  113. for (let i2 = 0; i2 < decoded.length; i2++) {
  114. const line = decoded[i2];
  115. if (i2 > 0) {
  116. buf = reserve(buf, pos, 1);
  117. buf[pos++] = semicolon;
  118. }
  119. if (line.length === 0)
  120. continue;
  121. state[0] = 0;
  122. for (let j = 0; j < line.length; j++) {
  123. const segment = line[j];
  124. buf = reserve(buf, pos, 36);
  125. if (j > 0)
  126. buf[pos++] = comma;
  127. pos = encodeInteger(buf, pos, state, segment, 0);
  128. if (segment.length === 1)
  129. continue;
  130. pos = encodeInteger(buf, pos, state, segment, 1);
  131. pos = encodeInteger(buf, pos, state, segment, 2);
  132. pos = encodeInteger(buf, pos, state, segment, 3);
  133. if (segment.length === 4)
  134. continue;
  135. pos = encodeInteger(buf, pos, state, segment, 4);
  136. }
  137. }
  138. return td.decode(buf.subarray(0, pos));
  139. }
  140. function reserve(buf, pos, count) {
  141. if (buf.length > pos + count)
  142. return buf;
  143. const swap = new Uint8Array(buf.length * 2);
  144. swap.set(buf);
  145. return swap;
  146. }
  147. function encodeInteger(buf, pos, state, segment, j) {
  148. const next = segment[j];
  149. let num = next - state[j];
  150. state[j] = next;
  151. num = num < 0 ? -num << 1 | 1 : num << 1;
  152. do {
  153. let clamped = num & 31;
  154. num >>>= 5;
  155. if (num > 0)
  156. clamped |= 32;
  157. buf[pos++] = intToChar[clamped];
  158. } while (num > 0);
  159. return pos;
  160. }
  161. // node_modules/.pnpm/@jridgewell+resolve-uri@3.0.5/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs
  162. var schemeRegex = /^[\w+.-]+:\/\//;
  163. var urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?/;
  164. function isAbsoluteUrl(input) {
  165. return schemeRegex.test(input);
  166. }
  167. function isSchemeRelativeUrl(input) {
  168. return input.startsWith("//");
  169. }
  170. function isAbsolutePath(input) {
  171. return input.startsWith("/");
  172. }
  173. function parseAbsoluteUrl(input) {
  174. const match = urlRegex.exec(input);
  175. return {
  176. scheme: match[1],
  177. user: match[2] || "",
  178. host: match[3],
  179. port: match[4] || "",
  180. path: match[5] || "/",
  181. relativePath: false
  182. };
  183. }
  184. function parseUrl(input) {
  185. if (isSchemeRelativeUrl(input)) {
  186. const url = parseAbsoluteUrl("http:" + input);
  187. url.scheme = "";
  188. return url;
  189. }
  190. if (isAbsolutePath(input)) {
  191. const url = parseAbsoluteUrl("http://foo.com" + input);
  192. url.scheme = "";
  193. url.host = "";
  194. return url;
  195. }
  196. if (!isAbsoluteUrl(input)) {
  197. const url = parseAbsoluteUrl("http://foo.com/" + input);
  198. url.scheme = "";
  199. url.host = "";
  200. url.relativePath = true;
  201. return url;
  202. }
  203. return parseAbsoluteUrl(input);
  204. }
  205. function stripPathFilename(path2) {
  206. if (path2.endsWith("/.."))
  207. return path2;
  208. const index = path2.lastIndexOf("/");
  209. return path2.slice(0, index + 1);
  210. }
  211. function mergePaths(url, base) {
  212. if (!url.relativePath)
  213. return;
  214. normalizePath(base);
  215. if (url.path === "/") {
  216. url.path = base.path;
  217. } else {
  218. url.path = stripPathFilename(base.path) + url.path;
  219. }
  220. url.relativePath = base.relativePath;
  221. }
  222. function normalizePath(url) {
  223. const { relativePath } = url;
  224. const pieces = url.path.split("/");
  225. let pointer = 1;
  226. let positive = 0;
  227. let addTrailingSlash = false;
  228. for (let i2 = 1; i2 < pieces.length; i2++) {
  229. const piece = pieces[i2];
  230. if (!piece) {
  231. addTrailingSlash = true;
  232. continue;
  233. }
  234. addTrailingSlash = false;
  235. if (piece === ".")
  236. continue;
  237. if (piece === "..") {
  238. if (positive) {
  239. addTrailingSlash = true;
  240. positive--;
  241. pointer--;
  242. } else if (relativePath) {
  243. pieces[pointer++] = piece;
  244. }
  245. continue;
  246. }
  247. pieces[pointer++] = piece;
  248. positive++;
  249. }
  250. let path2 = "";
  251. for (let i2 = 1; i2 < pointer; i2++) {
  252. path2 += "/" + pieces[i2];
  253. }
  254. if (!path2 || addTrailingSlash && !path2.endsWith("/..")) {
  255. path2 += "/";
  256. }
  257. url.path = path2;
  258. }
  259. function resolve(input, base) {
  260. if (!input && !base)
  261. return "";
  262. const url = parseUrl(input);
  263. if (base && !url.scheme) {
  264. const baseUrl = parseUrl(base);
  265. url.scheme = baseUrl.scheme;
  266. if (!url.host || baseUrl.scheme === "file:") {
  267. url.user = baseUrl.user;
  268. url.host = baseUrl.host;
  269. url.port = baseUrl.port;
  270. }
  271. mergePaths(url, baseUrl);
  272. }
  273. normalizePath(url);
  274. if (url.relativePath) {
  275. const path2 = url.path.slice(1);
  276. if (!path2)
  277. return ".";
  278. const keepRelative = (base || input).startsWith(".");
  279. return !keepRelative || path2.startsWith(".") ? path2 : "./" + path2;
  280. }
  281. if (!url.scheme && !url.host)
  282. return url.path;
  283. return `${url.scheme}//${url.user}${url.host}${url.port}${url.path}`;
  284. }
  285. // node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs
  286. function resolve2(input, base) {
  287. if (base && !base.endsWith("/"))
  288. base += "/";
  289. return resolve(input, base);
  290. }
  291. function stripFilename(path2) {
  292. if (!path2)
  293. return "";
  294. const index = path2.lastIndexOf("/");
  295. return path2.slice(0, index + 1);
  296. }
  297. var COLUMN = 0;
  298. var SOURCES_INDEX = 1;
  299. var SOURCE_LINE = 2;
  300. var SOURCE_COLUMN = 3;
  301. var NAMES_INDEX = 4;
  302. var REV_GENERATED_LINE = 1;
  303. var REV_GENERATED_COLUMN = 2;
  304. function maybeSort(mappings, owned) {
  305. const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
  306. if (unsortedIndex === mappings.length)
  307. return mappings;
  308. if (!owned)
  309. mappings = mappings.slice();
  310. for (let i2 = unsortedIndex; i2 < mappings.length; i2 = nextUnsortedSegmentLine(mappings, i2 + 1)) {
  311. mappings[i2] = sortSegments(mappings[i2], owned);
  312. }
  313. return mappings;
  314. }
  315. function nextUnsortedSegmentLine(mappings, start) {
  316. for (let i2 = start; i2 < mappings.length; i2++) {
  317. if (!isSorted(mappings[i2]))
  318. return i2;
  319. }
  320. return mappings.length;
  321. }
  322. function isSorted(line) {
  323. for (let j = 1; j < line.length; j++) {
  324. if (line[j][COLUMN] < line[j - 1][COLUMN]) {
  325. return false;
  326. }
  327. }
  328. return true;
  329. }
  330. function sortSegments(line, owned) {
  331. if (!owned)
  332. line = line.slice();
  333. return line.sort(sortComparator2);
  334. }
  335. function sortComparator2(a, b) {
  336. return a[COLUMN] - b[COLUMN];
  337. }
  338. var found = false;
  339. function binarySearch(haystack, needle, low, high) {
  340. while (low <= high) {
  341. const mid = low + (high - low >> 1);
  342. const cmp = haystack[mid][COLUMN] - needle;
  343. if (cmp === 0) {
  344. found = true;
  345. return mid;
  346. }
  347. if (cmp < 0) {
  348. low = mid + 1;
  349. } else {
  350. high = mid - 1;
  351. }
  352. }
  353. found = false;
  354. return low - 1;
  355. }
  356. function upperBound(haystack, needle, index) {
  357. for (let i2 = index + 1; i2 < haystack.length; i2++, index++) {
  358. if (haystack[i2][COLUMN] !== needle)
  359. break;
  360. }
  361. return index;
  362. }
  363. function lowerBound(haystack, needle, index) {
  364. for (let i2 = index - 1; i2 >= 0; i2--, index--) {
  365. if (haystack[i2][COLUMN] !== needle)
  366. break;
  367. }
  368. return index;
  369. }
  370. function memoizedState() {
  371. return {
  372. lastKey: -1,
  373. lastNeedle: -1,
  374. lastIndex: -1
  375. };
  376. }
  377. function memoizedBinarySearch(haystack, needle, state, key) {
  378. const { lastKey, lastNeedle, lastIndex } = state;
  379. let low = 0;
  380. let high = haystack.length - 1;
  381. if (key === lastKey) {
  382. if (needle === lastNeedle) {
  383. found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
  384. return lastIndex;
  385. }
  386. if (needle >= lastNeedle) {
  387. low = lastIndex === -1 ? 0 : lastIndex;
  388. } else {
  389. high = lastIndex;
  390. }
  391. }
  392. state.lastKey = key;
  393. state.lastNeedle = needle;
  394. return state.lastIndex = binarySearch(haystack, needle, low, high);
  395. }
  396. function buildBySources(decoded, memos) {
  397. const sources2 = memos.map(buildNullArray);
  398. for (let i2 = 0; i2 < decoded.length; i2++) {
  399. const line = decoded[i2];
  400. for (let j = 0; j < line.length; j++) {
  401. const seg = line[j];
  402. if (seg.length === 1)
  403. continue;
  404. const sourceIndex = seg[SOURCES_INDEX];
  405. const sourceLine = seg[SOURCE_LINE];
  406. const sourceColumn = seg[SOURCE_COLUMN];
  407. const originalSource = sources2[sourceIndex];
  408. const originalLine = originalSource[sourceLine] || (originalSource[sourceLine] = []);
  409. const memo = memos[sourceIndex];
  410. const index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine));
  411. insert(originalLine, memo.lastIndex = index + 1, [sourceColumn, i2, seg[COLUMN]]);
  412. }
  413. }
  414. return sources2;
  415. }
  416. function insert(array, index, value) {
  417. for (let i2 = array.length; i2 > index; i2--) {
  418. array[i2] = array[i2 - 1];
  419. }
  420. array[index] = value;
  421. }
  422. function buildNullArray() {
  423. return { __proto__: null };
  424. }
  425. var INVALID_ORIGINAL_MAPPING = Object.freeze({
  426. source: null,
  427. line: null,
  428. column: null,
  429. name: null
  430. });
  431. var INVALID_GENERATED_MAPPING = Object.freeze({
  432. line: null,
  433. column: null
  434. });
  435. var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)";
  436. var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)";
  437. var LEAST_UPPER_BOUND = -1;
  438. var GREATEST_LOWER_BOUND = 1;
  439. var encodedMappings;
  440. var decodedMappings;
  441. var traceSegment;
  442. var originalPositionFor;
  443. var generatedPositionFor;
  444. var eachMapping;
  445. var presortedDecodedMap;
  446. var decodedMap;
  447. var encodedMap;
  448. var TraceMap = class {
  449. constructor(map, mapUrl) {
  450. this._decodedMemo = memoizedState();
  451. this._bySources = void 0;
  452. this._bySourceMemos = void 0;
  453. const isString = typeof map === "string";
  454. if (!isString && map.constructor === TraceMap)
  455. return map;
  456. const parsed = isString ? JSON.parse(map) : map;
  457. const { version, file, names, sourceRoot, sources: sources2, sourcesContent } = parsed;
  458. this.version = version;
  459. this.file = file;
  460. this.names = names;
  461. this.sourceRoot = sourceRoot;
  462. this.sources = sources2;
  463. this.sourcesContent = sourcesContent;
  464. if (sourceRoot || mapUrl) {
  465. const from = resolve2(sourceRoot || "", stripFilename(mapUrl));
  466. this.resolvedSources = sources2.map((s) => resolve2(s || "", from));
  467. } else {
  468. this.resolvedSources = sources2.map((s) => s || "");
  469. }
  470. const { mappings } = parsed;
  471. if (typeof mappings === "string") {
  472. this._encoded = mappings;
  473. this._decoded = void 0;
  474. } else {
  475. this._encoded = void 0;
  476. this._decoded = maybeSort(mappings, isString);
  477. }
  478. }
  479. };
  480. (() => {
  481. encodedMappings = (map) => {
  482. var _a;
  483. return (_a = map._encoded) !== null && _a !== void 0 ? _a : map._encoded = encode(map._decoded);
  484. };
  485. decodedMappings = (map) => {
  486. return map._decoded || (map._decoded = decode(map._encoded));
  487. };
  488. traceSegment = (map, line, column) => {
  489. const decoded = decodedMappings(map);
  490. if (line >= decoded.length)
  491. return null;
  492. return traceSegmentInternal(decoded[line], map._decodedMemo, line, column, GREATEST_LOWER_BOUND);
  493. };
  494. originalPositionFor = (map, { line, column, bias }) => {
  495. line--;
  496. if (line < 0)
  497. throw new Error(LINE_GTR_ZERO);
  498. if (column < 0)
  499. throw new Error(COL_GTR_EQ_ZERO);
  500. const decoded = decodedMappings(map);
  501. if (line >= decoded.length)
  502. return INVALID_ORIGINAL_MAPPING;
  503. const segment = traceSegmentInternal(decoded[line], map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
  504. if (segment == null)
  505. return INVALID_ORIGINAL_MAPPING;
  506. if (segment.length == 1)
  507. return INVALID_ORIGINAL_MAPPING;
  508. const { names, resolvedSources } = map;
  509. return {
  510. source: resolvedSources[segment[SOURCES_INDEX]],
  511. line: segment[SOURCE_LINE] + 1,
  512. column: segment[SOURCE_COLUMN],
  513. name: segment.length === 5 ? names[segment[NAMES_INDEX]] : null
  514. };
  515. };
  516. generatedPositionFor = (map, { source, line, column, bias }) => {
  517. line--;
  518. if (line < 0)
  519. throw new Error(LINE_GTR_ZERO);
  520. if (column < 0)
  521. throw new Error(COL_GTR_EQ_ZERO);
  522. const { sources: sources2, resolvedSources } = map;
  523. let sourceIndex = sources2.indexOf(source);
  524. if (sourceIndex === -1)
  525. sourceIndex = resolvedSources.indexOf(source);
  526. if (sourceIndex === -1)
  527. return INVALID_GENERATED_MAPPING;
  528. const generated = map._bySources || (map._bySources = buildBySources(decodedMappings(map), map._bySourceMemos = sources2.map(memoizedState)));
  529. const memos = map._bySourceMemos;
  530. const segments = generated[sourceIndex][line];
  531. if (segments == null)
  532. return INVALID_GENERATED_MAPPING;
  533. const segment = traceSegmentInternal(segments, memos[sourceIndex], line, column, bias || GREATEST_LOWER_BOUND);
  534. if (segment == null)
  535. return INVALID_GENERATED_MAPPING;
  536. return {
  537. line: segment[REV_GENERATED_LINE] + 1,
  538. column: segment[REV_GENERATED_COLUMN]
  539. };
  540. };
  541. eachMapping = (map, cb) => {
  542. const decoded = decodedMappings(map);
  543. const { names, resolvedSources } = map;
  544. for (let i2 = 0; i2 < decoded.length; i2++) {
  545. const line = decoded[i2];
  546. for (let j = 0; j < line.length; j++) {
  547. const seg = line[j];
  548. const generatedLine = i2 + 1;
  549. const generatedColumn = seg[0];
  550. let source = null;
  551. let originalLine = null;
  552. let originalColumn = null;
  553. let name = null;
  554. if (seg.length !== 1) {
  555. source = resolvedSources[seg[1]];
  556. originalLine = seg[2] + 1;
  557. originalColumn = seg[3];
  558. }
  559. if (seg.length === 5)
  560. name = names[seg[4]];
  561. cb({
  562. generatedLine,
  563. generatedColumn,
  564. source,
  565. originalLine,
  566. originalColumn,
  567. name
  568. });
  569. }
  570. }
  571. };
  572. presortedDecodedMap = (map, mapUrl) => {
  573. const clone = Object.assign({}, map);
  574. clone.mappings = [];
  575. const tracer = new TraceMap(clone, mapUrl);
  576. tracer._decoded = map.mappings;
  577. return tracer;
  578. };
  579. decodedMap = (map) => {
  580. return {
  581. version: 3,
  582. file: map.file,
  583. names: map.names,
  584. sourceRoot: map.sourceRoot,
  585. sources: map.sources,
  586. sourcesContent: map.sourcesContent,
  587. mappings: decodedMappings(map)
  588. };
  589. };
  590. encodedMap = (map) => {
  591. return {
  592. version: 3,
  593. file: map.file,
  594. names: map.names,
  595. sourceRoot: map.sourceRoot,
  596. sources: map.sources,
  597. sourcesContent: map.sourcesContent,
  598. mappings: encodedMappings(map)
  599. };
  600. };
  601. })();
  602. function traceSegmentInternal(segments, memo, line, column, bias) {
  603. let index = memoizedBinarySearch(segments, column, memo, line);
  604. if (found) {
  605. index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
  606. } else if (bias === LEAST_UPPER_BOUND)
  607. index++;
  608. if (index === -1 || index === segments.length)
  609. return null;
  610. return segments[index];
  611. }
  612. // node_modules/.pnpm/@jridgewell+set-array@1.1.0/node_modules/@jridgewell/set-array/dist/set-array.mjs
  613. var get;
  614. var put;
  615. var pop;
  616. var SetArray = class {
  617. constructor() {
  618. this._indexes = { __proto__: null };
  619. this.array = [];
  620. }
  621. };
  622. (() => {
  623. get = (strarr, key) => strarr._indexes[key];
  624. put = (strarr, key) => {
  625. const index = get(strarr, key);
  626. if (index !== void 0)
  627. return index;
  628. const { array, _indexes: indexes } = strarr;
  629. return indexes[key] = array.push(key) - 1;
  630. };
  631. pop = (strarr) => {
  632. const { array, _indexes: indexes } = strarr;
  633. if (array.length === 0)
  634. return;
  635. const last = array.pop();
  636. indexes[last] = void 0;
  637. };
  638. })();
  639. // node_modules/.pnpm/@jridgewell+gen-mapping@0.1.1/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs
  640. var addSegment;
  641. var addMapping;
  642. var setSourceContent;
  643. var decodedMap2;
  644. var encodedMap2;
  645. var allMappings;
  646. var GenMapping = class {
  647. constructor({ file, sourceRoot } = {}) {
  648. this._names = new SetArray();
  649. this._sources = new SetArray();
  650. this._sourcesContent = [];
  651. this._mappings = [];
  652. this.file = file;
  653. this.sourceRoot = sourceRoot;
  654. }
  655. };
  656. (() => {
  657. addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name) => {
  658. const { _mappings: mappings, _sources: sources2, _sourcesContent: sourcesContent, _names: names } = map;
  659. const line = getLine(mappings, genLine);
  660. if (source == null) {
  661. const seg2 = [genColumn];
  662. const index2 = getColumnIndex(line, genColumn, seg2);
  663. return insert2(line, index2, seg2);
  664. }
  665. const sourcesIndex = put(sources2, source);
  666. const seg = name ? [genColumn, sourcesIndex, sourceLine, sourceColumn, put(names, name)] : [genColumn, sourcesIndex, sourceLine, sourceColumn];
  667. const index = getColumnIndex(line, genColumn, seg);
  668. if (sourcesIndex === sourcesContent.length)
  669. sourcesContent[sourcesIndex] = null;
  670. insert2(line, index, seg);
  671. };
  672. addMapping = (map, mapping) => {
  673. const { generated, source, original, name } = mapping;
  674. return addSegment(map, generated.line - 1, generated.column, source, original == null ? void 0 : original.line - 1, original === null || original === void 0 ? void 0 : original.column, name);
  675. };
  676. setSourceContent = (map, source, content) => {
  677. const { _sources: sources2, _sourcesContent: sourcesContent } = map;
  678. sourcesContent[put(sources2, source)] = content;
  679. };
  680. decodedMap2 = (map) => {
  681. const { file, sourceRoot, _mappings: mappings, _sources: sources2, _sourcesContent: sourcesContent, _names: names } = map;
  682. return {
  683. version: 3,
  684. file,
  685. names: names.array,
  686. sourceRoot: sourceRoot || void 0,
  687. sources: sources2.array,
  688. sourcesContent,
  689. mappings
  690. };
  691. };
  692. encodedMap2 = (map) => {
  693. const decoded = decodedMap2(map);
  694. return Object.assign(Object.assign({}, decoded), { mappings: encode(decoded.mappings) });
  695. };
  696. allMappings = (map) => {
  697. const out = [];
  698. const { _mappings: mappings, _sources: sources2, _names: names } = map;
  699. for (let i2 = 0; i2 < mappings.length; i2++) {
  700. const line = mappings[i2];
  701. for (let j = 0; j < line.length; j++) {
  702. const seg = line[j];
  703. const generated = { line: i2 + 1, column: seg[0] };
  704. let source = void 0;
  705. let original = void 0;
  706. let name = void 0;
  707. if (seg.length !== 1) {
  708. source = sources2.array[seg[1]];
  709. original = { line: seg[2] + 1, column: seg[3] };
  710. if (seg.length === 5)
  711. name = names.array[seg[4]];
  712. }
  713. out.push({ generated, source, original, name });
  714. }
  715. }
  716. return out;
  717. };
  718. })();
  719. function getLine(mappings, index) {
  720. for (let i2 = mappings.length; i2 <= index; i2++) {
  721. mappings[i2] = [];
  722. }
  723. return mappings[index];
  724. }
  725. function getColumnIndex(line, column, seg) {
  726. let index = line.length;
  727. for (let i2 = index - 1; i2 >= 0; i2--, index--) {
  728. const current = line[i2];
  729. const col = current[0];
  730. if (col > column)
  731. continue;
  732. if (col < column)
  733. break;
  734. const cmp = compare(current, seg);
  735. if (cmp === 0)
  736. return index;
  737. if (cmp < 0)
  738. break;
  739. }
  740. return index;
  741. }
  742. function compare(a, b) {
  743. let cmp = compareNum(a.length, b.length);
  744. if (cmp !== 0)
  745. return cmp;
  746. if (a.length === 1)
  747. return 0;
  748. cmp = compareNum(a[1], b[1]);
  749. if (cmp !== 0)
  750. return cmp;
  751. cmp = compareNum(a[2], b[2]);
  752. if (cmp !== 0)
  753. return cmp;
  754. cmp = compareNum(a[3], b[3]);
  755. if (cmp !== 0)
  756. return cmp;
  757. if (a.length === 4)
  758. return 0;
  759. return compareNum(a[4], b[4]);
  760. }
  761. function compareNum(a, b) {
  762. return a - b;
  763. }
  764. function insert2(array, index, value) {
  765. if (index === -1)
  766. return;
  767. for (let i2 = array.length; i2 > index; i2--) {
  768. array[i2] = array[i2 - 1];
  769. }
  770. array[index] = value;
  771. }
  772. // node_modules/.pnpm/@ampproject+remapping@2.2.0/node_modules/@ampproject/remapping/dist/remapping.mjs
  773. var SOURCELESS_MAPPING = {
  774. source: null,
  775. column: null,
  776. line: null,
  777. name: null,
  778. content: null
  779. };
  780. var EMPTY_SOURCES = [];
  781. function Source(map, sources2, source, content) {
  782. return {
  783. map,
  784. sources: sources2,
  785. source,
  786. content
  787. };
  788. }
  789. function MapSource(map, sources2) {
  790. return Source(map, sources2, "", null);
  791. }
  792. function OriginalSource(source, content) {
  793. return Source(null, EMPTY_SOURCES, source, content);
  794. }
  795. function traceMappings(tree) {
  796. const gen = new GenMapping({ file: tree.map.file });
  797. const { sources: rootSources, map } = tree;
  798. const rootNames = map.names;
  799. const rootMappings = decodedMappings(map);
  800. for (let i2 = 0; i2 < rootMappings.length; i2++) {
  801. const segments = rootMappings[i2];
  802. let lastSource = null;
  803. let lastSourceLine = null;
  804. let lastSourceColumn = null;
  805. for (let j = 0; j < segments.length; j++) {
  806. const segment = segments[j];
  807. const genCol = segment[0];
  808. let traced = SOURCELESS_MAPPING;
  809. if (segment.length !== 1) {
  810. const source2 = rootSources[segment[1]];
  811. traced = originalPositionFor2(source2, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : "");
  812. if (traced == null)
  813. continue;
  814. }
  815. const { column, line, name, content, source } = traced;
  816. if (line === lastSourceLine && column === lastSourceColumn && source === lastSource) {
  817. continue;
  818. }
  819. lastSourceLine = line;
  820. lastSourceColumn = column;
  821. lastSource = source;
  822. addSegment(gen, i2, genCol, source, line, column, name);
  823. if (content != null)
  824. setSourceContent(gen, source, content);
  825. }
  826. }
  827. return gen;
  828. }
  829. function originalPositionFor2(source, line, column, name) {
  830. if (!source.map) {
  831. return { column, line, name, source: source.source, content: source.content };
  832. }
  833. const segment = traceSegment(source.map, line, column);
  834. if (segment == null)
  835. return null;
  836. if (segment.length === 1)
  837. return SOURCELESS_MAPPING;
  838. return originalPositionFor2(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name);
  839. }
  840. function asArray(value) {
  841. if (Array.isArray(value))
  842. return value;
  843. return [value];
  844. }
  845. function buildSourceMapTree(input, loader) {
  846. const maps = asArray(input).map((m) => new TraceMap(m, ""));
  847. const map = maps.pop();
  848. for (let i2 = 0; i2 < maps.length; i2++) {
  849. if (maps[i2].sources.length > 1) {
  850. throw new Error(`Transformation map ${i2} must have exactly one source file.
  851. Did you specify these with the most recent transformation maps first?`);
  852. }
  853. }
  854. let tree = build(map, loader, "", 0);
  855. for (let i2 = maps.length - 1; i2 >= 0; i2--) {
  856. tree = MapSource(maps[i2], [tree]);
  857. }
  858. return tree;
  859. }
  860. function build(map, loader, importer, importerDepth) {
  861. const { resolvedSources, sourcesContent } = map;
  862. const depth = importerDepth + 1;
  863. const children = resolvedSources.map((sourceFile, i2) => {
  864. const ctx = {
  865. importer,
  866. depth,
  867. source: sourceFile || "",
  868. content: void 0
  869. };
  870. const sourceMap = loader(ctx.source, ctx);
  871. const { source, content } = ctx;
  872. if (sourceMap)
  873. return build(new TraceMap(sourceMap, source), loader, source, depth);
  874. const sourceContent = content !== void 0 ? content : sourcesContent ? sourcesContent[i2] : null;
  875. return OriginalSource(source, sourceContent);
  876. });
  877. return MapSource(map, children);
  878. }
  879. var SourceMap = class {
  880. constructor(map, options) {
  881. const out = options.decodedMappings ? decodedMap2(map) : encodedMap2(map);
  882. this.version = out.version;
  883. this.file = out.file;
  884. this.mappings = out.mappings;
  885. this.names = out.names;
  886. this.sourceRoot = out.sourceRoot;
  887. this.sources = out.sources;
  888. if (!options.excludeContent) {
  889. this.sourcesContent = out.sourcesContent;
  890. }
  891. }
  892. toString() {
  893. return JSON.stringify(this);
  894. }
  895. };
  896. function remapping(input, loader, options) {
  897. const opts = typeof options === "object" ? options : { excludeContent: !!options, decodedMappings: false };
  898. const tree = buildSourceMapTree(input, loader);
  899. return new SourceMap(traceMappings(tree), opts);
  900. }
  901. // src/utils.ts
  902. import { isAbsolute, normalize } from "path";
  903. function normalizeAbsolutePath(path2) {
  904. if (isAbsolute(path2))
  905. return normalize(path2);
  906. else
  907. return path2;
  908. }
  909. function toArray(array) {
  910. array = array || [];
  911. if (Array.isArray(array))
  912. return array;
  913. return [array];
  914. }
  915. // src/esbuild/utils.ts
  916. var ExtToLoader = {
  917. ".js": "js",
  918. ".mjs": "js",
  919. ".cjs": "js",
  920. ".jsx": "jsx",
  921. ".ts": "ts",
  922. ".cts": "ts",
  923. ".mts": "ts",
  924. ".tsx": "tsx",
  925. ".css": "css",
  926. ".less": "css",
  927. ".stylus": "css",
  928. ".scss": "css",
  929. ".sass": "css",
  930. ".json": "json",
  931. ".txt": "text"
  932. };
  933. function guessLoader(id) {
  934. return ExtToLoader[extname(id).toLowerCase()] || "js";
  935. }
  936. function fixSourceMap(map) {
  937. if (!("toString" in map)) {
  938. Object.defineProperty(map, "toString", {
  939. enumerable: false,
  940. value: function toString() {
  941. return JSON.stringify(this);
  942. }
  943. });
  944. }
  945. if (!("toUrl" in map)) {
  946. Object.defineProperty(map, "toUrl", {
  947. enumerable: false,
  948. value: function toUrl() {
  949. return `data:application/json;charset=utf-8;base64,${Buffer.from(this.toString()).toString("base64")}`;
  950. }
  951. });
  952. }
  953. return map;
  954. }
  955. var nullSourceMap = {
  956. names: [],
  957. sources: [],
  958. mappings: "",
  959. version: 3
  960. };
  961. function combineSourcemaps(filename, sourcemapList) {
  962. sourcemapList = sourcemapList.filter((m) => m.sources);
  963. if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0))
  964. return { ...nullSourceMap };
  965. let map;
  966. let mapIndex = 1;
  967. const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === void 0;
  968. if (useArrayInterface) {
  969. map = remapping(sourcemapList, () => null, true);
  970. } else {
  971. map = remapping(
  972. sourcemapList[0],
  973. (sourcefile) => {
  974. if (sourcefile === filename && sourcemapList[mapIndex])
  975. return sourcemapList[mapIndex++];
  976. else
  977. return { ...nullSourceMap };
  978. },
  979. true
  980. );
  981. }
  982. if (!map.file)
  983. delete map.file;
  984. return map;
  985. }
  986. // src/esbuild/index.ts
  987. var watchListRecord = {};
  988. var watchList = /* @__PURE__ */ new Set();
  989. var i = 0;
  990. function getEsbuildPlugin(factory) {
  991. return (userOptions) => {
  992. const meta = {
  993. framework: "esbuild"
  994. };
  995. const plugins = toArray(factory(userOptions, meta));
  996. const setup = (plugin) => plugin.esbuild?.setup ?? ((pluginBuild) => {
  997. const { onStart, onEnd, onResolve, onLoad, initialOptions, esbuild: { build: build2 } } = pluginBuild;
  998. meta.build = pluginBuild;
  999. const onResolveFilter = plugin.esbuild?.onResolveFilter ?? /.*/;
  1000. const onLoadFilter = plugin.esbuild?.onLoadFilter ?? /.*/;
  1001. const context = {
  1002. parse(code, opts = {}) {
  1003. return Parser.parse(code, {
  1004. sourceType: "module",
  1005. ecmaVersion: "latest",
  1006. locations: true,
  1007. ...opts
  1008. });
  1009. },
  1010. addWatchFile(id) {
  1011. watchList.add(path.resolve(id));
  1012. },
  1013. emitFile(emittedFile) {
  1014. const outFileName = emittedFile.fileName || emittedFile.name;
  1015. if (initialOptions.outdir && emittedFile.source && outFileName)
  1016. fs.writeFileSync(path.resolve(initialOptions.outdir, outFileName), emittedFile.source);
  1017. },
  1018. getWatchFiles() {
  1019. return Array.from(watchList);
  1020. }
  1021. };
  1022. if (initialOptions.outdir && !fs.existsSync(initialOptions.outdir))
  1023. fs.mkdirSync(initialOptions.outdir, { recursive: true });
  1024. if (plugin.buildStart)
  1025. onStart(() => plugin.buildStart.call(context));
  1026. if (plugin.buildEnd || plugin.writeBundle || initialOptions.watch) {
  1027. const rebuild = () => build2({
  1028. ...initialOptions,
  1029. watch: false
  1030. });
  1031. onEnd(async () => {
  1032. if (plugin.buildEnd)
  1033. await plugin.buildEnd.call(context);
  1034. if (plugin.writeBundle)
  1035. await plugin.writeBundle();
  1036. if (initialOptions.watch) {
  1037. Object.keys(watchListRecord).forEach((id) => {
  1038. if (!watchList.has(id)) {
  1039. watchListRecord[id].close();
  1040. delete watchListRecord[id];
  1041. }
  1042. });
  1043. watchList.forEach((id) => {
  1044. if (!Object.keys(watchListRecord).includes(id)) {
  1045. watchListRecord[id] = chokidar.watch(id);
  1046. watchListRecord[id].on("change", async () => {
  1047. await plugin.watchChange?.call(context, id, { event: "update" });
  1048. rebuild();
  1049. });
  1050. watchListRecord[id].on("unlink", async () => {
  1051. await plugin.watchChange?.call(context, id, { event: "delete" });
  1052. rebuild();
  1053. });
  1054. }
  1055. });
  1056. }
  1057. });
  1058. }
  1059. if (plugin.resolveId) {
  1060. onResolve({ filter: onResolveFilter }, async (args) => {
  1061. if (initialOptions.external?.includes(args.path)) {
  1062. return void 0;
  1063. }
  1064. const isEntry = args.kind === "entry-point";
  1065. const result = await plugin.resolveId(
  1066. args.path,
  1067. isEntry ? void 0 : args.importer,
  1068. { isEntry }
  1069. );
  1070. if (typeof result === "string")
  1071. return { path: result, namespace: plugin.name };
  1072. else if (typeof result === "object" && result !== null)
  1073. return { path: result.id, external: result.external, namespace: plugin.name };
  1074. });
  1075. }
  1076. if (plugin.load || plugin.transform) {
  1077. onLoad({ filter: onLoadFilter }, async (args) => {
  1078. const id = args.path + args.suffix;
  1079. const errors = [];
  1080. const warnings = [];
  1081. const pluginContext = {
  1082. error(message) {
  1083. errors.push({ text: String(message) });
  1084. },
  1085. warn(message) {
  1086. warnings.push({ text: String(message) });
  1087. }
  1088. };
  1089. const resolveDir = path.dirname(args.path);
  1090. let code, map;
  1091. if (plugin.load && (!plugin.loadInclude || plugin.loadInclude(id))) {
  1092. const result = await plugin.load.call(Object.assign(context, pluginContext), id);
  1093. if (typeof result === "string") {
  1094. code = result;
  1095. } else if (typeof result === "object" && result !== null) {
  1096. code = result.code;
  1097. map = result.map;
  1098. }
  1099. }
  1100. if (!plugin.transform) {
  1101. if (code === void 0)
  1102. return null;
  1103. if (map) {
  1104. if (!map.sourcesContent || map.sourcesContent.length === 0)
  1105. map.sourcesContent = [code];
  1106. map = fixSourceMap(map);
  1107. code += `
  1108. //# sourceMappingURL=${map.toUrl()}`;
  1109. }
  1110. return { contents: code, errors, warnings, loader: guessLoader(args.path), resolveDir };
  1111. }
  1112. if (!plugin.transformInclude || plugin.transformInclude(id)) {
  1113. if (!code) {
  1114. code = await fs.promises.readFile(args.path, "utf8");
  1115. }
  1116. const result = await plugin.transform.call(Object.assign(context, pluginContext), code, id);
  1117. if (typeof result === "string") {
  1118. code = result;
  1119. } else if (typeof result === "object" && result !== null) {
  1120. code = result.code;
  1121. if (map && result.map) {
  1122. map = combineSourcemaps(args.path, [
  1123. result.map,
  1124. map
  1125. ]);
  1126. } else {
  1127. map = result.map;
  1128. }
  1129. }
  1130. }
  1131. if (code) {
  1132. if (map) {
  1133. if (!map.sourcesContent || map.sourcesContent.length === 0)
  1134. map.sourcesContent = [code];
  1135. map = fixSourceMap(map);
  1136. code += `
  1137. //# sourceMappingURL=${map.toUrl()}`;
  1138. }
  1139. return { contents: code, errors, warnings, loader: guessLoader(args.path), resolveDir };
  1140. }
  1141. });
  1142. }
  1143. });
  1144. const setupMultiplePlugins = () => (build2) => {
  1145. for (const plugin of plugins)
  1146. setup(plugin)(build2);
  1147. };
  1148. return plugins.length === 1 ? { name: plugins[0].name, setup: setup(plugins[0]) } : { name: meta.esbuildHostName ?? `unplugin-host-${i++}`, setup: setupMultiplePlugins() };
  1149. };
  1150. }
  1151. // src/rollup/index.ts
  1152. function getRollupPlugin(factory) {
  1153. return (userOptions) => {
  1154. const meta = {
  1155. framework: "rollup"
  1156. };
  1157. const rawPlugins = toArray(factory(userOptions, meta));
  1158. const plugins = rawPlugins.map((plugin) => toRollupPlugin(plugin));
  1159. return plugins.length === 1 ? plugins[0] : plugins;
  1160. };
  1161. }
  1162. function toRollupPlugin(plugin, containRollupOptions = true) {
  1163. if (plugin.transform && plugin.transformInclude) {
  1164. const _transform = plugin.transform;
  1165. plugin.transform = function(code, id) {
  1166. if (plugin.transformInclude && !plugin.transformInclude(id))
  1167. return null;
  1168. return _transform.call(this, code, id);
  1169. };
  1170. }
  1171. if (plugin.load && plugin.loadInclude) {
  1172. const _load = plugin.load;
  1173. plugin.load = function(id) {
  1174. if (plugin.loadInclude && !plugin.loadInclude(id))
  1175. return null;
  1176. return _load.call(this, id);
  1177. };
  1178. }
  1179. if (plugin.rollup && containRollupOptions)
  1180. Object.assign(plugin, plugin.rollup);
  1181. return plugin;
  1182. }
  1183. // src/vite/index.ts
  1184. function getVitePlugin(factory) {
  1185. return (userOptions) => {
  1186. const meta = {
  1187. framework: "vite"
  1188. };
  1189. const rawPlugins = toArray(factory(userOptions, meta));
  1190. const plugins = rawPlugins.map((rawPlugin) => {
  1191. const plugin = toRollupPlugin(rawPlugin, false);
  1192. if (rawPlugin.vite)
  1193. Object.assign(plugin, rawPlugin.vite);
  1194. return plugin;
  1195. });
  1196. return plugins.length === 1 ? plugins[0] : plugins;
  1197. };
  1198. }
  1199. // src/webpack/index.ts
  1200. import fs2 from "fs";
  1201. import { fileURLToPath } from "url";
  1202. import { dirname, resolve as resolve4 } from "path";
  1203. import VirtualModulesPlugin from "webpack-virtual-modules";
  1204. // src/webpack/context.ts
  1205. import { resolve as resolve3 } from "path";
  1206. import sources from "webpack-sources";
  1207. import { Parser as Parser2 } from "acorn";
  1208. function createContext(compilation) {
  1209. return {
  1210. parse(code, opts = {}) {
  1211. return Parser2.parse(code, {
  1212. sourceType: "module",
  1213. ecmaVersion: "latest",
  1214. locations: true,
  1215. ...opts
  1216. });
  1217. },
  1218. addWatchFile(id) {
  1219. (compilation.fileDependencies ?? compilation.compilationDependencies).add(
  1220. resolve3(process.cwd(), id)
  1221. );
  1222. },
  1223. emitFile(emittedFile) {
  1224. const outFileName = emittedFile.fileName || emittedFile.name;
  1225. if (emittedFile.source && outFileName) {
  1226. compilation.emitAsset(
  1227. outFileName,
  1228. sources ? new sources.RawSource(
  1229. typeof emittedFile.source === "string" ? emittedFile.source : Buffer.from(emittedFile.source)
  1230. ) : {
  1231. source: () => emittedFile.source,
  1232. size: () => emittedFile.source.length
  1233. }
  1234. );
  1235. }
  1236. },
  1237. getWatchFiles() {
  1238. return Array.from(
  1239. compilation.fileDependencies ?? compilation.compilationDependencies
  1240. );
  1241. }
  1242. };
  1243. }
  1244. // src/webpack/index.ts
  1245. var _dirname = typeof __dirname !== "undefined" ? __dirname : dirname(fileURLToPath(import.meta.url));
  1246. var TRANSFORM_LOADER = resolve4(
  1247. _dirname,
  1248. false ? "../../dist/webpack/loaders/transform" : "webpack/loaders/transform"
  1249. );
  1250. var LOAD_LOADER = resolve4(
  1251. _dirname,
  1252. false ? "../../dist/webpack/loaders/load" : "webpack/loaders/load"
  1253. );
  1254. var VIRTUAL_MODULE_PREFIX = resolve4(process.cwd(), "_virtual_");
  1255. function getWebpackPlugin(factory) {
  1256. return (userOptions) => {
  1257. return {
  1258. apply(compiler) {
  1259. const injected = compiler.$unpluginContext || {};
  1260. compiler.$unpluginContext = injected;
  1261. const meta = {
  1262. framework: "webpack",
  1263. webpack: {
  1264. compiler
  1265. }
  1266. };
  1267. const rawPlugins = toArray(factory(userOptions, meta));
  1268. for (const rawPlugin of rawPlugins) {
  1269. const plugin = Object.assign(
  1270. rawPlugin,
  1271. {
  1272. __unpluginMeta: meta,
  1273. __virtualModulePrefix: VIRTUAL_MODULE_PREFIX
  1274. }
  1275. );
  1276. injected[plugin.name] = plugin;
  1277. compiler.hooks.thisCompilation.tap(plugin.name, (compilation) => {
  1278. compilation.hooks.childCompiler.tap(plugin.name, (childCompiler) => {
  1279. childCompiler.$unpluginContext = injected;
  1280. });
  1281. });
  1282. const externalModules = /* @__PURE__ */ new Set();
  1283. if (plugin.transform) {
  1284. const useLoader = [{
  1285. loader: `${TRANSFORM_LOADER}?unpluginName=${encodeURIComponent(plugin.name)}`
  1286. }];
  1287. const useNone = [];
  1288. compiler.options.module.rules.unshift({
  1289. enforce: plugin.enforce,
  1290. use: (data) => {
  1291. if (data.resource == null)
  1292. return useNone;
  1293. const id = normalizeAbsolutePath(data.resource + (data.resourceQuery || ""));
  1294. if (!plugin.transformInclude || plugin.transformInclude(id))
  1295. return useLoader;
  1296. return useNone;
  1297. }
  1298. });
  1299. }
  1300. if (plugin.resolveId) {
  1301. let vfs = compiler.options.plugins.find((i2) => i2 instanceof VirtualModulesPlugin);
  1302. if (!vfs) {
  1303. vfs = new VirtualModulesPlugin();
  1304. compiler.options.plugins.push(vfs);
  1305. }
  1306. plugin.__vfsModules = /* @__PURE__ */ new Set();
  1307. plugin.__vfs = vfs;
  1308. const resolverPlugin = {
  1309. apply(resolver) {
  1310. const target = resolver.ensureHook("resolve");
  1311. resolver.getHook("resolve").tapAsync(plugin.name, async (request, resolveContext, callback) => {
  1312. if (!request.request)
  1313. return callback();
  1314. if (normalizeAbsolutePath(request.request).startsWith(plugin.__virtualModulePrefix))
  1315. return callback();
  1316. const id = normalizeAbsolutePath(request.request);
  1317. const requestContext = request.context;
  1318. const importer = requestContext.issuer !== "" ? requestContext.issuer : void 0;
  1319. const isEntry = requestContext.issuer === "";
  1320. const resolveIdResult = await plugin.resolveId(id, importer, { isEntry });
  1321. if (resolveIdResult == null)
  1322. return callback();
  1323. let resolved = typeof resolveIdResult === "string" ? resolveIdResult : resolveIdResult.id;
  1324. const isExternal = typeof resolveIdResult === "string" ? false : resolveIdResult.external === true;
  1325. if (isExternal)
  1326. externalModules.add(resolved);
  1327. if (!fs2.existsSync(resolved)) {
  1328. resolved = normalizeAbsolutePath(
  1329. plugin.__virtualModulePrefix + encodeURIComponent(resolved)
  1330. );
  1331. if (!plugin.__vfsModules.has(resolved)) {
  1332. plugin.__vfs.writeModule(resolved, "");
  1333. plugin.__vfsModules.add(resolved);
  1334. }
  1335. }
  1336. const newRequest = {
  1337. ...request,
  1338. request: resolved
  1339. };
  1340. resolver.doResolve(target, newRequest, null, resolveContext, callback);
  1341. });
  1342. }
  1343. };
  1344. compiler.options.resolve.plugins = compiler.options.resolve.plugins || [];
  1345. compiler.options.resolve.plugins.push(resolverPlugin);
  1346. }
  1347. if (plugin.load) {
  1348. compiler.options.module.rules.unshift({
  1349. include(id) {
  1350. if (id.startsWith(plugin.__virtualModulePrefix))
  1351. id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length));
  1352. if (plugin.loadInclude && !plugin.loadInclude(id))
  1353. return false;
  1354. return !externalModules.has(id);
  1355. },
  1356. enforce: plugin.enforce,
  1357. use: [{
  1358. loader: LOAD_LOADER,
  1359. options: {
  1360. unpluginName: plugin.name
  1361. }
  1362. }]
  1363. });
  1364. }
  1365. if (plugin.webpack)
  1366. plugin.webpack(compiler);
  1367. if (plugin.watchChange || plugin.buildStart) {
  1368. compiler.hooks.make.tapPromise(plugin.name, async (compilation) => {
  1369. const context = createContext(compilation);
  1370. if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) {
  1371. const promises = [];
  1372. if (compiler.modifiedFiles) {
  1373. compiler.modifiedFiles.forEach(
  1374. (file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "update" })))
  1375. );
  1376. }
  1377. if (compiler.removedFiles) {
  1378. compiler.removedFiles.forEach(
  1379. (file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "delete" })))
  1380. );
  1381. }
  1382. await Promise.all(promises);
  1383. }
  1384. if (plugin.buildStart)
  1385. return await plugin.buildStart.call(context);
  1386. });
  1387. }
  1388. if (plugin.buildEnd) {
  1389. compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => {
  1390. await plugin.buildEnd.call(createContext(compilation));
  1391. });
  1392. }
  1393. if (plugin.writeBundle) {
  1394. compiler.hooks.afterEmit.tap(plugin.name, () => {
  1395. plugin.writeBundle();
  1396. });
  1397. }
  1398. }
  1399. }
  1400. };
  1401. };
  1402. }
  1403. // src/define.ts
  1404. function createUnplugin(factory) {
  1405. return {
  1406. get esbuild() {
  1407. return getEsbuildPlugin(factory);
  1408. },
  1409. get rollup() {
  1410. return getRollupPlugin(factory);
  1411. },
  1412. get vite() {
  1413. return getVitePlugin(factory);
  1414. },
  1415. get webpack() {
  1416. return getWebpackPlugin(factory);
  1417. },
  1418. get raw() {
  1419. return factory;
  1420. }
  1421. };
  1422. }
  1423. export {
  1424. createUnplugin
  1425. };