isomorfeus-asset-manager 0.16.4 → 0.18.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -45,11 +45,11 @@ __export(browser_exports, {
45
45
  analyzeMetafileSync: () => analyzeMetafileSync,
46
46
  build: () => build,
47
47
  buildSync: () => buildSync,
48
+ context: () => context,
48
49
  default: () => browser_default,
49
50
  formatMessages: () => formatMessages,
50
51
  formatMessagesSync: () => formatMessagesSync,
51
52
  initialize: () => initialize,
52
- serve: () => serve,
53
53
  transform: () => transform,
54
54
  transformSync: () => transformSync,
55
55
  version: () => version
@@ -236,15 +236,14 @@ function validateTarget(target) {
236
236
  }
237
237
  var canBeAnything = () => null;
238
238
  var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
239
- var mustBeBooleanOrObject = (value) => typeof value === "boolean" || typeof value === "object" && !Array.isArray(value) ? null : "a boolean or an object";
240
239
  var mustBeString = (value) => typeof value === "string" ? null : "a string";
241
240
  var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
242
241
  var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
243
242
  var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
244
243
  var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
245
244
  var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
245
+ var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
246
246
  var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
247
- var mustBeArrayOrRecord = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
248
247
  var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
249
248
  var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
250
249
  var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
@@ -342,6 +341,7 @@ function pushCommonFlags(flags, options, keys) {
342
341
  let pure = getFlag(options, keys, "pure", mustBeArray);
343
342
  let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
344
343
  let platform = getFlag(options, keys, "platform", mustBeString);
344
+ let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
345
345
  if (legalComments)
346
346
  flags.push(`--legal-comments=${legalComments}`);
347
347
  if (sourceRoot !== void 0)
@@ -360,6 +360,8 @@ function pushCommonFlags(flags, options, keys) {
360
360
  flags.push(`--global-name=${globalName}`);
361
361
  if (platform)
362
362
  flags.push(`--platform=${platform}`);
363
+ if (tsconfigRaw)
364
+ flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
363
365
  if (minify)
364
366
  flags.push("--minify");
365
367
  if (minifySyntax)
@@ -432,12 +434,10 @@ function flagsForBuildOptions(callName, options, isTTY, logLevelDefault, writeDe
432
434
  let keys = /* @__PURE__ */ Object.create(null);
433
435
  let stdinContents = null;
434
436
  let stdinResolveDir = null;
435
- let watchMode = null;
436
437
  pushLogFlags(flags, options, keys, isTTY, logLevelDefault);
437
438
  pushCommonFlags(flags, options, keys);
438
439
  let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
439
440
  let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
440
- let watch = getFlag(options, keys, "watch", mustBeBooleanOrObject);
441
441
  let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
442
442
  let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
443
443
  let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
@@ -461,12 +461,11 @@ function flagsForBuildOptions(callName, options, isTTY, logLevelDefault, writeDe
461
461
  let inject = getFlag(options, keys, "inject", mustBeArray);
462
462
  let banner = getFlag(options, keys, "banner", mustBeObject);
463
463
  let footer = getFlag(options, keys, "footer", mustBeObject);
464
- let entryPoints = getFlag(options, keys, "entryPoints", mustBeArrayOrRecord);
464
+ let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints);
465
465
  let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
466
466
  let stdin = getFlag(options, keys, "stdin", mustBeObject);
467
467
  let write = (_a = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a : writeDefault;
468
468
  let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
469
- let incremental = getFlag(options, keys, "incremental", mustBeBoolean) === true;
470
469
  let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
471
470
  keys.plugins = true;
472
471
  checkForInvalidFlags(options, keys, `in ${callName}() call`);
@@ -476,17 +475,6 @@ function flagsForBuildOptions(callName, options, isTTY, logLevelDefault, writeDe
476
475
  flags.push("--bundle");
477
476
  if (allowOverwrite)
478
477
  flags.push("--allow-overwrite");
479
- if (watch) {
480
- flags.push("--watch");
481
- if (typeof watch === "boolean") {
482
- watchMode = {};
483
- } else {
484
- let watchKeys = /* @__PURE__ */ Object.create(null);
485
- let onRebuild = getFlag(watch, watchKeys, "onRebuild", mustBeFunction);
486
- checkForInvalidFlags(watch, watchKeys, `on "watch" in ${callName}() call`);
487
- watchMode = { onRebuild };
488
- }
489
- }
490
478
  if (splitting)
491
479
  flags.push("--splitting");
492
480
  if (preserveSymlinks)
@@ -584,8 +572,21 @@ function flagsForBuildOptions(callName, options, isTTY, logLevelDefault, writeDe
584
572
  }
585
573
  if (entryPoints) {
586
574
  if (Array.isArray(entryPoints)) {
587
- for (let entryPoint of entryPoints) {
588
- entries.push(["", validateStringValue(entryPoint, "entry point")]);
575
+ for (let i = 0, n = entryPoints.length; i < n; i++) {
576
+ let entryPoint = entryPoints[i];
577
+ if (typeof entryPoint === "object" && entryPoint !== null) {
578
+ let entryPointKeys = /* @__PURE__ */ Object.create(null);
579
+ let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
580
+ let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
581
+ checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
582
+ if (input === void 0)
583
+ throw new Error('Missing property "in" for entry point at index ' + i);
584
+ if (output === void 0)
585
+ throw new Error('Missing property "out" for entry point at index ' + i);
586
+ entries.push([output, input]);
587
+ } else {
588
+ entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
589
+ }
589
590
  }
590
591
  } else {
591
592
  for (let key in entryPoints) {
@@ -625,9 +626,7 @@ function flagsForBuildOptions(callName, options, isTTY, logLevelDefault, writeDe
625
626
  stdinContents,
626
627
  stdinResolveDir,
627
628
  absWorkingDir,
628
- incremental,
629
629
  nodePaths,
630
- watch: watchMode,
631
630
  mangleCache: validateMangleCache(mangleCache)
632
631
  };
633
632
  }
@@ -637,7 +636,6 @@ function flagsForTransformOptions(callName, options, isTTY, logLevelDefault) {
637
636
  pushLogFlags(flags, options, keys, isTTY, logLevelDefault);
638
637
  pushCommonFlags(flags, options, keys);
639
638
  let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
640
- let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
641
639
  let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
642
640
  let loader = getFlag(options, keys, "loader", mustBeString);
643
641
  let banner = getFlag(options, keys, "banner", mustBeString);
@@ -646,8 +644,6 @@ function flagsForTransformOptions(callName, options, isTTY, logLevelDefault) {
646
644
  checkForInvalidFlags(options, keys, `in ${callName}() call`);
647
645
  if (sourcemap)
648
646
  flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
649
- if (tsconfigRaw)
650
- flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
651
647
  if (sourcefile)
652
648
  flags.push(`--sourcefile=${sourcefile}`);
653
649
  if (loader)
@@ -750,8 +746,8 @@ function createChannel(streamIn) {
750
746
  if (isFirstPacket) {
751
747
  isFirstPacket = false;
752
748
  let binaryVersion = String.fromCharCode(...bytes);
753
- if (binaryVersion !== "0.16.17") {
754
- throw new Error(`Cannot start service: Host version "${"0.16.17"}" does not match binary version ${quote(binaryVersion)}`);
749
+ if (binaryVersion !== "0.18.4") {
750
+ throw new Error(`Cannot start service: Host version "${"0.18.4"}" does not match binary version ${quote(binaryVersion)}`);
755
751
  }
756
752
  return;
757
753
  }
@@ -767,7 +763,7 @@ function createChannel(streamIn) {
767
763
  callback(null, packet.value);
768
764
  }
769
765
  };
770
- let buildOrServe = ({ callName, refs, serveOptions, options, isTTY, defaultWD, callback }) => {
766
+ let buildOrContext = ({ callName, refs, options, isTTY, defaultWD, callback }) => {
771
767
  let refCount = 0;
772
768
  const buildKey = nextBuildKey++;
773
769
  const requestCallbacks = {};
@@ -788,7 +784,7 @@ function createChannel(streamIn) {
788
784
  };
789
785
  requestCallbacksByKey[buildKey] = requestCallbacks;
790
786
  buildRefs.ref();
791
- buildOrServeImpl(
787
+ buildOrContextImpl(
792
788
  callName,
793
789
  buildKey,
794
790
  sendRequest,
@@ -797,10 +793,8 @@ function createChannel(streamIn) {
797
793
  streamIn,
798
794
  requestCallbacks,
799
795
  options,
800
- serveOptions,
801
796
  isTTY,
802
797
  defaultWD,
803
- closeData,
804
798
  (err, res) => {
805
799
  try {
806
800
  callback(err, res);
@@ -836,7 +830,13 @@ function createChannel(streamIn) {
836
830
  let outstanding = 1;
837
831
  let next = () => {
838
832
  if (--outstanding === 0) {
839
- let result = { warnings, code: response.code, map: response.map };
833
+ let result = {
834
+ warnings,
835
+ code: response.code,
836
+ map: response.map,
837
+ mangleCache: void 0,
838
+ legalComments: void 0
839
+ };
840
840
  if ("legalComments" in response)
841
841
  result.legalComments = response == null ? void 0 : response.legalComments;
842
842
  if (response.mangleCache)
@@ -942,30 +942,26 @@ function createChannel(streamIn) {
942
942
  readFromStdout,
943
943
  afterClose,
944
944
  service: {
945
- buildOrServe,
945
+ buildOrContext,
946
946
  transform: transform2,
947
947
  formatMessages: formatMessages2,
948
948
  analyzeMetafile: analyzeMetafile2
949
949
  }
950
950
  };
951
951
  }
952
- function buildOrServeImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, serveOptions, isTTY, defaultWD, closeData, callback) {
952
+ function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY, defaultWD, callback) {
953
953
  const details = createObjectStash();
954
- const logPluginError = (e, pluginName, note, done) => {
954
+ const isContext = callName === "context";
955
+ const handleError = (e, pluginName) => {
955
956
  const flags = [];
956
957
  try {
957
958
  pushLogFlags(flags, options, {}, isTTY, buildLogLevelDefault);
958
959
  } catch (e2) {
959
960
  }
960
- const message = extractErrorMessageV8(e, streamIn, details, note, pluginName);
961
+ const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName);
961
962
  sendRequest(refs, { command: "error", flags, error: message }, () => {
962
963
  message.detail = details.load(message.detail);
963
- done(message);
964
- });
965
- };
966
- const handleError = (e, pluginName) => {
967
- logPluginError(e, pluginName, void 0, (error) => {
968
- callback(failureErrorWithLog("Build failed", [error], []), null);
964
+ callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
969
965
  });
970
966
  };
971
967
  let plugins;
@@ -973,15 +969,13 @@ function buildOrServeImpl(callName, buildKey, sendRequest, sendResponse, refs, s
973
969
  const value = options.plugins;
974
970
  if (value !== void 0) {
975
971
  if (!Array.isArray(value))
976
- throw new Error(`"plugins" must be an array`);
972
+ return handleError(new Error(`"plugins" must be an array`), "");
977
973
  plugins = value;
978
974
  }
979
975
  }
980
976
  if (plugins && plugins.length > 0) {
981
- if (streamIn.isSync) {
982
- handleError(new Error("Cannot use plugins in synchronous API calls"), "");
983
- return;
984
- }
977
+ if (streamIn.isSync)
978
+ return handleError(new Error("Cannot use plugins in synchronous API calls"), "");
985
979
  handlePlugins(
986
980
  buildKey,
987
981
  sendRequest,
@@ -994,12 +988,10 @@ function buildOrServeImpl(callName, buildKey, sendRequest, sendResponse, refs, s
994
988
  details
995
989
  ).then(
996
990
  (result) => {
997
- if (!result.ok) {
998
- handleError(result.error, result.pluginName);
999
- return;
1000
- }
991
+ if (!result.ok)
992
+ return handleError(result.error, result.pluginName);
1001
993
  try {
1002
- buildOrServeContinue(result.requestPlugins, result.runOnEndCallbacks);
994
+ buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
1003
995
  } catch (e) {
1004
996
  handleError(e, "");
1005
997
  }
@@ -1009,25 +1001,26 @@ function buildOrServeImpl(callName, buildKey, sendRequest, sendResponse, refs, s
1009
1001
  return;
1010
1002
  }
1011
1003
  try {
1012
- buildOrServeContinue(null, (result, logPluginError2, done) => done());
1004
+ buildOrContextContinue(null, (result, done) => done([], []), () => {
1005
+ });
1013
1006
  } catch (e) {
1014
1007
  handleError(e, "");
1015
1008
  }
1016
- function buildOrServeContinue(requestPlugins, runOnEndCallbacks) {
1017
- let writeDefault = !streamIn.isWriteUnavailable;
1018
- let {
1009
+ function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
1010
+ const writeDefault = streamIn.hasFS;
1011
+ const {
1019
1012
  entries,
1020
1013
  flags,
1021
1014
  write,
1022
1015
  stdinContents,
1023
1016
  stdinResolveDir,
1024
1017
  absWorkingDir,
1025
- incremental,
1026
1018
  nodePaths,
1027
- watch,
1028
1019
  mangleCache
1029
1020
  } = flagsForBuildOptions(callName, options, isTTY, buildLogLevelDefault, writeDefault);
1030
- let request = {
1021
+ if (write && !streamIn.hasFS)
1022
+ throw new Error(`The "write" option is unavailable in this environment`);
1023
+ const request = {
1031
1024
  command: "build",
1032
1025
  key: buildKey,
1033
1026
  entries,
@@ -1036,17 +1029,23 @@ function buildOrServeImpl(callName, buildKey, sendRequest, sendResponse, refs, s
1036
1029
  stdinContents,
1037
1030
  stdinResolveDir,
1038
1031
  absWorkingDir: absWorkingDir || defaultWD,
1039
- incremental,
1040
- nodePaths
1032
+ nodePaths,
1033
+ context: isContext
1041
1034
  };
1042
1035
  if (requestPlugins)
1043
1036
  request.plugins = requestPlugins;
1044
1037
  if (mangleCache)
1045
1038
  request.mangleCache = mangleCache;
1046
- let serve2 = serveOptions && buildServeData(buildKey, sendRequest, sendResponse, refs, requestCallbacks, serveOptions, request);
1047
- let rebuild;
1048
- let stop;
1049
- let copyResponseToResult = (response, result) => {
1039
+ const buildResponseToResult = (response, callback2) => {
1040
+ const result = {
1041
+ errors: replaceDetailsInMessages(response.errors, details),
1042
+ warnings: replaceDetailsInMessages(response.warnings, details),
1043
+ outputFiles: void 0,
1044
+ metafile: void 0,
1045
+ mangleCache: void 0
1046
+ };
1047
+ const originalErrors = result.errors.slice();
1048
+ const originalWarnings = result.warnings.slice();
1050
1049
  if (response.outputFiles)
1051
1050
  result.outputFiles = response.outputFiles.map(convertOutputFiles);
1052
1051
  if (response.metafile)
@@ -1055,170 +1054,163 @@ function buildOrServeImpl(callName, buildKey, sendRequest, sendResponse, refs, s
1055
1054
  result.mangleCache = response.mangleCache;
1056
1055
  if (response.writeToStdout !== void 0)
1057
1056
  console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
1058
- };
1059
- let buildResponseToResult = (response, callback2) => {
1060
- let result = {
1061
- errors: replaceDetailsInMessages(response.errors, details),
1062
- warnings: replaceDetailsInMessages(response.warnings, details)
1063
- };
1064
- copyResponseToResult(response, result);
1065
- runOnEndCallbacks(result, logPluginError, () => {
1066
- if (result.errors.length > 0) {
1067
- return callback2(failureErrorWithLog("Build failed", result.errors, result.warnings), null);
1057
+ runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
1058
+ if (originalErrors.length > 0 || onEndErrors.length > 0) {
1059
+ const error = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings));
1060
+ return callback2(error, null, onEndErrors, onEndWarnings);
1068
1061
  }
1069
- if (response.rebuild) {
1070
- if (!rebuild) {
1071
- let isDisposed = false;
1072
- rebuild = () => new Promise((resolve, reject) => {
1073
- if (isDisposed || closeData.didClose)
1074
- throw new Error("Cannot rebuild");
1075
- sendRequest(
1076
- refs,
1077
- { command: "rebuild", key: buildKey },
1078
- (error2, response2) => {
1062
+ callback2(null, result, onEndErrors, onEndWarnings);
1063
+ });
1064
+ };
1065
+ let latestResultPromise;
1066
+ let provideLatestResult;
1067
+ if (isContext)
1068
+ requestCallbacks["on-end"] = (id, request2) => new Promise((resolve) => {
1069
+ buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => {
1070
+ const response = {
1071
+ errors: onEndErrors,
1072
+ warnings: onEndWarnings
1073
+ };
1074
+ if (provideLatestResult)
1075
+ provideLatestResult(err, result);
1076
+ latestResultPromise = void 0;
1077
+ provideLatestResult = void 0;
1078
+ sendResponse(id, response);
1079
+ resolve();
1080
+ });
1081
+ });
1082
+ sendRequest(refs, request, (error, response) => {
1083
+ if (error)
1084
+ return callback(new Error(error), null);
1085
+ if (!isContext) {
1086
+ return buildResponseToResult(response, (err, res) => {
1087
+ scheduleOnDisposeCallbacks();
1088
+ return callback(err, res);
1089
+ });
1090
+ }
1091
+ if (response.errors.length > 0) {
1092
+ return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
1093
+ }
1094
+ let didDispose = false;
1095
+ const result = {
1096
+ rebuild: () => {
1097
+ if (!latestResultPromise)
1098
+ latestResultPromise = new Promise((resolve, reject) => {
1099
+ let settlePromise;
1100
+ provideLatestResult = (err, result2) => {
1101
+ if (!settlePromise)
1102
+ settlePromise = () => err ? reject(err) : resolve(result2);
1103
+ };
1104
+ const triggerAnotherBuild = () => {
1105
+ const request2 = {
1106
+ command: "rebuild",
1107
+ key: buildKey
1108
+ };
1109
+ sendRequest(refs, request2, (error2, response2) => {
1079
1110
  if (error2) {
1080
- const message = { id: "", pluginName: "", text: error2, location: null, notes: [], detail: void 0 };
1081
- return callback2(failureErrorWithLog("Build failed", [message], []), null);
1111
+ reject(new Error(error2));
1112
+ } else if (settlePromise) {
1113
+ settlePromise();
1114
+ } else {
1115
+ triggerAnotherBuild();
1082
1116
  }
1083
- buildResponseToResult(response2, (error3, result3) => {
1084
- if (error3)
1085
- reject(error3);
1086
- else
1087
- resolve(result3);
1088
- });
1089
- }
1090
- );
1117
+ });
1118
+ };
1119
+ triggerAnotherBuild();
1091
1120
  });
1092
- refs.ref();
1093
- rebuild.dispose = () => {
1094
- if (isDisposed)
1095
- return;
1096
- isDisposed = true;
1097
- sendRequest(refs, { command: "rebuild-dispose", key: buildKey }, () => {
1098
- });
1099
- refs.unref();
1100
- };
1101
- }
1102
- result.rebuild = rebuild;
1103
- }
1104
- if (response.watch) {
1105
- if (!stop) {
1106
- let isStopped = false;
1107
- refs.ref();
1108
- stop = () => {
1109
- if (isStopped)
1110
- return;
1111
- isStopped = true;
1112
- delete requestCallbacks["watch-rebuild"];
1113
- sendRequest(refs, { command: "watch-stop", key: buildKey }, () => {
1114
- });
1115
- refs.unref();
1116
- };
1117
- if (watch) {
1118
- requestCallbacks["watch-rebuild"] = (id, request2) => {
1119
- try {
1120
- let watchResponse = request2.args;
1121
- let result2 = {
1122
- errors: replaceDetailsInMessages(watchResponse.errors, details),
1123
- warnings: replaceDetailsInMessages(watchResponse.warnings, details)
1124
- };
1125
- copyResponseToResult(watchResponse, result2);
1126
- runOnEndCallbacks(result2, logPluginError, () => {
1127
- if (result2.errors.length > 0) {
1128
- if (watch.onRebuild)
1129
- watch.onRebuild(failureErrorWithLog("Build failed", result2.errors, result2.warnings), null);
1130
- return;
1131
- }
1132
- result2.stop = stop;
1133
- if (watch.onRebuild)
1134
- watch.onRebuild(null, result2);
1135
- });
1136
- } catch (err) {
1137
- console.error(err);
1138
- }
1121
+ return latestResultPromise;
1122
+ },
1123
+ watch: (options2 = {}) => new Promise((resolve, reject) => {
1124
+ if (!streamIn.hasFS)
1125
+ throw new Error(`Cannot use the "watch" API in this environment`);
1126
+ const keys = {};
1127
+ checkForInvalidFlags(options2, keys, `in watch() call`);
1128
+ const request2 = {
1129
+ command: "watch",
1130
+ key: buildKey
1131
+ };
1132
+ sendRequest(refs, request2, (error2) => {
1133
+ if (error2)
1134
+ reject(new Error(error2));
1135
+ else
1136
+ resolve(void 0);
1137
+ });
1138
+ }),
1139
+ serve: (options2 = {}) => new Promise((resolve, reject) => {
1140
+ if (!streamIn.hasFS)
1141
+ throw new Error(`Cannot use the "serve" API in this environment`);
1142
+ const keys = {};
1143
+ const port = getFlag(options2, keys, "port", mustBeInteger);
1144
+ const host = getFlag(options2, keys, "host", mustBeString);
1145
+ const servedir = getFlag(options2, keys, "servedir", mustBeString);
1146
+ const keyfile = getFlag(options2, keys, "keyfile", mustBeString);
1147
+ const certfile = getFlag(options2, keys, "certfile", mustBeString);
1148
+ const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction);
1149
+ checkForInvalidFlags(options2, keys, `in serve() call`);
1150
+ const request2 = {
1151
+ command: "serve",
1152
+ key: buildKey,
1153
+ onRequest: !!onRequest
1154
+ };
1155
+ if (port !== void 0)
1156
+ request2.port = port;
1157
+ if (host !== void 0)
1158
+ request2.host = host;
1159
+ if (servedir !== void 0)
1160
+ request2.servedir = servedir;
1161
+ if (keyfile !== void 0)
1162
+ request2.keyfile = keyfile;
1163
+ if (certfile !== void 0)
1164
+ request2.certfile = certfile;
1165
+ sendRequest(refs, request2, (error2, response2) => {
1166
+ if (error2)
1167
+ return reject(new Error(error2));
1168
+ if (onRequest) {
1169
+ requestCallbacks["serve-request"] = (id, request3) => {
1170
+ onRequest(request3.args);
1139
1171
  sendResponse(id, {});
1140
1172
  };
1141
1173
  }
1142
- }
1143
- result.stop = stop;
1144
- }
1145
- callback2(null, result);
1146
- });
1147
- };
1148
- if (write && streamIn.isWriteUnavailable)
1149
- throw new Error(`The "write" option is unavailable in this environment`);
1150
- if (incremental && streamIn.isSync)
1151
- throw new Error(`Cannot use "incremental" with a synchronous build`);
1152
- if (watch && streamIn.isSync)
1153
- throw new Error(`Cannot use "watch" with a synchronous build`);
1154
- sendRequest(refs, request, (error, response) => {
1155
- if (error)
1156
- return callback(new Error(error), null);
1157
- if (serve2) {
1158
- let serveResponse = response;
1159
- let isStopped = false;
1160
- refs.ref();
1161
- let result = {
1162
- port: serveResponse.port,
1163
- host: serveResponse.host,
1164
- wait: serve2.wait,
1165
- stop() {
1166
- if (isStopped)
1167
- return;
1168
- isStopped = true;
1169
- serve2.stop();
1174
+ resolve(response2);
1175
+ });
1176
+ }),
1177
+ cancel: () => new Promise((resolve) => {
1178
+ if (didDispose)
1179
+ return resolve();
1180
+ const request2 = {
1181
+ command: "cancel",
1182
+ key: buildKey
1183
+ };
1184
+ sendRequest(refs, request2, () => {
1185
+ resolve();
1186
+ });
1187
+ }),
1188
+ dispose: () => new Promise((resolve) => {
1189
+ if (didDispose)
1190
+ return resolve();
1191
+ didDispose = true;
1192
+ const request2 = {
1193
+ command: "dispose",
1194
+ key: buildKey
1195
+ };
1196
+ sendRequest(refs, request2, () => {
1197
+ resolve();
1198
+ scheduleOnDisposeCallbacks();
1170
1199
  refs.unref();
1171
- }
1172
- };
1173
- refs.ref();
1174
- serve2.wait.then(refs.unref, refs.unref);
1175
- return callback(null, result);
1176
- }
1177
- return buildResponseToResult(response, callback);
1200
+ });
1201
+ })
1202
+ };
1203
+ refs.ref();
1204
+ callback(null, result);
1178
1205
  });
1179
1206
  }
1180
1207
  }
1181
- var buildServeData = (buildKey, sendRequest, sendResponse, refs, requestCallbacks, options, request) => {
1182
- let keys = {};
1183
- let port = getFlag(options, keys, "port", mustBeInteger);
1184
- let host = getFlag(options, keys, "host", mustBeString);
1185
- let servedir = getFlag(options, keys, "servedir", mustBeString);
1186
- let onRequest = getFlag(options, keys, "onRequest", mustBeFunction);
1187
- let wait = new Promise((resolve, reject) => {
1188
- requestCallbacks["serve-wait"] = (id, request2) => {
1189
- if (request2.error !== null)
1190
- reject(new Error(request2.error));
1191
- else
1192
- resolve();
1193
- sendResponse(id, {});
1194
- };
1195
- });
1196
- request.serve = {};
1197
- checkForInvalidFlags(options, keys, `in serve() call`);
1198
- if (port !== void 0)
1199
- request.serve.port = port;
1200
- if (host !== void 0)
1201
- request.serve.host = host;
1202
- if (servedir !== void 0)
1203
- request.serve.servedir = servedir;
1204
- requestCallbacks["serve-request"] = (id, request2) => {
1205
- if (onRequest)
1206
- onRequest(request2.args);
1207
- sendResponse(id, {});
1208
- };
1209
- return {
1210
- wait,
1211
- stop() {
1212
- sendRequest(refs, { command: "serve-stop", key: buildKey }, () => {
1213
- });
1214
- }
1215
- };
1216
- };
1217
1208
  var handlePlugins = (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => __async(void 0, null, function* () {
1218
1209
  let onStartCallbacks = [];
1219
1210
  let onEndCallbacks = [];
1220
1211
  let onResolveCallbacks = {};
1221
1212
  let onLoadCallbacks = {};
1213
+ let onDisposeCallbacks = [];
1222
1214
  let nextCallbackID = 0;
1223
1215
  let i = 0;
1224
1216
  let requestPlugins = [];
@@ -1336,6 +1328,9 @@ var handlePlugins = (buildKey, sendRequest, sendResponse, refs, streamIn, reques
1336
1328
  onLoadCallbacks[id] = { name, callback, note: registeredNote };
1337
1329
  plugin.onLoad.push({ id, filter: filter.source, namespace: namespace || "" });
1338
1330
  },
1331
+ onDispose(callback) {
1332
+ onDisposeCallbacks.push(callback);
1333
+ },
1339
1334
  esbuild: streamIn.esbuild
1340
1335
  });
1341
1336
  if (promise)
@@ -1484,25 +1479,62 @@ var handlePlugins = (buildKey, sendRequest, sendResponse, refs, streamIn, reques
1484
1479
  }
1485
1480
  sendResponse(id, response);
1486
1481
  });
1487
- let runOnEndCallbacks = (result, logPluginError, done) => done();
1482
+ let runOnEndCallbacks = (result, done) => done([], []);
1488
1483
  if (onEndCallbacks.length > 0) {
1489
- runOnEndCallbacks = (result, logPluginError, done) => {
1484
+ runOnEndCallbacks = (result, done) => {
1490
1485
  (() => __async(void 0, null, function* () {
1486
+ const onEndErrors = [];
1487
+ const onEndWarnings = [];
1491
1488
  for (const { name, callback, note } of onEndCallbacks) {
1489
+ let newErrors;
1490
+ let newWarnings;
1492
1491
  try {
1493
- yield callback(result);
1492
+ const value = yield callback(result);
1493
+ if (value != null) {
1494
+ if (typeof value !== "object")
1495
+ throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
1496
+ let keys = {};
1497
+ let errors = getFlag(value, keys, "errors", mustBeArray);
1498
+ let warnings = getFlag(value, keys, "warnings", mustBeArray);
1499
+ checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
1500
+ if (errors != null)
1501
+ newErrors = sanitizeMessages(errors, "errors", details, name);
1502
+ if (warnings != null)
1503
+ newWarnings = sanitizeMessages(warnings, "warnings", details, name);
1504
+ }
1494
1505
  } catch (e) {
1495
- result.errors.push(yield new Promise((resolve) => logPluginError(e, name, note && note(), resolve)));
1506
+ newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
1507
+ }
1508
+ if (newErrors) {
1509
+ onEndErrors.push(...newErrors);
1510
+ try {
1511
+ result.errors.push(...newErrors);
1512
+ } catch (e) {
1513
+ }
1514
+ }
1515
+ if (newWarnings) {
1516
+ onEndWarnings.push(...newWarnings);
1517
+ try {
1518
+ result.warnings.push(...newWarnings);
1519
+ } catch (e) {
1520
+ }
1496
1521
  }
1497
1522
  }
1498
- }))().then(done);
1523
+ done(onEndErrors, onEndWarnings);
1524
+ }))();
1499
1525
  };
1500
1526
  }
1527
+ let scheduleOnDisposeCallbacks = () => {
1528
+ for (const cb of onDisposeCallbacks) {
1529
+ setTimeout(() => cb(), 0);
1530
+ }
1531
+ };
1501
1532
  isSetupDone = true;
1502
1533
  return {
1503
1534
  ok: true,
1504
1535
  requestPlugins,
1505
- runOnEndCallbacks
1536
+ runOnEndCallbacks,
1537
+ scheduleOnDisposeCallbacks
1506
1538
  };
1507
1539
  });
1508
1540
  function createObjectStash() {
@@ -1709,11 +1741,9 @@ function convertOutputFiles({ path, contents }) {
1709
1741
  }
1710
1742
 
1711
1743
  // lib/npm/browser.ts
1712
- var version = "0.16.17";
1744
+ var version = "0.18.4";
1713
1745
  var build = (options) => ensureServiceIsRunning().build(options);
1714
- var serve = () => {
1715
- throw new Error(`The "serve" API only works in node`);
1716
- };
1746
+ var context = (options) => ensureServiceIsRunning().context(options);
1717
1747
  var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
1718
1748
  var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
1719
1749
  var analyzeMetafile = (metafile, options) => ensureServiceIsRunning().analyzeMetafile(metafile, options);
@@ -1756,7 +1786,7 @@ var initialize = (options) => {
1756
1786
  var startRunningService = (wasmURL, wasmModule, useWorker) => __async(void 0, null, function* () {
1757
1787
  let worker;
1758
1788
  if (useWorker) {
1759
- 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.substr(0, nl));\n outputBuf = outputBuf.substr(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 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 go: {\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 = 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) + 1\n // setTimeout has been seen to fire up to 1 millisecond early\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)\n 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)\n resumeStdin();\n }\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.16.17"}`];\n tryToInstantiateModule(wasm, go).then(\n (instance) => {\n postMessage(null);\n go.run(instance);\n },\n (error) => {\n postMessage(error);\n }\n );\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)\n 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" });
1789
+ 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 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 go: {\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) + 1\n // setTimeout has been seen to fire up to 1 millisecond early\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)\n 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)\n resumeStdin();\n }\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.18.4"}`];\n tryToInstantiateModule(wasm, go).then(\n (instance) => {\n postMessage(null);\n go.run(instance);\n },\n (error) => {\n postMessage(error);\n }\n );\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)\n 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" });
1760
1790
  worker = new Worker(URL.createObjectURL(blob));
1761
1791
  } else {
1762
1792
  let onmessage = ((postMessage) => {
@@ -1805,8 +1835,8 @@ var startRunningService = (wasmURL, wasmModule, useWorker) => __async(void 0, nu
1805
1835
  outputBuf += decoder.decode(buf);
1806
1836
  const nl = outputBuf.lastIndexOf("\n");
1807
1837
  if (nl != -1) {
1808
- console.log(outputBuf.substr(0, nl));
1809
- outputBuf = outputBuf.substr(nl + 1);
1838
+ console.log(outputBuf.substring(0, nl));
1839
+ outputBuf = outputBuf.substring(nl + 1);
1810
1840
  }
1811
1841
  return buf.length;
1812
1842
  },
@@ -2073,7 +2103,7 @@ var startRunningService = (wasmURL, wasmModule, useWorker) => __async(void 0, nu
2073
2103
  // func walltime() (sec int64, nsec int32)
2074
2104
  "runtime.walltime": (sp) => {
2075
2105
  sp >>>= 0;
2076
- const msec = new Date().getTime();
2106
+ const msec = (/* @__PURE__ */ new Date()).getTime();
2077
2107
  setInt64(sp + 8, msec / 1e3);
2078
2108
  this.mem.setInt32(sp + 16, msec % 1e3 * 1e6, true);
2079
2109
  },
@@ -2392,7 +2422,7 @@ var startRunningService = (wasmURL, wasmModule, useWorker) => __async(void 0, nu
2392
2422
  callback(null, count);
2393
2423
  };
2394
2424
  let go = new globalThis.Go();
2395
- go.argv = ["", `--service=${"0.16.17"}`];
2425
+ go.argv = ["", `--service=${"0.18.4"}`];
2396
2426
  tryToInstantiateModule(wasm, go).then(
2397
2427
  (instance) => {
2398
2428
  postMessage(null);
@@ -2448,15 +2478,22 @@ var startRunningService = (wasmURL, wasmModule, useWorker) => __async(void 0, nu
2448
2478
  worker.postMessage(bytes);
2449
2479
  },
2450
2480
  isSync: false,
2451
- isWriteUnavailable: true,
2481
+ hasFS: false,
2452
2482
  esbuild: browser_exports
2453
2483
  });
2454
2484
  yield firstMessagePromise;
2455
2485
  longLivedService = {
2456
- build: (options) => new Promise((resolve, reject) => service.buildOrServe({
2486
+ build: (options) => new Promise((resolve, reject) => service.buildOrContext({
2457
2487
  callName: "build",
2458
2488
  refs: null,
2459
- serveOptions: null,
2489
+ options,
2490
+ isTTY: false,
2491
+ defaultWD: "/",
2492
+ callback: (err, res) => err ? reject(err) : resolve(res)
2493
+ })),
2494
+ context: (options) => new Promise((resolve, reject) => service.buildOrContext({
2495
+ callName: "context",
2496
+ refs: null,
2460
2497
  options,
2461
2498
  isTTY: false,
2462
2499
  defaultWD: "/",