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