browser.js 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439
  1. (module=>{
  2. "use strict";
  3. var __defProp = Object.defineProperty;
  4. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  5. var __getOwnPropNames = Object.getOwnPropertyNames;
  6. var __hasOwnProp = Object.prototype.hasOwnProperty;
  7. var __export = (target, all) => {
  8. for (var name in all)
  9. __defProp(target, name, { get: all[name], enumerable: true });
  10. };
  11. var __copyProps = (to, from, except, desc) => {
  12. if (from && typeof from === "object" || typeof from === "function") {
  13. for (let key of __getOwnPropNames(from))
  14. if (!__hasOwnProp.call(to, key) && key !== except)
  15. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  16. }
  17. return to;
  18. };
  19. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  20. var __async = (__this, __arguments, generator) => {
  21. return new Promise((resolve, reject) => {
  22. var fulfilled = (value) => {
  23. try {
  24. step(generator.next(value));
  25. } catch (e) {
  26. reject(e);
  27. }
  28. };
  29. var rejected = (value) => {
  30. try {
  31. step(generator.throw(value));
  32. } catch (e) {
  33. reject(e);
  34. }
  35. };
  36. var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
  37. step((generator = generator.apply(__this, __arguments)).next());
  38. });
  39. };
  40. // lib/npm/browser.ts
  41. var browser_exports = {};
  42. __export(browser_exports, {
  43. analyzeMetafile: () => analyzeMetafile,
  44. analyzeMetafileSync: () => analyzeMetafileSync,
  45. build: () => build,
  46. buildSync: () => buildSync,
  47. context: () => context,
  48. default: () => browser_default,
  49. formatMessages: () => formatMessages,
  50. formatMessagesSync: () => formatMessagesSync,
  51. initialize: () => initialize,
  52. stop: () => stop,
  53. transform: () => transform,
  54. transformSync: () => transformSync,
  55. version: () => version
  56. });
  57. module.exports = __toCommonJS(browser_exports);
  58. // lib/shared/stdio_protocol.ts
  59. function encodePacket(packet) {
  60. let visit = (value) => {
  61. if (value === null) {
  62. bb.write8(0);
  63. } else if (typeof value === "boolean") {
  64. bb.write8(1);
  65. bb.write8(+value);
  66. } else if (typeof value === "number") {
  67. bb.write8(2);
  68. bb.write32(value | 0);
  69. } else if (typeof value === "string") {
  70. bb.write8(3);
  71. bb.write(encodeUTF8(value));
  72. } else if (value instanceof Uint8Array) {
  73. bb.write8(4);
  74. bb.write(value);
  75. } else if (value instanceof Array) {
  76. bb.write8(5);
  77. bb.write32(value.length);
  78. for (let item of value) {
  79. visit(item);
  80. }
  81. } else {
  82. let keys = Object.keys(value);
  83. bb.write8(6);
  84. bb.write32(keys.length);
  85. for (let key of keys) {
  86. bb.write(encodeUTF8(key));
  87. visit(value[key]);
  88. }
  89. }
  90. };
  91. let bb = new ByteBuffer();
  92. bb.write32(0);
  93. bb.write32(packet.id << 1 | +!packet.isRequest);
  94. visit(packet.value);
  95. writeUInt32LE(bb.buf, bb.len - 4, 0);
  96. return bb.buf.subarray(0, bb.len);
  97. }
  98. function decodePacket(bytes) {
  99. let visit = () => {
  100. switch (bb.read8()) {
  101. case 0:
  102. return null;
  103. case 1:
  104. return !!bb.read8();
  105. case 2:
  106. return bb.read32();
  107. case 3:
  108. return decodeUTF8(bb.read());
  109. case 4:
  110. return bb.read();
  111. case 5: {
  112. let count = bb.read32();
  113. let value2 = [];
  114. for (let i = 0; i < count; i++) {
  115. value2.push(visit());
  116. }
  117. return value2;
  118. }
  119. case 6: {
  120. let count = bb.read32();
  121. let value2 = {};
  122. for (let i = 0; i < count; i++) {
  123. value2[decodeUTF8(bb.read())] = visit();
  124. }
  125. return value2;
  126. }
  127. default:
  128. throw new Error("Invalid packet");
  129. }
  130. };
  131. let bb = new ByteBuffer(bytes);
  132. let id = bb.read32();
  133. let isRequest = (id & 1) === 0;
  134. id >>>= 1;
  135. let value = visit();
  136. if (bb.ptr !== bytes.length) {
  137. throw new Error("Invalid packet");
  138. }
  139. return { id, isRequest, value };
  140. }
  141. var ByteBuffer = class {
  142. constructor(buf = new Uint8Array(1024)) {
  143. this.buf = buf;
  144. this.len = 0;
  145. this.ptr = 0;
  146. }
  147. _write(delta) {
  148. if (this.len + delta > this.buf.length) {
  149. let clone = new Uint8Array((this.len + delta) * 2);
  150. clone.set(this.buf);
  151. this.buf = clone;
  152. }
  153. this.len += delta;
  154. return this.len - delta;
  155. }
  156. write8(value) {
  157. let offset = this._write(1);
  158. this.buf[offset] = value;
  159. }
  160. write32(value) {
  161. let offset = this._write(4);
  162. writeUInt32LE(this.buf, value, offset);
  163. }
  164. write(bytes) {
  165. let offset = this._write(4 + bytes.length);
  166. writeUInt32LE(this.buf, bytes.length, offset);
  167. this.buf.set(bytes, offset + 4);
  168. }
  169. _read(delta) {
  170. if (this.ptr + delta > this.buf.length) {
  171. throw new Error("Invalid packet");
  172. }
  173. this.ptr += delta;
  174. return this.ptr - delta;
  175. }
  176. read8() {
  177. return this.buf[this._read(1)];
  178. }
  179. read32() {
  180. return readUInt32LE(this.buf, this._read(4));
  181. }
  182. read() {
  183. let length = this.read32();
  184. let bytes = new Uint8Array(length);
  185. let ptr = this._read(bytes.length);
  186. bytes.set(this.buf.subarray(ptr, ptr + length));
  187. return bytes;
  188. }
  189. };
  190. var encodeUTF8;
  191. var decodeUTF8;
  192. var encodeInvariant;
  193. if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
  194. let encoder = new TextEncoder();
  195. let decoder = new TextDecoder();
  196. encodeUTF8 = (text) => encoder.encode(text);
  197. decodeUTF8 = (bytes) => decoder.decode(bytes);
  198. encodeInvariant = 'new TextEncoder().encode("")';
  199. } else if (typeof Buffer !== "undefined") {
  200. encodeUTF8 = (text) => Buffer.from(text);
  201. decodeUTF8 = (bytes) => {
  202. let { buffer, byteOffset, byteLength } = bytes;
  203. return Buffer.from(buffer, byteOffset, byteLength).toString();
  204. };
  205. encodeInvariant = 'Buffer.from("")';
  206. } else {
  207. throw new Error("No UTF-8 codec found");
  208. }
  209. if (!(encodeUTF8("") instanceof Uint8Array))
  210. throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false
  211. This indicates that your JavaScript environment is broken. You cannot use
  212. esbuild in this environment because esbuild relies on this invariant. This
  213. is not a problem with esbuild. You need to fix your environment instead.
  214. `);
  215. function readUInt32LE(buffer, offset) {
  216. return buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24;
  217. }
  218. function writeUInt32LE(buffer, value, offset) {
  219. buffer[offset++] = value;
  220. buffer[offset++] = value >> 8;
  221. buffer[offset++] = value >> 16;
  222. buffer[offset++] = value >> 24;
  223. }
  224. // lib/shared/common.ts
  225. var quote = JSON.stringify;
  226. var buildLogLevelDefault = "warning";
  227. var transformLogLevelDefault = "silent";
  228. function validateTarget(target) {
  229. validateStringValue(target, "target");
  230. if (target.indexOf(",") >= 0) throw new Error(`Invalid target: ${target}`);
  231. return target;
  232. }
  233. var canBeAnything = () => null;
  234. var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
  235. var mustBeString = (value) => typeof value === "string" ? null : "a string";
  236. var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
  237. var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
  238. var mustBeValidPortNumber = (value) => typeof value === "number" && value === (value | 0) && value >= 0 && value <= 65535 ? null : "a valid port number";
  239. var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
  240. var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
  241. var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
  242. var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
  243. var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
  244. var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
  245. var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
  246. var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
  247. var mustBeStringOrArray = (value) => typeof value === "string" || Array.isArray(value) ? null : "a string or an array";
  248. var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
  249. var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL";
  250. function getFlag(object, keys, key, mustBeFn) {
  251. let value = object[key];
  252. keys[key + ""] = true;
  253. if (value === void 0) return void 0;
  254. let mustBe = mustBeFn(value);
  255. if (mustBe !== null) throw new Error(`${quote(key)} must be ${mustBe}`);
  256. return value;
  257. }
  258. function checkForInvalidFlags(object, keys, where) {
  259. for (let key in object) {
  260. if (!(key in keys)) {
  261. throw new Error(`Invalid option ${where}: ${quote(key)}`);
  262. }
  263. }
  264. }
  265. function validateInitializeOptions(options) {
  266. let keys = /* @__PURE__ */ Object.create(null);
  267. let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL);
  268. let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule);
  269. let worker = getFlag(options, keys, "worker", mustBeBoolean);
  270. checkForInvalidFlags(options, keys, "in initialize() call");
  271. return {
  272. wasmURL,
  273. wasmModule,
  274. worker
  275. };
  276. }
  277. function validateMangleCache(mangleCache) {
  278. let validated;
  279. if (mangleCache !== void 0) {
  280. validated = /* @__PURE__ */ Object.create(null);
  281. for (let key in mangleCache) {
  282. let value = mangleCache[key];
  283. if (typeof value === "string" || value === false) {
  284. validated[key] = value;
  285. } else {
  286. throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`);
  287. }
  288. }
  289. }
  290. return validated;
  291. }
  292. function pushLogFlags(flags, options, keys, isTTY, logLevelDefault) {
  293. let color = getFlag(options, keys, "color", mustBeBoolean);
  294. let logLevel = getFlag(options, keys, "logLevel", mustBeString);
  295. let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
  296. if (color !== void 0) flags.push(`--color=${color}`);
  297. else if (isTTY) flags.push(`--color=true`);
  298. flags.push(`--log-level=${logLevel || logLevelDefault}`);
  299. flags.push(`--log-limit=${logLimit || 0}`);
  300. }
  301. function validateStringValue(value, what, key) {
  302. if (typeof value !== "string") {
  303. throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`);
  304. }
  305. return value;
  306. }
  307. function pushCommonFlags(flags, options, keys) {
  308. let legalComments = getFlag(options, keys, "legalComments", mustBeString);
  309. let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
  310. let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
  311. let target = getFlag(options, keys, "target", mustBeStringOrArray);
  312. let format = getFlag(options, keys, "format", mustBeString);
  313. let globalName = getFlag(options, keys, "globalName", mustBeString);
  314. let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp);
  315. let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp);
  316. let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean);
  317. let minify = getFlag(options, keys, "minify", mustBeBoolean);
  318. let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
  319. let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
  320. let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
  321. let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger);
  322. let drop = getFlag(options, keys, "drop", mustBeArray);
  323. let dropLabels = getFlag(options, keys, "dropLabels", mustBeArray);
  324. let charset = getFlag(options, keys, "charset", mustBeString);
  325. let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
  326. let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
  327. let jsx = getFlag(options, keys, "jsx", mustBeString);
  328. let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
  329. let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
  330. let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString);
  331. let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean);
  332. let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean);
  333. let define = getFlag(options, keys, "define", mustBeObject);
  334. let logOverride = getFlag(options, keys, "logOverride", mustBeObject);
  335. let supported = getFlag(options, keys, "supported", mustBeObject);
  336. let pure = getFlag(options, keys, "pure", mustBeArray);
  337. let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
  338. let platform = getFlag(options, keys, "platform", mustBeString);
  339. let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
  340. if (legalComments) flags.push(`--legal-comments=${legalComments}`);
  341. if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`);
  342. if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`);
  343. if (target) {
  344. if (Array.isArray(target)) flags.push(`--target=${Array.from(target).map(validateTarget).join(",")}`);
  345. else flags.push(`--target=${validateTarget(target)}`);
  346. }
  347. if (format) flags.push(`--format=${format}`);
  348. if (globalName) flags.push(`--global-name=${globalName}`);
  349. if (platform) flags.push(`--platform=${platform}`);
  350. if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
  351. if (minify) flags.push("--minify");
  352. if (minifySyntax) flags.push("--minify-syntax");
  353. if (minifyWhitespace) flags.push("--minify-whitespace");
  354. if (minifyIdentifiers) flags.push("--minify-identifiers");
  355. if (lineLimit) flags.push(`--line-limit=${lineLimit}`);
  356. if (charset) flags.push(`--charset=${charset}`);
  357. if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`);
  358. if (ignoreAnnotations) flags.push(`--ignore-annotations`);
  359. if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`);
  360. if (dropLabels) flags.push(`--drop-labels=${Array.from(dropLabels).map((what) => validateStringValue(what, "dropLabels")).join(",")}`);
  361. if (mangleProps) flags.push(`--mangle-props=${mangleProps.source}`);
  362. if (reserveProps) flags.push(`--reserve-props=${reserveProps.source}`);
  363. if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`);
  364. if (jsx) flags.push(`--jsx=${jsx}`);
  365. if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`);
  366. if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`);
  367. if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`);
  368. if (jsxDev) flags.push(`--jsx-dev`);
  369. if (jsxSideEffects) flags.push(`--jsx-side-effects`);
  370. if (define) {
  371. for (let key in define) {
  372. if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`);
  373. flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`);
  374. }
  375. }
  376. if (logOverride) {
  377. for (let key in logOverride) {
  378. if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`);
  379. flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`);
  380. }
  381. }
  382. if (supported) {
  383. for (let key in supported) {
  384. if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`);
  385. const value = supported[key];
  386. if (typeof value !== "boolean") throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`);
  387. flags.push(`--supported:${key}=${value}`);
  388. }
  389. }
  390. if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`);
  391. if (keepNames) flags.push(`--keep-names`);
  392. }
  393. function flagsForBuildOptions(callName, options, isTTY, logLevelDefault, writeDefault) {
  394. var _a;
  395. let flags = [];
  396. let entries = [];
  397. let keys = /* @__PURE__ */ Object.create(null);
  398. let stdinContents = null;
  399. let stdinResolveDir = null;
  400. pushLogFlags(flags, options, keys, isTTY, logLevelDefault);
  401. pushCommonFlags(flags, options, keys);
  402. let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
  403. let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
  404. let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
  405. let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
  406. let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
  407. let outfile = getFlag(options, keys, "outfile", mustBeString);
  408. let outdir = getFlag(options, keys, "outdir", mustBeString);
  409. let outbase = getFlag(options, keys, "outbase", mustBeString);
  410. let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
  411. let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArray);
  412. let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArray);
  413. let mainFields = getFlag(options, keys, "mainFields", mustBeArray);
  414. let conditions = getFlag(options, keys, "conditions", mustBeArray);
  415. let external = getFlag(options, keys, "external", mustBeArray);
  416. let packages = getFlag(options, keys, "packages", mustBeString);
  417. let alias = getFlag(options, keys, "alias", mustBeObject);
  418. let loader = getFlag(options, keys, "loader", mustBeObject);
  419. let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
  420. let publicPath = getFlag(options, keys, "publicPath", mustBeString);
  421. let entryNames = getFlag(options, keys, "entryNames", mustBeString);
  422. let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
  423. let assetNames = getFlag(options, keys, "assetNames", mustBeString);
  424. let inject = getFlag(options, keys, "inject", mustBeArray);
  425. let banner = getFlag(options, keys, "banner", mustBeObject);
  426. let footer = getFlag(options, keys, "footer", mustBeObject);
  427. let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints);
  428. let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
  429. let stdin = getFlag(options, keys, "stdin", mustBeObject);
  430. let write = (_a = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a : writeDefault;
  431. let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
  432. let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
  433. keys.plugins = true;
  434. checkForInvalidFlags(options, keys, `in ${callName}() call`);
  435. if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
  436. if (bundle) flags.push("--bundle");
  437. if (allowOverwrite) flags.push("--allow-overwrite");
  438. if (splitting) flags.push("--splitting");
  439. if (preserveSymlinks) flags.push("--preserve-symlinks");
  440. if (metafile) flags.push(`--metafile`);
  441. if (outfile) flags.push(`--outfile=${outfile}`);
  442. if (outdir) flags.push(`--outdir=${outdir}`);
  443. if (outbase) flags.push(`--outbase=${outbase}`);
  444. if (tsconfig) flags.push(`--tsconfig=${tsconfig}`);
  445. if (packages) flags.push(`--packages=${packages}`);
  446. if (resolveExtensions) {
  447. let values = [];
  448. for (let value of resolveExtensions) {
  449. validateStringValue(value, "resolve extension");
  450. if (value.indexOf(",") >= 0) throw new Error(`Invalid resolve extension: ${value}`);
  451. values.push(value);
  452. }
  453. flags.push(`--resolve-extensions=${values.join(",")}`);
  454. }
  455. if (publicPath) flags.push(`--public-path=${publicPath}`);
  456. if (entryNames) flags.push(`--entry-names=${entryNames}`);
  457. if (chunkNames) flags.push(`--chunk-names=${chunkNames}`);
  458. if (assetNames) flags.push(`--asset-names=${assetNames}`);
  459. if (mainFields) {
  460. let values = [];
  461. for (let value of mainFields) {
  462. validateStringValue(value, "main field");
  463. if (value.indexOf(",") >= 0) throw new Error(`Invalid main field: ${value}`);
  464. values.push(value);
  465. }
  466. flags.push(`--main-fields=${values.join(",")}`);
  467. }
  468. if (conditions) {
  469. let values = [];
  470. for (let value of conditions) {
  471. validateStringValue(value, "condition");
  472. if (value.indexOf(",") >= 0) throw new Error(`Invalid condition: ${value}`);
  473. values.push(value);
  474. }
  475. flags.push(`--conditions=${values.join(",")}`);
  476. }
  477. if (external) for (let name of external) flags.push(`--external:${validateStringValue(name, "external")}`);
  478. if (alias) {
  479. for (let old in alias) {
  480. if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`);
  481. flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`);
  482. }
  483. }
  484. if (banner) {
  485. for (let type in banner) {
  486. if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`);
  487. flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`);
  488. }
  489. }
  490. if (footer) {
  491. for (let type in footer) {
  492. if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`);
  493. flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`);
  494. }
  495. }
  496. if (inject) for (let path of inject) flags.push(`--inject:${validateStringValue(path, "inject")}`);
  497. if (loader) {
  498. for (let ext in loader) {
  499. if (ext.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext}`);
  500. flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`);
  501. }
  502. }
  503. if (outExtension) {
  504. for (let ext in outExtension) {
  505. if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`);
  506. flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
  507. }
  508. }
  509. if (entryPoints) {
  510. if (Array.isArray(entryPoints)) {
  511. for (let i = 0, n = entryPoints.length; i < n; i++) {
  512. let entryPoint = entryPoints[i];
  513. if (typeof entryPoint === "object" && entryPoint !== null) {
  514. let entryPointKeys = /* @__PURE__ */ Object.create(null);
  515. let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
  516. let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
  517. checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
  518. if (input === void 0) throw new Error('Missing property "in" for entry point at index ' + i);
  519. if (output === void 0) throw new Error('Missing property "out" for entry point at index ' + i);
  520. entries.push([output, input]);
  521. } else {
  522. entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
  523. }
  524. }
  525. } else {
  526. for (let key in entryPoints) {
  527. entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
  528. }
  529. }
  530. }
  531. if (stdin) {
  532. let stdinKeys = /* @__PURE__ */ Object.create(null);
  533. let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
  534. let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
  535. let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
  536. let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
  537. checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object');
  538. if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
  539. if (loader2) flags.push(`--loader=${loader2}`);
  540. if (resolveDir) stdinResolveDir = resolveDir;
  541. if (typeof contents === "string") stdinContents = encodeUTF8(contents);
  542. else if (contents instanceof Uint8Array) stdinContents = contents;
  543. }
  544. let nodePaths = [];
  545. if (nodePathsInput) {
  546. for (let value of nodePathsInput) {
  547. value += "";
  548. nodePaths.push(value);
  549. }
  550. }
  551. return {
  552. entries,
  553. flags,
  554. write,
  555. stdinContents,
  556. stdinResolveDir,
  557. absWorkingDir,
  558. nodePaths,
  559. mangleCache: validateMangleCache(mangleCache)
  560. };
  561. }
  562. function flagsForTransformOptions(callName, options, isTTY, logLevelDefault) {
  563. let flags = [];
  564. let keys = /* @__PURE__ */ Object.create(null);
  565. pushLogFlags(flags, options, keys, isTTY, logLevelDefault);
  566. pushCommonFlags(flags, options, keys);
  567. let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
  568. let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
  569. let loader = getFlag(options, keys, "loader", mustBeString);
  570. let banner = getFlag(options, keys, "banner", mustBeString);
  571. let footer = getFlag(options, keys, "footer", mustBeString);
  572. let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
  573. checkForInvalidFlags(options, keys, `in ${callName}() call`);
  574. if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
  575. if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
  576. if (loader) flags.push(`--loader=${loader}`);
  577. if (banner) flags.push(`--banner=${banner}`);
  578. if (footer) flags.push(`--footer=${footer}`);
  579. return {
  580. flags,
  581. mangleCache: validateMangleCache(mangleCache)
  582. };
  583. }
  584. function createChannel(streamIn) {
  585. const requestCallbacksByKey = {};
  586. const closeData = { didClose: false, reason: "" };
  587. let responseCallbacks = {};
  588. let nextRequestID = 0;
  589. let nextBuildKey = 0;
  590. let stdout = new Uint8Array(16 * 1024);
  591. let stdoutUsed = 0;
  592. let readFromStdout = (chunk) => {
  593. let limit = stdoutUsed + chunk.length;
  594. if (limit > stdout.length) {
  595. let swap = new Uint8Array(limit * 2);
  596. swap.set(stdout);
  597. stdout = swap;
  598. }
  599. stdout.set(chunk, stdoutUsed);
  600. stdoutUsed += chunk.length;
  601. let offset = 0;
  602. while (offset + 4 <= stdoutUsed) {
  603. let length = readUInt32LE(stdout, offset);
  604. if (offset + 4 + length > stdoutUsed) {
  605. break;
  606. }
  607. offset += 4;
  608. handleIncomingPacket(stdout.subarray(offset, offset + length));
  609. offset += length;
  610. }
  611. if (offset > 0) {
  612. stdout.copyWithin(0, offset, stdoutUsed);
  613. stdoutUsed -= offset;
  614. }
  615. };
  616. let afterClose = (error) => {
  617. closeData.didClose = true;
  618. if (error) closeData.reason = ": " + (error.message || error);
  619. const text = "The service was stopped" + closeData.reason;
  620. for (let id in responseCallbacks) {
  621. responseCallbacks[id](text, null);
  622. }
  623. responseCallbacks = {};
  624. };
  625. let sendRequest = (refs, value, callback) => {
  626. if (closeData.didClose) return callback("The service is no longer running" + closeData.reason, null);
  627. let id = nextRequestID++;
  628. responseCallbacks[id] = (error, response) => {
  629. try {
  630. callback(error, response);
  631. } finally {
  632. if (refs) refs.unref();
  633. }
  634. };
  635. if (refs) refs.ref();
  636. streamIn.writeToStdin(encodePacket({ id, isRequest: true, value }));
  637. };
  638. let sendResponse = (id, value) => {
  639. if (closeData.didClose) throw new Error("The service is no longer running" + closeData.reason);
  640. streamIn.writeToStdin(encodePacket({ id, isRequest: false, value }));
  641. };
  642. let handleRequest = (id, request) => __async(this, null, function* () {
  643. try {
  644. if (request.command === "ping") {
  645. sendResponse(id, {});
  646. return;
  647. }
  648. if (typeof request.key === "number") {
  649. const requestCallbacks = requestCallbacksByKey[request.key];
  650. if (!requestCallbacks) {
  651. return;
  652. }
  653. const callback = requestCallbacks[request.command];
  654. if (callback) {
  655. yield callback(id, request);
  656. return;
  657. }
  658. }
  659. throw new Error(`Invalid command: ` + request.command);
  660. } catch (e) {
  661. const errors = [extractErrorMessageV8(e, streamIn, null, void 0, "")];
  662. try {
  663. sendResponse(id, { errors });
  664. } catch (e2) {
  665. }
  666. }
  667. });
  668. let isFirstPacket = true;
  669. let handleIncomingPacket = (bytes) => {
  670. if (isFirstPacket) {
  671. isFirstPacket = false;
  672. let binaryVersion = String.fromCharCode(...bytes);
  673. if (binaryVersion !== "0.25.1") {
  674. throw new Error(`Cannot start service: Host version "${"0.25.1"}" does not match binary version ${quote(binaryVersion)}`);
  675. }
  676. return;
  677. }
  678. let packet = decodePacket(bytes);
  679. if (packet.isRequest) {
  680. handleRequest(packet.id, packet.value);
  681. } else {
  682. let callback = responseCallbacks[packet.id];
  683. delete responseCallbacks[packet.id];
  684. if (packet.value.error) callback(packet.value.error, {});
  685. else callback(null, packet.value);
  686. }
  687. };
  688. let buildOrContext = ({ callName, refs, options, isTTY, defaultWD, callback }) => {
  689. let refCount = 0;
  690. const buildKey = nextBuildKey++;
  691. const requestCallbacks = {};
  692. const buildRefs = {
  693. ref() {
  694. if (++refCount === 1) {
  695. if (refs) refs.ref();
  696. }
  697. },
  698. unref() {
  699. if (--refCount === 0) {
  700. delete requestCallbacksByKey[buildKey];
  701. if (refs) refs.unref();
  702. }
  703. }
  704. };
  705. requestCallbacksByKey[buildKey] = requestCallbacks;
  706. buildRefs.ref();
  707. buildOrContextImpl(
  708. callName,
  709. buildKey,
  710. sendRequest,
  711. sendResponse,
  712. buildRefs,
  713. streamIn,
  714. requestCallbacks,
  715. options,
  716. isTTY,
  717. defaultWD,
  718. (err, res) => {
  719. try {
  720. callback(err, res);
  721. } finally {
  722. buildRefs.unref();
  723. }
  724. }
  725. );
  726. };
  727. let transform2 = ({ callName, refs, input, options, isTTY, fs, callback }) => {
  728. const details = createObjectStash();
  729. let start = (inputPath) => {
  730. try {
  731. if (typeof input !== "string" && !(input instanceof Uint8Array))
  732. throw new Error('The input to "transform" must be a string or a Uint8Array');
  733. let {
  734. flags,
  735. mangleCache
  736. } = flagsForTransformOptions(callName, options, isTTY, transformLogLevelDefault);
  737. let request = {
  738. command: "transform",
  739. flags,
  740. inputFS: inputPath !== null,
  741. input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input
  742. };
  743. if (mangleCache) request.mangleCache = mangleCache;
  744. sendRequest(refs, request, (error, response) => {
  745. if (error) return callback(new Error(error), null);
  746. let errors = replaceDetailsInMessages(response.errors, details);
  747. let warnings = replaceDetailsInMessages(response.warnings, details);
  748. let outstanding = 1;
  749. let next = () => {
  750. if (--outstanding === 0) {
  751. let result = {
  752. warnings,
  753. code: response.code,
  754. map: response.map,
  755. mangleCache: void 0,
  756. legalComments: void 0
  757. };
  758. if ("legalComments" in response) result.legalComments = response == null ? void 0 : response.legalComments;
  759. if (response.mangleCache) result.mangleCache = response == null ? void 0 : response.mangleCache;
  760. callback(null, result);
  761. }
  762. };
  763. if (errors.length > 0) return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
  764. if (response.codeFS) {
  765. outstanding++;
  766. fs.readFile(response.code, (err, contents) => {
  767. if (err !== null) {
  768. callback(err, null);
  769. } else {
  770. response.code = contents;
  771. next();
  772. }
  773. });
  774. }
  775. if (response.mapFS) {
  776. outstanding++;
  777. fs.readFile(response.map, (err, contents) => {
  778. if (err !== null) {
  779. callback(err, null);
  780. } else {
  781. response.map = contents;
  782. next();
  783. }
  784. });
  785. }
  786. next();
  787. });
  788. } catch (e) {
  789. let flags = [];
  790. try {
  791. pushLogFlags(flags, options, {}, isTTY, transformLogLevelDefault);
  792. } catch (e2) {
  793. }
  794. const error = extractErrorMessageV8(e, streamIn, details, void 0, "");
  795. sendRequest(refs, { command: "error", flags, error }, () => {
  796. error.detail = details.load(error.detail);
  797. callback(failureErrorWithLog("Transform failed", [error], []), null);
  798. });
  799. }
  800. };
  801. if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) {
  802. let next = start;
  803. start = () => fs.writeFile(input, next);
  804. }
  805. start(null);
  806. };
  807. let formatMessages2 = ({ callName, refs, messages, options, callback }) => {
  808. if (!options) throw new Error(`Missing second argument in ${callName}() call`);
  809. let keys = {};
  810. let kind = getFlag(options, keys, "kind", mustBeString);
  811. let color = getFlag(options, keys, "color", mustBeBoolean);
  812. let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
  813. checkForInvalidFlags(options, keys, `in ${callName}() call`);
  814. if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`);
  815. if (kind !== "error" && kind !== "warning") throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
  816. let request = {
  817. command: "format-msgs",
  818. messages: sanitizeMessages(messages, "messages", null, "", terminalWidth),
  819. isWarning: kind === "warning"
  820. };
  821. if (color !== void 0) request.color = color;
  822. if (terminalWidth !== void 0) request.terminalWidth = terminalWidth;
  823. sendRequest(refs, request, (error, response) => {
  824. if (error) return callback(new Error(error), null);
  825. callback(null, response.messages);
  826. });
  827. };
  828. let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => {
  829. if (options === void 0) options = {};
  830. let keys = {};
  831. let color = getFlag(options, keys, "color", mustBeBoolean);
  832. let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
  833. checkForInvalidFlags(options, keys, `in ${callName}() call`);
  834. let request = {
  835. command: "analyze-metafile",
  836. metafile
  837. };
  838. if (color !== void 0) request.color = color;
  839. if (verbose !== void 0) request.verbose = verbose;
  840. sendRequest(refs, request, (error, response) => {
  841. if (error) return callback(new Error(error), null);
  842. callback(null, response.result);
  843. });
  844. };
  845. return {
  846. readFromStdout,
  847. afterClose,
  848. service: {
  849. buildOrContext,
  850. transform: transform2,
  851. formatMessages: formatMessages2,
  852. analyzeMetafile: analyzeMetafile2
  853. }
  854. };
  855. }
  856. function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY, defaultWD, callback) {
  857. const details = createObjectStash();
  858. const isContext = callName === "context";
  859. const handleError = (e, pluginName) => {
  860. const flags = [];
  861. try {
  862. pushLogFlags(flags, options, {}, isTTY, buildLogLevelDefault);
  863. } catch (e2) {
  864. }
  865. const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName);
  866. sendRequest(refs, { command: "error", flags, error: message }, () => {
  867. message.detail = details.load(message.detail);
  868. callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
  869. });
  870. };
  871. let plugins;
  872. if (typeof options === "object") {
  873. const value = options.plugins;
  874. if (value !== void 0) {
  875. if (!Array.isArray(value)) return handleError(new Error(`"plugins" must be an array`), "");
  876. plugins = value;
  877. }
  878. }
  879. if (plugins && plugins.length > 0) {
  880. if (streamIn.isSync) return handleError(new Error("Cannot use plugins in synchronous API calls"), "");
  881. handlePlugins(
  882. buildKey,
  883. sendRequest,
  884. sendResponse,
  885. refs,
  886. streamIn,
  887. requestCallbacks,
  888. options,
  889. plugins,
  890. details
  891. ).then(
  892. (result) => {
  893. if (!result.ok) return handleError(result.error, result.pluginName);
  894. try {
  895. buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
  896. } catch (e) {
  897. handleError(e, "");
  898. }
  899. },
  900. (e) => handleError(e, "")
  901. );
  902. return;
  903. }
  904. try {
  905. buildOrContextContinue(null, (result, done) => done([], []), () => {
  906. });
  907. } catch (e) {
  908. handleError(e, "");
  909. }
  910. function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
  911. const writeDefault = streamIn.hasFS;
  912. const {
  913. entries,
  914. flags,
  915. write,
  916. stdinContents,
  917. stdinResolveDir,
  918. absWorkingDir,
  919. nodePaths,
  920. mangleCache
  921. } = flagsForBuildOptions(callName, options, isTTY, buildLogLevelDefault, writeDefault);
  922. if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`);
  923. const request = {
  924. command: "build",
  925. key: buildKey,
  926. entries,
  927. flags,
  928. write,
  929. stdinContents,
  930. stdinResolveDir,
  931. absWorkingDir: absWorkingDir || defaultWD,
  932. nodePaths,
  933. context: isContext
  934. };
  935. if (requestPlugins) request.plugins = requestPlugins;
  936. if (mangleCache) request.mangleCache = mangleCache;
  937. const buildResponseToResult = (response, callback2) => {
  938. const result = {
  939. errors: replaceDetailsInMessages(response.errors, details),
  940. warnings: replaceDetailsInMessages(response.warnings, details),
  941. outputFiles: void 0,
  942. metafile: void 0,
  943. mangleCache: void 0
  944. };
  945. const originalErrors = result.errors.slice();
  946. const originalWarnings = result.warnings.slice();
  947. if (response.outputFiles) result.outputFiles = response.outputFiles.map(convertOutputFiles);
  948. if (response.metafile) result.metafile = JSON.parse(response.metafile);
  949. if (response.mangleCache) result.mangleCache = response.mangleCache;
  950. if (response.writeToStdout !== void 0) console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
  951. runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
  952. if (originalErrors.length > 0 || onEndErrors.length > 0) {
  953. const error = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings));
  954. return callback2(error, null, onEndErrors, onEndWarnings);
  955. }
  956. callback2(null, result, onEndErrors, onEndWarnings);
  957. });
  958. };
  959. let latestResultPromise;
  960. let provideLatestResult;
  961. if (isContext)
  962. requestCallbacks["on-end"] = (id, request2) => new Promise((resolve) => {
  963. buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => {
  964. const response = {
  965. errors: onEndErrors,
  966. warnings: onEndWarnings
  967. };
  968. if (provideLatestResult) provideLatestResult(err, result);
  969. latestResultPromise = void 0;
  970. provideLatestResult = void 0;
  971. sendResponse(id, response);
  972. resolve();
  973. });
  974. });
  975. sendRequest(refs, request, (error, response) => {
  976. if (error) return callback(new Error(error), null);
  977. if (!isContext) {
  978. return buildResponseToResult(response, (err, res) => {
  979. scheduleOnDisposeCallbacks();
  980. return callback(err, res);
  981. });
  982. }
  983. if (response.errors.length > 0) {
  984. return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
  985. }
  986. let didDispose = false;
  987. const result = {
  988. rebuild: () => {
  989. if (!latestResultPromise) latestResultPromise = new Promise((resolve, reject) => {
  990. let settlePromise;
  991. provideLatestResult = (err, result2) => {
  992. if (!settlePromise) settlePromise = () => err ? reject(err) : resolve(result2);
  993. };
  994. const triggerAnotherBuild = () => {
  995. const request2 = {
  996. command: "rebuild",
  997. key: buildKey
  998. };
  999. sendRequest(refs, request2, (error2, response2) => {
  1000. if (error2) {
  1001. reject(new Error(error2));
  1002. } else if (settlePromise) {
  1003. settlePromise();
  1004. } else {
  1005. triggerAnotherBuild();
  1006. }
  1007. });
  1008. };
  1009. triggerAnotherBuild();
  1010. });
  1011. return latestResultPromise;
  1012. },
  1013. watch: (options2 = {}) => new Promise((resolve, reject) => {
  1014. if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`);
  1015. const keys = {};
  1016. checkForInvalidFlags(options2, keys, `in watch() call`);
  1017. const request2 = {
  1018. command: "watch",
  1019. key: buildKey
  1020. };
  1021. sendRequest(refs, request2, (error2) => {
  1022. if (error2) reject(new Error(error2));
  1023. else resolve(void 0);
  1024. });
  1025. }),
  1026. serve: (options2 = {}) => new Promise((resolve, reject) => {
  1027. if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`);
  1028. const keys = {};
  1029. const port = getFlag(options2, keys, "port", mustBeValidPortNumber);
  1030. const host = getFlag(options2, keys, "host", mustBeString);
  1031. const servedir = getFlag(options2, keys, "servedir", mustBeString);
  1032. const keyfile = getFlag(options2, keys, "keyfile", mustBeString);
  1033. const certfile = getFlag(options2, keys, "certfile", mustBeString);
  1034. const fallback = getFlag(options2, keys, "fallback", mustBeString);
  1035. const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction);
  1036. checkForInvalidFlags(options2, keys, `in serve() call`);
  1037. const request2 = {
  1038. command: "serve",
  1039. key: buildKey,
  1040. onRequest: !!onRequest
  1041. };
  1042. if (port !== void 0) request2.port = port;
  1043. if (host !== void 0) request2.host = host;
  1044. if (servedir !== void 0) request2.servedir = servedir;
  1045. if (keyfile !== void 0) request2.keyfile = keyfile;
  1046. if (certfile !== void 0) request2.certfile = certfile;
  1047. if (fallback !== void 0) request2.fallback = fallback;
  1048. sendRequest(refs, request2, (error2, response2) => {
  1049. if (error2) return reject(new Error(error2));
  1050. if (onRequest) {
  1051. requestCallbacks["serve-request"] = (id, request3) => {
  1052. onRequest(request3.args);
  1053. sendResponse(id, {});
  1054. };
  1055. }
  1056. resolve(response2);
  1057. });
  1058. }),
  1059. cancel: () => new Promise((resolve) => {
  1060. if (didDispose) return resolve();
  1061. const request2 = {
  1062. command: "cancel",
  1063. key: buildKey
  1064. };
  1065. sendRequest(refs, request2, () => {
  1066. resolve();
  1067. });
  1068. }),
  1069. dispose: () => new Promise((resolve) => {
  1070. if (didDispose) return resolve();
  1071. didDispose = true;
  1072. const request2 = {
  1073. command: "dispose",
  1074. key: buildKey
  1075. };
  1076. sendRequest(refs, request2, () => {
  1077. resolve();
  1078. scheduleOnDisposeCallbacks();
  1079. refs.unref();
  1080. });
  1081. })
  1082. };
  1083. refs.ref();
  1084. callback(null, result);
  1085. });
  1086. }
  1087. }
  1088. var handlePlugins = (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => __async(void 0, null, function* () {
  1089. let onStartCallbacks = [];
  1090. let onEndCallbacks = [];
  1091. let onResolveCallbacks = {};
  1092. let onLoadCallbacks = {};
  1093. let onDisposeCallbacks = [];
  1094. let nextCallbackID = 0;
  1095. let i = 0;
  1096. let requestPlugins = [];
  1097. let isSetupDone = false;
  1098. plugins = [...plugins];
  1099. for (let item of plugins) {
  1100. let keys = {};
  1101. if (typeof item !== "object") throw new Error(`Plugin at index ${i} must be an object`);
  1102. const name = getFlag(item, keys, "name", mustBeString);
  1103. if (typeof name !== "string" || name === "") throw new Error(`Plugin at index ${i} is missing a name`);
  1104. try {
  1105. let setup = getFlag(item, keys, "setup", mustBeFunction);
  1106. if (typeof setup !== "function") throw new Error(`Plugin is missing a setup function`);
  1107. checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`);
  1108. let plugin = {
  1109. name,
  1110. onStart: false,
  1111. onEnd: false,
  1112. onResolve: [],
  1113. onLoad: []
  1114. };
  1115. i++;
  1116. let resolve = (path, options = {}) => {
  1117. if (!isSetupDone) throw new Error('Cannot call "resolve" before plugin setup has completed');
  1118. if (typeof path !== "string") throw new Error(`The path to resolve must be a string`);
  1119. let keys2 = /* @__PURE__ */ Object.create(null);
  1120. let pluginName = getFlag(options, keys2, "pluginName", mustBeString);
  1121. let importer = getFlag(options, keys2, "importer", mustBeString);
  1122. let namespace = getFlag(options, keys2, "namespace", mustBeString);
  1123. let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString);
  1124. let kind = getFlag(options, keys2, "kind", mustBeString);
  1125. let pluginData = getFlag(options, keys2, "pluginData", canBeAnything);
  1126. let importAttributes = getFlag(options, keys2, "with", mustBeObject);
  1127. checkForInvalidFlags(options, keys2, "in resolve() call");
  1128. return new Promise((resolve2, reject) => {
  1129. const request = {
  1130. command: "resolve",
  1131. path,
  1132. key: buildKey,
  1133. pluginName: name
  1134. };
  1135. if (pluginName != null) request.pluginName = pluginName;
  1136. if (importer != null) request.importer = importer;
  1137. if (namespace != null) request.namespace = namespace;
  1138. if (resolveDir != null) request.resolveDir = resolveDir;
  1139. if (kind != null) request.kind = kind;
  1140. else throw new Error(`Must specify "kind" when calling "resolve"`);
  1141. if (pluginData != null) request.pluginData = details.store(pluginData);
  1142. if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, "with");
  1143. sendRequest(refs, request, (error, response) => {
  1144. if (error !== null) reject(new Error(error));
  1145. else resolve2({
  1146. errors: replaceDetailsInMessages(response.errors, details),
  1147. warnings: replaceDetailsInMessages(response.warnings, details),
  1148. path: response.path,
  1149. external: response.external,
  1150. sideEffects: response.sideEffects,
  1151. namespace: response.namespace,
  1152. suffix: response.suffix,
  1153. pluginData: details.load(response.pluginData)
  1154. });
  1155. });
  1156. });
  1157. };
  1158. let promise = setup({
  1159. initialOptions,
  1160. resolve,
  1161. onStart(callback) {
  1162. let registeredText = `This error came from the "onStart" callback registered here:`;
  1163. let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart");
  1164. onStartCallbacks.push({ name, callback, note: registeredNote });
  1165. plugin.onStart = true;
  1166. },
  1167. onEnd(callback) {
  1168. let registeredText = `This error came from the "onEnd" callback registered here:`;
  1169. let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd");
  1170. onEndCallbacks.push({ name, callback, note: registeredNote });
  1171. plugin.onEnd = true;
  1172. },
  1173. onResolve(options, callback) {
  1174. let registeredText = `This error came from the "onResolve" callback registered here:`;
  1175. let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve");
  1176. let keys2 = {};
  1177. let filter = getFlag(options, keys2, "filter", mustBeRegExp);
  1178. let namespace = getFlag(options, keys2, "namespace", mustBeString);
  1179. checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`);
  1180. if (filter == null) throw new Error(`onResolve() call is missing a filter`);
  1181. let id = nextCallbackID++;
  1182. onResolveCallbacks[id] = { name, callback, note: registeredNote };
  1183. plugin.onResolve.push({ id, filter: filter.source, namespace: namespace || "" });
  1184. },
  1185. onLoad(options, callback) {
  1186. let registeredText = `This error came from the "onLoad" callback registered here:`;
  1187. let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad");
  1188. let keys2 = {};
  1189. let filter = getFlag(options, keys2, "filter", mustBeRegExp);
  1190. let namespace = getFlag(options, keys2, "namespace", mustBeString);
  1191. checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`);
  1192. if (filter == null) throw new Error(`onLoad() call is missing a filter`);
  1193. let id = nextCallbackID++;
  1194. onLoadCallbacks[id] = { name, callback, note: registeredNote };
  1195. plugin.onLoad.push({ id, filter: filter.source, namespace: namespace || "" });
  1196. },
  1197. onDispose(callback) {
  1198. onDisposeCallbacks.push(callback);
  1199. },
  1200. esbuild: streamIn.esbuild
  1201. });
  1202. if (promise) yield promise;
  1203. requestPlugins.push(plugin);
  1204. } catch (e) {
  1205. return { ok: false, error: e, pluginName: name };
  1206. }
  1207. }
  1208. requestCallbacks["on-start"] = (id, request) => __async(void 0, null, function* () {
  1209. details.clear();
  1210. let response = { errors: [], warnings: [] };
  1211. yield Promise.all(onStartCallbacks.map((_0) => __async(void 0, [_0], function* ({ name, callback, note }) {
  1212. try {
  1213. let result = yield callback();
  1214. if (result != null) {
  1215. if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`);
  1216. let keys = {};
  1217. let errors = getFlag(result, keys, "errors", mustBeArray);
  1218. let warnings = getFlag(result, keys, "warnings", mustBeArray);
  1219. checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`);
  1220. if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0));
  1221. if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0));
  1222. }
  1223. } catch (e) {
  1224. response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name));
  1225. }
  1226. })));
  1227. sendResponse(id, response);
  1228. });
  1229. requestCallbacks["on-resolve"] = (id, request) => __async(void 0, null, function* () {
  1230. let response = {}, name = "", callback, note;
  1231. for (let id2 of request.ids) {
  1232. try {
  1233. ({ name, callback, note } = onResolveCallbacks[id2]);
  1234. let result = yield callback({
  1235. path: request.path,
  1236. importer: request.importer,
  1237. namespace: request.namespace,
  1238. resolveDir: request.resolveDir,
  1239. kind: request.kind,
  1240. pluginData: details.load(request.pluginData),
  1241. with: request.with
  1242. });
  1243. if (result != null) {
  1244. if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`);
  1245. let keys = {};
  1246. let pluginName = getFlag(result, keys, "pluginName", mustBeString);
  1247. let path = getFlag(result, keys, "path", mustBeString);
  1248. let namespace = getFlag(result, keys, "namespace", mustBeString);
  1249. let suffix = getFlag(result, keys, "suffix", mustBeString);
  1250. let external = getFlag(result, keys, "external", mustBeBoolean);
  1251. let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
  1252. let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
  1253. let errors = getFlag(result, keys, "errors", mustBeArray);
  1254. let warnings = getFlag(result, keys, "warnings", mustBeArray);
  1255. let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray);
  1256. let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray);
  1257. checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`);
  1258. response.id = id2;
  1259. if (pluginName != null) response.pluginName = pluginName;
  1260. if (path != null) response.path = path;
  1261. if (namespace != null) response.namespace = namespace;
  1262. if (suffix != null) response.suffix = suffix;
  1263. if (external != null) response.external = external;
  1264. if (sideEffects != null) response.sideEffects = sideEffects;
  1265. if (pluginData != null) response.pluginData = details.store(pluginData);
  1266. if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
  1267. if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
  1268. if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
  1269. if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
  1270. break;
  1271. }
  1272. } catch (e) {
  1273. response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
  1274. break;
  1275. }
  1276. }
  1277. sendResponse(id, response);
  1278. });
  1279. requestCallbacks["on-load"] = (id, request) => __async(void 0, null, function* () {
  1280. let response = {}, name = "", callback, note;
  1281. for (let id2 of request.ids) {
  1282. try {
  1283. ({ name, callback, note } = onLoadCallbacks[id2]);
  1284. let result = yield callback({
  1285. path: request.path,
  1286. namespace: request.namespace,
  1287. suffix: request.suffix,
  1288. pluginData: details.load(request.pluginData),
  1289. with: request.with
  1290. });
  1291. if (result != null) {
  1292. if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`);
  1293. let keys = {};
  1294. let pluginName = getFlag(result, keys, "pluginName", mustBeString);
  1295. let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
  1296. let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
  1297. let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
  1298. let loader = getFlag(result, keys, "loader", mustBeString);
  1299. let errors = getFlag(result, keys, "errors", mustBeArray);
  1300. let warnings = getFlag(result, keys, "warnings", mustBeArray);
  1301. let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray);
  1302. let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray);
  1303. checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`);
  1304. response.id = id2;
  1305. if (pluginName != null) response.pluginName = pluginName;
  1306. if (contents instanceof Uint8Array) response.contents = contents;
  1307. else if (contents != null) response.contents = encodeUTF8(contents);
  1308. if (resolveDir != null) response.resolveDir = resolveDir;
  1309. if (pluginData != null) response.pluginData = details.store(pluginData);
  1310. if (loader != null) response.loader = loader;
  1311. if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
  1312. if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
  1313. if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
  1314. if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
  1315. break;
  1316. }
  1317. } catch (e) {
  1318. response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
  1319. break;
  1320. }
  1321. }
  1322. sendResponse(id, response);
  1323. });
  1324. let runOnEndCallbacks = (result, done) => done([], []);
  1325. if (onEndCallbacks.length > 0) {
  1326. runOnEndCallbacks = (result, done) => {
  1327. (() => __async(void 0, null, function* () {
  1328. const onEndErrors = [];
  1329. const onEndWarnings = [];
  1330. for (const { name, callback, note } of onEndCallbacks) {
  1331. let newErrors;
  1332. let newWarnings;
  1333. try {
  1334. const value = yield callback(result);
  1335. if (value != null) {
  1336. if (typeof value !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
  1337. let keys = {};
  1338. let errors = getFlag(value, keys, "errors", mustBeArray);
  1339. let warnings = getFlag(value, keys, "warnings", mustBeArray);
  1340. checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
  1341. if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name, void 0);
  1342. if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
  1343. }
  1344. } catch (e) {
  1345. newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
  1346. }
  1347. if (newErrors) {
  1348. onEndErrors.push(...newErrors);
  1349. try {
  1350. result.errors.push(...newErrors);
  1351. } catch (e) {
  1352. }
  1353. }
  1354. if (newWarnings) {
  1355. onEndWarnings.push(...newWarnings);
  1356. try {
  1357. result.warnings.push(...newWarnings);
  1358. } catch (e) {
  1359. }
  1360. }
  1361. }
  1362. done(onEndErrors, onEndWarnings);
  1363. }))();
  1364. };
  1365. }
  1366. let scheduleOnDisposeCallbacks = () => {
  1367. for (const cb of onDisposeCallbacks) {
  1368. setTimeout(() => cb(), 0);
  1369. }
  1370. };
  1371. isSetupDone = true;
  1372. return {
  1373. ok: true,
  1374. requestPlugins,
  1375. runOnEndCallbacks,
  1376. scheduleOnDisposeCallbacks
  1377. };
  1378. });
  1379. function createObjectStash() {
  1380. const map = /* @__PURE__ */ new Map();
  1381. let nextID = 0;
  1382. return {
  1383. clear() {
  1384. map.clear();
  1385. },
  1386. load(id) {
  1387. return map.get(id);
  1388. },
  1389. store(value) {
  1390. if (value === void 0) return -1;
  1391. const id = nextID++;
  1392. map.set(id, value);
  1393. return id;
  1394. }
  1395. };
  1396. }
  1397. function extractCallerV8(e, streamIn, ident) {
  1398. let note;
  1399. let tried = false;
  1400. return () => {
  1401. if (tried) return note;
  1402. tried = true;
  1403. try {
  1404. let lines = (e.stack + "").split("\n");
  1405. lines.splice(1, 1);
  1406. let location2 = parseStackLinesV8(streamIn, lines, ident);
  1407. if (location2) {
  1408. note = { text: e.message, location: location2 };
  1409. return note;
  1410. }
  1411. } catch (e2) {
  1412. }
  1413. };
  1414. }
  1415. function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
  1416. let text = "Internal error";
  1417. let location2 = null;
  1418. try {
  1419. text = (e && e.message || e) + "";
  1420. } catch (e2) {
  1421. }
  1422. try {
  1423. location2 = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), "");
  1424. } catch (e2) {
  1425. }
  1426. return { id: "", pluginName, text, location: location2, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 };
  1427. }
  1428. function parseStackLinesV8(streamIn, lines, ident) {
  1429. let at = " at ";
  1430. if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) {
  1431. for (let i = 1; i < lines.length; i++) {
  1432. let line = lines[i];
  1433. if (!line.startsWith(at)) continue;
  1434. line = line.slice(at.length);
  1435. while (true) {
  1436. let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
  1437. if (match) {
  1438. line = match[1];
  1439. continue;
  1440. }
  1441. match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
  1442. if (match) {
  1443. line = match[1];
  1444. continue;
  1445. }
  1446. match = /^(\S+):(\d+):(\d+)$/.exec(line);
  1447. if (match) {
  1448. let contents;
  1449. try {
  1450. contents = streamIn.readFileSync(match[1], "utf8");
  1451. } catch (e) {
  1452. break;
  1453. }
  1454. let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
  1455. let column = +match[3] - 1;
  1456. let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
  1457. return {
  1458. file: match[1],
  1459. namespace: "file",
  1460. line: +match[2],
  1461. column: encodeUTF8(lineText.slice(0, column)).length,
  1462. length: encodeUTF8(lineText.slice(column, column + length)).length,
  1463. lineText: lineText + "\n" + lines.slice(1).join("\n"),
  1464. suggestion: ""
  1465. };
  1466. }
  1467. break;
  1468. }
  1469. }
  1470. }
  1471. return null;
  1472. }
  1473. function failureErrorWithLog(text, errors, warnings) {
  1474. let limit = 5;
  1475. text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => {
  1476. if (i === limit) return "\n...";
  1477. if (!e.location) return `
  1478. error: ${e.text}`;
  1479. let { file, line, column } = e.location;
  1480. let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : "";
  1481. return `
  1482. ${file}:${line}:${column}: ERROR: ${pluginText}${e.text}`;
  1483. }).join("");
  1484. let error = new Error(text);
  1485. for (const [key, value] of [["errors", errors], ["warnings", warnings]]) {
  1486. Object.defineProperty(error, key, {
  1487. configurable: true,
  1488. enumerable: true,
  1489. get: () => value,
  1490. set: (value2) => Object.defineProperty(error, key, {
  1491. configurable: true,
  1492. enumerable: true,
  1493. value: value2
  1494. })
  1495. });
  1496. }
  1497. return error;
  1498. }
  1499. function replaceDetailsInMessages(messages, stash) {
  1500. for (const message of messages) {
  1501. message.detail = stash.load(message.detail);
  1502. }
  1503. return messages;
  1504. }
  1505. function sanitizeLocation(location2, where, terminalWidth) {
  1506. if (location2 == null) return null;
  1507. let keys = {};
  1508. let file = getFlag(location2, keys, "file", mustBeString);
  1509. let namespace = getFlag(location2, keys, "namespace", mustBeString);
  1510. let line = getFlag(location2, keys, "line", mustBeInteger);
  1511. let column = getFlag(location2, keys, "column", mustBeInteger);
  1512. let length = getFlag(location2, keys, "length", mustBeInteger);
  1513. let lineText = getFlag(location2, keys, "lineText", mustBeString);
  1514. let suggestion = getFlag(location2, keys, "suggestion", mustBeString);
  1515. checkForInvalidFlags(location2, keys, where);
  1516. if (lineText) {
  1517. const relevantASCII = lineText.slice(
  1518. 0,
  1519. (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80)
  1520. );
  1521. if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) {
  1522. lineText = relevantASCII;
  1523. }
  1524. }
  1525. return {
  1526. file: file || "",
  1527. namespace: namespace || "",
  1528. line: line || 0,
  1529. column: column || 0,
  1530. length: length || 0,
  1531. lineText: lineText || "",
  1532. suggestion: suggestion || ""
  1533. };
  1534. }
  1535. function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) {
  1536. let messagesClone = [];
  1537. let index = 0;
  1538. for (const message of messages) {
  1539. let keys = {};
  1540. let id = getFlag(message, keys, "id", mustBeString);
  1541. let pluginName = getFlag(message, keys, "pluginName", mustBeString);
  1542. let text = getFlag(message, keys, "text", mustBeString);
  1543. let location2 = getFlag(message, keys, "location", mustBeObjectOrNull);
  1544. let notes = getFlag(message, keys, "notes", mustBeArray);
  1545. let detail = getFlag(message, keys, "detail", canBeAnything);
  1546. let where = `in element ${index} of "${property}"`;
  1547. checkForInvalidFlags(message, keys, where);
  1548. let notesClone = [];
  1549. if (notes) {
  1550. for (const note of notes) {
  1551. let noteKeys = {};
  1552. let noteText = getFlag(note, noteKeys, "text", mustBeString);
  1553. let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
  1554. checkForInvalidFlags(note, noteKeys, where);
  1555. notesClone.push({
  1556. text: noteText || "",
  1557. location: sanitizeLocation(noteLocation, where, terminalWidth)
  1558. });
  1559. }
  1560. }
  1561. messagesClone.push({
  1562. id: id || "",
  1563. pluginName: pluginName || fallbackPluginName,
  1564. text: text || "",
  1565. location: sanitizeLocation(location2, where, terminalWidth),
  1566. notes: notesClone,
  1567. detail: stash ? stash.store(detail) : -1
  1568. });
  1569. index++;
  1570. }
  1571. return messagesClone;
  1572. }
  1573. function sanitizeStringArray(values, property) {
  1574. const result = [];
  1575. for (const value of values) {
  1576. if (typeof value !== "string") throw new Error(`${quote(property)} must be an array of strings`);
  1577. result.push(value);
  1578. }
  1579. return result;
  1580. }
  1581. function sanitizeStringMap(map, property) {
  1582. const result = /* @__PURE__ */ Object.create(null);
  1583. for (const key in map) {
  1584. const value = map[key];
  1585. if (typeof value !== "string") throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`);
  1586. result[key] = value;
  1587. }
  1588. return result;
  1589. }
  1590. function convertOutputFiles({ path, contents, hash }) {
  1591. let text = null;
  1592. return {
  1593. path,
  1594. contents,
  1595. hash,
  1596. get text() {
  1597. const binary = this.contents;
  1598. if (text === null || binary !== contents) {
  1599. contents = binary;
  1600. text = decodeUTF8(binary);
  1601. }
  1602. return text;
  1603. }
  1604. };
  1605. }
  1606. // lib/npm/browser.ts
  1607. var version = "0.25.1";
  1608. var build = (options) => ensureServiceIsRunning().build(options);
  1609. var context = (options) => ensureServiceIsRunning().context(options);
  1610. var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
  1611. var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
  1612. var analyzeMetafile = (metafile, options) => ensureServiceIsRunning().analyzeMetafile(metafile, options);
  1613. var buildSync = () => {
  1614. throw new Error(`The "buildSync" API only works in node`);
  1615. };
  1616. var transformSync = () => {
  1617. throw new Error(`The "transformSync" API only works in node`);
  1618. };
  1619. var formatMessagesSync = () => {
  1620. throw new Error(`The "formatMessagesSync" API only works in node`);
  1621. };
  1622. var analyzeMetafileSync = () => {
  1623. throw new Error(`The "analyzeMetafileSync" API only works in node`);
  1624. };
  1625. var stop = () => {
  1626. if (stopService) stopService();
  1627. return Promise.resolve();
  1628. };
  1629. var initializePromise;
  1630. var stopService;
  1631. var longLivedService;
  1632. var ensureServiceIsRunning = () => {
  1633. if (longLivedService) return longLivedService;
  1634. if (initializePromise) throw new Error('You need to wait for the promise returned from "initialize" to be resolved before calling this');
  1635. throw new Error('You need to call "initialize" before calling this');
  1636. };
  1637. var initialize = (options) => {
  1638. options = validateInitializeOptions(options || {});
  1639. let wasmURL = options.wasmURL;
  1640. let wasmModule = options.wasmModule;
  1641. let useWorker = options.worker !== false;
  1642. if (!wasmURL && !wasmModule) throw new Error('Must provide either the "wasmURL" option or the "wasmModule" option');
  1643. if (initializePromise) throw new Error('Cannot call "initialize" more than once');
  1644. initializePromise = startRunningService(wasmURL || "", wasmModule, useWorker);
  1645. initializePromise.catch(() => {
  1646. initializePromise = void 0;
  1647. });
  1648. return initializePromise;
  1649. };
  1650. var startRunningService = (wasmURL, wasmModule, useWorker) => __async(void 0, null, function* () {
  1651. let worker;
  1652. let rejectAllWith;
  1653. const rejectAllPromise = new Promise((resolve) => rejectAllWith = resolve);
  1654. if (useWorker) {
  1655. let blob = new Blob([`onmessage=${'((postMessage) => {\n // Copyright 2018 The Go Authors. All rights reserved.\n // Use of this source code is governed by a BSD-style\n // license that can be found in the LICENSE file.\n var __async = (__this, __arguments, generator) => {\n return new Promise((resolve, reject) => {\n var fulfilled = (value) => {\n try {\n step(generator.next(value));\n } catch (e) {\n reject(e);\n }\n };\n var rejected = (value) => {\n try {\n step(generator.throw(value));\n } catch (e) {\n reject(e);\n }\n };\n var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);\n step((generator = generator.apply(__this, __arguments)).next());\n });\n };\n let onmessage;\n let globalThis = {};\n for (let o = self; o; o = Object.getPrototypeOf(o))\n for (let k of Object.getOwnPropertyNames(o))\n if (!(k in globalThis))\n Object.defineProperty(globalThis, k, { get: () => self[k] });\n "use strict";\n (() => {\n const enosys = () => {\n const err = new Error("not implemented");\n err.code = "ENOSYS";\n return err;\n };\n if (!globalThis.fs) {\n let outputBuf = "";\n globalThis.fs = {\n constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1 },\n // unused\n writeSync(fd, buf) {\n outputBuf += decoder.decode(buf);\n const nl = outputBuf.lastIndexOf("\\n");\n if (nl != -1) {\n console.log(outputBuf.substring(0, nl));\n outputBuf = outputBuf.substring(nl + 1);\n }\n return buf.length;\n },\n write(fd, buf, offset, length, position, callback) {\n if (offset !== 0 || length !== buf.length || position !== null) {\n callback(enosys());\n return;\n }\n const n = this.writeSync(fd, buf);\n callback(null, n);\n },\n chmod(path, mode, callback) {\n callback(enosys());\n },\n chown(path, uid, gid, callback) {\n callback(enosys());\n },\n close(fd, callback) {\n callback(enosys());\n },\n fchmod(fd, mode, callback) {\n callback(enosys());\n },\n fchown(fd, uid, gid, callback) {\n callback(enosys());\n },\n fstat(fd, callback) {\n callback(enosys());\n },\n fsync(fd, callback) {\n callback(null);\n },\n ftruncate(fd, length, callback) {\n callback(enosys());\n },\n lchown(path, uid, gid, callback) {\n callback(enosys());\n },\n link(path, link, callback) {\n callback(enosys());\n },\n lstat(path, callback) {\n callback(enosys());\n },\n mkdir(path, perm, callback) {\n callback(enosys());\n },\n open(path, flags, mode, callback) {\n callback(enosys());\n },\n read(fd, buffer, offset, length, position, callback) {\n callback(enosys());\n },\n readdir(path, callback) {\n callback(enosys());\n },\n readlink(path, callback) {\n callback(enosys());\n },\n rename(from, to, callback) {\n callback(enosys());\n },\n rmdir(path, callback) {\n callback(enosys());\n },\n stat(path, callback) {\n callback(enosys());\n },\n symlink(path, link, callback) {\n callback(enosys());\n },\n truncate(path, length, callback) {\n callback(enosys());\n },\n unlink(path, callback) {\n callback(enosys());\n },\n utimes(path, atime, mtime, callback) {\n callback(enosys());\n }\n };\n }\n if (!globalThis.process) {\n globalThis.process = {\n getuid() {\n return -1;\n },\n getgid() {\n return -1;\n },\n geteuid() {\n return -1;\n },\n getegid() {\n return -1;\n },\n getgroups() {\n throw enosys();\n },\n pid: -1,\n ppid: -1,\n umask() {\n throw enosys();\n },\n cwd() {\n throw enosys();\n },\n chdir() {\n throw enosys();\n }\n };\n }\n if (!globalThis.crypto) {\n throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");\n }\n if (!globalThis.performance) {\n throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");\n }\n if (!globalThis.TextEncoder) {\n throw new Error("globalThis.TextEncoder is not available, polyfill required");\n }\n if (!globalThis.TextDecoder) {\n throw new Error("globalThis.TextDecoder is not available, polyfill required");\n }\n const encoder = new TextEncoder("utf-8");\n const decoder = new TextDecoder("utf-8");\n globalThis.Go = class {\n constructor() {\n this.argv = ["js"];\n this.env = {};\n this.exit = (code) => {\n if (code !== 0) {\n console.warn("exit code:", code);\n }\n };\n this._exitPromise = new Promise((resolve) => {\n this._resolveExitPromise = resolve;\n });\n this._pendingEvent = null;\n this._scheduledTimeouts = /* @__PURE__ */ new Map();\n this._nextCallbackTimeoutID = 1;\n const setInt64 = (addr, v) => {\n this.mem.setUint32(addr + 0, v, true);\n this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);\n };\n const setInt32 = (addr, v) => {\n this.mem.setUint32(addr + 0, v, true);\n };\n const getInt64 = (addr) => {\n const low = this.mem.getUint32(addr + 0, true);\n const high = this.mem.getInt32(addr + 4, true);\n return low + high * 4294967296;\n };\n const loadValue = (addr) => {\n const f = this.mem.getFloat64(addr, true);\n if (f === 0) {\n return void 0;\n }\n if (!isNaN(f)) {\n return f;\n }\n const id = this.mem.getUint32(addr, true);\n return this._values[id];\n };\n const storeValue = (addr, v) => {\n const nanHead = 2146959360;\n if (typeof v === "number" && v !== 0) {\n if (isNaN(v)) {\n this.mem.setUint32(addr + 4, nanHead, true);\n this.mem.setUint32(addr, 0, true);\n return;\n }\n this.mem.setFloat64(addr, v, true);\n return;\n }\n if (v === void 0) {\n this.mem.setFloat64(addr, 0, true);\n return;\n }\n let id = this._ids.get(v);\n if (id === void 0) {\n id = this._idPool.pop();\n if (id === void 0) {\n id = this._values.length;\n }\n this._values[id] = v;\n this._goRefCounts[id] = 0;\n this._ids.set(v, id);\n }\n this._goRefCounts[id]++;\n let typeFlag = 0;\n switch (typeof v) {\n case "object":\n if (v !== null) {\n typeFlag = 1;\n }\n break;\n case "string":\n typeFlag = 2;\n break;\n case "symbol":\n typeFlag = 3;\n break;\n case "function":\n typeFlag = 4;\n break;\n }\n this.mem.setUint32(addr + 4, nanHead | typeFlag, true);\n this.mem.setUint32(addr, id, true);\n };\n const loadSlice = (addr) => {\n const array = getInt64(addr + 0);\n const len = getInt64(addr + 8);\n return new Uint8Array(this._inst.exports.mem.buffer, array, len);\n };\n const loadSliceOfValues = (addr) => {\n const array = getInt64(addr + 0);\n const len = getInt64(addr + 8);\n const a = new Array(len);\n for (let i = 0; i < len; i++) {\n a[i] = loadValue(array + i * 8);\n }\n return a;\n };\n const loadString = (addr) => {\n const saddr = getInt64(addr + 0);\n const len = getInt64(addr + 8);\n return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));\n };\n const timeOrigin = Date.now() - performance.now();\n this.importObject = {\n _gotest: {\n add: (a, b) => a + b\n },\n gojs: {\n // Go\'s SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)\n // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported\n // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).\n // This changes the SP, thus we have to update the SP used by the imported function.\n // func wasmExit(code int32)\n "runtime.wasmExit": (sp) => {\n sp >>>= 0;\n const code = this.mem.getInt32(sp + 8, true);\n this.exited = true;\n delete this._inst;\n delete this._values;\n delete this._goRefCounts;\n delete this._ids;\n delete this._idPool;\n this.exit(code);\n },\n // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)\n "runtime.wasmWrite": (sp) => {\n sp >>>= 0;\n const fd = getInt64(sp + 8);\n const p = getInt64(sp + 16);\n const n = this.mem.getInt32(sp + 24, true);\n globalThis.fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));\n },\n // func resetMemoryDataView()\n "runtime.resetMemoryDataView": (sp) => {\n sp >>>= 0;\n this.mem = new DataView(this._inst.exports.mem.buffer);\n },\n // func nanotime1() int64\n "runtime.nanotime1": (sp) => {\n sp >>>= 0;\n setInt64(sp + 8, (timeOrigin + performance.now()) * 1e6);\n },\n // func walltime() (sec int64, nsec int32)\n "runtime.walltime": (sp) => {\n sp >>>= 0;\n const msec = (/* @__PURE__ */ new Date()).getTime();\n setInt64(sp + 8, msec / 1e3);\n this.mem.setInt32(sp + 16, msec % 1e3 * 1e6, true);\n },\n // func scheduleTimeoutEvent(delay int64) int32\n "runtime.scheduleTimeoutEvent": (sp) => {\n sp >>>= 0;\n const id = this._nextCallbackTimeoutID;\n this._nextCallbackTimeoutID++;\n this._scheduledTimeouts.set(id, setTimeout(\n () => {\n this._resume();\n while (this._scheduledTimeouts.has(id)) {\n console.warn("scheduleTimeoutEvent: missed timeout event");\n this._resume();\n }\n },\n getInt64(sp + 8)\n ));\n this.mem.setInt32(sp + 16, id, true);\n },\n // func clearTimeoutEvent(id int32)\n "runtime.clearTimeoutEvent": (sp) => {\n sp >>>= 0;\n const id = this.mem.getInt32(sp + 8, true);\n clearTimeout(this._scheduledTimeouts.get(id));\n this._scheduledTimeouts.delete(id);\n },\n // func getRandomData(r []byte)\n "runtime.getRandomData": (sp) => {\n sp >>>= 0;\n crypto.getRandomValues(loadSlice(sp + 8));\n },\n // func finalizeRef(v ref)\n "syscall/js.finalizeRef": (sp) => {\n sp >>>= 0;\n const id = this.mem.getUint32(sp + 8, true);\n this._goRefCounts[id]--;\n if (this._goRefCounts[id] === 0) {\n const v = this._values[id];\n this._values[id] = null;\n this._ids.delete(v);\n this._idPool.push(id);\n }\n },\n // func stringVal(value string) ref\n "syscall/js.stringVal": (sp) => {\n sp >>>= 0;\n storeValue(sp + 24, loadString(sp + 8));\n },\n // func valueGet(v ref, p string) ref\n "syscall/js.valueGet": (sp) => {\n sp >>>= 0;\n const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));\n sp = this._inst.exports.getsp() >>> 0;\n storeValue(sp + 32, result);\n },\n // func valueSet(v ref, p string, x ref)\n "syscall/js.valueSet": (sp) => {\n sp >>>= 0;\n Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));\n },\n // func valueDelete(v ref, p string)\n "syscall/js.valueDelete": (sp) => {\n sp >>>= 0;\n Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));\n },\n // func valueIndex(v ref, i int) ref\n "syscall/js.valueIndex": (sp) => {\n sp >>>= 0;\n storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));\n },\n // valueSetIndex(v ref, i int, x ref)\n "syscall/js.valueSetIndex": (sp) => {\n sp >>>= 0;\n Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));\n },\n // func valueCall(v ref, m string, args []ref) (ref, bool)\n "syscall/js.valueCall": (sp) => {\n sp >>>= 0;\n try {\n const v = loadValue(sp + 8);\n const m = Reflect.get(v, loadString(sp + 16));\n const args = loadSliceOfValues(sp + 32);\n const result = Reflect.apply(m, v, args);\n sp = this._inst.exports.getsp() >>> 0;\n storeValue(sp + 56, result);\n this.mem.setUint8(sp + 64, 1);\n } catch (err) {\n sp = this._inst.exports.getsp() >>> 0;\n storeValue(sp + 56, err);\n this.mem.setUint8(sp + 64, 0);\n }\n },\n // func valueInvoke(v ref, args []ref) (ref, bool)\n "syscall/js.valueInvoke": (sp) => {\n sp >>>= 0;\n try {\n const v = loadValue(sp + 8);\n const args = loadSliceOfValues(sp + 16);\n const result = Reflect.apply(v, void 0, args);\n sp = this._inst.exports.getsp() >>> 0;\n storeValue(sp + 40, result);\n this.mem.setUint8(sp + 48, 1);\n } catch (err) {\n sp = this._inst.exports.getsp() >>> 0;\n storeValue(sp + 40, err);\n this.mem.setUint8(sp + 48, 0);\n }\n },\n // func valueNew(v ref, args []ref) (ref, bool)\n "syscall/js.valueNew": (sp) => {\n sp >>>= 0;\n try {\n const v = loadValue(sp + 8);\n const args = loadSliceOfValues(sp + 16);\n const result = Reflect.construct(v, args);\n sp = this._inst.exports.getsp() >>> 0;\n storeValue(sp + 40, result);\n this.mem.setUint8(sp + 48, 1);\n } catch (err) {\n sp = this._inst.exports.getsp() >>> 0;\n storeValue(sp + 40, err);\n this.mem.setUint8(sp + 48, 0);\n }\n },\n // func valueLength(v ref) int\n "syscall/js.valueLength": (sp) => {\n sp >>>= 0;\n setInt64(sp + 16, parseInt(loadValue(sp + 8).length));\n },\n // valuePrepareString(v ref) (ref, int)\n "syscall/js.valuePrepareString": (sp) => {\n sp >>>= 0;\n const str = encoder.encode(String(loadValue(sp + 8)));\n storeValue(sp + 16, str);\n setInt64(sp + 24, str.length);\n },\n // valueLoadString(v ref, b []byte)\n "syscall/js.valueLoadString": (sp) => {\n sp >>>= 0;\n const str = loadValue(sp + 8);\n loadSlice(sp + 16).set(str);\n },\n // func valueInstanceOf(v ref, t ref) bool\n "syscall/js.valueInstanceOf": (sp) => {\n sp >>>= 0;\n this.mem.setUint8(sp + 24, loadValue(sp + 8) instanceof loadValue(sp + 16) ? 1 : 0);\n },\n // func copyBytesToGo(dst []byte, src ref) (int, bool)\n "syscall/js.copyBytesToGo": (sp) => {\n sp >>>= 0;\n const dst = loadSlice(sp + 8);\n const src = loadValue(sp + 32);\n if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {\n this.mem.setUint8(sp + 48, 0);\n return;\n }\n const toCopy = src.subarray(0, dst.length);\n dst.set(toCopy);\n setInt64(sp + 40, toCopy.length);\n this.mem.setUint8(sp + 48, 1);\n },\n // func copyBytesToJS(dst ref, src []byte) (int, bool)\n "syscall/js.copyBytesToJS": (sp) => {\n sp >>>= 0;\n const dst = loadValue(sp + 8);\n const src = loadSlice(sp + 16);\n if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {\n this.mem.setUint8(sp + 48, 0);\n return;\n }\n const toCopy = src.subarray(0, dst.length);\n dst.set(toCopy);\n setInt64(sp + 40, toCopy.length);\n this.mem.setUint8(sp + 48, 1);\n },\n "debug": (value) => {\n console.log(value);\n }\n }\n };\n }\n run(instance) {\n return __async(this, null, function* () {\n if (!(instance instanceof WebAssembly.Instance)) {\n throw new Error("Go.run: WebAssembly.Instance expected");\n }\n this._inst = instance;\n this.mem = new DataView(this._inst.exports.mem.buffer);\n this._values = [\n // JS values that Go currently has references to, indexed by reference id\n NaN,\n 0,\n null,\n true,\n false,\n globalThis,\n this\n ];\n this._goRefCounts = new Array(this._values.length).fill(Infinity);\n this._ids = /* @__PURE__ */ new Map([\n // mapping from JS values to reference ids\n [0, 1],\n [null, 2],\n [true, 3],\n [false, 4],\n [globalThis, 5],\n [this, 6]\n ]);\n this._idPool = [];\n this.exited = false;\n let offset = 4096;\n const strPtr = (str) => {\n const ptr = offset;\n const bytes = encoder.encode(str + "\\0");\n new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);\n offset += bytes.length;\n if (offset % 8 !== 0) {\n offset += 8 - offset % 8;\n }\n return ptr;\n };\n const argc = this.argv.length;\n const argvPtrs = [];\n this.argv.forEach((arg) => {\n argvPtrs.push(strPtr(arg));\n });\n argvPtrs.push(0);\n const keys = Object.keys(this.env).sort();\n keys.forEach((key) => {\n argvPtrs.push(strPtr(`${key}=${this.env[key]}`));\n });\n argvPtrs.push(0);\n const argv = offset;\n argvPtrs.forEach((ptr) => {\n this.mem.setUint32(offset, ptr, true);\n this.mem.setUint32(offset + 4, 0, true);\n offset += 8;\n });\n const wasmMinDataAddr = 4096 + 8192;\n if (offset >= wasmMinDataAddr) {\n throw new Error("total length of command line and environment variables exceeds limit");\n }\n this._inst.exports.run(argc, argv);\n if (this.exited) {\n this._resolveExitPromise();\n }\n yield this._exitPromise;\n });\n }\n _resume() {\n if (this.exited) {\n throw new Error("Go program has already exited");\n }\n this._inst.exports.resume();\n if (this.exited) {\n this._resolveExitPromise();\n }\n }\n _makeFuncWrapper(id) {\n const go = this;\n return function() {\n const event = { id, this: this, args: arguments };\n go._pendingEvent = event;\n go._resume();\n return event.result;\n };\n }\n };\n })();\n onmessage = ({ data: wasm }) => {\n let decoder = new TextDecoder();\n let fs = globalThis.fs;\n let stderr = "";\n fs.writeSync = (fd, buffer) => {\n if (fd === 1) {\n postMessage(buffer);\n } else if (fd === 2) {\n stderr += decoder.decode(buffer);\n let parts = stderr.split("\\n");\n if (parts.length > 1) console.log(parts.slice(0, -1).join("\\n"));\n stderr = parts[parts.length - 1];\n } else {\n throw new Error("Bad write");\n }\n return buffer.length;\n };\n let stdin = [];\n let resumeStdin;\n let stdinPos = 0;\n onmessage = ({ data }) => {\n if (data.length > 0) {\n stdin.push(data);\n if (resumeStdin) resumeStdin();\n }\n return go;\n };\n fs.read = (fd, buffer, offset, length, position, callback) => {\n if (fd !== 0 || offset !== 0 || length !== buffer.length || position !== null) {\n throw new Error("Bad read");\n }\n if (stdin.length === 0) {\n resumeStdin = () => fs.read(fd, buffer, offset, length, position, callback);\n return;\n }\n let first = stdin[0];\n let count = Math.max(0, Math.min(length, first.length - stdinPos));\n buffer.set(first.subarray(stdinPos, stdinPos + count), offset);\n stdinPos += count;\n if (stdinPos === first.length) {\n stdin.shift();\n stdinPos = 0;\n }\n callback(null, count);\n };\n let go = new globalThis.Go();\n go.argv = ["", `--service=${"0.25.1"}`];\n tryToInstantiateModule(wasm, go).then(\n (instance) => {\n postMessage(null);\n go.run(instance);\n },\n (error) => {\n postMessage(error);\n }\n );\n return go;\n };\n function tryToInstantiateModule(wasm, go) {\n return __async(this, null, function* () {\n if (wasm instanceof WebAssembly.Module) {\n return WebAssembly.instantiate(wasm, go.importObject);\n }\n const res = yield fetch(wasm);\n if (!res.ok) throw new Error(`Failed to download ${JSON.stringify(wasm)}`);\n if ("instantiateStreaming" in WebAssembly && /^application\\/wasm($|;)/i.test(res.headers.get("Content-Type") || "")) {\n const result2 = yield WebAssembly.instantiateStreaming(res, go.importObject);\n return result2.instance;\n }\n const bytes = yield res.arrayBuffer();\n const result = yield WebAssembly.instantiate(bytes, go.importObject);\n return result.instance;\n });\n }\n return (m) => onmessage(m);\n })'}(postMessage)`], { type: "text/javascript" });
  1656. worker = new Worker(URL.createObjectURL(blob));
  1657. } else {
  1658. let onmessage = ((postMessage) => {
  1659. // Copyright 2018 The Go Authors. All rights reserved.
  1660. // Use of this source code is governed by a BSD-style
  1661. // license that can be found in the LICENSE file.
  1662. var __async = (__this, __arguments, generator) => {
  1663. return new Promise((resolve, reject) => {
  1664. var fulfilled = (value) => {
  1665. try {
  1666. step(generator.next(value));
  1667. } catch (e) {
  1668. reject(e);
  1669. }
  1670. };
  1671. var rejected = (value) => {
  1672. try {
  1673. step(generator.throw(value));
  1674. } catch (e) {
  1675. reject(e);
  1676. }
  1677. };
  1678. var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
  1679. step((generator = generator.apply(__this, __arguments)).next());
  1680. });
  1681. };
  1682. let onmessage;
  1683. let globalThis = {};
  1684. for (let o = self; o; o = Object.getPrototypeOf(o))
  1685. for (let k of Object.getOwnPropertyNames(o))
  1686. if (!(k in globalThis))
  1687. Object.defineProperty(globalThis, k, { get: () => self[k] });
  1688. "use strict";
  1689. (() => {
  1690. const enosys = () => {
  1691. const err = new Error("not implemented");
  1692. err.code = "ENOSYS";
  1693. return err;
  1694. };
  1695. if (!globalThis.fs) {
  1696. let outputBuf = "";
  1697. globalThis.fs = {
  1698. constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1 },
  1699. // unused
  1700. writeSync(fd, buf) {
  1701. outputBuf += decoder.decode(buf);
  1702. const nl = outputBuf.lastIndexOf("\n");
  1703. if (nl != -1) {
  1704. console.log(outputBuf.substring(0, nl));
  1705. outputBuf = outputBuf.substring(nl + 1);
  1706. }
  1707. return buf.length;
  1708. },
  1709. write(fd, buf, offset, length, position, callback) {
  1710. if (offset !== 0 || length !== buf.length || position !== null) {
  1711. callback(enosys());
  1712. return;
  1713. }
  1714. const n = this.writeSync(fd, buf);
  1715. callback(null, n);
  1716. },
  1717. chmod(path, mode, callback) {
  1718. callback(enosys());
  1719. },
  1720. chown(path, uid, gid, callback) {
  1721. callback(enosys());
  1722. },
  1723. close(fd, callback) {
  1724. callback(enosys());
  1725. },
  1726. fchmod(fd, mode, callback) {
  1727. callback(enosys());
  1728. },
  1729. fchown(fd, uid, gid, callback) {
  1730. callback(enosys());
  1731. },
  1732. fstat(fd, callback) {
  1733. callback(enosys());
  1734. },
  1735. fsync(fd, callback) {
  1736. callback(null);
  1737. },
  1738. ftruncate(fd, length, callback) {
  1739. callback(enosys());
  1740. },
  1741. lchown(path, uid, gid, callback) {
  1742. callback(enosys());
  1743. },
  1744. link(path, link, callback) {
  1745. callback(enosys());
  1746. },
  1747. lstat(path, callback) {
  1748. callback(enosys());
  1749. },
  1750. mkdir(path, perm, callback) {
  1751. callback(enosys());
  1752. },
  1753. open(path, flags, mode, callback) {
  1754. callback(enosys());
  1755. },
  1756. read(fd, buffer, offset, length, position, callback) {
  1757. callback(enosys());
  1758. },
  1759. readdir(path, callback) {
  1760. callback(enosys());
  1761. },
  1762. readlink(path, callback) {
  1763. callback(enosys());
  1764. },
  1765. rename(from, to, callback) {
  1766. callback(enosys());
  1767. },
  1768. rmdir(path, callback) {
  1769. callback(enosys());
  1770. },
  1771. stat(path, callback) {
  1772. callback(enosys());
  1773. },
  1774. symlink(path, link, callback) {
  1775. callback(enosys());
  1776. },
  1777. truncate(path, length, callback) {
  1778. callback(enosys());
  1779. },
  1780. unlink(path, callback) {
  1781. callback(enosys());
  1782. },
  1783. utimes(path, atime, mtime, callback) {
  1784. callback(enosys());
  1785. }
  1786. };
  1787. }
  1788. if (!globalThis.process) {
  1789. globalThis.process = {
  1790. getuid() {
  1791. return -1;
  1792. },
  1793. getgid() {
  1794. return -1;
  1795. },
  1796. geteuid() {
  1797. return -1;
  1798. },
  1799. getegid() {
  1800. return -1;
  1801. },
  1802. getgroups() {
  1803. throw enosys();
  1804. },
  1805. pid: -1,
  1806. ppid: -1,
  1807. umask() {
  1808. throw enosys();
  1809. },
  1810. cwd() {
  1811. throw enosys();
  1812. },
  1813. chdir() {
  1814. throw enosys();
  1815. }
  1816. };
  1817. }
  1818. if (!globalThis.crypto) {
  1819. throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");
  1820. }
  1821. if (!globalThis.performance) {
  1822. throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");
  1823. }
  1824. if (!globalThis.TextEncoder) {
  1825. throw new Error("globalThis.TextEncoder is not available, polyfill required");
  1826. }
  1827. if (!globalThis.TextDecoder) {
  1828. throw new Error("globalThis.TextDecoder is not available, polyfill required");
  1829. }
  1830. const encoder = new TextEncoder("utf-8");
  1831. const decoder = new TextDecoder("utf-8");
  1832. globalThis.Go = class {
  1833. constructor() {
  1834. this.argv = ["js"];
  1835. this.env = {};
  1836. this.exit = (code) => {
  1837. if (code !== 0) {
  1838. console.warn("exit code:", code);
  1839. }
  1840. };
  1841. this._exitPromise = new Promise((resolve) => {
  1842. this._resolveExitPromise = resolve;
  1843. });
  1844. this._pendingEvent = null;
  1845. this._scheduledTimeouts = /* @__PURE__ */ new Map();
  1846. this._nextCallbackTimeoutID = 1;
  1847. const setInt64 = (addr, v) => {
  1848. this.mem.setUint32(addr + 0, v, true);
  1849. this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
  1850. };
  1851. const setInt32 = (addr, v) => {
  1852. this.mem.setUint32(addr + 0, v, true);
  1853. };
  1854. const getInt64 = (addr) => {
  1855. const low = this.mem.getUint32(addr + 0, true);
  1856. const high = this.mem.getInt32(addr + 4, true);
  1857. return low + high * 4294967296;
  1858. };
  1859. const loadValue = (addr) => {
  1860. const f = this.mem.getFloat64(addr, true);
  1861. if (f === 0) {
  1862. return void 0;
  1863. }
  1864. if (!isNaN(f)) {
  1865. return f;
  1866. }
  1867. const id = this.mem.getUint32(addr, true);
  1868. return this._values[id];
  1869. };
  1870. const storeValue = (addr, v) => {
  1871. const nanHead = 2146959360;
  1872. if (typeof v === "number" && v !== 0) {
  1873. if (isNaN(v)) {
  1874. this.mem.setUint32(addr + 4, nanHead, true);
  1875. this.mem.setUint32(addr, 0, true);
  1876. return;
  1877. }
  1878. this.mem.setFloat64(addr, v, true);
  1879. return;
  1880. }
  1881. if (v === void 0) {
  1882. this.mem.setFloat64(addr, 0, true);
  1883. return;
  1884. }
  1885. let id = this._ids.get(v);
  1886. if (id === void 0) {
  1887. id = this._idPool.pop();
  1888. if (id === void 0) {
  1889. id = this._values.length;
  1890. }
  1891. this._values[id] = v;
  1892. this._goRefCounts[id] = 0;
  1893. this._ids.set(v, id);
  1894. }
  1895. this._goRefCounts[id]++;
  1896. let typeFlag = 0;
  1897. switch (typeof v) {
  1898. case "object":
  1899. if (v !== null) {
  1900. typeFlag = 1;
  1901. }
  1902. break;
  1903. case "string":
  1904. typeFlag = 2;
  1905. break;
  1906. case "symbol":
  1907. typeFlag = 3;
  1908. break;
  1909. case "function":
  1910. typeFlag = 4;
  1911. break;
  1912. }
  1913. this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
  1914. this.mem.setUint32(addr, id, true);
  1915. };
  1916. const loadSlice = (addr) => {
  1917. const array = getInt64(addr + 0);
  1918. const len = getInt64(addr + 8);
  1919. return new Uint8Array(this._inst.exports.mem.buffer, array, len);
  1920. };
  1921. const loadSliceOfValues = (addr) => {
  1922. const array = getInt64(addr + 0);
  1923. const len = getInt64(addr + 8);
  1924. const a = new Array(len);
  1925. for (let i = 0; i < len; i++) {
  1926. a[i] = loadValue(array + i * 8);
  1927. }
  1928. return a;
  1929. };
  1930. const loadString = (addr) => {
  1931. const saddr = getInt64(addr + 0);
  1932. const len = getInt64(addr + 8);
  1933. return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
  1934. };
  1935. const timeOrigin = Date.now() - performance.now();
  1936. this.importObject = {
  1937. _gotest: {
  1938. add: (a, b) => a + b
  1939. },
  1940. gojs: {
  1941. // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
  1942. // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
  1943. // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
  1944. // This changes the SP, thus we have to update the SP used by the imported function.
  1945. // func wasmExit(code int32)
  1946. "runtime.wasmExit": (sp) => {
  1947. sp >>>= 0;
  1948. const code = this.mem.getInt32(sp + 8, true);
  1949. this.exited = true;
  1950. delete this._inst;
  1951. delete this._values;
  1952. delete this._goRefCounts;
  1953. delete this._ids;
  1954. delete this._idPool;
  1955. this.exit(code);
  1956. },
  1957. // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
  1958. "runtime.wasmWrite": (sp) => {
  1959. sp >>>= 0;
  1960. const fd = getInt64(sp + 8);
  1961. const p = getInt64(sp + 16);
  1962. const n = this.mem.getInt32(sp + 24, true);
  1963. globalThis.fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
  1964. },
  1965. // func resetMemoryDataView()
  1966. "runtime.resetMemoryDataView": (sp) => {
  1967. sp >>>= 0;
  1968. this.mem = new DataView(this._inst.exports.mem.buffer);
  1969. },
  1970. // func nanotime1() int64
  1971. "runtime.nanotime1": (sp) => {
  1972. sp >>>= 0;
  1973. setInt64(sp + 8, (timeOrigin + performance.now()) * 1e6);
  1974. },
  1975. // func walltime() (sec int64, nsec int32)
  1976. "runtime.walltime": (sp) => {
  1977. sp >>>= 0;
  1978. const msec = (/* @__PURE__ */ new Date()).getTime();
  1979. setInt64(sp + 8, msec / 1e3);
  1980. this.mem.setInt32(sp + 16, msec % 1e3 * 1e6, true);
  1981. },
  1982. // func scheduleTimeoutEvent(delay int64) int32
  1983. "runtime.scheduleTimeoutEvent": (sp) => {
  1984. sp >>>= 0;
  1985. const id = this._nextCallbackTimeoutID;
  1986. this._nextCallbackTimeoutID++;
  1987. this._scheduledTimeouts.set(id, setTimeout(
  1988. () => {
  1989. this._resume();
  1990. while (this._scheduledTimeouts.has(id)) {
  1991. console.warn("scheduleTimeoutEvent: missed timeout event");
  1992. this._resume();
  1993. }
  1994. },
  1995. getInt64(sp + 8)
  1996. ));
  1997. this.mem.setInt32(sp + 16, id, true);
  1998. },
  1999. // func clearTimeoutEvent(id int32)
  2000. "runtime.clearTimeoutEvent": (sp) => {
  2001. sp >>>= 0;
  2002. const id = this.mem.getInt32(sp + 8, true);
  2003. clearTimeout(this._scheduledTimeouts.get(id));
  2004. this._scheduledTimeouts.delete(id);
  2005. },
  2006. // func getRandomData(r []byte)
  2007. "runtime.getRandomData": (sp) => {
  2008. sp >>>= 0;
  2009. crypto.getRandomValues(loadSlice(sp + 8));
  2010. },
  2011. // func finalizeRef(v ref)
  2012. "syscall/js.finalizeRef": (sp) => {
  2013. sp >>>= 0;
  2014. const id = this.mem.getUint32(sp + 8, true);
  2015. this._goRefCounts[id]--;
  2016. if (this._goRefCounts[id] === 0) {
  2017. const v = this._values[id];
  2018. this._values[id] = null;
  2019. this._ids.delete(v);
  2020. this._idPool.push(id);
  2021. }
  2022. },
  2023. // func stringVal(value string) ref
  2024. "syscall/js.stringVal": (sp) => {
  2025. sp >>>= 0;
  2026. storeValue(sp + 24, loadString(sp + 8));
  2027. },
  2028. // func valueGet(v ref, p string) ref
  2029. "syscall/js.valueGet": (sp) => {
  2030. sp >>>= 0;
  2031. const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
  2032. sp = this._inst.exports.getsp() >>> 0;
  2033. storeValue(sp + 32, result);
  2034. },
  2035. // func valueSet(v ref, p string, x ref)
  2036. "syscall/js.valueSet": (sp) => {
  2037. sp >>>= 0;
  2038. Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
  2039. },
  2040. // func valueDelete(v ref, p string)
  2041. "syscall/js.valueDelete": (sp) => {
  2042. sp >>>= 0;
  2043. Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
  2044. },
  2045. // func valueIndex(v ref, i int) ref
  2046. "syscall/js.valueIndex": (sp) => {
  2047. sp >>>= 0;
  2048. storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
  2049. },
  2050. // valueSetIndex(v ref, i int, x ref)
  2051. "syscall/js.valueSetIndex": (sp) => {
  2052. sp >>>= 0;
  2053. Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
  2054. },
  2055. // func valueCall(v ref, m string, args []ref) (ref, bool)
  2056. "syscall/js.valueCall": (sp) => {
  2057. sp >>>= 0;
  2058. try {
  2059. const v = loadValue(sp + 8);
  2060. const m = Reflect.get(v, loadString(sp + 16));
  2061. const args = loadSliceOfValues(sp + 32);
  2062. const result = Reflect.apply(m, v, args);
  2063. sp = this._inst.exports.getsp() >>> 0;
  2064. storeValue(sp + 56, result);
  2065. this.mem.setUint8(sp + 64, 1);
  2066. } catch (err) {
  2067. sp = this._inst.exports.getsp() >>> 0;
  2068. storeValue(sp + 56, err);
  2069. this.mem.setUint8(sp + 64, 0);
  2070. }
  2071. },
  2072. // func valueInvoke(v ref, args []ref) (ref, bool)
  2073. "syscall/js.valueInvoke": (sp) => {
  2074. sp >>>= 0;
  2075. try {
  2076. const v = loadValue(sp + 8);
  2077. const args = loadSliceOfValues(sp + 16);
  2078. const result = Reflect.apply(v, void 0, args);
  2079. sp = this._inst.exports.getsp() >>> 0;
  2080. storeValue(sp + 40, result);
  2081. this.mem.setUint8(sp + 48, 1);
  2082. } catch (err) {
  2083. sp = this._inst.exports.getsp() >>> 0;
  2084. storeValue(sp + 40, err);
  2085. this.mem.setUint8(sp + 48, 0);
  2086. }
  2087. },
  2088. // func valueNew(v ref, args []ref) (ref, bool)
  2089. "syscall/js.valueNew": (sp) => {
  2090. sp >>>= 0;
  2091. try {
  2092. const v = loadValue(sp + 8);
  2093. const args = loadSliceOfValues(sp + 16);
  2094. const result = Reflect.construct(v, args);
  2095. sp = this._inst.exports.getsp() >>> 0;
  2096. storeValue(sp + 40, result);
  2097. this.mem.setUint8(sp + 48, 1);
  2098. } catch (err) {
  2099. sp = this._inst.exports.getsp() >>> 0;
  2100. storeValue(sp + 40, err);
  2101. this.mem.setUint8(sp + 48, 0);
  2102. }
  2103. },
  2104. // func valueLength(v ref) int
  2105. "syscall/js.valueLength": (sp) => {
  2106. sp >>>= 0;
  2107. setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
  2108. },
  2109. // valuePrepareString(v ref) (ref, int)
  2110. "syscall/js.valuePrepareString": (sp) => {
  2111. sp >>>= 0;
  2112. const str = encoder.encode(String(loadValue(sp + 8)));
  2113. storeValue(sp + 16, str);
  2114. setInt64(sp + 24, str.length);
  2115. },
  2116. // valueLoadString(v ref, b []byte)
  2117. "syscall/js.valueLoadString": (sp) => {
  2118. sp >>>= 0;
  2119. const str = loadValue(sp + 8);
  2120. loadSlice(sp + 16).set(str);
  2121. },
  2122. // func valueInstanceOf(v ref, t ref) bool
  2123. "syscall/js.valueInstanceOf": (sp) => {
  2124. sp >>>= 0;
  2125. this.mem.setUint8(sp + 24, loadValue(sp + 8) instanceof loadValue(sp + 16) ? 1 : 0);
  2126. },
  2127. // func copyBytesToGo(dst []byte, src ref) (int, bool)
  2128. "syscall/js.copyBytesToGo": (sp) => {
  2129. sp >>>= 0;
  2130. const dst = loadSlice(sp + 8);
  2131. const src = loadValue(sp + 32);
  2132. if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
  2133. this.mem.setUint8(sp + 48, 0);
  2134. return;
  2135. }
  2136. const toCopy = src.subarray(0, dst.length);
  2137. dst.set(toCopy);
  2138. setInt64(sp + 40, toCopy.length);
  2139. this.mem.setUint8(sp + 48, 1);
  2140. },
  2141. // func copyBytesToJS(dst ref, src []byte) (int, bool)
  2142. "syscall/js.copyBytesToJS": (sp) => {
  2143. sp >>>= 0;
  2144. const dst = loadValue(sp + 8);
  2145. const src = loadSlice(sp + 16);
  2146. if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
  2147. this.mem.setUint8(sp + 48, 0);
  2148. return;
  2149. }
  2150. const toCopy = src.subarray(0, dst.length);
  2151. dst.set(toCopy);
  2152. setInt64(sp + 40, toCopy.length);
  2153. this.mem.setUint8(sp + 48, 1);
  2154. },
  2155. "debug": (value) => {
  2156. console.log(value);
  2157. }
  2158. }
  2159. };
  2160. }
  2161. run(instance) {
  2162. return __async(this, null, function* () {
  2163. if (!(instance instanceof WebAssembly.Instance)) {
  2164. throw new Error("Go.run: WebAssembly.Instance expected");
  2165. }
  2166. this._inst = instance;
  2167. this.mem = new DataView(this._inst.exports.mem.buffer);
  2168. this._values = [
  2169. // JS values that Go currently has references to, indexed by reference id
  2170. NaN,
  2171. 0,
  2172. null,
  2173. true,
  2174. false,
  2175. globalThis,
  2176. this
  2177. ];
  2178. this._goRefCounts = new Array(this._values.length).fill(Infinity);
  2179. this._ids = /* @__PURE__ */ new Map([
  2180. // mapping from JS values to reference ids
  2181. [0, 1],
  2182. [null, 2],
  2183. [true, 3],
  2184. [false, 4],
  2185. [globalThis, 5],
  2186. [this, 6]
  2187. ]);
  2188. this._idPool = [];
  2189. this.exited = false;
  2190. let offset = 4096;
  2191. const strPtr = (str) => {
  2192. const ptr = offset;
  2193. const bytes = encoder.encode(str + "\0");
  2194. new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
  2195. offset += bytes.length;
  2196. if (offset % 8 !== 0) {
  2197. offset += 8 - offset % 8;
  2198. }
  2199. return ptr;
  2200. };
  2201. const argc = this.argv.length;
  2202. const argvPtrs = [];
  2203. this.argv.forEach((arg) => {
  2204. argvPtrs.push(strPtr(arg));
  2205. });
  2206. argvPtrs.push(0);
  2207. const keys = Object.keys(this.env).sort();
  2208. keys.forEach((key) => {
  2209. argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
  2210. });
  2211. argvPtrs.push(0);
  2212. const argv = offset;
  2213. argvPtrs.forEach((ptr) => {
  2214. this.mem.setUint32(offset, ptr, true);
  2215. this.mem.setUint32(offset + 4, 0, true);
  2216. offset += 8;
  2217. });
  2218. const wasmMinDataAddr = 4096 + 8192;
  2219. if (offset >= wasmMinDataAddr) {
  2220. throw new Error("total length of command line and environment variables exceeds limit");
  2221. }
  2222. this._inst.exports.run(argc, argv);
  2223. if (this.exited) {
  2224. this._resolveExitPromise();
  2225. }
  2226. yield this._exitPromise;
  2227. });
  2228. }
  2229. _resume() {
  2230. if (this.exited) {
  2231. throw new Error("Go program has already exited");
  2232. }
  2233. this._inst.exports.resume();
  2234. if (this.exited) {
  2235. this._resolveExitPromise();
  2236. }
  2237. }
  2238. _makeFuncWrapper(id) {
  2239. const go = this;
  2240. return function() {
  2241. const event = { id, this: this, args: arguments };
  2242. go._pendingEvent = event;
  2243. go._resume();
  2244. return event.result;
  2245. };
  2246. }
  2247. };
  2248. })();
  2249. onmessage = ({ data: wasm }) => {
  2250. let decoder = new TextDecoder();
  2251. let fs = globalThis.fs;
  2252. let stderr = "";
  2253. fs.writeSync = (fd, buffer) => {
  2254. if (fd === 1) {
  2255. postMessage(buffer);
  2256. } else if (fd === 2) {
  2257. stderr += decoder.decode(buffer);
  2258. let parts = stderr.split("\n");
  2259. if (parts.length > 1) console.log(parts.slice(0, -1).join("\n"));
  2260. stderr = parts[parts.length - 1];
  2261. } else {
  2262. throw new Error("Bad write");
  2263. }
  2264. return buffer.length;
  2265. };
  2266. let stdin = [];
  2267. let resumeStdin;
  2268. let stdinPos = 0;
  2269. onmessage = ({ data }) => {
  2270. if (data.length > 0) {
  2271. stdin.push(data);
  2272. if (resumeStdin) resumeStdin();
  2273. }
  2274. return go;
  2275. };
  2276. fs.read = (fd, buffer, offset, length, position, callback) => {
  2277. if (fd !== 0 || offset !== 0 || length !== buffer.length || position !== null) {
  2278. throw new Error("Bad read");
  2279. }
  2280. if (stdin.length === 0) {
  2281. resumeStdin = () => fs.read(fd, buffer, offset, length, position, callback);
  2282. return;
  2283. }
  2284. let first = stdin[0];
  2285. let count = Math.max(0, Math.min(length, first.length - stdinPos));
  2286. buffer.set(first.subarray(stdinPos, stdinPos + count), offset);
  2287. stdinPos += count;
  2288. if (stdinPos === first.length) {
  2289. stdin.shift();
  2290. stdinPos = 0;
  2291. }
  2292. callback(null, count);
  2293. };
  2294. let go = new globalThis.Go();
  2295. go.argv = ["", `--service=${"0.25.1"}`];
  2296. tryToInstantiateModule(wasm, go).then(
  2297. (instance) => {
  2298. postMessage(null);
  2299. go.run(instance);
  2300. },
  2301. (error) => {
  2302. postMessage(error);
  2303. }
  2304. );
  2305. return go;
  2306. };
  2307. function tryToInstantiateModule(wasm, go) {
  2308. return __async(this, null, function* () {
  2309. if (wasm instanceof WebAssembly.Module) {
  2310. return WebAssembly.instantiate(wasm, go.importObject);
  2311. }
  2312. const res = yield fetch(wasm);
  2313. if (!res.ok) throw new Error(`Failed to download ${JSON.stringify(wasm)}`);
  2314. if ("instantiateStreaming" in WebAssembly && /^application\/wasm($|;)/i.test(res.headers.get("Content-Type") || "")) {
  2315. const result2 = yield WebAssembly.instantiateStreaming(res, go.importObject);
  2316. return result2.instance;
  2317. }
  2318. const bytes = yield res.arrayBuffer();
  2319. const result = yield WebAssembly.instantiate(bytes, go.importObject);
  2320. return result.instance;
  2321. });
  2322. }
  2323. return (m) => onmessage(m);
  2324. })((data) => worker.onmessage({ data }));
  2325. let go;
  2326. worker = {
  2327. onmessage: null,
  2328. postMessage: (data) => setTimeout(() => {
  2329. try {
  2330. go = onmessage({ data });
  2331. } catch (error) {
  2332. rejectAllWith(error);
  2333. }
  2334. }),
  2335. terminate() {
  2336. if (go)
  2337. for (let timeout of go._scheduledTimeouts.values())
  2338. clearTimeout(timeout);
  2339. }
  2340. };
  2341. }
  2342. let firstMessageResolve;
  2343. let firstMessageReject;
  2344. const firstMessagePromise = new Promise((resolve, reject) => {
  2345. firstMessageResolve = resolve;
  2346. firstMessageReject = reject;
  2347. });
  2348. worker.onmessage = ({ data: error }) => {
  2349. worker.onmessage = ({ data }) => readFromStdout(data);
  2350. if (error) firstMessageReject(error);
  2351. else firstMessageResolve();
  2352. };
  2353. worker.postMessage(wasmModule || new URL(wasmURL, location.href).toString());
  2354. let { readFromStdout, service } = createChannel({
  2355. writeToStdin(bytes) {
  2356. worker.postMessage(bytes);
  2357. },
  2358. isSync: false,
  2359. hasFS: false,
  2360. esbuild: browser_exports
  2361. });
  2362. yield firstMessagePromise;
  2363. stopService = () => {
  2364. worker.terminate();
  2365. initializePromise = void 0;
  2366. stopService = void 0;
  2367. longLivedService = void 0;
  2368. };
  2369. longLivedService = {
  2370. build: (options) => new Promise((resolve, reject) => {
  2371. rejectAllPromise.then(reject);
  2372. service.buildOrContext({
  2373. callName: "build",
  2374. refs: null,
  2375. options,
  2376. isTTY: false,
  2377. defaultWD: "/",
  2378. callback: (err, res) => err ? reject(err) : resolve(res)
  2379. });
  2380. }),
  2381. context: (options) => new Promise((resolve, reject) => {
  2382. rejectAllPromise.then(reject);
  2383. service.buildOrContext({
  2384. callName: "context",
  2385. refs: null,
  2386. options,
  2387. isTTY: false,
  2388. defaultWD: "/",
  2389. callback: (err, res) => err ? reject(err) : resolve(res)
  2390. });
  2391. }),
  2392. transform: (input, options) => new Promise((resolve, reject) => {
  2393. rejectAllPromise.then(reject);
  2394. service.transform({
  2395. callName: "transform",
  2396. refs: null,
  2397. input,
  2398. options: options || {},
  2399. isTTY: false,
  2400. fs: {
  2401. readFile(_, callback) {
  2402. callback(new Error("Internal error"), null);
  2403. },
  2404. writeFile(_, callback) {
  2405. callback(null);
  2406. }
  2407. },
  2408. callback: (err, res) => err ? reject(err) : resolve(res)
  2409. });
  2410. }),
  2411. formatMessages: (messages, options) => new Promise((resolve, reject) => {
  2412. rejectAllPromise.then(reject);
  2413. service.formatMessages({
  2414. callName: "formatMessages",
  2415. refs: null,
  2416. messages,
  2417. options,
  2418. callback: (err, res) => err ? reject(err) : resolve(res)
  2419. });
  2420. }),
  2421. analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => {
  2422. rejectAllPromise.then(reject);
  2423. service.analyzeMetafile({
  2424. callName: "analyzeMetafile",
  2425. refs: null,
  2426. metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
  2427. options,
  2428. callback: (err, res) => err ? reject(err) : resolve(res)
  2429. });
  2430. })
  2431. };
  2432. });
  2433. var browser_default = browser_exports;
  2434. })(typeof module==="object"?module:{set exports(x){(typeof self!=="undefined"?self:this).esbuild=x}});