@dura-run/cli 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/dura.js CHANGED
@@ -2425,7 +2425,7 @@ async function openBrowser(url) {
2425
2425
  child.unref();
2426
2426
  }
2427
2427
  function registerLoginCommand(program2) {
2428
- program2.command("login").description("Authenticate with the Dura control plane").option("--api-key <key>", "Authenticate using an API key").option("--api-url <url>", "Set the API base URL").action(async (opts, cmd) => {
2428
+ program2.command("login").description("Authenticate with the dura control plane").option("--api-key <key>", "Authenticate using an API key").option("--api-url <url>", "Set the API base URL").action(async (opts, cmd) => {
2429
2429
  const output = getOutput(cmd);
2430
2430
  if (opts.apiKey) {
2431
2431
  const updates = { apiKey: opts.apiKey };
@@ -2677,7 +2677,7 @@ __export(exports_logout, {
2677
2677
  registerLogoutCommand: () => registerLogoutCommand
2678
2678
  });
2679
2679
  function registerLogoutCommand(program2) {
2680
- program2.command("logout").description("Log out from the Dura control plane").option("--revoke", "Also revoke the API key on the server").option("--api-url <url>", "API base URL override").action(async (opts, cmd) => {
2680
+ program2.command("logout").description("Log out from the dura control plane").option("--revoke", "Also revoke the API key on the server").option("--api-url <url>", "API base URL override").action(async (opts, cmd) => {
2681
2681
  const output = getOutput(cmd);
2682
2682
  const token = getAuthToken();
2683
2683
  if (!token) {
@@ -2783,7 +2783,7 @@ __export(exports_new, {
2783
2783
  import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
2784
2784
  import { join as join2, resolve } from "node:path";
2785
2785
  function registerNewCommand(program2) {
2786
- program2.command("new <name>").description("Scaffold a new Dura project").option("--dir <path>", "Parent directory (defaults to current dir)").option("--org <id>", "Organization ID for API registration").option("--template <slug>", "Fork a template as the starting point").option("--trigger <kind>", "Default trigger kind for the scaffold: get | post | cron", "get").action(async (name, opts, cmd) => {
2786
+ program2.command("new <name>").description("Scaffold a new dura project").option("--dir <path>", "Parent directory (defaults to current dir)").option("--org <id>", "Organization ID for API registration").option("--template <slug>", "Fork a template as the starting point").option("--trigger <kind>", "Default trigger kind for the scaffold: get | post | cron", "get").action(async (name, opts, cmd) => {
2787
2787
  const output = getOutput(cmd);
2788
2788
  if (!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name)) {
2789
2789
  output.error("INVALID_NAME", "Project name must start with a letter and contain only letters, numbers, hyphens, and underscores");
@@ -2869,7 +2869,7 @@ Set required secrets: ${result.requiredSecrets.join(", ")}`);
2869
2869
  output.info("No org specified. Run dura login and set a default org to register projects.");
2870
2870
  }
2871
2871
  } else {
2872
- output.info("Run dura login to register your project with the Dura control plane.");
2872
+ output.info("Run dura login to register your project with the dura control plane.");
2873
2873
  }
2874
2874
  output.success({
2875
2875
  created: true,
@@ -13846,2648 +13846,6 @@ var init_audit = __esm(() => {
13846
13846
  init_config_store();
13847
13847
  });
13848
13848
 
13849
- // ../../node_modules/.bun/esbuild@0.28.0/node_modules/esbuild/lib/main.js
13850
- var require_main = __commonJS((exports, module) => {
13851
- var __dirname = "/Users/gldc/Developer/dura-run/node_modules/.bun/esbuild@0.28.0/node_modules/esbuild/lib", __filename = "/Users/gldc/Developer/dura-run/node_modules/.bun/esbuild@0.28.0/node_modules/esbuild/lib/main.js";
13852
- var __defProp2 = Object.defineProperty;
13853
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13854
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
13855
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
13856
- var __export2 = (target, all) => {
13857
- for (var name in all)
13858
- __defProp2(target, name, { get: all[name], enumerable: true });
13859
- };
13860
- var __copyProps = (to, from, except2, desc) => {
13861
- if (from && typeof from === "object" || typeof from === "function") {
13862
- for (let key of __getOwnPropNames2(from))
13863
- if (!__hasOwnProp2.call(to, key) && key !== except2)
13864
- __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13865
- }
13866
- return to;
13867
- };
13868
- var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
13869
- var node_exports = {};
13870
- __export2(node_exports, {
13871
- analyzeMetafile: () => analyzeMetafile,
13872
- analyzeMetafileSync: () => analyzeMetafileSync,
13873
- build: () => build,
13874
- buildSync: () => buildSync,
13875
- context: () => context,
13876
- default: () => node_default,
13877
- formatMessages: () => formatMessages,
13878
- formatMessagesSync: () => formatMessagesSync,
13879
- initialize: () => initialize,
13880
- stop: () => stop,
13881
- transform: () => transform,
13882
- transformSync: () => transformSync,
13883
- version: () => version2
13884
- });
13885
- module.exports = __toCommonJS(node_exports);
13886
- function encodePacket(packet) {
13887
- let visit = (value) => {
13888
- if (value === null) {
13889
- bb.write8(0);
13890
- } else if (typeof value === "boolean") {
13891
- bb.write8(1);
13892
- bb.write8(+value);
13893
- } else if (typeof value === "number") {
13894
- bb.write8(2);
13895
- bb.write32(value | 0);
13896
- } else if (typeof value === "string") {
13897
- bb.write8(3);
13898
- bb.write(encodeUTF8(value));
13899
- } else if (value instanceof Uint8Array) {
13900
- bb.write8(4);
13901
- bb.write(value);
13902
- } else if (value instanceof Array) {
13903
- bb.write8(5);
13904
- bb.write32(value.length);
13905
- for (let item of value) {
13906
- visit(item);
13907
- }
13908
- } else {
13909
- let keys = Object.keys(value);
13910
- bb.write8(6);
13911
- bb.write32(keys.length);
13912
- for (let key of keys) {
13913
- bb.write(encodeUTF8(key));
13914
- visit(value[key]);
13915
- }
13916
- }
13917
- };
13918
- let bb = new ByteBuffer;
13919
- bb.write32(0);
13920
- bb.write32(packet.id << 1 | +!packet.isRequest);
13921
- visit(packet.value);
13922
- writeUInt32LE(bb.buf, bb.len - 4, 0);
13923
- return bb.buf.subarray(0, bb.len);
13924
- }
13925
- function decodePacket(bytes) {
13926
- let visit = () => {
13927
- switch (bb.read8()) {
13928
- case 0:
13929
- return null;
13930
- case 1:
13931
- return !!bb.read8();
13932
- case 2:
13933
- return bb.read32();
13934
- case 3:
13935
- return decodeUTF8(bb.read());
13936
- case 4:
13937
- return bb.read();
13938
- case 5: {
13939
- let count = bb.read32();
13940
- let value2 = [];
13941
- for (let i = 0;i < count; i++) {
13942
- value2.push(visit());
13943
- }
13944
- return value2;
13945
- }
13946
- case 6: {
13947
- let count = bb.read32();
13948
- let value2 = {};
13949
- for (let i = 0;i < count; i++) {
13950
- value2[decodeUTF8(bb.read())] = visit();
13951
- }
13952
- return value2;
13953
- }
13954
- default:
13955
- throw new Error("Invalid packet");
13956
- }
13957
- };
13958
- let bb = new ByteBuffer(bytes);
13959
- let id = bb.read32();
13960
- let isRequest = (id & 1) === 0;
13961
- id >>>= 1;
13962
- let value = visit();
13963
- if (bb.ptr !== bytes.length) {
13964
- throw new Error("Invalid packet");
13965
- }
13966
- return { id, isRequest, value };
13967
- }
13968
- var ByteBuffer = class {
13969
- constructor(buf = new Uint8Array(1024)) {
13970
- this.buf = buf;
13971
- this.len = 0;
13972
- this.ptr = 0;
13973
- }
13974
- _write(delta) {
13975
- if (this.len + delta > this.buf.length) {
13976
- let clone = new Uint8Array((this.len + delta) * 2);
13977
- clone.set(this.buf);
13978
- this.buf = clone;
13979
- }
13980
- this.len += delta;
13981
- return this.len - delta;
13982
- }
13983
- write8(value) {
13984
- let offset = this._write(1);
13985
- this.buf[offset] = value;
13986
- }
13987
- write32(value) {
13988
- let offset = this._write(4);
13989
- writeUInt32LE(this.buf, value, offset);
13990
- }
13991
- write(bytes) {
13992
- let offset = this._write(4 + bytes.length);
13993
- writeUInt32LE(this.buf, bytes.length, offset);
13994
- this.buf.set(bytes, offset + 4);
13995
- }
13996
- _read(delta) {
13997
- if (this.ptr + delta > this.buf.length) {
13998
- throw new Error("Invalid packet");
13999
- }
14000
- this.ptr += delta;
14001
- return this.ptr - delta;
14002
- }
14003
- read8() {
14004
- return this.buf[this._read(1)];
14005
- }
14006
- read32() {
14007
- return readUInt32LE(this.buf, this._read(4));
14008
- }
14009
- read() {
14010
- let length = this.read32();
14011
- let bytes = new Uint8Array(length);
14012
- let ptr = this._read(bytes.length);
14013
- bytes.set(this.buf.subarray(ptr, ptr + length));
14014
- return bytes;
14015
- }
14016
- };
14017
- var encodeUTF8;
14018
- var decodeUTF8;
14019
- var encodeInvariant;
14020
- if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
14021
- let encoder = new TextEncoder;
14022
- let decoder = new TextDecoder;
14023
- encodeUTF8 = (text3) => encoder.encode(text3);
14024
- decodeUTF8 = (bytes) => decoder.decode(bytes);
14025
- encodeInvariant = 'new TextEncoder().encode("")';
14026
- } else if (typeof Buffer !== "undefined") {
14027
- encodeUTF8 = (text3) => Buffer.from(text3);
14028
- decodeUTF8 = (bytes) => {
14029
- let { buffer: buffer2, byteOffset, byteLength } = bytes;
14030
- return Buffer.from(buffer2, byteOffset, byteLength).toString();
14031
- };
14032
- encodeInvariant = 'Buffer.from("")';
14033
- } else {
14034
- throw new Error("No UTF-8 codec found");
14035
- }
14036
- if (!(encodeUTF8("") instanceof Uint8Array))
14037
- throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false
14038
-
14039
- This indicates that your JavaScript environment is broken. You cannot use
14040
- esbuild in this environment because esbuild relies on this invariant. This
14041
- is not a problem with esbuild. You need to fix your environment instead.
14042
- `);
14043
- function readUInt32LE(buffer2, offset) {
14044
- return (buffer2[offset++] | buffer2[offset++] << 8 | buffer2[offset++] << 16 | buffer2[offset++] << 24) >>> 0;
14045
- }
14046
- function writeUInt32LE(buffer2, value, offset) {
14047
- buffer2[offset++] = value;
14048
- buffer2[offset++] = value >> 8;
14049
- buffer2[offset++] = value >> 16;
14050
- buffer2[offset++] = value >> 24;
14051
- }
14052
- var fromCharCode = String.fromCharCode;
14053
- function throwSyntaxError(bytes, index2, message) {
14054
- const c = bytes[index2];
14055
- let line3 = 1;
14056
- let column2 = 0;
14057
- for (let i = 0;i < index2; i++) {
14058
- if (bytes[i] === 10) {
14059
- line3++;
14060
- column2 = 0;
14061
- } else {
14062
- column2++;
14063
- }
14064
- }
14065
- throw new SyntaxError(message ? message : index2 === bytes.length ? "Unexpected end of input while parsing JSON" : c >= 32 && c <= 126 ? `Unexpected character ${fromCharCode(c)} in JSON at position ${index2} (line ${line3}, column ${column2})` : `Unexpected byte 0x${c.toString(16)} in JSON at position ${index2} (line ${line3}, column ${column2})`);
14066
- }
14067
- function JSON_parse(bytes) {
14068
- if (!(bytes instanceof Uint8Array)) {
14069
- throw new Error(`JSON input must be a Uint8Array`);
14070
- }
14071
- const propertyStack = [];
14072
- const objectStack = [];
14073
- const stateStack = [];
14074
- const length = bytes.length;
14075
- let property = null;
14076
- let state = 0;
14077
- let object;
14078
- let i = 0;
14079
- while (i < length) {
14080
- let c = bytes[i++];
14081
- if (c <= 32) {
14082
- continue;
14083
- }
14084
- let value;
14085
- if (state === 2 && property === null && c !== 34 && c !== 125) {
14086
- throwSyntaxError(bytes, --i);
14087
- }
14088
- switch (c) {
14089
- case 116: {
14090
- if (bytes[i++] !== 114 || bytes[i++] !== 117 || bytes[i++] !== 101) {
14091
- throwSyntaxError(bytes, --i);
14092
- }
14093
- value = true;
14094
- break;
14095
- }
14096
- case 102: {
14097
- if (bytes[i++] !== 97 || bytes[i++] !== 108 || bytes[i++] !== 115 || bytes[i++] !== 101) {
14098
- throwSyntaxError(bytes, --i);
14099
- }
14100
- value = false;
14101
- break;
14102
- }
14103
- case 110: {
14104
- if (bytes[i++] !== 117 || bytes[i++] !== 108 || bytes[i++] !== 108) {
14105
- throwSyntaxError(bytes, --i);
14106
- }
14107
- value = null;
14108
- break;
14109
- }
14110
- case 45:
14111
- case 46:
14112
- case 48:
14113
- case 49:
14114
- case 50:
14115
- case 51:
14116
- case 52:
14117
- case 53:
14118
- case 54:
14119
- case 55:
14120
- case 56:
14121
- case 57: {
14122
- let index2 = i;
14123
- value = fromCharCode(c);
14124
- c = bytes[i];
14125
- while (true) {
14126
- switch (c) {
14127
- case 43:
14128
- case 45:
14129
- case 46:
14130
- case 48:
14131
- case 49:
14132
- case 50:
14133
- case 51:
14134
- case 52:
14135
- case 53:
14136
- case 54:
14137
- case 55:
14138
- case 56:
14139
- case 57:
14140
- case 101:
14141
- case 69: {
14142
- value += fromCharCode(c);
14143
- c = bytes[++i];
14144
- continue;
14145
- }
14146
- }
14147
- break;
14148
- }
14149
- value = +value;
14150
- if (isNaN(value)) {
14151
- throwSyntaxError(bytes, --index2, "Invalid number");
14152
- }
14153
- break;
14154
- }
14155
- case 34: {
14156
- value = "";
14157
- while (true) {
14158
- if (i >= length) {
14159
- throwSyntaxError(bytes, length);
14160
- }
14161
- c = bytes[i++];
14162
- if (c === 34) {
14163
- break;
14164
- } else if (c === 92) {
14165
- switch (bytes[i++]) {
14166
- case 34:
14167
- value += '"';
14168
- break;
14169
- case 47:
14170
- value += "/";
14171
- break;
14172
- case 92:
14173
- value += "\\";
14174
- break;
14175
- case 98:
14176
- value += "\b";
14177
- break;
14178
- case 102:
14179
- value += "\f";
14180
- break;
14181
- case 110:
14182
- value += `
14183
- `;
14184
- break;
14185
- case 114:
14186
- value += "\r";
14187
- break;
14188
- case 116:
14189
- value += "\t";
14190
- break;
14191
- case 117: {
14192
- let code = 0;
14193
- for (let j = 0;j < 4; j++) {
14194
- c = bytes[i++];
14195
- code <<= 4;
14196
- if (c >= 48 && c <= 57)
14197
- code |= c - 48;
14198
- else if (c >= 97 && c <= 102)
14199
- code |= c + (10 - 97);
14200
- else if (c >= 65 && c <= 70)
14201
- code |= c + (10 - 65);
14202
- else
14203
- throwSyntaxError(bytes, --i);
14204
- }
14205
- value += fromCharCode(code);
14206
- break;
14207
- }
14208
- default:
14209
- throwSyntaxError(bytes, --i);
14210
- break;
14211
- }
14212
- } else if (c <= 127) {
14213
- value += fromCharCode(c);
14214
- } else if ((c & 224) === 192) {
14215
- value += fromCharCode((c & 31) << 6 | bytes[i++] & 63);
14216
- } else if ((c & 240) === 224) {
14217
- value += fromCharCode((c & 15) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63);
14218
- } else if ((c & 248) == 240) {
14219
- let codePoint = (c & 7) << 18 | (bytes[i++] & 63) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63;
14220
- if (codePoint > 65535) {
14221
- codePoint -= 65536;
14222
- value += fromCharCode(codePoint >> 10 & 1023 | 55296);
14223
- codePoint = 56320 | codePoint & 1023;
14224
- }
14225
- value += fromCharCode(codePoint);
14226
- }
14227
- }
14228
- value[0];
14229
- break;
14230
- }
14231
- case 91: {
14232
- value = [];
14233
- propertyStack.push(property);
14234
- objectStack.push(object);
14235
- stateStack.push(state);
14236
- property = null;
14237
- object = value;
14238
- state = 1;
14239
- continue;
14240
- }
14241
- case 123: {
14242
- value = {};
14243
- propertyStack.push(property);
14244
- objectStack.push(object);
14245
- stateStack.push(state);
14246
- property = null;
14247
- object = value;
14248
- state = 2;
14249
- continue;
14250
- }
14251
- case 93: {
14252
- if (state !== 1) {
14253
- throwSyntaxError(bytes, --i);
14254
- }
14255
- value = object;
14256
- property = propertyStack.pop();
14257
- object = objectStack.pop();
14258
- state = stateStack.pop();
14259
- break;
14260
- }
14261
- case 125: {
14262
- if (state !== 2) {
14263
- throwSyntaxError(bytes, --i);
14264
- }
14265
- value = object;
14266
- property = propertyStack.pop();
14267
- object = objectStack.pop();
14268
- state = stateStack.pop();
14269
- break;
14270
- }
14271
- default: {
14272
- throwSyntaxError(bytes, --i);
14273
- }
14274
- }
14275
- c = bytes[i];
14276
- while (c <= 32) {
14277
- c = bytes[++i];
14278
- }
14279
- switch (state) {
14280
- case 0: {
14281
- if (i === length) {
14282
- return value;
14283
- }
14284
- break;
14285
- }
14286
- case 1: {
14287
- object.push(value);
14288
- if (c === 44) {
14289
- i++;
14290
- continue;
14291
- }
14292
- if (c === 93) {
14293
- continue;
14294
- }
14295
- break;
14296
- }
14297
- case 2: {
14298
- if (property === null) {
14299
- property = value;
14300
- if (c === 58) {
14301
- i++;
14302
- continue;
14303
- }
14304
- } else {
14305
- object[property] = value;
14306
- property = null;
14307
- if (c === 44) {
14308
- i++;
14309
- continue;
14310
- }
14311
- if (c === 125) {
14312
- continue;
14313
- }
14314
- }
14315
- break;
14316
- }
14317
- }
14318
- break;
14319
- }
14320
- throwSyntaxError(bytes, i);
14321
- }
14322
- var quote = JSON.stringify;
14323
- var buildLogLevelDefault = "warning";
14324
- var transformLogLevelDefault = "silent";
14325
- function validateAndJoinStringArray(values2, what) {
14326
- const toJoin = [];
14327
- for (const value of values2) {
14328
- validateStringValue(value, what);
14329
- if (value.indexOf(",") >= 0)
14330
- throw new Error(`Invalid ${what}: ${value}`);
14331
- toJoin.push(value);
14332
- }
14333
- return toJoin.join(",");
14334
- }
14335
- var canBeAnything = () => null;
14336
- var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
14337
- var mustBeString = (value) => typeof value === "string" ? null : "a string";
14338
- var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
14339
- var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
14340
- var mustBeValidPortNumber = (value) => typeof value === "number" && value === (value | 0) && value >= 0 && value <= 65535 ? null : "a valid port number";
14341
- var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
14342
- var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
14343
- var mustBeArrayOfStrings = (value) => Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "an array of strings";
14344
- var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
14345
- var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
14346
- var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
14347
- var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
14348
- var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
14349
- var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
14350
- var mustBeStringOrArrayOfStrings = (value) => typeof value === "string" || Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "a string or an array of strings";
14351
- var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
14352
- var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL";
14353
- function getFlag(object, keys, key, mustBeFn) {
14354
- let value = object[key];
14355
- keys[key + ""] = true;
14356
- if (value === undefined)
14357
- return;
14358
- let mustBe = mustBeFn(value);
14359
- if (mustBe !== null)
14360
- throw new Error(`${quote(key)} must be ${mustBe}`);
14361
- return value;
14362
- }
14363
- function checkForInvalidFlags(object, keys, where) {
14364
- for (let key in object) {
14365
- if (!(key in keys)) {
14366
- throw new Error(`Invalid option ${where}: ${quote(key)}`);
14367
- }
14368
- }
14369
- }
14370
- function validateInitializeOptions(options) {
14371
- let keys = /* @__PURE__ */ Object.create(null);
14372
- let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL);
14373
- let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule);
14374
- let worker = getFlag(options, keys, "worker", mustBeBoolean);
14375
- checkForInvalidFlags(options, keys, "in initialize() call");
14376
- return {
14377
- wasmURL,
14378
- wasmModule,
14379
- worker
14380
- };
14381
- }
14382
- function validateMangleCache(mangleCache) {
14383
- let validated;
14384
- if (mangleCache !== undefined) {
14385
- validated = /* @__PURE__ */ Object.create(null);
14386
- for (let key in mangleCache) {
14387
- let value = mangleCache[key];
14388
- if (typeof value === "string" || value === false) {
14389
- validated[key] = value;
14390
- } else {
14391
- throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`);
14392
- }
14393
- }
14394
- }
14395
- return validated;
14396
- }
14397
- function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) {
14398
- let color = getFlag(options, keys, "color", mustBeBoolean);
14399
- let logLevel = getFlag(options, keys, "logLevel", mustBeString);
14400
- let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
14401
- if (color !== undefined)
14402
- flags.push(`--color=${color}`);
14403
- else if (isTTY2)
14404
- flags.push(`--color=true`);
14405
- flags.push(`--log-level=${logLevel || logLevelDefault}`);
14406
- flags.push(`--log-limit=${logLimit || 0}`);
14407
- }
14408
- function validateStringValue(value, what, key) {
14409
- if (typeof value !== "string") {
14410
- throw new Error(`Expected value for ${what}${key !== undefined ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`);
14411
- }
14412
- return value;
14413
- }
14414
- function pushCommonFlags(flags, options, keys) {
14415
- let legalComments = getFlag(options, keys, "legalComments", mustBeString);
14416
- let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
14417
- let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
14418
- let target = getFlag(options, keys, "target", mustBeStringOrArrayOfStrings);
14419
- let format = getFlag(options, keys, "format", mustBeString);
14420
- let globalName = getFlag(options, keys, "globalName", mustBeString);
14421
- let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp);
14422
- let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp);
14423
- let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean);
14424
- let minify = getFlag(options, keys, "minify", mustBeBoolean);
14425
- let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
14426
- let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
14427
- let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
14428
- let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger);
14429
- let drop = getFlag(options, keys, "drop", mustBeArrayOfStrings);
14430
- let dropLabels = getFlag(options, keys, "dropLabels", mustBeArrayOfStrings);
14431
- let charset = getFlag(options, keys, "charset", mustBeString);
14432
- let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
14433
- let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
14434
- let jsx = getFlag(options, keys, "jsx", mustBeString);
14435
- let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
14436
- let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
14437
- let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString);
14438
- let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean);
14439
- let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean);
14440
- let define = getFlag(options, keys, "define", mustBeObject);
14441
- let logOverride = getFlag(options, keys, "logOverride", mustBeObject);
14442
- let supported = getFlag(options, keys, "supported", mustBeObject);
14443
- let pure = getFlag(options, keys, "pure", mustBeArrayOfStrings);
14444
- let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
14445
- let platform = getFlag(options, keys, "platform", mustBeString);
14446
- let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
14447
- let absPaths = getFlag(options, keys, "absPaths", mustBeArrayOfStrings);
14448
- if (legalComments)
14449
- flags.push(`--legal-comments=${legalComments}`);
14450
- if (sourceRoot !== undefined)
14451
- flags.push(`--source-root=${sourceRoot}`);
14452
- if (sourcesContent !== undefined)
14453
- flags.push(`--sources-content=${sourcesContent}`);
14454
- if (target)
14455
- flags.push(`--target=${validateAndJoinStringArray(Array.isArray(target) ? target : [target], "target")}`);
14456
- if (format)
14457
- flags.push(`--format=${format}`);
14458
- if (globalName)
14459
- flags.push(`--global-name=${globalName}`);
14460
- if (platform)
14461
- flags.push(`--platform=${platform}`);
14462
- if (tsconfigRaw)
14463
- flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
14464
- if (minify)
14465
- flags.push("--minify");
14466
- if (minifySyntax)
14467
- flags.push("--minify-syntax");
14468
- if (minifyWhitespace)
14469
- flags.push("--minify-whitespace");
14470
- if (minifyIdentifiers)
14471
- flags.push("--minify-identifiers");
14472
- if (lineLimit)
14473
- flags.push(`--line-limit=${lineLimit}`);
14474
- if (charset)
14475
- flags.push(`--charset=${charset}`);
14476
- if (treeShaking !== undefined)
14477
- flags.push(`--tree-shaking=${treeShaking}`);
14478
- if (ignoreAnnotations)
14479
- flags.push(`--ignore-annotations`);
14480
- if (drop)
14481
- for (let what of drop)
14482
- flags.push(`--drop:${validateStringValue(what, "drop")}`);
14483
- if (dropLabels)
14484
- flags.push(`--drop-labels=${validateAndJoinStringArray(dropLabels, "drop label")}`);
14485
- if (absPaths)
14486
- flags.push(`--abs-paths=${validateAndJoinStringArray(absPaths, "abs paths")}`);
14487
- if (mangleProps)
14488
- flags.push(`--mangle-props=${jsRegExpToGoRegExp(mangleProps)}`);
14489
- if (reserveProps)
14490
- flags.push(`--reserve-props=${jsRegExpToGoRegExp(reserveProps)}`);
14491
- if (mangleQuoted !== undefined)
14492
- flags.push(`--mangle-quoted=${mangleQuoted}`);
14493
- if (jsx)
14494
- flags.push(`--jsx=${jsx}`);
14495
- if (jsxFactory)
14496
- flags.push(`--jsx-factory=${jsxFactory}`);
14497
- if (jsxFragment)
14498
- flags.push(`--jsx-fragment=${jsxFragment}`);
14499
- if (jsxImportSource)
14500
- flags.push(`--jsx-import-source=${jsxImportSource}`);
14501
- if (jsxDev)
14502
- flags.push(`--jsx-dev`);
14503
- if (jsxSideEffects)
14504
- flags.push(`--jsx-side-effects`);
14505
- if (define) {
14506
- for (let key in define) {
14507
- if (key.indexOf("=") >= 0)
14508
- throw new Error(`Invalid define: ${key}`);
14509
- flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`);
14510
- }
14511
- }
14512
- if (logOverride) {
14513
- for (let key in logOverride) {
14514
- if (key.indexOf("=") >= 0)
14515
- throw new Error(`Invalid log override: ${key}`);
14516
- flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`);
14517
- }
14518
- }
14519
- if (supported) {
14520
- for (let key in supported) {
14521
- if (key.indexOf("=") >= 0)
14522
- throw new Error(`Invalid supported: ${key}`);
14523
- const value = supported[key];
14524
- if (typeof value !== "boolean")
14525
- throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`);
14526
- flags.push(`--supported:${key}=${value}`);
14527
- }
14528
- }
14529
- if (pure)
14530
- for (let fn of pure)
14531
- flags.push(`--pure:${validateStringValue(fn, "pure")}`);
14532
- if (keepNames)
14533
- flags.push(`--keep-names`);
14534
- }
14535
- function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) {
14536
- var _a2;
14537
- let flags = [];
14538
- let entries = [];
14539
- let keys = /* @__PURE__ */ Object.create(null);
14540
- let stdinContents = null;
14541
- let stdinResolveDir = null;
14542
- pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
14543
- pushCommonFlags(flags, options, keys);
14544
- let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
14545
- let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
14546
- let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
14547
- let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
14548
- let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
14549
- let outfile = getFlag(options, keys, "outfile", mustBeString);
14550
- let outdir = getFlag(options, keys, "outdir", mustBeString);
14551
- let outbase = getFlag(options, keys, "outbase", mustBeString);
14552
- let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
14553
- let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArrayOfStrings);
14554
- let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArrayOfStrings);
14555
- let mainFields = getFlag(options, keys, "mainFields", mustBeArrayOfStrings);
14556
- let conditions2 = getFlag(options, keys, "conditions", mustBeArrayOfStrings);
14557
- let external2 = getFlag(options, keys, "external", mustBeArrayOfStrings);
14558
- let packages = getFlag(options, keys, "packages", mustBeString);
14559
- let alias3 = getFlag(options, keys, "alias", mustBeObject);
14560
- let loader = getFlag(options, keys, "loader", mustBeObject);
14561
- let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
14562
- let publicPath = getFlag(options, keys, "publicPath", mustBeString);
14563
- let entryNames = getFlag(options, keys, "entryNames", mustBeString);
14564
- let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
14565
- let assetNames = getFlag(options, keys, "assetNames", mustBeString);
14566
- let inject = getFlag(options, keys, "inject", mustBeArrayOfStrings);
14567
- let banner = getFlag(options, keys, "banner", mustBeObject);
14568
- let footer = getFlag(options, keys, "footer", mustBeObject);
14569
- let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints);
14570
- let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
14571
- let stdin = getFlag(options, keys, "stdin", mustBeObject);
14572
- let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault;
14573
- let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
14574
- let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
14575
- keys.plugins = true;
14576
- checkForInvalidFlags(options, keys, `in ${callName}() call`);
14577
- if (sourcemap)
14578
- flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
14579
- if (bundle)
14580
- flags.push("--bundle");
14581
- if (allowOverwrite)
14582
- flags.push("--allow-overwrite");
14583
- if (splitting)
14584
- flags.push("--splitting");
14585
- if (preserveSymlinks)
14586
- flags.push("--preserve-symlinks");
14587
- if (metafile)
14588
- flags.push(`--metafile`);
14589
- if (outfile)
14590
- flags.push(`--outfile=${outfile}`);
14591
- if (outdir)
14592
- flags.push(`--outdir=${outdir}`);
14593
- if (outbase)
14594
- flags.push(`--outbase=${outbase}`);
14595
- if (tsconfig)
14596
- flags.push(`--tsconfig=${tsconfig}`);
14597
- if (packages)
14598
- flags.push(`--packages=${packages}`);
14599
- if (resolveExtensions)
14600
- flags.push(`--resolve-extensions=${validateAndJoinStringArray(resolveExtensions, "resolve extension")}`);
14601
- if (publicPath)
14602
- flags.push(`--public-path=${publicPath}`);
14603
- if (entryNames)
14604
- flags.push(`--entry-names=${entryNames}`);
14605
- if (chunkNames)
14606
- flags.push(`--chunk-names=${chunkNames}`);
14607
- if (assetNames)
14608
- flags.push(`--asset-names=${assetNames}`);
14609
- if (mainFields)
14610
- flags.push(`--main-fields=${validateAndJoinStringArray(mainFields, "main field")}`);
14611
- if (conditions2)
14612
- flags.push(`--conditions=${validateAndJoinStringArray(conditions2, "condition")}`);
14613
- if (external2)
14614
- for (let name of external2)
14615
- flags.push(`--external:${validateStringValue(name, "external")}`);
14616
- if (alias3) {
14617
- for (let old in alias3) {
14618
- if (old.indexOf("=") >= 0)
14619
- throw new Error(`Invalid package name in alias: ${old}`);
14620
- flags.push(`--alias:${old}=${validateStringValue(alias3[old], "alias", old)}`);
14621
- }
14622
- }
14623
- if (banner) {
14624
- for (let type in banner) {
14625
- if (type.indexOf("=") >= 0)
14626
- throw new Error(`Invalid banner file type: ${type}`);
14627
- flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`);
14628
- }
14629
- }
14630
- if (footer) {
14631
- for (let type in footer) {
14632
- if (type.indexOf("=") >= 0)
14633
- throw new Error(`Invalid footer file type: ${type}`);
14634
- flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`);
14635
- }
14636
- }
14637
- if (inject)
14638
- for (let path3 of inject)
14639
- flags.push(`--inject:${validateStringValue(path3, "inject")}`);
14640
- if (loader) {
14641
- for (let ext in loader) {
14642
- if (ext.indexOf("=") >= 0)
14643
- throw new Error(`Invalid loader extension: ${ext}`);
14644
- flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`);
14645
- }
14646
- }
14647
- if (outExtension) {
14648
- for (let ext in outExtension) {
14649
- if (ext.indexOf("=") >= 0)
14650
- throw new Error(`Invalid out extension: ${ext}`);
14651
- flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
14652
- }
14653
- }
14654
- if (entryPoints) {
14655
- if (Array.isArray(entryPoints)) {
14656
- for (let i = 0, n = entryPoints.length;i < n; i++) {
14657
- let entryPoint = entryPoints[i];
14658
- if (typeof entryPoint === "object" && entryPoint !== null) {
14659
- let entryPointKeys = /* @__PURE__ */ Object.create(null);
14660
- let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
14661
- let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
14662
- checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
14663
- if (input === undefined)
14664
- throw new Error('Missing property "in" for entry point at index ' + i);
14665
- if (output === undefined)
14666
- throw new Error('Missing property "out" for entry point at index ' + i);
14667
- entries.push([output, input]);
14668
- } else {
14669
- entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
14670
- }
14671
- }
14672
- } else {
14673
- for (let key in entryPoints) {
14674
- entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
14675
- }
14676
- }
14677
- }
14678
- if (stdin) {
14679
- let stdinKeys = /* @__PURE__ */ Object.create(null);
14680
- let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
14681
- let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
14682
- let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
14683
- let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
14684
- checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object');
14685
- if (sourcefile)
14686
- flags.push(`--sourcefile=${sourcefile}`);
14687
- if (loader2)
14688
- flags.push(`--loader=${loader2}`);
14689
- if (resolveDir)
14690
- stdinResolveDir = resolveDir;
14691
- if (typeof contents === "string")
14692
- stdinContents = encodeUTF8(contents);
14693
- else if (contents instanceof Uint8Array)
14694
- stdinContents = contents;
14695
- }
14696
- let nodePaths = [];
14697
- if (nodePathsInput) {
14698
- for (let value of nodePathsInput) {
14699
- value += "";
14700
- nodePaths.push(value);
14701
- }
14702
- }
14703
- return {
14704
- entries,
14705
- flags,
14706
- write,
14707
- stdinContents,
14708
- stdinResolveDir,
14709
- absWorkingDir,
14710
- nodePaths,
14711
- mangleCache: validateMangleCache(mangleCache)
14712
- };
14713
- }
14714
- function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) {
14715
- let flags = [];
14716
- let keys = /* @__PURE__ */ Object.create(null);
14717
- pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
14718
- pushCommonFlags(flags, options, keys);
14719
- let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
14720
- let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
14721
- let loader = getFlag(options, keys, "loader", mustBeString);
14722
- let banner = getFlag(options, keys, "banner", mustBeString);
14723
- let footer = getFlag(options, keys, "footer", mustBeString);
14724
- let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
14725
- checkForInvalidFlags(options, keys, `in ${callName}() call`);
14726
- if (sourcemap)
14727
- flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
14728
- if (sourcefile)
14729
- flags.push(`--sourcefile=${sourcefile}`);
14730
- if (loader)
14731
- flags.push(`--loader=${loader}`);
14732
- if (banner)
14733
- flags.push(`--banner=${banner}`);
14734
- if (footer)
14735
- flags.push(`--footer=${footer}`);
14736
- return {
14737
- flags,
14738
- mangleCache: validateMangleCache(mangleCache)
14739
- };
14740
- }
14741
- function createChannel(streamIn) {
14742
- const requestCallbacksByKey = {};
14743
- const closeData = { didClose: false, reason: "" };
14744
- let responseCallbacks = {};
14745
- let nextRequestID = 0;
14746
- let nextBuildKey = 0;
14747
- let stdout = new Uint8Array(16 * 1024);
14748
- let stdoutUsed = 0;
14749
- let readFromStdout = (chunk) => {
14750
- let limit = stdoutUsed + chunk.length;
14751
- if (limit > stdout.length) {
14752
- let swap = new Uint8Array(limit * 2);
14753
- swap.set(stdout);
14754
- stdout = swap;
14755
- }
14756
- stdout.set(chunk, stdoutUsed);
14757
- stdoutUsed += chunk.length;
14758
- let offset = 0;
14759
- while (offset + 4 <= stdoutUsed) {
14760
- let length = readUInt32LE(stdout, offset);
14761
- if (offset + 4 + length > stdoutUsed) {
14762
- break;
14763
- }
14764
- offset += 4;
14765
- handleIncomingPacket(stdout.subarray(offset, offset + length));
14766
- offset += length;
14767
- }
14768
- if (offset > 0) {
14769
- stdout.copyWithin(0, offset, stdoutUsed);
14770
- stdoutUsed -= offset;
14771
- }
14772
- };
14773
- let afterClose = (error) => {
14774
- closeData.didClose = true;
14775
- if (error)
14776
- closeData.reason = ": " + (error.message || error);
14777
- const text3 = "The service was stopped" + closeData.reason;
14778
- for (let id in responseCallbacks) {
14779
- responseCallbacks[id](text3, null);
14780
- }
14781
- responseCallbacks = {};
14782
- };
14783
- let sendRequest = (refs, value, callback) => {
14784
- if (closeData.didClose)
14785
- return callback("The service is no longer running" + closeData.reason, null);
14786
- let id = nextRequestID++;
14787
- responseCallbacks[id] = (error, response) => {
14788
- try {
14789
- callback(error, response);
14790
- } finally {
14791
- if (refs)
14792
- refs.unref();
14793
- }
14794
- };
14795
- if (refs)
14796
- refs.ref();
14797
- streamIn.writeToStdin(encodePacket({ id, isRequest: true, value }));
14798
- };
14799
- let sendResponse = (id, value) => {
14800
- if (closeData.didClose)
14801
- throw new Error("The service is no longer running" + closeData.reason);
14802
- streamIn.writeToStdin(encodePacket({ id, isRequest: false, value }));
14803
- };
14804
- let handleRequest = async (id, request) => {
14805
- try {
14806
- if (request.command === "ping") {
14807
- sendResponse(id, {});
14808
- return;
14809
- }
14810
- if (typeof request.key === "number") {
14811
- const requestCallbacks = requestCallbacksByKey[request.key];
14812
- if (!requestCallbacks) {
14813
- return;
14814
- }
14815
- const callback = requestCallbacks[request.command];
14816
- if (callback) {
14817
- await callback(id, request);
14818
- return;
14819
- }
14820
- }
14821
- throw new Error(`Invalid command: ` + request.command);
14822
- } catch (e) {
14823
- const errors3 = [extractErrorMessageV8(e, streamIn, null, undefined, "")];
14824
- try {
14825
- sendResponse(id, { errors: errors3 });
14826
- } catch {}
14827
- }
14828
- };
14829
- let isFirstPacket = true;
14830
- let handleIncomingPacket = (bytes) => {
14831
- if (isFirstPacket) {
14832
- isFirstPacket = false;
14833
- let binaryVersion = String.fromCharCode(...bytes);
14834
- if (binaryVersion !== "0.28.0") {
14835
- throw new Error(`Cannot start service: Host version "${"0.28.0"}" does not match binary version ${quote(binaryVersion)}`);
14836
- }
14837
- return;
14838
- }
14839
- let packet = decodePacket(bytes);
14840
- if (packet.isRequest) {
14841
- handleRequest(packet.id, packet.value);
14842
- } else {
14843
- let callback = responseCallbacks[packet.id];
14844
- delete responseCallbacks[packet.id];
14845
- if (packet.value.error)
14846
- callback(packet.value.error, {});
14847
- else
14848
- callback(null, packet.value);
14849
- }
14850
- };
14851
- let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => {
14852
- let refCount = 0;
14853
- const buildKey = nextBuildKey++;
14854
- const requestCallbacks = {};
14855
- const buildRefs = {
14856
- ref() {
14857
- if (++refCount === 1) {
14858
- if (refs)
14859
- refs.ref();
14860
- }
14861
- },
14862
- unref() {
14863
- if (--refCount === 0) {
14864
- delete requestCallbacksByKey[buildKey];
14865
- if (refs)
14866
- refs.unref();
14867
- }
14868
- }
14869
- };
14870
- requestCallbacksByKey[buildKey] = requestCallbacks;
14871
- buildRefs.ref();
14872
- buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, buildRefs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, (err, res) => {
14873
- try {
14874
- callback(err, res);
14875
- } finally {
14876
- buildRefs.unref();
14877
- }
14878
- });
14879
- };
14880
- let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => {
14881
- const details = createObjectStash();
14882
- let start = (inputPath) => {
14883
- try {
14884
- if (typeof input !== "string" && !(input instanceof Uint8Array))
14885
- throw new Error('The input to "transform" must be a string or a Uint8Array');
14886
- let {
14887
- flags,
14888
- mangleCache
14889
- } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault);
14890
- let request = {
14891
- command: "transform",
14892
- flags,
14893
- inputFS: inputPath !== null,
14894
- input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input
14895
- };
14896
- if (mangleCache)
14897
- request.mangleCache = mangleCache;
14898
- sendRequest(refs, request, (error, response) => {
14899
- if (error)
14900
- return callback(new Error(error), null);
14901
- let errors3 = replaceDetailsInMessages(response.errors, details);
14902
- let warnings = replaceDetailsInMessages(response.warnings, details);
14903
- let outstanding = 1;
14904
- let next = () => {
14905
- if (--outstanding === 0) {
14906
- let result = {
14907
- warnings,
14908
- code: response.code,
14909
- map: response.map,
14910
- mangleCache: undefined,
14911
- legalComments: undefined
14912
- };
14913
- if ("legalComments" in response)
14914
- result.legalComments = response == null ? undefined : response.legalComments;
14915
- if (response.mangleCache)
14916
- result.mangleCache = response == null ? undefined : response.mangleCache;
14917
- callback(null, result);
14918
- }
14919
- };
14920
- if (errors3.length > 0)
14921
- return callback(failureErrorWithLog("Transform failed", errors3, warnings), null);
14922
- if (response.codeFS) {
14923
- outstanding++;
14924
- fs3.readFile(response.code, (err, contents) => {
14925
- if (err !== null) {
14926
- callback(err, null);
14927
- } else {
14928
- response.code = contents;
14929
- next();
14930
- }
14931
- });
14932
- }
14933
- if (response.mapFS) {
14934
- outstanding++;
14935
- fs3.readFile(response.map, (err, contents) => {
14936
- if (err !== null) {
14937
- callback(err, null);
14938
- } else {
14939
- response.map = contents;
14940
- next();
14941
- }
14942
- });
14943
- }
14944
- next();
14945
- });
14946
- } catch (e) {
14947
- let flags = [];
14948
- try {
14949
- pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault);
14950
- } catch {}
14951
- const error = extractErrorMessageV8(e, streamIn, details, undefined, "");
14952
- sendRequest(refs, { command: "error", flags, error }, () => {
14953
- error.detail = details.load(error.detail);
14954
- callback(failureErrorWithLog("Transform failed", [error], []), null);
14955
- });
14956
- }
14957
- };
14958
- if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) {
14959
- let next = start;
14960
- start = () => fs3.writeFile(input, next);
14961
- }
14962
- start(null);
14963
- };
14964
- let formatMessages2 = ({ callName, refs, messages: messages2, options, callback }) => {
14965
- if (!options)
14966
- throw new Error(`Missing second argument in ${callName}() call`);
14967
- let keys = {};
14968
- let kind = getFlag(options, keys, "kind", mustBeString);
14969
- let color = getFlag(options, keys, "color", mustBeBoolean);
14970
- let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
14971
- checkForInvalidFlags(options, keys, `in ${callName}() call`);
14972
- if (kind === undefined)
14973
- throw new Error(`Missing "kind" in ${callName}() call`);
14974
- if (kind !== "error" && kind !== "warning")
14975
- throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
14976
- let request = {
14977
- command: "format-msgs",
14978
- messages: sanitizeMessages(messages2, "messages", null, "", terminalWidth),
14979
- isWarning: kind === "warning"
14980
- };
14981
- if (color !== undefined)
14982
- request.color = color;
14983
- if (terminalWidth !== undefined)
14984
- request.terminalWidth = terminalWidth;
14985
- sendRequest(refs, request, (error, response) => {
14986
- if (error)
14987
- return callback(new Error(error), null);
14988
- callback(null, response.messages);
14989
- });
14990
- };
14991
- let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => {
14992
- if (options === undefined)
14993
- options = {};
14994
- let keys = {};
14995
- let color = getFlag(options, keys, "color", mustBeBoolean);
14996
- let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
14997
- checkForInvalidFlags(options, keys, `in ${callName}() call`);
14998
- let request = {
14999
- command: "analyze-metafile",
15000
- metafile
15001
- };
15002
- if (color !== undefined)
15003
- request.color = color;
15004
- if (verbose !== undefined)
15005
- request.verbose = verbose;
15006
- sendRequest(refs, request, (error, response) => {
15007
- if (error)
15008
- return callback(new Error(error), null);
15009
- callback(null, response.result);
15010
- });
15011
- };
15012
- return {
15013
- readFromStdout,
15014
- afterClose,
15015
- service: {
15016
- buildOrContext,
15017
- transform: transform2,
15018
- formatMessages: formatMessages2,
15019
- analyzeMetafile: analyzeMetafile2
15020
- }
15021
- };
15022
- }
15023
- function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) {
15024
- const details = createObjectStash();
15025
- const isContext = callName === "context";
15026
- const handleError = (e, pluginName) => {
15027
- const flags = [];
15028
- try {
15029
- pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault);
15030
- } catch {}
15031
- const message = extractErrorMessageV8(e, streamIn, details, undefined, pluginName);
15032
- sendRequest(refs, { command: "error", flags, error: message }, () => {
15033
- message.detail = details.load(message.detail);
15034
- callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
15035
- });
15036
- };
15037
- let plugins;
15038
- if (typeof options === "object") {
15039
- const value = options.plugins;
15040
- if (value !== undefined) {
15041
- if (!Array.isArray(value))
15042
- return handleError(new Error(`"plugins" must be an array`), "");
15043
- plugins = value;
15044
- }
15045
- }
15046
- if (plugins && plugins.length > 0) {
15047
- if (streamIn.isSync)
15048
- return handleError(new Error("Cannot use plugins in synchronous API calls"), "");
15049
- handlePlugins(buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, plugins, details).then((result) => {
15050
- if (!result.ok)
15051
- return handleError(result.error, result.pluginName);
15052
- try {
15053
- buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
15054
- } catch (e) {
15055
- handleError(e, "");
15056
- }
15057
- }, (e) => handleError(e, ""));
15058
- return;
15059
- }
15060
- try {
15061
- buildOrContextContinue(null, (result, done) => done([], []), () => {});
15062
- } catch (e) {
15063
- handleError(e, "");
15064
- }
15065
- function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
15066
- const writeDefault = streamIn.hasFS;
15067
- const {
15068
- entries,
15069
- flags,
15070
- write,
15071
- stdinContents,
15072
- stdinResolveDir,
15073
- absWorkingDir,
15074
- nodePaths,
15075
- mangleCache
15076
- } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault);
15077
- if (write && !streamIn.hasFS)
15078
- throw new Error(`The "write" option is unavailable in this environment`);
15079
- const request = {
15080
- command: "build",
15081
- key: buildKey,
15082
- entries,
15083
- flags,
15084
- write,
15085
- stdinContents,
15086
- stdinResolveDir,
15087
- absWorkingDir: absWorkingDir || defaultWD2,
15088
- nodePaths,
15089
- context: isContext
15090
- };
15091
- if (requestPlugins)
15092
- request.plugins = requestPlugins;
15093
- if (mangleCache)
15094
- request.mangleCache = mangleCache;
15095
- const buildResponseToResult = (response, callback2) => {
15096
- const result = {
15097
- errors: replaceDetailsInMessages(response.errors, details),
15098
- warnings: replaceDetailsInMessages(response.warnings, details),
15099
- outputFiles: undefined,
15100
- metafile: undefined,
15101
- mangleCache: undefined
15102
- };
15103
- const originalErrors = result.errors.slice();
15104
- const originalWarnings = result.warnings.slice();
15105
- if (response.outputFiles)
15106
- result.outputFiles = response.outputFiles.map(convertOutputFiles);
15107
- if (response.metafile && response.metafile.length)
15108
- result.metafile = parseJSON(response.metafile);
15109
- if (response.mangleCache)
15110
- result.mangleCache = response.mangleCache;
15111
- if (response.writeToStdout !== undefined)
15112
- console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
15113
- runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
15114
- if (originalErrors.length > 0 || onEndErrors.length > 0) {
15115
- const error = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings));
15116
- return callback2(error, null, onEndErrors, onEndWarnings);
15117
- }
15118
- callback2(null, result, onEndErrors, onEndWarnings);
15119
- });
15120
- };
15121
- let latestResultPromise;
15122
- let provideLatestResult;
15123
- if (isContext)
15124
- requestCallbacks["on-end"] = (id, request2) => new Promise((resolve2) => {
15125
- buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => {
15126
- const response = {
15127
- errors: onEndErrors,
15128
- warnings: onEndWarnings
15129
- };
15130
- if (provideLatestResult)
15131
- provideLatestResult(err, result);
15132
- latestResultPromise = undefined;
15133
- provideLatestResult = undefined;
15134
- sendResponse(id, response);
15135
- resolve2();
15136
- });
15137
- });
15138
- sendRequest(refs, request, (error, response) => {
15139
- if (error)
15140
- return callback(new Error(error), null);
15141
- if (!isContext) {
15142
- return buildResponseToResult(response, (err, res) => {
15143
- scheduleOnDisposeCallbacks();
15144
- return callback(err, res);
15145
- });
15146
- }
15147
- if (response.errors.length > 0) {
15148
- return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
15149
- }
15150
- let didDispose = false;
15151
- const result = {
15152
- rebuild: () => {
15153
- if (!latestResultPromise)
15154
- latestResultPromise = new Promise((resolve2, reject) => {
15155
- let settlePromise;
15156
- provideLatestResult = (err, result2) => {
15157
- if (!settlePromise)
15158
- settlePromise = () => err ? reject(err) : resolve2(result2);
15159
- };
15160
- const triggerAnotherBuild = () => {
15161
- const request2 = {
15162
- command: "rebuild",
15163
- key: buildKey
15164
- };
15165
- sendRequest(refs, request2, (error2, response2) => {
15166
- if (error2) {
15167
- reject(new Error(error2));
15168
- } else if (settlePromise) {
15169
- settlePromise();
15170
- } else {
15171
- triggerAnotherBuild();
15172
- }
15173
- });
15174
- };
15175
- triggerAnotherBuild();
15176
- });
15177
- return latestResultPromise;
15178
- },
15179
- watch: (options2 = {}) => new Promise((resolve2, reject) => {
15180
- if (!streamIn.hasFS)
15181
- throw new Error(`Cannot use the "watch" API in this environment`);
15182
- const keys = {};
15183
- const delay = getFlag(options2, keys, "delay", mustBeInteger);
15184
- checkForInvalidFlags(options2, keys, `in watch() call`);
15185
- const request2 = {
15186
- command: "watch",
15187
- key: buildKey
15188
- };
15189
- if (delay)
15190
- request2.delay = delay;
15191
- sendRequest(refs, request2, (error2) => {
15192
- if (error2)
15193
- reject(new Error(error2));
15194
- else
15195
- resolve2(undefined);
15196
- });
15197
- }),
15198
- serve: (options2 = {}) => new Promise((resolve2, reject) => {
15199
- if (!streamIn.hasFS)
15200
- throw new Error(`Cannot use the "serve" API in this environment`);
15201
- const keys = {};
15202
- const port = getFlag(options2, keys, "port", mustBeValidPortNumber);
15203
- const host = getFlag(options2, keys, "host", mustBeString);
15204
- const servedir = getFlag(options2, keys, "servedir", mustBeString);
15205
- const keyfile = getFlag(options2, keys, "keyfile", mustBeString);
15206
- const certfile = getFlag(options2, keys, "certfile", mustBeString);
15207
- const fallback = getFlag(options2, keys, "fallback", mustBeString);
15208
- const cors = getFlag(options2, keys, "cors", mustBeObject);
15209
- const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction);
15210
- checkForInvalidFlags(options2, keys, `in serve() call`);
15211
- const request2 = {
15212
- command: "serve",
15213
- key: buildKey,
15214
- onRequest: !!onRequest
15215
- };
15216
- if (port !== undefined)
15217
- request2.port = port;
15218
- if (host !== undefined)
15219
- request2.host = host;
15220
- if (servedir !== undefined)
15221
- request2.servedir = servedir;
15222
- if (keyfile !== undefined)
15223
- request2.keyfile = keyfile;
15224
- if (certfile !== undefined)
15225
- request2.certfile = certfile;
15226
- if (fallback !== undefined)
15227
- request2.fallback = fallback;
15228
- if (cors) {
15229
- const corsKeys = {};
15230
- const origin = getFlag(cors, corsKeys, "origin", mustBeStringOrArrayOfStrings);
15231
- checkForInvalidFlags(cors, corsKeys, `on "cors" object`);
15232
- if (Array.isArray(origin))
15233
- request2.corsOrigin = origin;
15234
- else if (origin !== undefined)
15235
- request2.corsOrigin = [origin];
15236
- }
15237
- sendRequest(refs, request2, (error2, response2) => {
15238
- if (error2)
15239
- return reject(new Error(error2));
15240
- if (onRequest) {
15241
- requestCallbacks["serve-request"] = (id, request3) => {
15242
- onRequest(request3.args);
15243
- sendResponse(id, {});
15244
- };
15245
- }
15246
- resolve2(response2);
15247
- });
15248
- }),
15249
- cancel: () => new Promise((resolve2) => {
15250
- if (didDispose)
15251
- return resolve2();
15252
- const request2 = {
15253
- command: "cancel",
15254
- key: buildKey
15255
- };
15256
- sendRequest(refs, request2, () => {
15257
- resolve2();
15258
- });
15259
- }),
15260
- dispose: () => new Promise((resolve2) => {
15261
- if (didDispose)
15262
- return resolve2();
15263
- didDispose = true;
15264
- const request2 = {
15265
- command: "dispose",
15266
- key: buildKey
15267
- };
15268
- sendRequest(refs, request2, () => {
15269
- resolve2();
15270
- scheduleOnDisposeCallbacks();
15271
- refs.unref();
15272
- });
15273
- })
15274
- };
15275
- refs.ref();
15276
- callback(null, result);
15277
- });
15278
- }
15279
- }
15280
- var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => {
15281
- let onStartCallbacks = [];
15282
- let onEndCallbacks = [];
15283
- let onResolveCallbacks = {};
15284
- let onLoadCallbacks = {};
15285
- let onDisposeCallbacks = [];
15286
- let nextCallbackID = 0;
15287
- let i = 0;
15288
- let requestPlugins = [];
15289
- let isSetupDone = false;
15290
- plugins = [...plugins];
15291
- for (let item of plugins) {
15292
- let keys = {};
15293
- if (typeof item !== "object")
15294
- throw new Error(`Plugin at index ${i} must be an object`);
15295
- const name = getFlag(item, keys, "name", mustBeString);
15296
- if (typeof name !== "string" || name === "")
15297
- throw new Error(`Plugin at index ${i} is missing a name`);
15298
- try {
15299
- let setup = getFlag(item, keys, "setup", mustBeFunction);
15300
- if (typeof setup !== "function")
15301
- throw new Error(`Plugin is missing a setup function`);
15302
- checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`);
15303
- let plugin = {
15304
- name,
15305
- onStart: false,
15306
- onEnd: false,
15307
- onResolve: [],
15308
- onLoad: []
15309
- };
15310
- i++;
15311
- let resolve2 = (path3, options = {}) => {
15312
- if (!isSetupDone)
15313
- throw new Error('Cannot call "resolve" before plugin setup has completed');
15314
- if (typeof path3 !== "string")
15315
- throw new Error(`The path to resolve must be a string`);
15316
- let keys2 = /* @__PURE__ */ Object.create(null);
15317
- let pluginName = getFlag(options, keys2, "pluginName", mustBeString);
15318
- let importer = getFlag(options, keys2, "importer", mustBeString);
15319
- let namespace = getFlag(options, keys2, "namespace", mustBeString);
15320
- let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString);
15321
- let kind = getFlag(options, keys2, "kind", mustBeString);
15322
- let pluginData = getFlag(options, keys2, "pluginData", canBeAnything);
15323
- let importAttributes = getFlag(options, keys2, "with", mustBeObject);
15324
- checkForInvalidFlags(options, keys2, "in resolve() call");
15325
- return new Promise((resolve22, reject) => {
15326
- const request = {
15327
- command: "resolve",
15328
- path: path3,
15329
- key: buildKey,
15330
- pluginName: name
15331
- };
15332
- if (pluginName != null)
15333
- request.pluginName = pluginName;
15334
- if (importer != null)
15335
- request.importer = importer;
15336
- if (namespace != null)
15337
- request.namespace = namespace;
15338
- if (resolveDir != null)
15339
- request.resolveDir = resolveDir;
15340
- if (kind != null)
15341
- request.kind = kind;
15342
- else
15343
- throw new Error(`Must specify "kind" when calling "resolve"`);
15344
- if (pluginData != null)
15345
- request.pluginData = details.store(pluginData);
15346
- if (importAttributes != null)
15347
- request.with = sanitizeStringMap(importAttributes, "with");
15348
- sendRequest(refs, request, (error, response) => {
15349
- if (error !== null)
15350
- reject(new Error(error));
15351
- else
15352
- resolve22({
15353
- errors: replaceDetailsInMessages(response.errors, details),
15354
- warnings: replaceDetailsInMessages(response.warnings, details),
15355
- path: response.path,
15356
- external: response.external,
15357
- sideEffects: response.sideEffects,
15358
- namespace: response.namespace,
15359
- suffix: response.suffix,
15360
- pluginData: details.load(response.pluginData)
15361
- });
15362
- });
15363
- });
15364
- };
15365
- let promise = setup({
15366
- initialOptions,
15367
- resolve: resolve2,
15368
- onStart(callback) {
15369
- let registeredText = `This error came from the "onStart" callback registered here:`;
15370
- let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart");
15371
- onStartCallbacks.push({ name, callback, note: registeredNote });
15372
- plugin.onStart = true;
15373
- },
15374
- onEnd(callback) {
15375
- let registeredText = `This error came from the "onEnd" callback registered here:`;
15376
- let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd");
15377
- onEndCallbacks.push({ name, callback, note: registeredNote });
15378
- plugin.onEnd = true;
15379
- },
15380
- onResolve(options, callback) {
15381
- let registeredText = `This error came from the "onResolve" callback registered here:`;
15382
- let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve");
15383
- let keys2 = {};
15384
- let filter = getFlag(options, keys2, "filter", mustBeRegExp);
15385
- let namespace = getFlag(options, keys2, "namespace", mustBeString);
15386
- checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`);
15387
- if (filter == null)
15388
- throw new Error(`onResolve() call is missing a filter`);
15389
- let id = nextCallbackID++;
15390
- onResolveCallbacks[id] = { name, callback, note: registeredNote };
15391
- plugin.onResolve.push({ id, filter: jsRegExpToGoRegExp(filter), namespace: namespace || "" });
15392
- },
15393
- onLoad(options, callback) {
15394
- let registeredText = `This error came from the "onLoad" callback registered here:`;
15395
- let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad");
15396
- let keys2 = {};
15397
- let filter = getFlag(options, keys2, "filter", mustBeRegExp);
15398
- let namespace = getFlag(options, keys2, "namespace", mustBeString);
15399
- checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`);
15400
- if (filter == null)
15401
- throw new Error(`onLoad() call is missing a filter`);
15402
- let id = nextCallbackID++;
15403
- onLoadCallbacks[id] = { name, callback, note: registeredNote };
15404
- plugin.onLoad.push({ id, filter: jsRegExpToGoRegExp(filter), namespace: namespace || "" });
15405
- },
15406
- onDispose(callback) {
15407
- onDisposeCallbacks.push(callback);
15408
- },
15409
- esbuild: streamIn.esbuild
15410
- });
15411
- if (promise)
15412
- await promise;
15413
- requestPlugins.push(plugin);
15414
- } catch (e) {
15415
- return { ok: false, error: e, pluginName: name };
15416
- }
15417
- }
15418
- requestCallbacks["on-start"] = async (id, request) => {
15419
- details.clear();
15420
- let response = { errors: [], warnings: [] };
15421
- await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => {
15422
- try {
15423
- let result = await callback();
15424
- if (result != null) {
15425
- if (typeof result !== "object")
15426
- throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`);
15427
- let keys = {};
15428
- let errors3 = getFlag(result, keys, "errors", mustBeArray);
15429
- let warnings = getFlag(result, keys, "warnings", mustBeArray);
15430
- checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`);
15431
- if (errors3 != null)
15432
- response.errors.push(...sanitizeMessages(errors3, "errors", details, name, undefined));
15433
- if (warnings != null)
15434
- response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, undefined));
15435
- }
15436
- } catch (e) {
15437
- response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name));
15438
- }
15439
- }));
15440
- sendResponse(id, response);
15441
- };
15442
- requestCallbacks["on-resolve"] = async (id, request) => {
15443
- let response = {}, name = "", callback, note;
15444
- for (let id2 of request.ids) {
15445
- try {
15446
- ({ name, callback, note } = onResolveCallbacks[id2]);
15447
- let result = await callback({
15448
- path: request.path,
15449
- importer: request.importer,
15450
- namespace: request.namespace,
15451
- resolveDir: request.resolveDir,
15452
- kind: request.kind,
15453
- pluginData: details.load(request.pluginData),
15454
- with: request.with
15455
- });
15456
- if (result != null) {
15457
- if (typeof result !== "object")
15458
- throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`);
15459
- let keys = {};
15460
- let pluginName = getFlag(result, keys, "pluginName", mustBeString);
15461
- let path3 = getFlag(result, keys, "path", mustBeString);
15462
- let namespace = getFlag(result, keys, "namespace", mustBeString);
15463
- let suffix = getFlag(result, keys, "suffix", mustBeString);
15464
- let external2 = getFlag(result, keys, "external", mustBeBoolean);
15465
- let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
15466
- let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
15467
- let errors3 = getFlag(result, keys, "errors", mustBeArray);
15468
- let warnings = getFlag(result, keys, "warnings", mustBeArray);
15469
- let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
15470
- let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
15471
- checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`);
15472
- response.id = id2;
15473
- if (pluginName != null)
15474
- response.pluginName = pluginName;
15475
- if (path3 != null)
15476
- response.path = path3;
15477
- if (namespace != null)
15478
- response.namespace = namespace;
15479
- if (suffix != null)
15480
- response.suffix = suffix;
15481
- if (external2 != null)
15482
- response.external = external2;
15483
- if (sideEffects != null)
15484
- response.sideEffects = sideEffects;
15485
- if (pluginData != null)
15486
- response.pluginData = details.store(pluginData);
15487
- if (errors3 != null)
15488
- response.errors = sanitizeMessages(errors3, "errors", details, name, undefined);
15489
- if (warnings != null)
15490
- response.warnings = sanitizeMessages(warnings, "warnings", details, name, undefined);
15491
- if (watchFiles != null)
15492
- response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
15493
- if (watchDirs != null)
15494
- response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
15495
- break;
15496
- }
15497
- } catch (e) {
15498
- response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
15499
- break;
15500
- }
15501
- }
15502
- sendResponse(id, response);
15503
- };
15504
- requestCallbacks["on-load"] = async (id, request) => {
15505
- let response = {}, name = "", callback, note;
15506
- for (let id2 of request.ids) {
15507
- try {
15508
- ({ name, callback, note } = onLoadCallbacks[id2]);
15509
- let result = await callback({
15510
- path: request.path,
15511
- namespace: request.namespace,
15512
- suffix: request.suffix,
15513
- pluginData: details.load(request.pluginData),
15514
- with: request.with
15515
- });
15516
- if (result != null) {
15517
- if (typeof result !== "object")
15518
- throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`);
15519
- let keys = {};
15520
- let pluginName = getFlag(result, keys, "pluginName", mustBeString);
15521
- let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
15522
- let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
15523
- let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
15524
- let loader = getFlag(result, keys, "loader", mustBeString);
15525
- let errors3 = getFlag(result, keys, "errors", mustBeArray);
15526
- let warnings = getFlag(result, keys, "warnings", mustBeArray);
15527
- let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
15528
- let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
15529
- checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`);
15530
- response.id = id2;
15531
- if (pluginName != null)
15532
- response.pluginName = pluginName;
15533
- if (contents instanceof Uint8Array)
15534
- response.contents = contents;
15535
- else if (contents != null)
15536
- response.contents = encodeUTF8(contents);
15537
- if (resolveDir != null)
15538
- response.resolveDir = resolveDir;
15539
- if (pluginData != null)
15540
- response.pluginData = details.store(pluginData);
15541
- if (loader != null)
15542
- response.loader = loader;
15543
- if (errors3 != null)
15544
- response.errors = sanitizeMessages(errors3, "errors", details, name, undefined);
15545
- if (warnings != null)
15546
- response.warnings = sanitizeMessages(warnings, "warnings", details, name, undefined);
15547
- if (watchFiles != null)
15548
- response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
15549
- if (watchDirs != null)
15550
- response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
15551
- break;
15552
- }
15553
- } catch (e) {
15554
- response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
15555
- break;
15556
- }
15557
- }
15558
- sendResponse(id, response);
15559
- };
15560
- let runOnEndCallbacks = (result, done) => done([], []);
15561
- if (onEndCallbacks.length > 0) {
15562
- runOnEndCallbacks = (result, done) => {
15563
- (async () => {
15564
- const onEndErrors = [];
15565
- const onEndWarnings = [];
15566
- for (const { name, callback, note } of onEndCallbacks) {
15567
- let newErrors;
15568
- let newWarnings;
15569
- try {
15570
- const value = await callback(result);
15571
- if (value != null) {
15572
- if (typeof value !== "object")
15573
- throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
15574
- let keys = {};
15575
- let errors3 = getFlag(value, keys, "errors", mustBeArray);
15576
- let warnings = getFlag(value, keys, "warnings", mustBeArray);
15577
- checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
15578
- if (errors3 != null)
15579
- newErrors = sanitizeMessages(errors3, "errors", details, name, undefined);
15580
- if (warnings != null)
15581
- newWarnings = sanitizeMessages(warnings, "warnings", details, name, undefined);
15582
- }
15583
- } catch (e) {
15584
- newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
15585
- }
15586
- if (newErrors) {
15587
- onEndErrors.push(...newErrors);
15588
- try {
15589
- result.errors.push(...newErrors);
15590
- } catch {}
15591
- }
15592
- if (newWarnings) {
15593
- onEndWarnings.push(...newWarnings);
15594
- try {
15595
- result.warnings.push(...newWarnings);
15596
- } catch {}
15597
- }
15598
- }
15599
- done(onEndErrors, onEndWarnings);
15600
- })();
15601
- };
15602
- }
15603
- let scheduleOnDisposeCallbacks = () => {
15604
- for (const cb of onDisposeCallbacks) {
15605
- setTimeout(() => cb(), 0);
15606
- }
15607
- };
15608
- isSetupDone = true;
15609
- return {
15610
- ok: true,
15611
- requestPlugins,
15612
- runOnEndCallbacks,
15613
- scheduleOnDisposeCallbacks
15614
- };
15615
- };
15616
- function createObjectStash() {
15617
- const map = /* @__PURE__ */ new Map;
15618
- let nextID = 0;
15619
- return {
15620
- clear() {
15621
- map.clear();
15622
- },
15623
- load(id) {
15624
- return map.get(id);
15625
- },
15626
- store(value) {
15627
- if (value === undefined)
15628
- return -1;
15629
- const id = nextID++;
15630
- map.set(id, value);
15631
- return id;
15632
- }
15633
- };
15634
- }
15635
- function extractCallerV8(e, streamIn, ident) {
15636
- let note;
15637
- let tried = false;
15638
- return () => {
15639
- if (tried)
15640
- return note;
15641
- tried = true;
15642
- try {
15643
- let lines = (e.stack + "").split(`
15644
- `);
15645
- lines.splice(1, 1);
15646
- let location = parseStackLinesV8(streamIn, lines, ident);
15647
- if (location) {
15648
- note = { text: e.message, location };
15649
- return note;
15650
- }
15651
- } catch {}
15652
- };
15653
- }
15654
- function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
15655
- let text3 = "Internal error";
15656
- let location = null;
15657
- try {
15658
- text3 = (e && e.message || e) + "";
15659
- } catch {}
15660
- try {
15661
- location = parseStackLinesV8(streamIn, (e.stack + "").split(`
15662
- `), "");
15663
- } catch {}
15664
- return { id: "", pluginName, text: text3, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 };
15665
- }
15666
- function parseStackLinesV8(streamIn, lines, ident) {
15667
- let at = " at ";
15668
- if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) {
15669
- for (let i = 1;i < lines.length; i++) {
15670
- let line3 = lines[i];
15671
- if (!line3.startsWith(at))
15672
- continue;
15673
- line3 = line3.slice(at.length);
15674
- while (true) {
15675
- let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line3);
15676
- if (match) {
15677
- line3 = match[1];
15678
- continue;
15679
- }
15680
- match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line3);
15681
- if (match) {
15682
- line3 = match[1];
15683
- continue;
15684
- }
15685
- match = /^(\S+):(\d+):(\d+)$/.exec(line3);
15686
- if (match) {
15687
- let contents;
15688
- try {
15689
- contents = streamIn.readFileSync(match[1], "utf8");
15690
- } catch {
15691
- break;
15692
- }
15693
- let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
15694
- let column2 = +match[3] - 1;
15695
- let length = lineText.slice(column2, column2 + ident.length) === ident ? ident.length : 0;
15696
- return {
15697
- file: match[1],
15698
- namespace: "file",
15699
- line: +match[2],
15700
- column: encodeUTF8(lineText.slice(0, column2)).length,
15701
- length: encodeUTF8(lineText.slice(column2, column2 + length)).length,
15702
- lineText: lineText + `
15703
- ` + lines.slice(1).join(`
15704
- `),
15705
- suggestion: ""
15706
- };
15707
- }
15708
- break;
15709
- }
15710
- }
15711
- }
15712
- return null;
15713
- }
15714
- function failureErrorWithLog(text3, errors3, warnings) {
15715
- let limit = 5;
15716
- text3 += errors3.length < 1 ? "" : ` with ${errors3.length} error${errors3.length < 2 ? "" : "s"}:` + errors3.slice(0, limit + 1).map((e, i) => {
15717
- if (i === limit)
15718
- return `
15719
- ...`;
15720
- if (!e.location)
15721
- return `
15722
- error: ${e.text}`;
15723
- let { file, line: line3, column: column2 } = e.location;
15724
- let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : "";
15725
- return `
15726
- ${file}:${line3}:${column2}: ERROR: ${pluginText}${e.text}`;
15727
- }).join("");
15728
- let error = new Error(text3);
15729
- for (const [key, value] of [["errors", errors3], ["warnings", warnings]]) {
15730
- Object.defineProperty(error, key, {
15731
- configurable: true,
15732
- enumerable: true,
15733
- get: () => value,
15734
- set: (value2) => Object.defineProperty(error, key, {
15735
- configurable: true,
15736
- enumerable: true,
15737
- value: value2
15738
- })
15739
- });
15740
- }
15741
- return error;
15742
- }
15743
- function replaceDetailsInMessages(messages2, stash) {
15744
- for (const message of messages2) {
15745
- message.detail = stash.load(message.detail);
15746
- }
15747
- return messages2;
15748
- }
15749
- function sanitizeLocation(location, where, terminalWidth) {
15750
- if (location == null)
15751
- return null;
15752
- let keys = {};
15753
- let file = getFlag(location, keys, "file", mustBeString);
15754
- let namespace = getFlag(location, keys, "namespace", mustBeString);
15755
- let line3 = getFlag(location, keys, "line", mustBeInteger);
15756
- let column2 = getFlag(location, keys, "column", mustBeInteger);
15757
- let length = getFlag(location, keys, "length", mustBeInteger);
15758
- let lineText = getFlag(location, keys, "lineText", mustBeString);
15759
- let suggestion = getFlag(location, keys, "suggestion", mustBeString);
15760
- checkForInvalidFlags(location, keys, where);
15761
- if (lineText) {
15762
- const relevantASCII = lineText.slice(0, (column2 && column2 > 0 ? column2 : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80));
15763
- if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) {
15764
- lineText = relevantASCII;
15765
- }
15766
- }
15767
- return {
15768
- file: file || "",
15769
- namespace: namespace || "",
15770
- line: line3 || 0,
15771
- column: column2 || 0,
15772
- length: length || 0,
15773
- lineText: lineText || "",
15774
- suggestion: suggestion || ""
15775
- };
15776
- }
15777
- function sanitizeMessages(messages2, property, stash, fallbackPluginName, terminalWidth) {
15778
- let messagesClone = [];
15779
- let index2 = 0;
15780
- for (const message of messages2) {
15781
- let keys = {};
15782
- let id = getFlag(message, keys, "id", mustBeString);
15783
- let pluginName = getFlag(message, keys, "pluginName", mustBeString);
15784
- let text3 = getFlag(message, keys, "text", mustBeString);
15785
- let location = getFlag(message, keys, "location", mustBeObjectOrNull);
15786
- let notes = getFlag(message, keys, "notes", mustBeArray);
15787
- let detail = getFlag(message, keys, "detail", canBeAnything);
15788
- let where = `in element ${index2} of "${property}"`;
15789
- checkForInvalidFlags(message, keys, where);
15790
- let notesClone = [];
15791
- if (notes) {
15792
- for (const note of notes) {
15793
- let noteKeys = {};
15794
- let noteText = getFlag(note, noteKeys, "text", mustBeString);
15795
- let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
15796
- checkForInvalidFlags(note, noteKeys, where);
15797
- notesClone.push({
15798
- text: noteText || "",
15799
- location: sanitizeLocation(noteLocation, where, terminalWidth)
15800
- });
15801
- }
15802
- }
15803
- messagesClone.push({
15804
- id: id || "",
15805
- pluginName: pluginName || fallbackPluginName,
15806
- text: text3 || "",
15807
- location: sanitizeLocation(location, where, terminalWidth),
15808
- notes: notesClone,
15809
- detail: stash ? stash.store(detail) : -1
15810
- });
15811
- index2++;
15812
- }
15813
- return messagesClone;
15814
- }
15815
- function sanitizeStringArray(values2, property) {
15816
- const result = [];
15817
- for (const value of values2) {
15818
- if (typeof value !== "string")
15819
- throw new Error(`${quote(property)} must be an array of strings`);
15820
- result.push(value);
15821
- }
15822
- return result;
15823
- }
15824
- function sanitizeStringMap(map, property) {
15825
- const result = /* @__PURE__ */ Object.create(null);
15826
- for (const key in map) {
15827
- const value = map[key];
15828
- if (typeof value !== "string")
15829
- throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`);
15830
- result[key] = value;
15831
- }
15832
- return result;
15833
- }
15834
- function convertOutputFiles({ path: path3, contents, hash }) {
15835
- let text3 = null;
15836
- return {
15837
- path: path3,
15838
- contents,
15839
- hash,
15840
- get text() {
15841
- const binary = this.contents;
15842
- if (text3 === null || binary !== contents) {
15843
- contents = binary;
15844
- text3 = decodeUTF8(binary);
15845
- }
15846
- return text3;
15847
- }
15848
- };
15849
- }
15850
- function jsRegExpToGoRegExp(regexp) {
15851
- let result = regexp.source;
15852
- if (regexp.flags)
15853
- result = `(?${regexp.flags})${result}`;
15854
- return result;
15855
- }
15856
- function parseJSON(bytes) {
15857
- let text3;
15858
- try {
15859
- text3 = decodeUTF8(bytes);
15860
- } catch {
15861
- return JSON_parse(bytes);
15862
- }
15863
- return JSON.parse(text3);
15864
- }
15865
- var fs2 = __require("fs");
15866
- var os2 = __require("os");
15867
- var path = __require("path");
15868
- var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
15869
- var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
15870
- var packageDarwin_arm64 = "@esbuild/darwin-arm64";
15871
- var packageDarwin_x64 = "@esbuild/darwin-x64";
15872
- var knownWindowsPackages = {
15873
- "win32 arm64 LE": "@esbuild/win32-arm64",
15874
- "win32 ia32 LE": "@esbuild/win32-ia32",
15875
- "win32 x64 LE": "@esbuild/win32-x64"
15876
- };
15877
- var knownUnixlikePackages = {
15878
- "aix ppc64 BE": "@esbuild/aix-ppc64",
15879
- "android arm64 LE": "@esbuild/android-arm64",
15880
- "darwin arm64 LE": "@esbuild/darwin-arm64",
15881
- "darwin x64 LE": "@esbuild/darwin-x64",
15882
- "freebsd arm64 LE": "@esbuild/freebsd-arm64",
15883
- "freebsd x64 LE": "@esbuild/freebsd-x64",
15884
- "linux arm LE": "@esbuild/linux-arm",
15885
- "linux arm64 LE": "@esbuild/linux-arm64",
15886
- "linux ia32 LE": "@esbuild/linux-ia32",
15887
- "linux mips64el LE": "@esbuild/linux-mips64el",
15888
- "linux ppc64 LE": "@esbuild/linux-ppc64",
15889
- "linux riscv64 LE": "@esbuild/linux-riscv64",
15890
- "linux s390x BE": "@esbuild/linux-s390x",
15891
- "linux x64 LE": "@esbuild/linux-x64",
15892
- "linux loong64 LE": "@esbuild/linux-loong64",
15893
- "netbsd arm64 LE": "@esbuild/netbsd-arm64",
15894
- "netbsd x64 LE": "@esbuild/netbsd-x64",
15895
- "openbsd arm64 LE": "@esbuild/openbsd-arm64",
15896
- "openbsd x64 LE": "@esbuild/openbsd-x64",
15897
- "sunos x64 LE": "@esbuild/sunos-x64"
15898
- };
15899
- var knownWebAssemblyFallbackPackages = {
15900
- "android arm LE": "@esbuild/android-arm",
15901
- "android x64 LE": "@esbuild/android-x64",
15902
- "openharmony arm64 LE": "@esbuild/openharmony-arm64"
15903
- };
15904
- function pkgAndSubpathForCurrentPlatform() {
15905
- let pkg;
15906
- let subpath;
15907
- let isWASM = false;
15908
- let platformKey = `${process.platform} ${os2.arch()} ${os2.endianness()}`;
15909
- if (platformKey in knownWindowsPackages) {
15910
- pkg = knownWindowsPackages[platformKey];
15911
- subpath = "esbuild.exe";
15912
- } else if (platformKey in knownUnixlikePackages) {
15913
- pkg = knownUnixlikePackages[platformKey];
15914
- subpath = "bin/esbuild";
15915
- } else if (platformKey in knownWebAssemblyFallbackPackages) {
15916
- pkg = knownWebAssemblyFallbackPackages[platformKey];
15917
- subpath = "bin/esbuild";
15918
- isWASM = true;
15919
- } else {
15920
- throw new Error(`Unsupported platform: ${platformKey}`);
15921
- }
15922
- return { pkg, subpath, isWASM };
15923
- }
15924
- function pkgForSomeOtherPlatform() {
15925
- const libMainJS = __require.resolve("esbuild");
15926
- const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS)));
15927
- if (path.basename(nodeModulesDirectory) === "node_modules") {
15928
- for (const unixKey in knownUnixlikePackages) {
15929
- try {
15930
- const pkg = knownUnixlikePackages[unixKey];
15931
- if (fs2.existsSync(path.join(nodeModulesDirectory, pkg)))
15932
- return pkg;
15933
- } catch {}
15934
- }
15935
- for (const windowsKey in knownWindowsPackages) {
15936
- try {
15937
- const pkg = knownWindowsPackages[windowsKey];
15938
- if (fs2.existsSync(path.join(nodeModulesDirectory, pkg)))
15939
- return pkg;
15940
- } catch {}
15941
- }
15942
- }
15943
- return null;
15944
- }
15945
- function downloadedBinPath(pkg, subpath) {
15946
- const esbuildLibDir = path.dirname(__require.resolve("esbuild"));
15947
- return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
15948
- }
15949
- function generateBinPath() {
15950
- if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
15951
- if (!fs2.existsSync(ESBUILD_BINARY_PATH)) {
15952
- console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
15953
- } else {
15954
- return { binPath: ESBUILD_BINARY_PATH, isWASM: false };
15955
- }
15956
- }
15957
- const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
15958
- let binPath;
15959
- try {
15960
- binPath = __require.resolve(`${pkg}/${subpath}`);
15961
- } catch (e) {
15962
- binPath = downloadedBinPath(pkg, subpath);
15963
- if (!fs2.existsSync(binPath)) {
15964
- try {
15965
- __require.resolve(pkg);
15966
- } catch {
15967
- const otherPkg = pkgForSomeOtherPlatform();
15968
- if (otherPkg) {
15969
- let suggestions = `
15970
- Specifically the "${otherPkg}" package is present but this platform
15971
- needs the "${pkg}" package instead. People often get into this
15972
- situation by installing esbuild on Windows or macOS and copying "node_modules"
15973
- into a Docker image that runs Linux, or by copying "node_modules" between
15974
- Windows and WSL environments.
15975
-
15976
- If you are installing with npm, you can try not copying the "node_modules"
15977
- directory when you copy the files over, and running "npm ci" or "npm install"
15978
- on the destination platform after the copy. Or you could consider using yarn
15979
- instead of npm which has built-in support for installing a package on multiple
15980
- platforms simultaneously.
15981
-
15982
- If you are installing with yarn, you can try listing both this platform and the
15983
- other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
15984
- feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
15985
- Keep in mind that this means multiple copies of esbuild will be present.
15986
- `;
15987
- if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) {
15988
- suggestions = `
15989
- Specifically the "${otherPkg}" package is present but this platform
15990
- needs the "${pkg}" package instead. People often get into this
15991
- situation by installing esbuild with npm running inside of Rosetta 2 and then
15992
- trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
15993
- 2 is Apple's on-the-fly x86_64-to-arm64 translation service).
15994
-
15995
- If you are installing with npm, you can try ensuring that both npm and node are
15996
- not running under Rosetta 2 and then reinstalling esbuild. This likely involves
15997
- changing how you installed npm and/or node. For example, installing node with
15998
- the universal installer here should work: https://nodejs.org/en/download/. Or
15999
- you could consider using yarn instead of npm which has built-in support for
16000
- installing a package on multiple platforms simultaneously.
16001
-
16002
- If you are installing with yarn, you can try listing both "arm64" and "x64"
16003
- in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
16004
- https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
16005
- Keep in mind that this means multiple copies of esbuild will be present.
16006
- `;
16007
- }
16008
- throw new Error(`
16009
- You installed esbuild for another platform than the one you're currently using.
16010
- This won't work because esbuild is written with native code and needs to
16011
- install a platform-specific binary executable.
16012
- ${suggestions}
16013
- Another alternative is to use the "esbuild-wasm" package instead, which works
16014
- the same way on all platforms. But it comes with a heavy performance cost and
16015
- can sometimes be 10x slower than the "esbuild" package, so you may also not
16016
- want to do that.
16017
- `);
16018
- }
16019
- throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
16020
-
16021
- If you are installing esbuild with npm, make sure that you don't specify the
16022
- "--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
16023
- of "package.json" is used by esbuild to install the correct binary executable
16024
- for your current platform.`);
16025
- }
16026
- throw e;
16027
- }
16028
- }
16029
- if (/\.zip\//.test(binPath)) {
16030
- let pnpapi;
16031
- try {
16032
- pnpapi = (()=>{throw new Error("Cannot require module "+"pnpapi");})();
16033
- } catch (e) {}
16034
- if (pnpapi) {
16035
- const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
16036
- const binTargetPath = path.join(root, "node_modules", ".cache", "esbuild", `pnpapi-${pkg.replace("/", "-")}-${"0.28.0"}-${path.basename(subpath)}`);
16037
- if (!fs2.existsSync(binTargetPath)) {
16038
- fs2.mkdirSync(path.dirname(binTargetPath), { recursive: true });
16039
- fs2.copyFileSync(binPath, binTargetPath);
16040
- fs2.chmodSync(binTargetPath, 493);
16041
- }
16042
- return { binPath: binTargetPath, isWASM };
16043
- }
16044
- }
16045
- return { binPath, isWASM };
16046
- }
16047
- var child_process = __require("child_process");
16048
- var crypto2 = __require("crypto");
16049
- var path2 = __require("path");
16050
- var fs22 = __require("fs");
16051
- var os22 = __require("os");
16052
- var tty = __require("tty");
16053
- var worker_threads;
16054
- if (process.env.ESBUILD_WORKER_THREADS !== "0") {
16055
- try {
16056
- worker_threads = __require("worker_threads");
16057
- } catch {}
16058
- let [major, minor] = process.versions.node.split(".");
16059
- if (+major < 12 || +major === 12 && +minor < 17 || +major === 13 && +minor < 13) {
16060
- worker_threads = undefined;
16061
- }
16062
- }
16063
- var _a;
16064
- var isInternalWorkerThread = ((_a = worker_threads == null ? undefined : worker_threads.workerData) == null ? undefined : _a.esbuildVersion) === "0.28.0";
16065
- var esbuildCommandAndArgs = () => {
16066
- if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) {
16067
- throw new Error(`The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle.
16068
-
16069
- More information: The file containing the code for esbuild's JavaScript API (${__filename}) does not appear to be inside the esbuild package on the file system, which usually means that the esbuild package was bundled into another file. This is problematic because the API needs to run a binary executable inside the esbuild package which is located using a relative path from the API code to the executable. If the esbuild package is bundled, the relative path will be incorrect and the executable won't be found.`);
16070
- }
16071
- if (false) {} else {
16072
- const { binPath, isWASM } = generateBinPath();
16073
- if (isWASM) {
16074
- return ["node", [binPath]];
16075
- } else {
16076
- return [binPath, []];
16077
- }
16078
- }
16079
- };
16080
- var isTTY = () => tty.isatty(2);
16081
- var fsSync = {
16082
- readFile(tempFile, callback) {
16083
- try {
16084
- let contents = fs22.readFileSync(tempFile, "utf8");
16085
- try {
16086
- fs22.unlinkSync(tempFile);
16087
- } catch {}
16088
- callback(null, contents);
16089
- } catch (err) {
16090
- callback(err, null);
16091
- }
16092
- },
16093
- writeFile(contents, callback) {
16094
- try {
16095
- let tempFile = randomFileName();
16096
- fs22.writeFileSync(tempFile, contents);
16097
- callback(tempFile);
16098
- } catch {
16099
- callback(null);
16100
- }
16101
- }
16102
- };
16103
- var fsAsync = {
16104
- readFile(tempFile, callback) {
16105
- try {
16106
- fs22.readFile(tempFile, "utf8", (err, contents) => {
16107
- try {
16108
- fs22.unlink(tempFile, () => callback(err, contents));
16109
- } catch {
16110
- callback(err, contents);
16111
- }
16112
- });
16113
- } catch (err) {
16114
- callback(err, null);
16115
- }
16116
- },
16117
- writeFile(contents, callback) {
16118
- try {
16119
- let tempFile = randomFileName();
16120
- fs22.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile));
16121
- } catch {
16122
- callback(null);
16123
- }
16124
- }
16125
- };
16126
- var version2 = "0.28.0";
16127
- var build = (options) => ensureServiceIsRunning().build(options);
16128
- var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions);
16129
- var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
16130
- var formatMessages = (messages2, options) => ensureServiceIsRunning().formatMessages(messages2, options);
16131
- var analyzeMetafile = (messages2, options) => ensureServiceIsRunning().analyzeMetafile(messages2, options);
16132
- var buildSync = (options) => {
16133
- if (worker_threads && !isInternalWorkerThread) {
16134
- if (!workerThreadService)
16135
- workerThreadService = startWorkerThreadService(worker_threads);
16136
- return workerThreadService.buildSync(options);
16137
- }
16138
- let result;
16139
- runServiceSync((service) => service.buildOrContext({
16140
- callName: "buildSync",
16141
- refs: null,
16142
- options,
16143
- isTTY: isTTY(),
16144
- defaultWD,
16145
- callback: (err, res) => {
16146
- if (err)
16147
- throw err;
16148
- result = res;
16149
- }
16150
- }));
16151
- return result;
16152
- };
16153
- var transformSync = (input, options) => {
16154
- if (worker_threads && !isInternalWorkerThread) {
16155
- if (!workerThreadService)
16156
- workerThreadService = startWorkerThreadService(worker_threads);
16157
- return workerThreadService.transformSync(input, options);
16158
- }
16159
- let result;
16160
- runServiceSync((service) => service.transform({
16161
- callName: "transformSync",
16162
- refs: null,
16163
- input,
16164
- options: options || {},
16165
- isTTY: isTTY(),
16166
- fs: fsSync,
16167
- callback: (err, res) => {
16168
- if (err)
16169
- throw err;
16170
- result = res;
16171
- }
16172
- }));
16173
- return result;
16174
- };
16175
- var formatMessagesSync = (messages2, options) => {
16176
- if (worker_threads && !isInternalWorkerThread) {
16177
- if (!workerThreadService)
16178
- workerThreadService = startWorkerThreadService(worker_threads);
16179
- return workerThreadService.formatMessagesSync(messages2, options);
16180
- }
16181
- let result;
16182
- runServiceSync((service) => service.formatMessages({
16183
- callName: "formatMessagesSync",
16184
- refs: null,
16185
- messages: messages2,
16186
- options,
16187
- callback: (err, res) => {
16188
- if (err)
16189
- throw err;
16190
- result = res;
16191
- }
16192
- }));
16193
- return result;
16194
- };
16195
- var analyzeMetafileSync = (metafile, options) => {
16196
- if (worker_threads && !isInternalWorkerThread) {
16197
- if (!workerThreadService)
16198
- workerThreadService = startWorkerThreadService(worker_threads);
16199
- return workerThreadService.analyzeMetafileSync(metafile, options);
16200
- }
16201
- let result;
16202
- runServiceSync((service) => service.analyzeMetafile({
16203
- callName: "analyzeMetafileSync",
16204
- refs: null,
16205
- metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
16206
- options,
16207
- callback: (err, res) => {
16208
- if (err)
16209
- throw err;
16210
- result = res;
16211
- }
16212
- }));
16213
- return result;
16214
- };
16215
- var stop = () => {
16216
- if (stopService)
16217
- stopService();
16218
- if (workerThreadService)
16219
- workerThreadService.stop();
16220
- return Promise.resolve();
16221
- };
16222
- var initializeWasCalled = false;
16223
- var initialize = (options) => {
16224
- options = validateInitializeOptions(options || {});
16225
- if (options.wasmURL)
16226
- throw new Error(`The "wasmURL" option only works in the browser`);
16227
- if (options.wasmModule)
16228
- throw new Error(`The "wasmModule" option only works in the browser`);
16229
- if (options.worker)
16230
- throw new Error(`The "worker" option only works in the browser`);
16231
- if (initializeWasCalled)
16232
- throw new Error('Cannot call "initialize" more than once');
16233
- ensureServiceIsRunning();
16234
- initializeWasCalled = true;
16235
- return Promise.resolve();
16236
- };
16237
- var defaultWD = process.cwd();
16238
- var longLivedService;
16239
- var stopService;
16240
- var ensureServiceIsRunning = () => {
16241
- if (longLivedService)
16242
- return longLivedService;
16243
- let [command, args] = esbuildCommandAndArgs();
16244
- let child = child_process.spawn(command, args.concat(`--service=${"0.28.0"}`, "--ping"), {
16245
- windowsHide: true,
16246
- stdio: ["pipe", "pipe", "inherit"],
16247
- cwd: defaultWD
16248
- });
16249
- let { readFromStdout, afterClose, service } = createChannel({
16250
- writeToStdin(bytes) {
16251
- child.stdin.write(bytes, (err) => {
16252
- if (err)
16253
- afterClose(err);
16254
- });
16255
- },
16256
- readFileSync: fs22.readFileSync,
16257
- isSync: false,
16258
- hasFS: true,
16259
- esbuild: node_exports
16260
- });
16261
- child.stdin.on("error", afterClose);
16262
- child.on("error", afterClose);
16263
- const stdin = child.stdin;
16264
- const stdout = child.stdout;
16265
- stdout.on("data", readFromStdout);
16266
- stdout.on("end", afterClose);
16267
- stopService = () => {
16268
- stdin.destroy();
16269
- stdout.destroy();
16270
- child.kill();
16271
- initializeWasCalled = false;
16272
- longLivedService = undefined;
16273
- stopService = undefined;
16274
- };
16275
- let refCount = 0;
16276
- child.unref();
16277
- if (stdin.unref) {
16278
- stdin.unref();
16279
- }
16280
- if (stdout.unref) {
16281
- stdout.unref();
16282
- }
16283
- const refs = {
16284
- ref() {
16285
- if (++refCount === 1)
16286
- child.ref();
16287
- },
16288
- unref() {
16289
- if (--refCount === 0)
16290
- child.unref();
16291
- }
16292
- };
16293
- longLivedService = {
16294
- build: (options) => new Promise((resolve2, reject) => {
16295
- service.buildOrContext({
16296
- callName: "build",
16297
- refs,
16298
- options,
16299
- isTTY: isTTY(),
16300
- defaultWD,
16301
- callback: (err, res) => err ? reject(err) : resolve2(res)
16302
- });
16303
- }),
16304
- context: (options) => new Promise((resolve2, reject) => service.buildOrContext({
16305
- callName: "context",
16306
- refs,
16307
- options,
16308
- isTTY: isTTY(),
16309
- defaultWD,
16310
- callback: (err, res) => err ? reject(err) : resolve2(res)
16311
- })),
16312
- transform: (input, options) => new Promise((resolve2, reject) => service.transform({
16313
- callName: "transform",
16314
- refs,
16315
- input,
16316
- options: options || {},
16317
- isTTY: isTTY(),
16318
- fs: fsAsync,
16319
- callback: (err, res) => err ? reject(err) : resolve2(res)
16320
- })),
16321
- formatMessages: (messages2, options) => new Promise((resolve2, reject) => service.formatMessages({
16322
- callName: "formatMessages",
16323
- refs,
16324
- messages: messages2,
16325
- options,
16326
- callback: (err, res) => err ? reject(err) : resolve2(res)
16327
- })),
16328
- analyzeMetafile: (metafile, options) => new Promise((resolve2, reject) => service.analyzeMetafile({
16329
- callName: "analyzeMetafile",
16330
- refs,
16331
- metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
16332
- options,
16333
- callback: (err, res) => err ? reject(err) : resolve2(res)
16334
- }))
16335
- };
16336
- return longLivedService;
16337
- };
16338
- var runServiceSync = (callback) => {
16339
- let [command, args] = esbuildCommandAndArgs();
16340
- let stdin = new Uint8Array;
16341
- let { readFromStdout, afterClose, service } = createChannel({
16342
- writeToStdin(bytes) {
16343
- if (stdin.length !== 0)
16344
- throw new Error("Must run at most one command");
16345
- stdin = bytes;
16346
- },
16347
- isSync: true,
16348
- hasFS: true,
16349
- esbuild: node_exports
16350
- });
16351
- callback(service);
16352
- let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.28.0"}`), {
16353
- cwd: defaultWD,
16354
- windowsHide: true,
16355
- input: stdin,
16356
- maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
16357
- });
16358
- readFromStdout(stdout);
16359
- afterClose(null);
16360
- };
16361
- var randomFileName = () => {
16362
- return path2.join(os22.tmpdir(), `esbuild-${crypto2.randomBytes(32).toString("hex")}`);
16363
- };
16364
- var workerThreadService = null;
16365
- var startWorkerThreadService = (worker_threads2) => {
16366
- let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel;
16367
- let worker = new worker_threads2.Worker(__filename, {
16368
- workerData: { workerPort, defaultWD, esbuildVersion: "0.28.0" },
16369
- transferList: [workerPort],
16370
- execArgv: []
16371
- });
16372
- let nextID = 0;
16373
- let fakeBuildError = (text3) => {
16374
- let error = new Error(`Build failed with 1 error:
16375
- error: ${text3}`);
16376
- let errors3 = [{ id: "", pluginName: "", text: text3, location: null, notes: [], detail: undefined }];
16377
- error.errors = errors3;
16378
- error.warnings = [];
16379
- return error;
16380
- };
16381
- let validateBuildSyncOptions = (options) => {
16382
- if (!options)
16383
- return;
16384
- let plugins = options.plugins;
16385
- if (plugins && plugins.length > 0)
16386
- throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
16387
- };
16388
- let applyProperties = (object, properties) => {
16389
- for (let key in properties) {
16390
- object[key] = properties[key];
16391
- }
16392
- };
16393
- let runCallSync = (command, args) => {
16394
- let id = nextID++;
16395
- let sharedBuffer = new SharedArrayBuffer(8);
16396
- let sharedBufferView = new Int32Array(sharedBuffer);
16397
- let msg = { sharedBuffer, id, command, args };
16398
- worker.postMessage(msg);
16399
- let status = Atomics.wait(sharedBufferView, 0, 0);
16400
- if (status !== "ok" && status !== "not-equal")
16401
- throw new Error("Internal error: Atomics.wait() failed: " + status);
16402
- let { message: { id: id2, resolve: resolve2, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort);
16403
- if (id !== id2)
16404
- throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
16405
- if (reject) {
16406
- applyProperties(reject, properties);
16407
- throw reject;
16408
- }
16409
- return resolve2;
16410
- };
16411
- worker.unref();
16412
- return {
16413
- buildSync(options) {
16414
- validateBuildSyncOptions(options);
16415
- return runCallSync("build", [options]);
16416
- },
16417
- transformSync(input, options) {
16418
- return runCallSync("transform", [input, options]);
16419
- },
16420
- formatMessagesSync(messages2, options) {
16421
- return runCallSync("formatMessages", [messages2, options]);
16422
- },
16423
- analyzeMetafileSync(metafile, options) {
16424
- return runCallSync("analyzeMetafile", [metafile, options]);
16425
- },
16426
- stop() {
16427
- worker.terminate();
16428
- workerThreadService = null;
16429
- }
16430
- };
16431
- };
16432
- var startSyncServiceWorker = () => {
16433
- let workerPort = worker_threads.workerData.workerPort;
16434
- let parentPort = worker_threads.parentPort;
16435
- let extractProperties = (object) => {
16436
- let properties = {};
16437
- if (object && typeof object === "object") {
16438
- for (let key in object) {
16439
- properties[key] = object[key];
16440
- }
16441
- }
16442
- return properties;
16443
- };
16444
- try {
16445
- let service = ensureServiceIsRunning();
16446
- defaultWD = worker_threads.workerData.defaultWD;
16447
- parentPort.on("message", (msg) => {
16448
- (async () => {
16449
- let { sharedBuffer, id, command, args } = msg;
16450
- let sharedBufferView = new Int32Array(sharedBuffer);
16451
- try {
16452
- switch (command) {
16453
- case "build":
16454
- workerPort.postMessage({ id, resolve: await service.build(args[0]) });
16455
- break;
16456
- case "transform":
16457
- workerPort.postMessage({ id, resolve: await service.transform(args[0], args[1]) });
16458
- break;
16459
- case "formatMessages":
16460
- workerPort.postMessage({ id, resolve: await service.formatMessages(args[0], args[1]) });
16461
- break;
16462
- case "analyzeMetafile":
16463
- workerPort.postMessage({ id, resolve: await service.analyzeMetafile(args[0], args[1]) });
16464
- break;
16465
- default:
16466
- throw new Error(`Invalid command: ${command}`);
16467
- }
16468
- } catch (reject) {
16469
- workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
16470
- }
16471
- Atomics.add(sharedBufferView, 0, 1);
16472
- Atomics.notify(sharedBufferView, 0, Infinity);
16473
- })();
16474
- });
16475
- } catch (reject) {
16476
- parentPort.on("message", (msg) => {
16477
- let { sharedBuffer, id } = msg;
16478
- let sharedBufferView = new Int32Array(sharedBuffer);
16479
- workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
16480
- Atomics.add(sharedBufferView, 0, 1);
16481
- Atomics.notify(sharedBufferView, 0, Infinity);
16482
- });
16483
- }
16484
- };
16485
- if (isInternalWorkerThread) {
16486
- startSyncServiceWorker();
16487
- }
16488
- var node_default = node_exports;
16489
- });
16490
-
16491
13849
  // src/lib/manifest-generator.ts
16492
13850
  function generateDeploymentManifest(_projectDir, manifest) {
16493
13851
  const automations2 = manifest.automations.map((auto) => ({
@@ -16518,6 +13876,7 @@ import {
16518
13876
  } from "node:fs";
16519
13877
  import { createGzip } from "node:zlib";
16520
13878
  import { Readable } from "node:stream";
13879
+ import * as esbuild from "esbuild";
16521
13880
  async function createBundle(projectDir, options) {
16522
13881
  const maxSize = options?.maxBundleSize ?? MAX_BUNDLE_SIZE_BYTES;
16523
13882
  let duraManifest;
@@ -16663,12 +14022,10 @@ function createTarHeader(name, size2) {
16663
14022
  header.set(encoder.encode(checksumStr), 148);
16664
14023
  return header;
16665
14024
  }
16666
- var esbuild;
16667
14025
  var init_bundler = __esm(() => {
16668
14026
  init_src2();
16669
14027
  init_manifest2();
16670
14028
  init_manifest_generator();
16671
- esbuild = __toESM(require_main(), 1);
16672
14029
  });
16673
14030
 
16674
14031
  // src/commands/deploy.ts
@@ -20496,7 +17853,7 @@ function registerAddCommand(program2) {
20496
17853
  const projectDir = opts.dir ? resolve5(opts.dir) : process.cwd();
20497
17854
  const duraJsonPath = join11(projectDir, "dura.json");
20498
17855
  if (!existsSync10(duraJsonPath)) {
20499
- output.error("NOT_A_DURA_PROJECT", "No dura.json found in the current directory", "Run this command from a Dura project directory or use --dir");
17856
+ output.error("NOT_A_DURA_PROJECT", "No dura.json found in the current directory", "Run this command from a dura project directory or use --dir");
20500
17857
  return;
20501
17858
  }
20502
17859
  const existingRoutes = getExistingRoutes(projectDir);
@@ -21742,7 +19099,7 @@ __export(exports_init, {
21742
19099
  import { existsSync as existsSync12, mkdirSync as mkdirSync7, writeFileSync as writeFileSync10 } from "node:fs";
21743
19100
  import { join as join13, resolve as resolve6, basename } from "node:path";
21744
19101
  function registerInitCommand(program2) {
21745
- program2.command("init").description("Initialize a Dura project in the current directory and install AI agent skills").option("--dir <path>", "Project directory (defaults to current dir)").option("--name <name>", "Project name (defaults to directory name)").option("--global", "Install AI agent skills globally (~/.claude/skills/dura/)").option("--local", "Install AI agent skills locally (.claude/skills/dura/)").option("--skip-skills", "Skip AI agent skill installation").action(async (opts, cmd) => {
19102
+ program2.command("init").description("Initialize a dura project in the current directory and install AI agent skills").option("--dir <path>", "Project directory (defaults to current dir)").option("--name <name>", "Project name (defaults to directory name)").option("--global", "Install AI agent skills globally (~/.claude/skills/dura/)").option("--local", "Install AI agent skills locally (.claude/skills/dura/)").option("--skip-skills", "Skip AI agent skill installation").action(async (opts, cmd) => {
21746
19103
  const output = getOutput(cmd);
21747
19104
  const projectDir = resolve6(opts.dir ?? process.cwd());
21748
19105
  const projectName = opts.name ?? sanitizeName(basename(projectDir));
@@ -21770,9 +19127,9 @@ function registerInitCommand(program2) {
21770
19127
  writeFileSync10(gitignorePath, GITIGNORE_CONTENT2);
21771
19128
  }
21772
19129
  if (alreadyInitialized) {
21773
- output.info(`Re-checked Dura project "${projectName}" in ${projectDir}`);
19130
+ output.info(`Re-checked dura project "${projectName}" in ${projectDir}`);
21774
19131
  } else {
21775
- output.info(`Initialized Dura project "${projectName}"`);
19132
+ output.info(`Initialized dura project "${projectName}"`);
21776
19133
  }
21777
19134
  if (!opts.skipSkills) {
21778
19135
  let skillScope;
@@ -21807,7 +19164,7 @@ function registerInitCommand(program2) {
21807
19164
  output.info("");
21808
19165
  output.info("Quickstart:");
21809
19166
  output.info(" dura dev # Start the local dev server");
21810
- output.info(" dura deploy # Deploy to the Dura cloud");
19167
+ output.info(" dura deploy # Deploy to the dura cloud");
21811
19168
  output.info(" dura run hello # Manually trigger an automation");
21812
19169
  }
21813
19170
  });
@@ -21929,7 +19286,7 @@ var init_projects2 = __esm(() => {
21929
19286
  import { realpathSync } from "node:fs";
21930
19287
  function createProgram() {
21931
19288
  const program2 = new Command;
21932
- program2.name("dura").description("Dura.run CLI — manage your automations from the command line").version(CLI_VERSION, "-v, --version").option("--json", "Output in JSON format").hook("preAction", (thisCommand) => {
19289
+ program2.name("dura").description("dura.run CLI — manage your automations from the command line").version(CLI_VERSION, "-v, --version").option("--json", "Output in JSON format").hook("preAction", (thisCommand) => {
21933
19290
  const opts = thisCommand.optsWithGlobals();
21934
19291
  const output = new Output({ json: opts.json });
21935
19292
  thisCommand.setOptionValue("_output", output);
@@ -22029,7 +19386,7 @@ async function registerAllCommands(program2) {
22029
19386
  registerOpenApiCommand2(program2);
22030
19387
  return program2;
22031
19388
  }
22032
- var CLI_VERSION = "0.2.0";
19389
+ var CLI_VERSION = "0.2.1";
22033
19390
  var init_src3 = __esm(() => {
22034
19391
  init_esm();
22035
19392
  if (import.meta.url === `file://${realpathSync(process.argv[1] ?? "").replace(/\\/g, "/")}`) {
@@ -22046,4 +19403,4 @@ export {
22046
19403
  CLI_VERSION
22047
19404
  };
22048
19405
 
22049
- //# debugId=53C9238AA228047C64756E2164756E21
19406
+ //# debugId=25AB4373003CF5A164756E2164756E21