@kaynooo/cli-wt 0.1.1 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,25 +1,36 @@
1
1
  #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
2
  // @bun
3
+ var __esm = (fn, res, err) => () => {
4
+ if (fn)
5
+ try {
6
+ res = fn(fn = 0);
7
+ } catch (e) {
8
+ err = [e];
9
+ }
10
+ if (err)
11
+ throw err[0];
12
+ return res;
13
+ };
3
14
 
4
- // src/cli.ts
5
- import process11 from "process";
6
- // ../kit/src/args.ts
7
- import process5 from "process";
8
- import { parseArgs } from "util";
9
-
10
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
11
- var ot = /[.*+?^${}()|[\]\\]/g;
12
- function B(t) {
15
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rkhsft4a.js
16
+ function U(t) {
13
17
  return t.replace(ot, "\\$&");
14
18
  }
15
- var N = new Map;
16
- var be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
17
- var z = new Map;
19
+ var ot, N, be, W;
20
+ var init_chunk_rkhsft4a = __esm(() => {
21
+ ot = /[.*+?^${}()|[\]\\]/g;
22
+ N = new Map;
23
+ be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
24
+ W = new Map;
25
+ });
26
+
27
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
28
+ var init_text = __esm(() => {
29
+ init_chunk_rkhsft4a();
30
+ });
18
31
 
19
32
  // ../kit/src/mode.ts
20
33
  import process2 from "process";
21
- var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
22
- var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
23
34
  function isSet(value) {
24
35
  return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
25
36
  }
@@ -33,12 +44,13 @@ function outputMode(stream = process2.stdout, env = process2.env) {
33
44
  return "terminal";
34
45
  return isSet(env.CI) ? "ci" : "pipe";
35
46
  }
47
+ var MODES, AGENT_VARIABLES;
48
+ var init_mode = __esm(() => {
49
+ MODES = new Set(["terminal", "ci", "agent", "pipe"]);
50
+ AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
51
+ });
36
52
 
37
- // ../kit/src/style.ts
38
- import process3 from "process";
39
-
40
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
41
- var G2 = /^[a-f0-9]+$/i;
53
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
42
54
  function b(r) {
43
55
  let e = r.startsWith("#") ? r.slice(1) : r;
44
56
  if (!G2.test(e))
@@ -49,11 +61,6 @@ function b(r) {
49
61
  throw Error(`Invalid hex color length: ${e.length}`);
50
62
  return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
51
63
  }
52
- var B2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
53
- let [l, n, c] = b(r);
54
- return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
55
- }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
56
- var h = new Set(["", "1", "2", "3", "true"]);
57
64
  function C(r, e = globalThis.process?.env ?? {}) {
58
65
  if (e.FORCE_COLOR !== undefined)
59
66
  return h.has(e.FORCE_COLOR);
@@ -67,7 +74,7 @@ function f(r, e = []) {
67
74
  l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
68
75
  let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
69
76
  return new Proxy(c, { get(t, i) {
70
- let a = B2[i];
77
+ let a = B[i];
71
78
  if (Array.isArray(a)) {
72
79
  let s = g.get(i);
73
80
  if (s === undefined)
@@ -90,32 +97,65 @@ function f(r, e = []) {
90
97
  function Fe(r = {}) {
91
98
  return f(r);
92
99
  }
93
- var o = Fe();
100
+ var G2, B, h, o;
101
+ var init_chunk_x450vn3m = __esm(() => {
102
+ G2 = /^[a-f0-9]+$/i;
103
+ B = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
104
+ let [l, n, c] = b(r);
105
+ return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
106
+ }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
107
+ h = new Set(["", "1", "2", "3", "true"]);
108
+ o = Fe();
109
+ });
110
+
111
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
112
+ var init_colors = __esm(() => {
113
+ init_chunk_x450vn3m();
114
+ });
115
+
116
+ // ../kit/src/config.ts
117
+ var init_config = __esm(() => {
118
+ init_args();
119
+ });
120
+
121
+ // ../kit/src/user-config.ts
122
+ var init_user_config = () => {};
94
123
 
95
124
  // ../kit/src/theme.ts
96
- var ENDS = new Map;
97
- var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
98
- var MAX_FILE_BYTES = 64 * 1024;
99
- var warned = new Set;
125
+ var ENDS, STYLES, MAX_FILE_BYTES, warned;
126
+ var init_theme = __esm(() => {
127
+ init_config();
128
+ init_user_config();
129
+ ENDS = new Map;
130
+ STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
131
+ MAX_FILE_BYTES = 64 * 1024;
132
+ warned = new Set;
133
+ });
100
134
 
101
135
  // ../kit/src/style.ts
136
+ import process3 from "process";
102
137
  function takesControlCodes(stream, env = process3.env) {
103
138
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
104
139
  }
105
140
  function paint(stream, env = process3.env) {
106
141
  return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
107
142
  }
108
- var STATUS_WORDS = {
109
- passed: ["passed", "success", "succeeded", "ok"],
110
- failed: ["failed", "failure", "error", "errored"],
111
- running: ["running", "in_progress", "started", "holding"],
112
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
113
- skipped: ["skipped", "cancelled", "canceled", "manual"]
114
- };
115
- var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
143
+ var STATUS_WORDS, STATUS_OF;
144
+ var init_style = __esm(() => {
145
+ init_colors();
146
+ init_mode();
147
+ init_theme();
148
+ STATUS_WORDS = {
149
+ passed: ["passed", "success", "succeeded", "ok"],
150
+ failed: ["failed", "failure", "error", "errored"],
151
+ running: ["running", "in_progress", "started", "holding"],
152
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
153
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
154
+ };
155
+ STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
156
+ });
116
157
 
117
158
  // ../kit/src/format.ts
118
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
119
159
  function formatSeconds(total) {
120
160
  let rest = Math.max(0, Math.round(total));
121
161
  const amounts = UNITS.map(([unit, size]) => {
@@ -136,13 +176,16 @@ function upTo(text, separator) {
136
176
  const end = text.indexOf(separator);
137
177
  return end === -1 ? text : text.slice(0, end);
138
178
  }
139
- var ESCAPE = String.fromCharCode(27);
179
+ var UNITS, ESCAPE;
180
+ var init_format = __esm(() => {
181
+ init_mode();
182
+ init_style();
183
+ UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
184
+ ESCAPE = String.fromCharCode(27);
185
+ });
140
186
 
141
187
  // ../kit/src/help.ts
142
188
  import process4 from "process";
143
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
144
- var USAGE_PREFIX = /^usage:\s*/i;
145
- var FULL_STOP = /\.$/;
146
189
  function usageLine(usage, colors = paint(process4.stdout)) {
147
190
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
148
191
  }
@@ -179,7 +222,6 @@ function exampleRows(examples, colors = paint(process4.stdout)) {
179
222
  return [];
180
223
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
181
224
  }
182
- var MAX_INLINE_CHOICES = 24;
183
225
  function optionRows(options, colors = paint(process4.stdout)) {
184
226
  const rows = Object.entries(options).map(([name, option]) => {
185
227
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -194,6 +236,14 @@ function optionRows(options, colors = paint(process4.stdout)) {
194
236
  const width = Math.max(0, ...rows.map((row) => row.width));
195
237
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
196
238
  }
239
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, MAX_INLINE_CHOICES = 24;
240
+ var init_help = __esm(() => {
241
+ init_mode();
242
+ init_style();
243
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
244
+ USAGE_PREFIX = /^usage:\s*/i;
245
+ FULL_STOP = /\.$/;
246
+ });
197
247
 
198
248
  // ../kit/src/text.ts
199
249
  function distance(a, b) {
@@ -221,37 +271,23 @@ function closest(name, names) {
221
271
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
222
272
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
223
273
  }
274
+ var init_text2 = () => {};
275
+
276
+ // ../kit/src/input.ts
277
+ var init_input = __esm(() => {
278
+ init_args();
279
+ });
224
280
 
225
281
  // ../kit/src/args.ts
226
- var DASHES = /^-+/;
227
- class Exit extends Error {
228
- code;
229
- hint;
230
- constructor(message, code, hint) {
231
- super(message);
232
- this.code = code;
233
- this.hint = hint;
234
- }
235
- }
282
+ import process5 from "process";
283
+ import { parseArgs } from "util";
236
284
  function fail(message, code = 2, hint) {
237
285
  throw new Exit(message, code, hint);
238
286
  }
239
-
240
- class UsageError extends Exit {
241
- constructor(message, hint) {
242
- super(message, 2, hint);
243
- }
244
- }
245
287
  function badUsage(message) {
246
288
  throw new UsageError(message);
247
289
  }
248
290
 
249
- class HelpShown extends Exit {
250
- constructor() {
251
- super("help shown", 0);
252
- }
253
- }
254
-
255
291
  class Completing {
256
292
  options;
257
293
  positionals;
@@ -262,11 +298,6 @@ class Completing {
262
298
  this.candidates = candidates;
263
299
  }
264
300
  }
265
- var completion = { active: false };
266
- var OUTPUT_OPTIONS = {
267
- color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
268
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
269
- };
270
301
  function applyOutput(color, plain, env = process5.env) {
271
302
  const when = plain === true ? "never" : color ?? "auto";
272
303
  if (when === "auto")
@@ -420,7 +451,6 @@ function parseError(error) {
420
451
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
421
452
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
422
453
  }
423
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
424
454
  function nearestOption(message, options, allowNegative) {
425
455
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
426
456
  if (typed === undefined)
@@ -436,6 +466,54 @@ function nearestOption(message, options, allowNegative) {
436
466
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
437
467
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
438
468
  }
469
+ var DASHES, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
470
+ var init_args = __esm(() => {
471
+ init_format();
472
+ init_help();
473
+ init_text2();
474
+ init_help();
475
+ init_input();
476
+ DASHES = /^-+/;
477
+ Exit = class Exit extends Error {
478
+ code;
479
+ hint;
480
+ constructor(message, code, hint) {
481
+ super(message);
482
+ this.code = code;
483
+ this.hint = hint;
484
+ }
485
+ };
486
+ UsageError = class UsageError extends Exit {
487
+ constructor(message, hint) {
488
+ super(message, 2, hint);
489
+ }
490
+ };
491
+ HelpShown = class HelpShown extends Exit {
492
+ constructor() {
493
+ super("help shown", 0);
494
+ }
495
+ };
496
+ completion = { active: false };
497
+ OUTPUT_OPTIONS = {
498
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
499
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
500
+ };
501
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
502
+ });
503
+
504
+ // ../kit/src/folders.ts
505
+ var SKIPPED_FOLDERS;
506
+ var init_folders = __esm(() => {
507
+ init_user_config();
508
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
509
+ });
510
+
511
+ // src/cli.ts
512
+ import process12 from "process";
513
+
514
+ // ../kit/src/index.ts
515
+ init_args();
516
+
439
517
  // ../kit/src/argv.ts
440
518
  import { readFileSync, realpathSync } from "fs";
441
519
  import { resolve } from "path";
@@ -460,15 +538,73 @@ function scriptArgs(argv = process6.argv.slice(2), cmdline = commandLine(), scri
460
538
  const after = at === -1 ? [] : cmdline.slice(at + 1);
461
539
  return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
462
540
  }
541
+ // ../kit/src/chart.ts
542
+ init_format();
543
+ init_mode();
544
+ init_style();
545
+ init_theme();
546
+ // ../kit/src/ci.ts
547
+ init_args();
548
+ init_format();
549
+
463
550
  // ../kit/src/progress.ts
551
+ init_format();
552
+ init_style();
553
+ init_theme();
464
554
  var ESC = String.fromCharCode(27);
465
555
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
466
556
  var RESET_STYLE = `${ESC}[0m`;
467
557
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
558
+
559
+ // ../kit/src/ci.ts
560
+ init_style();
561
+
562
+ // ../kit/src/tool.ts
563
+ init_format();
468
564
  // ../kit/src/cli.ts
565
+ init_args();
469
566
  import { readFileSync as readFileSync2, realpathSync as realpathSync2 } from "fs";
470
567
  import { dirname as dirname2, join as join2 } from "path";
471
- import process9 from "process";
568
+ import process10 from "process";
569
+
570
+ // ../kit/src/askpass.ts
571
+ import process7 from "process";
572
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
573
+ async function askpassClient(argv) {
574
+ const socketPath = process7.env[SOCKET_VARIABLE];
575
+ if (socketPath === undefined)
576
+ return;
577
+ const request = { prompt: argv[0] ?? "", ...process7.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
578
+ const { promise, resolve } = Promise.withResolvers();
579
+ let received = "";
580
+ try {
581
+ await Bun.connect({
582
+ unix: socketPath,
583
+ socket: {
584
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
585
+ `),
586
+ data: (_, chunk) => {
587
+ received += chunk.toString();
588
+ },
589
+ close: () => resolve(received),
590
+ error: () => resolve("")
591
+ }
592
+ });
593
+ } catch {
594
+ return 1;
595
+ }
596
+ const reply = await promise;
597
+ if (reply === "")
598
+ return 1;
599
+ const { answer } = JSON.parse(reply);
600
+ if (request.notice === true)
601
+ return 0;
602
+ if (answer === undefined)
603
+ return 1;
604
+ process7.stdout.write(`${answer}
605
+ `);
606
+ return 0;
607
+ }
472
608
 
473
609
  // ../kit/src/completions.ts
474
610
  var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
@@ -531,28 +667,34 @@ compdef __kaynooo_cli_complete ${bins.join(" ")}
531
667
  }
532
668
 
533
669
  // ../kit/src/notify.ts
534
- import process7 from "process";
670
+ init_format();
671
+ init_mode();
672
+ import process8 from "process";
535
673
  var NOTIFY_AFTER_MS = 1e4;
536
674
  var CANCELLED = 130;
537
675
  function base64(text) {
538
676
  return Buffer.from(text).toString("base64");
539
677
  }
540
- function notification(title, body, env = process7.env) {
541
- const id = `kit${process7.pid}`;
678
+ function notification(title, body, env = process8.env) {
679
+ const id = `kit${process8.pid}`;
542
680
  const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
543
681
  return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
544
682
  }
545
- function notifyEnd(command, code, ms, { stream = process7.stderr, env = process7.env } = {}) {
683
+ function notifyEnd(command, code, ms, { stream = process8.stderr, env = process8.env } = {}) {
546
684
  if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
547
685
  return;
548
686
  stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
549
687
  }
550
688
 
689
+ // ../kit/src/cli.ts
690
+ init_style();
691
+ init_text2();
692
+
551
693
  // ../kit/src/usage.ts
552
694
  import { appendFileSync, mkdirSync } from "fs";
553
695
  import { homedir } from "os";
554
696
  import { dirname, isAbsolute, join } from "path";
555
- import process8 from "process";
697
+ import process9 from "process";
556
698
 
557
699
  // ../kit/src/logs.ts
558
700
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -566,14 +708,14 @@ var usageError;
566
708
  function noteUsageError(message) {
567
709
  usageError = message;
568
710
  }
569
- function stateHome(env = process8.env) {
711
+ function stateHome(env = process9.env) {
570
712
  const dir = env.XDG_STATE_HOME;
571
713
  return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
572
714
  }
573
- function usagePath(env = process8.env) {
715
+ function usagePath(env = process9.env) {
574
716
  return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
575
717
  }
576
- function usageRecorded(env = process8.env) {
718
+ function usageRecorded(env = process9.env) {
577
719
  const off = env.KAYNOOO_CLI_NO_USAGE;
578
720
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
579
721
  }
@@ -582,12 +724,12 @@ function flagNames(argv) {
582
724
  const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
583
725
  return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
584
726
  }
585
- function usageEntry(bin, command, argv, code, now = new Date) {
727
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
586
728
  const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
587
729
  usageError = undefined;
588
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
730
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
589
731
  }
590
- function recordUsage(entry, env = process8.env) {
732
+ function recordUsage(entry, env = process9.env) {
591
733
  if (!usageRecorded(env))
592
734
  return;
593
735
  try {
@@ -681,8 +823,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
681
823
  `);
682
824
  }
683
825
  function printError(prefix, message, hint, cause) {
684
- const colors = paint(process9.stderr);
685
- const styled = takesControlCodes(process9.stderr);
826
+ const colors = paint(process10.stderr);
827
+ const styled = takesControlCodes(process10.stderr);
686
828
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
687
829
  const under = (label, text, tint) => text === undefined ? "" : `
688
830
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -725,11 +867,11 @@ async function dispatch(level, typed, { version, redact }) {
725
867
  }
726
868
  }
727
869
  if (name === undefined && level.path.length > 1) {
728
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stderr));
870
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process10.stderr));
729
871
  return 2;
730
872
  }
731
873
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
732
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stdout));
874
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process10.stdout));
733
875
  return 0;
734
876
  }
735
877
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -875,6 +1017,9 @@ function packageVersion(entry = Bun.main) {
875
1017
  }
876
1018
  async function runCli(cli, argv = scriptArgs()) {
877
1019
  const version = cli.version ?? packageVersion();
1020
+ const answered = await askpassClient(argv);
1021
+ if (answered !== undefined)
1022
+ return answered;
878
1023
  if (argv[0] === COMPLETE)
879
1024
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
880
1025
  if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
@@ -885,7 +1030,7 @@ async function runCli(cli, argv = scriptArgs()) {
885
1030
  notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
886
1031
  if (cli.usage !== false) {
887
1032
  try {
888
- recordUsage(usageEntry(cli.name, command, argv, code));
1033
+ recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
889
1034
  } catch {}
890
1035
  }
891
1036
  return code;
@@ -905,20 +1050,55 @@ function commandPath(scope, argv) {
905
1050
  }
906
1051
  return path.length === 0 ? undefined : path.join(" ");
907
1052
  }
908
- // ../kit/src/folders.ts
909
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1053
+
1054
+ // ../kit/src/index.ts
1055
+ init_config();
1056
+
1057
+ // ../kit/src/excerpt.ts
1058
+ init_text2();
1059
+
1060
+ // ../kit/src/index.ts
1061
+ init_folders();
1062
+ init_format();
1063
+
1064
+ // ../kit/src/git.ts
1065
+ init_args();
1066
+ // ../kit/src/limit.ts
1067
+ init_args();
1068
+
1069
+ // ../kit/src/index.ts
1070
+ init_mode();
1071
+
1072
+ // ../kit/src/report.ts
1073
+ init_style();
1074
+ init_text2();
910
1075
  // ../kit/src/secrets.ts
911
1076
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
912
1077
  // ../kit/src/sessions.ts
913
1078
  var {Glob } = globalThis.Bun;
914
1079
  var SESSION_FILES = new Glob("*.json");
915
1080
  var ACCOUNT_DIRS = new Glob("*/sessions");
1081
+
1082
+ // ../kit/src/index.ts
1083
+ init_style();
1084
+ init_text2();
1085
+ init_theme();
1086
+ init_user_config();
1087
+
1088
+ // ../kit/src/watch.ts
1089
+ init_args();
1090
+ init_input();
1091
+ init_style();
1092
+ // ../kit/src/workspace-root.ts
1093
+ init_user_config();
916
1094
  // src/commands.ts
917
1095
  import { existsSync as existsSync10, rmSync as rmSync4 } from "fs";
918
- var {$: $8 } = globalThis.Bun;
1096
+ var {$: $9 } = globalThis.Bun;
919
1097
 
920
1098
  // src/errors.ts
921
1099
  import { readFileSync as readFileSync3 } from "fs";
1100
+ var {$ } = globalThis.Bun;
1101
+
922
1102
  class KnownError extends Error {
923
1103
  }
924
1104
  var BOOT_TIME_LINE = /^btime (\d+)$/m;
@@ -935,23 +1115,26 @@ function alive(pid) {
935
1115
  return error.code === "EPERM";
936
1116
  }
937
1117
  }
938
- function failKnown(error) {
1118
+ function knownMessage(error) {
939
1119
  if (error instanceof KnownError)
940
- fail(error.message, 1);
1120
+ return error.message;
1121
+ return error instanceof $.ShellError ? error.stderr.toString().trim() || error.message : undefined;
1122
+ }
1123
+ function failureText(error) {
1124
+ return knownMessage(error) ?? (error instanceof Error ? error.message : String(error));
1125
+ }
1126
+ function failKnown(error) {
1127
+ const message = knownMessage(error);
1128
+ if (message !== undefined)
1129
+ fail(message, 1);
941
1130
  throw error;
942
1131
  }
943
1132
 
944
- // src/files.ts
945
- import { existsSync as existsSync4, lstatSync, mkdirSync as mkdirSync3, readFileSync as readFileSync6, renameSync, rmSync as rmSync2, statSync, symlinkSync, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
946
- import { constants } from "os";
947
- import { basename as basename2, dirname as dirname4, join as join7 } from "path";
1133
+ // src/git.ts
1134
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readdirSync as readdirSync2, rmdirSync } from "fs";
1135
+ import { basename as basename2, dirname as dirname4, join as join5 } from "path";
948
1136
  var {$: $2 } = globalThis.Bun;
949
1137
 
950
- // src/compose.ts
951
- import { existsSync as existsSync3, readFileSync as readFileSync4 } from "fs";
952
- import { join as join5 } from "path";
953
- var {$ } = globalThis.Bun;
954
-
955
1138
  // src/project.ts
956
1139
  import { existsSync as existsSync2, readdirSync, realpathSync as realpathSync3 } from "fs";
957
1140
  import { basename, dirname as dirname3, join as join4 } from "path";
@@ -1032,12 +1215,18 @@ function assertValid(project) {
1032
1215
  async function loadProjects() {
1033
1216
  const settings = await wtConfig();
1034
1217
  const files = existsSync2(settings.manifests) ? readdirSync(settings.manifests).filter((file) => file.endsWith(".ts")).sort() : [];
1035
- return Promise.all(files.map(async (file) => {
1218
+ const projects = await Promise.all(files.map(async (file) => {
1036
1219
  const { default: config } = await import(join4(settings.manifests, file));
1037
1220
  const project = { ...config, root: expandHome(config.root), name: basename(file, ".ts"), settings };
1038
1221
  assertValid(project);
1039
1222
  return project;
1040
1223
  }));
1224
+ for (const [index, project] of projects.entries()) {
1225
+ const twin = projects.slice(0, index).find((other) => basename(other.root) === basename(project.root));
1226
+ if (twin)
1227
+ throw new WtError(`${twin.name}.ts and ${project.name}.ts both have a checkout named ${basename(project.root)}, so their worktrees would share stacks and volumes: rename the folder of a checkout that has no worktrees yet, or remove one of the files`);
1228
+ }
1229
+ return projects;
1041
1230
  }
1042
1231
  async function findProject(name) {
1043
1232
  const project = (await loadProjects()).find((p) => p.name === name);
@@ -1096,7 +1285,112 @@ async function locateWorktree(cwd, task, projectName) {
1096
1285
  return worktreeOf(here.project, name);
1097
1286
  }
1098
1287
 
1288
+ // src/git.ts
1289
+ async function git2(cwd, ...args) {
1290
+ const result = await $2`git -C ${cwd} ${args}`.quiet().nothrow();
1291
+ return { ok: result.exitCode === 0, out: `${result.stdout.toString()}${result.stderr.toString()}`.trim() };
1292
+ }
1293
+ async function branchExists(repo, branch) {
1294
+ if ((await git2(repo, "show-ref", "--quiet", "--verify", `refs/heads/${branch}`)).ok)
1295
+ return true;
1296
+ return (await git2(repo, "for-each-ref", "--format=%(refname)", `refs/remotes/*/${branch}`)).out !== "";
1297
+ }
1298
+ async function onBranch(repo, dir, branch) {
1299
+ return git2(repo, "worktree", "add", ...await branchExists(repo, branch) ? [dir, branch] : ["-b", branch, dir]);
1300
+ }
1301
+ async function addWorktrees(worktree, branch) {
1302
+ const { project, dir } = worktree;
1303
+ if (existsSync3(dir))
1304
+ throw new WtError(`${dir} already exists: \`wt sync ${worktree.task} -p ${project.name}\` finishes it, \`wt rm ${worktree.task} -p ${project.name}\` removes it`);
1305
+ mkdirSync2(dirname4(dir), { recursive: true });
1306
+ const root = project.repos.length ? await git2(project.root, "worktree", "add", "--detach", dir) : await onBranch(project.root, dir, branch);
1307
+ if (!root.ok)
1308
+ throw new WtError(`git worktree add failed for the root:
1309
+ ${root.out}`);
1310
+ for (const repo of project.repos) {
1311
+ const added = await onBranch(join5(project.root, repo), join5(dir, repo), branch);
1312
+ if (!added.ok) {
1313
+ await removeWorktrees(worktree);
1314
+ throw new WtError(`git worktree add failed for ${repo}, rolled back:
1315
+ ${added.out}`);
1316
+ }
1317
+ }
1318
+ }
1319
+ async function removeWorktrees(worktree) {
1320
+ const { project, dir } = worktree;
1321
+ await Promise.all(project.repos.map(async (repo) => git2(join5(project.root, repo), "worktree", "remove", "--force", join5(dir, repo))));
1322
+ await git2(project.root, "worktree", "remove", "--force", dir);
1323
+ if (existsSync3(dir))
1324
+ await $2`docker run --rm -v ${`${dirname4(dir)}:/parent`} alpine rm -rf ${`/parent/${basename2(dir)}`}`.quiet();
1325
+ await Promise.all([".", ...project.repos].map(async (repo) => git2(join5(project.root, repo), "worktree", "prune")));
1326
+ if (existsSync3(dirname4(dir)) && !readdirSync2(dirname4(dir)).length)
1327
+ rmdirSync(dirname4(dir));
1328
+ }
1329
+ async function dirtyRepos(worktree) {
1330
+ const repos = [".", ...worktree.project.repos];
1331
+ const statuses = await Promise.all(repos.map(async (repo) => git2(join5(worktree.dir, repo), "status", "--porcelain")));
1332
+ return repos.filter((_, index) => statuses[index].ok && statuses[index].out !== "").map((repo) => repo === "." ? "root" : repo);
1333
+ }
1334
+ async function unreachableByRepo(dir, repos) {
1335
+ const all = [".", ...repos];
1336
+ const counts = await Promise.all(all.map(async (repo) => git2(join5(dir, repo), "rev-list", "--count", "HEAD", "--not", "--branches", "--remotes", "--tags")));
1337
+ return all.map((repo, index) => ({ repo: repo === "." ? "root" : repo, count: Number(counts[index].ok ? counts[index].out : 0) })).filter(({ count }) => count > 0);
1338
+ }
1339
+ async function unreachableCommits(worktree) {
1340
+ return (await unreachableByRepo(worktree.dir, worktree.project.repos)).map(({ repo, count }) => `${repo} (${count} commit${count === 1 ? "" : "s"})`);
1341
+ }
1342
+ async function unreachableCount(dir, repos) {
1343
+ return (await unreachableByRepo(dir, repos)).reduce((total, { count }) => total + count, 0);
1344
+ }
1345
+ async function isRegistered(worktree) {
1346
+ const listed = await git2(worktree.project.root, "worktree", "list", "--porcelain");
1347
+ return listed.out.split(`
1348
+ `).includes(`worktree ${worktree.dir}`);
1349
+ }
1350
+ async function currentBranch(dir) {
1351
+ const result = await git2(dir, "rev-parse", "--abbrev-ref", "HEAD");
1352
+ return result.ok ? result.out : "?";
1353
+ }
1354
+
1355
+ // src/routes.ts
1356
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3 } from "fs";
1357
+ import { join as join6 } from "path";
1358
+ var {$: $3 } = globalThis.Bun;
1359
+ var LEADING_STAR = /^\*/;
1360
+ async function mkcert(certFile, keyFile, hosts) {
1361
+ const result = await $3`mkcert -cert-file ${certFile} -key-file ${keyFile} ${hosts}`.quiet().nothrow();
1362
+ if (result.exitCode !== 0)
1363
+ throw new WtError(`mkcert failed for ${hosts.join(" ")}:
1364
+ ${result.stderr.toString()}`);
1365
+ }
1366
+ async function writeStackCerts(worktree) {
1367
+ const { project } = worktree;
1368
+ if (project.certs === undefined)
1369
+ return;
1370
+ const dir = join6(worktree.dir, project.certs);
1371
+ mkdirSync3(dir, { recursive: true });
1372
+ await Promise.all(project.routes.map(async (route) => {
1373
+ const served = worktreeHost(route.host, worktree.task);
1374
+ const name = served.replace(LEADING_STAR, "_wildcard");
1375
+ const cert = join6(dir, `${name}.pem`);
1376
+ const key = join6(dir, `${name}-key.pem`);
1377
+ return existsSync4(cert) && existsSync4(key) ? undefined : mkcert(cert, key, [served]);
1378
+ }));
1379
+ }
1380
+ function urlsOf(worktree) {
1381
+ return worktree.project.routes.filter((route) => !route.host.startsWith("*.")).map((route) => `https://${worktreeHost(route.host, worktree.task)}`);
1382
+ }
1383
+
1384
+ // src/run.ts
1385
+ import { existsSync as existsSync7, mkdirSync as mkdirSync5, readdirSync as readdirSync4, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "fs";
1386
+ import { userInfo } from "os";
1387
+ import { join as join9 } from "path";
1388
+ var {$: $5 } = globalThis.Bun;
1389
+
1099
1390
  // src/compose.ts
1391
+ import { existsSync as existsSync5, readFileSync as readFileSync4 } from "fs";
1392
+ import { join as join7 } from "path";
1393
+ var {$: $4 } = globalThis.Bun;
1100
1394
  var COMPOSE_FILES = ["compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"];
1101
1395
  var SKIP_PROFILE = "wt-skip";
1102
1396
  function composeEnv(overrides = {}) {
@@ -1104,7 +1398,7 @@ function composeEnv(overrides = {}) {
1104
1398
  return { ...Object.fromEntries(env), ...overrides };
1105
1399
  }
1106
1400
  async function composeConfig(dir, env = {}) {
1107
- const result = await $`docker compose config --format json`.cwd(dir).env(composeEnv(env)).quiet().nothrow();
1401
+ const result = await $4`docker compose config --format json`.cwd(dir).env(composeEnv(env)).quiet().nothrow();
1108
1402
  if (result.exitCode !== 0)
1109
1403
  throw new WtError(`docker compose config failed in ${dir}:
1110
1404
  ${result.stderr.toString()}`);
@@ -1113,13 +1407,13 @@ ${result.stderr.toString()}`);
1113
1407
  var COMPOSE_FILE_LINE = /^COMPOSE_FILE=(.*)$/m;
1114
1408
  var QUOTES_AROUND = /^["']|["']$/g;
1115
1409
  function baseComposeFiles(dir, overrides) {
1116
- const envFile = join5(dir, ".env");
1117
- const line = existsSync3(envFile) ? readFileSync4(envFile, "utf8").match(COMPOSE_FILE_LINE) : null;
1410
+ const envFile = join7(dir, ".env");
1411
+ const line = existsSync5(envFile) ? readFileSync4(envFile, "utf8").match(COMPOSE_FILE_LINE) : null;
1118
1412
  const files = line ? line[1].replace(QUOTES_AROUND, "").split(":").filter(Boolean) : [];
1119
1413
  const base = files.filter((file) => !file.startsWith(`${overrides}/`));
1120
1414
  if (base.length)
1121
1415
  return base;
1122
- const found = COMPOSE_FILES.find((file) => existsSync3(join5(dir, file)));
1416
+ const found = COMPOSE_FILES.find((file) => existsSync5(join7(dir, file)));
1123
1417
  if (found === undefined)
1124
1418
  throw new WtError(`no compose file in ${dir}`);
1125
1419
  return [found];
@@ -1215,432 +1509,45 @@ function overrideWarnings(worktree, config) {
1215
1509
  return warnings;
1216
1510
  }
1217
1511
  async function runningProjects() {
1218
- const result = await $`docker compose ls --format json`.quiet().nothrow();
1512
+ const result = await $4`docker compose ls --format json`.quiet().nothrow();
1219
1513
  if (result.exitCode !== 0)
1220
1514
  return new Set;
1221
1515
  return new Set(JSON.parse(result.stdout.toString()).map((stack) => stack.Name));
1222
1516
  }
1223
1517
 
1224
- // src/queue.ts
1225
- import { mkdirSync as mkdirSync2, readdirSync as readdirSync2, readFileSync as readFileSync5, rmSync, writeFileSync } from "fs";
1226
- import { join as join6 } from "path";
1227
- var queueDir = (settings, name) => join6(settings.state, "queues", name);
1228
- var POLL_MS = 1000;
1229
- function liveTickets(dir) {
1230
- const names = readdirSync2(dir).sort();
1231
- return names.filter((name) => {
1232
- const dash = name.indexOf("-");
1233
- if (Number(name.slice(0, dash)) >= bootTime() && alive(Number(name.slice(dash + 1))))
1234
- return true;
1235
- rmSync(join6(dir, name), { force: true });
1236
- return false;
1237
- });
1238
- }
1239
- function labelOf(ticket) {
1240
- try {
1241
- return readFileSync5(ticket, "utf8");
1242
- } catch {
1243
- return "";
1518
+ // src/env_file.ts
1519
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
1520
+
1521
+ // ../env/src/dotenv.ts
1522
+ var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
1523
+ var INLINE_COMMENT = /\s+#.*$/;
1524
+ var CARRIAGE_RETURN = /\r$/;
1525
+ var ESCAPES = { n: `
1526
+ `, r: "\r", t: "\t", '"': '"', "\\": "\\", $: "$" };
1527
+ function closingQuote(text, quote) {
1528
+ for (let index = 0;index < text.length; index++) {
1529
+ if (quote === '"' && text[index] === "\\")
1530
+ index++;
1531
+ else if (text[index] === quote)
1532
+ return index;
1244
1533
  }
1534
+ return -1;
1245
1535
  }
1246
- async function inLine(dir, label, waiting, work) {
1247
- mkdirSync2(dir, { recursive: true });
1248
- const name = `${String(Date.now()).padStart(15, "0")}-${process.pid}`;
1249
- const ticket = join6(dir, name);
1250
- const release = () => rmSync(ticket, { force: true });
1251
- writeFileSync(ticket, label);
1252
- process.once("exit", release);
1253
- try {
1254
- let shown = -1;
1255
- for (;; ) {
1256
- const ahead = liveTickets(dir).filter((other) => other < name);
1257
- if (ahead.length === 0)
1258
- break;
1259
- if (ahead.length !== shown) {
1260
- shown = ahead.length;
1261
- waiting(ahead.length, labelOf(join6(dir, ahead[0])));
1262
- }
1263
- await Bun.sleep(POLL_MS);
1536
+ function unescapeDollar(text) {
1537
+ return text.replaceAll("\\$", "$");
1538
+ }
1539
+ function unescapeDouble(text) {
1540
+ let out = "";
1541
+ for (let index = 0;index < text.length; index++) {
1542
+ const next = text[index + 1];
1543
+ if (text[index] === "\\" && next !== undefined && next in ESCAPES) {
1544
+ out += ESCAPES[next];
1545
+ index++;
1546
+ } else {
1547
+ out += text[index];
1264
1548
  }
1265
- return await work();
1266
- } finally {
1267
- release();
1268
1549
  }
1269
- }
1270
-
1271
- // src/files.ts
1272
- var PARTIAL = ".wt-partial";
1273
- var PAUSE_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
1274
- function writeIfChanged(path, content) {
1275
- if (existsSync4(path) && readFileSync6(path, "utf8") === content)
1276
- return false;
1277
- mkdirSync3(dirname4(path), { recursive: true });
1278
- writeFileSync2(path, content);
1279
- return true;
1280
- }
1281
- async function volumeExists(name) {
1282
- return (await $2`docker volume inspect ${name}`.quiet().nothrow()).exitCode === 0;
1283
- }
1284
- async function copyFromMain(worktree) {
1285
- const warnings = [];
1286
- for (const entry of worktree.project.copy ?? []) {
1287
- const source = join7(worktree.project.root, entry);
1288
- const target = join7(worktree.dir, entry);
1289
- if (!existsSync4(source)) {
1290
- warnings.push(`copy: ${entry} does not exist in main`);
1291
- continue;
1292
- }
1293
- if (existsSync4(target))
1294
- continue;
1295
- const partial = `${target}${PARTIAL}`;
1296
- mkdirSync3(dirname4(target), { recursive: true });
1297
- rmSync2(partial, { recursive: true, force: true });
1298
- await $2`cp -a --reflink=auto ${source} ${partial}`.quiet();
1299
- renameSync(partial, target);
1300
- }
1301
- return warnings;
1302
- }
1303
- function linkFromMain(worktree) {
1304
- for (const entry of worktree.project.link ?? []) {
1305
- const source = join7(worktree.project.root, entry);
1306
- const target = join7(worktree.dir, entry);
1307
- if (existsSync4(source) && !existsSync4(target)) {
1308
- mkdirSync3(dirname4(target), { recursive: true });
1309
- symlinkSync(source, target);
1310
- }
1311
- }
1312
- }
1313
- var WILDCARD_LABEL = /^\*\./;
1314
- function rewriteHosts(text, routes, task) {
1315
- const hosts = [...new Set(routes.map((route) => route.host.replace(WILDCARD_LABEL, "")))].sort((a, b) => b.length - a.length);
1316
- const pattern = new RegExp(`(?<![\\w.-])(\\.?)(${hosts.map(B).join("|")})(?![\\w.-])`, "g");
1317
- return text.replace(pattern, (_, dot, host) => `${dot}${worktreeHost(host, task)}`);
1318
- }
1319
- function setEnvValue(text, key, value) {
1320
- const line = `${key}=${value}`;
1321
- const pattern = new RegExp(`^${B(key)}=.*$`, "m");
1322
- if (pattern.test(text))
1323
- return text.replace(pattern, line);
1324
- return `${text}${text === "" || text.endsWith(`
1325
- `) ? "" : `
1326
- `}${line}
1327
- `;
1328
- }
1329
- function expandEnvValue(value, worktree) {
1330
- return value.replaceAll("{task}", worktree.task).replaceAll("{port}", String(worktree.clientPort));
1331
- }
1332
- function writeEnvFiles(worktree) {
1333
- const { project, task, dir } = worktree;
1334
- const envFiles = (project.copy ?? []).filter((entry) => basename2(entry).startsWith(".env") && statSync(join7(dir, entry), { throwIfNoEntry: false })?.isFile());
1335
- for (const entry of new Set([...envFiles, ".env"])) {
1336
- const file = join7(dir, entry);
1337
- let text = existsSync4(file) ? rewriteHosts(readFileSync6(file, "utf8"), project.routes, task) : "";
1338
- for (const [key, value] of Object.entries(project.env?.[entry] ?? {}))
1339
- text = setEnvValue(text, key, expandEnvValue(value, worktree));
1340
- if (entry === ".env") {
1341
- text = setEnvValue(text, "COMPOSE_PROJECT_NAME", worktree.id);
1342
- text = setEnvValue(text, "COMPOSE_FILE", [...baseComposeFiles(dir, worktree.project.settings.overrides), worktree.files.override].join(":"));
1343
- }
1344
- writeIfChanged(file, text);
1345
- }
1346
- }
1347
- function unlinkLegacySymlink(dir, entry) {
1348
- let path = dir;
1349
- for (const part of entry.split("/")) {
1350
- path = join7(path, part);
1351
- const stat = lstatSync(path, { throwIfNoEntry: false });
1352
- if (!stat)
1353
- return;
1354
- if (stat.isSymbolicLink())
1355
- return unlinkSync(path);
1356
- }
1357
- }
1358
- async function mainContainers(main, status) {
1359
- return (await $2`docker ps -q --filter ${`status=${status}`} --filter ${`label=com.docker.compose.project=${main.name}`}`.quiet().text()).split(`
1360
- `).filter(Boolean);
1361
- }
1362
- function unpause(ids) {
1363
- if (ids.length)
1364
- Bun.spawnSync(["docker", "unpause", ...ids], { stdout: "ignore", stderr: "ignore" });
1365
- }
1366
- async function whilePaused(ids, work, abort, record) {
1367
- const release = () => {
1368
- unpause(ids);
1369
- if (record !== undefined)
1370
- rmSync2(record, { force: true });
1371
- };
1372
- const onSignal = (signal) => {
1373
- abort?.();
1374
- release();
1375
- process.exit(128 + constants.signals[signal]);
1376
- };
1377
- for (const signal of PAUSE_SIGNALS)
1378
- process.once(signal, onSignal);
1379
- try {
1380
- if (ids.length) {
1381
- if (record !== undefined) {
1382
- mkdirSync3(dirname4(record), { recursive: true });
1383
- writeFileSync2(record, `${ids.join(`
1384
- `)}
1385
- `);
1386
- }
1387
- await $2`docker pause ${ids}`.quiet();
1388
- }
1389
- return await work();
1390
- } finally {
1391
- for (const signal of PAUSE_SIGNALS)
1392
- process.off(signal, onSignal);
1393
- release();
1394
- }
1395
- }
1396
- async function settle(copies) {
1397
- const results = await Promise.allSettled(copies.map(async (copy) => copy()));
1398
- return results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
1399
- }
1400
- function failureText(error) {
1401
- if (error instanceof $2.ShellError)
1402
- return error.stderr.toString().trim() || error.message;
1403
- return error instanceof Error ? error.message : String(error);
1404
- }
1405
- var pausedRecord = (worktree) => queueDir(worktree.project.settings, `${worktree.project.name}.paused`);
1406
- function readPending(file) {
1407
- return new Set(existsSync4(file) ? readFileSync6(file, "utf8").split(`
1408
- `).filter(Boolean) : []);
1409
- }
1410
- function writePending(file, volumes) {
1411
- const text = [...volumes].join(`
1412
- `);
1413
- if (!text)
1414
- return rmSync2(file, { force: true });
1415
- mkdirSync3(dirname4(file), { recursive: true });
1416
- writeFileSync2(file, `${text}
1417
- `);
1418
- }
1419
- async function cloneData(worktree, main) {
1420
- return inLine(queueDir(worktree.project.settings, `${worktree.project.name}.clone`), `cloning ${worktree.task}`, (_, running) => console.error(`wt: ${worktree.project.name}'s main is busy ${running || "cloning"}, waiting`), async () => {
1421
- const record = pausedRecord(worktree);
1422
- const recorded = readPending(record);
1423
- const leftover = recorded.size ? (await mainContainers(main, "paused")).filter((id) => recorded.has(id)) : [];
1424
- unpause(leftover);
1425
- rmSync2(record, { force: true });
1426
- const warnings = leftover.length ? [`clone: unpaused ${leftover.length} of main's containers a clone cut short had left paused`] : [];
1427
- return [...warnings, ...await cloneInLine(worktree, main)];
1428
- });
1429
- }
1430
- async function cloneInLine(worktree, main) {
1431
- const warnings = [];
1432
- const pending = [];
1433
- const unfinished = readPending(worktree.files.clonesPending);
1434
- const copyLabel = `wt.clone=${worktree.id}`;
1435
- const stopCopies = () => {
1436
- const ids = Bun.spawnSync(["docker", "ps", "-q", "--filter", `label=${copyLabel}`]).stdout.toString().split(`
1437
- `).filter(Boolean);
1438
- if (ids.length)
1439
- Bun.spawnSync(["docker", "rm", "-f", ...ids], { stdout: "ignore", stderr: "ignore" });
1440
- };
1441
- for (const entry of worktree.project.clone ?? []) {
1442
- const source = join7(worktree.project.root, entry);
1443
- if (existsSync4(source)) {
1444
- unlinkLegacySymlink(worktree.dir, entry);
1445
- const target = join7(worktree.dir, entry);
1446
- if (existsSync4(target))
1447
- continue;
1448
- if (!statSync(source).isDirectory())
1449
- throw new WtError(`clone: ${entry} is not a directory`);
1450
- const partial = `/to/${basename2(target)}${PARTIAL}`;
1451
- pending.push({
1452
- copy: async () => {
1453
- mkdirSync3(dirname4(target), { recursive: true });
1454
- await $2`docker run --rm --label ${copyLabel} -v ${`${source}:/from:ro`} -v ${`${dirname4(target)}:/to`} alpine sh -c ${`rm -rf '${partial}' && mkdir '${partial}' && cp -a /from/. '${partial}/' && mv '${partial}' '/to/${basename2(target)}'`}`.quiet();
1455
- }
1456
- });
1457
- continue;
1458
- }
1459
- const volume = main.volumes?.[entry];
1460
- if (!volume) {
1461
- warnings.push(`clone: ${entry} is neither a path in main nor a volume of its stack`);
1462
- continue;
1463
- }
1464
- if (volume.driver_opts?.device !== undefined && volume.driver_opts.device !== "")
1465
- throw new WtError(`clone: volume ${entry} is a bind to ${volume.driver_opts.device}, list that path instead`);
1466
- const sourceVolume = volume.name ?? `${main.name}_${entry}`;
1467
- const targetVolume = `${worktree.id}_${entry}`;
1468
- if (await volumeExists(targetVolume)) {
1469
- if (!unfinished.has(targetVolume))
1470
- continue;
1471
- const removed = await $2`docker volume rm ${targetVolume}`.quiet().nothrow();
1472
- if (removed.exitCode !== 0)
1473
- throw new WtError(`clone: volume ${targetVolume} was cut short mid-copy and cannot be emptied (${removed.stderr.toString().trim()}), \`wt down ${worktree.task}\` then \`wt sync ${worktree.task}\``);
1474
- }
1475
- if (!await volumeExists(sourceVolume)) {
1476
- warnings.push(`clone: main has no volume ${sourceVolume} yet, the worktree starts with an empty one`);
1477
- continue;
1478
- }
1479
- pending.push({
1480
- volume: targetVolume,
1481
- copy: async () => {
1482
- await $2`docker volume create --label ${`com.docker.compose.project=${worktree.id}`} --label ${`com.docker.compose.volume=${entry}`} ${targetVolume}`.quiet();
1483
- await $2`docker run --rm --label ${copyLabel} -v ${`${sourceVolume}:/from:ro`} -v ${`${targetVolume}:/to`} alpine cp -a /from/. /to/`.quiet();
1484
- unfinished.delete(targetVolume);
1485
- }
1486
- });
1487
- }
1488
- if (!pending.length) {
1489
- writePending(worktree.files.clonesPending, unfinished);
1490
- return warnings;
1491
- }
1492
- for (const { volume } of pending) {
1493
- if (volume !== undefined)
1494
- unfinished.add(volume);
1495
- }
1496
- writePending(worktree.files.clonesPending, unfinished);
1497
- const failures = await whilePaused(await mainContainers(main, "running"), async () => settle(pending.map(({ copy }) => copy)), stopCopies, pausedRecord(worktree));
1498
- writePending(worktree.files.clonesPending, unfinished);
1499
- if (failures.length)
1500
- throw new WtError(`clone failed, \`wt sync ${worktree.task}\` starts it again:
1501
- ${failures.map(failureText).join(`
1502
- `)}`);
1503
- return warnings;
1504
- }
1505
-
1506
- // src/git.ts
1507
- import { existsSync as existsSync5, mkdirSync as mkdirSync4, readdirSync as readdirSync3, rmdirSync } from "fs";
1508
- import { basename as basename3, dirname as dirname5, join as join8 } from "path";
1509
- var {$: $3 } = globalThis.Bun;
1510
- async function git2(cwd, ...args) {
1511
- const result = await $3`git -C ${cwd} ${args}`.quiet().nothrow();
1512
- return { ok: result.exitCode === 0, out: `${result.stdout.toString()}${result.stderr.toString()}`.trim() };
1513
- }
1514
- async function branchExists(repo, branch) {
1515
- if ((await git2(repo, "show-ref", "--quiet", "--verify", `refs/heads/${branch}`)).ok)
1516
- return true;
1517
- return (await git2(repo, "for-each-ref", "--format=%(refname)", `refs/remotes/*/${branch}`)).out !== "";
1518
- }
1519
- async function onBranch(repo, dir, branch) {
1520
- return git2(repo, "worktree", "add", ...await branchExists(repo, branch) ? [dir, branch] : ["-b", branch, dir]);
1521
- }
1522
- async function addWorktrees(worktree, branch) {
1523
- const { project, dir } = worktree;
1524
- if (existsSync5(dir))
1525
- throw new WtError(`${dir} already exists: \`wt sync ${worktree.task} -p ${project.name}\` finishes it, \`wt rm ${worktree.task} -p ${project.name}\` removes it`);
1526
- mkdirSync4(dirname5(dir), { recursive: true });
1527
- const root = project.repos.length ? await git2(project.root, "worktree", "add", "--detach", dir) : await onBranch(project.root, dir, branch);
1528
- if (!root.ok)
1529
- throw new WtError(`git worktree add failed for the root:
1530
- ${root.out}`);
1531
- for (const repo of project.repos) {
1532
- const added = await onBranch(join8(project.root, repo), join8(dir, repo), branch);
1533
- if (!added.ok) {
1534
- await removeWorktrees(worktree);
1535
- throw new WtError(`git worktree add failed for ${repo}, rolled back:
1536
- ${added.out}`);
1537
- }
1538
- }
1539
- }
1540
- async function removeWorktrees(worktree) {
1541
- const { project, dir } = worktree;
1542
- await Promise.all(project.repos.map(async (repo) => git2(join8(project.root, repo), "worktree", "remove", "--force", join8(dir, repo))));
1543
- await git2(project.root, "worktree", "remove", "--force", dir);
1544
- if (existsSync5(dir))
1545
- await $3`docker run --rm -v ${`${dirname5(dir)}:/parent`} alpine rm -rf ${`/parent/${basename3(dir)}`}`.quiet();
1546
- await Promise.all([".", ...project.repos].map(async (repo) => git2(join8(project.root, repo), "worktree", "prune")));
1547
- if (existsSync5(dirname5(dir)) && !readdirSync3(dirname5(dir)).length)
1548
- rmdirSync(dirname5(dir));
1549
- }
1550
- async function dirtyRepos(worktree) {
1551
- const repos = [".", ...worktree.project.repos];
1552
- const statuses = await Promise.all(repos.map(async (repo) => git2(join8(worktree.dir, repo), "status", "--porcelain")));
1553
- return repos.filter((_, index) => statuses[index].ok && statuses[index].out !== "").map((repo) => repo === "." ? "root" : repo);
1554
- }
1555
- async function unreachableByRepo(dir, repos) {
1556
- const all = [".", ...repos];
1557
- const counts = await Promise.all(all.map(async (repo) => git2(join8(dir, repo), "rev-list", "--count", "HEAD", "--not", "--branches", "--remotes", "--tags")));
1558
- return all.map((repo, index) => ({ repo: repo === "." ? "root" : repo, count: Number(counts[index].ok ? counts[index].out : 0) })).filter(({ count }) => count > 0);
1559
- }
1560
- async function unreachableCommits(worktree) {
1561
- return (await unreachableByRepo(worktree.dir, worktree.project.repos)).map(({ repo, count }) => `${repo} (${count} commit${count === 1 ? "" : "s"})`);
1562
- }
1563
- async function unreachableCount(dir, repos) {
1564
- return (await unreachableByRepo(dir, repos)).reduce((total, { count }) => total + count, 0);
1565
- }
1566
- async function isRegistered(worktree) {
1567
- const listed = await git2(worktree.project.root, "worktree", "list", "--porcelain");
1568
- return listed.out.split(`
1569
- `).includes(`worktree ${worktree.dir}`);
1570
- }
1571
- async function currentBranch(dir) {
1572
- const result = await git2(dir, "rev-parse", "--abbrev-ref", "HEAD");
1573
- return result.ok ? result.out : "?";
1574
- }
1575
-
1576
- // src/routes.ts
1577
- import { existsSync as existsSync6, mkdirSync as mkdirSync5 } from "fs";
1578
- import { join as join9 } from "path";
1579
- var {$: $4 } = globalThis.Bun;
1580
- var LEADING_STAR = /^\*/;
1581
- async function mkcert(certFile, keyFile, hosts) {
1582
- const result = await $4`mkcert -cert-file ${certFile} -key-file ${keyFile} ${hosts}`.quiet().nothrow();
1583
- if (result.exitCode !== 0)
1584
- throw new WtError(`mkcert failed for ${hosts.join(" ")}:
1585
- ${result.stderr.toString()}`);
1586
- }
1587
- async function writeStackCerts(worktree) {
1588
- const { project } = worktree;
1589
- if (project.certs === undefined)
1590
- return;
1591
- const dir = join9(worktree.dir, project.certs);
1592
- mkdirSync5(dir, { recursive: true });
1593
- await Promise.all(project.routes.map(async (route) => {
1594
- const served = worktreeHost(route.host, worktree.task);
1595
- const name = served.replace(LEADING_STAR, "_wildcard");
1596
- const cert = join9(dir, `${name}.pem`);
1597
- const key = join9(dir, `${name}-key.pem`);
1598
- return existsSync6(cert) && existsSync6(key) ? undefined : mkcert(cert, key, [served]);
1599
- }));
1600
- }
1601
- function urlsOf(worktree) {
1602
- return worktree.project.routes.filter((route) => !route.host.startsWith("*.")).map((route) => `https://${worktreeHost(route.host, worktree.task)}`);
1603
- }
1604
-
1605
- // src/run.ts
1606
- import { existsSync as existsSync8, mkdirSync as mkdirSync6, readdirSync as readdirSync4, rmSync as rmSync3, writeFileSync as writeFileSync3 } from "fs";
1607
- import { userInfo } from "os";
1608
- import { join as join10 } from "path";
1609
- var {$: $5 } = globalThis.Bun;
1610
-
1611
- // src/env_file.ts
1612
- import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
1613
-
1614
- // ../env/src/dotenv.ts
1615
- var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
1616
- var INLINE_COMMENT = /\s+#.*$/;
1617
- var CARRIAGE_RETURN = /\r$/;
1618
- var ESCAPES = { n: `
1619
- `, r: "\r", t: "\t", '"': '"', "\\": "\\", $: "$" };
1620
- function closingQuote(text, quote) {
1621
- for (let index = 0;index < text.length; index++) {
1622
- if (quote === '"' && text[index] === "\\")
1623
- index++;
1624
- else if (text[index] === quote)
1625
- return index;
1626
- }
1627
- return -1;
1628
- }
1629
- function unescapeDollar(text) {
1630
- return text.replaceAll("\\$", "$");
1631
- }
1632
- function unescapeDouble(text) {
1633
- let out = "";
1634
- for (let index = 0;index < text.length; index++) {
1635
- const next = text[index + 1];
1636
- if (text[index] === "\\" && next !== undefined && next in ESCAPES) {
1637
- out += ESCAPES[next];
1638
- index++;
1639
- } else {
1640
- out += text[index];
1641
- }
1642
- }
1643
- return out;
1550
+ return out;
1644
1551
  }
1645
1552
  function parseDotenv(text) {
1646
1553
  const physical = text.split(`
@@ -1693,7 +1600,54 @@ function entries(file) {
1693
1600
 
1694
1601
  // src/env_file.ts
1695
1602
  function readEnvFile(path) {
1696
- return existsSync7(path) ? Object.fromEntries(entries(parseDotenv(readFileSync7(path, "utf8")))) : {};
1603
+ return existsSync6(path) ? Object.fromEntries(entries(parseDotenv(readFileSync5(path, "utf8")))) : {};
1604
+ }
1605
+
1606
+ // src/queue.ts
1607
+ import { mkdirSync as mkdirSync4, readdirSync as readdirSync3, readFileSync as readFileSync6, rmSync, writeFileSync } from "fs";
1608
+ import { join as join8 } from "path";
1609
+ var queueDir = (settings, name) => join8(settings.state, "queues", name);
1610
+ var POLL_MS = 1000;
1611
+ function liveTickets(dir) {
1612
+ const names = readdirSync3(dir).sort();
1613
+ return names.filter((name) => {
1614
+ const dash = name.indexOf("-");
1615
+ if (Number(name.slice(0, dash)) >= bootTime() && alive(Number(name.slice(dash + 1))))
1616
+ return true;
1617
+ rmSync(join8(dir, name), { force: true });
1618
+ return false;
1619
+ });
1620
+ }
1621
+ function labelOf(ticket) {
1622
+ try {
1623
+ return readFileSync6(ticket, "utf8");
1624
+ } catch {
1625
+ return "";
1626
+ }
1627
+ }
1628
+ async function inLine(dir, label, waiting, work) {
1629
+ mkdirSync4(dir, { recursive: true });
1630
+ const name = `${String(Date.now()).padStart(15, "0")}-${process.pid}`;
1631
+ const ticket = join8(dir, name);
1632
+ const release = () => rmSync(ticket, { force: true });
1633
+ writeFileSync(ticket, label);
1634
+ process.once("exit", release);
1635
+ try {
1636
+ let shown = -1;
1637
+ for (;; ) {
1638
+ const ahead = liveTickets(dir).filter((other) => other < name);
1639
+ if (ahead.length === 0)
1640
+ break;
1641
+ if (ahead.length !== shown) {
1642
+ shown = ahead.length;
1643
+ waiting(ahead.length, labelOf(join8(dir, ahead[0])));
1644
+ }
1645
+ await Bun.sleep(POLL_MS);
1646
+ }
1647
+ return await work();
1648
+ } finally {
1649
+ release();
1650
+ }
1697
1651
  }
1698
1652
 
1699
1653
  // src/run.ts
@@ -1702,8 +1656,8 @@ var DEFAULT_PORT = 5432;
1702
1656
  var READY_TRIES = 60;
1703
1657
  var testContainer = (worktree) => `wt-${worktree.project.name}-test-db`;
1704
1658
  function testDatabase(dir) {
1705
- const base = existsSync8(join10(dir, ".env")) ? ".env" : ".env.dist";
1706
- const env = Object.assign({}, ...[base, ".env.test", ".env.test.local"].map((file) => readEnvFile(join10(dir, file))));
1659
+ const base = existsSync7(join9(dir, ".env")) ? ".env" : ".env.dist";
1660
+ const env = Object.assign({}, ...[base, ".env.test", ".env.test.local"].map((file) => readEnvFile(join9(dir, file))));
1707
1661
  if (env.DATABASE_URL === undefined || env.DATABASE_URL === "")
1708
1662
  throw new WtError(`no DATABASE_URL in the test env files of ${dir}`);
1709
1663
  const url = new URL(env.DATABASE_URL);
@@ -1724,7 +1678,7 @@ function runPlan(worktree, run, config, database, ids = userInfo(), tty = false)
1724
1678
  const service = config.services[run.service];
1725
1679
  if (!service)
1726
1680
  throw new WtError(`${config.name} has no service ${run.service}`);
1727
- const source = join10(worktree.project.root, run.dir);
1681
+ const source = join9(worktree.project.root, run.dir);
1728
1682
  const target = service.volumes?.find((volume) => volume.type === "bind" && volume.source === source)?.target;
1729
1683
  if (target === undefined)
1730
1684
  throw new WtError(`${run.service} does not bind-mount ${source}, so wt cannot tell where the worktree's copy goes`);
@@ -1770,7 +1724,7 @@ function runPlan(worktree, run, config, database, ids = userInfo(), tty = false)
1770
1724
  "-e",
1771
1725
  `TEST_TOKEN=${testToken(worktree.task)}`,
1772
1726
  "-v",
1773
- `${join10(worktree.dir, run.dir)}:${target}`,
1727
+ `${join9(worktree.dir, run.dir)}:${target}`,
1774
1728
  "-w",
1775
1729
  target,
1776
1730
  service.image ?? `${config.name}-${run.service}`,
@@ -1823,26 +1777,26 @@ async function forgetTestDatabases(worktree) {
1823
1777
  await $5`docker exec ${container} sh -c ${'dropdb -U "$POSTGRES_USER" --force "$0"'} ${name}`.quiet().nothrow();
1824
1778
  }
1825
1779
  const markers = worktree.project.settings.state;
1826
- if (!existsSync8(markers))
1780
+ if (!existsSync7(markers))
1827
1781
  return;
1828
1782
  for (const file of readdirSync4(markers).filter((name) => name.startsWith(`${worktree.id}.test-`)))
1829
- rmSync3(join10(markers, file), { force: true });
1783
+ rmSync2(join9(markers, file), { force: true });
1830
1784
  }
1831
1785
  async function provision(worktree, run, plan, databaseId) {
1832
1786
  const markers = worktree.project.settings.state;
1833
- const marker = join10(markers, `${worktree.id}.test-${databaseId.slice(0, 12)}`);
1834
- if (existsSync8(marker))
1787
+ const marker = join9(markers, `${worktree.id}.test-${databaseId.slice(0, 12)}`);
1788
+ if (existsSync7(marker))
1835
1789
  return;
1836
1790
  await inLine(queueDir(worktree.project.settings, `${worktree.id}.provision`), "provisioning", () => console.error(`wt run: waiting for ${worktree.task}'s test database to be provisioned`), async () => {
1837
- if (existsSync8(marker))
1791
+ if (existsSync7(marker))
1838
1792
  return;
1839
1793
  console.error(`wt run: provisioning ${worktree.task}'s test database`);
1840
1794
  for (const step of run.provision) {
1841
1795
  if (await runInherit(["docker", ...plan.runner(["sh", "-c", step])]) !== 0)
1842
1796
  throw new WtError(`provisioning failed on \`${step}\`, run it again with \`wt run ${worktree.task} -- sh -c '${step}'\``);
1843
1797
  }
1844
- mkdirSync6(markers, { recursive: true });
1845
- writeFileSync3(marker, "");
1798
+ mkdirSync5(markers, { recursive: true });
1799
+ writeFileSync2(marker, "");
1846
1800
  });
1847
1801
  }
1848
1802
  async function runTask(task, command, project) {
@@ -1851,7 +1805,7 @@ async function runTask(task, command, project) {
1851
1805
  assertWorktreeExists(worktree);
1852
1806
  if (!run)
1853
1807
  throw new WtError(`${name} has no \`run\` in its manifest, so wt cannot tell which service runs its tests`);
1854
- const database = testDatabase(join10(worktree.dir, run.dir));
1808
+ const database = testDatabase(join9(worktree.dir, run.dir));
1855
1809
  const plan = runPlan(worktree, run, await composeConfig(root), database, userInfo(), Boolean(process.stdin.isTTY && process.stdout.isTTY));
1856
1810
  await provision(worktree, run, plan, await ensureDatabase(plan, database));
1857
1811
  return runInherit(["docker", ...plan.runner(command)]);
@@ -1862,20 +1816,20 @@ async function runHeavy(command) {
1862
1816
  }
1863
1817
 
1864
1818
  // src/stack.ts
1865
- import { existsSync as existsSync9, mkdirSync as mkdirSync7, writeFileSync as writeFileSync4 } from "fs";
1819
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, writeFileSync as writeFileSync3 } from "fs";
1866
1820
  import { homedir as homedir3 } from "os";
1867
- import { dirname as dirname7 } from "path";
1821
+ import { dirname as dirname6 } from "path";
1868
1822
  var {$: $7 } = globalThis.Bun;
1869
1823
 
1870
1824
  // src/proxy.ts
1871
- import { dirname as dirname6, join as join11 } from "path";
1825
+ import { dirname as dirname5, join as join10 } from "path";
1872
1826
  var {$: $6 } = globalThis.Bun;
1873
- function devproxyArgv() {
1874
- const onPath = Bun.which("devproxy");
1827
+ function devproxyArgv(path = process.env.PATH ?? "") {
1828
+ const onPath = Bun.which("devproxy", { PATH: path });
1875
1829
  if (onPath !== null)
1876
1830
  return [onPath];
1877
1831
  try {
1878
- return [process.execPath, join11(dirname6(Bun.resolveSync("@kaynooo/devproxy", import.meta.dir)), "..", "dist", "cli.js")];
1832
+ return [process.execPath, "--no-env-file", "--config=/dev/null", join10(dirname5(Bun.resolveSync("@kaynooo/devproxy", import.meta.dir)), "..", "dist", "cli.js")];
1879
1833
  } catch {
1880
1834
  return [];
1881
1835
  }
@@ -1904,27 +1858,37 @@ function slugOf(ref) {
1904
1858
  async function spawnInherit(argv, cwd, env = process.env) {
1905
1859
  return Bun.spawn(argv, { cwd, env, stdio: ["inherit", "inherit", "inherit"] }).exited;
1906
1860
  }
1907
- async function runTemplate(template, worktree) {
1908
- const argv = fillTemplate(template, { project: worktree.project.name, task: worktree.task, dir: worktree.dir, id: worktree.id });
1909
- if (await spawnInherit(argv, worktree.dir) !== 0)
1861
+ async function spawnRunner(role, argv, cwd) {
1862
+ try {
1863
+ return await spawnInherit(argv, cwd);
1864
+ } catch (error) {
1865
+ if (error.code === "ENOENT")
1866
+ throw new WtError(`\`${argv[0]}\` is not on PATH: fix runner.${role} in ${configPath()}`);
1867
+ throw error;
1868
+ }
1869
+ }
1870
+ var argvOf = (template, worktree) => fillTemplate(template, { project: worktree.project.name, task: worktree.task, dir: worktree.dir, id: worktree.id });
1871
+ async function runTemplate(role, template, worktree) {
1872
+ const argv = argvOf(template, worktree);
1873
+ if (await spawnRunner(role, argv, worktree.dir) !== 0)
1910
1874
  throw new WtError(`\`${argv.join(" ")}\` failed`);
1911
1875
  }
1912
1876
  async function runSetup(worktree, env = composeEnv()) {
1913
1877
  const setup = worktree.project.setup ?? [];
1914
1878
  const marker = worktree.files.setupMarker;
1915
- if (!setup.length || existsSync9(marker))
1879
+ if (!setup.length || existsSync8(marker))
1916
1880
  return;
1917
1881
  for (const command of setup) {
1918
1882
  if (await spawnInherit(["sh", "-c", command], worktree.dir, env) !== 0)
1919
1883
  throw new WtError(`the worktree setup failed on \`${command}\``);
1920
1884
  }
1921
- mkdirSync7(dirname7(marker), { recursive: true });
1922
- writeFileSync4(marker, "");
1885
+ mkdirSync6(dirname6(marker), { recursive: true });
1886
+ writeFileSync3(marker, "");
1923
1887
  }
1924
1888
  async function stackUp(worktree) {
1925
1889
  const { up } = worktree.project.settings.runner;
1926
1890
  if (up)
1927
- return runTemplate(up, worktree);
1891
+ return runTemplate("up", up, worktree);
1928
1892
  if (await hasDevproxy())
1929
1893
  await devproxyUp();
1930
1894
  const network = worktree.project.settings.proxyNetwork;
@@ -1936,9 +1900,9 @@ async function stackUp(worktree) {
1936
1900
  }
1937
1901
  async function stackDown(worktree) {
1938
1902
  const { down } = worktree.project.settings.runner;
1939
- if (down && existsSync9(worktree.dir))
1940
- return runTemplate(down, worktree);
1941
- const here = existsSync9(worktree.dir);
1903
+ if (down && existsSync8(worktree.dir))
1904
+ return runTemplate("down", down, worktree);
1905
+ const here = existsSync8(worktree.dir);
1942
1906
  const argv = here ? ["docker", "compose", "down", "--remove-orphans"] : ["docker", "compose", "-p", worktree.id, "down", "--remove-orphans"];
1943
1907
  if (await spawnInherit(argv, here ? worktree.dir : homedir3(), composeEnv()) !== 0)
1944
1908
  throw new WtError(`docker compose down failed for ${worktree.id}`);
@@ -1947,15 +1911,256 @@ async function afterRemove(worktree) {
1947
1911
  const { removed } = worktree.project.settings.runner;
1948
1912
  if (!removed)
1949
1913
  return;
1950
- const argv = fillTemplate(removed, { project: worktree.project.name, task: worktree.task, dir: worktree.dir, id: worktree.id });
1951
- if (await spawnInherit(argv, worktree.project.root) !== 0)
1952
- console.warn(`wt: \`${argv.join(" ")}\` failed after removing ${worktree.id}`);
1914
+ const argv = argvOf(removed, worktree);
1915
+ try {
1916
+ if (await spawnRunner("removed", argv, worktree.project.root) !== 0)
1917
+ console.warn(`wt: \`${argv.join(" ")}\` failed after removing ${worktree.id}`);
1918
+ } catch (error) {
1919
+ if (!(error instanceof WtError))
1920
+ throw error;
1921
+ console.warn(`wt: ${error.message}, after removing ${worktree.id}`);
1922
+ }
1953
1923
  }
1954
1924
  async function hasContainers(composeName) {
1955
1925
  const found = await $7`docker ps -aq --filter ${`label=com.docker.compose.project=${composeName}`}`.quiet().nothrow();
1956
1926
  return found.stdout.toString().trim() !== "";
1957
1927
  }
1958
1928
 
1929
+ // src/files.ts
1930
+ init_text();
1931
+ import { existsSync as existsSync9, lstatSync, mkdirSync as mkdirSync7, readFileSync as readFileSync7, renameSync, rmSync as rmSync3, statSync, symlinkSync, unlinkSync, writeFileSync as writeFileSync4 } from "fs";
1932
+ import { constants } from "os";
1933
+ import { basename as basename3, dirname as dirname7, join as join11 } from "path";
1934
+ var {$: $8 } = globalThis.Bun;
1935
+ var PARTIAL = ".wt-partial";
1936
+ var PAUSE_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
1937
+ function writeIfChanged(path, content) {
1938
+ if (existsSync9(path) && readFileSync7(path, "utf8") === content)
1939
+ return false;
1940
+ mkdirSync7(dirname7(path), { recursive: true });
1941
+ writeFileSync4(path, content);
1942
+ return true;
1943
+ }
1944
+ async function volumeExists(name) {
1945
+ return (await $8`docker volume inspect ${name}`.quiet().nothrow()).exitCode === 0;
1946
+ }
1947
+ async function copyFromMain(worktree) {
1948
+ const warnings = [];
1949
+ for (const entry of worktree.project.copy ?? []) {
1950
+ const source = join11(worktree.project.root, entry);
1951
+ const target = join11(worktree.dir, entry);
1952
+ if (!existsSync9(source)) {
1953
+ warnings.push(`copy: ${entry} does not exist in main`);
1954
+ continue;
1955
+ }
1956
+ if (existsSync9(target))
1957
+ continue;
1958
+ const partial = `${target}${PARTIAL}`;
1959
+ mkdirSync7(dirname7(target), { recursive: true });
1960
+ rmSync3(partial, { recursive: true, force: true });
1961
+ await $8`cp -a --reflink=auto ${source} ${partial}`.quiet();
1962
+ renameSync(partial, target);
1963
+ }
1964
+ return warnings;
1965
+ }
1966
+ function linkFromMain(worktree) {
1967
+ for (const entry of worktree.project.link ?? []) {
1968
+ const source = join11(worktree.project.root, entry);
1969
+ const target = join11(worktree.dir, entry);
1970
+ if (existsSync9(source) && !existsSync9(target)) {
1971
+ mkdirSync7(dirname7(target), { recursive: true });
1972
+ symlinkSync(source, target);
1973
+ }
1974
+ }
1975
+ }
1976
+ var WILDCARD_LABEL = /^\*\./;
1977
+ function rewriteHosts(text, routes, task) {
1978
+ const hosts = [...new Set(routes.map((route) => route.host.replace(WILDCARD_LABEL, "")))].sort((a, b) => b.length - a.length);
1979
+ const pattern = new RegExp(`(?<![\\w.-])(\\.?)(${hosts.map(U).join("|")})(?![\\w.-])`, "g");
1980
+ return text.replace(pattern, (_, dot, host) => `${dot}${worktreeHost(host, task)}`);
1981
+ }
1982
+ function setEnvValue(text, key, value) {
1983
+ const line = `${key}=${value}`;
1984
+ const pattern = new RegExp(`^${U(key)}=.*$`, "m");
1985
+ if (pattern.test(text))
1986
+ return text.replace(pattern, line);
1987
+ return `${text}${text === "" || text.endsWith(`
1988
+ `) ? "" : `
1989
+ `}${line}
1990
+ `;
1991
+ }
1992
+ function expandEnvValue(value, worktree) {
1993
+ return value.replaceAll("{task}", worktree.task).replaceAll("{port}", String(worktree.clientPort));
1994
+ }
1995
+ function writeEnvFiles(worktree) {
1996
+ const { project, task, dir } = worktree;
1997
+ const envFiles = (project.copy ?? []).filter((entry) => basename3(entry).startsWith(".env") && statSync(join11(dir, entry), { throwIfNoEntry: false })?.isFile());
1998
+ for (const entry of new Set([...envFiles, ".env"])) {
1999
+ const file = join11(dir, entry);
2000
+ let text = existsSync9(file) ? rewriteHosts(readFileSync7(file, "utf8"), project.routes, task) : "";
2001
+ for (const [key, value] of Object.entries(project.env?.[entry] ?? {}))
2002
+ text = setEnvValue(text, key, expandEnvValue(value, worktree));
2003
+ if (entry === ".env") {
2004
+ text = setEnvValue(text, "COMPOSE_PROJECT_NAME", worktree.id);
2005
+ text = setEnvValue(text, "COMPOSE_FILE", [...baseComposeFiles(dir, worktree.project.settings.overrides), worktree.files.override].join(":"));
2006
+ }
2007
+ writeIfChanged(file, text);
2008
+ }
2009
+ }
2010
+ function unlinkLegacySymlink(dir, entry) {
2011
+ let path = dir;
2012
+ for (const part of entry.split("/")) {
2013
+ path = join11(path, part);
2014
+ const stat = lstatSync(path, { throwIfNoEntry: false });
2015
+ if (!stat)
2016
+ return;
2017
+ if (stat.isSymbolicLink())
2018
+ return unlinkSync(path);
2019
+ }
2020
+ }
2021
+ async function mainContainers(main, status) {
2022
+ return (await $8`docker ps -q --filter ${`status=${status}`} --filter ${`label=com.docker.compose.project=${main.name}`}`.quiet().text()).split(`
2023
+ `).filter(Boolean);
2024
+ }
2025
+ function unpause(ids) {
2026
+ if (ids.length)
2027
+ Bun.spawnSync(["docker", "unpause", ...ids], { stdout: "ignore", stderr: "ignore" });
2028
+ }
2029
+ async function whilePaused(ids, work, abort, record) {
2030
+ const release = () => {
2031
+ unpause(ids);
2032
+ if (record !== undefined)
2033
+ rmSync3(record, { force: true });
2034
+ };
2035
+ const onSignal = (signal) => {
2036
+ abort?.();
2037
+ release();
2038
+ process.exit(128 + constants.signals[signal]);
2039
+ };
2040
+ for (const signal of PAUSE_SIGNALS)
2041
+ process.once(signal, onSignal);
2042
+ try {
2043
+ if (ids.length) {
2044
+ if (record !== undefined) {
2045
+ mkdirSync7(dirname7(record), { recursive: true });
2046
+ writeFileSync4(record, `${ids.join(`
2047
+ `)}
2048
+ `);
2049
+ }
2050
+ await $8`docker pause ${ids}`.quiet();
2051
+ }
2052
+ return await work();
2053
+ } finally {
2054
+ for (const signal of PAUSE_SIGNALS)
2055
+ process.off(signal, onSignal);
2056
+ release();
2057
+ }
2058
+ }
2059
+ async function settle(copies) {
2060
+ const results = await Promise.allSettled(copies.map(async (copy) => copy()));
2061
+ return results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
2062
+ }
2063
+ var pausedRecord = (worktree) => queueDir(worktree.project.settings, `${worktree.project.name}.paused`);
2064
+ function readPending(file) {
2065
+ return new Set(existsSync9(file) ? readFileSync7(file, "utf8").split(`
2066
+ `).filter(Boolean) : []);
2067
+ }
2068
+ function writePending(file, volumes) {
2069
+ const text = [...volumes].join(`
2070
+ `);
2071
+ if (!text)
2072
+ return rmSync3(file, { force: true });
2073
+ mkdirSync7(dirname7(file), { recursive: true });
2074
+ writeFileSync4(file, `${text}
2075
+ `);
2076
+ }
2077
+ async function cloneData(worktree, main) {
2078
+ return inLine(queueDir(worktree.project.settings, `${worktree.project.name}.clone`), `cloning ${worktree.task}`, (_, running) => console.error(`wt: ${worktree.project.name}'s main is busy ${running || "cloning"}, waiting`), async () => {
2079
+ const record = pausedRecord(worktree);
2080
+ const recorded = readPending(record);
2081
+ const leftover = recorded.size ? (await mainContainers(main, "paused")).filter((id) => recorded.has(id)) : [];
2082
+ unpause(leftover);
2083
+ rmSync3(record, { force: true });
2084
+ const warnings = leftover.length ? [`clone: unpaused ${leftover.length} of main's containers a clone cut short had left paused`] : [];
2085
+ return [...warnings, ...await cloneInLine(worktree, main)];
2086
+ });
2087
+ }
2088
+ async function cloneInLine(worktree, main) {
2089
+ const warnings = [];
2090
+ const pending = [];
2091
+ const unfinished = readPending(worktree.files.clonesPending);
2092
+ const copyLabel = `wt.clone=${worktree.id}`;
2093
+ const stopCopies = () => {
2094
+ const ids = Bun.spawnSync(["docker", "ps", "-q", "--filter", `label=${copyLabel}`]).stdout.toString().split(`
2095
+ `).filter(Boolean);
2096
+ if (ids.length)
2097
+ Bun.spawnSync(["docker", "rm", "-f", ...ids], { stdout: "ignore", stderr: "ignore" });
2098
+ };
2099
+ for (const entry of worktree.project.clone ?? []) {
2100
+ const source = join11(worktree.project.root, entry);
2101
+ if (existsSync9(source)) {
2102
+ unlinkLegacySymlink(worktree.dir, entry);
2103
+ const target = join11(worktree.dir, entry);
2104
+ if (existsSync9(target))
2105
+ continue;
2106
+ if (!statSync(source).isDirectory())
2107
+ throw new WtError(`clone: ${entry} is not a directory`);
2108
+ const partial = `/to/${basename3(target)}${PARTIAL}`;
2109
+ pending.push({
2110
+ copy: async () => {
2111
+ mkdirSync7(dirname7(target), { recursive: true });
2112
+ await $8`docker run --rm --label ${copyLabel} -v ${`${source}:/from:ro`} -v ${`${dirname7(target)}:/to`} alpine sh -c ${`rm -rf '${partial}' && mkdir '${partial}' && cp -a /from/. '${partial}/' && mv '${partial}' '/to/${basename3(target)}'`}`.quiet();
2113
+ }
2114
+ });
2115
+ continue;
2116
+ }
2117
+ const volume = main.volumes?.[entry];
2118
+ if (!volume) {
2119
+ warnings.push(`clone: ${entry} is neither a path in main nor a volume of its stack`);
2120
+ continue;
2121
+ }
2122
+ if (volume.driver_opts?.device !== undefined && volume.driver_opts.device !== "")
2123
+ throw new WtError(`clone: volume ${entry} is a bind to ${volume.driver_opts.device}, list that path instead`);
2124
+ const sourceVolume = volume.name ?? `${main.name}_${entry}`;
2125
+ const targetVolume = `${worktree.id}_${entry}`;
2126
+ if (await volumeExists(targetVolume)) {
2127
+ if (!unfinished.has(targetVolume))
2128
+ continue;
2129
+ const removed = await $8`docker volume rm ${targetVolume}`.quiet().nothrow();
2130
+ if (removed.exitCode !== 0)
2131
+ throw new WtError(`clone: volume ${targetVolume} was cut short mid-copy and cannot be emptied (${removed.stderr.toString().trim()}), \`wt down ${worktree.task}\` then \`wt sync ${worktree.task}\``);
2132
+ }
2133
+ if (!await volumeExists(sourceVolume)) {
2134
+ warnings.push(`clone: main has no volume ${sourceVolume} yet, the worktree starts with an empty one`);
2135
+ continue;
2136
+ }
2137
+ pending.push({
2138
+ volume: targetVolume,
2139
+ copy: async () => {
2140
+ await $8`docker volume create --label ${`com.docker.compose.project=${worktree.id}`} --label ${`com.docker.compose.volume=${entry}`} ${targetVolume}`.quiet();
2141
+ await $8`docker run --rm --label ${copyLabel} -v ${`${sourceVolume}:/from:ro`} -v ${`${targetVolume}:/to`} alpine cp -a /from/. /to/`.quiet();
2142
+ unfinished.delete(targetVolume);
2143
+ }
2144
+ });
2145
+ }
2146
+ if (!pending.length) {
2147
+ writePending(worktree.files.clonesPending, unfinished);
2148
+ return warnings;
2149
+ }
2150
+ for (const { volume } of pending) {
2151
+ if (volume !== undefined)
2152
+ unfinished.add(volume);
2153
+ }
2154
+ writePending(worktree.files.clonesPending, unfinished);
2155
+ const failures = await whilePaused(await mainContainers(main, "running"), async () => settle(pending.map(({ copy }) => copy)), stopCopies, pausedRecord(worktree));
2156
+ writePending(worktree.files.clonesPending, unfinished);
2157
+ if (failures.length)
2158
+ throw new WtError(`clone failed, \`wt sync ${worktree.task}\` starts it again:
2159
+ ${failures.map(failureText).join(`
2160
+ `)}`);
2161
+ return warnings;
2162
+ }
2163
+
1959
2164
  // src/sync.ts
1960
2165
  async function syncWorktree(worktree) {
1961
2166
  assertWorktreeExists(worktree);
@@ -1976,20 +2181,20 @@ async function syncWorktree(worktree) {
1976
2181
  var ANONYMOUS_VOLUME = /^[0-9a-f]{64}$/;
1977
2182
  var WHITESPACE = /\s+/;
1978
2183
  async function anonymousVolumes(worktree) {
1979
- const containers = (await $8`docker ps -aq --filter ${`label=com.docker.compose.project=${worktree.id}`}`.quiet().text()).split(`
2184
+ const containers = (await $9`docker ps -aq --filter ${`label=com.docker.compose.project=${worktree.id}`}`.quiet().text()).split(`
1980
2185
  `).filter(Boolean);
1981
2186
  if (!containers.length)
1982
2187
  return [];
1983
- const mounts = await $8`docker inspect --format ${'{{range .Mounts}}{{if eq .Type "volume"}}{{.Name}} {{end}}{{end}}'} ${containers}`.quiet().nothrow();
2188
+ const mounts = await $9`docker inspect --format ${'{{range .Mounts}}{{if eq .Type "volume"}}{{.Name}} {{end}}{{end}}'} ${containers}`.quiet().nothrow();
1984
2189
  return mounts.text().split(WHITESPACE).filter((name) => ANONYMOUS_VOLUME.test(name));
1985
2190
  }
1986
2191
  async function removeVolumes(worktree, anonymous) {
1987
- const named = (await $8`docker volume ls -q --filter ${`label=com.docker.compose.project=${worktree.id}`}`.quiet().text()).split(`
2192
+ const named = (await $9`docker volume ls -q --filter ${`label=com.docker.compose.project=${worktree.id}`}`.quiet().text()).split(`
1988
2193
  `).filter((volume) => volume.startsWith(`${worktree.id}_`));
1989
2194
  const volumes = [...new Set([...named, ...anonymous])];
1990
2195
  if (!volumes.length)
1991
2196
  return;
1992
- const removed = await $8`docker volume rm ${volumes}`.quiet().nothrow();
2197
+ const removed = await $9`docker volume rm ${volumes}`.quiet().nothrow();
1993
2198
  if (removed.exitCode !== 0)
1994
2199
  throw new WtError(`could not remove the volumes of ${worktree.id}:
1995
2200
  ${removed.stderr.toString().trim()}`);
@@ -2003,8 +2208,9 @@ async function addTask(task, branch, options) {
2003
2208
  await syncWorktree(worktree);
2004
2209
  } catch (error) {
2005
2210
  const way = `the worktree is checked out but not ready: \`wt sync ${task} -p ${project.name}\` resumes it, \`wt rm ${task} -p ${project.name}\` removes it`;
2006
- if (error instanceof KnownError || error instanceof $8.ShellError)
2007
- throw new WtError(`${failureText(error)}
2211
+ const message = knownMessage(error);
2212
+ if (message !== undefined)
2213
+ throw new WtError(`${message}
2008
2214
  ${way}`);
2009
2215
  console.error(`wt: ${way}`);
2010
2216
  throw error;
@@ -2034,6 +2240,7 @@ async function assertRemovable(task, options) {
2034
2240
  if (!existsSync10(worktree.dir) && !Object.values(worktree.files).some((file) => existsSync10(file)) && !await isRegistered(worktree))
2035
2241
  throw new WtError(`no worktree ${worktree.task} of ${worktree.project.name}, nothing removed`);
2036
2242
  await refuseLosingWork(worktree, options.force === true);
2243
+ return worktree;
2037
2244
  }
2038
2245
  async function removeTask(task, options) {
2039
2246
  const worktree = await locateWorktree(process.cwd(), task, options.project);
@@ -2186,7 +2393,7 @@ async function initProject(dir, options) {
2186
2393
  // src/jobs.ts
2187
2394
  import { closeSync, fstatSync, mkdirSync as mkdirSync9, openSync, readdirSync as readdirSync6, readFileSync as readFileSync8, readSync, renameSync as renameSync2, rmSync as rmSync5, statSync as statSync3, writeFileSync as writeFileSync6 } from "fs";
2188
2395
  import { join as join13 } from "path";
2189
- var {$: $9 } = globalThis.Bun;
2396
+ var {$: $10 } = globalThis.Bun;
2190
2397
  var HELD_ENV = "WT_JOBS_HELD";
2191
2398
  var STARTING_MS = 30000;
2192
2399
  var TAKEOVER_MS = 5000;
@@ -2271,7 +2478,7 @@ function logTail(file, lines = 5) {
2271
2478
  }
2272
2479
  async function notify(app, title, body, critical = false) {
2273
2480
  if (Bun.which("notify-send") !== null)
2274
- await $9`notify-send -a ${app} ${critical ? ["-u", "critical"] : []} ${title} ${body}`.quiet().nothrow();
2481
+ await $10`notify-send -a ${app} ${critical ? ["-u", "critical"] : []} ${title} ${body}`.quiet().nothrow();
2275
2482
  }
2276
2483
 
2277
2484
  class Jobs {
@@ -2393,7 +2600,7 @@ class Jobs {
2393
2600
  try {
2394
2601
  return await action() ?? 0;
2395
2602
  } catch (error) {
2396
- const message = error instanceof Error ? error.message : String(error);
2603
+ const message = failureText(error);
2397
2604
  await this.failDetached(message);
2398
2605
  if (bg !== undefined)
2399
2606
  await this.notifyRefused(bg, message);
@@ -2434,7 +2641,8 @@ async function attempt(work) {
2434
2641
  await work();
2435
2642
  return 0;
2436
2643
  } catch (error) {
2437
- console.error(error instanceof KnownError ? `error: ${error.message}` : error);
2644
+ const message = knownMessage(error);
2645
+ console.error(message !== undefined ? `error: ${message}` : error);
2438
2646
  return 1;
2439
2647
  }
2440
2648
  }
@@ -2521,19 +2729,26 @@ function shellWrapper(shell) {
2521
2729
  async function jobs() {
2522
2730
  return new Jobs({ dir: (await wtConfig()).jobs, app: "wt" });
2523
2731
  }
2524
- async function guarded(action) {
2732
+ async function guarded(action, bg) {
2525
2733
  try {
2526
- return await (await jobs()).guarded(action);
2734
+ return await (await jobs()).guarded(action, bg);
2527
2735
  } catch (error) {
2528
2736
  return failKnown(error);
2529
2737
  }
2530
2738
  }
2739
+ function bgName(values, ...words) {
2740
+ return values.bg ? ["wt", ...words.filter((word) => word !== undefined)].join(" ") : undefined;
2741
+ }
2531
2742
  async function projectNames() {
2532
- return (await loadProjects()).map((project) => project.name);
2743
+ try {
2744
+ return (await loadProjects()).map((project) => project.name);
2745
+ } catch {
2746
+ return [];
2747
+ }
2533
2748
  }
2534
2749
  async function taskNames() {
2535
2750
  try {
2536
- return listTasks((await locate(process11.cwd())).project);
2751
+ return listTasks((await locate(process12.cwd())).project);
2537
2752
  } catch {
2538
2753
  return [];
2539
2754
  }
@@ -2541,8 +2756,7 @@ async function taskNames() {
2541
2756
  var TASK = { "[task]": taskNames, "<task>": taskNames };
2542
2757
  var PROJECT_OPTION = { type: "string", short: "p", candidates: projectNames, description: "manifest to use instead of the one the current directory belongs to" };
2543
2758
  var BG_OPTION = { type: "boolean", description: "run it away from any terminal, its output in the worktree's job log, a notification saying how it went" };
2544
- async function asWorktreeJob(verb, task, options, argv, work) {
2545
- const { project } = await locate(process11.cwd(), options.project);
2759
+ async function asWorktreeJob(verb, { project, task }, options, argv, work) {
2546
2760
  const ref = `${project.name}/${task}`;
2547
2761
  const stack = { ref, slug: slugOf(ref) };
2548
2762
  const queue = await jobs();
@@ -2552,13 +2766,8 @@ async function asWorktreeJob(verb, task, options, argv, work) {
2552
2766
  queue.forget(stack);
2553
2767
  return code;
2554
2768
  }
2555
- try {
2556
- const job = queue.detach(stack, verb, [import.meta.path, ...argv, "-p", project.name]);
2557
- console.log(`wt: ${verb} ${ref} runs out of sight, its output in ${job.log}`);
2558
- } catch (error) {
2559
- await queue.notifyRefused(`wt ${verb} ${ref}`, error instanceof Error ? error.message : String(error));
2560
- throw error;
2561
- }
2769
+ const job = queue.detach(stack, verb, [import.meta.path, ...argv, "-p", project.name]);
2770
+ console.log(`wt: ${verb} ${ref} runs out of sight, its output in ${job.log}`);
2562
2771
  return 0;
2563
2772
  }
2564
2773
  var ADD_USAGE = `wt add <task> [branch] [-p <name>] [--bg]
@@ -2626,7 +2835,7 @@ var TASKS_USAGE = `wt tasks [-p <name>]
2626
2835
  Prints the worktree names of the project, one per line.
2627
2836
 
2628
2837
  Exits 0 when it printed them, 1 when there is no such project, 2 on a usage error.`;
2629
- process11.exitCode = await runCli({
2838
+ process12.exitCode = await runCli({
2630
2839
  name: "wt",
2631
2840
  about: "git worktrees of a compose project, each with its own stack, data and <task>.<host> subdomains beside main",
2632
2841
  replaces: "a second clone, port juggling and a shared database to try a branch",
@@ -2636,7 +2845,10 @@ process11.exitCode = await runCli({
2636
2845
  summary: "create a worktree, copy its files and data from main, and route its subdomains",
2637
2846
  run: async (args) => {
2638
2847
  const { values, positionals: [task, branch] } = parse(args, ADD_USAGE, { project: PROJECT_OPTION, bg: BG_OPTION }, { positionals: ["<task>", "[branch]"] });
2639
- return guarded(async () => asWorktreeJob("add", task, values, ["add", task, ...branch === undefined ? [] : [branch]], async () => addTask(task, branch, values)));
2848
+ return guarded(async () => {
2849
+ const worktree = worktreeOf((await locate(process12.cwd(), values.project)).project, task);
2850
+ return asWorktreeJob("add", worktree, values, ["add", task, ...branch === undefined ? [] : [branch]], async () => addTask(task, branch, values));
2851
+ }, bgName(values, "add", task));
2640
2852
  }
2641
2853
  },
2642
2854
  sync: {
@@ -2644,8 +2856,9 @@ process11.exitCode = await runCli({
2644
2856
  run: async (args) => {
2645
2857
  const { values, positionals: [task] } = parse(args, SYNC_USAGE, { project: PROJECT_OPTION }, { positionals: ["[task]"], candidates: TASK });
2646
2858
  return guarded(async () => {
2647
- const { task: name } = await locateWorktree(process11.cwd(), task, values.project);
2648
- return asWorktreeJob("sync", name, values, ["sync", name], async () => syncTask(name, values));
2859
+ const worktree = await locateWorktree(process12.cwd(), task, values.project);
2860
+ assertWorktreeExists(worktree);
2861
+ return asWorktreeJob("sync", worktree, values, ["sync", worktree.task], async () => syncTask(worktree.task, values));
2649
2862
  });
2650
2863
  }
2651
2864
  },
@@ -2658,9 +2871,9 @@ process11.exitCode = await runCli({
2658
2871
  bg: BG_OPTION
2659
2872
  }, { positionals: ["<task>"], candidates: TASK });
2660
2873
  return guarded(async () => {
2661
- await assertRemovable(task, values);
2662
- return asWorktreeJob("rm", task, values, ["rm", task, ...values.force ? ["--force"] : []], async () => removeTask(task, values));
2663
- });
2874
+ const worktree = await assertRemovable(task, values);
2875
+ return asWorktreeJob("rm", worktree, values, ["rm", task, ...values.force ? ["--force"] : []], async () => removeTask(task, values));
2876
+ }, bgName(values, "rm", task));
2664
2877
  }
2665
2878
  },
2666
2879
  up: {
@@ -2668,9 +2881,10 @@ process11.exitCode = await runCli({
2668
2881
  run: async (args) => {
2669
2882
  const { values, positionals: [task] } = parse(args, UP_USAGE, { project: PROJECT_OPTION, bg: BG_OPTION }, { positionals: ["[task]"], candidates: TASK });
2670
2883
  return guarded(async () => {
2671
- const worktree = await locateWorktree(process11.cwd(), task, values.project);
2672
- return asWorktreeJob("up", worktree.task, values, ["up", worktree.task], async () => upTask(worktree));
2673
- });
2884
+ const worktree = await locateWorktree(process12.cwd(), task, values.project);
2885
+ assertWorktreeExists(worktree);
2886
+ return asWorktreeJob("up", worktree, values, ["up", worktree.task], async () => upTask(worktree));
2887
+ }, bgName(values, "up", task));
2674
2888
  }
2675
2889
  },
2676
2890
  down: {
@@ -2678,9 +2892,10 @@ process11.exitCode = await runCli({
2678
2892
  run: async (args) => {
2679
2893
  const { values, positionals: [task] } = parse(args, DOWN_USAGE, { project: PROJECT_OPTION, bg: BG_OPTION }, { positionals: ["[task]"], candidates: TASK });
2680
2894
  return guarded(async () => {
2681
- const worktree = await locateWorktree(process11.cwd(), task, values.project);
2682
- return asWorktreeJob("down", worktree.task, values, ["down", worktree.task], async () => downTask(worktree));
2683
- });
2895
+ const worktree = await locateWorktree(process12.cwd(), task, values.project);
2896
+ assertWorktreeExists(worktree);
2897
+ return asWorktreeJob("down", worktree, values, ["down", worktree.task], async () => downTask(worktree));
2898
+ }, bgName(values, "down", task));
2684
2899
  }
2685
2900
  },
2686
2901
  ls: {
@@ -2708,7 +2923,7 @@ process11.exitCode = await runCli({
2708
2923
  name: { type: "string", description: "the manifest's name, also hashed into the dev server port (the checkout's folder name)" },
2709
2924
  print: { type: "boolean", description: "print the draft instead of writing it" }
2710
2925
  }, { positionals: ["[dir]"] });
2711
- return guarded(async () => initProject(dir ?? process11.cwd(), values));
2926
+ return guarded(async () => initProject(dir ?? process12.cwd(), values));
2712
2927
  }
2713
2928
  },
2714
2929
  run: {