index.js 68 KB

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