版博士V2.0程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.mjs 46 KiB

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