main.js 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239
  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. // lib/npm/node.ts
  30. var node_exports = {};
  31. __export(node_exports, {
  32. analyzeMetafile: () => analyzeMetafile,
  33. analyzeMetafileSync: () => analyzeMetafileSync,
  34. build: () => build,
  35. buildSync: () => buildSync,
  36. context: () => context,
  37. default: () => node_default,
  38. formatMessages: () => formatMessages,
  39. formatMessagesSync: () => formatMessagesSync,
  40. initialize: () => initialize,
  41. stop: () => stop,
  42. transform: () => transform,
  43. transformSync: () => transformSync,
  44. version: () => version
  45. });
  46. module.exports = __toCommonJS(node_exports);
  47. // lib/shared/stdio_protocol.ts
  48. function encodePacket(packet) {
  49. let visit = (value) => {
  50. if (value === null) {
  51. bb.write8(0);
  52. } else if (typeof value === "boolean") {
  53. bb.write8(1);
  54. bb.write8(+value);
  55. } else if (typeof value === "number") {
  56. bb.write8(2);
  57. bb.write32(value | 0);
  58. } else if (typeof value === "string") {
  59. bb.write8(3);
  60. bb.write(encodeUTF8(value));
  61. } else if (value instanceof Uint8Array) {
  62. bb.write8(4);
  63. bb.write(value);
  64. } else if (value instanceof Array) {
  65. bb.write8(5);
  66. bb.write32(value.length);
  67. for (let item of value) {
  68. visit(item);
  69. }
  70. } else {
  71. let keys = Object.keys(value);
  72. bb.write8(6);
  73. bb.write32(keys.length);
  74. for (let key of keys) {
  75. bb.write(encodeUTF8(key));
  76. visit(value[key]);
  77. }
  78. }
  79. };
  80. let bb = new ByteBuffer();
  81. bb.write32(0);
  82. bb.write32(packet.id << 1 | +!packet.isRequest);
  83. visit(packet.value);
  84. writeUInt32LE(bb.buf, bb.len - 4, 0);
  85. return bb.buf.subarray(0, bb.len);
  86. }
  87. function decodePacket(bytes) {
  88. let visit = () => {
  89. switch (bb.read8()) {
  90. case 0:
  91. return null;
  92. case 1:
  93. return !!bb.read8();
  94. case 2:
  95. return bb.read32();
  96. case 3:
  97. return decodeUTF8(bb.read());
  98. case 4:
  99. return bb.read();
  100. case 5: {
  101. let count = bb.read32();
  102. let value2 = [];
  103. for (let i = 0; i < count; i++) {
  104. value2.push(visit());
  105. }
  106. return value2;
  107. }
  108. case 6: {
  109. let count = bb.read32();
  110. let value2 = {};
  111. for (let i = 0; i < count; i++) {
  112. value2[decodeUTF8(bb.read())] = visit();
  113. }
  114. return value2;
  115. }
  116. default:
  117. throw new Error("Invalid packet");
  118. }
  119. };
  120. let bb = new ByteBuffer(bytes);
  121. let id = bb.read32();
  122. let isRequest = (id & 1) === 0;
  123. id >>>= 1;
  124. let value = visit();
  125. if (bb.ptr !== bytes.length) {
  126. throw new Error("Invalid packet");
  127. }
  128. return { id, isRequest, value };
  129. }
  130. var ByteBuffer = class {
  131. constructor(buf = new Uint8Array(1024)) {
  132. this.buf = buf;
  133. this.len = 0;
  134. this.ptr = 0;
  135. }
  136. _write(delta) {
  137. if (this.len + delta > this.buf.length) {
  138. let clone = new Uint8Array((this.len + delta) * 2);
  139. clone.set(this.buf);
  140. this.buf = clone;
  141. }
  142. this.len += delta;
  143. return this.len - delta;
  144. }
  145. write8(value) {
  146. let offset = this._write(1);
  147. this.buf[offset] = value;
  148. }
  149. write32(value) {
  150. let offset = this._write(4);
  151. writeUInt32LE(this.buf, value, offset);
  152. }
  153. write(bytes) {
  154. let offset = this._write(4 + bytes.length);
  155. writeUInt32LE(this.buf, bytes.length, offset);
  156. this.buf.set(bytes, offset + 4);
  157. }
  158. _read(delta) {
  159. if (this.ptr + delta > this.buf.length) {
  160. throw new Error("Invalid packet");
  161. }
  162. this.ptr += delta;
  163. return this.ptr - delta;
  164. }
  165. read8() {
  166. return this.buf[this._read(1)];
  167. }
  168. read32() {
  169. return readUInt32LE(this.buf, this._read(4));
  170. }
  171. read() {
  172. let length = this.read32();
  173. let bytes = new Uint8Array(length);
  174. let ptr = this._read(bytes.length);
  175. bytes.set(this.buf.subarray(ptr, ptr + length));
  176. return bytes;
  177. }
  178. };
  179. var encodeUTF8;
  180. var decodeUTF8;
  181. var encodeInvariant;
  182. if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
  183. let encoder = new TextEncoder();
  184. let decoder = new TextDecoder();
  185. encodeUTF8 = (text) => encoder.encode(text);
  186. decodeUTF8 = (bytes) => decoder.decode(bytes);
  187. encodeInvariant = 'new TextEncoder().encode("")';
  188. } else if (typeof Buffer !== "undefined") {
  189. encodeUTF8 = (text) => Buffer.from(text);
  190. decodeUTF8 = (bytes) => {
  191. let { buffer, byteOffset, byteLength } = bytes;
  192. return Buffer.from(buffer, byteOffset, byteLength).toString();
  193. };
  194. encodeInvariant = 'Buffer.from("")';
  195. } else {
  196. throw new Error("No UTF-8 codec found");
  197. }
  198. if (!(encodeUTF8("") instanceof Uint8Array))
  199. throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false
  200. This indicates that your JavaScript environment is broken. You cannot use
  201. esbuild in this environment because esbuild relies on this invariant. This
  202. is not a problem with esbuild. You need to fix your environment instead.
  203. `);
  204. function readUInt32LE(buffer, offset) {
  205. return buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24;
  206. }
  207. function writeUInt32LE(buffer, value, offset) {
  208. buffer[offset++] = value;
  209. buffer[offset++] = value >> 8;
  210. buffer[offset++] = value >> 16;
  211. buffer[offset++] = value >> 24;
  212. }
  213. // lib/shared/common.ts
  214. var quote = JSON.stringify;
  215. var buildLogLevelDefault = "warning";
  216. var transformLogLevelDefault = "silent";
  217. function validateTarget(target) {
  218. validateStringValue(target, "target");
  219. if (target.indexOf(",") >= 0) throw new Error(`Invalid target: ${target}`);
  220. return target;
  221. }
  222. var canBeAnything = () => null;
  223. var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
  224. var mustBeString = (value) => typeof value === "string" ? null : "a string";
  225. var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
  226. var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
  227. var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
  228. var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
  229. var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
  230. var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
  231. var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
  232. var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
  233. var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
  234. var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
  235. var mustBeStringOrArray = (value) => typeof value === "string" || Array.isArray(value) ? null : "a string or an array";
  236. var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
  237. var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL";
  238. function getFlag(object, keys, key, mustBeFn) {
  239. let value = object[key];
  240. keys[key + ""] = true;
  241. if (value === void 0) return void 0;
  242. let mustBe = mustBeFn(value);
  243. if (mustBe !== null) throw new Error(`${quote(key)} must be ${mustBe}`);
  244. return value;
  245. }
  246. function checkForInvalidFlags(object, keys, where) {
  247. for (let key in object) {
  248. if (!(key in keys)) {
  249. throw new Error(`Invalid option ${where}: ${quote(key)}`);
  250. }
  251. }
  252. }
  253. function validateInitializeOptions(options) {
  254. let keys = /* @__PURE__ */ Object.create(null);
  255. let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL);
  256. let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule);
  257. let worker = getFlag(options, keys, "worker", mustBeBoolean);
  258. checkForInvalidFlags(options, keys, "in initialize() call");
  259. return {
  260. wasmURL,
  261. wasmModule,
  262. worker
  263. };
  264. }
  265. function validateMangleCache(mangleCache) {
  266. let validated;
  267. if (mangleCache !== void 0) {
  268. validated = /* @__PURE__ */ Object.create(null);
  269. for (let key in mangleCache) {
  270. let value = mangleCache[key];
  271. if (typeof value === "string" || value === false) {
  272. validated[key] = value;
  273. } else {
  274. throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`);
  275. }
  276. }
  277. }
  278. return validated;
  279. }
  280. function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) {
  281. let color = getFlag(options, keys, "color", mustBeBoolean);
  282. let logLevel = getFlag(options, keys, "logLevel", mustBeString);
  283. let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
  284. if (color !== void 0) flags.push(`--color=${color}`);
  285. else if (isTTY2) flags.push(`--color=true`);
  286. flags.push(`--log-level=${logLevel || logLevelDefault}`);
  287. flags.push(`--log-limit=${logLimit || 0}`);
  288. }
  289. function validateStringValue(value, what, key) {
  290. if (typeof value !== "string") {
  291. throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`);
  292. }
  293. return value;
  294. }
  295. function pushCommonFlags(flags, options, keys) {
  296. let legalComments = getFlag(options, keys, "legalComments", mustBeString);
  297. let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
  298. let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
  299. let target = getFlag(options, keys, "target", mustBeStringOrArray);
  300. let format = getFlag(options, keys, "format", mustBeString);
  301. let globalName = getFlag(options, keys, "globalName", mustBeString);
  302. let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp);
  303. let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp);
  304. let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean);
  305. let minify = getFlag(options, keys, "minify", mustBeBoolean);
  306. let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
  307. let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
  308. let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
  309. let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger);
  310. let drop = getFlag(options, keys, "drop", mustBeArray);
  311. let dropLabels = getFlag(options, keys, "dropLabels", mustBeArray);
  312. let charset = getFlag(options, keys, "charset", mustBeString);
  313. let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
  314. let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
  315. let jsx = getFlag(options, keys, "jsx", mustBeString);
  316. let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
  317. let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
  318. let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString);
  319. let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean);
  320. let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean);
  321. let define = getFlag(options, keys, "define", mustBeObject);
  322. let logOverride = getFlag(options, keys, "logOverride", mustBeObject);
  323. let supported = getFlag(options, keys, "supported", mustBeObject);
  324. let pure = getFlag(options, keys, "pure", mustBeArray);
  325. let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
  326. let platform = getFlag(options, keys, "platform", mustBeString);
  327. let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
  328. if (legalComments) flags.push(`--legal-comments=${legalComments}`);
  329. if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`);
  330. if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`);
  331. if (target) {
  332. if (Array.isArray(target)) flags.push(`--target=${Array.from(target).map(validateTarget).join(",")}`);
  333. else flags.push(`--target=${validateTarget(target)}`);
  334. }
  335. if (format) flags.push(`--format=${format}`);
  336. if (globalName) flags.push(`--global-name=${globalName}`);
  337. if (platform) flags.push(`--platform=${platform}`);
  338. if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
  339. if (minify) flags.push("--minify");
  340. if (minifySyntax) flags.push("--minify-syntax");
  341. if (minifyWhitespace) flags.push("--minify-whitespace");
  342. if (minifyIdentifiers) flags.push("--minify-identifiers");
  343. if (lineLimit) flags.push(`--line-limit=${lineLimit}`);
  344. if (charset) flags.push(`--charset=${charset}`);
  345. if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`);
  346. if (ignoreAnnotations) flags.push(`--ignore-annotations`);
  347. if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`);
  348. if (dropLabels) flags.push(`--drop-labels=${Array.from(dropLabels).map((what) => validateStringValue(what, "dropLabels")).join(",")}`);
  349. if (mangleProps) flags.push(`--mangle-props=${mangleProps.source}`);
  350. if (reserveProps) flags.push(`--reserve-props=${reserveProps.source}`);
  351. if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`);
  352. if (jsx) flags.push(`--jsx=${jsx}`);
  353. if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`);
  354. if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`);
  355. if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`);
  356. if (jsxDev) flags.push(`--jsx-dev`);
  357. if (jsxSideEffects) flags.push(`--jsx-side-effects`);
  358. if (define) {
  359. for (let key in define) {
  360. if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`);
  361. flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`);
  362. }
  363. }
  364. if (logOverride) {
  365. for (let key in logOverride) {
  366. if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`);
  367. flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`);
  368. }
  369. }
  370. if (supported) {
  371. for (let key in supported) {
  372. if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`);
  373. const value = supported[key];
  374. if (typeof value !== "boolean") throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`);
  375. flags.push(`--supported:${key}=${value}`);
  376. }
  377. }
  378. if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`);
  379. if (keepNames) flags.push(`--keep-names`);
  380. }
  381. function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) {
  382. var _a2;
  383. let flags = [];
  384. let entries = [];
  385. let keys = /* @__PURE__ */ Object.create(null);
  386. let stdinContents = null;
  387. let stdinResolveDir = null;
  388. pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
  389. pushCommonFlags(flags, options, keys);
  390. let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
  391. let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
  392. let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
  393. let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
  394. let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
  395. let outfile = getFlag(options, keys, "outfile", mustBeString);
  396. let outdir = getFlag(options, keys, "outdir", mustBeString);
  397. let outbase = getFlag(options, keys, "outbase", mustBeString);
  398. let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
  399. let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArray);
  400. let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArray);
  401. let mainFields = getFlag(options, keys, "mainFields", mustBeArray);
  402. let conditions = getFlag(options, keys, "conditions", mustBeArray);
  403. let external = getFlag(options, keys, "external", mustBeArray);
  404. let packages = getFlag(options, keys, "packages", mustBeString);
  405. let alias = getFlag(options, keys, "alias", mustBeObject);
  406. let loader = getFlag(options, keys, "loader", mustBeObject);
  407. let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
  408. let publicPath = getFlag(options, keys, "publicPath", mustBeString);
  409. let entryNames = getFlag(options, keys, "entryNames", mustBeString);
  410. let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
  411. let assetNames = getFlag(options, keys, "assetNames", mustBeString);
  412. let inject = getFlag(options, keys, "inject", mustBeArray);
  413. let banner = getFlag(options, keys, "banner", mustBeObject);
  414. let footer = getFlag(options, keys, "footer", mustBeObject);
  415. let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints);
  416. let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
  417. let stdin = getFlag(options, keys, "stdin", mustBeObject);
  418. let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault;
  419. let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
  420. let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
  421. keys.plugins = true;
  422. checkForInvalidFlags(options, keys, `in ${callName}() call`);
  423. if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
  424. if (bundle) flags.push("--bundle");
  425. if (allowOverwrite) flags.push("--allow-overwrite");
  426. if (splitting) flags.push("--splitting");
  427. if (preserveSymlinks) flags.push("--preserve-symlinks");
  428. if (metafile) flags.push(`--metafile`);
  429. if (outfile) flags.push(`--outfile=${outfile}`);
  430. if (outdir) flags.push(`--outdir=${outdir}`);
  431. if (outbase) flags.push(`--outbase=${outbase}`);
  432. if (tsconfig) flags.push(`--tsconfig=${tsconfig}`);
  433. if (packages) flags.push(`--packages=${packages}`);
  434. if (resolveExtensions) {
  435. let values = [];
  436. for (let value of resolveExtensions) {
  437. validateStringValue(value, "resolve extension");
  438. if (value.indexOf(",") >= 0) throw new Error(`Invalid resolve extension: ${value}`);
  439. values.push(value);
  440. }
  441. flags.push(`--resolve-extensions=${values.join(",")}`);
  442. }
  443. if (publicPath) flags.push(`--public-path=${publicPath}`);
  444. if (entryNames) flags.push(`--entry-names=${entryNames}`);
  445. if (chunkNames) flags.push(`--chunk-names=${chunkNames}`);
  446. if (assetNames) flags.push(`--asset-names=${assetNames}`);
  447. if (mainFields) {
  448. let values = [];
  449. for (let value of mainFields) {
  450. validateStringValue(value, "main field");
  451. if (value.indexOf(",") >= 0) throw new Error(`Invalid main field: ${value}`);
  452. values.push(value);
  453. }
  454. flags.push(`--main-fields=${values.join(",")}`);
  455. }
  456. if (conditions) {
  457. let values = [];
  458. for (let value of conditions) {
  459. validateStringValue(value, "condition");
  460. if (value.indexOf(",") >= 0) throw new Error(`Invalid condition: ${value}`);
  461. values.push(value);
  462. }
  463. flags.push(`--conditions=${values.join(",")}`);
  464. }
  465. if (external) for (let name of external) flags.push(`--external:${validateStringValue(name, "external")}`);
  466. if (alias) {
  467. for (let old in alias) {
  468. if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`);
  469. flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`);
  470. }
  471. }
  472. if (banner) {
  473. for (let type in banner) {
  474. if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`);
  475. flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`);
  476. }
  477. }
  478. if (footer) {
  479. for (let type in footer) {
  480. if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`);
  481. flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`);
  482. }
  483. }
  484. if (inject) for (let path3 of inject) flags.push(`--inject:${validateStringValue(path3, "inject")}`);
  485. if (loader) {
  486. for (let ext in loader) {
  487. if (ext.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext}`);
  488. flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`);
  489. }
  490. }
  491. if (outExtension) {
  492. for (let ext in outExtension) {
  493. if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`);
  494. flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
  495. }
  496. }
  497. if (entryPoints) {
  498. if (Array.isArray(entryPoints)) {
  499. for (let i = 0, n = entryPoints.length; i < n; i++) {
  500. let entryPoint = entryPoints[i];
  501. if (typeof entryPoint === "object" && entryPoint !== null) {
  502. let entryPointKeys = /* @__PURE__ */ Object.create(null);
  503. let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
  504. let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
  505. checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
  506. if (input === void 0) throw new Error('Missing property "in" for entry point at index ' + i);
  507. if (output === void 0) throw new Error('Missing property "out" for entry point at index ' + i);
  508. entries.push([output, input]);
  509. } else {
  510. entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
  511. }
  512. }
  513. } else {
  514. for (let key in entryPoints) {
  515. entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
  516. }
  517. }
  518. }
  519. if (stdin) {
  520. let stdinKeys = /* @__PURE__ */ Object.create(null);
  521. let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
  522. let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
  523. let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
  524. let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
  525. checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object');
  526. if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
  527. if (loader2) flags.push(`--loader=${loader2}`);
  528. if (resolveDir) stdinResolveDir = resolveDir;
  529. if (typeof contents === "string") stdinContents = encodeUTF8(contents);
  530. else if (contents instanceof Uint8Array) stdinContents = contents;
  531. }
  532. let nodePaths = [];
  533. if (nodePathsInput) {
  534. for (let value of nodePathsInput) {
  535. value += "";
  536. nodePaths.push(value);
  537. }
  538. }
  539. return {
  540. entries,
  541. flags,
  542. write,
  543. stdinContents,
  544. stdinResolveDir,
  545. absWorkingDir,
  546. nodePaths,
  547. mangleCache: validateMangleCache(mangleCache)
  548. };
  549. }
  550. function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) {
  551. let flags = [];
  552. let keys = /* @__PURE__ */ Object.create(null);
  553. pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
  554. pushCommonFlags(flags, options, keys);
  555. let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
  556. let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
  557. let loader = getFlag(options, keys, "loader", mustBeString);
  558. let banner = getFlag(options, keys, "banner", mustBeString);
  559. let footer = getFlag(options, keys, "footer", mustBeString);
  560. let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
  561. checkForInvalidFlags(options, keys, `in ${callName}() call`);
  562. if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
  563. if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
  564. if (loader) flags.push(`--loader=${loader}`);
  565. if (banner) flags.push(`--banner=${banner}`);
  566. if (footer) flags.push(`--footer=${footer}`);
  567. return {
  568. flags,
  569. mangleCache: validateMangleCache(mangleCache)
  570. };
  571. }
  572. function createChannel(streamIn) {
  573. const requestCallbacksByKey = {};
  574. const closeData = { didClose: false, reason: "" };
  575. let responseCallbacks = {};
  576. let nextRequestID = 0;
  577. let nextBuildKey = 0;
  578. let stdout = new Uint8Array(16 * 1024);
  579. let stdoutUsed = 0;
  580. let readFromStdout = (chunk) => {
  581. let limit = stdoutUsed + chunk.length;
  582. if (limit > stdout.length) {
  583. let swap = new Uint8Array(limit * 2);
  584. swap.set(stdout);
  585. stdout = swap;
  586. }
  587. stdout.set(chunk, stdoutUsed);
  588. stdoutUsed += chunk.length;
  589. let offset = 0;
  590. while (offset + 4 <= stdoutUsed) {
  591. let length = readUInt32LE(stdout, offset);
  592. if (offset + 4 + length > stdoutUsed) {
  593. break;
  594. }
  595. offset += 4;
  596. handleIncomingPacket(stdout.subarray(offset, offset + length));
  597. offset += length;
  598. }
  599. if (offset > 0) {
  600. stdout.copyWithin(0, offset, stdoutUsed);
  601. stdoutUsed -= offset;
  602. }
  603. };
  604. let afterClose = (error) => {
  605. closeData.didClose = true;
  606. if (error) closeData.reason = ": " + (error.message || error);
  607. const text = "The service was stopped" + closeData.reason;
  608. for (let id in responseCallbacks) {
  609. responseCallbacks[id](text, null);
  610. }
  611. responseCallbacks = {};
  612. };
  613. let sendRequest = (refs, value, callback) => {
  614. if (closeData.didClose) return callback("The service is no longer running" + closeData.reason, null);
  615. let id = nextRequestID++;
  616. responseCallbacks[id] = (error, response) => {
  617. try {
  618. callback(error, response);
  619. } finally {
  620. if (refs) refs.unref();
  621. }
  622. };
  623. if (refs) refs.ref();
  624. streamIn.writeToStdin(encodePacket({ id, isRequest: true, value }));
  625. };
  626. let sendResponse = (id, value) => {
  627. if (closeData.didClose) throw new Error("The service is no longer running" + closeData.reason);
  628. streamIn.writeToStdin(encodePacket({ id, isRequest: false, value }));
  629. };
  630. let handleRequest = async (id, request) => {
  631. try {
  632. if (request.command === "ping") {
  633. sendResponse(id, {});
  634. return;
  635. }
  636. if (typeof request.key === "number") {
  637. const requestCallbacks = requestCallbacksByKey[request.key];
  638. if (!requestCallbacks) {
  639. return;
  640. }
  641. const callback = requestCallbacks[request.command];
  642. if (callback) {
  643. await callback(id, request);
  644. return;
  645. }
  646. }
  647. throw new Error(`Invalid command: ` + request.command);
  648. } catch (e) {
  649. const errors = [extractErrorMessageV8(e, streamIn, null, void 0, "")];
  650. try {
  651. sendResponse(id, { errors });
  652. } catch {
  653. }
  654. }
  655. };
  656. let isFirstPacket = true;
  657. let handleIncomingPacket = (bytes) => {
  658. if (isFirstPacket) {
  659. isFirstPacket = false;
  660. let binaryVersion = String.fromCharCode(...bytes);
  661. if (binaryVersion !== "0.21.5") {
  662. throw new Error(`Cannot start service: Host version "${"0.21.5"}" does not match binary version ${quote(binaryVersion)}`);
  663. }
  664. return;
  665. }
  666. let packet = decodePacket(bytes);
  667. if (packet.isRequest) {
  668. handleRequest(packet.id, packet.value);
  669. } else {
  670. let callback = responseCallbacks[packet.id];
  671. delete responseCallbacks[packet.id];
  672. if (packet.value.error) callback(packet.value.error, {});
  673. else callback(null, packet.value);
  674. }
  675. };
  676. let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => {
  677. let refCount = 0;
  678. const buildKey = nextBuildKey++;
  679. const requestCallbacks = {};
  680. const buildRefs = {
  681. ref() {
  682. if (++refCount === 1) {
  683. if (refs) refs.ref();
  684. }
  685. },
  686. unref() {
  687. if (--refCount === 0) {
  688. delete requestCallbacksByKey[buildKey];
  689. if (refs) refs.unref();
  690. }
  691. }
  692. };
  693. requestCallbacksByKey[buildKey] = requestCallbacks;
  694. buildRefs.ref();
  695. buildOrContextImpl(
  696. callName,
  697. buildKey,
  698. sendRequest,
  699. sendResponse,
  700. buildRefs,
  701. streamIn,
  702. requestCallbacks,
  703. options,
  704. isTTY2,
  705. defaultWD2,
  706. (err, res) => {
  707. try {
  708. callback(err, res);
  709. } finally {
  710. buildRefs.unref();
  711. }
  712. }
  713. );
  714. };
  715. let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => {
  716. const details = createObjectStash();
  717. let start = (inputPath) => {
  718. try {
  719. if (typeof input !== "string" && !(input instanceof Uint8Array))
  720. throw new Error('The input to "transform" must be a string or a Uint8Array');
  721. let {
  722. flags,
  723. mangleCache
  724. } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault);
  725. let request = {
  726. command: "transform",
  727. flags,
  728. inputFS: inputPath !== null,
  729. input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input
  730. };
  731. if (mangleCache) request.mangleCache = mangleCache;
  732. sendRequest(refs, request, (error, response) => {
  733. if (error) return callback(new Error(error), null);
  734. let errors = replaceDetailsInMessages(response.errors, details);
  735. let warnings = replaceDetailsInMessages(response.warnings, details);
  736. let outstanding = 1;
  737. let next = () => {
  738. if (--outstanding === 0) {
  739. let result = {
  740. warnings,
  741. code: response.code,
  742. map: response.map,
  743. mangleCache: void 0,
  744. legalComments: void 0
  745. };
  746. if ("legalComments" in response) result.legalComments = response == null ? void 0 : response.legalComments;
  747. if (response.mangleCache) result.mangleCache = response == null ? void 0 : response.mangleCache;
  748. callback(null, result);
  749. }
  750. };
  751. if (errors.length > 0) return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
  752. if (response.codeFS) {
  753. outstanding++;
  754. fs3.readFile(response.code, (err, contents) => {
  755. if (err !== null) {
  756. callback(err, null);
  757. } else {
  758. response.code = contents;
  759. next();
  760. }
  761. });
  762. }
  763. if (response.mapFS) {
  764. outstanding++;
  765. fs3.readFile(response.map, (err, contents) => {
  766. if (err !== null) {
  767. callback(err, null);
  768. } else {
  769. response.map = contents;
  770. next();
  771. }
  772. });
  773. }
  774. next();
  775. });
  776. } catch (e) {
  777. let flags = [];
  778. try {
  779. pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault);
  780. } catch {
  781. }
  782. const error = extractErrorMessageV8(e, streamIn, details, void 0, "");
  783. sendRequest(refs, { command: "error", flags, error }, () => {
  784. error.detail = details.load(error.detail);
  785. callback(failureErrorWithLog("Transform failed", [error], []), null);
  786. });
  787. }
  788. };
  789. if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) {
  790. let next = start;
  791. start = () => fs3.writeFile(input, next);
  792. }
  793. start(null);
  794. };
  795. let formatMessages2 = ({ callName, refs, messages, options, callback }) => {
  796. if (!options) throw new Error(`Missing second argument in ${callName}() call`);
  797. let keys = {};
  798. let kind = getFlag(options, keys, "kind", mustBeString);
  799. let color = getFlag(options, keys, "color", mustBeBoolean);
  800. let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
  801. checkForInvalidFlags(options, keys, `in ${callName}() call`);
  802. if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`);
  803. if (kind !== "error" && kind !== "warning") throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
  804. let request = {
  805. command: "format-msgs",
  806. messages: sanitizeMessages(messages, "messages", null, "", terminalWidth),
  807. isWarning: kind === "warning"
  808. };
  809. if (color !== void 0) request.color = color;
  810. if (terminalWidth !== void 0) request.terminalWidth = terminalWidth;
  811. sendRequest(refs, request, (error, response) => {
  812. if (error) return callback(new Error(error), null);
  813. callback(null, response.messages);
  814. });
  815. };
  816. let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => {
  817. if (options === void 0) options = {};
  818. let keys = {};
  819. let color = getFlag(options, keys, "color", mustBeBoolean);
  820. let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
  821. checkForInvalidFlags(options, keys, `in ${callName}() call`);
  822. let request = {
  823. command: "analyze-metafile",
  824. metafile
  825. };
  826. if (color !== void 0) request.color = color;
  827. if (verbose !== void 0) request.verbose = verbose;
  828. sendRequest(refs, request, (error, response) => {
  829. if (error) return callback(new Error(error), null);
  830. callback(null, response.result);
  831. });
  832. };
  833. return {
  834. readFromStdout,
  835. afterClose,
  836. service: {
  837. buildOrContext,
  838. transform: transform2,
  839. formatMessages: formatMessages2,
  840. analyzeMetafile: analyzeMetafile2
  841. }
  842. };
  843. }
  844. function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) {
  845. const details = createObjectStash();
  846. const isContext = callName === "context";
  847. const handleError = (e, pluginName) => {
  848. const flags = [];
  849. try {
  850. pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault);
  851. } catch {
  852. }
  853. const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName);
  854. sendRequest(refs, { command: "error", flags, error: message }, () => {
  855. message.detail = details.load(message.detail);
  856. callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
  857. });
  858. };
  859. let plugins;
  860. if (typeof options === "object") {
  861. const value = options.plugins;
  862. if (value !== void 0) {
  863. if (!Array.isArray(value)) return handleError(new Error(`"plugins" must be an array`), "");
  864. plugins = value;
  865. }
  866. }
  867. if (plugins && plugins.length > 0) {
  868. if (streamIn.isSync) return handleError(new Error("Cannot use plugins in synchronous API calls"), "");
  869. handlePlugins(
  870. buildKey,
  871. sendRequest,
  872. sendResponse,
  873. refs,
  874. streamIn,
  875. requestCallbacks,
  876. options,
  877. plugins,
  878. details
  879. ).then(
  880. (result) => {
  881. if (!result.ok) return handleError(result.error, result.pluginName);
  882. try {
  883. buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
  884. } catch (e) {
  885. handleError(e, "");
  886. }
  887. },
  888. (e) => handleError(e, "")
  889. );
  890. return;
  891. }
  892. try {
  893. buildOrContextContinue(null, (result, done) => done([], []), () => {
  894. });
  895. } catch (e) {
  896. handleError(e, "");
  897. }
  898. function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
  899. const writeDefault = streamIn.hasFS;
  900. const {
  901. entries,
  902. flags,
  903. write,
  904. stdinContents,
  905. stdinResolveDir,
  906. absWorkingDir,
  907. nodePaths,
  908. mangleCache
  909. } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault);
  910. if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`);
  911. const request = {
  912. command: "build",
  913. key: buildKey,
  914. entries,
  915. flags,
  916. write,
  917. stdinContents,
  918. stdinResolveDir,
  919. absWorkingDir: absWorkingDir || defaultWD2,
  920. nodePaths,
  921. context: isContext
  922. };
  923. if (requestPlugins) request.plugins = requestPlugins;
  924. if (mangleCache) request.mangleCache = mangleCache;
  925. const buildResponseToResult = (response, callback2) => {
  926. const result = {
  927. errors: replaceDetailsInMessages(response.errors, details),
  928. warnings: replaceDetailsInMessages(response.warnings, details),
  929. outputFiles: void 0,
  930. metafile: void 0,
  931. mangleCache: void 0
  932. };
  933. const originalErrors = result.errors.slice();
  934. const originalWarnings = result.warnings.slice();
  935. if (response.outputFiles) result.outputFiles = response.outputFiles.map(convertOutputFiles);
  936. if (response.metafile) result.metafile = JSON.parse(response.metafile);
  937. if (response.mangleCache) result.mangleCache = response.mangleCache;
  938. if (response.writeToStdout !== void 0) console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
  939. runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
  940. if (originalErrors.length > 0 || onEndErrors.length > 0) {
  941. const error = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings));
  942. return callback2(error, null, onEndErrors, onEndWarnings);
  943. }
  944. callback2(null, result, onEndErrors, onEndWarnings);
  945. });
  946. };
  947. let latestResultPromise;
  948. let provideLatestResult;
  949. if (isContext)
  950. requestCallbacks["on-end"] = (id, request2) => new Promise((resolve) => {
  951. buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => {
  952. const response = {
  953. errors: onEndErrors,
  954. warnings: onEndWarnings
  955. };
  956. if (provideLatestResult) provideLatestResult(err, result);
  957. latestResultPromise = void 0;
  958. provideLatestResult = void 0;
  959. sendResponse(id, response);
  960. resolve();
  961. });
  962. });
  963. sendRequest(refs, request, (error, response) => {
  964. if (error) return callback(new Error(error), null);
  965. if (!isContext) {
  966. return buildResponseToResult(response, (err, res) => {
  967. scheduleOnDisposeCallbacks();
  968. return callback(err, res);
  969. });
  970. }
  971. if (response.errors.length > 0) {
  972. return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
  973. }
  974. let didDispose = false;
  975. const result = {
  976. rebuild: () => {
  977. if (!latestResultPromise) latestResultPromise = new Promise((resolve, reject) => {
  978. let settlePromise;
  979. provideLatestResult = (err, result2) => {
  980. if (!settlePromise) settlePromise = () => err ? reject(err) : resolve(result2);
  981. };
  982. const triggerAnotherBuild = () => {
  983. const request2 = {
  984. command: "rebuild",
  985. key: buildKey
  986. };
  987. sendRequest(refs, request2, (error2, response2) => {
  988. if (error2) {
  989. reject(new Error(error2));
  990. } else if (settlePromise) {
  991. settlePromise();
  992. } else {
  993. triggerAnotherBuild();
  994. }
  995. });
  996. };
  997. triggerAnotherBuild();
  998. });
  999. return latestResultPromise;
  1000. },
  1001. watch: (options2 = {}) => new Promise((resolve, reject) => {
  1002. if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`);
  1003. const keys = {};
  1004. checkForInvalidFlags(options2, keys, `in watch() call`);
  1005. const request2 = {
  1006. command: "watch",
  1007. key: buildKey
  1008. };
  1009. sendRequest(refs, request2, (error2) => {
  1010. if (error2) reject(new Error(error2));
  1011. else resolve(void 0);
  1012. });
  1013. }),
  1014. serve: (options2 = {}) => new Promise((resolve, reject) => {
  1015. if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`);
  1016. const keys = {};
  1017. const port = getFlag(options2, keys, "port", mustBeInteger);
  1018. const host = getFlag(options2, keys, "host", mustBeString);
  1019. const servedir = getFlag(options2, keys, "servedir", mustBeString);
  1020. const keyfile = getFlag(options2, keys, "keyfile", mustBeString);
  1021. const certfile = getFlag(options2, keys, "certfile", mustBeString);
  1022. const fallback = getFlag(options2, keys, "fallback", mustBeString);
  1023. const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction);
  1024. checkForInvalidFlags(options2, keys, `in serve() call`);
  1025. const request2 = {
  1026. command: "serve",
  1027. key: buildKey,
  1028. onRequest: !!onRequest
  1029. };
  1030. if (port !== void 0) request2.port = port;
  1031. if (host !== void 0) request2.host = host;
  1032. if (servedir !== void 0) request2.servedir = servedir;
  1033. if (keyfile !== void 0) request2.keyfile = keyfile;
  1034. if (certfile !== void 0) request2.certfile = certfile;
  1035. if (fallback !== void 0) request2.fallback = fallback;
  1036. sendRequest(refs, request2, (error2, response2) => {
  1037. if (error2) return reject(new Error(error2));
  1038. if (onRequest) {
  1039. requestCallbacks["serve-request"] = (id, request3) => {
  1040. onRequest(request3.args);
  1041. sendResponse(id, {});
  1042. };
  1043. }
  1044. resolve(response2);
  1045. });
  1046. }),
  1047. cancel: () => new Promise((resolve) => {
  1048. if (didDispose) return resolve();
  1049. const request2 = {
  1050. command: "cancel",
  1051. key: buildKey
  1052. };
  1053. sendRequest(refs, request2, () => {
  1054. resolve();
  1055. });
  1056. }),
  1057. dispose: () => new Promise((resolve) => {
  1058. if (didDispose) return resolve();
  1059. didDispose = true;
  1060. const request2 = {
  1061. command: "dispose",
  1062. key: buildKey
  1063. };
  1064. sendRequest(refs, request2, () => {
  1065. resolve();
  1066. scheduleOnDisposeCallbacks();
  1067. refs.unref();
  1068. });
  1069. })
  1070. };
  1071. refs.ref();
  1072. callback(null, result);
  1073. });
  1074. }
  1075. }
  1076. var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => {
  1077. let onStartCallbacks = [];
  1078. let onEndCallbacks = [];
  1079. let onResolveCallbacks = {};
  1080. let onLoadCallbacks = {};
  1081. let onDisposeCallbacks = [];
  1082. let nextCallbackID = 0;
  1083. let i = 0;
  1084. let requestPlugins = [];
  1085. let isSetupDone = false;
  1086. plugins = [...plugins];
  1087. for (let item of plugins) {
  1088. let keys = {};
  1089. if (typeof item !== "object") throw new Error(`Plugin at index ${i} must be an object`);
  1090. const name = getFlag(item, keys, "name", mustBeString);
  1091. if (typeof name !== "string" || name === "") throw new Error(`Plugin at index ${i} is missing a name`);
  1092. try {
  1093. let setup = getFlag(item, keys, "setup", mustBeFunction);
  1094. if (typeof setup !== "function") throw new Error(`Plugin is missing a setup function`);
  1095. checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`);
  1096. let plugin = {
  1097. name,
  1098. onStart: false,
  1099. onEnd: false,
  1100. onResolve: [],
  1101. onLoad: []
  1102. };
  1103. i++;
  1104. let resolve = (path3, options = {}) => {
  1105. if (!isSetupDone) throw new Error('Cannot call "resolve" before plugin setup has completed');
  1106. if (typeof path3 !== "string") throw new Error(`The path to resolve must be a string`);
  1107. let keys2 = /* @__PURE__ */ Object.create(null);
  1108. let pluginName = getFlag(options, keys2, "pluginName", mustBeString);
  1109. let importer = getFlag(options, keys2, "importer", mustBeString);
  1110. let namespace = getFlag(options, keys2, "namespace", mustBeString);
  1111. let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString);
  1112. let kind = getFlag(options, keys2, "kind", mustBeString);
  1113. let pluginData = getFlag(options, keys2, "pluginData", canBeAnything);
  1114. let importAttributes = getFlag(options, keys2, "with", mustBeObject);
  1115. checkForInvalidFlags(options, keys2, "in resolve() call");
  1116. return new Promise((resolve2, reject) => {
  1117. const request = {
  1118. command: "resolve",
  1119. path: path3,
  1120. key: buildKey,
  1121. pluginName: name
  1122. };
  1123. if (pluginName != null) request.pluginName = pluginName;
  1124. if (importer != null) request.importer = importer;
  1125. if (namespace != null) request.namespace = namespace;
  1126. if (resolveDir != null) request.resolveDir = resolveDir;
  1127. if (kind != null) request.kind = kind;
  1128. else throw new Error(`Must specify "kind" when calling "resolve"`);
  1129. if (pluginData != null) request.pluginData = details.store(pluginData);
  1130. if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, "with");
  1131. sendRequest(refs, request, (error, response) => {
  1132. if (error !== null) reject(new Error(error));
  1133. else resolve2({
  1134. errors: replaceDetailsInMessages(response.errors, details),
  1135. warnings: replaceDetailsInMessages(response.warnings, details),
  1136. path: response.path,
  1137. external: response.external,
  1138. sideEffects: response.sideEffects,
  1139. namespace: response.namespace,
  1140. suffix: response.suffix,
  1141. pluginData: details.load(response.pluginData)
  1142. });
  1143. });
  1144. });
  1145. };
  1146. let promise = setup({
  1147. initialOptions,
  1148. resolve,
  1149. onStart(callback) {
  1150. let registeredText = `This error came from the "onStart" callback registered here:`;
  1151. let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart");
  1152. onStartCallbacks.push({ name, callback, note: registeredNote });
  1153. plugin.onStart = true;
  1154. },
  1155. onEnd(callback) {
  1156. let registeredText = `This error came from the "onEnd" callback registered here:`;
  1157. let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd");
  1158. onEndCallbacks.push({ name, callback, note: registeredNote });
  1159. plugin.onEnd = true;
  1160. },
  1161. onResolve(options, callback) {
  1162. let registeredText = `This error came from the "onResolve" callback registered here:`;
  1163. let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve");
  1164. let keys2 = {};
  1165. let filter = getFlag(options, keys2, "filter", mustBeRegExp);
  1166. let namespace = getFlag(options, keys2, "namespace", mustBeString);
  1167. checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`);
  1168. if (filter == null) throw new Error(`onResolve() call is missing a filter`);
  1169. let id = nextCallbackID++;
  1170. onResolveCallbacks[id] = { name, callback, note: registeredNote };
  1171. plugin.onResolve.push({ id, filter: filter.source, namespace: namespace || "" });
  1172. },
  1173. onLoad(options, callback) {
  1174. let registeredText = `This error came from the "onLoad" callback registered here:`;
  1175. let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad");
  1176. let keys2 = {};
  1177. let filter = getFlag(options, keys2, "filter", mustBeRegExp);
  1178. let namespace = getFlag(options, keys2, "namespace", mustBeString);
  1179. checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`);
  1180. if (filter == null) throw new Error(`onLoad() call is missing a filter`);
  1181. let id = nextCallbackID++;
  1182. onLoadCallbacks[id] = { name, callback, note: registeredNote };
  1183. plugin.onLoad.push({ id, filter: filter.source, namespace: namespace || "" });
  1184. },
  1185. onDispose(callback) {
  1186. onDisposeCallbacks.push(callback);
  1187. },
  1188. esbuild: streamIn.esbuild
  1189. });
  1190. if (promise) await promise;
  1191. requestPlugins.push(plugin);
  1192. } catch (e) {
  1193. return { ok: false, error: e, pluginName: name };
  1194. }
  1195. }
  1196. requestCallbacks["on-start"] = async (id, request) => {
  1197. let response = { errors: [], warnings: [] };
  1198. await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => {
  1199. try {
  1200. let result = await callback();
  1201. if (result != null) {
  1202. if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`);
  1203. let keys = {};
  1204. let errors = getFlag(result, keys, "errors", mustBeArray);
  1205. let warnings = getFlag(result, keys, "warnings", mustBeArray);
  1206. checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`);
  1207. if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0));
  1208. if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0));
  1209. }
  1210. } catch (e) {
  1211. response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name));
  1212. }
  1213. }));
  1214. sendResponse(id, response);
  1215. };
  1216. requestCallbacks["on-resolve"] = async (id, request) => {
  1217. let response = {}, name = "", callback, note;
  1218. for (let id2 of request.ids) {
  1219. try {
  1220. ({ name, callback, note } = onResolveCallbacks[id2]);
  1221. let result = await callback({
  1222. path: request.path,
  1223. importer: request.importer,
  1224. namespace: request.namespace,
  1225. resolveDir: request.resolveDir,
  1226. kind: request.kind,
  1227. pluginData: details.load(request.pluginData),
  1228. with: request.with
  1229. });
  1230. if (result != null) {
  1231. if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`);
  1232. let keys = {};
  1233. let pluginName = getFlag(result, keys, "pluginName", mustBeString);
  1234. let path3 = getFlag(result, keys, "path", mustBeString);
  1235. let namespace = getFlag(result, keys, "namespace", mustBeString);
  1236. let suffix = getFlag(result, keys, "suffix", mustBeString);
  1237. let external = getFlag(result, keys, "external", mustBeBoolean);
  1238. let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
  1239. let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
  1240. let errors = getFlag(result, keys, "errors", mustBeArray);
  1241. let warnings = getFlag(result, keys, "warnings", mustBeArray);
  1242. let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray);
  1243. let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray);
  1244. checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`);
  1245. response.id = id2;
  1246. if (pluginName != null) response.pluginName = pluginName;
  1247. if (path3 != null) response.path = path3;
  1248. if (namespace != null) response.namespace = namespace;
  1249. if (suffix != null) response.suffix = suffix;
  1250. if (external != null) response.external = external;
  1251. if (sideEffects != null) response.sideEffects = sideEffects;
  1252. if (pluginData != null) response.pluginData = details.store(pluginData);
  1253. if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
  1254. if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
  1255. if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
  1256. if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
  1257. break;
  1258. }
  1259. } catch (e) {
  1260. response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
  1261. break;
  1262. }
  1263. }
  1264. sendResponse(id, response);
  1265. };
  1266. requestCallbacks["on-load"] = async (id, request) => {
  1267. let response = {}, name = "", callback, note;
  1268. for (let id2 of request.ids) {
  1269. try {
  1270. ({ name, callback, note } = onLoadCallbacks[id2]);
  1271. let result = await callback({
  1272. path: request.path,
  1273. namespace: request.namespace,
  1274. suffix: request.suffix,
  1275. pluginData: details.load(request.pluginData),
  1276. with: request.with
  1277. });
  1278. if (result != null) {
  1279. if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`);
  1280. let keys = {};
  1281. let pluginName = getFlag(result, keys, "pluginName", mustBeString);
  1282. let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
  1283. let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
  1284. let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
  1285. let loader = getFlag(result, keys, "loader", mustBeString);
  1286. let errors = getFlag(result, keys, "errors", mustBeArray);
  1287. let warnings = getFlag(result, keys, "warnings", mustBeArray);
  1288. let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray);
  1289. let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray);
  1290. checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`);
  1291. response.id = id2;
  1292. if (pluginName != null) response.pluginName = pluginName;
  1293. if (contents instanceof Uint8Array) response.contents = contents;
  1294. else if (contents != null) response.contents = encodeUTF8(contents);
  1295. if (resolveDir != null) response.resolveDir = resolveDir;
  1296. if (pluginData != null) response.pluginData = details.store(pluginData);
  1297. if (loader != null) response.loader = loader;
  1298. if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
  1299. if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
  1300. if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
  1301. if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
  1302. break;
  1303. }
  1304. } catch (e) {
  1305. response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
  1306. break;
  1307. }
  1308. }
  1309. sendResponse(id, response);
  1310. };
  1311. let runOnEndCallbacks = (result, done) => done([], []);
  1312. if (onEndCallbacks.length > 0) {
  1313. runOnEndCallbacks = (result, done) => {
  1314. (async () => {
  1315. const onEndErrors = [];
  1316. const onEndWarnings = [];
  1317. for (const { name, callback, note } of onEndCallbacks) {
  1318. let newErrors;
  1319. let newWarnings;
  1320. try {
  1321. const value = await callback(result);
  1322. if (value != null) {
  1323. if (typeof value !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
  1324. let keys = {};
  1325. let errors = getFlag(value, keys, "errors", mustBeArray);
  1326. let warnings = getFlag(value, keys, "warnings", mustBeArray);
  1327. checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
  1328. if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name, void 0);
  1329. if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
  1330. }
  1331. } catch (e) {
  1332. newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
  1333. }
  1334. if (newErrors) {
  1335. onEndErrors.push(...newErrors);
  1336. try {
  1337. result.errors.push(...newErrors);
  1338. } catch {
  1339. }
  1340. }
  1341. if (newWarnings) {
  1342. onEndWarnings.push(...newWarnings);
  1343. try {
  1344. result.warnings.push(...newWarnings);
  1345. } catch {
  1346. }
  1347. }
  1348. }
  1349. done(onEndErrors, onEndWarnings);
  1350. })();
  1351. };
  1352. }
  1353. let scheduleOnDisposeCallbacks = () => {
  1354. for (const cb of onDisposeCallbacks) {
  1355. setTimeout(() => cb(), 0);
  1356. }
  1357. };
  1358. isSetupDone = true;
  1359. return {
  1360. ok: true,
  1361. requestPlugins,
  1362. runOnEndCallbacks,
  1363. scheduleOnDisposeCallbacks
  1364. };
  1365. };
  1366. function createObjectStash() {
  1367. const map = /* @__PURE__ */ new Map();
  1368. let nextID = 0;
  1369. return {
  1370. load(id) {
  1371. return map.get(id);
  1372. },
  1373. store(value) {
  1374. if (value === void 0) return -1;
  1375. const id = nextID++;
  1376. map.set(id, value);
  1377. return id;
  1378. }
  1379. };
  1380. }
  1381. function extractCallerV8(e, streamIn, ident) {
  1382. let note;
  1383. let tried = false;
  1384. return () => {
  1385. if (tried) return note;
  1386. tried = true;
  1387. try {
  1388. let lines = (e.stack + "").split("\n");
  1389. lines.splice(1, 1);
  1390. let location = parseStackLinesV8(streamIn, lines, ident);
  1391. if (location) {
  1392. note = { text: e.message, location };
  1393. return note;
  1394. }
  1395. } catch {
  1396. }
  1397. };
  1398. }
  1399. function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
  1400. let text = "Internal error";
  1401. let location = null;
  1402. try {
  1403. text = (e && e.message || e) + "";
  1404. } catch {
  1405. }
  1406. try {
  1407. location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), "");
  1408. } catch {
  1409. }
  1410. return { id: "", pluginName, text, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 };
  1411. }
  1412. function parseStackLinesV8(streamIn, lines, ident) {
  1413. let at = " at ";
  1414. if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) {
  1415. for (let i = 1; i < lines.length; i++) {
  1416. let line = lines[i];
  1417. if (!line.startsWith(at)) continue;
  1418. line = line.slice(at.length);
  1419. while (true) {
  1420. let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
  1421. if (match) {
  1422. line = match[1];
  1423. continue;
  1424. }
  1425. match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
  1426. if (match) {
  1427. line = match[1];
  1428. continue;
  1429. }
  1430. match = /^(\S+):(\d+):(\d+)$/.exec(line);
  1431. if (match) {
  1432. let contents;
  1433. try {
  1434. contents = streamIn.readFileSync(match[1], "utf8");
  1435. } catch {
  1436. break;
  1437. }
  1438. let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
  1439. let column = +match[3] - 1;
  1440. let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
  1441. return {
  1442. file: match[1],
  1443. namespace: "file",
  1444. line: +match[2],
  1445. column: encodeUTF8(lineText.slice(0, column)).length,
  1446. length: encodeUTF8(lineText.slice(column, column + length)).length,
  1447. lineText: lineText + "\n" + lines.slice(1).join("\n"),
  1448. suggestion: ""
  1449. };
  1450. }
  1451. break;
  1452. }
  1453. }
  1454. }
  1455. return null;
  1456. }
  1457. function failureErrorWithLog(text, errors, warnings) {
  1458. let limit = 5;
  1459. text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => {
  1460. if (i === limit) return "\n...";
  1461. if (!e.location) return `
  1462. error: ${e.text}`;
  1463. let { file, line, column } = e.location;
  1464. let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : "";
  1465. return `
  1466. ${file}:${line}:${column}: ERROR: ${pluginText}${e.text}`;
  1467. }).join("");
  1468. let error = new Error(text);
  1469. for (const [key, value] of [["errors", errors], ["warnings", warnings]]) {
  1470. Object.defineProperty(error, key, {
  1471. configurable: true,
  1472. enumerable: true,
  1473. get: () => value,
  1474. set: (value2) => Object.defineProperty(error, key, {
  1475. configurable: true,
  1476. enumerable: true,
  1477. value: value2
  1478. })
  1479. });
  1480. }
  1481. return error;
  1482. }
  1483. function replaceDetailsInMessages(messages, stash) {
  1484. for (const message of messages) {
  1485. message.detail = stash.load(message.detail);
  1486. }
  1487. return messages;
  1488. }
  1489. function sanitizeLocation(location, where, terminalWidth) {
  1490. if (location == null) return null;
  1491. let keys = {};
  1492. let file = getFlag(location, keys, "file", mustBeString);
  1493. let namespace = getFlag(location, keys, "namespace", mustBeString);
  1494. let line = getFlag(location, keys, "line", mustBeInteger);
  1495. let column = getFlag(location, keys, "column", mustBeInteger);
  1496. let length = getFlag(location, keys, "length", mustBeInteger);
  1497. let lineText = getFlag(location, keys, "lineText", mustBeString);
  1498. let suggestion = getFlag(location, keys, "suggestion", mustBeString);
  1499. checkForInvalidFlags(location, keys, where);
  1500. if (lineText) {
  1501. const relevantASCII = lineText.slice(
  1502. 0,
  1503. (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80)
  1504. );
  1505. if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) {
  1506. lineText = relevantASCII;
  1507. }
  1508. }
  1509. return {
  1510. file: file || "",
  1511. namespace: namespace || "",
  1512. line: line || 0,
  1513. column: column || 0,
  1514. length: length || 0,
  1515. lineText: lineText || "",
  1516. suggestion: suggestion || ""
  1517. };
  1518. }
  1519. function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) {
  1520. let messagesClone = [];
  1521. let index = 0;
  1522. for (const message of messages) {
  1523. let keys = {};
  1524. let id = getFlag(message, keys, "id", mustBeString);
  1525. let pluginName = getFlag(message, keys, "pluginName", mustBeString);
  1526. let text = getFlag(message, keys, "text", mustBeString);
  1527. let location = getFlag(message, keys, "location", mustBeObjectOrNull);
  1528. let notes = getFlag(message, keys, "notes", mustBeArray);
  1529. let detail = getFlag(message, keys, "detail", canBeAnything);
  1530. let where = `in element ${index} of "${property}"`;
  1531. checkForInvalidFlags(message, keys, where);
  1532. let notesClone = [];
  1533. if (notes) {
  1534. for (const note of notes) {
  1535. let noteKeys = {};
  1536. let noteText = getFlag(note, noteKeys, "text", mustBeString);
  1537. let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
  1538. checkForInvalidFlags(note, noteKeys, where);
  1539. notesClone.push({
  1540. text: noteText || "",
  1541. location: sanitizeLocation(noteLocation, where, terminalWidth)
  1542. });
  1543. }
  1544. }
  1545. messagesClone.push({
  1546. id: id || "",
  1547. pluginName: pluginName || fallbackPluginName,
  1548. text: text || "",
  1549. location: sanitizeLocation(location, where, terminalWidth),
  1550. notes: notesClone,
  1551. detail: stash ? stash.store(detail) : -1
  1552. });
  1553. index++;
  1554. }
  1555. return messagesClone;
  1556. }
  1557. function sanitizeStringArray(values, property) {
  1558. const result = [];
  1559. for (const value of values) {
  1560. if (typeof value !== "string") throw new Error(`${quote(property)} must be an array of strings`);
  1561. result.push(value);
  1562. }
  1563. return result;
  1564. }
  1565. function sanitizeStringMap(map, property) {
  1566. const result = /* @__PURE__ */ Object.create(null);
  1567. for (const key in map) {
  1568. const value = map[key];
  1569. if (typeof value !== "string") throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`);
  1570. result[key] = value;
  1571. }
  1572. return result;
  1573. }
  1574. function convertOutputFiles({ path: path3, contents, hash }) {
  1575. let text = null;
  1576. return {
  1577. path: path3,
  1578. contents,
  1579. hash,
  1580. get text() {
  1581. const binary = this.contents;
  1582. if (text === null || binary !== contents) {
  1583. contents = binary;
  1584. text = decodeUTF8(binary);
  1585. }
  1586. return text;
  1587. }
  1588. };
  1589. }
  1590. // lib/npm/node-platform.ts
  1591. var fs = require("fs");
  1592. var os = require("os");
  1593. var path = require("path");
  1594. var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
  1595. var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
  1596. var packageDarwin_arm64 = "@esbuild/darwin-arm64";
  1597. var packageDarwin_x64 = "@esbuild/darwin-x64";
  1598. var knownWindowsPackages = {
  1599. "win32 arm64 LE": "@esbuild/win32-arm64",
  1600. "win32 ia32 LE": "@esbuild/win32-ia32",
  1601. "win32 x64 LE": "@esbuild/win32-x64"
  1602. };
  1603. var knownUnixlikePackages = {
  1604. "aix ppc64 BE": "@esbuild/aix-ppc64",
  1605. "android arm64 LE": "@esbuild/android-arm64",
  1606. "darwin arm64 LE": "@esbuild/darwin-arm64",
  1607. "darwin x64 LE": "@esbuild/darwin-x64",
  1608. "freebsd arm64 LE": "@esbuild/freebsd-arm64",
  1609. "freebsd x64 LE": "@esbuild/freebsd-x64",
  1610. "linux arm LE": "@esbuild/linux-arm",
  1611. "linux arm64 LE": "@esbuild/linux-arm64",
  1612. "linux ia32 LE": "@esbuild/linux-ia32",
  1613. "linux mips64el LE": "@esbuild/linux-mips64el",
  1614. "linux ppc64 LE": "@esbuild/linux-ppc64",
  1615. "linux riscv64 LE": "@esbuild/linux-riscv64",
  1616. "linux s390x BE": "@esbuild/linux-s390x",
  1617. "linux x64 LE": "@esbuild/linux-x64",
  1618. "linux loong64 LE": "@esbuild/linux-loong64",
  1619. "netbsd x64 LE": "@esbuild/netbsd-x64",
  1620. "openbsd x64 LE": "@esbuild/openbsd-x64",
  1621. "sunos x64 LE": "@esbuild/sunos-x64"
  1622. };
  1623. var knownWebAssemblyFallbackPackages = {
  1624. "android arm LE": "@esbuild/android-arm",
  1625. "android x64 LE": "@esbuild/android-x64"
  1626. };
  1627. function pkgAndSubpathForCurrentPlatform() {
  1628. let pkg;
  1629. let subpath;
  1630. let isWASM = false;
  1631. let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
  1632. if (platformKey in knownWindowsPackages) {
  1633. pkg = knownWindowsPackages[platformKey];
  1634. subpath = "esbuild.exe";
  1635. } else if (platformKey in knownUnixlikePackages) {
  1636. pkg = knownUnixlikePackages[platformKey];
  1637. subpath = "bin/esbuild";
  1638. } else if (platformKey in knownWebAssemblyFallbackPackages) {
  1639. pkg = knownWebAssemblyFallbackPackages[platformKey];
  1640. subpath = "bin/esbuild";
  1641. isWASM = true;
  1642. } else {
  1643. throw new Error(`Unsupported platform: ${platformKey}`);
  1644. }
  1645. return { pkg, subpath, isWASM };
  1646. }
  1647. function pkgForSomeOtherPlatform() {
  1648. const libMainJS = require.resolve("esbuild");
  1649. const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS)));
  1650. if (path.basename(nodeModulesDirectory) === "node_modules") {
  1651. for (const unixKey in knownUnixlikePackages) {
  1652. try {
  1653. const pkg = knownUnixlikePackages[unixKey];
  1654. if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
  1655. } catch {
  1656. }
  1657. }
  1658. for (const windowsKey in knownWindowsPackages) {
  1659. try {
  1660. const pkg = knownWindowsPackages[windowsKey];
  1661. if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
  1662. } catch {
  1663. }
  1664. }
  1665. }
  1666. return null;
  1667. }
  1668. function downloadedBinPath(pkg, subpath) {
  1669. const esbuildLibDir = path.dirname(require.resolve("esbuild"));
  1670. return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
  1671. }
  1672. function generateBinPath() {
  1673. if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
  1674. if (!fs.existsSync(ESBUILD_BINARY_PATH)) {
  1675. console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
  1676. } else {
  1677. return { binPath: ESBUILD_BINARY_PATH, isWASM: false };
  1678. }
  1679. }
  1680. const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
  1681. let binPath;
  1682. try {
  1683. binPath = require.resolve(`${pkg}/${subpath}`);
  1684. } catch (e) {
  1685. binPath = downloadedBinPath(pkg, subpath);
  1686. if (!fs.existsSync(binPath)) {
  1687. try {
  1688. require.resolve(pkg);
  1689. } catch {
  1690. const otherPkg = pkgForSomeOtherPlatform();
  1691. if (otherPkg) {
  1692. let suggestions = `
  1693. Specifically the "${otherPkg}" package is present but this platform
  1694. needs the "${pkg}" package instead. People often get into this
  1695. situation by installing esbuild on Windows or macOS and copying "node_modules"
  1696. into a Docker image that runs Linux, or by copying "node_modules" between
  1697. Windows and WSL environments.
  1698. If you are installing with npm, you can try not copying the "node_modules"
  1699. directory when you copy the files over, and running "npm ci" or "npm install"
  1700. on the destination platform after the copy. Or you could consider using yarn
  1701. instead of npm which has built-in support for installing a package on multiple
  1702. platforms simultaneously.
  1703. If you are installing with yarn, you can try listing both this platform and the
  1704. other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
  1705. feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
  1706. Keep in mind that this means multiple copies of esbuild will be present.
  1707. `;
  1708. if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) {
  1709. suggestions = `
  1710. Specifically the "${otherPkg}" package is present but this platform
  1711. needs the "${pkg}" package instead. People often get into this
  1712. situation by installing esbuild with npm running inside of Rosetta 2 and then
  1713. trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
  1714. 2 is Apple's on-the-fly x86_64-to-arm64 translation service).
  1715. If you are installing with npm, you can try ensuring that both npm and node are
  1716. not running under Rosetta 2 and then reinstalling esbuild. This likely involves
  1717. changing how you installed npm and/or node. For example, installing node with
  1718. the universal installer here should work: https://nodejs.org/en/download/. Or
  1719. you could consider using yarn instead of npm which has built-in support for
  1720. installing a package on multiple platforms simultaneously.
  1721. If you are installing with yarn, you can try listing both "arm64" and "x64"
  1722. in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
  1723. https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
  1724. Keep in mind that this means multiple copies of esbuild will be present.
  1725. `;
  1726. }
  1727. throw new Error(`
  1728. You installed esbuild for another platform than the one you're currently using.
  1729. This won't work because esbuild is written with native code and needs to
  1730. install a platform-specific binary executable.
  1731. ${suggestions}
  1732. Another alternative is to use the "esbuild-wasm" package instead, which works
  1733. the same way on all platforms. But it comes with a heavy performance cost and
  1734. can sometimes be 10x slower than the "esbuild" package, so you may also not
  1735. want to do that.
  1736. `);
  1737. }
  1738. throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
  1739. If you are installing esbuild with npm, make sure that you don't specify the
  1740. "--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
  1741. of "package.json" is used by esbuild to install the correct binary executable
  1742. for your current platform.`);
  1743. }
  1744. throw e;
  1745. }
  1746. }
  1747. if (/\.zip\//.test(binPath)) {
  1748. let pnpapi;
  1749. try {
  1750. pnpapi = require("pnpapi");
  1751. } catch (e) {
  1752. }
  1753. if (pnpapi) {
  1754. const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
  1755. const binTargetPath = path.join(
  1756. root,
  1757. "node_modules",
  1758. ".cache",
  1759. "esbuild",
  1760. `pnpapi-${pkg.replace("/", "-")}-${"0.21.5"}-${path.basename(subpath)}`
  1761. );
  1762. if (!fs.existsSync(binTargetPath)) {
  1763. fs.mkdirSync(path.dirname(binTargetPath), { recursive: true });
  1764. fs.copyFileSync(binPath, binTargetPath);
  1765. fs.chmodSync(binTargetPath, 493);
  1766. }
  1767. return { binPath: binTargetPath, isWASM };
  1768. }
  1769. }
  1770. return { binPath, isWASM };
  1771. }
  1772. // lib/npm/node.ts
  1773. var child_process = require("child_process");
  1774. var crypto = require("crypto");
  1775. var path2 = require("path");
  1776. var fs2 = require("fs");
  1777. var os2 = require("os");
  1778. var tty = require("tty");
  1779. var worker_threads;
  1780. if (process.env.ESBUILD_WORKER_THREADS !== "0") {
  1781. try {
  1782. worker_threads = require("worker_threads");
  1783. } catch {
  1784. }
  1785. let [major, minor] = process.versions.node.split(".");
  1786. if (
  1787. // <v12.17.0 does not work
  1788. +major < 12 || +major === 12 && +minor < 17 || +major === 13 && +minor < 13
  1789. ) {
  1790. worker_threads = void 0;
  1791. }
  1792. }
  1793. var _a;
  1794. var isInternalWorkerThread = ((_a = worker_threads == null ? void 0 : worker_threads.workerData) == null ? void 0 : _a.esbuildVersion) === "0.21.5";
  1795. var esbuildCommandAndArgs = () => {
  1796. if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) {
  1797. throw new Error(
  1798. `The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle.
  1799. More information: The file containing the code for esbuild's JavaScript API (${__filename}) does not appear to be inside the esbuild package on the file system, which usually means that the esbuild package was bundled into another file. This is problematic because the API needs to run a binary executable inside the esbuild package which is located using a relative path from the API code to the executable. If the esbuild package is bundled, the relative path will be incorrect and the executable won't be found.`
  1800. );
  1801. }
  1802. if (false) {
  1803. return ["node", [path2.join(__dirname, "..", "bin", "esbuild")]];
  1804. } else {
  1805. const { binPath, isWASM } = generateBinPath();
  1806. if (isWASM) {
  1807. return ["node", [binPath]];
  1808. } else {
  1809. return [binPath, []];
  1810. }
  1811. }
  1812. };
  1813. var isTTY = () => tty.isatty(2);
  1814. var fsSync = {
  1815. readFile(tempFile, callback) {
  1816. try {
  1817. let contents = fs2.readFileSync(tempFile, "utf8");
  1818. try {
  1819. fs2.unlinkSync(tempFile);
  1820. } catch {
  1821. }
  1822. callback(null, contents);
  1823. } catch (err) {
  1824. callback(err, null);
  1825. }
  1826. },
  1827. writeFile(contents, callback) {
  1828. try {
  1829. let tempFile = randomFileName();
  1830. fs2.writeFileSync(tempFile, contents);
  1831. callback(tempFile);
  1832. } catch {
  1833. callback(null);
  1834. }
  1835. }
  1836. };
  1837. var fsAsync = {
  1838. readFile(tempFile, callback) {
  1839. try {
  1840. fs2.readFile(tempFile, "utf8", (err, contents) => {
  1841. try {
  1842. fs2.unlink(tempFile, () => callback(err, contents));
  1843. } catch {
  1844. callback(err, contents);
  1845. }
  1846. });
  1847. } catch (err) {
  1848. callback(err, null);
  1849. }
  1850. },
  1851. writeFile(contents, callback) {
  1852. try {
  1853. let tempFile = randomFileName();
  1854. fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile));
  1855. } catch {
  1856. callback(null);
  1857. }
  1858. }
  1859. };
  1860. var version = "0.21.5";
  1861. var build = (options) => ensureServiceIsRunning().build(options);
  1862. var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions);
  1863. var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
  1864. var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
  1865. var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options);
  1866. var buildSync = (options) => {
  1867. if (worker_threads && !isInternalWorkerThread) {
  1868. if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
  1869. return workerThreadService.buildSync(options);
  1870. }
  1871. let result;
  1872. runServiceSync((service) => service.buildOrContext({
  1873. callName: "buildSync",
  1874. refs: null,
  1875. options,
  1876. isTTY: isTTY(),
  1877. defaultWD,
  1878. callback: (err, res) => {
  1879. if (err) throw err;
  1880. result = res;
  1881. }
  1882. }));
  1883. return result;
  1884. };
  1885. var transformSync = (input, options) => {
  1886. if (worker_threads && !isInternalWorkerThread) {
  1887. if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
  1888. return workerThreadService.transformSync(input, options);
  1889. }
  1890. let result;
  1891. runServiceSync((service) => service.transform({
  1892. callName: "transformSync",
  1893. refs: null,
  1894. input,
  1895. options: options || {},
  1896. isTTY: isTTY(),
  1897. fs: fsSync,
  1898. callback: (err, res) => {
  1899. if (err) throw err;
  1900. result = res;
  1901. }
  1902. }));
  1903. return result;
  1904. };
  1905. var formatMessagesSync = (messages, options) => {
  1906. if (worker_threads && !isInternalWorkerThread) {
  1907. if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
  1908. return workerThreadService.formatMessagesSync(messages, options);
  1909. }
  1910. let result;
  1911. runServiceSync((service) => service.formatMessages({
  1912. callName: "formatMessagesSync",
  1913. refs: null,
  1914. messages,
  1915. options,
  1916. callback: (err, res) => {
  1917. if (err) throw err;
  1918. result = res;
  1919. }
  1920. }));
  1921. return result;
  1922. };
  1923. var analyzeMetafileSync = (metafile, options) => {
  1924. if (worker_threads && !isInternalWorkerThread) {
  1925. if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
  1926. return workerThreadService.analyzeMetafileSync(metafile, options);
  1927. }
  1928. let result;
  1929. runServiceSync((service) => service.analyzeMetafile({
  1930. callName: "analyzeMetafileSync",
  1931. refs: null,
  1932. metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
  1933. options,
  1934. callback: (err, res) => {
  1935. if (err) throw err;
  1936. result = res;
  1937. }
  1938. }));
  1939. return result;
  1940. };
  1941. var stop = () => {
  1942. if (stopService) stopService();
  1943. if (workerThreadService) workerThreadService.stop();
  1944. return Promise.resolve();
  1945. };
  1946. var initializeWasCalled = false;
  1947. var initialize = (options) => {
  1948. options = validateInitializeOptions(options || {});
  1949. if (options.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`);
  1950. if (options.wasmModule) throw new Error(`The "wasmModule" option only works in the browser`);
  1951. if (options.worker) throw new Error(`The "worker" option only works in the browser`);
  1952. if (initializeWasCalled) throw new Error('Cannot call "initialize" more than once');
  1953. ensureServiceIsRunning();
  1954. initializeWasCalled = true;
  1955. return Promise.resolve();
  1956. };
  1957. var defaultWD = process.cwd();
  1958. var longLivedService;
  1959. var stopService;
  1960. var ensureServiceIsRunning = () => {
  1961. if (longLivedService) return longLivedService;
  1962. let [command, args] = esbuildCommandAndArgs();
  1963. let child = child_process.spawn(command, args.concat(`--service=${"0.21.5"}`, "--ping"), {
  1964. windowsHide: true,
  1965. stdio: ["pipe", "pipe", "inherit"],
  1966. cwd: defaultWD
  1967. });
  1968. let { readFromStdout, afterClose, service } = createChannel({
  1969. writeToStdin(bytes) {
  1970. child.stdin.write(bytes, (err) => {
  1971. if (err) afterClose(err);
  1972. });
  1973. },
  1974. readFileSync: fs2.readFileSync,
  1975. isSync: false,
  1976. hasFS: true,
  1977. esbuild: node_exports
  1978. });
  1979. child.stdin.on("error", afterClose);
  1980. child.on("error", afterClose);
  1981. const stdin = child.stdin;
  1982. const stdout = child.stdout;
  1983. stdout.on("data", readFromStdout);
  1984. stdout.on("end", afterClose);
  1985. stopService = () => {
  1986. stdin.destroy();
  1987. stdout.destroy();
  1988. child.kill();
  1989. initializeWasCalled = false;
  1990. longLivedService = void 0;
  1991. stopService = void 0;
  1992. };
  1993. let refCount = 0;
  1994. child.unref();
  1995. if (stdin.unref) {
  1996. stdin.unref();
  1997. }
  1998. if (stdout.unref) {
  1999. stdout.unref();
  2000. }
  2001. const refs = {
  2002. ref() {
  2003. if (++refCount === 1) child.ref();
  2004. },
  2005. unref() {
  2006. if (--refCount === 0) child.unref();
  2007. }
  2008. };
  2009. longLivedService = {
  2010. build: (options) => new Promise((resolve, reject) => {
  2011. service.buildOrContext({
  2012. callName: "build",
  2013. refs,
  2014. options,
  2015. isTTY: isTTY(),
  2016. defaultWD,
  2017. callback: (err, res) => err ? reject(err) : resolve(res)
  2018. });
  2019. }),
  2020. context: (options) => new Promise((resolve, reject) => service.buildOrContext({
  2021. callName: "context",
  2022. refs,
  2023. options,
  2024. isTTY: isTTY(),
  2025. defaultWD,
  2026. callback: (err, res) => err ? reject(err) : resolve(res)
  2027. })),
  2028. transform: (input, options) => new Promise((resolve, reject) => service.transform({
  2029. callName: "transform",
  2030. refs,
  2031. input,
  2032. options: options || {},
  2033. isTTY: isTTY(),
  2034. fs: fsAsync,
  2035. callback: (err, res) => err ? reject(err) : resolve(res)
  2036. })),
  2037. formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({
  2038. callName: "formatMessages",
  2039. refs,
  2040. messages,
  2041. options,
  2042. callback: (err, res) => err ? reject(err) : resolve(res)
  2043. })),
  2044. analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => service.analyzeMetafile({
  2045. callName: "analyzeMetafile",
  2046. refs,
  2047. metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
  2048. options,
  2049. callback: (err, res) => err ? reject(err) : resolve(res)
  2050. }))
  2051. };
  2052. return longLivedService;
  2053. };
  2054. var runServiceSync = (callback) => {
  2055. let [command, args] = esbuildCommandAndArgs();
  2056. let stdin = new Uint8Array();
  2057. let { readFromStdout, afterClose, service } = createChannel({
  2058. writeToStdin(bytes) {
  2059. if (stdin.length !== 0) throw new Error("Must run at most one command");
  2060. stdin = bytes;
  2061. },
  2062. isSync: true,
  2063. hasFS: true,
  2064. esbuild: node_exports
  2065. });
  2066. callback(service);
  2067. let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.21.5"}`), {
  2068. cwd: defaultWD,
  2069. windowsHide: true,
  2070. input: stdin,
  2071. // We don't know how large the output could be. If it's too large, the
  2072. // command will fail with ENOBUFS. Reserve 16mb for now since that feels
  2073. // like it should be enough. Also allow overriding this with an environment
  2074. // variable.
  2075. maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
  2076. });
  2077. readFromStdout(stdout);
  2078. afterClose(null);
  2079. };
  2080. var randomFileName = () => {
  2081. return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`);
  2082. };
  2083. var workerThreadService = null;
  2084. var startWorkerThreadService = (worker_threads2) => {
  2085. let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel();
  2086. let worker = new worker_threads2.Worker(__filename, {
  2087. workerData: { workerPort, defaultWD, esbuildVersion: "0.21.5" },
  2088. transferList: [workerPort],
  2089. // From node's documentation: https://nodejs.org/api/worker_threads.html
  2090. //
  2091. // Take care when launching worker threads from preload scripts (scripts loaded
  2092. // and run using the `-r` command line flag). Unless the `execArgv` option is
  2093. // explicitly set, new Worker threads automatically inherit the command line flags
  2094. // from the running process and will preload the same preload scripts as the main
  2095. // thread. If the preload script unconditionally launches a worker thread, every
  2096. // thread spawned will spawn another until the application crashes.
  2097. //
  2098. execArgv: []
  2099. });
  2100. let nextID = 0;
  2101. let fakeBuildError = (text) => {
  2102. let error = new Error(`Build failed with 1 error:
  2103. error: ${text}`);
  2104. let errors = [{ id: "", pluginName: "", text, location: null, notes: [], detail: void 0 }];
  2105. error.errors = errors;
  2106. error.warnings = [];
  2107. return error;
  2108. };
  2109. let validateBuildSyncOptions = (options) => {
  2110. if (!options) return;
  2111. let plugins = options.plugins;
  2112. if (plugins && plugins.length > 0) throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
  2113. };
  2114. let applyProperties = (object, properties) => {
  2115. for (let key in properties) {
  2116. object[key] = properties[key];
  2117. }
  2118. };
  2119. let runCallSync = (command, args) => {
  2120. let id = nextID++;
  2121. let sharedBuffer = new SharedArrayBuffer(8);
  2122. let sharedBufferView = new Int32Array(sharedBuffer);
  2123. let msg = { sharedBuffer, id, command, args };
  2124. worker.postMessage(msg);
  2125. let status = Atomics.wait(sharedBufferView, 0, 0);
  2126. if (status !== "ok" && status !== "not-equal") throw new Error("Internal error: Atomics.wait() failed: " + status);
  2127. let { message: { id: id2, resolve, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort);
  2128. if (id !== id2) throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
  2129. if (reject) {
  2130. applyProperties(reject, properties);
  2131. throw reject;
  2132. }
  2133. return resolve;
  2134. };
  2135. worker.unref();
  2136. return {
  2137. buildSync(options) {
  2138. validateBuildSyncOptions(options);
  2139. return runCallSync("build", [options]);
  2140. },
  2141. transformSync(input, options) {
  2142. return runCallSync("transform", [input, options]);
  2143. },
  2144. formatMessagesSync(messages, options) {
  2145. return runCallSync("formatMessages", [messages, options]);
  2146. },
  2147. analyzeMetafileSync(metafile, options) {
  2148. return runCallSync("analyzeMetafile", [metafile, options]);
  2149. },
  2150. stop() {
  2151. worker.terminate();
  2152. workerThreadService = null;
  2153. }
  2154. };
  2155. };
  2156. var startSyncServiceWorker = () => {
  2157. let workerPort = worker_threads.workerData.workerPort;
  2158. let parentPort = worker_threads.parentPort;
  2159. let extractProperties = (object) => {
  2160. let properties = {};
  2161. if (object && typeof object === "object") {
  2162. for (let key in object) {
  2163. properties[key] = object[key];
  2164. }
  2165. }
  2166. return properties;
  2167. };
  2168. try {
  2169. let service = ensureServiceIsRunning();
  2170. defaultWD = worker_threads.workerData.defaultWD;
  2171. parentPort.on("message", (msg) => {
  2172. (async () => {
  2173. let { sharedBuffer, id, command, args } = msg;
  2174. let sharedBufferView = new Int32Array(sharedBuffer);
  2175. try {
  2176. switch (command) {
  2177. case "build":
  2178. workerPort.postMessage({ id, resolve: await service.build(args[0]) });
  2179. break;
  2180. case "transform":
  2181. workerPort.postMessage({ id, resolve: await service.transform(args[0], args[1]) });
  2182. break;
  2183. case "formatMessages":
  2184. workerPort.postMessage({ id, resolve: await service.formatMessages(args[0], args[1]) });
  2185. break;
  2186. case "analyzeMetafile":
  2187. workerPort.postMessage({ id, resolve: await service.analyzeMetafile(args[0], args[1]) });
  2188. break;
  2189. default:
  2190. throw new Error(`Invalid command: ${command}`);
  2191. }
  2192. } catch (reject) {
  2193. workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
  2194. }
  2195. Atomics.add(sharedBufferView, 0, 1);
  2196. Atomics.notify(sharedBufferView, 0, Infinity);
  2197. })();
  2198. });
  2199. } catch (reject) {
  2200. parentPort.on("message", (msg) => {
  2201. let { sharedBuffer, id } = msg;
  2202. let sharedBufferView = new Int32Array(sharedBuffer);
  2203. workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
  2204. Atomics.add(sharedBufferView, 0, 1);
  2205. Atomics.notify(sharedBufferView, 0, Infinity);
  2206. });
  2207. }
  2208. };
  2209. if (isInternalWorkerThread) {
  2210. startSyncServiceWorker();
  2211. }
  2212. var node_default = node_exports;
  2213. // Annotate the CommonJS export names for ESM import in node:
  2214. 0 && (module.exports = {
  2215. analyzeMetafile,
  2216. analyzeMetafileSync,
  2217. build,
  2218. buildSync,
  2219. context,
  2220. formatMessages,
  2221. formatMessagesSync,
  2222. initialize,
  2223. stop,
  2224. transform,
  2225. transformSync,
  2226. version
  2227. });