@vertz/cli 0.2.0

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/index.js ADDED
@@ -0,0 +1,4326 @@
1
+ import { createRequire } from "node:module";
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __toESM = (mod, isNodeMode, target) => {
8
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
9
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
10
+ for (let key of __getOwnPropNames(mod))
11
+ if (!__hasOwnProp.call(to, key))
12
+ __defProp(to, key, {
13
+ get: () => mod[key],
14
+ enumerable: true
15
+ });
16
+ return to;
17
+ };
18
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
19
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
20
+
21
+ // ../../node_modules/.bun/esbuild@0.27.3/node_modules/esbuild/lib/main.js
22
+ var require_main = __commonJS((exports, module) => {
23
+ var __dirname = "/home/runner/work/vertz/vertz/node_modules/.bun/esbuild@0.27.3/node_modules/esbuild/lib", __filename = "/home/runner/work/vertz/vertz/node_modules/.bun/esbuild@0.27.3/node_modules/esbuild/lib/main.js";
24
+ var __defProp2 = Object.defineProperty;
25
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
26
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
27
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
28
+ var __export = (target, all) => {
29
+ for (var name in all)
30
+ __defProp2(target, name, { get: all[name], enumerable: true });
31
+ };
32
+ var __copyProps = (to, from, except, desc) => {
33
+ if (from && typeof from === "object" || typeof from === "function") {
34
+ for (let key of __getOwnPropNames2(from))
35
+ if (!__hasOwnProp2.call(to, key) && key !== except)
36
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
37
+ }
38
+ return to;
39
+ };
40
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
41
+ var node_exports = {};
42
+ __export(node_exports, {
43
+ analyzeMetafile: () => analyzeMetafile,
44
+ analyzeMetafileSync: () => analyzeMetafileSync,
45
+ build: () => build,
46
+ buildSync: () => buildSync,
47
+ context: () => context,
48
+ default: () => node_default,
49
+ formatMessages: () => formatMessages,
50
+ formatMessagesSync: () => formatMessagesSync,
51
+ initialize: () => initialize,
52
+ stop: () => stop,
53
+ transform: () => transform,
54
+ transformSync: () => transformSync,
55
+ version: () => version
56
+ });
57
+ module.exports = __toCommonJS(node_exports);
58
+ function encodePacket(packet) {
59
+ let visit = (value) => {
60
+ if (value === null) {
61
+ bb.write8(0);
62
+ } else if (typeof value === "boolean") {
63
+ bb.write8(1);
64
+ bb.write8(+value);
65
+ } else if (typeof value === "number") {
66
+ bb.write8(2);
67
+ bb.write32(value | 0);
68
+ } else if (typeof value === "string") {
69
+ bb.write8(3);
70
+ bb.write(encodeUTF8(value));
71
+ } else if (value instanceof Uint8Array) {
72
+ bb.write8(4);
73
+ bb.write(value);
74
+ } else if (value instanceof Array) {
75
+ bb.write8(5);
76
+ bb.write32(value.length);
77
+ for (let item of value) {
78
+ visit(item);
79
+ }
80
+ } else {
81
+ let keys = Object.keys(value);
82
+ bb.write8(6);
83
+ bb.write32(keys.length);
84
+ for (let key of keys) {
85
+ bb.write(encodeUTF8(key));
86
+ visit(value[key]);
87
+ }
88
+ }
89
+ };
90
+ let bb = new ByteBuffer;
91
+ bb.write32(0);
92
+ bb.write32(packet.id << 1 | +!packet.isRequest);
93
+ visit(packet.value);
94
+ writeUInt32LE(bb.buf, bb.len - 4, 0);
95
+ return bb.buf.subarray(0, bb.len);
96
+ }
97
+ function decodePacket(bytes) {
98
+ let visit = () => {
99
+ switch (bb.read8()) {
100
+ case 0:
101
+ return null;
102
+ case 1:
103
+ return !!bb.read8();
104
+ case 2:
105
+ return bb.read32();
106
+ case 3:
107
+ return decodeUTF8(bb.read());
108
+ case 4:
109
+ return bb.read();
110
+ case 5: {
111
+ let count = bb.read32();
112
+ let value2 = [];
113
+ for (let i = 0;i < count; i++) {
114
+ value2.push(visit());
115
+ }
116
+ return value2;
117
+ }
118
+ case 6: {
119
+ let count = bb.read32();
120
+ let value2 = {};
121
+ for (let i = 0;i < count; i++) {
122
+ value2[decodeUTF8(bb.read())] = visit();
123
+ }
124
+ return value2;
125
+ }
126
+ default:
127
+ throw new Error("Invalid packet");
128
+ }
129
+ };
130
+ let bb = new ByteBuffer(bytes);
131
+ let id = bb.read32();
132
+ let isRequest = (id & 1) === 0;
133
+ id >>>= 1;
134
+ let value = visit();
135
+ if (bb.ptr !== bytes.length) {
136
+ throw new Error("Invalid packet");
137
+ }
138
+ return { id, isRequest, value };
139
+ }
140
+ var ByteBuffer = class {
141
+ constructor(buf = new Uint8Array(1024)) {
142
+ this.buf = buf;
143
+ this.len = 0;
144
+ this.ptr = 0;
145
+ }
146
+ _write(delta) {
147
+ if (this.len + delta > this.buf.length) {
148
+ let clone = new Uint8Array((this.len + delta) * 2);
149
+ clone.set(this.buf);
150
+ this.buf = clone;
151
+ }
152
+ this.len += delta;
153
+ return this.len - delta;
154
+ }
155
+ write8(value) {
156
+ let offset = this._write(1);
157
+ this.buf[offset] = value;
158
+ }
159
+ write32(value) {
160
+ let offset = this._write(4);
161
+ writeUInt32LE(this.buf, value, offset);
162
+ }
163
+ write(bytes) {
164
+ let offset = this._write(4 + bytes.length);
165
+ writeUInt32LE(this.buf, bytes.length, offset);
166
+ this.buf.set(bytes, offset + 4);
167
+ }
168
+ _read(delta) {
169
+ if (this.ptr + delta > this.buf.length) {
170
+ throw new Error("Invalid packet");
171
+ }
172
+ this.ptr += delta;
173
+ return this.ptr - delta;
174
+ }
175
+ read8() {
176
+ return this.buf[this._read(1)];
177
+ }
178
+ read32() {
179
+ return readUInt32LE(this.buf, this._read(4));
180
+ }
181
+ read() {
182
+ let length = this.read32();
183
+ let bytes = new Uint8Array(length);
184
+ let ptr = this._read(bytes.length);
185
+ bytes.set(this.buf.subarray(ptr, ptr + length));
186
+ return bytes;
187
+ }
188
+ };
189
+ var encodeUTF8;
190
+ var decodeUTF8;
191
+ var encodeInvariant;
192
+ if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
193
+ let encoder = new TextEncoder;
194
+ let decoder = new TextDecoder;
195
+ encodeUTF8 = (text) => encoder.encode(text);
196
+ decodeUTF8 = (bytes) => decoder.decode(bytes);
197
+ encodeInvariant = 'new TextEncoder().encode("")';
198
+ } else if (typeof Buffer !== "undefined") {
199
+ encodeUTF8 = (text) => Buffer.from(text);
200
+ decodeUTF8 = (bytes) => {
201
+ let { buffer, byteOffset, byteLength } = bytes;
202
+ return Buffer.from(buffer, byteOffset, byteLength).toString();
203
+ };
204
+ encodeInvariant = 'Buffer.from("")';
205
+ } else {
206
+ throw new Error("No UTF-8 codec found");
207
+ }
208
+ if (!(encodeUTF8("") instanceof Uint8Array))
209
+ throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false
210
+
211
+ This indicates that your JavaScript environment is broken. You cannot use
212
+ esbuild in this environment because esbuild relies on this invariant. This
213
+ is not a problem with esbuild. You need to fix your environment instead.
214
+ `);
215
+ function readUInt32LE(buffer, offset) {
216
+ return buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24;
217
+ }
218
+ function writeUInt32LE(buffer, value, offset) {
219
+ buffer[offset++] = value;
220
+ buffer[offset++] = value >> 8;
221
+ buffer[offset++] = value >> 16;
222
+ buffer[offset++] = value >> 24;
223
+ }
224
+ var quote = JSON.stringify;
225
+ var buildLogLevelDefault = "warning";
226
+ var transformLogLevelDefault = "silent";
227
+ function validateAndJoinStringArray(values, what) {
228
+ const toJoin = [];
229
+ for (const value of values) {
230
+ validateStringValue(value, what);
231
+ if (value.indexOf(",") >= 0)
232
+ throw new Error(`Invalid ${what}: ${value}`);
233
+ toJoin.push(value);
234
+ }
235
+ return toJoin.join(",");
236
+ }
237
+ var canBeAnything = () => null;
238
+ var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
239
+ var mustBeString = (value) => typeof value === "string" ? null : "a string";
240
+ var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
241
+ var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
242
+ var mustBeValidPortNumber = (value) => typeof value === "number" && value === (value | 0) && value >= 0 && value <= 65535 ? null : "a valid port number";
243
+ var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
244
+ var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
245
+ var mustBeArrayOfStrings = (value) => Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "an array of strings";
246
+ var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
247
+ var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
248
+ var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
249
+ var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
250
+ var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
251
+ var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
252
+ var mustBeStringOrArrayOfStrings = (value) => typeof value === "string" || Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "a string or an array of strings";
253
+ var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
254
+ var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL";
255
+ function getFlag(object, keys, key, mustBeFn) {
256
+ let value = object[key];
257
+ keys[key + ""] = true;
258
+ if (value === undefined)
259
+ return;
260
+ let mustBe = mustBeFn(value);
261
+ if (mustBe !== null)
262
+ throw new Error(`${quote(key)} must be ${mustBe}`);
263
+ return value;
264
+ }
265
+ function checkForInvalidFlags(object, keys, where) {
266
+ for (let key in object) {
267
+ if (!(key in keys)) {
268
+ throw new Error(`Invalid option ${where}: ${quote(key)}`);
269
+ }
270
+ }
271
+ }
272
+ function validateInitializeOptions(options) {
273
+ let keys = /* @__PURE__ */ Object.create(null);
274
+ let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL);
275
+ let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule);
276
+ let worker = getFlag(options, keys, "worker", mustBeBoolean);
277
+ checkForInvalidFlags(options, keys, "in initialize() call");
278
+ return {
279
+ wasmURL,
280
+ wasmModule,
281
+ worker
282
+ };
283
+ }
284
+ function validateMangleCache(mangleCache) {
285
+ let validated;
286
+ if (mangleCache !== undefined) {
287
+ validated = /* @__PURE__ */ Object.create(null);
288
+ for (let key in mangleCache) {
289
+ let value = mangleCache[key];
290
+ if (typeof value === "string" || value === false) {
291
+ validated[key] = value;
292
+ } else {
293
+ throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`);
294
+ }
295
+ }
296
+ }
297
+ return validated;
298
+ }
299
+ function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) {
300
+ let color = getFlag(options, keys, "color", mustBeBoolean);
301
+ let logLevel = getFlag(options, keys, "logLevel", mustBeString);
302
+ let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
303
+ if (color !== undefined)
304
+ flags.push(`--color=${color}`);
305
+ else if (isTTY2)
306
+ flags.push(`--color=true`);
307
+ flags.push(`--log-level=${logLevel || logLevelDefault}`);
308
+ flags.push(`--log-limit=${logLimit || 0}`);
309
+ }
310
+ function validateStringValue(value, what, key) {
311
+ if (typeof value !== "string") {
312
+ throw new Error(`Expected value for ${what}${key !== undefined ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`);
313
+ }
314
+ return value;
315
+ }
316
+ function pushCommonFlags(flags, options, keys) {
317
+ let legalComments = getFlag(options, keys, "legalComments", mustBeString);
318
+ let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
319
+ let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
320
+ let target = getFlag(options, keys, "target", mustBeStringOrArrayOfStrings);
321
+ let format = getFlag(options, keys, "format", mustBeString);
322
+ let globalName = getFlag(options, keys, "globalName", mustBeString);
323
+ let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp);
324
+ let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp);
325
+ let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean);
326
+ let minify = getFlag(options, keys, "minify", mustBeBoolean);
327
+ let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
328
+ let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
329
+ let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
330
+ let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger);
331
+ let drop = getFlag(options, keys, "drop", mustBeArrayOfStrings);
332
+ let dropLabels = getFlag(options, keys, "dropLabels", mustBeArrayOfStrings);
333
+ let charset = getFlag(options, keys, "charset", mustBeString);
334
+ let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
335
+ let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
336
+ let jsx = getFlag(options, keys, "jsx", mustBeString);
337
+ let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
338
+ let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
339
+ let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString);
340
+ let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean);
341
+ let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean);
342
+ let define = getFlag(options, keys, "define", mustBeObject);
343
+ let logOverride = getFlag(options, keys, "logOverride", mustBeObject);
344
+ let supported = getFlag(options, keys, "supported", mustBeObject);
345
+ let pure = getFlag(options, keys, "pure", mustBeArrayOfStrings);
346
+ let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
347
+ let platform = getFlag(options, keys, "platform", mustBeString);
348
+ let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
349
+ let absPaths = getFlag(options, keys, "absPaths", mustBeArrayOfStrings);
350
+ if (legalComments)
351
+ flags.push(`--legal-comments=${legalComments}`);
352
+ if (sourceRoot !== undefined)
353
+ flags.push(`--source-root=${sourceRoot}`);
354
+ if (sourcesContent !== undefined)
355
+ flags.push(`--sources-content=${sourcesContent}`);
356
+ if (target)
357
+ flags.push(`--target=${validateAndJoinStringArray(Array.isArray(target) ? target : [target], "target")}`);
358
+ if (format)
359
+ flags.push(`--format=${format}`);
360
+ if (globalName)
361
+ flags.push(`--global-name=${globalName}`);
362
+ if (platform)
363
+ flags.push(`--platform=${platform}`);
364
+ if (tsconfigRaw)
365
+ flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
366
+ if (minify)
367
+ flags.push("--minify");
368
+ if (minifySyntax)
369
+ flags.push("--minify-syntax");
370
+ if (minifyWhitespace)
371
+ flags.push("--minify-whitespace");
372
+ if (minifyIdentifiers)
373
+ flags.push("--minify-identifiers");
374
+ if (lineLimit)
375
+ flags.push(`--line-limit=${lineLimit}`);
376
+ if (charset)
377
+ flags.push(`--charset=${charset}`);
378
+ if (treeShaking !== undefined)
379
+ flags.push(`--tree-shaking=${treeShaking}`);
380
+ if (ignoreAnnotations)
381
+ flags.push(`--ignore-annotations`);
382
+ if (drop)
383
+ for (let what of drop)
384
+ flags.push(`--drop:${validateStringValue(what, "drop")}`);
385
+ if (dropLabels)
386
+ flags.push(`--drop-labels=${validateAndJoinStringArray(dropLabels, "drop label")}`);
387
+ if (absPaths)
388
+ flags.push(`--abs-paths=${validateAndJoinStringArray(absPaths, "abs paths")}`);
389
+ if (mangleProps)
390
+ flags.push(`--mangle-props=${jsRegExpToGoRegExp(mangleProps)}`);
391
+ if (reserveProps)
392
+ flags.push(`--reserve-props=${jsRegExpToGoRegExp(reserveProps)}`);
393
+ if (mangleQuoted !== undefined)
394
+ flags.push(`--mangle-quoted=${mangleQuoted}`);
395
+ if (jsx)
396
+ flags.push(`--jsx=${jsx}`);
397
+ if (jsxFactory)
398
+ flags.push(`--jsx-factory=${jsxFactory}`);
399
+ if (jsxFragment)
400
+ flags.push(`--jsx-fragment=${jsxFragment}`);
401
+ if (jsxImportSource)
402
+ flags.push(`--jsx-import-source=${jsxImportSource}`);
403
+ if (jsxDev)
404
+ flags.push(`--jsx-dev`);
405
+ if (jsxSideEffects)
406
+ flags.push(`--jsx-side-effects`);
407
+ if (define) {
408
+ for (let key in define) {
409
+ if (key.indexOf("=") >= 0)
410
+ throw new Error(`Invalid define: ${key}`);
411
+ flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`);
412
+ }
413
+ }
414
+ if (logOverride) {
415
+ for (let key in logOverride) {
416
+ if (key.indexOf("=") >= 0)
417
+ throw new Error(`Invalid log override: ${key}`);
418
+ flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`);
419
+ }
420
+ }
421
+ if (supported) {
422
+ for (let key in supported) {
423
+ if (key.indexOf("=") >= 0)
424
+ throw new Error(`Invalid supported: ${key}`);
425
+ const value = supported[key];
426
+ if (typeof value !== "boolean")
427
+ throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`);
428
+ flags.push(`--supported:${key}=${value}`);
429
+ }
430
+ }
431
+ if (pure)
432
+ for (let fn of pure)
433
+ flags.push(`--pure:${validateStringValue(fn, "pure")}`);
434
+ if (keepNames)
435
+ flags.push(`--keep-names`);
436
+ }
437
+ function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) {
438
+ var _a2;
439
+ let flags = [];
440
+ let entries = [];
441
+ let keys = /* @__PURE__ */ Object.create(null);
442
+ let stdinContents = null;
443
+ let stdinResolveDir = null;
444
+ pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
445
+ pushCommonFlags(flags, options, keys);
446
+ let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
447
+ let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
448
+ let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
449
+ let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
450
+ let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
451
+ let outfile = getFlag(options, keys, "outfile", mustBeString);
452
+ let outdir = getFlag(options, keys, "outdir", mustBeString);
453
+ let outbase = getFlag(options, keys, "outbase", mustBeString);
454
+ let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
455
+ let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArrayOfStrings);
456
+ let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArrayOfStrings);
457
+ let mainFields = getFlag(options, keys, "mainFields", mustBeArrayOfStrings);
458
+ let conditions = getFlag(options, keys, "conditions", mustBeArrayOfStrings);
459
+ let external = getFlag(options, keys, "external", mustBeArrayOfStrings);
460
+ let packages = getFlag(options, keys, "packages", mustBeString);
461
+ let alias = getFlag(options, keys, "alias", mustBeObject);
462
+ let loader = getFlag(options, keys, "loader", mustBeObject);
463
+ let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
464
+ let publicPath = getFlag(options, keys, "publicPath", mustBeString);
465
+ let entryNames = getFlag(options, keys, "entryNames", mustBeString);
466
+ let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
467
+ let assetNames = getFlag(options, keys, "assetNames", mustBeString);
468
+ let inject = getFlag(options, keys, "inject", mustBeArrayOfStrings);
469
+ let banner = getFlag(options, keys, "banner", mustBeObject);
470
+ let footer = getFlag(options, keys, "footer", mustBeObject);
471
+ let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints);
472
+ let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
473
+ let stdin = getFlag(options, keys, "stdin", mustBeObject);
474
+ let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault;
475
+ let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
476
+ let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
477
+ keys.plugins = true;
478
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
479
+ if (sourcemap)
480
+ flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
481
+ if (bundle)
482
+ flags.push("--bundle");
483
+ if (allowOverwrite)
484
+ flags.push("--allow-overwrite");
485
+ if (splitting)
486
+ flags.push("--splitting");
487
+ if (preserveSymlinks)
488
+ flags.push("--preserve-symlinks");
489
+ if (metafile)
490
+ flags.push(`--metafile`);
491
+ if (outfile)
492
+ flags.push(`--outfile=${outfile}`);
493
+ if (outdir)
494
+ flags.push(`--outdir=${outdir}`);
495
+ if (outbase)
496
+ flags.push(`--outbase=${outbase}`);
497
+ if (tsconfig)
498
+ flags.push(`--tsconfig=${tsconfig}`);
499
+ if (packages)
500
+ flags.push(`--packages=${packages}`);
501
+ if (resolveExtensions)
502
+ flags.push(`--resolve-extensions=${validateAndJoinStringArray(resolveExtensions, "resolve extension")}`);
503
+ if (publicPath)
504
+ flags.push(`--public-path=${publicPath}`);
505
+ if (entryNames)
506
+ flags.push(`--entry-names=${entryNames}`);
507
+ if (chunkNames)
508
+ flags.push(`--chunk-names=${chunkNames}`);
509
+ if (assetNames)
510
+ flags.push(`--asset-names=${assetNames}`);
511
+ if (mainFields)
512
+ flags.push(`--main-fields=${validateAndJoinStringArray(mainFields, "main field")}`);
513
+ if (conditions)
514
+ flags.push(`--conditions=${validateAndJoinStringArray(conditions, "condition")}`);
515
+ if (external)
516
+ for (let name of external)
517
+ flags.push(`--external:${validateStringValue(name, "external")}`);
518
+ if (alias) {
519
+ for (let old in alias) {
520
+ if (old.indexOf("=") >= 0)
521
+ throw new Error(`Invalid package name in alias: ${old}`);
522
+ flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`);
523
+ }
524
+ }
525
+ if (banner) {
526
+ for (let type in banner) {
527
+ if (type.indexOf("=") >= 0)
528
+ throw new Error(`Invalid banner file type: ${type}`);
529
+ flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`);
530
+ }
531
+ }
532
+ if (footer) {
533
+ for (let type in footer) {
534
+ if (type.indexOf("=") >= 0)
535
+ throw new Error(`Invalid footer file type: ${type}`);
536
+ flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`);
537
+ }
538
+ }
539
+ if (inject)
540
+ for (let path3 of inject)
541
+ flags.push(`--inject:${validateStringValue(path3, "inject")}`);
542
+ if (loader) {
543
+ for (let ext in loader) {
544
+ if (ext.indexOf("=") >= 0)
545
+ throw new Error(`Invalid loader extension: ${ext}`);
546
+ flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`);
547
+ }
548
+ }
549
+ if (outExtension) {
550
+ for (let ext in outExtension) {
551
+ if (ext.indexOf("=") >= 0)
552
+ throw new Error(`Invalid out extension: ${ext}`);
553
+ flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
554
+ }
555
+ }
556
+ if (entryPoints) {
557
+ if (Array.isArray(entryPoints)) {
558
+ for (let i = 0, n = entryPoints.length;i < n; i++) {
559
+ let entryPoint = entryPoints[i];
560
+ if (typeof entryPoint === "object" && entryPoint !== null) {
561
+ let entryPointKeys = /* @__PURE__ */ Object.create(null);
562
+ let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
563
+ let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
564
+ checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
565
+ if (input === undefined)
566
+ throw new Error('Missing property "in" for entry point at index ' + i);
567
+ if (output === undefined)
568
+ throw new Error('Missing property "out" for entry point at index ' + i);
569
+ entries.push([output, input]);
570
+ } else {
571
+ entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
572
+ }
573
+ }
574
+ } else {
575
+ for (let key in entryPoints) {
576
+ entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
577
+ }
578
+ }
579
+ }
580
+ if (stdin) {
581
+ let stdinKeys = /* @__PURE__ */ Object.create(null);
582
+ let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
583
+ let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
584
+ let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
585
+ let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
586
+ checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object');
587
+ if (sourcefile)
588
+ flags.push(`--sourcefile=${sourcefile}`);
589
+ if (loader2)
590
+ flags.push(`--loader=${loader2}`);
591
+ if (resolveDir)
592
+ stdinResolveDir = resolveDir;
593
+ if (typeof contents === "string")
594
+ stdinContents = encodeUTF8(contents);
595
+ else if (contents instanceof Uint8Array)
596
+ stdinContents = contents;
597
+ }
598
+ let nodePaths = [];
599
+ if (nodePathsInput) {
600
+ for (let value of nodePathsInput) {
601
+ value += "";
602
+ nodePaths.push(value);
603
+ }
604
+ }
605
+ return {
606
+ entries,
607
+ flags,
608
+ write,
609
+ stdinContents,
610
+ stdinResolveDir,
611
+ absWorkingDir,
612
+ nodePaths,
613
+ mangleCache: validateMangleCache(mangleCache)
614
+ };
615
+ }
616
+ function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) {
617
+ let flags = [];
618
+ let keys = /* @__PURE__ */ Object.create(null);
619
+ pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
620
+ pushCommonFlags(flags, options, keys);
621
+ let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
622
+ let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
623
+ let loader = getFlag(options, keys, "loader", mustBeString);
624
+ let banner = getFlag(options, keys, "banner", mustBeString);
625
+ let footer = getFlag(options, keys, "footer", mustBeString);
626
+ let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
627
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
628
+ if (sourcemap)
629
+ flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
630
+ if (sourcefile)
631
+ flags.push(`--sourcefile=${sourcefile}`);
632
+ if (loader)
633
+ flags.push(`--loader=${loader}`);
634
+ if (banner)
635
+ flags.push(`--banner=${banner}`);
636
+ if (footer)
637
+ flags.push(`--footer=${footer}`);
638
+ return {
639
+ flags,
640
+ mangleCache: validateMangleCache(mangleCache)
641
+ };
642
+ }
643
+ function createChannel(streamIn) {
644
+ const requestCallbacksByKey = {};
645
+ const closeData = { didClose: false, reason: "" };
646
+ let responseCallbacks = {};
647
+ let nextRequestID = 0;
648
+ let nextBuildKey = 0;
649
+ let stdout = new Uint8Array(16 * 1024);
650
+ let stdoutUsed = 0;
651
+ let readFromStdout = (chunk) => {
652
+ let limit = stdoutUsed + chunk.length;
653
+ if (limit > stdout.length) {
654
+ let swap = new Uint8Array(limit * 2);
655
+ swap.set(stdout);
656
+ stdout = swap;
657
+ }
658
+ stdout.set(chunk, stdoutUsed);
659
+ stdoutUsed += chunk.length;
660
+ let offset = 0;
661
+ while (offset + 4 <= stdoutUsed) {
662
+ let length = readUInt32LE(stdout, offset);
663
+ if (offset + 4 + length > stdoutUsed) {
664
+ break;
665
+ }
666
+ offset += 4;
667
+ handleIncomingPacket(stdout.subarray(offset, offset + length));
668
+ offset += length;
669
+ }
670
+ if (offset > 0) {
671
+ stdout.copyWithin(0, offset, stdoutUsed);
672
+ stdoutUsed -= offset;
673
+ }
674
+ };
675
+ let afterClose = (error) => {
676
+ closeData.didClose = true;
677
+ if (error)
678
+ closeData.reason = ": " + (error.message || error);
679
+ const text = "The service was stopped" + closeData.reason;
680
+ for (let id in responseCallbacks) {
681
+ responseCallbacks[id](text, null);
682
+ }
683
+ responseCallbacks = {};
684
+ };
685
+ let sendRequest = (refs, value, callback) => {
686
+ if (closeData.didClose)
687
+ return callback("The service is no longer running" + closeData.reason, null);
688
+ let id = nextRequestID++;
689
+ responseCallbacks[id] = (error, response) => {
690
+ try {
691
+ callback(error, response);
692
+ } finally {
693
+ if (refs)
694
+ refs.unref();
695
+ }
696
+ };
697
+ if (refs)
698
+ refs.ref();
699
+ streamIn.writeToStdin(encodePacket({ id, isRequest: true, value }));
700
+ };
701
+ let sendResponse = (id, value) => {
702
+ if (closeData.didClose)
703
+ throw new Error("The service is no longer running" + closeData.reason);
704
+ streamIn.writeToStdin(encodePacket({ id, isRequest: false, value }));
705
+ };
706
+ let handleRequest = async (id, request) => {
707
+ try {
708
+ if (request.command === "ping") {
709
+ sendResponse(id, {});
710
+ return;
711
+ }
712
+ if (typeof request.key === "number") {
713
+ const requestCallbacks = requestCallbacksByKey[request.key];
714
+ if (!requestCallbacks) {
715
+ return;
716
+ }
717
+ const callback = requestCallbacks[request.command];
718
+ if (callback) {
719
+ await callback(id, request);
720
+ return;
721
+ }
722
+ }
723
+ throw new Error(`Invalid command: ` + request.command);
724
+ } catch (e) {
725
+ const errors = [extractErrorMessageV8(e, streamIn, null, undefined, "")];
726
+ try {
727
+ sendResponse(id, { errors });
728
+ } catch {}
729
+ }
730
+ };
731
+ let isFirstPacket = true;
732
+ let handleIncomingPacket = (bytes) => {
733
+ if (isFirstPacket) {
734
+ isFirstPacket = false;
735
+ let binaryVersion = String.fromCharCode(...bytes);
736
+ if (binaryVersion !== "0.27.3") {
737
+ throw new Error(`Cannot start service: Host version "${"0.27.3"}" does not match binary version ${quote(binaryVersion)}`);
738
+ }
739
+ return;
740
+ }
741
+ let packet = decodePacket(bytes);
742
+ if (packet.isRequest) {
743
+ handleRequest(packet.id, packet.value);
744
+ } else {
745
+ let callback = responseCallbacks[packet.id];
746
+ delete responseCallbacks[packet.id];
747
+ if (packet.value.error)
748
+ callback(packet.value.error, {});
749
+ else
750
+ callback(null, packet.value);
751
+ }
752
+ };
753
+ let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => {
754
+ let refCount = 0;
755
+ const buildKey = nextBuildKey++;
756
+ const requestCallbacks = {};
757
+ const buildRefs = {
758
+ ref() {
759
+ if (++refCount === 1) {
760
+ if (refs)
761
+ refs.ref();
762
+ }
763
+ },
764
+ unref() {
765
+ if (--refCount === 0) {
766
+ delete requestCallbacksByKey[buildKey];
767
+ if (refs)
768
+ refs.unref();
769
+ }
770
+ }
771
+ };
772
+ requestCallbacksByKey[buildKey] = requestCallbacks;
773
+ buildRefs.ref();
774
+ buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, buildRefs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, (err, res) => {
775
+ try {
776
+ callback(err, res);
777
+ } finally {
778
+ buildRefs.unref();
779
+ }
780
+ });
781
+ };
782
+ let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => {
783
+ const details = createObjectStash();
784
+ let start = (inputPath) => {
785
+ try {
786
+ if (typeof input !== "string" && !(input instanceof Uint8Array))
787
+ throw new Error('The input to "transform" must be a string or a Uint8Array');
788
+ let {
789
+ flags,
790
+ mangleCache
791
+ } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault);
792
+ let request = {
793
+ command: "transform",
794
+ flags,
795
+ inputFS: inputPath !== null,
796
+ input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input
797
+ };
798
+ if (mangleCache)
799
+ request.mangleCache = mangleCache;
800
+ sendRequest(refs, request, (error, response) => {
801
+ if (error)
802
+ return callback(new Error(error), null);
803
+ let errors = replaceDetailsInMessages(response.errors, details);
804
+ let warnings = replaceDetailsInMessages(response.warnings, details);
805
+ let outstanding = 1;
806
+ let next = () => {
807
+ if (--outstanding === 0) {
808
+ let result = {
809
+ warnings,
810
+ code: response.code,
811
+ map: response.map,
812
+ mangleCache: undefined,
813
+ legalComments: undefined
814
+ };
815
+ if ("legalComments" in response)
816
+ result.legalComments = response == null ? undefined : response.legalComments;
817
+ if (response.mangleCache)
818
+ result.mangleCache = response == null ? undefined : response.mangleCache;
819
+ callback(null, result);
820
+ }
821
+ };
822
+ if (errors.length > 0)
823
+ return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
824
+ if (response.codeFS) {
825
+ outstanding++;
826
+ fs3.readFile(response.code, (err, contents) => {
827
+ if (err !== null) {
828
+ callback(err, null);
829
+ } else {
830
+ response.code = contents;
831
+ next();
832
+ }
833
+ });
834
+ }
835
+ if (response.mapFS) {
836
+ outstanding++;
837
+ fs3.readFile(response.map, (err, contents) => {
838
+ if (err !== null) {
839
+ callback(err, null);
840
+ } else {
841
+ response.map = contents;
842
+ next();
843
+ }
844
+ });
845
+ }
846
+ next();
847
+ });
848
+ } catch (e) {
849
+ let flags = [];
850
+ try {
851
+ pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault);
852
+ } catch {}
853
+ const error = extractErrorMessageV8(e, streamIn, details, undefined, "");
854
+ sendRequest(refs, { command: "error", flags, error }, () => {
855
+ error.detail = details.load(error.detail);
856
+ callback(failureErrorWithLog("Transform failed", [error], []), null);
857
+ });
858
+ }
859
+ };
860
+ if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) {
861
+ let next = start;
862
+ start = () => fs3.writeFile(input, next);
863
+ }
864
+ start(null);
865
+ };
866
+ let formatMessages2 = ({ callName, refs, messages, options, callback }) => {
867
+ if (!options)
868
+ throw new Error(`Missing second argument in ${callName}() call`);
869
+ let keys = {};
870
+ let kind = getFlag(options, keys, "kind", mustBeString);
871
+ let color = getFlag(options, keys, "color", mustBeBoolean);
872
+ let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
873
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
874
+ if (kind === undefined)
875
+ throw new Error(`Missing "kind" in ${callName}() call`);
876
+ if (kind !== "error" && kind !== "warning")
877
+ throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
878
+ let request = {
879
+ command: "format-msgs",
880
+ messages: sanitizeMessages(messages, "messages", null, "", terminalWidth),
881
+ isWarning: kind === "warning"
882
+ };
883
+ if (color !== undefined)
884
+ request.color = color;
885
+ if (terminalWidth !== undefined)
886
+ request.terminalWidth = terminalWidth;
887
+ sendRequest(refs, request, (error, response) => {
888
+ if (error)
889
+ return callback(new Error(error), null);
890
+ callback(null, response.messages);
891
+ });
892
+ };
893
+ let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => {
894
+ if (options === undefined)
895
+ options = {};
896
+ let keys = {};
897
+ let color = getFlag(options, keys, "color", mustBeBoolean);
898
+ let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
899
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
900
+ let request = {
901
+ command: "analyze-metafile",
902
+ metafile
903
+ };
904
+ if (color !== undefined)
905
+ request.color = color;
906
+ if (verbose !== undefined)
907
+ request.verbose = verbose;
908
+ sendRequest(refs, request, (error, response) => {
909
+ if (error)
910
+ return callback(new Error(error), null);
911
+ callback(null, response.result);
912
+ });
913
+ };
914
+ return {
915
+ readFromStdout,
916
+ afterClose,
917
+ service: {
918
+ buildOrContext,
919
+ transform: transform2,
920
+ formatMessages: formatMessages2,
921
+ analyzeMetafile: analyzeMetafile2
922
+ }
923
+ };
924
+ }
925
+ function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) {
926
+ const details = createObjectStash();
927
+ const isContext = callName === "context";
928
+ const handleError = (e, pluginName) => {
929
+ const flags = [];
930
+ try {
931
+ pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault);
932
+ } catch {}
933
+ const message = extractErrorMessageV8(e, streamIn, details, undefined, pluginName);
934
+ sendRequest(refs, { command: "error", flags, error: message }, () => {
935
+ message.detail = details.load(message.detail);
936
+ callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
937
+ });
938
+ };
939
+ let plugins;
940
+ if (typeof options === "object") {
941
+ const value = options.plugins;
942
+ if (value !== undefined) {
943
+ if (!Array.isArray(value))
944
+ return handleError(new Error(`"plugins" must be an array`), "");
945
+ plugins = value;
946
+ }
947
+ }
948
+ if (plugins && plugins.length > 0) {
949
+ if (streamIn.isSync)
950
+ return handleError(new Error("Cannot use plugins in synchronous API calls"), "");
951
+ handlePlugins(buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, plugins, details).then((result) => {
952
+ if (!result.ok)
953
+ return handleError(result.error, result.pluginName);
954
+ try {
955
+ buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
956
+ } catch (e) {
957
+ handleError(e, "");
958
+ }
959
+ }, (e) => handleError(e, ""));
960
+ return;
961
+ }
962
+ try {
963
+ buildOrContextContinue(null, (result, done) => done([], []), () => {});
964
+ } catch (e) {
965
+ handleError(e, "");
966
+ }
967
+ function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
968
+ const writeDefault = streamIn.hasFS;
969
+ const {
970
+ entries,
971
+ flags,
972
+ write,
973
+ stdinContents,
974
+ stdinResolveDir,
975
+ absWorkingDir,
976
+ nodePaths,
977
+ mangleCache
978
+ } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault);
979
+ if (write && !streamIn.hasFS)
980
+ throw new Error(`The "write" option is unavailable in this environment`);
981
+ const request = {
982
+ command: "build",
983
+ key: buildKey,
984
+ entries,
985
+ flags,
986
+ write,
987
+ stdinContents,
988
+ stdinResolveDir,
989
+ absWorkingDir: absWorkingDir || defaultWD2,
990
+ nodePaths,
991
+ context: isContext
992
+ };
993
+ if (requestPlugins)
994
+ request.plugins = requestPlugins;
995
+ if (mangleCache)
996
+ request.mangleCache = mangleCache;
997
+ const buildResponseToResult = (response, callback2) => {
998
+ const result = {
999
+ errors: replaceDetailsInMessages(response.errors, details),
1000
+ warnings: replaceDetailsInMessages(response.warnings, details),
1001
+ outputFiles: undefined,
1002
+ metafile: undefined,
1003
+ mangleCache: undefined
1004
+ };
1005
+ const originalErrors = result.errors.slice();
1006
+ const originalWarnings = result.warnings.slice();
1007
+ if (response.outputFiles)
1008
+ result.outputFiles = response.outputFiles.map(convertOutputFiles);
1009
+ if (response.metafile)
1010
+ result.metafile = JSON.parse(response.metafile);
1011
+ if (response.mangleCache)
1012
+ result.mangleCache = response.mangleCache;
1013
+ if (response.writeToStdout !== undefined)
1014
+ console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
1015
+ runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
1016
+ if (originalErrors.length > 0 || onEndErrors.length > 0) {
1017
+ const error = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings));
1018
+ return callback2(error, null, onEndErrors, onEndWarnings);
1019
+ }
1020
+ callback2(null, result, onEndErrors, onEndWarnings);
1021
+ });
1022
+ };
1023
+ let latestResultPromise;
1024
+ let provideLatestResult;
1025
+ if (isContext)
1026
+ requestCallbacks["on-end"] = (id, request2) => new Promise((resolve2) => {
1027
+ buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => {
1028
+ const response = {
1029
+ errors: onEndErrors,
1030
+ warnings: onEndWarnings
1031
+ };
1032
+ if (provideLatestResult)
1033
+ provideLatestResult(err, result);
1034
+ latestResultPromise = undefined;
1035
+ provideLatestResult = undefined;
1036
+ sendResponse(id, response);
1037
+ resolve2();
1038
+ });
1039
+ });
1040
+ sendRequest(refs, request, (error, response) => {
1041
+ if (error)
1042
+ return callback(new Error(error), null);
1043
+ if (!isContext) {
1044
+ return buildResponseToResult(response, (err, res) => {
1045
+ scheduleOnDisposeCallbacks();
1046
+ return callback(err, res);
1047
+ });
1048
+ }
1049
+ if (response.errors.length > 0) {
1050
+ return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
1051
+ }
1052
+ let didDispose = false;
1053
+ const result = {
1054
+ rebuild: () => {
1055
+ if (!latestResultPromise)
1056
+ latestResultPromise = new Promise((resolve2, reject) => {
1057
+ let settlePromise;
1058
+ provideLatestResult = (err, result2) => {
1059
+ if (!settlePromise)
1060
+ settlePromise = () => err ? reject(err) : resolve2(result2);
1061
+ };
1062
+ const triggerAnotherBuild = () => {
1063
+ const request2 = {
1064
+ command: "rebuild",
1065
+ key: buildKey
1066
+ };
1067
+ sendRequest(refs, request2, (error2, response2) => {
1068
+ if (error2) {
1069
+ reject(new Error(error2));
1070
+ } else if (settlePromise) {
1071
+ settlePromise();
1072
+ } else {
1073
+ triggerAnotherBuild();
1074
+ }
1075
+ });
1076
+ };
1077
+ triggerAnotherBuild();
1078
+ });
1079
+ return latestResultPromise;
1080
+ },
1081
+ watch: (options2 = {}) => new Promise((resolve2, reject) => {
1082
+ if (!streamIn.hasFS)
1083
+ throw new Error(`Cannot use the "watch" API in this environment`);
1084
+ const keys = {};
1085
+ const delay = getFlag(options2, keys, "delay", mustBeInteger);
1086
+ checkForInvalidFlags(options2, keys, `in watch() call`);
1087
+ const request2 = {
1088
+ command: "watch",
1089
+ key: buildKey
1090
+ };
1091
+ if (delay)
1092
+ request2.delay = delay;
1093
+ sendRequest(refs, request2, (error2) => {
1094
+ if (error2)
1095
+ reject(new Error(error2));
1096
+ else
1097
+ resolve2(undefined);
1098
+ });
1099
+ }),
1100
+ serve: (options2 = {}) => new Promise((resolve2, reject) => {
1101
+ if (!streamIn.hasFS)
1102
+ throw new Error(`Cannot use the "serve" API in this environment`);
1103
+ const keys = {};
1104
+ const port = getFlag(options2, keys, "port", mustBeValidPortNumber);
1105
+ const host = getFlag(options2, keys, "host", mustBeString);
1106
+ const servedir = getFlag(options2, keys, "servedir", mustBeString);
1107
+ const keyfile = getFlag(options2, keys, "keyfile", mustBeString);
1108
+ const certfile = getFlag(options2, keys, "certfile", mustBeString);
1109
+ const fallback = getFlag(options2, keys, "fallback", mustBeString);
1110
+ const cors = getFlag(options2, keys, "cors", mustBeObject);
1111
+ const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction);
1112
+ checkForInvalidFlags(options2, keys, `in serve() call`);
1113
+ const request2 = {
1114
+ command: "serve",
1115
+ key: buildKey,
1116
+ onRequest: !!onRequest
1117
+ };
1118
+ if (port !== undefined)
1119
+ request2.port = port;
1120
+ if (host !== undefined)
1121
+ request2.host = host;
1122
+ if (servedir !== undefined)
1123
+ request2.servedir = servedir;
1124
+ if (keyfile !== undefined)
1125
+ request2.keyfile = keyfile;
1126
+ if (certfile !== undefined)
1127
+ request2.certfile = certfile;
1128
+ if (fallback !== undefined)
1129
+ request2.fallback = fallback;
1130
+ if (cors) {
1131
+ const corsKeys = {};
1132
+ const origin = getFlag(cors, corsKeys, "origin", mustBeStringOrArrayOfStrings);
1133
+ checkForInvalidFlags(cors, corsKeys, `on "cors" object`);
1134
+ if (Array.isArray(origin))
1135
+ request2.corsOrigin = origin;
1136
+ else if (origin !== undefined)
1137
+ request2.corsOrigin = [origin];
1138
+ }
1139
+ sendRequest(refs, request2, (error2, response2) => {
1140
+ if (error2)
1141
+ return reject(new Error(error2));
1142
+ if (onRequest) {
1143
+ requestCallbacks["serve-request"] = (id, request3) => {
1144
+ onRequest(request3.args);
1145
+ sendResponse(id, {});
1146
+ };
1147
+ }
1148
+ resolve2(response2);
1149
+ });
1150
+ }),
1151
+ cancel: () => new Promise((resolve2) => {
1152
+ if (didDispose)
1153
+ return resolve2();
1154
+ const request2 = {
1155
+ command: "cancel",
1156
+ key: buildKey
1157
+ };
1158
+ sendRequest(refs, request2, () => {
1159
+ resolve2();
1160
+ });
1161
+ }),
1162
+ dispose: () => new Promise((resolve2) => {
1163
+ if (didDispose)
1164
+ return resolve2();
1165
+ didDispose = true;
1166
+ const request2 = {
1167
+ command: "dispose",
1168
+ key: buildKey
1169
+ };
1170
+ sendRequest(refs, request2, () => {
1171
+ resolve2();
1172
+ scheduleOnDisposeCallbacks();
1173
+ refs.unref();
1174
+ });
1175
+ })
1176
+ };
1177
+ refs.ref();
1178
+ callback(null, result);
1179
+ });
1180
+ }
1181
+ }
1182
+ var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => {
1183
+ let onStartCallbacks = [];
1184
+ let onEndCallbacks = [];
1185
+ let onResolveCallbacks = {};
1186
+ let onLoadCallbacks = {};
1187
+ let onDisposeCallbacks = [];
1188
+ let nextCallbackID = 0;
1189
+ let i = 0;
1190
+ let requestPlugins = [];
1191
+ let isSetupDone = false;
1192
+ plugins = [...plugins];
1193
+ for (let item of plugins) {
1194
+ let keys = {};
1195
+ if (typeof item !== "object")
1196
+ throw new Error(`Plugin at index ${i} must be an object`);
1197
+ const name = getFlag(item, keys, "name", mustBeString);
1198
+ if (typeof name !== "string" || name === "")
1199
+ throw new Error(`Plugin at index ${i} is missing a name`);
1200
+ try {
1201
+ let setup = getFlag(item, keys, "setup", mustBeFunction);
1202
+ if (typeof setup !== "function")
1203
+ throw new Error(`Plugin is missing a setup function`);
1204
+ checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`);
1205
+ let plugin = {
1206
+ name,
1207
+ onStart: false,
1208
+ onEnd: false,
1209
+ onResolve: [],
1210
+ onLoad: []
1211
+ };
1212
+ i++;
1213
+ let resolve2 = (path3, options = {}) => {
1214
+ if (!isSetupDone)
1215
+ throw new Error('Cannot call "resolve" before plugin setup has completed');
1216
+ if (typeof path3 !== "string")
1217
+ throw new Error(`The path to resolve must be a string`);
1218
+ let keys2 = /* @__PURE__ */ Object.create(null);
1219
+ let pluginName = getFlag(options, keys2, "pluginName", mustBeString);
1220
+ let importer = getFlag(options, keys2, "importer", mustBeString);
1221
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1222
+ let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString);
1223
+ let kind = getFlag(options, keys2, "kind", mustBeString);
1224
+ let pluginData = getFlag(options, keys2, "pluginData", canBeAnything);
1225
+ let importAttributes = getFlag(options, keys2, "with", mustBeObject);
1226
+ checkForInvalidFlags(options, keys2, "in resolve() call");
1227
+ return new Promise((resolve22, reject) => {
1228
+ const request = {
1229
+ command: "resolve",
1230
+ path: path3,
1231
+ key: buildKey,
1232
+ pluginName: name
1233
+ };
1234
+ if (pluginName != null)
1235
+ request.pluginName = pluginName;
1236
+ if (importer != null)
1237
+ request.importer = importer;
1238
+ if (namespace != null)
1239
+ request.namespace = namespace;
1240
+ if (resolveDir != null)
1241
+ request.resolveDir = resolveDir;
1242
+ if (kind != null)
1243
+ request.kind = kind;
1244
+ else
1245
+ throw new Error(`Must specify "kind" when calling "resolve"`);
1246
+ if (pluginData != null)
1247
+ request.pluginData = details.store(pluginData);
1248
+ if (importAttributes != null)
1249
+ request.with = sanitizeStringMap(importAttributes, "with");
1250
+ sendRequest(refs, request, (error, response) => {
1251
+ if (error !== null)
1252
+ reject(new Error(error));
1253
+ else
1254
+ resolve22({
1255
+ errors: replaceDetailsInMessages(response.errors, details),
1256
+ warnings: replaceDetailsInMessages(response.warnings, details),
1257
+ path: response.path,
1258
+ external: response.external,
1259
+ sideEffects: response.sideEffects,
1260
+ namespace: response.namespace,
1261
+ suffix: response.suffix,
1262
+ pluginData: details.load(response.pluginData)
1263
+ });
1264
+ });
1265
+ });
1266
+ };
1267
+ let promise = setup({
1268
+ initialOptions,
1269
+ resolve: resolve2,
1270
+ onStart(callback) {
1271
+ let registeredText = `This error came from the "onStart" callback registered here:`;
1272
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart");
1273
+ onStartCallbacks.push({ name, callback, note: registeredNote });
1274
+ plugin.onStart = true;
1275
+ },
1276
+ onEnd(callback) {
1277
+ let registeredText = `This error came from the "onEnd" callback registered here:`;
1278
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd");
1279
+ onEndCallbacks.push({ name, callback, note: registeredNote });
1280
+ plugin.onEnd = true;
1281
+ },
1282
+ onResolve(options, callback) {
1283
+ let registeredText = `This error came from the "onResolve" callback registered here:`;
1284
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve");
1285
+ let keys2 = {};
1286
+ let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1287
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1288
+ checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`);
1289
+ if (filter == null)
1290
+ throw new Error(`onResolve() call is missing a filter`);
1291
+ let id = nextCallbackID++;
1292
+ onResolveCallbacks[id] = { name, callback, note: registeredNote };
1293
+ plugin.onResolve.push({ id, filter: jsRegExpToGoRegExp(filter), namespace: namespace || "" });
1294
+ },
1295
+ onLoad(options, callback) {
1296
+ let registeredText = `This error came from the "onLoad" callback registered here:`;
1297
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad");
1298
+ let keys2 = {};
1299
+ let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1300
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1301
+ checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`);
1302
+ if (filter == null)
1303
+ throw new Error(`onLoad() call is missing a filter`);
1304
+ let id = nextCallbackID++;
1305
+ onLoadCallbacks[id] = { name, callback, note: registeredNote };
1306
+ plugin.onLoad.push({ id, filter: jsRegExpToGoRegExp(filter), namespace: namespace || "" });
1307
+ },
1308
+ onDispose(callback) {
1309
+ onDisposeCallbacks.push(callback);
1310
+ },
1311
+ esbuild: streamIn.esbuild
1312
+ });
1313
+ if (promise)
1314
+ await promise;
1315
+ requestPlugins.push(plugin);
1316
+ } catch (e) {
1317
+ return { ok: false, error: e, pluginName: name };
1318
+ }
1319
+ }
1320
+ requestCallbacks["on-start"] = async (id, request) => {
1321
+ details.clear();
1322
+ let response = { errors: [], warnings: [] };
1323
+ await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => {
1324
+ try {
1325
+ let result = await callback();
1326
+ if (result != null) {
1327
+ if (typeof result !== "object")
1328
+ throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`);
1329
+ let keys = {};
1330
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1331
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1332
+ checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`);
1333
+ if (errors != null)
1334
+ response.errors.push(...sanitizeMessages(errors, "errors", details, name, undefined));
1335
+ if (warnings != null)
1336
+ response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, undefined));
1337
+ }
1338
+ } catch (e) {
1339
+ response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name));
1340
+ }
1341
+ }));
1342
+ sendResponse(id, response);
1343
+ };
1344
+ requestCallbacks["on-resolve"] = async (id, request) => {
1345
+ let response = {}, name = "", callback, note;
1346
+ for (let id2 of request.ids) {
1347
+ try {
1348
+ ({ name, callback, note } = onResolveCallbacks[id2]);
1349
+ let result = await callback({
1350
+ path: request.path,
1351
+ importer: request.importer,
1352
+ namespace: request.namespace,
1353
+ resolveDir: request.resolveDir,
1354
+ kind: request.kind,
1355
+ pluginData: details.load(request.pluginData),
1356
+ with: request.with
1357
+ });
1358
+ if (result != null) {
1359
+ if (typeof result !== "object")
1360
+ throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`);
1361
+ let keys = {};
1362
+ let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1363
+ let path3 = getFlag(result, keys, "path", mustBeString);
1364
+ let namespace = getFlag(result, keys, "namespace", mustBeString);
1365
+ let suffix = getFlag(result, keys, "suffix", mustBeString);
1366
+ let external = getFlag(result, keys, "external", mustBeBoolean);
1367
+ let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
1368
+ let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1369
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1370
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1371
+ let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
1372
+ let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
1373
+ checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`);
1374
+ response.id = id2;
1375
+ if (pluginName != null)
1376
+ response.pluginName = pluginName;
1377
+ if (path3 != null)
1378
+ response.path = path3;
1379
+ if (namespace != null)
1380
+ response.namespace = namespace;
1381
+ if (suffix != null)
1382
+ response.suffix = suffix;
1383
+ if (external != null)
1384
+ response.external = external;
1385
+ if (sideEffects != null)
1386
+ response.sideEffects = sideEffects;
1387
+ if (pluginData != null)
1388
+ response.pluginData = details.store(pluginData);
1389
+ if (errors != null)
1390
+ response.errors = sanitizeMessages(errors, "errors", details, name, undefined);
1391
+ if (warnings != null)
1392
+ response.warnings = sanitizeMessages(warnings, "warnings", details, name, undefined);
1393
+ if (watchFiles != null)
1394
+ response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1395
+ if (watchDirs != null)
1396
+ response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1397
+ break;
1398
+ }
1399
+ } catch (e) {
1400
+ response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
1401
+ break;
1402
+ }
1403
+ }
1404
+ sendResponse(id, response);
1405
+ };
1406
+ requestCallbacks["on-load"] = async (id, request) => {
1407
+ let response = {}, name = "", callback, note;
1408
+ for (let id2 of request.ids) {
1409
+ try {
1410
+ ({ name, callback, note } = onLoadCallbacks[id2]);
1411
+ let result = await callback({
1412
+ path: request.path,
1413
+ namespace: request.namespace,
1414
+ suffix: request.suffix,
1415
+ pluginData: details.load(request.pluginData),
1416
+ with: request.with
1417
+ });
1418
+ if (result != null) {
1419
+ if (typeof result !== "object")
1420
+ throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`);
1421
+ let keys = {};
1422
+ let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1423
+ let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
1424
+ let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
1425
+ let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1426
+ let loader = getFlag(result, keys, "loader", mustBeString);
1427
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1428
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1429
+ let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
1430
+ let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
1431
+ checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`);
1432
+ response.id = id2;
1433
+ if (pluginName != null)
1434
+ response.pluginName = pluginName;
1435
+ if (contents instanceof Uint8Array)
1436
+ response.contents = contents;
1437
+ else if (contents != null)
1438
+ response.contents = encodeUTF8(contents);
1439
+ if (resolveDir != null)
1440
+ response.resolveDir = resolveDir;
1441
+ if (pluginData != null)
1442
+ response.pluginData = details.store(pluginData);
1443
+ if (loader != null)
1444
+ response.loader = loader;
1445
+ if (errors != null)
1446
+ response.errors = sanitizeMessages(errors, "errors", details, name, undefined);
1447
+ if (warnings != null)
1448
+ response.warnings = sanitizeMessages(warnings, "warnings", details, name, undefined);
1449
+ if (watchFiles != null)
1450
+ response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1451
+ if (watchDirs != null)
1452
+ response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1453
+ break;
1454
+ }
1455
+ } catch (e) {
1456
+ response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
1457
+ break;
1458
+ }
1459
+ }
1460
+ sendResponse(id, response);
1461
+ };
1462
+ let runOnEndCallbacks = (result, done) => done([], []);
1463
+ if (onEndCallbacks.length > 0) {
1464
+ runOnEndCallbacks = (result, done) => {
1465
+ (async () => {
1466
+ const onEndErrors = [];
1467
+ const onEndWarnings = [];
1468
+ for (const { name, callback, note } of onEndCallbacks) {
1469
+ let newErrors;
1470
+ let newWarnings;
1471
+ try {
1472
+ const value = await callback(result);
1473
+ if (value != null) {
1474
+ if (typeof value !== "object")
1475
+ throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
1476
+ let keys = {};
1477
+ let errors = getFlag(value, keys, "errors", mustBeArray);
1478
+ let warnings = getFlag(value, keys, "warnings", mustBeArray);
1479
+ checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
1480
+ if (errors != null)
1481
+ newErrors = sanitizeMessages(errors, "errors", details, name, undefined);
1482
+ if (warnings != null)
1483
+ newWarnings = sanitizeMessages(warnings, "warnings", details, name, undefined);
1484
+ }
1485
+ } catch (e) {
1486
+ newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
1487
+ }
1488
+ if (newErrors) {
1489
+ onEndErrors.push(...newErrors);
1490
+ try {
1491
+ result.errors.push(...newErrors);
1492
+ } catch {}
1493
+ }
1494
+ if (newWarnings) {
1495
+ onEndWarnings.push(...newWarnings);
1496
+ try {
1497
+ result.warnings.push(...newWarnings);
1498
+ } catch {}
1499
+ }
1500
+ }
1501
+ done(onEndErrors, onEndWarnings);
1502
+ })();
1503
+ };
1504
+ }
1505
+ let scheduleOnDisposeCallbacks = () => {
1506
+ for (const cb of onDisposeCallbacks) {
1507
+ setTimeout(() => cb(), 0);
1508
+ }
1509
+ };
1510
+ isSetupDone = true;
1511
+ return {
1512
+ ok: true,
1513
+ requestPlugins,
1514
+ runOnEndCallbacks,
1515
+ scheduleOnDisposeCallbacks
1516
+ };
1517
+ };
1518
+ function createObjectStash() {
1519
+ const map = /* @__PURE__ */ new Map;
1520
+ let nextID = 0;
1521
+ return {
1522
+ clear() {
1523
+ map.clear();
1524
+ },
1525
+ load(id) {
1526
+ return map.get(id);
1527
+ },
1528
+ store(value) {
1529
+ if (value === undefined)
1530
+ return -1;
1531
+ const id = nextID++;
1532
+ map.set(id, value);
1533
+ return id;
1534
+ }
1535
+ };
1536
+ }
1537
+ function extractCallerV8(e, streamIn, ident) {
1538
+ let note;
1539
+ let tried = false;
1540
+ return () => {
1541
+ if (tried)
1542
+ return note;
1543
+ tried = true;
1544
+ try {
1545
+ let lines = (e.stack + "").split(`
1546
+ `);
1547
+ lines.splice(1, 1);
1548
+ let location = parseStackLinesV8(streamIn, lines, ident);
1549
+ if (location) {
1550
+ note = { text: e.message, location };
1551
+ return note;
1552
+ }
1553
+ } catch {}
1554
+ };
1555
+ }
1556
+ function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
1557
+ let text = "Internal error";
1558
+ let location = null;
1559
+ try {
1560
+ text = (e && e.message || e) + "";
1561
+ } catch {}
1562
+ try {
1563
+ location = parseStackLinesV8(streamIn, (e.stack + "").split(`
1564
+ `), "");
1565
+ } catch {}
1566
+ return { id: "", pluginName, text, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 };
1567
+ }
1568
+ function parseStackLinesV8(streamIn, lines, ident) {
1569
+ let at = " at ";
1570
+ if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) {
1571
+ for (let i = 1;i < lines.length; i++) {
1572
+ let line = lines[i];
1573
+ if (!line.startsWith(at))
1574
+ continue;
1575
+ line = line.slice(at.length);
1576
+ while (true) {
1577
+ let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
1578
+ if (match) {
1579
+ line = match[1];
1580
+ continue;
1581
+ }
1582
+ match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
1583
+ if (match) {
1584
+ line = match[1];
1585
+ continue;
1586
+ }
1587
+ match = /^(\S+):(\d+):(\d+)$/.exec(line);
1588
+ if (match) {
1589
+ let contents;
1590
+ try {
1591
+ contents = streamIn.readFileSync(match[1], "utf8");
1592
+ } catch {
1593
+ break;
1594
+ }
1595
+ let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
1596
+ let column = +match[3] - 1;
1597
+ let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
1598
+ return {
1599
+ file: match[1],
1600
+ namespace: "file",
1601
+ line: +match[2],
1602
+ column: encodeUTF8(lineText.slice(0, column)).length,
1603
+ length: encodeUTF8(lineText.slice(column, column + length)).length,
1604
+ lineText: lineText + `
1605
+ ` + lines.slice(1).join(`
1606
+ `),
1607
+ suggestion: ""
1608
+ };
1609
+ }
1610
+ break;
1611
+ }
1612
+ }
1613
+ }
1614
+ return null;
1615
+ }
1616
+ function failureErrorWithLog(text, errors, warnings) {
1617
+ let limit = 5;
1618
+ text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => {
1619
+ if (i === limit)
1620
+ return `
1621
+ ...`;
1622
+ if (!e.location)
1623
+ return `
1624
+ error: ${e.text}`;
1625
+ let { file, line, column } = e.location;
1626
+ let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : "";
1627
+ return `
1628
+ ${file}:${line}:${column}: ERROR: ${pluginText}${e.text}`;
1629
+ }).join("");
1630
+ let error = new Error(text);
1631
+ for (const [key, value] of [["errors", errors], ["warnings", warnings]]) {
1632
+ Object.defineProperty(error, key, {
1633
+ configurable: true,
1634
+ enumerable: true,
1635
+ get: () => value,
1636
+ set: (value2) => Object.defineProperty(error, key, {
1637
+ configurable: true,
1638
+ enumerable: true,
1639
+ value: value2
1640
+ })
1641
+ });
1642
+ }
1643
+ return error;
1644
+ }
1645
+ function replaceDetailsInMessages(messages, stash) {
1646
+ for (const message of messages) {
1647
+ message.detail = stash.load(message.detail);
1648
+ }
1649
+ return messages;
1650
+ }
1651
+ function sanitizeLocation(location, where, terminalWidth) {
1652
+ if (location == null)
1653
+ return null;
1654
+ let keys = {};
1655
+ let file = getFlag(location, keys, "file", mustBeString);
1656
+ let namespace = getFlag(location, keys, "namespace", mustBeString);
1657
+ let line = getFlag(location, keys, "line", mustBeInteger);
1658
+ let column = getFlag(location, keys, "column", mustBeInteger);
1659
+ let length = getFlag(location, keys, "length", mustBeInteger);
1660
+ let lineText = getFlag(location, keys, "lineText", mustBeString);
1661
+ let suggestion = getFlag(location, keys, "suggestion", mustBeString);
1662
+ checkForInvalidFlags(location, keys, where);
1663
+ if (lineText) {
1664
+ const relevantASCII = lineText.slice(0, (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80));
1665
+ if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) {
1666
+ lineText = relevantASCII;
1667
+ }
1668
+ }
1669
+ return {
1670
+ file: file || "",
1671
+ namespace: namespace || "",
1672
+ line: line || 0,
1673
+ column: column || 0,
1674
+ length: length || 0,
1675
+ lineText: lineText || "",
1676
+ suggestion: suggestion || ""
1677
+ };
1678
+ }
1679
+ function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) {
1680
+ let messagesClone = [];
1681
+ let index = 0;
1682
+ for (const message of messages) {
1683
+ let keys = {};
1684
+ let id = getFlag(message, keys, "id", mustBeString);
1685
+ let pluginName = getFlag(message, keys, "pluginName", mustBeString);
1686
+ let text = getFlag(message, keys, "text", mustBeString);
1687
+ let location = getFlag(message, keys, "location", mustBeObjectOrNull);
1688
+ let notes = getFlag(message, keys, "notes", mustBeArray);
1689
+ let detail = getFlag(message, keys, "detail", canBeAnything);
1690
+ let where = `in element ${index} of "${property}"`;
1691
+ checkForInvalidFlags(message, keys, where);
1692
+ let notesClone = [];
1693
+ if (notes) {
1694
+ for (const note of notes) {
1695
+ let noteKeys = {};
1696
+ let noteText = getFlag(note, noteKeys, "text", mustBeString);
1697
+ let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
1698
+ checkForInvalidFlags(note, noteKeys, where);
1699
+ notesClone.push({
1700
+ text: noteText || "",
1701
+ location: sanitizeLocation(noteLocation, where, terminalWidth)
1702
+ });
1703
+ }
1704
+ }
1705
+ messagesClone.push({
1706
+ id: id || "",
1707
+ pluginName: pluginName || fallbackPluginName,
1708
+ text: text || "",
1709
+ location: sanitizeLocation(location, where, terminalWidth),
1710
+ notes: notesClone,
1711
+ detail: stash ? stash.store(detail) : -1
1712
+ });
1713
+ index++;
1714
+ }
1715
+ return messagesClone;
1716
+ }
1717
+ function sanitizeStringArray(values, property) {
1718
+ const result = [];
1719
+ for (const value of values) {
1720
+ if (typeof value !== "string")
1721
+ throw new Error(`${quote(property)} must be an array of strings`);
1722
+ result.push(value);
1723
+ }
1724
+ return result;
1725
+ }
1726
+ function sanitizeStringMap(map, property) {
1727
+ const result = /* @__PURE__ */ Object.create(null);
1728
+ for (const key in map) {
1729
+ const value = map[key];
1730
+ if (typeof value !== "string")
1731
+ throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`);
1732
+ result[key] = value;
1733
+ }
1734
+ return result;
1735
+ }
1736
+ function convertOutputFiles({ path: path3, contents, hash }) {
1737
+ let text = null;
1738
+ return {
1739
+ path: path3,
1740
+ contents,
1741
+ hash,
1742
+ get text() {
1743
+ const binary = this.contents;
1744
+ if (text === null || binary !== contents) {
1745
+ contents = binary;
1746
+ text = decodeUTF8(binary);
1747
+ }
1748
+ return text;
1749
+ }
1750
+ };
1751
+ }
1752
+ function jsRegExpToGoRegExp(regexp) {
1753
+ let result = regexp.source;
1754
+ if (regexp.flags)
1755
+ result = `(?${regexp.flags})${result}`;
1756
+ return result;
1757
+ }
1758
+ var fs = __require("fs");
1759
+ var os = __require("os");
1760
+ var path = __require("path");
1761
+ var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
1762
+ var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
1763
+ var packageDarwin_arm64 = "@esbuild/darwin-arm64";
1764
+ var packageDarwin_x64 = "@esbuild/darwin-x64";
1765
+ var knownWindowsPackages = {
1766
+ "win32 arm64 LE": "@esbuild/win32-arm64",
1767
+ "win32 ia32 LE": "@esbuild/win32-ia32",
1768
+ "win32 x64 LE": "@esbuild/win32-x64"
1769
+ };
1770
+ var knownUnixlikePackages = {
1771
+ "aix ppc64 BE": "@esbuild/aix-ppc64",
1772
+ "android arm64 LE": "@esbuild/android-arm64",
1773
+ "darwin arm64 LE": "@esbuild/darwin-arm64",
1774
+ "darwin x64 LE": "@esbuild/darwin-x64",
1775
+ "freebsd arm64 LE": "@esbuild/freebsd-arm64",
1776
+ "freebsd x64 LE": "@esbuild/freebsd-x64",
1777
+ "linux arm LE": "@esbuild/linux-arm",
1778
+ "linux arm64 LE": "@esbuild/linux-arm64",
1779
+ "linux ia32 LE": "@esbuild/linux-ia32",
1780
+ "linux mips64el LE": "@esbuild/linux-mips64el",
1781
+ "linux ppc64 LE": "@esbuild/linux-ppc64",
1782
+ "linux riscv64 LE": "@esbuild/linux-riscv64",
1783
+ "linux s390x BE": "@esbuild/linux-s390x",
1784
+ "linux x64 LE": "@esbuild/linux-x64",
1785
+ "linux loong64 LE": "@esbuild/linux-loong64",
1786
+ "netbsd arm64 LE": "@esbuild/netbsd-arm64",
1787
+ "netbsd x64 LE": "@esbuild/netbsd-x64",
1788
+ "openbsd arm64 LE": "@esbuild/openbsd-arm64",
1789
+ "openbsd x64 LE": "@esbuild/openbsd-x64",
1790
+ "sunos x64 LE": "@esbuild/sunos-x64"
1791
+ };
1792
+ var knownWebAssemblyFallbackPackages = {
1793
+ "android arm LE": "@esbuild/android-arm",
1794
+ "android x64 LE": "@esbuild/android-x64",
1795
+ "openharmony arm64 LE": "@esbuild/openharmony-arm64"
1796
+ };
1797
+ function pkgAndSubpathForCurrentPlatform() {
1798
+ let pkg;
1799
+ let subpath;
1800
+ let isWASM = false;
1801
+ let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
1802
+ if (platformKey in knownWindowsPackages) {
1803
+ pkg = knownWindowsPackages[platformKey];
1804
+ subpath = "esbuild.exe";
1805
+ } else if (platformKey in knownUnixlikePackages) {
1806
+ pkg = knownUnixlikePackages[platformKey];
1807
+ subpath = "bin/esbuild";
1808
+ } else if (platformKey in knownWebAssemblyFallbackPackages) {
1809
+ pkg = knownWebAssemblyFallbackPackages[platformKey];
1810
+ subpath = "bin/esbuild";
1811
+ isWASM = true;
1812
+ } else {
1813
+ throw new Error(`Unsupported platform: ${platformKey}`);
1814
+ }
1815
+ return { pkg, subpath, isWASM };
1816
+ }
1817
+ function pkgForSomeOtherPlatform() {
1818
+ const libMainJS = __require.resolve("esbuild");
1819
+ const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS)));
1820
+ if (path.basename(nodeModulesDirectory) === "node_modules") {
1821
+ for (const unixKey in knownUnixlikePackages) {
1822
+ try {
1823
+ const pkg = knownUnixlikePackages[unixKey];
1824
+ if (fs.existsSync(path.join(nodeModulesDirectory, pkg)))
1825
+ return pkg;
1826
+ } catch {}
1827
+ }
1828
+ for (const windowsKey in knownWindowsPackages) {
1829
+ try {
1830
+ const pkg = knownWindowsPackages[windowsKey];
1831
+ if (fs.existsSync(path.join(nodeModulesDirectory, pkg)))
1832
+ return pkg;
1833
+ } catch {}
1834
+ }
1835
+ }
1836
+ return null;
1837
+ }
1838
+ function downloadedBinPath(pkg, subpath) {
1839
+ const esbuildLibDir = path.dirname(__require.resolve("esbuild"));
1840
+ return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
1841
+ }
1842
+ function generateBinPath() {
1843
+ if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
1844
+ if (!fs.existsSync(ESBUILD_BINARY_PATH)) {
1845
+ console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
1846
+ } else {
1847
+ return { binPath: ESBUILD_BINARY_PATH, isWASM: false };
1848
+ }
1849
+ }
1850
+ const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
1851
+ let binPath;
1852
+ try {
1853
+ binPath = __require.resolve(`${pkg}/${subpath}`);
1854
+ } catch (e) {
1855
+ binPath = downloadedBinPath(pkg, subpath);
1856
+ if (!fs.existsSync(binPath)) {
1857
+ try {
1858
+ __require.resolve(pkg);
1859
+ } catch {
1860
+ const otherPkg = pkgForSomeOtherPlatform();
1861
+ if (otherPkg) {
1862
+ let suggestions = `
1863
+ Specifically the "${otherPkg}" package is present but this platform
1864
+ needs the "${pkg}" package instead. People often get into this
1865
+ situation by installing esbuild on Windows or macOS and copying "node_modules"
1866
+ into a Docker image that runs Linux, or by copying "node_modules" between
1867
+ Windows and WSL environments.
1868
+
1869
+ If you are installing with npm, you can try not copying the "node_modules"
1870
+ directory when you copy the files over, and running "npm ci" or "npm install"
1871
+ on the destination platform after the copy. Or you could consider using yarn
1872
+ instead of npm which has built-in support for installing a package on multiple
1873
+ platforms simultaneously.
1874
+
1875
+ If you are installing with yarn, you can try listing both this platform and the
1876
+ other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
1877
+ feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
1878
+ Keep in mind that this means multiple copies of esbuild will be present.
1879
+ `;
1880
+ if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) {
1881
+ suggestions = `
1882
+ Specifically the "${otherPkg}" package is present but this platform
1883
+ needs the "${pkg}" package instead. People often get into this
1884
+ situation by installing esbuild with npm running inside of Rosetta 2 and then
1885
+ trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
1886
+ 2 is Apple's on-the-fly x86_64-to-arm64 translation service).
1887
+
1888
+ If you are installing with npm, you can try ensuring that both npm and node are
1889
+ not running under Rosetta 2 and then reinstalling esbuild. This likely involves
1890
+ changing how you installed npm and/or node. For example, installing node with
1891
+ the universal installer here should work: https://nodejs.org/en/download/. Or
1892
+ you could consider using yarn instead of npm which has built-in support for
1893
+ installing a package on multiple platforms simultaneously.
1894
+
1895
+ If you are installing with yarn, you can try listing both "arm64" and "x64"
1896
+ in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
1897
+ https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
1898
+ Keep in mind that this means multiple copies of esbuild will be present.
1899
+ `;
1900
+ }
1901
+ throw new Error(`
1902
+ You installed esbuild for another platform than the one you're currently using.
1903
+ This won't work because esbuild is written with native code and needs to
1904
+ install a platform-specific binary executable.
1905
+ ${suggestions}
1906
+ Another alternative is to use the "esbuild-wasm" package instead, which works
1907
+ the same way on all platforms. But it comes with a heavy performance cost and
1908
+ can sometimes be 10x slower than the "esbuild" package, so you may also not
1909
+ want to do that.
1910
+ `);
1911
+ }
1912
+ throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
1913
+
1914
+ If you are installing esbuild with npm, make sure that you don't specify the
1915
+ "--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
1916
+ of "package.json" is used by esbuild to install the correct binary executable
1917
+ for your current platform.`);
1918
+ }
1919
+ throw e;
1920
+ }
1921
+ }
1922
+ if (/\.zip\//.test(binPath)) {
1923
+ let pnpapi;
1924
+ try {
1925
+ pnpapi = (()=>{throw new Error("Cannot require module "+"pnpapi");})();
1926
+ } catch (e) {}
1927
+ if (pnpapi) {
1928
+ const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
1929
+ const binTargetPath = path.join(root, "node_modules", ".cache", "esbuild", `pnpapi-${pkg.replace("/", "-")}-${"0.27.3"}-${path.basename(subpath)}`);
1930
+ if (!fs.existsSync(binTargetPath)) {
1931
+ fs.mkdirSync(path.dirname(binTargetPath), { recursive: true });
1932
+ fs.copyFileSync(binPath, binTargetPath);
1933
+ fs.chmodSync(binTargetPath, 493);
1934
+ }
1935
+ return { binPath: binTargetPath, isWASM };
1936
+ }
1937
+ }
1938
+ return { binPath, isWASM };
1939
+ }
1940
+ var child_process = __require("child_process");
1941
+ var crypto = __require("crypto");
1942
+ var path2 = __require("path");
1943
+ var fs2 = __require("fs");
1944
+ var os2 = __require("os");
1945
+ var tty = __require("tty");
1946
+ var worker_threads;
1947
+ if (process.env.ESBUILD_WORKER_THREADS !== "0") {
1948
+ try {
1949
+ worker_threads = __require("worker_threads");
1950
+ } catch {}
1951
+ let [major, minor] = process.versions.node.split(".");
1952
+ if (+major < 12 || +major === 12 && +minor < 17 || +major === 13 && +minor < 13) {
1953
+ worker_threads = undefined;
1954
+ }
1955
+ }
1956
+ var _a;
1957
+ var isInternalWorkerThread = ((_a = worker_threads == null ? undefined : worker_threads.workerData) == null ? undefined : _a.esbuildVersion) === "0.27.3";
1958
+ var esbuildCommandAndArgs = () => {
1959
+ if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) {
1960
+ 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.
1961
+
1962
+ 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.`);
1963
+ }
1964
+ if (false) {} else {
1965
+ const { binPath, isWASM } = generateBinPath();
1966
+ if (isWASM) {
1967
+ return ["node", [binPath]];
1968
+ } else {
1969
+ return [binPath, []];
1970
+ }
1971
+ }
1972
+ };
1973
+ var isTTY = () => tty.isatty(2);
1974
+ var fsSync = {
1975
+ readFile(tempFile, callback) {
1976
+ try {
1977
+ let contents = fs2.readFileSync(tempFile, "utf8");
1978
+ try {
1979
+ fs2.unlinkSync(tempFile);
1980
+ } catch {}
1981
+ callback(null, contents);
1982
+ } catch (err) {
1983
+ callback(err, null);
1984
+ }
1985
+ },
1986
+ writeFile(contents, callback) {
1987
+ try {
1988
+ let tempFile = randomFileName();
1989
+ fs2.writeFileSync(tempFile, contents);
1990
+ callback(tempFile);
1991
+ } catch {
1992
+ callback(null);
1993
+ }
1994
+ }
1995
+ };
1996
+ var fsAsync = {
1997
+ readFile(tempFile, callback) {
1998
+ try {
1999
+ fs2.readFile(tempFile, "utf8", (err, contents) => {
2000
+ try {
2001
+ fs2.unlink(tempFile, () => callback(err, contents));
2002
+ } catch {
2003
+ callback(err, contents);
2004
+ }
2005
+ });
2006
+ } catch (err) {
2007
+ callback(err, null);
2008
+ }
2009
+ },
2010
+ writeFile(contents, callback) {
2011
+ try {
2012
+ let tempFile = randomFileName();
2013
+ fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile));
2014
+ } catch {
2015
+ callback(null);
2016
+ }
2017
+ }
2018
+ };
2019
+ var version = "0.27.3";
2020
+ var build = (options) => ensureServiceIsRunning().build(options);
2021
+ var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions);
2022
+ var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
2023
+ var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
2024
+ var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options);
2025
+ var buildSync = (options) => {
2026
+ if (worker_threads && !isInternalWorkerThread) {
2027
+ if (!workerThreadService)
2028
+ workerThreadService = startWorkerThreadService(worker_threads);
2029
+ return workerThreadService.buildSync(options);
2030
+ }
2031
+ let result;
2032
+ runServiceSync((service) => service.buildOrContext({
2033
+ callName: "buildSync",
2034
+ refs: null,
2035
+ options,
2036
+ isTTY: isTTY(),
2037
+ defaultWD,
2038
+ callback: (err, res) => {
2039
+ if (err)
2040
+ throw err;
2041
+ result = res;
2042
+ }
2043
+ }));
2044
+ return result;
2045
+ };
2046
+ var transformSync = (input, options) => {
2047
+ if (worker_threads && !isInternalWorkerThread) {
2048
+ if (!workerThreadService)
2049
+ workerThreadService = startWorkerThreadService(worker_threads);
2050
+ return workerThreadService.transformSync(input, options);
2051
+ }
2052
+ let result;
2053
+ runServiceSync((service) => service.transform({
2054
+ callName: "transformSync",
2055
+ refs: null,
2056
+ input,
2057
+ options: options || {},
2058
+ isTTY: isTTY(),
2059
+ fs: fsSync,
2060
+ callback: (err, res) => {
2061
+ if (err)
2062
+ throw err;
2063
+ result = res;
2064
+ }
2065
+ }));
2066
+ return result;
2067
+ };
2068
+ var formatMessagesSync = (messages, options) => {
2069
+ if (worker_threads && !isInternalWorkerThread) {
2070
+ if (!workerThreadService)
2071
+ workerThreadService = startWorkerThreadService(worker_threads);
2072
+ return workerThreadService.formatMessagesSync(messages, options);
2073
+ }
2074
+ let result;
2075
+ runServiceSync((service) => service.formatMessages({
2076
+ callName: "formatMessagesSync",
2077
+ refs: null,
2078
+ messages,
2079
+ options,
2080
+ callback: (err, res) => {
2081
+ if (err)
2082
+ throw err;
2083
+ result = res;
2084
+ }
2085
+ }));
2086
+ return result;
2087
+ };
2088
+ var analyzeMetafileSync = (metafile, options) => {
2089
+ if (worker_threads && !isInternalWorkerThread) {
2090
+ if (!workerThreadService)
2091
+ workerThreadService = startWorkerThreadService(worker_threads);
2092
+ return workerThreadService.analyzeMetafileSync(metafile, options);
2093
+ }
2094
+ let result;
2095
+ runServiceSync((service) => service.analyzeMetafile({
2096
+ callName: "analyzeMetafileSync",
2097
+ refs: null,
2098
+ metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2099
+ options,
2100
+ callback: (err, res) => {
2101
+ if (err)
2102
+ throw err;
2103
+ result = res;
2104
+ }
2105
+ }));
2106
+ return result;
2107
+ };
2108
+ var stop = () => {
2109
+ if (stopService)
2110
+ stopService();
2111
+ if (workerThreadService)
2112
+ workerThreadService.stop();
2113
+ return Promise.resolve();
2114
+ };
2115
+ var initializeWasCalled = false;
2116
+ var initialize = (options) => {
2117
+ options = validateInitializeOptions(options || {});
2118
+ if (options.wasmURL)
2119
+ throw new Error(`The "wasmURL" option only works in the browser`);
2120
+ if (options.wasmModule)
2121
+ throw new Error(`The "wasmModule" option only works in the browser`);
2122
+ if (options.worker)
2123
+ throw new Error(`The "worker" option only works in the browser`);
2124
+ if (initializeWasCalled)
2125
+ throw new Error('Cannot call "initialize" more than once');
2126
+ ensureServiceIsRunning();
2127
+ initializeWasCalled = true;
2128
+ return Promise.resolve();
2129
+ };
2130
+ var defaultWD = process.cwd();
2131
+ var longLivedService;
2132
+ var stopService;
2133
+ var ensureServiceIsRunning = () => {
2134
+ if (longLivedService)
2135
+ return longLivedService;
2136
+ let [command, args] = esbuildCommandAndArgs();
2137
+ let child = child_process.spawn(command, args.concat(`--service=${"0.27.3"}`, "--ping"), {
2138
+ windowsHide: true,
2139
+ stdio: ["pipe", "pipe", "inherit"],
2140
+ cwd: defaultWD
2141
+ });
2142
+ let { readFromStdout, afterClose, service } = createChannel({
2143
+ writeToStdin(bytes) {
2144
+ child.stdin.write(bytes, (err) => {
2145
+ if (err)
2146
+ afterClose(err);
2147
+ });
2148
+ },
2149
+ readFileSync: fs2.readFileSync,
2150
+ isSync: false,
2151
+ hasFS: true,
2152
+ esbuild: node_exports
2153
+ });
2154
+ child.stdin.on("error", afterClose);
2155
+ child.on("error", afterClose);
2156
+ const stdin = child.stdin;
2157
+ const stdout = child.stdout;
2158
+ stdout.on("data", readFromStdout);
2159
+ stdout.on("end", afterClose);
2160
+ stopService = () => {
2161
+ stdin.destroy();
2162
+ stdout.destroy();
2163
+ child.kill();
2164
+ initializeWasCalled = false;
2165
+ longLivedService = undefined;
2166
+ stopService = undefined;
2167
+ };
2168
+ let refCount = 0;
2169
+ child.unref();
2170
+ if (stdin.unref) {
2171
+ stdin.unref();
2172
+ }
2173
+ if (stdout.unref) {
2174
+ stdout.unref();
2175
+ }
2176
+ const refs = {
2177
+ ref() {
2178
+ if (++refCount === 1)
2179
+ child.ref();
2180
+ },
2181
+ unref() {
2182
+ if (--refCount === 0)
2183
+ child.unref();
2184
+ }
2185
+ };
2186
+ longLivedService = {
2187
+ build: (options) => new Promise((resolve2, reject) => {
2188
+ service.buildOrContext({
2189
+ callName: "build",
2190
+ refs,
2191
+ options,
2192
+ isTTY: isTTY(),
2193
+ defaultWD,
2194
+ callback: (err, res) => err ? reject(err) : resolve2(res)
2195
+ });
2196
+ }),
2197
+ context: (options) => new Promise((resolve2, reject) => service.buildOrContext({
2198
+ callName: "context",
2199
+ refs,
2200
+ options,
2201
+ isTTY: isTTY(),
2202
+ defaultWD,
2203
+ callback: (err, res) => err ? reject(err) : resolve2(res)
2204
+ })),
2205
+ transform: (input, options) => new Promise((resolve2, reject) => service.transform({
2206
+ callName: "transform",
2207
+ refs,
2208
+ input,
2209
+ options: options || {},
2210
+ isTTY: isTTY(),
2211
+ fs: fsAsync,
2212
+ callback: (err, res) => err ? reject(err) : resolve2(res)
2213
+ })),
2214
+ formatMessages: (messages, options) => new Promise((resolve2, reject) => service.formatMessages({
2215
+ callName: "formatMessages",
2216
+ refs,
2217
+ messages,
2218
+ options,
2219
+ callback: (err, res) => err ? reject(err) : resolve2(res)
2220
+ })),
2221
+ analyzeMetafile: (metafile, options) => new Promise((resolve2, reject) => service.analyzeMetafile({
2222
+ callName: "analyzeMetafile",
2223
+ refs,
2224
+ metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2225
+ options,
2226
+ callback: (err, res) => err ? reject(err) : resolve2(res)
2227
+ }))
2228
+ };
2229
+ return longLivedService;
2230
+ };
2231
+ var runServiceSync = (callback) => {
2232
+ let [command, args] = esbuildCommandAndArgs();
2233
+ let stdin = new Uint8Array;
2234
+ let { readFromStdout, afterClose, service } = createChannel({
2235
+ writeToStdin(bytes) {
2236
+ if (stdin.length !== 0)
2237
+ throw new Error("Must run at most one command");
2238
+ stdin = bytes;
2239
+ },
2240
+ isSync: true,
2241
+ hasFS: true,
2242
+ esbuild: node_exports
2243
+ });
2244
+ callback(service);
2245
+ let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.27.3"}`), {
2246
+ cwd: defaultWD,
2247
+ windowsHide: true,
2248
+ input: stdin,
2249
+ maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
2250
+ });
2251
+ readFromStdout(stdout);
2252
+ afterClose(null);
2253
+ };
2254
+ var randomFileName = () => {
2255
+ return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`);
2256
+ };
2257
+ var workerThreadService = null;
2258
+ var startWorkerThreadService = (worker_threads2) => {
2259
+ let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel;
2260
+ let worker = new worker_threads2.Worker(__filename, {
2261
+ workerData: { workerPort, defaultWD, esbuildVersion: "0.27.3" },
2262
+ transferList: [workerPort],
2263
+ execArgv: []
2264
+ });
2265
+ let nextID = 0;
2266
+ let fakeBuildError = (text) => {
2267
+ let error = new Error(`Build failed with 1 error:
2268
+ error: ${text}`);
2269
+ let errors = [{ id: "", pluginName: "", text, location: null, notes: [], detail: undefined }];
2270
+ error.errors = errors;
2271
+ error.warnings = [];
2272
+ return error;
2273
+ };
2274
+ let validateBuildSyncOptions = (options) => {
2275
+ if (!options)
2276
+ return;
2277
+ let plugins = options.plugins;
2278
+ if (plugins && plugins.length > 0)
2279
+ throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
2280
+ };
2281
+ let applyProperties = (object, properties) => {
2282
+ for (let key in properties) {
2283
+ object[key] = properties[key];
2284
+ }
2285
+ };
2286
+ let runCallSync = (command, args) => {
2287
+ let id = nextID++;
2288
+ let sharedBuffer = new SharedArrayBuffer(8);
2289
+ let sharedBufferView = new Int32Array(sharedBuffer);
2290
+ let msg = { sharedBuffer, id, command, args };
2291
+ worker.postMessage(msg);
2292
+ let status = Atomics.wait(sharedBufferView, 0, 0);
2293
+ if (status !== "ok" && status !== "not-equal")
2294
+ throw new Error("Internal error: Atomics.wait() failed: " + status);
2295
+ let { message: { id: id2, resolve: resolve2, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort);
2296
+ if (id !== id2)
2297
+ throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
2298
+ if (reject) {
2299
+ applyProperties(reject, properties);
2300
+ throw reject;
2301
+ }
2302
+ return resolve2;
2303
+ };
2304
+ worker.unref();
2305
+ return {
2306
+ buildSync(options) {
2307
+ validateBuildSyncOptions(options);
2308
+ return runCallSync("build", [options]);
2309
+ },
2310
+ transformSync(input, options) {
2311
+ return runCallSync("transform", [input, options]);
2312
+ },
2313
+ formatMessagesSync(messages, options) {
2314
+ return runCallSync("formatMessages", [messages, options]);
2315
+ },
2316
+ analyzeMetafileSync(metafile, options) {
2317
+ return runCallSync("analyzeMetafile", [metafile, options]);
2318
+ },
2319
+ stop() {
2320
+ worker.terminate();
2321
+ workerThreadService = null;
2322
+ }
2323
+ };
2324
+ };
2325
+ var startSyncServiceWorker = () => {
2326
+ let workerPort = worker_threads.workerData.workerPort;
2327
+ let parentPort = worker_threads.parentPort;
2328
+ let extractProperties = (object) => {
2329
+ let properties = {};
2330
+ if (object && typeof object === "object") {
2331
+ for (let key in object) {
2332
+ properties[key] = object[key];
2333
+ }
2334
+ }
2335
+ return properties;
2336
+ };
2337
+ try {
2338
+ let service = ensureServiceIsRunning();
2339
+ defaultWD = worker_threads.workerData.defaultWD;
2340
+ parentPort.on("message", (msg) => {
2341
+ (async () => {
2342
+ let { sharedBuffer, id, command, args } = msg;
2343
+ let sharedBufferView = new Int32Array(sharedBuffer);
2344
+ try {
2345
+ switch (command) {
2346
+ case "build":
2347
+ workerPort.postMessage({ id, resolve: await service.build(args[0]) });
2348
+ break;
2349
+ case "transform":
2350
+ workerPort.postMessage({ id, resolve: await service.transform(args[0], args[1]) });
2351
+ break;
2352
+ case "formatMessages":
2353
+ workerPort.postMessage({ id, resolve: await service.formatMessages(args[0], args[1]) });
2354
+ break;
2355
+ case "analyzeMetafile":
2356
+ workerPort.postMessage({ id, resolve: await service.analyzeMetafile(args[0], args[1]) });
2357
+ break;
2358
+ default:
2359
+ throw new Error(`Invalid command: ${command}`);
2360
+ }
2361
+ } catch (reject) {
2362
+ workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
2363
+ }
2364
+ Atomics.add(sharedBufferView, 0, 1);
2365
+ Atomics.notify(sharedBufferView, 0, Infinity);
2366
+ })();
2367
+ });
2368
+ } catch (reject) {
2369
+ parentPort.on("message", (msg) => {
2370
+ let { sharedBuffer, id } = msg;
2371
+ let sharedBufferView = new Int32Array(sharedBuffer);
2372
+ workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
2373
+ Atomics.add(sharedBufferView, 0, 1);
2374
+ Atomics.notify(sharedBufferView, 0, Infinity);
2375
+ });
2376
+ }
2377
+ };
2378
+ if (isInternalWorkerThread) {
2379
+ startSyncServiceWorker();
2380
+ }
2381
+ var node_default = node_exports;
2382
+ });
2383
+
2384
+ // src/cli.ts
2385
+ import { Command } from "commander";
2386
+
2387
+ // src/generators/naming.ts
2388
+ function toKebabCase(name) {
2389
+ return name.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2").toLowerCase();
2390
+ }
2391
+ function toPascalCase(name) {
2392
+ return name.split(/[-_\s]+/).map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join("");
2393
+ }
2394
+
2395
+ // src/generators/module.ts
2396
+ function generateModule(name, sourceDir) {
2397
+ const kebab = toKebabCase(name);
2398
+ const pascal = toPascalCase(kebab);
2399
+ const dir = `${sourceDir}/modules/${kebab}`;
2400
+ const moduleDefContent = `import { createModuleDef } from '@vertz/server';
2401
+
2402
+ export const ${pascal}ModuleDef = createModuleDef('${kebab}');
2403
+ `;
2404
+ const moduleContent = `import { createModule } from '@vertz/server';
2405
+ import { ${pascal}ModuleDef } from './${kebab}.module-def';
2406
+
2407
+ export const ${pascal}Module = createModule(${pascal}ModuleDef, (m) => {
2408
+ return m;
2409
+ });
2410
+ `;
2411
+ return [
2412
+ { path: `${dir}/${kebab}.module-def.ts`, content: moduleDefContent },
2413
+ { path: `${dir}/${kebab}.module.ts`, content: moduleContent }
2414
+ ];
2415
+ }
2416
+
2417
+ // src/generators/router.ts
2418
+ function generateRouter(name, moduleName, sourceDir) {
2419
+ const kebab = toKebabCase(name);
2420
+ const pascal = toPascalCase(kebab);
2421
+ const moduleKebab = toKebabCase(moduleName);
2422
+ const content = `import { createRouter } from '@vertz/server';
2423
+ import { ${pascal}ModuleDef } from './${moduleKebab}.module-def';
2424
+
2425
+ export const ${kebab}Router = createRouter(${pascal}ModuleDef, '/${kebab}', (r) => {
2426
+ return r;
2427
+ });
2428
+ `;
2429
+ return [
2430
+ {
2431
+ path: `${sourceDir}/modules/${moduleKebab}/${kebab}.router.ts`,
2432
+ content
2433
+ }
2434
+ ];
2435
+ }
2436
+
2437
+ // src/generators/schema.ts
2438
+ function generateSchema(name, moduleName, sourceDir) {
2439
+ const kebab = toKebabCase(name);
2440
+ const pascal = toPascalCase(kebab);
2441
+ const moduleKebab = toKebabCase(moduleName);
2442
+ const content = `import { createSchema } from '@vertz/server';
2443
+ import { z } from '@vertz/schema';
2444
+
2445
+ export const ${pascal}Schema = createSchema('${pascal}', z.object({
2446
+ // Add your schema fields here
2447
+ }));
2448
+ `;
2449
+ return [
2450
+ {
2451
+ path: `${sourceDir}/modules/${moduleKebab}/schemas/${kebab}.schema.ts`,
2452
+ content
2453
+ }
2454
+ ];
2455
+ }
2456
+
2457
+ // src/generators/service.ts
2458
+ function generateService(name, moduleName, sourceDir) {
2459
+ const kebab = toKebabCase(name);
2460
+ const pascal = toPascalCase(kebab);
2461
+ const moduleKebab = toKebabCase(moduleName);
2462
+ const content = `export function create${pascal}Service() {
2463
+ return {};
2464
+ }
2465
+ `;
2466
+ return [
2467
+ {
2468
+ path: `${sourceDir}/modules/${moduleKebab}/${kebab}.service.ts`,
2469
+ content
2470
+ }
2471
+ ];
2472
+ }
2473
+
2474
+ // src/commands/generate.ts
2475
+ var REQUIRES_MODULE = new Set(["service", "router", "schema"]);
2476
+ function generateAction(options) {
2477
+ const { type, name, module: moduleName, sourceDir } = options;
2478
+ if (REQUIRES_MODULE.has(type) && !moduleName) {
2479
+ return {
2480
+ success: false,
2481
+ files: [],
2482
+ error: `Generator "${type}" requires a --module option`
2483
+ };
2484
+ }
2485
+ const ensuredModuleName = moduleName;
2486
+ switch (type) {
2487
+ case "module":
2488
+ return { success: true, files: generateModule(name, sourceDir) };
2489
+ case "service":
2490
+ return { success: true, files: generateService(name, ensuredModuleName, sourceDir) };
2491
+ case "router":
2492
+ return { success: true, files: generateRouter(name, ensuredModuleName, sourceDir) };
2493
+ case "schema":
2494
+ return { success: true, files: generateSchema(name, ensuredModuleName, sourceDir) };
2495
+ default:
2496
+ return {
2497
+ success: false,
2498
+ files: [],
2499
+ error: `Unknown generator type: "${type}"`
2500
+ };
2501
+ }
2502
+ }
2503
+
2504
+ // src/commands/domain-gen.ts
2505
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync } from "node:fs";
2506
+ import { join } from "node:path";
2507
+ import { createHash } from "node:crypto";
2508
+ import { generateClient } from "@vertz/db";
2509
+ function findDomainFiles(cwd) {
2510
+ const domainsDir = join(cwd, "domains");
2511
+ if (!existsSync(domainsDir)) {
2512
+ return [];
2513
+ }
2514
+ const files = readdirSync(domainsDir);
2515
+ return files.filter((f) => f.endsWith(".domain.ts")).map((f) => join(domainsDir, f));
2516
+ }
2517
+ function computeDomainHash(files) {
2518
+ const hash = createHash("sha256");
2519
+ for (const file of files.sort()) {
2520
+ const content = readFileSync(file, "utf-8");
2521
+ hash.update(content);
2522
+ }
2523
+ return hash.digest("hex");
2524
+ }
2525
+ function shouldSkipGeneration(cwd, currentHash) {
2526
+ const hashFile = join(cwd, ".vertz", "generated", ".domain-hash");
2527
+ if (!existsSync(hashFile)) {
2528
+ return false;
2529
+ }
2530
+ try {
2531
+ const storedHash = readFileSync(hashFile, "utf-8").trim();
2532
+ return storedHash === currentHash;
2533
+ } catch {
2534
+ return false;
2535
+ }
2536
+ }
2537
+ function saveDomainHash(cwd, hash) {
2538
+ const dir = join(cwd, ".vertz", "generated");
2539
+ if (!existsSync(dir)) {
2540
+ mkdirSync(dir, { recursive: true });
2541
+ }
2542
+ writeFileSync(join(dir, ".domain-hash"), hash);
2543
+ }
2544
+ async function loadDomainDefinitions(cwd, files) {
2545
+ const { createJiti } = await import("jiti");
2546
+ const jitiImport = createJiti(cwd);
2547
+ const domains = [];
2548
+ for (const file of files) {
2549
+ try {
2550
+ const mod = jitiImport(file);
2551
+ const exports = mod.__esModule ? mod.default : mod;
2552
+ if (exports) {
2553
+ const domainExports = Array.isArray(exports) ? exports : [exports];
2554
+ for (const exp of domainExports) {
2555
+ if (exp && exp.name && exp.fields) {
2556
+ domains.push(exp);
2557
+ }
2558
+ }
2559
+ }
2560
+ } catch (err) {
2561
+ console.warn(`Warning: Failed to load domain file ${file}:`, err);
2562
+ }
2563
+ }
2564
+ return domains;
2565
+ }
2566
+ async function generateDomainAction(options) {
2567
+ const cwd = process.cwd();
2568
+ const dryRun = options.dryRun || false;
2569
+ const domainFiles = findDomainFiles(cwd);
2570
+ if (domainFiles.length === 0) {
2571
+ console.log("No domain files found in domains/ directory");
2572
+ return;
2573
+ }
2574
+ console.log(`Found ${domainFiles.length} domain file(s)`);
2575
+ const domainHash = computeDomainHash(domainFiles);
2576
+ if (shouldSkipGeneration(cwd, domainHash)) {
2577
+ console.log("Skipping generation - domains unchanged");
2578
+ return;
2579
+ }
2580
+ console.log("Generating DB client...");
2581
+ const domains = await loadDomainDefinitions(cwd, domainFiles);
2582
+ if (domains.length === 0) {
2583
+ console.log("No valid domain definitions found");
2584
+ return;
2585
+ }
2586
+ const clientCode = generateClient(domains);
2587
+ const outputDir = join(cwd, ".vertz", "generated");
2588
+ const outputFile = join(outputDir, "db-client.ts");
2589
+ if (dryRun) {
2590
+ console.log("Dry run - would write to:", outputFile);
2591
+ console.log(clientCode);
2592
+ return;
2593
+ }
2594
+ if (!existsSync(outputDir)) {
2595
+ mkdirSync(outputDir, { recursive: true });
2596
+ }
2597
+ writeFileSync(outputFile, clientCode);
2598
+ saveDomainHash(cwd, domainHash);
2599
+ console.log("DB client generated successfully");
2600
+ }
2601
+
2602
+ // src/commands/dev.ts
2603
+ import { spawn } from "node:child_process";
2604
+ import { join as join3 } from "node:path";
2605
+
2606
+ // src/pipeline/orchestrator.ts
2607
+ import { createCompiler } from "@vertz/compiler";
2608
+ import { generate, createCodegenPipeline } from "@vertz/codegen";
2609
+ var defaultPipelineConfig = {
2610
+ sourceDir: "src",
2611
+ outputDir: ".vertz/generated",
2612
+ typecheck: true,
2613
+ autoSyncDb: true,
2614
+ open: false,
2615
+ port: 3000,
2616
+ host: "localhost"
2617
+ };
2618
+
2619
+ class PipelineOrchestrator {
2620
+ config;
2621
+ compiler = null;
2622
+ appIR = null;
2623
+ isRunning = false;
2624
+ stages = new Map;
2625
+ constructor(config = {}) {
2626
+ this.config = { ...defaultPipelineConfig, ...config };
2627
+ }
2628
+ async initialize() {
2629
+ this.compiler = createCompiler({
2630
+ strict: false,
2631
+ forceGenerate: false,
2632
+ compiler: {
2633
+ sourceDir: this.config.sourceDir,
2634
+ outputDir: this.config.outputDir,
2635
+ entryFile: "src/app.ts",
2636
+ schemas: {
2637
+ enforceNaming: true,
2638
+ enforcePlacement: true
2639
+ },
2640
+ openapi: {
2641
+ output: ".vertz/generated/openapi.json",
2642
+ info: { title: "Vertz App", version: "1.0.0" }
2643
+ },
2644
+ validation: {
2645
+ requireResponseSchema: false,
2646
+ detectDeadCode: false
2647
+ }
2648
+ }
2649
+ });
2650
+ }
2651
+ async runFull() {
2652
+ const startTime = performance.now();
2653
+ const stages = [];
2654
+ let success = true;
2655
+ try {
2656
+ const analyzeResult = await this.runAnalyze();
2657
+ stages.push(analyzeResult);
2658
+ if (!analyzeResult.success) {
2659
+ success = false;
2660
+ }
2661
+ if (success && this.appIR) {
2662
+ const generateResult = await this.runCodegen();
2663
+ stages.push(generateResult);
2664
+ if (!generateResult.success) {
2665
+ success = false;
2666
+ }
2667
+ }
2668
+ } catch (error) {
2669
+ success = false;
2670
+ stages.push({
2671
+ stage: "analyze",
2672
+ success: false,
2673
+ durationMs: performance.now() - startTime,
2674
+ error: error instanceof Error ? error : new Error(String(error))
2675
+ });
2676
+ }
2677
+ return {
2678
+ success,
2679
+ stages,
2680
+ totalDurationMs: performance.now() - startTime,
2681
+ appIR: this.appIR ?? undefined
2682
+ };
2683
+ }
2684
+ async runStages(stages) {
2685
+ const startTime = performance.now();
2686
+ const results = [];
2687
+ for (const stage of stages) {
2688
+ let result;
2689
+ switch (stage) {
2690
+ case "analyze":
2691
+ result = await this.runAnalyze();
2692
+ break;
2693
+ case "codegen":
2694
+ result = await this.runCodegen();
2695
+ break;
2696
+ case "build-ui":
2697
+ result = await this.runBuildUI();
2698
+ break;
2699
+ case "db-sync":
2700
+ result = await this.runDbSync();
2701
+ break;
2702
+ default:
2703
+ continue;
2704
+ }
2705
+ results.push(result);
2706
+ this.stages.set(stage, result);
2707
+ }
2708
+ const allSuccess = results.every((r) => r.success);
2709
+ return {
2710
+ success: allSuccess,
2711
+ stages: results,
2712
+ totalDurationMs: performance.now() - startTime,
2713
+ appIR: this.appIR ?? undefined
2714
+ };
2715
+ }
2716
+ async runAnalyze() {
2717
+ const startTime = performance.now();
2718
+ if (!this.compiler) {
2719
+ await this.initialize();
2720
+ }
2721
+ try {
2722
+ this.appIR = await this.compiler.analyze();
2723
+ const diagnostics = await this.compiler.validate(this.appIR);
2724
+ const hasErrors = diagnostics.some((d) => d.severity === "error");
2725
+ return {
2726
+ stage: "analyze",
2727
+ success: !hasErrors,
2728
+ durationMs: performance.now() - startTime,
2729
+ output: hasErrors ? `${diagnostics.filter((d) => d.severity === "error").length} errors` : "Analysis complete"
2730
+ };
2731
+ } catch (error) {
2732
+ return {
2733
+ stage: "analyze",
2734
+ success: false,
2735
+ durationMs: performance.now() - startTime,
2736
+ error: error instanceof Error ? error : new Error(String(error))
2737
+ };
2738
+ }
2739
+ }
2740
+ async runCodegen() {
2741
+ const startTime = performance.now();
2742
+ if (!this.appIR) {
2743
+ return {
2744
+ stage: "codegen",
2745
+ success: false,
2746
+ durationMs: performance.now() - startTime,
2747
+ error: new Error("No AppIR available. Run analyze first.")
2748
+ };
2749
+ }
2750
+ try {
2751
+ const pipeline = createCodegenPipeline();
2752
+ const config = {
2753
+ generators: ["typescript"],
2754
+ outputDir: this.config.outputDir,
2755
+ format: true,
2756
+ incremental: true
2757
+ };
2758
+ const resolvedConfig = pipeline.resolveConfig(config);
2759
+ const result = await generate(this.appIR, resolvedConfig);
2760
+ return {
2761
+ stage: "codegen",
2762
+ success: true,
2763
+ durationMs: performance.now() - startTime,
2764
+ output: `Generated ${result.fileCount} files`
2765
+ };
2766
+ } catch (error) {
2767
+ return {
2768
+ stage: "codegen",
2769
+ success: false,
2770
+ durationMs: performance.now() - startTime,
2771
+ error: error instanceof Error ? error : new Error(String(error))
2772
+ };
2773
+ }
2774
+ }
2775
+ async runBuildUI() {
2776
+ const startTime = performance.now();
2777
+ return {
2778
+ stage: "build-ui",
2779
+ success: true,
2780
+ durationMs: performance.now() - startTime,
2781
+ output: "UI build delegated to Vite"
2782
+ };
2783
+ }
2784
+ async runDbSync() {
2785
+ const startTime = performance.now();
2786
+ return {
2787
+ stage: "db-sync",
2788
+ success: true,
2789
+ durationMs: performance.now() - startTime,
2790
+ output: "DB sync complete (noop for now)"
2791
+ };
2792
+ }
2793
+ getAppIR() {
2794
+ return this.appIR;
2795
+ }
2796
+ isPipelineRunning() {
2797
+ return this.isRunning;
2798
+ }
2799
+ getStageResult(stage) {
2800
+ return this.stages.get(stage);
2801
+ }
2802
+ async dispose() {
2803
+ this.compiler = null;
2804
+ this.appIR = null;
2805
+ this.stages.clear();
2806
+ }
2807
+ }
2808
+ function createPipelineOrchestrator(config) {
2809
+ return new PipelineOrchestrator(config);
2810
+ }
2811
+ // src/pipeline/watcher.ts
2812
+ var DEFAULT_IGNORE_PATTERNS = [
2813
+ "/node_modules/",
2814
+ "/.git/",
2815
+ "/.vertz/generated/",
2816
+ "/dist/",
2817
+ "/.turbo/",
2818
+ "/coverage/"
2819
+ ];
2820
+ var DEFAULT_DEBOUNCE_MS = 100;
2821
+ function categorizeFileChange(path) {
2822
+ const normalizedPath = path.replace(/\\/g, "/").toLowerCase();
2823
+ if (normalizedPath.includes(".domain.ts")) {
2824
+ return "domain";
2825
+ }
2826
+ if (normalizedPath.includes(".module.ts")) {
2827
+ return "module";
2828
+ }
2829
+ if (normalizedPath.includes(".schema.ts")) {
2830
+ return "schema";
2831
+ }
2832
+ if (normalizedPath.includes(".service.ts")) {
2833
+ return "service";
2834
+ }
2835
+ if (normalizedPath.includes(".route.ts")) {
2836
+ return "route";
2837
+ }
2838
+ if (normalizedPath.endsWith(".tsx") || normalizedPath.endsWith(".jsx")) {
2839
+ return "component";
2840
+ }
2841
+ if (normalizedPath === "vertz.config.ts" || normalizedPath === "vertz.config.js" || normalizedPath === "vertz.config.mts" || normalizedPath.includes("vertz.config")) {
2842
+ return "config";
2843
+ }
2844
+ return "other";
2845
+ }
2846
+ function getAffectedStages(category) {
2847
+ switch (category) {
2848
+ case "domain":
2849
+ case "module":
2850
+ case "service":
2851
+ case "route":
2852
+ return ["analyze", "codegen"];
2853
+ case "schema":
2854
+ return ["codegen"];
2855
+ case "component":
2856
+ return ["build-ui"];
2857
+ case "config":
2858
+ return ["analyze", "codegen", "build-ui"];
2859
+ case "other":
2860
+ default:
2861
+ return ["build-ui"];
2862
+ }
2863
+ }
2864
+ function getStagesForChanges(changes) {
2865
+ const stages = new Set;
2866
+ for (const change of changes) {
2867
+ const category = change.category ?? categorizeFileChange(change.path);
2868
+ const affected = getAffectedStages(category);
2869
+ affected.forEach((s) => stages.add(s));
2870
+ }
2871
+ if (stages.has("codegen") && !stages.has("analyze")) {
2872
+ stages.add("analyze");
2873
+ }
2874
+ return Array.from(stages);
2875
+ }
2876
+ function createWatcher(config) {
2877
+ const {
2878
+ dir,
2879
+ ignorePatterns = DEFAULT_IGNORE_PATTERNS,
2880
+ debounceMs = DEFAULT_DEBOUNCE_MS,
2881
+ onChange
2882
+ } = config;
2883
+ const handlers = [];
2884
+ let pending = [];
2885
+ let timer;
2886
+ function isIgnored(path) {
2887
+ return ignorePatterns.some((pattern) => path.includes(pattern));
2888
+ }
2889
+ function flush() {
2890
+ if (pending.length === 0)
2891
+ return;
2892
+ const changes = pending.map((change) => ({
2893
+ ...change,
2894
+ category: categorizeFileChange(change.path)
2895
+ }));
2896
+ const batch = pending;
2897
+ pending = [];
2898
+ for (const handler of handlers) {
2899
+ handler(changes);
2900
+ }
2901
+ if (onChange) {
2902
+ onChange(changes);
2903
+ }
2904
+ }
2905
+ return {
2906
+ on(_event, handler) {
2907
+ handlers.push(handler);
2908
+ },
2909
+ _emit(change) {
2910
+ if (isIgnored(change.path))
2911
+ return;
2912
+ pending.push(change);
2913
+ if (timer !== undefined) {
2914
+ clearTimeout(timer);
2915
+ }
2916
+ timer = setTimeout(flush, debounceMs);
2917
+ },
2918
+ close() {
2919
+ if (timer !== undefined) {
2920
+ clearTimeout(timer);
2921
+ }
2922
+ pending = [];
2923
+ }
2924
+ };
2925
+ }
2926
+
2927
+ class PipelineWatcherImpl {
2928
+ handlers = new Map;
2929
+ watcher;
2930
+ config;
2931
+ isClosed = false;
2932
+ constructor(config) {
2933
+ this.config = config;
2934
+ this.watcher = createWatcher({
2935
+ ...config,
2936
+ onChange: (changes) => this.handleChanges(changes)
2937
+ });
2938
+ }
2939
+ handleChanges(changes) {
2940
+ const stages = getStagesForChanges(changes);
2941
+ for (const stage of stages) {
2942
+ const handlers = this.handlers.get(stage);
2943
+ if (handlers) {
2944
+ for (const handler of handlers) {
2945
+ handler(changes);
2946
+ }
2947
+ }
2948
+ }
2949
+ }
2950
+ on(event, handler) {
2951
+ if (this.isClosed)
2952
+ return;
2953
+ const handlers = this.handlers.get(event) ?? [];
2954
+ handlers.push(handler);
2955
+ this.handlers.set(event, handlers);
2956
+ }
2957
+ close() {
2958
+ this.isClosed = true;
2959
+ this.watcher.close();
2960
+ this.handlers.clear();
2961
+ }
2962
+ }
2963
+ function createPipelineWatcher(config) {
2964
+ return new PipelineWatcherImpl(config);
2965
+ }
2966
+ // src/utils/paths.ts
2967
+ import { existsSync as existsSync2 } from "node:fs";
2968
+ import { dirname as dirname2, join as join2, resolve } from "node:path";
2969
+ var ROOT_MARKERS = ["package.json", "vertz.config.ts", "vertz.config.js"];
2970
+ function findProjectRoot(startDir) {
2971
+ let current = resolve(startDir ?? process.cwd());
2972
+ while (true) {
2973
+ for (const marker of ROOT_MARKERS) {
2974
+ if (existsSync2(join2(current, marker))) {
2975
+ return current;
2976
+ }
2977
+ }
2978
+ const parent = dirname2(current);
2979
+ if (parent === current) {
2980
+ break;
2981
+ }
2982
+ current = parent;
2983
+ }
2984
+ return;
2985
+ }
2986
+
2987
+ // src/utils/format.ts
2988
+ function formatDuration(ms) {
2989
+ if (ms < 1000) {
2990
+ return `${Math.round(ms)}ms`;
2991
+ }
2992
+ const seconds = ms / 1000;
2993
+ return `${seconds.toFixed(2)}s`;
2994
+ }
2995
+ function formatFileSize(bytes) {
2996
+ if (bytes < 1024) {
2997
+ return `${bytes} B`;
2998
+ }
2999
+ const kb = bytes / 1024;
3000
+ if (kb < 1024) {
3001
+ return `${kb.toFixed(1)} KB`;
3002
+ }
3003
+ const mb = kb / 1024;
3004
+ return `${mb.toFixed(1)} MB`;
3005
+ }
3006
+ function formatPath(absolutePath, cwd) {
3007
+ const base = cwd ?? process.cwd();
3008
+ if (absolutePath.startsWith(base)) {
3009
+ const relative = absolutePath.slice(base.length);
3010
+ if (relative.startsWith("/")) {
3011
+ return relative.slice(1);
3012
+ }
3013
+ return relative;
3014
+ }
3015
+ return absolutePath;
3016
+ }
3017
+
3018
+ // src/commands/dev.ts
3019
+ async function devAction(options = {}) {
3020
+ const {
3021
+ port = 3000,
3022
+ host = "localhost",
3023
+ open = false,
3024
+ typecheck = true,
3025
+ verbose = false
3026
+ } = options;
3027
+ const projectRoot = findProjectRoot(process.cwd());
3028
+ if (!projectRoot) {
3029
+ console.error("Error: Could not find project root. Are you in a Vertz project?");
3030
+ process.exit(1);
3031
+ }
3032
+ console.log(`\uD83D\uDE80 Starting Vertz development server...
3033
+ `);
3034
+ const pipelineConfig = {
3035
+ sourceDir: "src",
3036
+ outputDir: ".vertz/generated",
3037
+ typecheck,
3038
+ autoSyncDb: true,
3039
+ open,
3040
+ port,
3041
+ host
3042
+ };
3043
+ const orchestrator = new PipelineOrchestrator(pipelineConfig);
3044
+ let isRunning = true;
3045
+ let viteProcess = null;
3046
+ const shutdown = async () => {
3047
+ console.log(`
3048
+
3049
+ \uD83D\uDC4B Shutting down...`);
3050
+ isRunning = false;
3051
+ if (viteProcess) {
3052
+ viteProcess.kill("SIGTERM");
3053
+ }
3054
+ await orchestrator.dispose();
3055
+ process.exit(0);
3056
+ };
3057
+ process.on("SIGINT", shutdown);
3058
+ process.on("SIGTERM", shutdown);
3059
+ try {
3060
+ console.log("\uD83D\uDCE6 Running initial pipeline...");
3061
+ const initialResult = await orchestrator.runFull();
3062
+ if (!initialResult.success) {
3063
+ console.error(`
3064
+ ❌ Initial pipeline failed:`);
3065
+ for (const stage of initialResult.stages) {
3066
+ if (!stage.success && stage.error) {
3067
+ console.error(` - ${stage.stage}: ${stage.error.message}`);
3068
+ }
3069
+ }
3070
+ console.log(`
3071
+ \uD83D\uDCA1 Try fixing the errors above and the watcher will retry.`);
3072
+ } else {
3073
+ if (verbose) {
3074
+ console.log(`
3075
+ ✅ Initial pipeline complete:`);
3076
+ for (const stage of initialResult.stages) {
3077
+ console.log(` - ${stage.stage}: ${stage.output} (${formatDuration(stage.durationMs)})`);
3078
+ }
3079
+ }
3080
+ }
3081
+ console.log(`
3082
+ \uD83D\uDC40 Watching for file changes...`);
3083
+ const watcher = createPipelineWatcher({
3084
+ dir: join3(projectRoot, "src"),
3085
+ debounceMs: 100,
3086
+ onChange: async (changes) => {
3087
+ if (!isRunning)
3088
+ return;
3089
+ const stages = getStagesForFileChanges(changes);
3090
+ if (verbose) {
3091
+ console.log(`
3092
+ \uD83D\uDD04 File change detected: ${changes.map((c) => c.path).join(", ")}`);
3093
+ console.log(` Running stages: ${stages.join(", ")}`);
3094
+ }
3095
+ const result = await orchestrator.runStages(stages);
3096
+ if (!result.success) {
3097
+ console.error(`
3098
+ ❌ Pipeline update failed:`);
3099
+ for (const stage of result.stages) {
3100
+ if (!stage.success && stage.error) {
3101
+ console.error(` - ${stage.stage}: ${stage.error.message}`);
3102
+ }
3103
+ }
3104
+ console.log(`
3105
+ \uD83D\uDCA1 Try fixing the errors above.`);
3106
+ } else if (verbose) {
3107
+ for (const stage of result.stages) {
3108
+ console.log(` ✓ ${stage.stage}: ${stage.output}`);
3109
+ }
3110
+ }
3111
+ }
3112
+ });
3113
+ console.log(`
3114
+ \uD83C\uDF10 Starting Vite dev server on http://${host}:${port}...`);
3115
+ viteProcess = spawn("npx", ["vite", "--port", String(port), "--host", host], {
3116
+ cwd: projectRoot,
3117
+ stdio: "inherit",
3118
+ shell: true,
3119
+ env: {
3120
+ ...process.env,
3121
+ VERTZ_GENERATED_DIR: pipelineConfig.outputDir
3122
+ }
3123
+ });
3124
+ viteProcess.on("close", (code) => {
3125
+ if (isRunning && code !== 0) {
3126
+ console.log(`
3127
+ ⚠️ Vite process exited with code ${code}`);
3128
+ }
3129
+ shutdown();
3130
+ });
3131
+ } catch (error) {
3132
+ console.error(`
3133
+ ❌ Fatal error:`, error instanceof Error ? error.message : String(error));
3134
+ await shutdown();
3135
+ process.exit(1);
3136
+ }
3137
+ }
3138
+ function getStagesForFileChanges(changes) {
3139
+ const stages = new Set;
3140
+ for (const change of changes) {
3141
+ const path = change.path.toLowerCase();
3142
+ if (path.includes(".domain.ts") || path.includes(".module.ts") || path.includes(".service.ts") || path.includes(".route.ts")) {
3143
+ stages.add("analyze");
3144
+ stages.add("codegen");
3145
+ } else if (path.includes(".schema.ts")) {
3146
+ stages.add("codegen");
3147
+ } else if (path.endsWith(".tsx") || path.endsWith(".jsx")) {
3148
+ stages.add("build-ui");
3149
+ } else if (path.includes("vertz.config") || path.includes("vite.config")) {
3150
+ stages.add("analyze");
3151
+ stages.add("codegen");
3152
+ stages.add("build-ui");
3153
+ } else {
3154
+ stages.add("build-ui");
3155
+ }
3156
+ }
3157
+ if (stages.has("codegen") && !stages.has("analyze")) {
3158
+ stages.add("analyze");
3159
+ }
3160
+ return Array.from(stages);
3161
+ }
3162
+ function registerDevCommand(program) {
3163
+ program.command("dev").description("Start development server with hot reload (unified pipeline)").option("-p, --port <port>", "Server port", "3000").option("--host <host>", "Server host", "localhost").option("--open", "Open browser on start").option("--no-typecheck", "Disable background type checking").option("-v, --verbose", "Verbose output").action(async (opts) => {
3164
+ await devAction({
3165
+ port: parseInt(opts.port, 10),
3166
+ host: opts.host,
3167
+ open: opts.open,
3168
+ typecheck: opts.typecheck !== false && !opts.noTypecheck,
3169
+ verbose: opts.verbose
3170
+ });
3171
+ });
3172
+ }
3173
+
3174
+ // src/commands/build.ts
3175
+ import { existsSync as existsSync4 } from "node:fs";
3176
+ import { join as join5 } from "node:path";
3177
+
3178
+ // src/production-build/orchestrator.ts
3179
+ var esbuild = __toESM(require_main(), 1);
3180
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2, readdirSync as readdirSync2, statSync as statSync2 } from "node:fs";
3181
+ import { join as join4 } from "node:path";
3182
+ import { createCompiler as createCompiler2 } from "@vertz/compiler";
3183
+
3184
+ // src/production-build/types.ts
3185
+ var defaultBuildConfig = {
3186
+ sourceDir: "src",
3187
+ outputDir: ".vertz/build",
3188
+ typecheck: true,
3189
+ minify: true,
3190
+ sourcemap: false,
3191
+ target: "node",
3192
+ entryPoint: "src/app.ts"
3193
+ };
3194
+
3195
+ // src/production-build/orchestrator.ts
3196
+ class BuildOrchestrator {
3197
+ config;
3198
+ pipeline;
3199
+ compiler = null;
3200
+ constructor(config = {}) {
3201
+ this.config = { ...defaultBuildConfig, ...config };
3202
+ const pipelineConfig = {
3203
+ sourceDir: this.config.sourceDir,
3204
+ outputDir: ".vertz/generated",
3205
+ typecheck: this.config.typecheck,
3206
+ autoSyncDb: false,
3207
+ port: 3000,
3208
+ host: "localhost"
3209
+ };
3210
+ this.pipeline = new PipelineOrchestrator(pipelineConfig);
3211
+ }
3212
+ async build() {
3213
+ const startTime = performance.now();
3214
+ const stages = {
3215
+ codegen: false,
3216
+ typecheck: false,
3217
+ bundle: false
3218
+ };
3219
+ let manifest = {
3220
+ entryPoint: this.config.entryPoint,
3221
+ outputDir: this.config.outputDir,
3222
+ generatedFiles: [],
3223
+ size: 0,
3224
+ buildTime: Date.now(),
3225
+ target: this.config.target
3226
+ };
3227
+ try {
3228
+ console.log("\uD83D\uDCE6 Running codegen pipeline...");
3229
+ const codegenResult = await this.runCodegen();
3230
+ stages.codegen = codegenResult.success;
3231
+ if (!codegenResult.success) {
3232
+ return this.createFailureResult(stages, manifest, startTime, `Codegen failed: ${codegenResult.stages.map((s) => s.error?.message).join(", ")}`);
3233
+ }
3234
+ manifest.generatedFiles = this.collectGeneratedFiles();
3235
+ if (this.config.typecheck) {
3236
+ console.log("\uD83D\uDD0D Running TypeScript type checking...");
3237
+ const typecheckResult = await this.runTypecheck();
3238
+ stages.typecheck = typecheckResult;
3239
+ if (!typecheckResult) {
3240
+ return this.createFailureResult(stages, manifest, startTime, "Type checking failed");
3241
+ }
3242
+ }
3243
+ console.log("\uD83D\uDCE6 Bundling application...");
3244
+ const bundleResult = await this.runBundle();
3245
+ stages.bundle = bundleResult.success;
3246
+ if (!bundleResult.success) {
3247
+ return this.createFailureResult(stages, manifest, startTime, bundleResult.error || "Bundling failed");
3248
+ }
3249
+ manifest.size = bundleResult.size || 0;
3250
+ manifest.dependencies = bundleResult.dependencies;
3251
+ manifest.treeShaken = bundleResult.treeShaken;
3252
+ await this.writeManifest(manifest);
3253
+ const durationMs = performance.now() - startTime;
3254
+ console.log(`
3255
+ ✅ Build completed successfully!`);
3256
+ console.log(` Output: ${this.config.outputDir}`);
3257
+ console.log(` Size: ${formatFileSize(manifest.size)}`);
3258
+ console.log(` Time: ${formatDuration(durationMs)}`);
3259
+ return {
3260
+ success: true,
3261
+ stages,
3262
+ manifest,
3263
+ durationMs
3264
+ };
3265
+ } catch (error) {
3266
+ return this.createFailureResult(stages, manifest, startTime, error instanceof Error ? error.message : String(error));
3267
+ }
3268
+ }
3269
+ async runCodegen() {
3270
+ return this.pipeline.runFull();
3271
+ }
3272
+ async runTypecheck() {
3273
+ try {
3274
+ if (!this.compiler) {
3275
+ this.compiler = createCompiler2({
3276
+ strict: false,
3277
+ forceGenerate: false,
3278
+ compiler: {
3279
+ sourceDir: this.config.sourceDir,
3280
+ outputDir: ".vertz/generated",
3281
+ entryFile: this.config.entryPoint,
3282
+ schemas: {
3283
+ enforceNaming: true,
3284
+ enforcePlacement: true
3285
+ },
3286
+ openapi: {
3287
+ output: ".vertz/generated/openapi.json",
3288
+ info: { title: "Vertz App", version: "1.0.0" }
3289
+ },
3290
+ validation: {
3291
+ requireResponseSchema: false,
3292
+ detectDeadCode: false
3293
+ }
3294
+ }
3295
+ });
3296
+ }
3297
+ const ir = await this.compiler.analyze();
3298
+ const diagnostics = await this.compiler.validate(ir);
3299
+ const hasErrors = diagnostics.some((d) => d.severity === "error");
3300
+ if (hasErrors) {
3301
+ const errors = diagnostics.filter((d) => d.severity === "error");
3302
+ console.error(`
3303
+ ❌ Type checking found ${errors.length} error(s):`);
3304
+ errors.forEach((d) => {
3305
+ console.error(` ${d.file || "unknown"}:${d.line}:${d.column} - ${d.message}`);
3306
+ });
3307
+ return false;
3308
+ }
3309
+ const warnings = diagnostics.filter((d) => d.severity === "warning");
3310
+ if (warnings.length > 0) {
3311
+ console.log(`⚠️ Type checking found ${warnings.length} warning(s)`);
3312
+ }
3313
+ return true;
3314
+ } catch (error) {
3315
+ console.error("Type checking error:", error instanceof Error ? error.message : String(error));
3316
+ return false;
3317
+ }
3318
+ }
3319
+ async runBundle() {
3320
+ try {
3321
+ if (!existsSync3(this.config.outputDir)) {
3322
+ mkdirSync2(this.config.outputDir, { recursive: true });
3323
+ }
3324
+ const entryFile = join4(process.cwd(), this.config.entryPoint);
3325
+ const outfile = join4(this.config.outputDir, "index.js");
3326
+ const buildResult = await esbuild.build({
3327
+ entryPoints: [entryFile],
3328
+ bundle: true,
3329
+ platform: "node",
3330
+ format: "esm",
3331
+ outfile,
3332
+ target: this.getEsbuildTarget(),
3333
+ minify: this.config.minify,
3334
+ sourcemap: this.config.sourcemap,
3335
+ external: ["@vertz/*", "@anthropic-ai/sdk"],
3336
+ logLevel: "info",
3337
+ metafile: true
3338
+ });
3339
+ let size = 0;
3340
+ if (existsSync3(outfile)) {
3341
+ size = statSync2(outfile).size;
3342
+ }
3343
+ const dependencies = [];
3344
+ const treeShaken = [];
3345
+ if (buildResult.metafile) {
3346
+ const outputs = buildResult.metafile.outputs;
3347
+ for (const [_path, info] of Object.entries(outputs)) {
3348
+ for (const inputPath of Object.keys(info.inputs)) {
3349
+ if (!dependencies.includes(inputPath)) {
3350
+ dependencies.push(inputPath);
3351
+ }
3352
+ }
3353
+ }
3354
+ }
3355
+ return {
3356
+ success: true,
3357
+ size,
3358
+ dependencies,
3359
+ treeShaken
3360
+ };
3361
+ } catch (error) {
3362
+ return {
3363
+ success: false,
3364
+ error: error instanceof Error ? error.message : String(error)
3365
+ };
3366
+ }
3367
+ }
3368
+ getEsbuildTarget() {
3369
+ switch (this.config.target) {
3370
+ case "edge":
3371
+ return "edge88";
3372
+ case "worker":
3373
+ return "esnext";
3374
+ case "node":
3375
+ default:
3376
+ return "node18";
3377
+ }
3378
+ }
3379
+ collectGeneratedFiles() {
3380
+ const generatedDir = ".vertz/generated";
3381
+ const files = [];
3382
+ if (!existsSync3(generatedDir)) {
3383
+ return files;
3384
+ }
3385
+ const collectRecursive = (dir, basePath = "") => {
3386
+ const entries = readdirSync2(dir);
3387
+ for (const entry of entries) {
3388
+ const fullPath = join4(dir, entry);
3389
+ const relativePath = join4(basePath, entry);
3390
+ const stat = statSync2(fullPath);
3391
+ if (stat.isDirectory()) {
3392
+ collectRecursive(fullPath, relativePath);
3393
+ } else if (stat.isFile()) {
3394
+ const type = this.getFileType(entry);
3395
+ files.push({
3396
+ path: relativePath,
3397
+ size: stat.size,
3398
+ type
3399
+ });
3400
+ }
3401
+ }
3402
+ };
3403
+ try {
3404
+ collectRecursive(generatedDir);
3405
+ } catch {}
3406
+ return files;
3407
+ }
3408
+ getFileType(filename) {
3409
+ const lower = filename.toLowerCase();
3410
+ if (lower.includes("types") || lower.includes(".d.ts"))
3411
+ return "type";
3412
+ if (lower.includes("routes") || lower.includes("router"))
3413
+ return "route";
3414
+ if (lower.includes("openapi") || lower.includes("swagger"))
3415
+ return "openapi";
3416
+ if (lower.includes("client") || lower.includes("sdk"))
3417
+ return "client";
3418
+ return "type";
3419
+ }
3420
+ async writeManifest(manifest) {
3421
+ const manifestPath = join4(this.config.outputDir, "manifest.json");
3422
+ const manifestData = {
3423
+ ...manifest,
3424
+ generatedFiles: manifest.generatedFiles.map((f) => ({
3425
+ ...f,
3426
+ path: f.path.replace(/\\/g, "/")
3427
+ }))
3428
+ };
3429
+ writeFileSync2(manifestPath, JSON.stringify(manifestData, null, 2));
3430
+ console.log(` Manifest: ${manifestPath}`);
3431
+ }
3432
+ createFailureResult(stages, manifest, startTime, error) {
3433
+ return {
3434
+ success: false,
3435
+ stages,
3436
+ manifest,
3437
+ error,
3438
+ durationMs: performance.now() - startTime
3439
+ };
3440
+ }
3441
+ async dispose() {
3442
+ await this.pipeline.dispose();
3443
+ this.compiler = null;
3444
+ }
3445
+ }
3446
+ // src/commands/build.ts
3447
+ async function buildAction(options = {}) {
3448
+ const {
3449
+ strict: _strict = false,
3450
+ output,
3451
+ target = "node",
3452
+ noTypecheck = false,
3453
+ noMinify = false,
3454
+ sourcemap = false,
3455
+ verbose = false
3456
+ } = options;
3457
+ const projectRoot = findProjectRoot(process.cwd());
3458
+ if (!projectRoot) {
3459
+ console.error("Error: Could not find project root. Are you in a Vertz project?");
3460
+ return 1;
3461
+ }
3462
+ const entryPoint = "src/app.ts";
3463
+ const entryPath = join5(projectRoot, entryPoint);
3464
+ if (!existsSync4(entryPath)) {
3465
+ console.error(`Error: Entry point not found at ${entryPoint}`);
3466
+ console.error("Make sure you have an app.ts in your src directory.");
3467
+ return 1;
3468
+ }
3469
+ console.log(`\uD83D\uDE80 Starting Vertz production build...
3470
+ `);
3471
+ const buildConfig = {
3472
+ sourceDir: "src",
3473
+ outputDir: output || ".vertz/build",
3474
+ typecheck: !noTypecheck,
3475
+ minify: !noMinify,
3476
+ sourcemap,
3477
+ target,
3478
+ entryPoint
3479
+ };
3480
+ if (verbose) {
3481
+ console.log("Build configuration:");
3482
+ console.log(` Entry: ${entryPoint}`);
3483
+ console.log(` Output: ${buildConfig.outputDir}`);
3484
+ console.log(` Target: ${target}`);
3485
+ console.log(` Typecheck: ${buildConfig.typecheck ? "enabled" : "disabled"}`);
3486
+ console.log(` Minify: ${buildConfig.minify ? "enabled" : "disabled"}`);
3487
+ console.log(` Sourcemap: ${buildConfig.sourcemap ? "enabled" : "disabled"}`);
3488
+ console.log("");
3489
+ }
3490
+ const orchestrator = new BuildOrchestrator(buildConfig);
3491
+ try {
3492
+ const result = await orchestrator.build();
3493
+ if (!result.success) {
3494
+ console.error(`
3495
+ ❌ Build failed:`);
3496
+ console.error(` ${result.error}`);
3497
+ await orchestrator.dispose();
3498
+ return 1;
3499
+ }
3500
+ console.log(`
3501
+ \uD83D\uDCCA Build Summary:`);
3502
+ console.log(` Entry: ${result.manifest.entryPoint}`);
3503
+ console.log(` Output: ${result.manifest.outputDir}`);
3504
+ console.log(` Size: ${formatFileSize(result.manifest.size)}`);
3505
+ console.log(` Time: ${formatDuration(result.durationMs)}`);
3506
+ console.log(` Target: ${result.manifest.target}`);
3507
+ if (result.manifest.generatedFiles.length > 0) {
3508
+ console.log(`
3509
+ \uD83D\uDCC1 Generated Files (${result.manifest.generatedFiles.length}):`);
3510
+ const byType = new Map;
3511
+ for (const file of result.manifest.generatedFiles) {
3512
+ const count = byType.get(file.type) || 0;
3513
+ byType.set(file.type, count + 1);
3514
+ }
3515
+ for (const [type, count] of byType) {
3516
+ console.log(` - ${type}: ${count} file(s)`);
3517
+ }
3518
+ }
3519
+ await orchestrator.dispose();
3520
+ return 0;
3521
+ } catch (error) {
3522
+ console.error(`
3523
+ ❌ Fatal error:`, error instanceof Error ? error.message : String(error));
3524
+ await orchestrator.dispose();
3525
+ return 1;
3526
+ }
3527
+ }
3528
+
3529
+ // src/commands/create.ts
3530
+ import { resolveOptions, scaffold } from "@vertz/create-vertz-app";
3531
+ async function createAction(options) {
3532
+ const { projectName, runtime, example } = options;
3533
+ if (!projectName) {
3534
+ console.error("Error: Project name is required");
3535
+ console.error("Usage: vertz create <project-name>");
3536
+ process.exit(1);
3537
+ }
3538
+ const validName = /^[a-z0-9-]+$/.test(projectName);
3539
+ if (!validName) {
3540
+ console.error("Error: Project name must be lowercase alphanumeric with hyphens only");
3541
+ process.exit(1);
3542
+ }
3543
+ const validRuntimes = ["bun", "node", "deno"];
3544
+ const runtimeValue = (runtime || "bun").toLowerCase();
3545
+ if (!validRuntimes.includes(runtimeValue)) {
3546
+ console.error(`Error: Invalid runtime. Must be one of: ${validRuntimes.join(", ")}`);
3547
+ process.exit(1);
3548
+ }
3549
+ let includeExample;
3550
+ if (example === true) {
3551
+ includeExample = true;
3552
+ } else if (example === false) {
3553
+ includeExample = false;
3554
+ }
3555
+ const cliOptions = {
3556
+ projectName,
3557
+ runtime: runtimeValue,
3558
+ includeExample
3559
+ };
3560
+ try {
3561
+ const resolved = await resolveOptions(cliOptions);
3562
+ console.log(`Creating Vertz app: ${resolved.projectName}`);
3563
+ console.log(`Runtime: ${resolved.runtime}`);
3564
+ console.log(`Include example: ${resolved.includeExample ? "Yes" : "No"}`);
3565
+ const targetDir = process.cwd();
3566
+ await scaffold(targetDir, resolved);
3567
+ console.log(`
3568
+ ✓ Created ${resolved.projectName}`);
3569
+ console.log(`
3570
+ Next steps:`);
3571
+ console.log(` cd ${resolved.projectName}`);
3572
+ console.log(` bun install`);
3573
+ console.log(` bun run dev`);
3574
+ } catch (error) {
3575
+ if (error instanceof Error && error.message.includes("already exists")) {
3576
+ console.error(`
3577
+ Error: Directory "${projectName}" already exists.`);
3578
+ console.error("Please choose a different project name or remove the existing directory.");
3579
+ } else {
3580
+ console.error("Error:", error instanceof Error ? error.message : error);
3581
+ }
3582
+ process.exit(1);
3583
+ }
3584
+ }
3585
+
3586
+ // src/cli.ts
3587
+ function createCLI() {
3588
+ const program = new Command;
3589
+ program.name("vertz").description("Vertz CLI — build, check, and serve your Vertz app").version("0.1.0");
3590
+ program.command("create <name>").description("Scaffold a new Vertz project").option("-r, --runtime <runtime>", "Runtime to use (bun, node, deno)", "bun").option("-e, --example", "Include example health module").option("--no-example", "Exclude example health module").action(async (name, opts) => {
3591
+ await createAction({
3592
+ projectName: name,
3593
+ runtime: opts.runtime,
3594
+ example: opts.example
3595
+ });
3596
+ });
3597
+ program.command("check").description("Type-check and validate the project").option("--strict", "Enable strict mode").option("--format <format>", "Output format (text, json, github)", "text");
3598
+ program.command("build").description("Compile the project for production").option("--strict", "Enable strict mode").option("-o, --output <dir>", "Output directory", ".vertz/build").option("-t, --target <target>", "Build target (node, edge, worker)", "node").option("--no-typecheck", "Disable type checking").option("--no-minify", "Disable minification").option("--sourcemap", "Generate sourcemaps").option("-v, --verbose", "Verbose output").action(async (opts) => {
3599
+ const exitCode = await buildAction({
3600
+ strict: opts.strict,
3601
+ output: opts.output,
3602
+ target: opts.target,
3603
+ noTypecheck: opts.noTypecheck,
3604
+ noMinify: opts.noMinify,
3605
+ sourcemap: opts.sourcemap,
3606
+ verbose: opts.verbose
3607
+ });
3608
+ process.exit(exitCode);
3609
+ });
3610
+ program.command("dev").description("Start development server with hot reload (unified pipeline)").option("-p, --port <port>", "Server port", "3000").option("--host <host>", "Server host", "localhost").option("--open", "Open browser on start").option("--no-typecheck", "Disable background type checking").option("-v, --verbose", "Verbose output").action(async (opts) => {
3611
+ await devAction({
3612
+ port: parseInt(opts.port, 10),
3613
+ host: opts.host,
3614
+ open: opts.open,
3615
+ typecheck: opts.typecheck !== false && !opts.noTypecheck,
3616
+ verbose: opts.verbose
3617
+ });
3618
+ });
3619
+ program.command("generate [type] [name]").description("Generate a module, service, router, schema, or auto-discover domains").option("--dry-run", "Preview generated files without writing").option("--source-dir <dir>", "Source directory", "src").allowUnknownOption().action(async (type, name, options) => {
3620
+ if (!type) {
3621
+ await generateDomainAction(options);
3622
+ return;
3623
+ }
3624
+ const validTypes = ["module", "service", "router", "schema"];
3625
+ if (!validTypes.includes(type)) {
3626
+ await generateDomainAction(options);
3627
+ return;
3628
+ }
3629
+ const result = generateAction({
3630
+ type,
3631
+ name: name || "",
3632
+ module: options.module,
3633
+ sourceDir: options.sourceDir,
3634
+ dryRun: options.dryRun
3635
+ });
3636
+ if (!result.success) {
3637
+ console.error(result.error);
3638
+ process.exit(1);
3639
+ }
3640
+ });
3641
+ program.command("codegen").description("Generate SDK and CLI clients from the compiled API").option("--dry-run", "Preview generated files without writing").option("--output <dir>", "Output directory");
3642
+ program.command("routes").description("Display the route table").option("--format <format>", "Output format (table, json)", "table");
3643
+ return program;
3644
+ }
3645
+ // src/ui/diagnostic-formatter.ts
3646
+ import { symbols } from "@vertz/tui";
3647
+ function formatDiagnostic(diagnostic) {
3648
+ const icon = diagnostic.severity === "error" ? symbols.error : symbols.warning;
3649
+ const lines = [];
3650
+ const location = diagnostic.file ? `${diagnostic.file}:${diagnostic.line ?? 0}:${diagnostic.column ?? 0}` : "";
3651
+ lines.push(`${icon} ${diagnostic.code}: ${diagnostic.message}`);
3652
+ if (location) {
3653
+ lines.push(` at ${location}`);
3654
+ }
3655
+ if (diagnostic.sourceContext) {
3656
+ const ctx = diagnostic.sourceContext;
3657
+ for (const line of ctx.lines) {
3658
+ lines.push(` ${String(line.number).padStart(4)} ${line.text}`);
3659
+ }
3660
+ if (ctx.highlightStart >= 0 && ctx.highlightLength > 0) {
3661
+ const padding = " ".repeat(ctx.highlightStart + 6);
3662
+ const underline = "^".repeat(ctx.highlightLength);
3663
+ lines.push(`${padding}${underline}`);
3664
+ }
3665
+ }
3666
+ if (diagnostic.suggestion) {
3667
+ lines.push(` ${symbols.info} ${diagnostic.suggestion}`);
3668
+ }
3669
+ return lines.join(`
3670
+ `);
3671
+ }
3672
+ function formatDiagnosticSummary(diagnostics) {
3673
+ const errors = diagnostics.filter((d) => d.severity === "error");
3674
+ const warnings = diagnostics.filter((d) => d.severity === "warning");
3675
+ const parts = [];
3676
+ if (errors.length === 0 && warnings.length === 0) {
3677
+ return `${symbols.success} No errors`;
3678
+ }
3679
+ if (errors.length > 0) {
3680
+ parts.push(`${errors.length} error${errors.length === 1 ? "" : "s"}`);
3681
+ }
3682
+ if (warnings.length > 0) {
3683
+ parts.push(`${warnings.length} warning${warnings.length === 1 ? "" : "s"}`);
3684
+ }
3685
+ return parts.join(", ");
3686
+ }
3687
+ function formatDiagnosticsAsJSON(diagnostics, success) {
3688
+ return JSON.stringify({
3689
+ success,
3690
+ diagnostics: diagnostics.map((d) => ({
3691
+ severity: d.severity,
3692
+ code: d.code,
3693
+ message: d.message,
3694
+ file: d.file,
3695
+ line: d.line,
3696
+ column: d.column,
3697
+ suggestion: d.suggestion
3698
+ }))
3699
+ });
3700
+ }
3701
+ function formatDiagnosticsAsGitHub(diagnostics) {
3702
+ return diagnostics.map((d) => {
3703
+ const level = d.severity === "error" ? "error" : "warning";
3704
+ const file = d.file ?? "";
3705
+ const line = d.line ?? 0;
3706
+ const col = d.column ?? 0;
3707
+ return `::${level} file=${file},line=${line},col=${col}::${d.code}: ${d.message}`;
3708
+ }).join(`
3709
+ `);
3710
+ }
3711
+
3712
+ // src/commands/check.ts
3713
+ async function checkAction(options) {
3714
+ const { compiler, format } = options;
3715
+ const ir = await compiler.analyze();
3716
+ const diagnostics = await compiler.validate(ir);
3717
+ const hasErrors = diagnostics.some((d) => d.severity === "error");
3718
+ const success = !hasErrors;
3719
+ let output;
3720
+ switch (format) {
3721
+ case "json":
3722
+ output = formatDiagnosticsAsJSON(diagnostics, success);
3723
+ break;
3724
+ case "github":
3725
+ output = formatDiagnosticsAsGitHub(diagnostics);
3726
+ break;
3727
+ default: {
3728
+ const parts = [];
3729
+ for (const d of diagnostics) {
3730
+ parts.push(formatDiagnostic(d));
3731
+ }
3732
+ parts.push("");
3733
+ parts.push(formatDiagnosticSummary(diagnostics));
3734
+ output = parts.join(`
3735
+ `);
3736
+ break;
3737
+ }
3738
+ }
3739
+ return { success, diagnostics, output };
3740
+ }
3741
+ // src/deploy/dockerfile.ts
3742
+ function generateDockerConfig(runtime, port) {
3743
+ const dockerfile = runtime === "bun" ? generateBunDockerfile(port) : generateNodeDockerfile(port);
3744
+ const dockerignore = `node_modules
3745
+ .git
3746
+ .vertz
3747
+ dist
3748
+ *.log
3749
+ .env
3750
+ .env.*
3751
+ `;
3752
+ return [
3753
+ { path: "Dockerfile", content: dockerfile },
3754
+ { path: ".dockerignore", content: dockerignore }
3755
+ ];
3756
+ }
3757
+ function generateBunDockerfile(port) {
3758
+ return `# Build stage
3759
+ FROM oven/bun:1 AS build
3760
+ WORKDIR /app
3761
+ COPY package.json bun.lock* ./
3762
+ RUN bun install --frozen-lockfile
3763
+ COPY . .
3764
+ RUN bun run build
3765
+
3766
+ # Production stage
3767
+ FROM oven/bun:1-slim AS production
3768
+ WORKDIR /app
3769
+ COPY --from=build /app/package.json ./
3770
+ COPY --from=build /app/node_modules ./node_modules
3771
+ COPY --from=build /app/dist ./dist
3772
+ EXPOSE ${port}
3773
+ CMD ["bun", "run", "start"]
3774
+ `;
3775
+ }
3776
+ function generateNodeDockerfile(port) {
3777
+ return `# Build stage
3778
+ FROM node:22-slim AS build
3779
+ WORKDIR /app
3780
+ COPY package.json package-lock.json* ./
3781
+ RUN npm ci
3782
+ COPY . .
3783
+ RUN npm run build
3784
+
3785
+ # Production stage
3786
+ FROM node:22-slim AS production
3787
+ WORKDIR /app
3788
+ COPY --from=build /app/package.json ./
3789
+ COPY --from=build /app/node_modules ./node_modules
3790
+ COPY --from=build /app/dist ./dist
3791
+ EXPOSE ${port}
3792
+ CMD ["node", "dist/index.js"]
3793
+ `;
3794
+ }
3795
+
3796
+ // src/deploy/fly.ts
3797
+ function generateFlyConfig(runtime, port) {
3798
+ const flyToml = `app = "my-vertz-app"
3799
+ primary_region = "iad"
3800
+
3801
+ [build]
3802
+ dockerfile = "Dockerfile"
3803
+
3804
+ [http_service]
3805
+ internal_port = ${port}
3806
+ force_https = true
3807
+ auto_stop_machines = true
3808
+ auto_start_machines = true
3809
+
3810
+ [[http_service.checks]]
3811
+ grace_period = "10s"
3812
+ interval = "30s"
3813
+ method = "GET"
3814
+ path = "/health"
3815
+ timeout = "5s"
3816
+ `;
3817
+ const dockerFiles = generateDockerConfig(runtime, port);
3818
+ return [{ path: "fly.toml", content: flyToml }, ...dockerFiles];
3819
+ }
3820
+
3821
+ // src/deploy/railway.ts
3822
+ function generateRailwayConfig(runtime) {
3823
+ const isBun = runtime === "bun";
3824
+ const buildCmd = isBun ? "bun run build" : "npm run build";
3825
+ const startCmd = isBun ? "bun run start" : "node dist/index.js";
3826
+ const content = `[build]
3827
+ buildCommand = "${buildCmd}"
3828
+
3829
+ [deploy]
3830
+ startCommand = "${startCmd}"
3831
+ healthcheckPath = "/health"
3832
+ restartPolicyType = "ON_FAILURE"
3833
+ restartPolicyMaxRetries = 10
3834
+ `;
3835
+ return [{ path: "railway.toml", content }];
3836
+ }
3837
+
3838
+ // src/commands/deploy.ts
3839
+ var VALID_TARGETS = new Set(["fly", "railway", "docker"]);
3840
+ function deployAction(options) {
3841
+ const { target, runtime, port } = options;
3842
+ if (!VALID_TARGETS.has(target)) {
3843
+ return {
3844
+ success: false,
3845
+ files: [],
3846
+ error: `Unknown deploy target: "${target}". Valid targets: fly, railway, docker`
3847
+ };
3848
+ }
3849
+ switch (target) {
3850
+ case "railway":
3851
+ return { success: true, files: generateRailwayConfig(runtime) };
3852
+ case "fly":
3853
+ return { success: true, files: generateFlyConfig(runtime, port) };
3854
+ case "docker":
3855
+ return { success: true, files: generateDockerConfig(runtime, port) };
3856
+ }
3857
+ }
3858
+ // src/commands/routes.ts
3859
+ function extractRoutes(ir) {
3860
+ const routes = [];
3861
+ for (const mod of ir.modules) {
3862
+ for (const router of mod.routers) {
3863
+ for (const route of router.routes) {
3864
+ routes.push({
3865
+ method: route.method,
3866
+ path: route.path,
3867
+ fullPath: route.fullPath,
3868
+ operationId: route.operationId,
3869
+ moduleName: mod.name,
3870
+ middleware: route.middleware.map((m) => m.name)
3871
+ });
3872
+ }
3873
+ }
3874
+ }
3875
+ return routes;
3876
+ }
3877
+ function formatTable(routes) {
3878
+ if (routes.length === 0) {
3879
+ return "No routes found.";
3880
+ }
3881
+ const headers = ["Method", "Path", "Operation ID", "Module", "Middleware"];
3882
+ const rows = routes.map((r) => [
3883
+ r.method,
3884
+ r.path,
3885
+ r.operationId,
3886
+ r.moduleName,
3887
+ r.middleware.join(", ") || "-"
3888
+ ]);
3889
+ const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? "").length)));
3890
+ const lines = [];
3891
+ lines.push(`Routes (${routes.length} total)
3892
+ `);
3893
+ lines.push(headers.map((h, i) => h.padEnd(widths[i] ?? 0)).join(" "));
3894
+ lines.push(widths.map((w) => "-".repeat(w)).join(" "));
3895
+ for (const row of rows) {
3896
+ lines.push(row.map((c, i) => c.padEnd(widths[i] ?? 0)).join(" "));
3897
+ }
3898
+ return lines.join(`
3899
+ `);
3900
+ }
3901
+ async function routesAction(options) {
3902
+ const { compiler, format, module: moduleFilter } = options;
3903
+ const ir = await compiler.analyze();
3904
+ let routes = extractRoutes(ir);
3905
+ if (moduleFilter) {
3906
+ routes = routes.filter((r) => r.moduleName === moduleFilter);
3907
+ }
3908
+ let output;
3909
+ if (format === "json") {
3910
+ output = JSON.stringify(routes);
3911
+ } else {
3912
+ output = formatTable(routes);
3913
+ }
3914
+ return { routes, output };
3915
+ }
3916
+ // src/config/defaults.ts
3917
+ var defaultCLIConfig = {
3918
+ strict: false,
3919
+ forceGenerate: false,
3920
+ compiler: {
3921
+ sourceDir: "src",
3922
+ entryFile: "src/app.ts",
3923
+ outputDir: ".vertz/generated"
3924
+ },
3925
+ dev: {
3926
+ port: 3000,
3927
+ host: "localhost",
3928
+ open: false,
3929
+ typecheck: true
3930
+ },
3931
+ generators: {}
3932
+ };
3933
+ // src/config/loader.ts
3934
+ import { existsSync as existsSync5 } from "node:fs";
3935
+ import { join as join6, resolve as resolve2 } from "node:path";
3936
+ var CONFIG_FILES = ["vertz.config.ts", "vertz.config.js", "vertz.config.mjs"];
3937
+ function findConfigFile(startDir) {
3938
+ const dir = resolve2(startDir ?? process.cwd());
3939
+ for (const filename of CONFIG_FILES) {
3940
+ const filepath = join6(dir, filename);
3941
+ if (existsSync5(filepath)) {
3942
+ return filepath;
3943
+ }
3944
+ }
3945
+ return;
3946
+ }
3947
+ function deepMerge(target, source) {
3948
+ const result = { ...target };
3949
+ for (const key of Object.keys(source)) {
3950
+ const sourceVal = source[key];
3951
+ const targetVal = target[key];
3952
+ if (sourceVal !== null && sourceVal !== undefined && typeof sourceVal === "object" && !Array.isArray(sourceVal) && typeof targetVal === "object" && targetVal !== null && !Array.isArray(targetVal)) {
3953
+ result[key] = deepMerge(targetVal, sourceVal);
3954
+ } else if (sourceVal !== undefined) {
3955
+ result[key] = sourceVal;
3956
+ }
3957
+ }
3958
+ return result;
3959
+ }
3960
+ var defaultConfig = {
3961
+ strict: false,
3962
+ forceGenerate: false,
3963
+ compiler: {
3964
+ sourceDir: "src",
3965
+ entryFile: "src/app.ts",
3966
+ outputDir: ".vertz/generated"
3967
+ }
3968
+ };
3969
+ async function loadConfig(configPath) {
3970
+ if (!configPath) {
3971
+ return { ...defaultConfig };
3972
+ }
3973
+ const { createJiti } = await import("jiti");
3974
+ const jiti = createJiti(import.meta.url, {
3975
+ interopDefault: true
3976
+ });
3977
+ const loaded = await jiti.import(configPath);
3978
+ const userConfig = loaded && typeof loaded === "object" && "default" in loaded ? loaded.default ?? {} : loaded ?? {};
3979
+ return deepMerge(defaultConfig, userConfig);
3980
+ }
3981
+ // src/deploy/detector.ts
3982
+ import { join as join7 } from "node:path";
3983
+ var DETECTION_ORDER = [
3984
+ { file: "fly.toml", target: "fly" },
3985
+ { file: "railway.toml", target: "railway" },
3986
+ { file: "Dockerfile", target: "docker" }
3987
+ ];
3988
+ function detectTarget(projectRoot, existsFn) {
3989
+ for (const { file, target } of DETECTION_ORDER) {
3990
+ if (existsFn(join7(projectRoot, file))) {
3991
+ return target;
3992
+ }
3993
+ }
3994
+ return null;
3995
+ }
3996
+ // src/dev-server/dev-loop.ts
3997
+ function createDevLoop(deps) {
3998
+ return {
3999
+ async start() {
4000
+ const result = await deps.compile();
4001
+ if (result.success) {
4002
+ deps.startProcess();
4003
+ deps.onCompileSuccess(result);
4004
+ } else {
4005
+ deps.onCompileError(result);
4006
+ }
4007
+ deps.onFileChange(async (_changes) => {
4008
+ const recompileResult = await deps.compile();
4009
+ if (recompileResult.success) {
4010
+ await deps.stopProcess();
4011
+ deps.startProcess();
4012
+ deps.onCompileSuccess(recompileResult);
4013
+ } else {
4014
+ deps.onCompileError(recompileResult);
4015
+ }
4016
+ });
4017
+ },
4018
+ async stop() {
4019
+ await deps.stopProcess();
4020
+ }
4021
+ };
4022
+ }
4023
+ // src/dev-server/process-manager.ts
4024
+ function createProcessManager(spawnFn) {
4025
+ let child;
4026
+ const outputHandlers = [];
4027
+ const errorHandlers = [];
4028
+ return {
4029
+ start(entryPoint, env) {
4030
+ if (child) {
4031
+ child.kill("SIGTERM");
4032
+ child = undefined;
4033
+ }
4034
+ if (spawnFn) {
4035
+ child = spawnFn(entryPoint, env);
4036
+ child.stdout?.on("data", (data) => {
4037
+ const str = data.toString();
4038
+ for (const handler of outputHandlers) {
4039
+ handler(str);
4040
+ }
4041
+ });
4042
+ child.stderr?.on("data", (data) => {
4043
+ const str = data.toString();
4044
+ for (const handler of errorHandlers) {
4045
+ handler(str);
4046
+ }
4047
+ });
4048
+ child.on("exit", () => {
4049
+ child = undefined;
4050
+ });
4051
+ }
4052
+ },
4053
+ async stop() {
4054
+ if (!child)
4055
+ return;
4056
+ const proc = child;
4057
+ child = undefined;
4058
+ await new Promise((resolve3) => {
4059
+ const timeout = setTimeout(() => {
4060
+ proc.kill("SIGKILL");
4061
+ resolve3();
4062
+ }, 2000);
4063
+ proc.on("exit", () => {
4064
+ clearTimeout(timeout);
4065
+ resolve3();
4066
+ });
4067
+ proc.kill("SIGTERM");
4068
+ });
4069
+ },
4070
+ async restart(entryPoint, env) {
4071
+ await this.stop();
4072
+ this.start(entryPoint, env);
4073
+ },
4074
+ isRunning() {
4075
+ return child !== undefined;
4076
+ },
4077
+ onOutput(handler) {
4078
+ outputHandlers.push(handler);
4079
+ },
4080
+ onError(handler) {
4081
+ errorHandlers.push(handler);
4082
+ }
4083
+ };
4084
+ }
4085
+ // src/dev-server/watcher.ts
4086
+ var DEBOUNCE_MS = 100;
4087
+ var IGNORE_PATTERNS = ["/node_modules/", "/.git/", "/.vertz/generated/"];
4088
+ function isIgnored(path) {
4089
+ return IGNORE_PATTERNS.some((pattern) => path.includes(pattern));
4090
+ }
4091
+ function createWatcher2(_dir) {
4092
+ const handlers = [];
4093
+ let pending = [];
4094
+ let timer;
4095
+ function flush() {
4096
+ if (pending.length === 0)
4097
+ return;
4098
+ const batch = pending;
4099
+ pending = [];
4100
+ for (const handler of handlers) {
4101
+ handler(batch);
4102
+ }
4103
+ }
4104
+ return {
4105
+ on(_event, handler) {
4106
+ handlers.push(handler);
4107
+ },
4108
+ _emit(change) {
4109
+ if (isIgnored(change.path))
4110
+ return;
4111
+ pending.push(change);
4112
+ if (timer !== undefined) {
4113
+ clearTimeout(timer);
4114
+ }
4115
+ timer = setTimeout(flush, DEBOUNCE_MS);
4116
+ },
4117
+ close() {
4118
+ if (timer !== undefined) {
4119
+ clearTimeout(timer);
4120
+ }
4121
+ pending = [];
4122
+ }
4123
+ };
4124
+ }
4125
+ // src/ui/components/Banner.tsx
4126
+ import { Text } from "ink";
4127
+ import { jsxDEV } from "react/jsx-dev-runtime";
4128
+ function Banner({ version }) {
4129
+ return /* @__PURE__ */ jsxDEV(Text, {
4130
+ children: [
4131
+ /* @__PURE__ */ jsxDEV(Text, {
4132
+ bold: true,
4133
+ color: "cyanBright",
4134
+ children: "vertz"
4135
+ }, undefined, false, undefined, this),
4136
+ " ",
4137
+ /* @__PURE__ */ jsxDEV(Text, {
4138
+ dimColor: true,
4139
+ children: [
4140
+ "v",
4141
+ version
4142
+ ]
4143
+ }, undefined, true, undefined, this)
4144
+ ]
4145
+ }, undefined, true, undefined, this);
4146
+ }
4147
+ // src/ui/components/DiagnosticDisplay.tsx
4148
+ import { Box, Text as Text2 } from "ink";
4149
+ import { colors, symbols as symbols2 } from "@vertz/tui";
4150
+ import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
4151
+ function DiagnosticDisplay({ diagnostic }) {
4152
+ const isError = diagnostic.severity === "error";
4153
+ const icon = isError ? symbols2.error : symbols2.warning;
4154
+ const color = isError ? colors.error : colors.warning;
4155
+ const location = diagnostic.file ? `${diagnostic.file}:${diagnostic.line ?? 0}:${diagnostic.column ?? 0}` : "";
4156
+ return /* @__PURE__ */ jsxDEV2(Box, {
4157
+ flexDirection: "column",
4158
+ children: [
4159
+ /* @__PURE__ */ jsxDEV2(Text2, {
4160
+ color,
4161
+ children: [
4162
+ icon,
4163
+ " ",
4164
+ diagnostic.code
4165
+ ]
4166
+ }, undefined, true, undefined, this),
4167
+ /* @__PURE__ */ jsxDEV2(Text2, {
4168
+ children: [
4169
+ " ",
4170
+ diagnostic.message
4171
+ ]
4172
+ }, undefined, true, undefined, this),
4173
+ location && /* @__PURE__ */ jsxDEV2(Text2, {
4174
+ dimColor: true,
4175
+ children: [
4176
+ " at ",
4177
+ location
4178
+ ]
4179
+ }, undefined, true, undefined, this),
4180
+ diagnostic.sourceContext && /* @__PURE__ */ jsxDEV2(Box, {
4181
+ flexDirection: "column",
4182
+ marginTop: 1,
4183
+ children: diagnostic.sourceContext.lines.map((line) => /* @__PURE__ */ jsxDEV2(Text2, {
4184
+ children: [
4185
+ /* @__PURE__ */ jsxDEV2(Text2, {
4186
+ dimColor: true,
4187
+ children: [
4188
+ String(line.number).padStart(4),
4189
+ " "
4190
+ ]
4191
+ }, undefined, true, undefined, this),
4192
+ /* @__PURE__ */ jsxDEV2(Text2, {
4193
+ children: line.text
4194
+ }, undefined, false, undefined, this)
4195
+ ]
4196
+ }, line.number, true, undefined, this))
4197
+ }, undefined, false, undefined, this),
4198
+ diagnostic.suggestion && /* @__PURE__ */ jsxDEV2(Text2, {
4199
+ color: colors.info,
4200
+ children: [
4201
+ " ",
4202
+ symbols2.info,
4203
+ " ",
4204
+ diagnostic.suggestion
4205
+ ]
4206
+ }, undefined, true, undefined, this)
4207
+ ]
4208
+ }, undefined, true, undefined, this);
4209
+ }
4210
+ // src/ui/components/DiagnosticSummary.tsx
4211
+ import { Text as Text3 } from "ink";
4212
+ import { colors as colors2, symbols as symbols3 } from "@vertz/tui";
4213
+ import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
4214
+ function DiagnosticSummary({ diagnostics }) {
4215
+ const errors = diagnostics.filter((d) => d.severity === "error");
4216
+ const warnings = diagnostics.filter((d) => d.severity === "warning");
4217
+ if (errors.length === 0 && warnings.length === 0) {
4218
+ return /* @__PURE__ */ jsxDEV3(Text3, {
4219
+ color: colors2.success,
4220
+ children: [
4221
+ symbols3.success,
4222
+ " No errors"
4223
+ ]
4224
+ }, undefined, true, undefined, this);
4225
+ }
4226
+ const parts = [];
4227
+ if (errors.length > 0) {
4228
+ parts.push(/* @__PURE__ */ jsxDEV3(Text3, {
4229
+ color: colors2.error,
4230
+ children: [
4231
+ errors.length,
4232
+ " error",
4233
+ errors.length === 1 ? "" : "s"
4234
+ ]
4235
+ }, "errors", true, undefined, this));
4236
+ }
4237
+ if (warnings.length > 0) {
4238
+ if (parts.length > 0) {
4239
+ parts.push(/* @__PURE__ */ jsxDEV3(Text3, {
4240
+ children: ", "
4241
+ }, "sep", false, undefined, this));
4242
+ }
4243
+ parts.push(/* @__PURE__ */ jsxDEV3(Text3, {
4244
+ color: colors2.warning,
4245
+ children: [
4246
+ warnings.length,
4247
+ " warning",
4248
+ warnings.length === 1 ? "" : "s"
4249
+ ]
4250
+ }, "warnings", true, undefined, this));
4251
+ }
4252
+ return /* @__PURE__ */ jsxDEV3(Text3, {
4253
+ children: parts
4254
+ }, undefined, false, undefined, this);
4255
+ }
4256
+
4257
+ // src/index.ts
4258
+ import {
4259
+ colors as colors3,
4260
+ createTaskRunner,
4261
+ Message,
4262
+ SelectList,
4263
+ symbols as symbols4,
4264
+ Task,
4265
+ TaskList
4266
+ } from "@vertz/tui";
4267
+
4268
+ // src/utils/prompt.ts
4269
+ function isCI() {
4270
+ return process.env.CI === "true" || process.env.CI === "1" || process.env.CONTINUOUS_INTEGRATION === "true" || process.env.GITHUB_ACTIONS === "true" || process.env.GITLAB_CI === "true";
4271
+ }
4272
+ function requireParam(value, name) {
4273
+ if (value === undefined || value === "") {
4274
+ throw new Error(`Missing required parameter: ${name}`);
4275
+ }
4276
+ return value;
4277
+ }
4278
+ // src/utils/runtime-detect.ts
4279
+ function detectRuntime() {
4280
+ if (typeof globalThis !== "undefined" && "Bun" in globalThis) {
4281
+ return "bun";
4282
+ }
4283
+ return "node";
4284
+ }
4285
+ export {
4286
+ symbols4 as symbols,
4287
+ routesAction,
4288
+ requireParam,
4289
+ registerDevCommand,
4290
+ loadConfig,
4291
+ isCI,
4292
+ getAffectedStages,
4293
+ generateAction,
4294
+ formatPath,
4295
+ formatFileSize,
4296
+ formatDuration,
4297
+ formatDiagnosticSummary,
4298
+ formatDiagnostic,
4299
+ findProjectRoot,
4300
+ findConfigFile,
4301
+ devAction,
4302
+ detectTarget,
4303
+ detectRuntime,
4304
+ deployAction,
4305
+ defaultCLIConfig,
4306
+ createWatcher2 as createWatcher,
4307
+ createTaskRunner,
4308
+ createProcessManager,
4309
+ createPipelineWatcher,
4310
+ createPipelineOrchestrator,
4311
+ createDevLoop,
4312
+ createCLI,
4313
+ createAction,
4314
+ colors3 as colors,
4315
+ checkAction,
4316
+ categorizeFileChange,
4317
+ buildAction,
4318
+ TaskList,
4319
+ Task,
4320
+ SelectList,
4321
+ PipelineOrchestrator,
4322
+ Message,
4323
+ DiagnosticSummary,
4324
+ DiagnosticDisplay,
4325
+ Banner
4326
+ };