portcall 0.0.0-stage → 0.1.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.
@@ -0,0 +1,2777 @@
1
+ #!/usr/bin/env node
2
+ import { basename, dirname, join, resolve, sep } from "node:path";
3
+ import process from "node:process";
4
+ import { parseArgs, promisify } from "node:util";
5
+ import { execFile, spawn } from "node:child_process";
6
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
7
+ import { closeSync, createWriteStream, existsSync, mkdirSync, openSync, readFileSync, readSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
8
+ import { Buffer } from "node:buffer";
9
+ import { homedir } from "node:os";
10
+ import { readlink } from "node:fs/promises";
11
+ import { connect } from "node:net";
12
+ import { createInterface } from "node:readline";
13
+ // package.json
14
+ var version$1 = "0.1.0";
15
+ // node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/core.js
16
+ var _a$1;
17
+ const _zodDesc = {
18
+ value: void 0,
19
+ enumerable: false
20
+ };
21
+ let _E = "captureStackTrace" in Error ? Error : null;
22
+ function newError(Definition) {
23
+ const E = _E;
24
+ if (E) {
25
+ const saved = E.stackTraceLimit;
26
+ if (typeof saved === "number") {
27
+ try {
28
+ E.stackTraceLimit = 0;
29
+ } catch {
30
+ _E = null;
31
+ return new Definition();
32
+ }
33
+ try {
34
+ return new Definition();
35
+ } finally {
36
+ E.stackTraceLimit = saved;
37
+ }
38
+ }
39
+ }
40
+ return new Definition();
41
+ }
42
+ /* @__NO_SIDE_EFFECTS__ */
43
+ function $constructor(name, initializer, proto, params) {
44
+ const zodProto = {};
45
+ function Internals(def) {
46
+ this.def = def;
47
+ this.constr = _;
48
+ this.traits = /* @__PURE__ */ new Set();
49
+ }
50
+ Internals.prototype = zodProto;
51
+ const protoMembers = proto;
52
+ const initialized = protoMembers && /* @__PURE__ */ new WeakSet();
53
+ function init(inst, def) {
54
+ if (!inst._zod) {
55
+ _zodDesc.value = new Internals(def);
56
+ try {
57
+ Object.defineProperty(inst, "_zod", _zodDesc);
58
+ } finally {
59
+ _zodDesc.value = void 0;
60
+ }
61
+ } else if (inst._zod.traits.has(name)) return;
62
+ inst._zod.traits.add(name);
63
+ initializer(inst, def);
64
+ if (initialized) {
65
+ const own = Object.getPrototypeOf(inst);
66
+ const ctorProto = inst._zod.constr.prototype;
67
+ let up = own;
68
+ while (up && up !== ctorProto) up = Object.getPrototypeOf(up);
69
+ const target = up ?? own;
70
+ if (!initialized.has(target)) {
71
+ initialized.add(target);
72
+ members(target, protoMembers);
73
+ }
74
+ }
75
+ const proto = _.prototype;
76
+ for (const k in proto) {
77
+ if (!Object.prototype.hasOwnProperty.call(proto, k)) continue;
78
+ if (!(k in inst)) inst[k] = proto[k].bind(inst);
79
+ }
80
+ }
81
+ const Parent = params?.Parent ?? Object;
82
+ class Definition extends Parent {}
83
+ Object.defineProperty(Definition, "name", { value: name });
84
+ function _(def) {
85
+ const inst = params?.Parent ? newError(Definition) : this;
86
+ init(inst, def);
87
+ const deferred = inst._zod.deferred;
88
+ if (deferred) {
89
+ for (const fn of deferred) fn();
90
+ inst._zod.deferred = void 0;
91
+ }
92
+ const pp = globalThis.__zod_globalConfig?.postProcessor;
93
+ if (pp) pp(inst);
94
+ return inst;
95
+ }
96
+ Object.defineProperty(_, "init", { value: init });
97
+ Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => {
98
+ if (params?.Parent && inst instanceof params.Parent) return true;
99
+ return inst?._zod?.traits?.has(name);
100
+ } });
101
+ Object.defineProperty(_, "name", { value: name });
102
+ return _;
103
+ }
104
+ var $ZodAsyncError = class extends Error {
105
+ constructor() {
106
+ super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
107
+ }
108
+ };
109
+ (_a$1 = globalThis).__zod_globalConfig ?? (_a$1.__zod_globalConfig = {});
110
+ const globalConfig = globalThis.__zod_globalConfig;
111
+ function config(newConfig) {
112
+ if (newConfig) Object.assign(globalConfig, newConfig);
113
+ return globalConfig;
114
+ }
115
+ // node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/util.js
116
+ function joinValues(array, separator = "|") {
117
+ return array.map((val) => stringifyPrimitive(val)).join(separator);
118
+ }
119
+ function jsonStringifyReplacer(_, value) {
120
+ if (typeof value === "bigint") return value.toString();
121
+ return value;
122
+ }
123
+ var Cached = class {
124
+ constructor(getter) {
125
+ this._getter = getter;
126
+ this._value = void 0;
127
+ }
128
+ get value() {
129
+ const getter = this._getter;
130
+ if (getter !== void 0) {
131
+ this._value = getter();
132
+ this._getter = void 0;
133
+ }
134
+ return this._value;
135
+ }
136
+ };
137
+ function cached(getter) {
138
+ return new Cached(getter);
139
+ }
140
+ function nullish(input) {
141
+ return input === null || input === void 0;
142
+ }
143
+ function cleanRegex(source) {
144
+ const start = source.startsWith("^") ? 1 : 0;
145
+ const end = source.endsWith("$") ? source.length - 1 : source.length;
146
+ return source.slice(start, end);
147
+ }
148
+ function assignProp(target, prop, value) {
149
+ Object.defineProperty(target, prop, {
150
+ value,
151
+ writable: true,
152
+ enumerable: true,
153
+ configurable: true
154
+ });
155
+ }
156
+ const captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
157
+ function isObject(data) {
158
+ return typeof data === "object" && data !== null && !Array.isArray(data);
159
+ }
160
+ function isPlainObject(o) {
161
+ if (isObject(o) === false) return false;
162
+ const ctor = o.constructor;
163
+ if (ctor === void 0) return true;
164
+ if (typeof ctor !== "function") return true;
165
+ const prot = ctor.prototype;
166
+ if (isObject(prot) === false) return false;
167
+ if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false;
168
+ return true;
169
+ }
170
+ function clone(inst, def, params) {
171
+ const cl = new inst._zod.constr(def ?? inst._zod.def);
172
+ if (!def || params?.parent) cl._zod.parent = inst;
173
+ return cl;
174
+ }
175
+ function normalizeParams(_params) {
176
+ const params = _params;
177
+ if (!params) return {};
178
+ if (typeof params === "string") return { error: () => params };
179
+ if (params?.message !== void 0) {
180
+ if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params");
181
+ params.error = params.message;
182
+ }
183
+ delete params.message;
184
+ if (typeof params.error === "string") return {
185
+ ...params,
186
+ error: () => params.error
187
+ };
188
+ return params;
189
+ }
190
+ function stringifyPrimitive(value) {
191
+ if (typeof value === "bigint") return value.toString() + "n";
192
+ if (typeof value === "string") return `"${value}"`;
193
+ return `${value}`;
194
+ }
195
+ function optionalKeys(shape) {
196
+ return Object.keys(shape).filter((k) => {
197
+ return shape[k]._zod.optin !== void 0 && shape[k]._zod.optout === "optional";
198
+ });
199
+ }
200
+ const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({
201
+ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
202
+ int32: [-2147483648, 2147483647],
203
+ uint32: [0, 4294967295],
204
+ float32: [-34028234663852886e22, 34028234663852886e22],
205
+ float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
206
+ }))();
207
+ function aborted(x, startIndex = 0) {
208
+ if (x.aborted === true) return true;
209
+ for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true;
210
+ return false;
211
+ }
212
+ function explicitlyAborted(x, startIndex = 0) {
213
+ if (x.aborted === true) return true;
214
+ for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue === false) return true;
215
+ return false;
216
+ }
217
+ function prefixIssues(path, issues) {
218
+ return issues.map((iss) => {
219
+ var _a;
220
+ (_a = iss).path ?? (_a.path = []);
221
+ iss.path.unshift(path);
222
+ return iss;
223
+ });
224
+ }
225
+ function unwrapMessage(message) {
226
+ return typeof message === "string" ? message : message?.message;
227
+ }
228
+ function attachSchema(issues, start, inst) {
229
+ var _a;
230
+ for (let i = start; i < issues.length; i++) (_a = issues[i]).schema ?? (_a.schema = inst);
231
+ }
232
+ function finalizeIssue(iss, ctx, config) {
233
+ var _a;
234
+ const traits = iss.inst?._zod?.traits;
235
+ if (traits?.has("$ZodType")) {
236
+ if (traits.has("$ZodCheck")) (_a = iss).schema ?? (_a.schema = iss.inst);
237
+ else iss.schema = iss.inst;
238
+ }
239
+ const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : void 0;
240
+ const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
241
+ const full = {};
242
+ for (const k of Object.keys(iss)) {
243
+ if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__") continue;
244
+ full[k] = iss[k];
245
+ }
246
+ full.path ?? (full.path = []);
247
+ full.message = message;
248
+ if (ctx?.reportInput) full.input = iss.input;
249
+ return full;
250
+ }
251
+ const highSurrogate = /[\uD800-\uDBFF]/;
252
+ function codePointLength(str) {
253
+ const units = str.length;
254
+ if (!highSurrogate.test(str)) return units;
255
+ let count = units;
256
+ for (let i = 0; i < units - 1; i++) if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) {
257
+ count--;
258
+ i++;
259
+ }
260
+ return count;
261
+ }
262
+ function getLengthableOrigin(input) {
263
+ if (Array.isArray(input)) return "array";
264
+ if (typeof input === "string") return "string";
265
+ return "unknown";
266
+ }
267
+ function parsedType(data) {
268
+ const t = typeof data;
269
+ switch (t) {
270
+ case "number": return Number.isNaN(data) ? "nan" : "number";
271
+ case "object": {
272
+ if (data === null) return "null";
273
+ if (Array.isArray(data)) return "array";
274
+ const obj = data;
275
+ if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) return obj.constructor.name;
276
+ }
277
+ }
278
+ return t;
279
+ }
280
+ /**
281
+ * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working.
282
+ *
283
+ * Call this from a `proto` initializer, which runs once per prototype — never per instance.
284
+ */
285
+ function members(proto, table) {
286
+ for (const key in table) {
287
+ const desc = Object.getOwnPropertyDescriptor(table, key);
288
+ if (desc.get) Object.defineProperty(proto, key, {
289
+ ...desc,
290
+ enumerable: false
291
+ });
292
+ else defineBound(proto, key, desc.value);
293
+ }
294
+ }
295
+ /** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */
296
+ function own(inst, key, value, enumerable = true) {
297
+ Object.defineProperty(inst, key, {
298
+ configurable: true,
299
+ writable: true,
300
+ enumerable,
301
+ value
302
+ });
303
+ return value;
304
+ }
305
+ /** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */
306
+ function hide(inst, key, value) {
307
+ return own(inst, key, value, false);
308
+ }
309
+ function defineBound(proto, key, fn) {
310
+ Object.defineProperty(proto, key, {
311
+ configurable: true,
312
+ get() {
313
+ return this == null ? fn : own(this, key, fn.bind(this));
314
+ },
315
+ set(value) {
316
+ own(this, key, value);
317
+ }
318
+ });
319
+ }
320
+ /** Returns the prototype to install on, or `undefined` if this group is already installed on it. */
321
+ function claim(inst, sentinel) {
322
+ const proto = Object.getPrototypeOf(inst);
323
+ return sentinel in proto ? void 0 : proto;
324
+ }
325
+ let installing;
326
+ let broke = false;
327
+ const breaker = {
328
+ configurable: true,
329
+ get() {
330
+ broke = true;
331
+ }
332
+ };
333
+ /**
334
+ * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s
335
+ * constructor, computed from the internals object itself and cached there on
336
+ * first read. One accessor per constructor rather than one per instance.
337
+ */
338
+ function defineLazyInternal(inst, key, compute) {
339
+ const proto = Object.getPrototypeOf(inst._zod);
340
+ if (key in proto && installing !== inst._zod) {
341
+ installing = void 0;
342
+ return;
343
+ }
344
+ installing = inst._zod;
345
+ Object.defineProperty(proto, key, {
346
+ configurable: true,
347
+ get() {
348
+ Object.defineProperty(this, key, breaker);
349
+ const outer = broke;
350
+ broke = false;
351
+ try {
352
+ const value = compute(this);
353
+ if (broke) delete this[key];
354
+ else Object.defineProperty(this, key, {
355
+ configurable: true,
356
+ writable: true,
357
+ value
358
+ });
359
+ broke = broke || outer;
360
+ return value;
361
+ } catch (err) {
362
+ delete this[key];
363
+ broke = broke || outer;
364
+ throw err;
365
+ }
366
+ },
367
+ set(value) {
368
+ Object.defineProperty(this, key, {
369
+ configurable: true,
370
+ writable: true,
371
+ value
372
+ });
373
+ }
374
+ });
375
+ }
376
+ /**
377
+ * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own
378
+ * data property. One accessor per constructor rather than one per instance, because an own accessor
379
+ * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel.
380
+ */
381
+ function installLazyProp(inst, key, make, enumerable) {
382
+ const proto = claim(inst, key);
383
+ if (!proto) return;
384
+ Object.defineProperty(proto, key, {
385
+ configurable: true,
386
+ get() {
387
+ const desc = {
388
+ configurable: true,
389
+ writable: true,
390
+ enumerable,
391
+ value: void 0
392
+ };
393
+ Object.defineProperty(this, key, desc);
394
+ desc.value = make(this);
395
+ Object.defineProperty(this, key, desc);
396
+ return desc.value;
397
+ },
398
+ set(value) {
399
+ Object.defineProperty(this, key, {
400
+ configurable: true,
401
+ writable: true,
402
+ enumerable,
403
+ value
404
+ });
405
+ }
406
+ });
407
+ }
408
+ // node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/locales/en.js
409
+ const error = () => {
410
+ const Sizable = {
411
+ string: {
412
+ unit: "characters",
413
+ verb: "to have"
414
+ },
415
+ file: {
416
+ unit: "bytes",
417
+ verb: "to have"
418
+ },
419
+ array: {
420
+ unit: "items",
421
+ verb: "to have"
422
+ },
423
+ set: {
424
+ unit: "items",
425
+ verb: "to have"
426
+ },
427
+ map: {
428
+ unit: "entries",
429
+ verb: "to have"
430
+ }
431
+ };
432
+ function getSizing(origin) {
433
+ return Sizable[origin] ?? null;
434
+ }
435
+ const FormatDictionary = {
436
+ regex: "input",
437
+ email: "email address",
438
+ url: "URL",
439
+ emoji: "emoji",
440
+ uuid: "UUID",
441
+ uuidv4: "UUIDv4",
442
+ uuidv6: "UUIDv6",
443
+ nanoid: "nanoid",
444
+ guid: "GUID",
445
+ cuid: "cuid",
446
+ cuid2: "cuid2",
447
+ ulid: "ULID",
448
+ xid: "XID",
449
+ ksuid: "KSUID",
450
+ datetime: "ISO datetime",
451
+ date: "ISO date",
452
+ time: "ISO time",
453
+ duration: "ISO duration",
454
+ ipv4: "IPv4 address",
455
+ ipv6: "IPv6 address",
456
+ mac: "MAC address",
457
+ cidrv4: "IPv4 range",
458
+ cidrv6: "IPv6 range",
459
+ base64: "base64-encoded string",
460
+ base64url: "base64url-encoded string",
461
+ json_string: "JSON string",
462
+ e164: "E.164 number",
463
+ currency_code: "currency code",
464
+ credit_card: "credit card number",
465
+ iban: "IBAN",
466
+ jwt: "JWT",
467
+ template_literal: "input"
468
+ };
469
+ const TypeDictionary = { nan: "NaN" };
470
+ function getTypeName(type, input) {
471
+ if (type === "number" && typeof input === "number" && !Number.isFinite(input)) return String(input);
472
+ return TypeDictionary[type] ?? type;
473
+ }
474
+ return (issue) => {
475
+ switch (issue.code) {
476
+ case "invalid_type": return `Invalid input: expected ${getTypeName(issue.expected)}, received ${getTypeName(parsedType(issue.input), issue.input)}`;
477
+ case "invalid_value":
478
+ if (issue.values.length === 1) return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`;
479
+ return `Invalid option: expected one of ${joinValues(issue.values, "|")}`;
480
+ case "too_big": {
481
+ const adj = issue.exact ? "exactly " : issue.inclusive ? "<=" : "<";
482
+ const sizing = getSizing(issue.origin);
483
+ if (sizing) return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`;
484
+ return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`;
485
+ }
486
+ case "too_small": {
487
+ const adj = issue.exact ? "exactly " : issue.inclusive ? ">=" : ">";
488
+ const sizing = getSizing(issue.origin);
489
+ if (sizing) return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;
490
+ return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;
491
+ }
492
+ case "invalid_format": {
493
+ const _issue = issue;
494
+ if (_issue.format === "starts_with") return `Invalid string: must start with "${_issue.prefix}"`;
495
+ if (_issue.format === "ends_with") return `Invalid string: must end with "${_issue.suffix}"`;
496
+ if (_issue.format === "includes") return `Invalid string: must include "${_issue.includes}"`;
497
+ if (_issue.format === "regex") return `Invalid string: must match pattern ${_issue.pattern}`;
498
+ return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;
499
+ }
500
+ case "not_multiple_of": return `Invalid number: must be a multiple of ${issue.divisor}`;
501
+ case "unrecognized_keys": return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`;
502
+ case "invalid_key": return `Invalid key in ${issue.origin}`;
503
+ case "invalid_union":
504
+ if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) return `Invalid discriminator value. Expected ${issue.options.map((o) => `'${o}'`).join(" | ")}`;
505
+ if (issue.inclusive === false) return "Invalid input: more than one option matched";
506
+ return "Invalid input";
507
+ case "invalid_element": return `Invalid value in ${issue.origin}`;
508
+ default: return `Invalid input`;
509
+ }
510
+ };
511
+ };
512
+ function en_default() {
513
+ return { localeError: error() };
514
+ }
515
+ // node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/errors.js
516
+ function _getMessage() {
517
+ const internals = this._zod;
518
+ internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2));
519
+ return internals.message;
520
+ }
521
+ function _setMessage(value) {
522
+ this._zod.message = value;
523
+ }
524
+ const _messageDesc = {
525
+ get: _getMessage,
526
+ set: _setMessage,
527
+ enumerable: true,
528
+ configurable: true
529
+ };
530
+ const _issuesDesc = {
531
+ value: void 0,
532
+ enumerable: false
533
+ };
534
+ const _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
535
+ const initializer = (inst, def) => {
536
+ inst.name = "$ZodError";
537
+ _issuesDesc.value = def;
538
+ Object.defineProperty(inst, "issues", _issuesDesc);
539
+ _issuesDesc.value = void 0;
540
+ Object.defineProperty(inst, "message", _messageDesc);
541
+ const proto = Object.getPrototypeOf(inst);
542
+ if (!_installedToString.has(proto)) {
543
+ _installedToString.add(proto);
544
+ Object.defineProperty(proto, "toString", {
545
+ configurable: true,
546
+ enumerable: false,
547
+ get() {
548
+ const value = () => this.message;
549
+ Object.defineProperty(this, "toString", {
550
+ value,
551
+ configurable: true,
552
+ writable: true
553
+ });
554
+ return value;
555
+ },
556
+ set(value) {
557
+ Object.defineProperty(this, "toString", {
558
+ value,
559
+ configurable: true,
560
+ writable: true
561
+ });
562
+ }
563
+ });
564
+ }
565
+ };
566
+ const $ZodRealError = /* @__PURE__ */ $constructor("$ZodError", initializer, void 0, { Parent: Error });
567
+ /** Format a ZodError as a human-readable string in the following form.
568
+ *
569
+ * From
570
+ *
571
+ * ```ts
572
+ * ZodError {
573
+ * issues: [
574
+ * {
575
+ * expected: 'string',
576
+ * code: 'invalid_type',
577
+ * path: [ 'username' ],
578
+ * message: 'Invalid input: expected string'
579
+ * },
580
+ * {
581
+ * expected: 'number',
582
+ * code: 'invalid_type',
583
+ * path: [ 'favoriteNumbers', 1 ],
584
+ * message: 'Invalid input: expected number'
585
+ * }
586
+ * ];
587
+ * }
588
+ * ```
589
+ *
590
+ * to
591
+ *
592
+ * ```
593
+ * username
594
+ * ✖ Expected number, received string at "username
595
+ * favoriteNumbers[0]
596
+ * ✖ Invalid input: expected number
597
+ * ```
598
+ */
599
+ function toDotPath(_path) {
600
+ const segs = [];
601
+ const path = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
602
+ for (const seg of path) if (typeof seg === "number") segs.push(`[${seg}]`);
603
+ else if (typeof seg === "symbol") segs.push(`[${JSON.stringify(String(seg))}]`);
604
+ else if (/[^\w$]/.test(seg)) segs.push(`[${JSON.stringify(seg)}]`);
605
+ else {
606
+ if (segs.length) segs.push(".");
607
+ segs.push(seg);
608
+ }
609
+ return segs.join("");
610
+ }
611
+ function prettifyError(error) {
612
+ const lines = [];
613
+ const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);
614
+ for (const issue of issues) {
615
+ lines.push(`✖ ${issue.message}`);
616
+ if (issue.path?.length) lines.push(` → at ${toDotPath(issue.path)}`);
617
+ }
618
+ return lines.join("\n");
619
+ }
620
+ // node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/parse.js
621
+ const _parse = (_Err) => {
622
+ const fn = (schema, value, _ctx, _params) => {
623
+ const ctx = _ctx ? {
624
+ ..._ctx,
625
+ async: false
626
+ } : { async: false };
627
+ const result = schema._zod.run({
628
+ value,
629
+ issues: []
630
+ }, ctx);
631
+ if (result instanceof Promise) throw new $ZodAsyncError();
632
+ if (result.issues.length) {
633
+ const e = new ((_params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
634
+ captureStackTrace(e, _params?.callee ?? fn);
635
+ throw e;
636
+ }
637
+ return result.value;
638
+ };
639
+ return fn;
640
+ };
641
+ const parse = /* @__PURE__*/ _parse($ZodRealError);
642
+ const _parseAsync = (_Err) => {
643
+ const fn = async (schema, value, _ctx, params) => {
644
+ const ctx = _ctx ? {
645
+ ..._ctx,
646
+ async: true
647
+ } : { async: true };
648
+ let result = schema._zod.run({
649
+ value,
650
+ issues: []
651
+ }, ctx);
652
+ if (result instanceof Promise) result = await result;
653
+ if (result.issues.length) {
654
+ const e = new ((params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
655
+ captureStackTrace(e, params?.callee ?? fn);
656
+ throw e;
657
+ }
658
+ return result.value;
659
+ };
660
+ return fn;
661
+ };
662
+ const parseAsync = /* @__PURE__*/ _parseAsync($ZodRealError);
663
+ const _safeParse = (_Err) => (schema, value, _ctx) => {
664
+ const ctx = _ctx ? {
665
+ ..._ctx,
666
+ async: false
667
+ } : { async: false };
668
+ const result = schema._zod.run({
669
+ value,
670
+ issues: []
671
+ }, ctx);
672
+ if (result instanceof Promise) throw new $ZodAsyncError();
673
+ return result.issues.length ? failure(_Err, result.issues, ctx) : {
674
+ success: true,
675
+ data: result.value
676
+ };
677
+ };
678
+ const safeParse = /* @__PURE__*/ _safeParse($ZodRealError);
679
+ function failure(Err, issues, ctx) {
680
+ let error;
681
+ return {
682
+ success: false,
683
+ get error() {
684
+ if (!error) {
685
+ error = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config())));
686
+ issues = void 0;
687
+ ctx = void 0;
688
+ }
689
+ return error;
690
+ },
691
+ set error(e) {
692
+ error = e;
693
+ issues = void 0;
694
+ ctx = void 0;
695
+ }
696
+ };
697
+ }
698
+ const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
699
+ const ctx = _ctx ? {
700
+ ..._ctx,
701
+ async: true
702
+ } : { async: true };
703
+ let result = schema._zod.run({
704
+ value,
705
+ issues: []
706
+ }, ctx);
707
+ if (result instanceof Promise) result = await result;
708
+ return result.issues.length ? failure(_Err, result.issues, ctx) : {
709
+ success: true,
710
+ data: result.value
711
+ };
712
+ };
713
+ const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError);
714
+ // node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/regexes.js
715
+ const anyString = /^[\s\S]{0,}$/;
716
+ const number$1 = /^-?\d+(?:\.\d+)?$/;
717
+ // node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/checks.js
718
+ const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => {
719
+ var _a;
720
+ inst._zod ?? (inst._zod = {});
721
+ inst._zod.def = def;
722
+ (_a = inst._zod).onattach ?? (_a.onattach = []);
723
+ });
724
+ /** Default `when` for length-based checks: run only on non-nullish values with a `length`. */
725
+ const _whenHasLength = (payload) => {
726
+ const val = payload.value;
727
+ return !nullish(val) && val.length !== void 0;
728
+ };
729
+ const numericOriginMap = {
730
+ number: "number",
731
+ bigint: "bigint",
732
+ object: "date"
733
+ };
734
+ const $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => {
735
+ $ZodCheck.init(inst, def);
736
+ const origin = numericOriginMap[typeof def.value];
737
+ inst._zod.check = (payload) => {
738
+ if (def.inclusive ? payload.value <= def.value : payload.value < def.value) return;
739
+ payload.issues.push({
740
+ origin: numericOriginMap[typeof payload.value] ?? origin,
741
+ code: "too_big",
742
+ maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
743
+ input: payload.value,
744
+ inclusive: def.inclusive,
745
+ inst,
746
+ continue: !def.abort
747
+ });
748
+ };
749
+ });
750
+ const $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => {
751
+ $ZodCheck.init(inst, def);
752
+ const origin = numericOriginMap[typeof def.value];
753
+ inst._zod.check = (payload) => {
754
+ if (def.inclusive ? payload.value >= def.value : payload.value > def.value) return;
755
+ payload.issues.push({
756
+ origin: numericOriginMap[typeof payload.value] ?? origin,
757
+ code: "too_small",
758
+ minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
759
+ input: payload.value,
760
+ inclusive: def.inclusive,
761
+ inst,
762
+ continue: !def.abort
763
+ });
764
+ };
765
+ });
766
+ const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => {
767
+ $ZodCheck.init(inst, def);
768
+ def.format = def.format || "float64";
769
+ const isInt = def.format?.includes("int");
770
+ const origin = isInt ? "int" : "number";
771
+ const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
772
+ inst._zod.check = (payload) => {
773
+ const input = payload.value;
774
+ if (isInt) {
775
+ if (!Number.isInteger(input)) {
776
+ payload.issues.push({
777
+ expected: origin,
778
+ format: def.format,
779
+ code: "invalid_type",
780
+ continue: false,
781
+ input,
782
+ inst
783
+ });
784
+ return;
785
+ }
786
+ if (!Number.isSafeInteger(input)) {
787
+ if (input > 0) payload.issues.push({
788
+ input,
789
+ code: "too_big",
790
+ maximum: Number.MAX_SAFE_INTEGER,
791
+ note: "Integers must be within the safe integer range.",
792
+ inst,
793
+ origin,
794
+ inclusive: true,
795
+ continue: !def.abort
796
+ });
797
+ else payload.issues.push({
798
+ input,
799
+ code: "too_small",
800
+ minimum: Number.MIN_SAFE_INTEGER,
801
+ note: "Integers must be within the safe integer range.",
802
+ inst,
803
+ origin,
804
+ inclusive: true,
805
+ continue: !def.abort
806
+ });
807
+ return;
808
+ }
809
+ }
810
+ if (input < minimum) payload.issues.push({
811
+ origin: "number",
812
+ input,
813
+ code: "too_small",
814
+ minimum,
815
+ inclusive: true,
816
+ inst,
817
+ continue: !def.abort
818
+ });
819
+ if (input > maximum) payload.issues.push({
820
+ origin: "number",
821
+ input,
822
+ code: "too_big",
823
+ maximum,
824
+ inclusive: true,
825
+ inst,
826
+ continue: !def.abort
827
+ });
828
+ };
829
+ });
830
+ const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => {
831
+ var _a;
832
+ $ZodCheck.init(inst, def);
833
+ (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
834
+ inst._zod.check = (payload) => {
835
+ const input = payload.value;
836
+ const units = input.length;
837
+ if ((typeof input === "string" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input) : units) >= def.minimum) return;
838
+ const origin = getLengthableOrigin(input);
839
+ payload.issues.push({
840
+ origin,
841
+ code: "too_small",
842
+ minimum: def.minimum,
843
+ inclusive: true,
844
+ input,
845
+ inst,
846
+ continue: !def.abort
847
+ });
848
+ };
849
+ });
850
+ const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => {
851
+ var _a, _b;
852
+ $ZodCheck.init(inst, def);
853
+ if (def.pattern) (_a = inst._zod).check ?? (_a.check = (payload) => {
854
+ def.pattern.lastIndex = 0;
855
+ if (def.pattern.test(payload.value)) return;
856
+ payload.issues.push({
857
+ origin: "string",
858
+ code: "invalid_format",
859
+ format: def.format,
860
+ input: payload.value,
861
+ ...def.pattern ? { pattern: def.pattern.toString() } : {},
862
+ inst,
863
+ continue: !def.abort
864
+ });
865
+ });
866
+ else (_b = inst._zod).check ?? (_b.check = () => {});
867
+ });
868
+ const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => {
869
+ $ZodCheckStringFormat.init(inst, def);
870
+ inst._zod.check = (payload) => {
871
+ def.pattern.lastIndex = 0;
872
+ if (def.pattern.test(payload.value)) return;
873
+ payload.issues.push({
874
+ origin: "string",
875
+ code: "invalid_format",
876
+ format: "regex",
877
+ input: payload.value,
878
+ pattern: def.pattern.toString(),
879
+ inst,
880
+ continue: !def.abort
881
+ });
882
+ };
883
+ });
884
+ // node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/versions.js
885
+ const version = {
886
+ major: 4,
887
+ minor: 6,
888
+ patch: 7
889
+ };
890
+ // node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/schemas.js
891
+ const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
892
+ var _a;
893
+ inst ?? (inst = {});
894
+ inst._zod.def = def;
895
+ inst._zod.bag = inst._zod.bag || {};
896
+ inst._zod.version = version;
897
+ const defChecks = inst._zod.def.checks;
898
+ const checks = inst._zod.traits.has("$ZodCheck") ? [inst, ...defChecks ?? []] : defChecks?.length ? [...defChecks] : [];
899
+ for (const ch of checks) for (const fn of ch._zod.onattach) fn(inst);
900
+ if (checks.length === 0) {
901
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
902
+ inst._zod.deferred?.push(() => {
903
+ inst._zod.run = inst._zod.parse;
904
+ });
905
+ } else {
906
+ const runChecks = (payload, checks, ctx) => {
907
+ if (payload.memo) return payload;
908
+ let isAborted = aborted(payload);
909
+ let asyncResult;
910
+ for (const ch of checks) {
911
+ if (ch._zod.def.when) {
912
+ if (explicitlyAborted(payload)) continue;
913
+ if (!ch._zod.def.when(payload)) continue;
914
+ } else if (isAborted) continue;
915
+ const currLen = payload.issues.length;
916
+ const _ = ch._zod.check(payload);
917
+ if (_ instanceof Promise && ctx?.async === false) throw new $ZodAsyncError();
918
+ if (asyncResult || _ instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
919
+ await _;
920
+ if (payload.issues.length === currLen) return;
921
+ attachSchema(payload.issues, currLen, inst);
922
+ if (!isAborted) isAborted = aborted(payload, currLen);
923
+ });
924
+ else {
925
+ if (payload.issues.length === currLen) continue;
926
+ attachSchema(payload.issues, currLen, inst);
927
+ if (!isAborted) isAborted = aborted(payload, currLen);
928
+ }
929
+ }
930
+ if (asyncResult) return asyncResult.then(() => {
931
+ return payload;
932
+ });
933
+ return payload;
934
+ };
935
+ const handleCanaryResult = (canary, payload, ctx) => {
936
+ if (aborted(canary)) {
937
+ canary.aborted = true;
938
+ return canary;
939
+ }
940
+ const checkResult = runChecks(payload, checks, ctx);
941
+ if (checkResult instanceof Promise) {
942
+ if (ctx.async === false) throw new $ZodAsyncError();
943
+ return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));
944
+ }
945
+ return inst._zod.parse(checkResult, ctx);
946
+ };
947
+ inst._zod.run = (payload, ctx) => {
948
+ if (ctx.skipChecks) return inst._zod.parse(payload, ctx);
949
+ if (ctx.direction === "backward") {
950
+ const canary = inst._zod.parse({
951
+ value: payload.value,
952
+ issues: []
953
+ }, {
954
+ ...ctx,
955
+ skipChecks: true
956
+ });
957
+ if (canary instanceof Promise) return canary.then((canary) => {
958
+ return handleCanaryResult(canary, payload, ctx);
959
+ });
960
+ return handleCanaryResult(canary, payload, ctx);
961
+ }
962
+ const result = inst._zod.parse(payload, ctx);
963
+ if (result instanceof Promise) {
964
+ if (ctx.async === false) throw new $ZodAsyncError();
965
+ return result.then((result) => runChecks(result, checks, ctx));
966
+ }
967
+ return runChecks(result, checks, ctx);
968
+ };
969
+ }
970
+ }, {
971
+ get "~standard"() {
972
+ return hide(this, "~standard", standardProps(this));
973
+ },
974
+ set "~standard"(value) {
975
+ own(this, "~standard", value);
976
+ }
977
+ });
978
+ /** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */
979
+ const toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config())) } : { value: r.value };
980
+ async function validateAsync(inst, value) {
981
+ const ctx = { async: true };
982
+ return toStandardResult(await inst._zod.run({
983
+ value,
984
+ issues: []
985
+ }, ctx), ctx);
986
+ }
987
+ function standardProps(inst) {
988
+ return {
989
+ validate: (value) => {
990
+ const ctx = { async: false };
991
+ try {
992
+ const r = inst._zod.run({
993
+ value,
994
+ issues: []
995
+ }, ctx);
996
+ if (!(r instanceof Promise)) return toStandardResult(r, ctx);
997
+ } catch (_) {}
998
+ return validateAsync(inst, value);
999
+ },
1000
+ vendor: "zod",
1001
+ version: 1
1002
+ };
1003
+ }
1004
+ const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => {
1005
+ $ZodType.init(inst, def);
1006
+ inst._zod.pattern = def.pattern ?? anyString;
1007
+ inst._zod.parse = (payload, _) => {
1008
+ if (def.coerce) try {
1009
+ payload.value = String(payload.value);
1010
+ } catch (_) {}
1011
+ if (typeof payload.value === "string") return payload;
1012
+ payload.issues.push({
1013
+ expected: "string",
1014
+ code: "invalid_type",
1015
+ input: payload.value,
1016
+ inst
1017
+ });
1018
+ return payload;
1019
+ };
1020
+ });
1021
+ const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => {
1022
+ $ZodType.init(inst, def);
1023
+ inst._zod.pattern = number$1;
1024
+ inst._zod.parse = (payload, _ctx) => {
1025
+ if (def.coerce) try {
1026
+ payload.value = Number(payload.value);
1027
+ } catch (_) {}
1028
+ const input = payload.value;
1029
+ if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) return payload;
1030
+ const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? String(input) : void 0 : void 0;
1031
+ payload.issues.push({
1032
+ expected: "number",
1033
+ code: "invalid_type",
1034
+ input,
1035
+ inst,
1036
+ ...received ? { received } : {}
1037
+ });
1038
+ return payload;
1039
+ };
1040
+ });
1041
+ const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => {
1042
+ $ZodCheckNumberFormat.init(inst, def);
1043
+ $ZodNumber.init(inst, def);
1044
+ });
1045
+ const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => {
1046
+ $ZodType.init(inst, def);
1047
+ inst._zod.parse = (payload, _ctx) => {
1048
+ payload.issues.push({
1049
+ expected: "never",
1050
+ code: "invalid_type",
1051
+ input: payload.value,
1052
+ inst
1053
+ });
1054
+ return payload;
1055
+ };
1056
+ });
1057
+ function handlePropertyResult(result, final, key, input, optin, optout) {
1058
+ const isPresent = key in input;
1059
+ const isOptionalOut = optout === "optional";
1060
+ if (!isPresent && isOptionalOut && optin === "optional") return;
1061
+ if (result.issues.length) {
1062
+ if (optin !== void 0 && isOptionalOut && !isPresent) return;
1063
+ final.issues.push(...prefixIssues(key, result.issues));
1064
+ }
1065
+ if (!isPresent && optin === void 0) {
1066
+ if (!result.issues.length) final.issues.push({
1067
+ code: "invalid_type",
1068
+ expected: "nonoptional",
1069
+ input: void 0,
1070
+ path: [key]
1071
+ });
1072
+ return;
1073
+ }
1074
+ if (result.value === void 0) {
1075
+ if (isPresent || optin === "defaulted" && !isOptionalOut) final.value[key] = void 0;
1076
+ } else final.value[key] = result.value;
1077
+ }
1078
+ const NO_SYMBOL_KEYS = [];
1079
+ function normalizeDef(def) {
1080
+ const keys = Object.keys(def.shape);
1081
+ const ownSymbols = Object.getOwnPropertySymbols(def.shape);
1082
+ const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;
1083
+ const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;
1084
+ for (const k of allKeys) if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`);
1085
+ const okeys = optionalKeys(def.shape);
1086
+ return {
1087
+ ...def,
1088
+ allKeys,
1089
+ symbolKeys,
1090
+ keySet: new Set(keys),
1091
+ numKeys: keys.length,
1092
+ optionalKeys: new Set(okeys)
1093
+ };
1094
+ }
1095
+ function handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {
1096
+ const unrecognized = [];
1097
+ const keySet = def.keySet;
1098
+ const _catchall = def.catchall._zod;
1099
+ const t = _catchall.def.type;
1100
+ const optin = _catchall.optin;
1101
+ const optout = _catchall.optout;
1102
+ let seen = 0;
1103
+ for (const key in input) {
1104
+ if (abortEarly && payload.issues.length !== seen) {
1105
+ if (aborted(payload, seen)) break;
1106
+ seen = payload.issues.length;
1107
+ }
1108
+ if (keySet.has(key)) continue;
1109
+ if (key === "__proto__") {
1110
+ if (t === "never") unrecognized.push(key);
1111
+ continue;
1112
+ }
1113
+ if (t === "never") {
1114
+ unrecognized.push(key);
1115
+ continue;
1116
+ }
1117
+ const r = _catchall.run({
1118
+ value: input[key],
1119
+ issues: []
1120
+ }, ctx);
1121
+ if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));
1122
+ else handlePropertyResult(r, payload, key, input, optin, optout);
1123
+ }
1124
+ if (unrecognized.length) payload.issues.push({
1125
+ code: "unrecognized_keys",
1126
+ keys: unrecognized,
1127
+ input,
1128
+ inst,
1129
+ continue: true
1130
+ });
1131
+ if (!proms.length) return payload;
1132
+ return Promise.all(proms).then(() => {
1133
+ return payload;
1134
+ });
1135
+ }
1136
+ const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
1137
+ $ZodType.init(inst, def);
1138
+ const desc = Object.getOwnPropertyDescriptor(def, "shape");
1139
+ const sh = desc?.get ? desc.get.raw : def.shape ?? {};
1140
+ if (sh) {
1141
+ const get = () => {
1142
+ const newSh = { ...sh };
1143
+ Object.defineProperty(def, "shape", { value: newSh });
1144
+ get.raw = newSh;
1145
+ return newSh;
1146
+ };
1147
+ get.raw = sh;
1148
+ Object.defineProperty(def, "shape", { get });
1149
+ }
1150
+ const _normalized = cached(() => normalizeDef(def));
1151
+ defineLazyInternal(inst, "propValues", (zod) => {
1152
+ const shape = zod.def.shape;
1153
+ const propValues = {};
1154
+ for (const key in shape) {
1155
+ const field = shape[key]._zod;
1156
+ if (field.values) {
1157
+ if (!Object.prototype.hasOwnProperty.call(propValues, key)) assignProp(propValues, key, /* @__PURE__ */ new Set());
1158
+ for (const v of field.values) propValues[key].add(v);
1159
+ if (field.optin !== void 0) propValues[key].add(void 0);
1160
+ }
1161
+ }
1162
+ return propValues;
1163
+ });
1164
+ const isObject$1 = isObject;
1165
+ const catchall = def.catchall;
1166
+ let value;
1167
+ const memo = globalConfig.memoizer;
1168
+ memo?.attach(inst);
1169
+ inst._zod.parse = (payload, ctx) => {
1170
+ value ?? (value = _normalized.value);
1171
+ const input = payload.value;
1172
+ if (!isObject$1(input)) {
1173
+ payload.issues.push({
1174
+ expected: "object",
1175
+ code: "invalid_type",
1176
+ input,
1177
+ inst
1178
+ });
1179
+ return payload;
1180
+ }
1181
+ payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
1182
+ const proms = [];
1183
+ const shape = value.shape;
1184
+ const abortEarly = ctx?.abortEarly;
1185
+ let seen = payload.issues.length;
1186
+ for (const key of value.allKeys) {
1187
+ if (abortEarly && payload.issues.length !== seen) {
1188
+ if (aborted(payload, seen)) break;
1189
+ seen = payload.issues.length;
1190
+ }
1191
+ if (key === "__proto__") continue;
1192
+ const el = shape[key];
1193
+ const optin = el._zod.optin;
1194
+ const optout = el._zod.optout;
1195
+ const r = el._zod.run({
1196
+ value: input[key],
1197
+ issues: []
1198
+ }, ctx);
1199
+ if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));
1200
+ else handlePropertyResult(r, payload, key, input, optin, optout);
1201
+ }
1202
+ if (!catchall) return proms.length ? Promise.all(proms).then(() => payload) : payload;
1203
+ return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true);
1204
+ };
1205
+ });
1206
+ const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => {
1207
+ $ZodType.init(inst, def);
1208
+ const memo = globalConfig.memoizer;
1209
+ memo?.attach(inst);
1210
+ inst._zod.parse = (payload, ctx) => {
1211
+ const input = payload.value;
1212
+ if (!isPlainObject(input)) {
1213
+ payload.issues.push({
1214
+ expected: "record",
1215
+ code: "invalid_type",
1216
+ input,
1217
+ inst
1218
+ });
1219
+ return payload;
1220
+ }
1221
+ const proms = [];
1222
+ const values = def.keyType._zod.values;
1223
+ if (values && !def.partial) {
1224
+ payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
1225
+ const recordKeys = /* @__PURE__ */ new Set();
1226
+ for (const key of values) if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
1227
+ recordKeys.add(typeof key === "number" ? key.toString() : key);
1228
+ if (key === "__proto__") continue;
1229
+ const keyResult = def.keyType._zod.run({
1230
+ value: key,
1231
+ issues: []
1232
+ }, ctx);
1233
+ if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently");
1234
+ if (keyResult.issues.length) {
1235
+ payload.issues.push({
1236
+ code: "invalid_key",
1237
+ origin: "record",
1238
+ issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
1239
+ input: key,
1240
+ path: [key],
1241
+ inst
1242
+ });
1243
+ continue;
1244
+ }
1245
+ const outKey = keyResult.value;
1246
+ if (outKey === "__proto__") continue;
1247
+ const result = def.valueType._zod.run({
1248
+ value: input[key],
1249
+ issues: []
1250
+ }, ctx);
1251
+ if (result instanceof Promise) proms.push(result.then((result) => {
1252
+ if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
1253
+ payload.value[outKey] = result.value;
1254
+ }));
1255
+ else {
1256
+ if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
1257
+ payload.value[outKey] = result.value;
1258
+ }
1259
+ }
1260
+ let unrecognized;
1261
+ for (const key in input) if (!recordKeys.has(key)) {
1262
+ if (def.mode === "loose") {
1263
+ if (key === "__proto__") continue;
1264
+ payload.value[key] = input[key];
1265
+ } else {
1266
+ unrecognized = unrecognized ?? [];
1267
+ unrecognized.push(key);
1268
+ }
1269
+ }
1270
+ if (unrecognized && unrecognized.length > 0) payload.issues.push({
1271
+ code: "unrecognized_keys",
1272
+ input,
1273
+ inst,
1274
+ keys: unrecognized,
1275
+ continue: true
1276
+ });
1277
+ } else {
1278
+ payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
1279
+ let unrecognized;
1280
+ for (const key of Reflect.ownKeys(input)) {
1281
+ if (key === "__proto__") continue;
1282
+ if (!Object.prototype.propertyIsEnumerable.call(input, key)) continue;
1283
+ let keyResult = def.keyType._zod.run({
1284
+ value: key,
1285
+ issues: []
1286
+ }, ctx);
1287
+ if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently");
1288
+ if (typeof key === "string" && number$1.test(key) && keyResult.issues.length) {
1289
+ const retryResult = def.keyType._zod.run({
1290
+ value: Number(key),
1291
+ issues: []
1292
+ }, ctx);
1293
+ if (retryResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently");
1294
+ if (retryResult.issues.length === 0) keyResult = retryResult;
1295
+ }
1296
+ if (keyResult.issues.length) {
1297
+ if (def.mode === "loose") payload.value[key] = input[key];
1298
+ else if (values) {
1299
+ unrecognized = unrecognized ?? [];
1300
+ unrecognized.push(key);
1301
+ } else payload.issues.push({
1302
+ code: "invalid_key",
1303
+ origin: "record",
1304
+ issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
1305
+ input: key,
1306
+ path: [key],
1307
+ inst
1308
+ });
1309
+ continue;
1310
+ }
1311
+ const outKey = keyResult.value;
1312
+ if (outKey === "__proto__") continue;
1313
+ const result = def.valueType._zod.run({
1314
+ value: input[key],
1315
+ issues: []
1316
+ }, ctx);
1317
+ if (result instanceof Promise) proms.push(result.then((result) => {
1318
+ if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
1319
+ payload.value[outKey] = result.value;
1320
+ }));
1321
+ else {
1322
+ if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
1323
+ payload.value[outKey] = result.value;
1324
+ }
1325
+ }
1326
+ if (unrecognized && unrecognized.length > 0) payload.issues.push({
1327
+ code: "unrecognized_keys",
1328
+ input,
1329
+ inst,
1330
+ keys: unrecognized,
1331
+ continue: true
1332
+ });
1333
+ }
1334
+ if (proms.length) return Promise.all(proms).then(() => payload);
1335
+ return payload;
1336
+ };
1337
+ });
1338
+ function handleOptionalResult(payload, result) {
1339
+ payload.value = result.issues.length ? void 0 : result.value;
1340
+ return payload;
1341
+ }
1342
+ const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => {
1343
+ $ZodType.init(inst, def);
1344
+ defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional");
1345
+ inst._zod.optout = "optional";
1346
+ defineLazyInternal(inst, "values", (zod) => {
1347
+ const values = zod.def.innerType._zod.values;
1348
+ return values ? /* @__PURE__ */ new Set([...values, void 0]) : void 0;
1349
+ });
1350
+ defineLazyInternal(inst, "pattern", (zod) => {
1351
+ const pattern = zod.def.innerType._zod.pattern;
1352
+ return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;
1353
+ });
1354
+ inst._zod.parse = (payload, ctx) => {
1355
+ if (payload.value === void 0) {
1356
+ if (def.innerType._zod.optin !== "defaulted") return payload;
1357
+ const result = def.innerType._zod.run({
1358
+ value: payload.value,
1359
+ issues: []
1360
+ }, ctx);
1361
+ if (result instanceof Promise) return result.then((result) => handleOptionalResult(payload, result));
1362
+ return handleOptionalResult(payload, result);
1363
+ }
1364
+ return def.innerType._zod.run(payload, ctx);
1365
+ };
1366
+ });
1367
+ // node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/registries.js
1368
+ var _a;
1369
+ var $ZodRegistry = class {
1370
+ constructor() {
1371
+ this._map = /* @__PURE__ */ new WeakMap();
1372
+ this._idmap = /* @__PURE__ */ new Map();
1373
+ }
1374
+ add(schema, ..._meta) {
1375
+ const meta = _meta[0];
1376
+ this._map.set(schema, meta);
1377
+ if (meta && typeof meta === "object" && "id" in meta) this._idmap.set(meta.id, schema);
1378
+ return this;
1379
+ }
1380
+ clear() {
1381
+ this._map = /* @__PURE__ */ new WeakMap();
1382
+ this._idmap = /* @__PURE__ */ new Map();
1383
+ return this;
1384
+ }
1385
+ remove(schema) {
1386
+ const meta = this._map.get(schema);
1387
+ if (meta && typeof meta === "object" && "id" in meta) this._idmap.delete(meta.id);
1388
+ this._map.delete(schema);
1389
+ return this;
1390
+ }
1391
+ get(schema) {
1392
+ const p = schema._zod.parent;
1393
+ if (p) {
1394
+ const pm = { ...this.get(p) ?? {} };
1395
+ delete pm.id;
1396
+ const f = {
1397
+ ...pm,
1398
+ ...this._map.get(schema)
1399
+ };
1400
+ return Object.keys(f).length ? f : void 0;
1401
+ }
1402
+ return this._map.get(schema);
1403
+ }
1404
+ has(schema) {
1405
+ return this._map.has(schema);
1406
+ }
1407
+ };
1408
+ function registry() {
1409
+ return new $ZodRegistry();
1410
+ }
1411
+ (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
1412
+ const globalRegistry = globalThis.__zod_globalRegistry;
1413
+ // node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/api.js
1414
+ function snapshotChecks(def) {
1415
+ if (def.checks) def.checks = [...def.checks];
1416
+ return def;
1417
+ }
1418
+ // @__NO_SIDE_EFFECTS__
1419
+ function _string(Class, params) {
1420
+ return new Class(snapshotChecks({
1421
+ type: "string",
1422
+ ...normalizeParams(params)
1423
+ }));
1424
+ }
1425
+ // @__NO_SIDE_EFFECTS__
1426
+ function _number(Class, params) {
1427
+ return new Class(snapshotChecks({
1428
+ type: "number",
1429
+ checks: [],
1430
+ ...normalizeParams(params)
1431
+ }));
1432
+ }
1433
+ // @__NO_SIDE_EFFECTS__
1434
+ function _int(Class, params) {
1435
+ return new Class({
1436
+ type: "number",
1437
+ check: "number_format",
1438
+ abort: false,
1439
+ format: "safeint",
1440
+ ...normalizeParams(params)
1441
+ });
1442
+ }
1443
+ // @__NO_SIDE_EFFECTS__
1444
+ function _never(Class, params) {
1445
+ return new Class({
1446
+ type: "never",
1447
+ ...normalizeParams(params)
1448
+ });
1449
+ }
1450
+ // @__NO_SIDE_EFFECTS__
1451
+ function _lte(value, params) {
1452
+ return new $ZodCheckLessThan({
1453
+ check: "less_than",
1454
+ ...normalizeParams(params),
1455
+ value,
1456
+ inclusive: true
1457
+ });
1458
+ }
1459
+ // @__NO_SIDE_EFFECTS__
1460
+ function _gt(value, params) {
1461
+ return new $ZodCheckGreaterThan({
1462
+ check: "greater_than",
1463
+ ...normalizeParams(params),
1464
+ value,
1465
+ inclusive: false
1466
+ });
1467
+ }
1468
+ // @__NO_SIDE_EFFECTS__
1469
+ function _gte(value, params) {
1470
+ return new $ZodCheckGreaterThan({
1471
+ check: "greater_than",
1472
+ ...normalizeParams(params),
1473
+ value,
1474
+ inclusive: true
1475
+ });
1476
+ }
1477
+ // @__NO_SIDE_EFFECTS__
1478
+ function _positive(params) {
1479
+ return /* @__PURE__ */ _gt(0, params);
1480
+ }
1481
+ // @__NO_SIDE_EFFECTS__
1482
+ function _minLength(minimum, params) {
1483
+ return new $ZodCheckMinLength({
1484
+ check: "min_length",
1485
+ ...normalizeParams(params),
1486
+ minimum
1487
+ });
1488
+ }
1489
+ // @__NO_SIDE_EFFECTS__
1490
+ function _regex(pattern, params) {
1491
+ return new $ZodCheckRegex({
1492
+ check: "string_format",
1493
+ format: "regex",
1494
+ ...normalizeParams(params),
1495
+ pattern
1496
+ });
1497
+ }
1498
+ // @__NO_SIDE_EFFECTS__
1499
+ function describe$2(description) {
1500
+ const ch = new $ZodCheck({ check: "describe" });
1501
+ ch._zod.onattach = [(inst) => {
1502
+ const existing = globalRegistry.get(inst) ?? {};
1503
+ globalRegistry.add(inst, {
1504
+ ...existing,
1505
+ description
1506
+ });
1507
+ }];
1508
+ ch._zod.check = () => {};
1509
+ return ch;
1510
+ }
1511
+ // node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/schemas.js
1512
+ const ZodMiniType = /*@__PURE__*/ $constructor("ZodMiniType", (inst, def) => {
1513
+ if (!inst._zod) throw new Error("Uninitialized schema in ZodMiniType.");
1514
+ $ZodType.init(inst, def);
1515
+ inst.def = def;
1516
+ inst.type = def.type;
1517
+ }, {
1518
+ get with() {
1519
+ return this.check;
1520
+ },
1521
+ set with(value) {
1522
+ own(this, "with", value);
1523
+ },
1524
+ parse(data, params) {
1525
+ return parse(this, data, params, { callee: this.parse });
1526
+ },
1527
+ parseAsync(data, params) {
1528
+ return parseAsync(this, data, params, { callee: this.parseAsync });
1529
+ },
1530
+ safeParse(data, params) {
1531
+ return safeParse(this, data, params);
1532
+ },
1533
+ safeParseAsync(data, params) {
1534
+ return safeParseAsync(this, data, params);
1535
+ },
1536
+ check(...checks) {
1537
+ const def = this.def;
1538
+ return this.clone({
1539
+ ...def,
1540
+ checks: [...def.checks ?? [], ...checks.map((ch) => typeof ch === "function" ? { _zod: {
1541
+ check: ch,
1542
+ def: { check: "custom" },
1543
+ onattach: []
1544
+ } } : ch)]
1545
+ }, { parent: true });
1546
+ },
1547
+ clone(_def, params) {
1548
+ return clone(this, _def, params);
1549
+ },
1550
+ brand() {
1551
+ return this;
1552
+ },
1553
+ register(reg, meta) {
1554
+ reg.add(this, meta);
1555
+ return this;
1556
+ },
1557
+ apply(fn, ...args) {
1558
+ return args.length === 0 ? fn(this) : fn(this, ...args);
1559
+ }
1560
+ });
1561
+ const ZodMiniString = /*@__PURE__*/ $constructor("ZodMiniString", (inst, def) => {
1562
+ $ZodString.init(inst, def);
1563
+ ZodMiniType.init(inst, def);
1564
+ });
1565
+ // @__NO_SIDE_EFFECTS__
1566
+ function string(params) {
1567
+ return /* @__PURE__ */ _string(ZodMiniString, params);
1568
+ }
1569
+ const ZodMiniNumber = /*@__PURE__*/ $constructor("ZodMiniNumber", (inst, def) => {
1570
+ $ZodNumber.init(inst, def);
1571
+ ZodMiniType.init(inst, def);
1572
+ });
1573
+ // @__NO_SIDE_EFFECTS__
1574
+ function number(params) {
1575
+ return /* @__PURE__ */ _number(ZodMiniNumber, params);
1576
+ }
1577
+ const ZodMiniNumberFormat = /*@__PURE__*/ $constructor("ZodMiniNumberFormat", (inst, def) => {
1578
+ $ZodNumberFormat.init(inst, def);
1579
+ ZodMiniNumber.init(inst, def);
1580
+ });
1581
+ function int(params) {
1582
+ return /* @__PURE__ */ _int(ZodMiniNumberFormat, params);
1583
+ }
1584
+ const ZodMiniNever = /*@__PURE__*/ $constructor("ZodMiniNever", (inst, def) => {
1585
+ $ZodNever.init(inst, def);
1586
+ ZodMiniType.init(inst, def);
1587
+ });
1588
+ // @__NO_SIDE_EFFECTS__
1589
+ function never(params) {
1590
+ return /* @__PURE__ */ _never(ZodMiniNever, params);
1591
+ }
1592
+ const ZodMiniObject = /*@__PURE__*/ $constructor("ZodMiniObject", (inst, def) => {
1593
+ $ZodObject.init(inst, def);
1594
+ ZodMiniType.init(inst, def);
1595
+ installLazyProp(inst, "shape", (self) => self._zod.def.shape, false);
1596
+ });
1597
+ // @__NO_SIDE_EFFECTS__
1598
+ function strictObject(shape, params) {
1599
+ return new ZodMiniObject({
1600
+ type: "object",
1601
+ shape,
1602
+ catchall: /* @__PURE__ */ never(),
1603
+ ...normalizeParams(params)
1604
+ });
1605
+ }
1606
+ const ZodMiniRecord = /*@__PURE__*/ $constructor("ZodMiniRecord", (inst, def) => {
1607
+ $ZodRecord.init(inst, def);
1608
+ ZodMiniType.init(inst, def);
1609
+ });
1610
+ // @__NO_SIDE_EFFECTS__
1611
+ function record(keyType, valueType, params) {
1612
+ if (!valueType || !valueType._zod) return new ZodMiniRecord({
1613
+ type: "record",
1614
+ keyType: /* @__PURE__ */ string(),
1615
+ valueType: keyType,
1616
+ ...normalizeParams(valueType)
1617
+ });
1618
+ return new ZodMiniRecord({
1619
+ type: "record",
1620
+ keyType,
1621
+ valueType,
1622
+ ...normalizeParams(params)
1623
+ });
1624
+ }
1625
+ const ZodMiniOptional = /*@__PURE__*/ $constructor("ZodMiniOptional", (inst, def) => {
1626
+ $ZodOptional.init(inst, def);
1627
+ ZodMiniType.init(inst, def);
1628
+ });
1629
+ // @__NO_SIDE_EFFECTS__
1630
+ function optional(innerType) {
1631
+ return new ZodMiniOptional({
1632
+ type: "optional",
1633
+ innerType
1634
+ });
1635
+ }
1636
+ const describe$1 = describe$2;
1637
+ // src/config.ts
1638
+ config(en_default());
1639
+ const CONFIG_FILE = "portcall.json";
1640
+ const DEFAULT_READY_TIMEOUT = 60;
1641
+ const nameSchema = (/* @__PURE__ */ string()).check(/* @__PURE__ */ _regex(/^\w[\w.-]*$/, "use letters, digits, dot, dash or underscore"));
1642
+ const serviceSchema = /* @__PURE__ */ strictObject({
1643
+ command: (/* @__PURE__ */ optional((/* @__PURE__ */ string()).check(/* @__PURE__ */ _minLength(1)))).check(describe$1("Shell command that runs the service. Omit it for an external service (a database in Docker...): portcall then only checks its port.")),
1644
+ port: int().check(/* @__PURE__ */ _gte(1), /* @__PURE__ */ _lte(65535), describe$1("Port the service listens on. Also passed to the command as PORT.")),
1645
+ cwd: (/* @__PURE__ */ optional(/* @__PURE__ */ string())).check(describe$1("Directory to run the command in, relative to portcall.json. Default: the project root.")),
1646
+ env: (/* @__PURE__ */ optional(/* @__PURE__ */ record(/* @__PURE__ */ string(), /* @__PURE__ */ string()))).check(describe$1("Extra environment. {port} is this service's port, {ports.<service>} another service's.")),
1647
+ readyTimeout: (/* @__PURE__ */ optional((/* @__PURE__ */ number()).check(/* @__PURE__ */ _positive()))).check(describe$1("Seconds `portcall up` waits for the port. Default: 60."))
1648
+ });
1649
+ const configSchema = /* @__PURE__ */ strictObject({
1650
+ $schema: /* @__PURE__ */ optional(/* @__PURE__ */ string()),
1651
+ name: nameSchema.check(describe$1("Project name, used by `portcall -p <name>` and in the logs folder.")),
1652
+ services: (/* @__PURE__ */ record(nameSchema, serviceSchema)).check(describe$1("The project's services, by name."))
1653
+ });
1654
+ var ConfigError = class extends Error {};
1655
+ function findConfig(from) {
1656
+ let dir = resolve(from);
1657
+ for (;;) {
1658
+ const file = join(dir, CONFIG_FILE);
1659
+ if (existsSync(file)) return file;
1660
+ const parent = dirname(dir);
1661
+ if (parent === dir) return void 0;
1662
+ dir = parent;
1663
+ }
1664
+ }
1665
+ function loadProject(file) {
1666
+ let raw;
1667
+ try {
1668
+ raw = JSON.parse(readFileSync(file, "utf8"));
1669
+ } catch (error) {
1670
+ throw new ConfigError(`${file}: ${error.message}`);
1671
+ }
1672
+ return parseProject(raw, join(realpathSync(dirname(file)), basename(file)));
1673
+ }
1674
+ function parseProject(raw, file) {
1675
+ const parsed = configSchema.safeParse(raw);
1676
+ if (!parsed.success) throw new ConfigError(`${file}:\n${prettifyError(parsed.error)}`);
1677
+ const config = parsed.data;
1678
+ const root = dirname(file);
1679
+ const entries = Object.entries(config.services);
1680
+ if (entries.length === 0) throw new ConfigError(`${file}: "services" is empty`);
1681
+ const ports = /* @__PURE__ */ new Map();
1682
+ for (const [name, service] of entries) {
1683
+ const other = ports.get(service.port);
1684
+ if (other) throw new ConfigError(`${file}: services "${other}" and "${name}" both use port ${service.port}`);
1685
+ ports.set(service.port, name);
1686
+ }
1687
+ const services = entries.map(([name, service]) => ({
1688
+ name,
1689
+ port: service.port,
1690
+ command: service.command,
1691
+ cwd: resolve(root, service.cwd ?? "."),
1692
+ env: expandEnv(service.env ?? {}, service.port, ports, file, name),
1693
+ readyTimeout: service.readyTimeout ?? DEFAULT_READY_TIMEOUT
1694
+ }));
1695
+ return {
1696
+ name: config.name,
1697
+ root,
1698
+ file,
1699
+ services
1700
+ };
1701
+ }
1702
+ /** Fills `{port}` (this service) and `{ports.<service>}` (any service of the project). */
1703
+ function expandEnv(env, port, ports, file, service) {
1704
+ const byName = new Map([...ports].map(([p, name]) => [name, p]));
1705
+ const out = {};
1706
+ for (const [key, value] of Object.entries(env)) out[key] = value.replace(/\{(port|ports\.([\w.-]+))\}/g, (_, whole, other) => {
1707
+ if (whole === "port") return String(port);
1708
+ const found = byName.get(other);
1709
+ if (found === void 0) throw new ConfigError(`${file}: services.${service}.env.${key} refers to unknown service "${other}"`);
1710
+ return String(found);
1711
+ });
1712
+ return out;
1713
+ }
1714
+ // src/logs.ts
1715
+ const LINE = /^(\d{4}-\d\d-\d\dT[\d:.]+Z) \[(\w+)\] (.*)$/;
1716
+ const ERROR = /(?:error|exception)\b|\b(?:fatal|panic|unhandled|traceback|failed)\b|ERR!/i;
1717
+ const CONTINUATION = /^\s|^(?:caused by|\} )/i;
1718
+ const MAX_CONTINUATION = 40;
1719
+ const MAX_READ = 8388608;
1720
+ function parseLine(raw, service) {
1721
+ const match = LINE.exec(raw);
1722
+ if (!match) return {
1723
+ tag: "out",
1724
+ text: raw,
1725
+ service
1726
+ };
1727
+ return {
1728
+ time: new Date(match[1]),
1729
+ tag: match[2],
1730
+ text: match[3],
1731
+ service
1732
+ };
1733
+ }
1734
+ /** `30s`, `5m`, `2h`, `1d`, or anything `Date.parse` reads. Returns epoch ms. */
1735
+ function parseSince(value, now = Date.now()) {
1736
+ const match = /^(\d+)([smhd])$/.exec(value.trim());
1737
+ if (match) {
1738
+ const unit = {
1739
+ s: 1e3,
1740
+ m: 6e4,
1741
+ h: 36e5,
1742
+ d: 864e5
1743
+ }[match[2]];
1744
+ return now - Number(match[1]) * unit;
1745
+ }
1746
+ const time = Date.parse(value);
1747
+ if (Number.isNaN(time)) throw new Error(`--since: can't read "${value}" (try 30s, 5m, 2h or a date)`);
1748
+ return time;
1749
+ }
1750
+ function isError(line) {
1751
+ if (line.tag === "portcall") return /^exited with|^failed to start/.test(line.text);
1752
+ return ERROR.test(line.text);
1753
+ }
1754
+ function filterLines(lines, filter) {
1755
+ let out = lines;
1756
+ if (filter.since !== void 0) out = out.filter((line) => !line.time || line.time.getTime() >= filter.since);
1757
+ if (filter.errors) {
1758
+ const kept = [];
1759
+ for (let i = 0; i < out.length; i++) {
1760
+ if (!isError(out[i])) continue;
1761
+ kept.push(out[i]);
1762
+ let j = i + 1;
1763
+ while (j < out.length && j - i <= MAX_CONTINUATION && CONTINUATION.test(out[j].text) && !isError(out[j])) kept.push(out[j++]);
1764
+ i = j - 1;
1765
+ }
1766
+ out = kept;
1767
+ }
1768
+ if (filter.grep) out = out.filter((line) => filter.grep.test(line.text));
1769
+ if (filter.limit !== void 0) out = out.slice(-filter.limit);
1770
+ return out;
1771
+ }
1772
+ function readTail(file, maxBytes) {
1773
+ const size = statSync(file).size;
1774
+ const start = Math.max(0, size - maxBytes);
1775
+ const buffer = Buffer.alloc(size - start);
1776
+ const fd = openSync(file, "r");
1777
+ try {
1778
+ readSync(fd, buffer, 0, buffer.length, start);
1779
+ } finally {
1780
+ closeSync(fd);
1781
+ }
1782
+ const text = buffer.toString("utf8");
1783
+ return start > 0 ? text.slice(text.indexOf("\n") + 1) : text;
1784
+ }
1785
+ function readLog(file, service) {
1786
+ if (!existsSync(file)) return [];
1787
+ return readTail(file, MAX_READ).split("\n").filter(Boolean).map((raw) => parseLine(raw, service));
1788
+ }
1789
+ /** Several services' logs as one, in time order. */
1790
+ function mergeLogs(logs) {
1791
+ return logs.flat().sort((a, b) => (a.time?.getTime() ?? 0) - (b.time?.getTime() ?? 0));
1792
+ }
1793
+ function pad(n, width = 2) {
1794
+ return String(n).padStart(width, "0");
1795
+ }
1796
+ function formatLine(line, serviceWidth = 0) {
1797
+ return `${line.time ? `${pad(line.time.getHours())}:${pad(line.time.getMinutes())}:${pad(line.time.getSeconds())}.${pad(line.time.getMilliseconds(), 3)} ` : ""}${serviceWidth ? `${line.service.padEnd(serviceWidth)} ` : ""}${line.tag === "out" ? "" : `[${line.tag}] `}${line.text}`;
1798
+ }
1799
+ /** `tail -f` over several logs; a log that shrinks was rotated by a restart and is read again from its start. */
1800
+ async function followLogs(files, onLine, filter) {
1801
+ const offsets = files.map(({ file }) => existsSync(file) ? statSync(file).size : 0);
1802
+ const partial = files.map(() => "");
1803
+ for (;;) {
1804
+ for (const [i, { file, service }] of files.entries()) {
1805
+ if (!existsSync(file)) continue;
1806
+ const size = statSync(file).size;
1807
+ if (size < offsets[i]) {
1808
+ offsets[i] = 0;
1809
+ partial[i] = "";
1810
+ }
1811
+ if (size === offsets[i]) continue;
1812
+ const buffer = Buffer.alloc(size - offsets[i]);
1813
+ const fd = openSync(file, "r");
1814
+ try {
1815
+ readSync(fd, buffer, 0, buffer.length, offsets[i]);
1816
+ } finally {
1817
+ closeSync(fd);
1818
+ }
1819
+ offsets[i] = size;
1820
+ const chunks = (partial[i] + buffer.toString("utf8")).split("\n");
1821
+ partial[i] = chunks.pop();
1822
+ const lines = chunks.filter(Boolean).map((raw) => parseLine(raw, service));
1823
+ for (const line of filterLines(lines, {
1824
+ ...filter,
1825
+ limit: void 0,
1826
+ since: void 0
1827
+ })) onLine(line);
1828
+ }
1829
+ await setTimeout$1(250);
1830
+ }
1831
+ }
1832
+ // src/paths.ts
1833
+ function portcallHome() {
1834
+ return process.env.PORTCALL_HOME || join(homedir(), ".portcall");
1835
+ }
1836
+ function statePath() {
1837
+ return join(portcallHome(), "state.json");
1838
+ }
1839
+ function projectsPath() {
1840
+ return join(portcallHome(), "projects.json");
1841
+ }
1842
+ function logPath(project, service) {
1843
+ return join(portcallHome(), "logs", project, `${service}.log`);
1844
+ }
1845
+ // src/ports.ts
1846
+ const exec = promisify(execFile);
1847
+ function canConnect(host, port, timeoutMs) {
1848
+ return new Promise((resolve) => {
1849
+ const socket = connect({
1850
+ host,
1851
+ port
1852
+ });
1853
+ const done = (ok) => {
1854
+ socket.destroy();
1855
+ resolve(ok);
1856
+ };
1857
+ socket.setTimeout(timeoutMs, () => done(false));
1858
+ socket.once("connect", () => done(true));
1859
+ socket.once("error", () => done(false));
1860
+ });
1861
+ }
1862
+ /** Vite and friends often bind `::1` only, so both loopbacks are tried. */
1863
+ async function isListening(port, timeoutMs = 500) {
1864
+ return (await Promise.all(["127.0.0.1", "::1"].map((host) => canConnect(host, port, timeoutMs)))).some(Boolean);
1865
+ }
1866
+ /** Best effort: needs `lsof`, and only sees processes of the current user. */
1867
+ async function portHolder(port) {
1868
+ let stdout;
1869
+ try {
1870
+ ({stdout} = await exec("lsof", [
1871
+ "-nP",
1872
+ `-iTCP:${port}`,
1873
+ "-sTCP:LISTEN",
1874
+ "-t"
1875
+ ]));
1876
+ } catch {
1877
+ return;
1878
+ }
1879
+ const pid = Number(stdout.trim().split("\n")[0]);
1880
+ if (!pid) return void 0;
1881
+ const [command, cwd] = await Promise.all([processCommand(pid), processCwd(pid)]);
1882
+ return {
1883
+ pid,
1884
+ command,
1885
+ cwd
1886
+ };
1887
+ }
1888
+ async function processCommand(pid) {
1889
+ try {
1890
+ return (await exec("ps", [
1891
+ "-o",
1892
+ "command=",
1893
+ "-p",
1894
+ String(pid)
1895
+ ])).stdout.trim();
1896
+ } catch {
1897
+ return "";
1898
+ }
1899
+ }
1900
+ async function processCwd(pid) {
1901
+ try {
1902
+ if (process.platform === "linux") return await readlink(`/proc/${pid}/cwd`);
1903
+ const { stdout } = await exec("lsof", [
1904
+ "-a",
1905
+ "-p",
1906
+ String(pid),
1907
+ "-d",
1908
+ "cwd",
1909
+ "-Fn"
1910
+ ]);
1911
+ return stdout.split("\n").find((line) => line.startsWith("n"))?.slice(1);
1912
+ } catch {
1913
+ return;
1914
+ }
1915
+ }
1916
+ // src/proc.ts
1917
+ function isAlive(pid) {
1918
+ if (!pid) return false;
1919
+ try {
1920
+ process.kill(pid, 0);
1921
+ return true;
1922
+ } catch (error) {
1923
+ return error.code === "EPERM";
1924
+ }
1925
+ }
1926
+ function signal(pid, sig) {
1927
+ if (!pid) return;
1928
+ try {
1929
+ process.kill(pid, sig);
1930
+ } catch {}
1931
+ }
1932
+ /** Signals the whole process group led by `pid`: `pnpm dev` spawns its own children. */
1933
+ function signalGroup(pid, sig) {
1934
+ if (pid) signal(-pid, sig);
1935
+ }
1936
+ async function waitForDeath(pid, timeoutMs) {
1937
+ const deadline = Date.now() + timeoutMs;
1938
+ while (isAlive(pid)) {
1939
+ if (Date.now() > deadline) return false;
1940
+ await setTimeout$1(50);
1941
+ }
1942
+ return true;
1943
+ }
1944
+ // src/state.ts
1945
+ const LOCK_WAIT_MS = 5e3;
1946
+ const STALE_LOCK_MS = 1e4;
1947
+ function recordKey(project, service) {
1948
+ return `${project}/${service}`;
1949
+ }
1950
+ function readState() {
1951
+ try {
1952
+ const state = JSON.parse(readFileSync(statePath(), "utf8"));
1953
+ if (state && typeof state.services === "object") return state;
1954
+ } catch {}
1955
+ return { services: {} };
1956
+ }
1957
+ async function updateState(fn) {
1958
+ return withLock(() => {
1959
+ const state = readState();
1960
+ const result = fn(state);
1961
+ writeJson(statePath(), state);
1962
+ return result;
1963
+ });
1964
+ }
1965
+ function writeJson(file, value) {
1966
+ mkdirSync(portcallHome(), { recursive: true });
1967
+ const tmp = `${file}.${process.pid}.tmp`;
1968
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`);
1969
+ renameSync(tmp, file);
1970
+ }
1971
+ async function withLock(fn) {
1972
+ mkdirSync(portcallHome(), { recursive: true });
1973
+ const lock = join(portcallHome(), "state.lock");
1974
+ const deadline = Date.now() + LOCK_WAIT_MS;
1975
+ for (;;) try {
1976
+ closeSync(openSync(lock, "wx"));
1977
+ break;
1978
+ } catch (error) {
1979
+ if (error.code !== "EEXIST") throw error;
1980
+ try {
1981
+ if (Date.now() - statSync(lock).mtimeMs > STALE_LOCK_MS) unlinkSync(lock);
1982
+ } catch {}
1983
+ if (Date.now() > deadline) throw new Error(`state is locked (${lock}); delete it if no portcall command is running`);
1984
+ await setTimeout$1(20);
1985
+ }
1986
+ try {
1987
+ return fn();
1988
+ } finally {
1989
+ try {
1990
+ unlinkSync(lock);
1991
+ } catch {}
1992
+ }
1993
+ }
1994
+ function readRoots() {
1995
+ try {
1996
+ const roots = JSON.parse(readFileSync(projectsPath(), "utf8"));
1997
+ if (Array.isArray(roots)) return roots.filter((r) => typeof r === "string");
1998
+ } catch {}
1999
+ return [];
2000
+ }
2001
+ /** Remembers a project so `status --all`, `ports` and `--project` find it from anywhere. */
2002
+ function rememberProject(root) {
2003
+ const roots = readRoots();
2004
+ if (!roots.includes(root)) writeJson(projectsPath(), [...roots, root].sort());
2005
+ }
2006
+ function knownProjects() {
2007
+ const projects = [];
2008
+ const errors = [];
2009
+ const kept = [];
2010
+ const roots = readRoots();
2011
+ for (const root of roots) {
2012
+ const file = join(root, CONFIG_FILE);
2013
+ if (!existsSync(file)) continue;
2014
+ kept.push(root);
2015
+ try {
2016
+ projects.push(loadProject(file));
2017
+ } catch (error) {
2018
+ errors.push(error.message);
2019
+ }
2020
+ }
2021
+ if (kept.length !== roots.length) writeJson(projectsPath(), kept);
2022
+ return {
2023
+ projects,
2024
+ errors
2025
+ };
2026
+ }
2027
+ // src/status.ts
2028
+ function inside(dir, root) {
2029
+ return !!dir && (dir === root || dir.startsWith(root + sep));
2030
+ }
2031
+ async function serviceStatus(project, service, state) {
2032
+ const base = {
2033
+ project: project.name,
2034
+ service: service.name,
2035
+ port: service.port,
2036
+ url: `http://localhost:${service.port}`,
2037
+ external: !service.command
2038
+ };
2039
+ const record = state.services[recordKey(project.name, service.name)];
2040
+ if (record) {
2041
+ const alive = isAlive(record.supervisorPid) || isAlive(record.childPid);
2042
+ const managed = {
2043
+ pid: record.childPid ?? record.supervisorPid,
2044
+ startedAt: record.startedAt,
2045
+ log: record.log
2046
+ };
2047
+ if (record.root !== project.root && alive) return {
2048
+ ...base,
2049
+ ...managed,
2050
+ state: "elsewhere",
2051
+ root: record.root
2052
+ };
2053
+ if (record.exitedAt || !alive) return {
2054
+ ...base,
2055
+ ...managed,
2056
+ state: "crashed",
2057
+ exitCode: record.exitCode,
2058
+ exitSignal: record.exitSignal
2059
+ };
2060
+ return {
2061
+ ...base,
2062
+ ...managed,
2063
+ state: await isListening(service.port) ? "running" : "starting"
2064
+ };
2065
+ }
2066
+ const log = service.command ? logPath(project.name, service.name) : void 0;
2067
+ if (!await isListening(service.port)) return {
2068
+ ...base,
2069
+ log,
2070
+ state: "stopped"
2071
+ };
2072
+ if (base.external) return {
2073
+ ...base,
2074
+ state: "running"
2075
+ };
2076
+ const holder = await portHolder(service.port);
2077
+ return {
2078
+ ...base,
2079
+ log,
2080
+ holder,
2081
+ pid: holder?.pid,
2082
+ state: inside(holder?.cwd, project.root) ? "unmanaged" : "taken"
2083
+ };
2084
+ }
2085
+ async function projectStatus(project, state, only) {
2086
+ return Promise.all((only ?? project.services).map((service) => serviceStatus(project, service, state)));
2087
+ }
2088
+ // src/commands.ts
2089
+ const SUPERVISE_COMMAND = "__supervise";
2090
+ const STOP_WAIT_MS = 8e3;
2091
+ var UsageError = class extends Error {};
2092
+ function resolveProject(cwd, name) {
2093
+ if (name) {
2094
+ const { projects } = knownProjects();
2095
+ const matches = projects.filter((project) => project.name === name);
2096
+ if (matches.length === 0) throw new UsageError(`unknown project "${name}": run any portcall command once inside it so portcall knows where it is`);
2097
+ const here = matches.find((project) => cwd === project.root || cwd.startsWith(`${project.root}/`));
2098
+ if (here || matches.length === 1) return here ?? matches[0];
2099
+ throw new UsageError(`"${name}" exists in several checkouts, run portcall from the one you want:\n${matches.map((p) => ` ${p.root}`).join("\n")}`);
2100
+ }
2101
+ const file = findConfig(cwd);
2102
+ if (!file) throw new ConfigError(`no portcall.json in ${cwd} or above (see \`portcall help\`)`);
2103
+ const project = loadProject(file);
2104
+ rememberProject(project.root);
2105
+ return project;
2106
+ }
2107
+ function selectServices(project, names, runnableOnly = false) {
2108
+ if (names.length === 0) return runnableOnly ? project.services.filter((s) => s.command) : project.services;
2109
+ return names.map((name) => {
2110
+ const service = project.services.find((s) => s.name === name);
2111
+ if (!service) throw new UsageError(`${project.name} has no service "${name}" (services: ${project.services.map((s) => s.name).join(", ")})`);
2112
+ if (runnableOnly && !service.command) throw new UsageError(`${project.name}/${name} is external (no command): portcall only checks its port`);
2113
+ return service;
2114
+ });
2115
+ }
2116
+ function table(rows) {
2117
+ const widths = rows[0].map((_, i) => Math.max(...rows.map((row) => row[i].length)));
2118
+ return rows.map((row) => row.map((cell, i) => cell.padEnd(widths[i])).join(" ").trimEnd()).join("\n");
2119
+ }
2120
+ function duration(ms) {
2121
+ const s = Math.floor(ms / 1e3);
2122
+ if (s < 60) return `${s}s`;
2123
+ if (s < 3600) return `${Math.floor(s / 60)}m`;
2124
+ if (s < 86400) return `${Math.floor(s / 3600)}h${String(Math.floor(s % 3600 / 60)).padStart(2, "0")}`;
2125
+ return `${Math.floor(s / 86400)}d`;
2126
+ }
2127
+ function short(text, max = 60) {
2128
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
2129
+ }
2130
+ function describe(status) {
2131
+ switch (status.state) {
2132
+ case "crashed": return status.exitSignal ? `killed by ${status.exitSignal}` : `exit code ${status.exitCode ?? "?"}`;
2133
+ case "unmanaged": return `started outside portcall: ${short(status.holder?.command ?? "?")}`;
2134
+ case "taken": return `port held by ${status.holder ? `${short(status.holder.command)} (${status.holder.cwd ?? "?"})` : "another process"}`;
2135
+ case "elsewhere": return `run from ${status.root}`;
2136
+ default: return status.external ? "external" : "";
2137
+ }
2138
+ }
2139
+ function statusRows(statuses, withProject) {
2140
+ const head = [
2141
+ ...withProject ? ["PROJECT"] : [],
2142
+ "SERVICE",
2143
+ "STATE",
2144
+ "PORT",
2145
+ "PID",
2146
+ "UPTIME",
2147
+ "INFO"
2148
+ ];
2149
+ const now = Date.now();
2150
+ return [head, ...statuses.map((s) => [
2151
+ ...withProject ? [s.project] : [],
2152
+ s.service,
2153
+ s.state,
2154
+ String(s.port),
2155
+ s.pid ? String(s.pid) : "-",
2156
+ s.startedAt && (s.state === "running" || s.state === "starting") ? duration(now - s.startedAt) : "-",
2157
+ describe(s)
2158
+ ])];
2159
+ }
2160
+ async function status(io, cwd, opts) {
2161
+ const state = readState();
2162
+ if (opts.all) {
2163
+ const { projects, errors } = knownProjects();
2164
+ const statuses = (await Promise.all(projects.map((p) => projectStatus(p, state)))).flat();
2165
+ if (io.json) io.out(JSON.stringify({
2166
+ services: statuses,
2167
+ errors
2168
+ }, null, 2));
2169
+ else {
2170
+ io.out(statuses.length ? table(statusRows(statuses, true)) : "no known projects yet: run portcall once inside a project");
2171
+ errors.forEach((e) => io.err(`portcall: ${e}`));
2172
+ }
2173
+ return 0;
2174
+ }
2175
+ const project = resolveProject(cwd, opts.project);
2176
+ const statuses = await projectStatus(project, state);
2177
+ io.out(io.json ? JSON.stringify({
2178
+ project: project.name,
2179
+ root: project.root,
2180
+ services: statuses
2181
+ }, null, 2) : table(statusRows(statuses, false)));
2182
+ return 0;
2183
+ }
2184
+ const UP_FAILURES = [
2185
+ "crashed",
2186
+ "timeout",
2187
+ "blocked"
2188
+ ];
2189
+ function startService(project, service, state) {
2190
+ const log = logPath(project.name, service.name);
2191
+ const spec = {
2192
+ project: project.name,
2193
+ service: service.name,
2194
+ command: service.command,
2195
+ cwd: service.cwd,
2196
+ env: {
2197
+ PORT: String(service.port),
2198
+ ...service.env
2199
+ },
2200
+ log
2201
+ };
2202
+ const child = spawn(process.execPath, [
2203
+ ...process.execArgv,
2204
+ process.argv[1],
2205
+ SUPERVISE_COMMAND,
2206
+ JSON.stringify(spec)
2207
+ ], {
2208
+ cwd: service.cwd,
2209
+ detached: true,
2210
+ stdio: "ignore"
2211
+ });
2212
+ if (!child.pid) throw new Error(`could not start the supervisor for ${service.name}`);
2213
+ let exited = false;
2214
+ child.once("exit", () => {
2215
+ exited = true;
2216
+ });
2217
+ child.unref();
2218
+ state.services[recordKey(project.name, service.name)] = {
2219
+ project: project.name,
2220
+ service: service.name,
2221
+ root: project.root,
2222
+ port: service.port,
2223
+ command: service.command,
2224
+ supervisorPid: child.pid,
2225
+ startedAt: Date.now(),
2226
+ log
2227
+ };
2228
+ return {
2229
+ pid: child.pid,
2230
+ exited: () => exited
2231
+ };
2232
+ }
2233
+ async function waitReady(service, exited) {
2234
+ const deadline = Date.now() + service.readyTimeout * 1e3;
2235
+ for (;;) {
2236
+ if (exited()) return "exited";
2237
+ if (await isListening(service.port, 300)) return "ready";
2238
+ if (Date.now() > deadline) return "timeout";
2239
+ await setTimeout$1(200);
2240
+ }
2241
+ }
2242
+ async function up(io, cwd, names, opts) {
2243
+ const project = resolveProject(cwd, opts.project);
2244
+ const services = selectServices(project, names);
2245
+ const statuses = await projectStatus(project, readState(), services);
2246
+ const results = [];
2247
+ const toStart = [];
2248
+ for (const [i, st] of statuses.entries()) {
2249
+ const base = {
2250
+ service: st.service,
2251
+ port: st.port,
2252
+ url: st.url
2253
+ };
2254
+ switch (st.state) {
2255
+ case "running":
2256
+ case "starting":
2257
+ results.push({
2258
+ ...base,
2259
+ outcome: st.external ? "external-up" : "already-running",
2260
+ pid: st.pid
2261
+ });
2262
+ break;
2263
+ case "unmanaged":
2264
+ results.push({
2265
+ ...base,
2266
+ outcome: "running-outside",
2267
+ pid: st.pid,
2268
+ detail: describe(st)
2269
+ });
2270
+ break;
2271
+ case "elsewhere":
2272
+ case "taken":
2273
+ results.push({
2274
+ ...base,
2275
+ outcome: "blocked",
2276
+ pid: st.pid,
2277
+ detail: describe(st)
2278
+ });
2279
+ break;
2280
+ case "stopped":
2281
+ case "crashed": if (st.external) results.push({
2282
+ ...base,
2283
+ outcome: "external-down",
2284
+ detail: "nothing listens on this port; portcall does not start external services"
2285
+ });
2286
+ else toStart.push(services[i]);
2287
+ }
2288
+ }
2289
+ const started = await updateState((state) => toStart.map((service) => ({
2290
+ service,
2291
+ ...startService(project, service, state)
2292
+ })));
2293
+ results.push(...await Promise.all(started.map(async ({ service, pid, exited }) => {
2294
+ const base = {
2295
+ service: service.name,
2296
+ port: service.port,
2297
+ url: `http://localhost:${service.port}`,
2298
+ pid
2299
+ };
2300
+ if (!opts.wait) return {
2301
+ ...base,
2302
+ outcome: "started",
2303
+ detail: "not waiting for the port"
2304
+ };
2305
+ const t0 = Date.now();
2306
+ const ready = await waitReady(service, exited);
2307
+ if (ready === "ready") return {
2308
+ ...base,
2309
+ outcome: "started",
2310
+ detail: `ready in ${((Date.now() - t0) / 1e3).toFixed(1)}s`
2311
+ };
2312
+ const logTail = readLog(logPath(project.name, service.name), service.name).slice(-30).map((l) => formatLine(l));
2313
+ if (ready === "exited") {
2314
+ const record = readState().services[recordKey(project.name, service.name)];
2315
+ return {
2316
+ ...base,
2317
+ outcome: "crashed",
2318
+ detail: `exited before listening (code ${record?.exitCode ?? "?"})`,
2319
+ logTail
2320
+ };
2321
+ }
2322
+ return {
2323
+ ...base,
2324
+ outcome: "timeout",
2325
+ detail: `still running but nothing listens on ${service.port} after ${service.readyTimeout}s (wrong port in portcall.json?)`,
2326
+ logTail
2327
+ };
2328
+ })));
2329
+ const order = new Map(services.map((s, i) => [s.name, i]));
2330
+ results.sort((a, b) => order.get(a.service) - order.get(b.service));
2331
+ const failed = results.some((r) => UP_FAILURES.includes(r.outcome));
2332
+ if (io.json) io.out(JSON.stringify({
2333
+ project: project.name,
2334
+ ok: !failed,
2335
+ services: results
2336
+ }, null, 2));
2337
+ else {
2338
+ io.out(table([[
2339
+ "SERVICE",
2340
+ "RESULT",
2341
+ "URL",
2342
+ "PID",
2343
+ "INFO"
2344
+ ], ...results.map((r) => [
2345
+ r.service,
2346
+ r.outcome,
2347
+ r.url,
2348
+ r.pid ? String(r.pid) : "-",
2349
+ r.detail ?? ""
2350
+ ])]));
2351
+ for (const r of results.filter((r) => r.logTail?.length)) io.out(`\n--- ${r.service}: last log lines (portcall logs ${r.service}) ---\n${r.logTail.join("\n")}`);
2352
+ }
2353
+ return failed ? 1 : 0;
2354
+ }
2355
+ async function stopRecord(record) {
2356
+ if (!record.exitedAt) {
2357
+ signal(record.supervisorPid, "SIGTERM");
2358
+ if (!await waitForDeath(record.supervisorPid, STOP_WAIT_MS)) signal(record.supervisorPid, "SIGKILL");
2359
+ if (isAlive(record.childPid)) {
2360
+ signalGroup(record.childPid, "SIGTERM");
2361
+ if (!await waitForDeath(record.childPid, 3e3)) signalGroup(record.childPid, "SIGKILL");
2362
+ }
2363
+ }
2364
+ await updateState((state) => {
2365
+ const key = recordKey(record.project, record.service);
2366
+ if (state.services[key]?.supervisorPid === record.supervisorPid) delete state.services[key];
2367
+ });
2368
+ }
2369
+ async function stopPid(pid) {
2370
+ signal(pid, "SIGTERM");
2371
+ if (!await waitForDeath(pid, STOP_WAIT_MS)) signal(pid, "SIGKILL");
2372
+ }
2373
+ async function down(io, cwd, names, opts) {
2374
+ const project = resolveProject(cwd, opts.project);
2375
+ const services = selectServices(project, names);
2376
+ const state = readState();
2377
+ const statuses = await projectStatus(project, state, services);
2378
+ const results = await Promise.all(statuses.map(async (st) => {
2379
+ const record = state.services[recordKey(project.name, st.service)];
2380
+ if (st.external) return {
2381
+ service: st.service,
2382
+ outcome: "skipped",
2383
+ detail: "external, not managed by portcall"
2384
+ };
2385
+ switch (st.state) {
2386
+ case "running":
2387
+ case "starting":
2388
+ case "crashed":
2389
+ await stopRecord(record);
2390
+ return {
2391
+ service: st.service,
2392
+ outcome: "stopped"
2393
+ };
2394
+ case "elsewhere":
2395
+ if (!opts.force) return {
2396
+ service: st.service,
2397
+ outcome: "skipped",
2398
+ detail: `${describe(st)}; --force to stop it from here`
2399
+ };
2400
+ await stopRecord(record);
2401
+ return {
2402
+ service: st.service,
2403
+ outcome: "stopped",
2404
+ detail: describe(st)
2405
+ };
2406
+ case "unmanaged":
2407
+ if (!opts.force) return {
2408
+ service: st.service,
2409
+ outcome: "skipped",
2410
+ detail: `${describe(st)} (pid ${st.pid}); --force to stop it`
2411
+ };
2412
+ await stopPid(st.pid);
2413
+ return {
2414
+ service: st.service,
2415
+ outcome: "stopped",
2416
+ detail: describe(st)
2417
+ };
2418
+ case "taken": return {
2419
+ service: st.service,
2420
+ outcome: "skipped",
2421
+ detail: `${describe(st)}; not part of this project, portcall leaves it alone`
2422
+ };
2423
+ case "stopped": return {
2424
+ service: st.service,
2425
+ outcome: "not-running"
2426
+ };
2427
+ }
2428
+ }));
2429
+ if (!opts.quiet) {
2430
+ if (io.json) io.out(JSON.stringify({
2431
+ project: project.name,
2432
+ services: results
2433
+ }, null, 2));
2434
+ else io.out(table([[
2435
+ "SERVICE",
2436
+ "RESULT",
2437
+ "INFO"
2438
+ ], ...results.map((r) => [
2439
+ r.service,
2440
+ r.outcome,
2441
+ r.detail ?? ""
2442
+ ])]));
2443
+ }
2444
+ return 0;
2445
+ }
2446
+ async function restart(io, cwd, names, opts) {
2447
+ const runnable = selectServices(resolveProject(cwd, opts.project), names, true).map((s) => s.name);
2448
+ await down(io, cwd, runnable, {
2449
+ ...opts,
2450
+ quiet: true
2451
+ });
2452
+ return up(io, cwd, runnable, opts);
2453
+ }
2454
+ async function logs(io, cwd, names, opts) {
2455
+ const project = resolveProject(cwd, opts.project);
2456
+ const services = selectServices(project, names, true);
2457
+ const files = services.map((s) => ({
2458
+ file: logPath(project.name, s.name),
2459
+ service: s.name
2460
+ }));
2461
+ const width = services.length > 1 ? Math.max(...services.map((s) => s.name.length)) : 0;
2462
+ const lines = filterLines(mergeLogs(files.map((f) => readLog(f.file, f.service))), opts.filter);
2463
+ const toJson = (l) => ({
2464
+ time: l.time?.toISOString(),
2465
+ service: l.service,
2466
+ stream: l.tag,
2467
+ text: l.text
2468
+ });
2469
+ if (io.json && !opts.follow) io.out(JSON.stringify({
2470
+ project: project.name,
2471
+ lines: lines.map(toJson)
2472
+ }, null, 2));
2473
+ else if (lines.length) lines.forEach((l) => io.out(io.json ? JSON.stringify(toJson(l)) : formatLine(l, width)));
2474
+ else if (!opts.follow) io.out(files.some((f) => readLog(f.file, f.service).length) ? "(no matching lines)" : "(no logs yet: start it with `portcall up`)");
2475
+ if (opts.follow) await followLogs(files, (l) => io.out(io.json ? JSON.stringify(toJson(l)) : formatLine(l, width)), opts.filter);
2476
+ return 0;
2477
+ }
2478
+ async function ports(io, cwd) {
2479
+ const file = findConfig(cwd);
2480
+ if (file) rememberProject(loadProject(file).root);
2481
+ const { projects, errors } = knownProjects();
2482
+ const state = readState();
2483
+ const claims = /* @__PURE__ */ new Map();
2484
+ for (const project of projects) for (const service of project.services) claims.set(service.port, (claims.get(service.port) ?? /* @__PURE__ */ new Set()).add(project.name));
2485
+ const seen = /* @__PURE__ */ new Set();
2486
+ const rows = [];
2487
+ for (const project of projects) {
2488
+ if (seen.has(project.name)) continue;
2489
+ seen.add(project.name);
2490
+ for (const st of await projectStatus(project, state)) {
2491
+ const others = [...claims.get(st.port)].filter((name) => name !== project.name);
2492
+ rows.push({
2493
+ ...st,
2494
+ conflict: others
2495
+ });
2496
+ }
2497
+ }
2498
+ rows.sort((a, b) => a.port - b.port);
2499
+ if (io.json) io.out(JSON.stringify({
2500
+ ports: rows,
2501
+ errors
2502
+ }, null, 2));
2503
+ else {
2504
+ io.out(rows.length ? table([[
2505
+ "PORT",
2506
+ "PROJECT",
2507
+ "SERVICE",
2508
+ "STATE",
2509
+ "INFO"
2510
+ ], ...rows.map((r) => [
2511
+ String(r.port),
2512
+ r.project,
2513
+ r.service,
2514
+ r.state,
2515
+ [r.conflict.length ? `CONFLICT with ${r.conflict.join(", ")}` : "", describe(r)].filter(Boolean).join("; ")
2516
+ ])]) : "no known projects yet: run portcall once inside a project");
2517
+ errors.forEach((e) => io.err(`portcall: ${e}`));
2518
+ }
2519
+ return rows.some((r) => r.conflict.length) ? 1 : 0;
2520
+ }
2521
+ const AGENTS_SNIPPET = `## Dev servers
2522
+
2523
+ Dev servers run under portcall (config: \`portcall.json\`). Never start them yourself (no \`pnpm dev\`, \`vite\`, \`tsx watch\`, \`node --watch\`...).
2524
+
2525
+ - \`portcall status\`: what runs, on which port. Check it before assuming a server is down.
2526
+ - \`portcall up [service]\`: start what is not running; a no-op for what already is. It waits for the port and prints the log tail if the server crashes.
2527
+ - \`portcall restart <service>\`: after changing env, config or dependencies (watch mode reloads code by itself).
2528
+ - \`portcall logs <service> --errors\`, \`--since 2m\`, \`--grep <regex>\`, \`-n 200\`: server output, e.g. after a failing request.
2529
+ - Leave servers running when you are done. Add \`--json\` to any command for machine-readable output.
2530
+ `;
2531
+ function agents(io) {
2532
+ io.out(AGENTS_SNIPPET.trimEnd());
2533
+ return 0;
2534
+ }
2535
+ // src/supervise.ts
2536
+ const KILL_AFTER_MS = 5e3;
2537
+ const CLOSE_GRACE_MS = 3e3;
2538
+ const ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
2539
+ /** Plain text for the log: no escape codes, and a progress bar (`\r` rewrites) kept at its last state. */
2540
+ function cleanLine(line) {
2541
+ const text = line.replace(ANSI, "");
2542
+ return text.slice(text.lastIndexOf("\r") + 1).trimEnd();
2543
+ }
2544
+ /**
2545
+ * Runs in its own detached process, one per service: starts the command in a
2546
+ * new process group, timestamps its output into the log, records how it ended.
2547
+ */
2548
+ function supervise(spec) {
2549
+ const key = recordKey(spec.project, spec.service);
2550
+ mkdirSync(dirname(spec.log), { recursive: true });
2551
+ if (existsSync(spec.log)) renameSync(spec.log, `${spec.log}.1`);
2552
+ const out = createWriteStream(spec.log, { flags: "a" });
2553
+ const write = (tag, text) => {
2554
+ out.write(`${(/* @__PURE__ */ new Date()).toISOString()} [${tag}] ${text}\n`);
2555
+ };
2556
+ write("portcall", `$ ${spec.command}`);
2557
+ const child = spawn("/bin/sh", ["-c", spec.command], {
2558
+ cwd: spec.cwd,
2559
+ env: {
2560
+ ...process.env,
2561
+ ...spec.env
2562
+ },
2563
+ detached: true,
2564
+ stdio: [
2565
+ "ignore",
2566
+ "pipe",
2567
+ "pipe"
2568
+ ]
2569
+ });
2570
+ for (const [stream, tag] of [[child.stdout, "out"], [child.stderr, "err"]]) createInterface({
2571
+ input: stream,
2572
+ crlfDelay: 1e400
2573
+ }).on("line", (line) => {
2574
+ const text = cleanLine(line);
2575
+ if (text) write(tag, text);
2576
+ });
2577
+ updateState((state) => {
2578
+ const record = state.services[key];
2579
+ if (record?.supervisorPid === process.pid) record.childPid = child.pid;
2580
+ });
2581
+ let stopping = false;
2582
+ const stop = () => {
2583
+ if (stopping) return;
2584
+ stopping = true;
2585
+ write("portcall", "stopping");
2586
+ signalGroup(child.pid, "SIGTERM");
2587
+ setTimeout(signalGroup, KILL_AFTER_MS, child.pid, "SIGKILL").unref();
2588
+ };
2589
+ process.on("SIGTERM", stop);
2590
+ process.on("SIGINT", stop);
2591
+ process.on("SIGHUP", () => {});
2592
+ let finished = false;
2593
+ const finish = async (code, sig) => {
2594
+ if (finished) return;
2595
+ finished = true;
2596
+ write("portcall", stopping ? "stopped" : `exited with ${sig ? `signal ${sig}` : `code ${code}`}`);
2597
+ try {
2598
+ await updateState((state) => {
2599
+ const record = state.services[key];
2600
+ if (record?.supervisorPid !== process.pid) return;
2601
+ if (stopping) delete state.services[key];
2602
+ else Object.assign(record, {
2603
+ exitCode: code,
2604
+ exitSignal: sig,
2605
+ exitedAt: Date.now()
2606
+ });
2607
+ });
2608
+ } finally {
2609
+ out.end(() => process.exit(0));
2610
+ }
2611
+ };
2612
+ child.on("error", (error) => {
2613
+ write("portcall", `failed to start: ${error.message}`);
2614
+ finish(127, null);
2615
+ });
2616
+ child.on("exit", (code, sig) => {
2617
+ signalGroup(child.pid, "SIGTERM");
2618
+ setTimeout(() => void finish(code, sig), CLOSE_GRACE_MS).unref();
2619
+ child.on("close", () => void finish(code, sig));
2620
+ });
2621
+ }
2622
+ // src/cli.ts
2623
+ const USAGE = `portcall - run your dev servers in the background, on fixed ports, with logs agents can read
2624
+
2625
+ Usage:
2626
+ portcall up [service...] Start services (no-op for the ones already running), wait for their port
2627
+ portcall down [service...] Stop services
2628
+ portcall restart [service...] Stop then start
2629
+ portcall status [--all] What runs, on which port (--all: every project portcall knows)
2630
+ portcall logs [service...] Service output (all services when none named)
2631
+ portcall ports Every known project's ports, with conflicts
2632
+ portcall agents Print an AGENTS.md section telling coding agents how to use portcall
2633
+
2634
+ Options:
2635
+ -p, --project <name> Act on a known project from anywhere (default: the portcall.json at or above the cwd)
2636
+ -C, --cwd <dir> Run as if started in <dir>
2637
+ --json Machine-readable output
2638
+ --no-wait up/restart: return without waiting for the port
2639
+ --force down/restart: also stop a server of this project started outside portcall
2640
+ -h, --help This help
2641
+ -v, --version Print the version
2642
+
2643
+ Logs:
2644
+ -n, --lines <n> Last n lines (default 100)
2645
+ --since <time> Only lines after 30s, 5m, 2h, 1d or a date
2646
+ --grep <regex> Only lines matching (case-insensitive)
2647
+ --errors Only error lines, with their stack traces
2648
+ -f, --follow Keep printing new lines
2649
+
2650
+ portcall.json, at the project root:
2651
+ {
2652
+ "name": "myapp",
2653
+ "services": {
2654
+ "server": { "command": "pnpm dev:server", "port": 3000 },
2655
+ "web": { "command": "pnpm dev:web", "port": 5173, "env": { "API_URL": "http://localhost:{ports.server}" } },
2656
+ "db": { "port": 5432 }
2657
+ }
2658
+ }
2659
+ A service without "command" is external (a database in Docker...): portcall only checks its port.
2660
+ Each command gets PORT set to its port. Logs and state live in ~/.portcall (PORTCALL_HOME).
2661
+ `;
2662
+ async function main(argv) {
2663
+ if (argv[0] === "__supervise") {
2664
+ supervise(JSON.parse(argv[1]));
2665
+ return -1;
2666
+ }
2667
+ const { values, positionals } = parseArgs({
2668
+ args: argv,
2669
+ allowPositionals: true,
2670
+ options: {
2671
+ "project": {
2672
+ type: "string",
2673
+ short: "p"
2674
+ },
2675
+ "cwd": {
2676
+ type: "string",
2677
+ short: "C"
2678
+ },
2679
+ "json": { type: "boolean" },
2680
+ "all": {
2681
+ type: "boolean",
2682
+ short: "a"
2683
+ },
2684
+ "no-wait": { type: "boolean" },
2685
+ "force": { type: "boolean" },
2686
+ "lines": {
2687
+ type: "string",
2688
+ short: "n"
2689
+ },
2690
+ "since": { type: "string" },
2691
+ "grep": { type: "string" },
2692
+ "errors": { type: "boolean" },
2693
+ "follow": {
2694
+ type: "boolean",
2695
+ short: "f"
2696
+ },
2697
+ "help": {
2698
+ type: "boolean",
2699
+ short: "h"
2700
+ },
2701
+ "version": {
2702
+ type: "boolean",
2703
+ short: "v"
2704
+ }
2705
+ }
2706
+ });
2707
+ const io = {
2708
+ json: !!values.json,
2709
+ out: (text) => process.stdout.write(`${text}\n`),
2710
+ err: (text) => process.stderr.write(`${text}\n`)
2711
+ };
2712
+ if (values.version) {
2713
+ io.out(version$1);
2714
+ return 0;
2715
+ }
2716
+ const [command = "help", ...names] = positionals;
2717
+ if (values.help || command === "help") {
2718
+ io.out(USAGE.trimEnd());
2719
+ return 0;
2720
+ }
2721
+ const cwd = resolve(values.cwd ?? process.cwd());
2722
+ const project = values.project;
2723
+ const wait = !values["no-wait"];
2724
+ switch (command) {
2725
+ case "up":
2726
+ case "start": return up(io, cwd, names, {
2727
+ project,
2728
+ wait
2729
+ });
2730
+ case "down":
2731
+ case "stop": return down(io, cwd, names, {
2732
+ project,
2733
+ force: values.force
2734
+ });
2735
+ case "restart": return restart(io, cwd, names, {
2736
+ project,
2737
+ force: values.force,
2738
+ wait
2739
+ });
2740
+ case "status":
2741
+ case "ps": return status(io, cwd, {
2742
+ project,
2743
+ all: values.all
2744
+ });
2745
+ case "logs": {
2746
+ const lines = values.lines === void 0 ? 100 : Number(values.lines);
2747
+ if (!Number.isInteger(lines) || lines < 1) throw new Error(`--lines: expected a positive number, got "${values.lines}"`);
2748
+ let grep;
2749
+ try {
2750
+ grep = values.grep === void 0 ? void 0 : new RegExp(values.grep, "i");
2751
+ } catch {
2752
+ throw new Error(`--grep: invalid regular expression "${values.grep}"`);
2753
+ }
2754
+ return logs(io, cwd, names, {
2755
+ project,
2756
+ follow: values.follow,
2757
+ filter: {
2758
+ limit: lines,
2759
+ since: values.since === void 0 ? void 0 : parseSince(values.since),
2760
+ grep,
2761
+ errors: values.errors
2762
+ }
2763
+ });
2764
+ }
2765
+ case "ports": return ports(io, cwd);
2766
+ case "agents": return agents(io);
2767
+ default: throw new Error(`unknown command "${command}" (see \`portcall help\`)`);
2768
+ }
2769
+ }
2770
+ main(process.argv.slice(2)).then((code) => {
2771
+ if (code >= 0) process.exitCode = code;
2772
+ }, (error) => {
2773
+ if (process.argv.includes("--json")) process.stdout.write(`${JSON.stringify({ error: error.message })}\n`);
2774
+ else process.stderr.write(`portcall: ${error.message}\n`);
2775
+ process.exitCode = 1;
2776
+ });
2777
+ export {};