index.mjs 65 KB

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