@kaynooo/cli-wt 0.1.1 → 0.1.6

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,15 +176,38 @@ 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
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
190
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
191
+ `);
192
+ const blank = lines.indexOf("");
193
+ const synopses = blank === -1 ? lines : lines.slice(0, blank);
194
+ const details = blank === -1 ? [] : lines.slice(blank + 1);
195
+ const colon = synopses[0].indexOf(": ");
196
+ const inline = synopses[0].slice(colon + 2);
197
+ const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
198
+ if (colon !== -1)
199
+ synopses[0] = synopses[0].slice(0, colon);
200
+ const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
201
+ `)}`;
202
+ const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
203
+ const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
204
+ return [head, ...lead, ...rest].join(`
205
+ `);
206
+ }
207
+ function prose(line, colors) {
208
+ if (colors.cyan("x") === "x")
209
+ return line;
210
+ return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
148
211
  }
149
212
  function helpText(usage, options, colors = paint(process4.stdout), { examples = [], exits = [] } = {}) {
150
213
  return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
@@ -179,7 +242,6 @@ function exampleRows(examples, colors = paint(process4.stdout)) {
179
242
  return [];
180
243
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
181
244
  }
182
- var MAX_INLINE_CHOICES = 24;
183
245
  function optionRows(options, colors = paint(process4.stdout)) {
184
246
  const rows = Object.entries(options).map(([name, option]) => {
185
247
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -194,6 +256,15 @@ function optionRows(options, colors = paint(process4.stdout)) {
194
256
  const width = Math.max(0, ...rows.map((row) => row.width));
195
257
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
196
258
  }
259
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
260
+ var init_help = __esm(() => {
261
+ init_mode();
262
+ init_style();
263
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
264
+ USAGE_PREFIX = /^usage:\s*/i;
265
+ FULL_STOP = /\.$/;
266
+ PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
267
+ });
197
268
 
198
269
  // ../kit/src/text.ts
199
270
  function distance(a, b) {
@@ -221,37 +292,23 @@ function closest(name, names) {
221
292
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
222
293
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
223
294
  }
295
+ var init_text2 = () => {};
296
+
297
+ // ../kit/src/input.ts
298
+ var init_input = __esm(() => {
299
+ init_args();
300
+ });
224
301
 
225
302
  // ../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
- }
303
+ import process5 from "process";
304
+ import { parseArgs } from "util";
236
305
  function fail(message, code = 2, hint) {
237
306
  throw new Exit(message, code, hint);
238
307
  }
239
-
240
- class UsageError extends Exit {
241
- constructor(message, hint) {
242
- super(message, 2, hint);
243
- }
244
- }
245
308
  function badUsage(message) {
246
309
  throw new UsageError(message);
247
310
  }
248
311
 
249
- class HelpShown extends Exit {
250
- constructor() {
251
- super("help shown", 0);
252
- }
253
- }
254
-
255
312
  class Completing {
256
313
  options;
257
314
  positionals;
@@ -262,11 +319,6 @@ class Completing {
262
319
  this.candidates = candidates;
263
320
  }
264
321
  }
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
322
  function applyOutput(color, plain, env = process5.env) {
271
323
  const when = plain === true ? "never" : color ?? "auto";
272
324
  if (when === "auto")
@@ -420,7 +472,6 @@ function parseError(error) {
420
472
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
421
473
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
422
474
  }
423
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
424
475
  function nearestOption(message, options, allowNegative) {
425
476
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
426
477
  if (typed === undefined)
@@ -436,6 +487,61 @@ function nearestOption(message, options, allowNegative) {
436
487
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
437
488
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
438
489
  }
490
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
491
+ var init_args = __esm(() => {
492
+ init_format();
493
+ init_help();
494
+ init_text2();
495
+ init_help();
496
+ init_input();
497
+ DASHES = /^-+/;
498
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
499
+ Exit = class Exit extends Error {
500
+ code;
501
+ hint;
502
+ [EXIT] = true;
503
+ constructor(message, code, hint) {
504
+ super(message);
505
+ this.code = code;
506
+ this.hint = hint;
507
+ }
508
+ static [Symbol.hasInstance](value) {
509
+ if (this !== Exit)
510
+ return Function.prototype[Symbol.hasInstance].call(this, value);
511
+ return typeof value === "object" && value !== null && value[EXIT] === true;
512
+ }
513
+ };
514
+ UsageError = class UsageError extends Exit {
515
+ constructor(message, hint) {
516
+ super(message, 2, hint);
517
+ }
518
+ };
519
+ HelpShown = class HelpShown extends Exit {
520
+ constructor() {
521
+ super("help shown", 0);
522
+ }
523
+ };
524
+ completion = { active: false };
525
+ OUTPUT_OPTIONS = {
526
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
527
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
528
+ };
529
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
530
+ });
531
+
532
+ // ../kit/src/folders.ts
533
+ var SKIPPED_FOLDERS;
534
+ var init_folders = __esm(() => {
535
+ init_user_config();
536
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
537
+ });
538
+
539
+ // src/cli.ts
540
+ import process12 from "process";
541
+
542
+ // ../kit/src/index.ts
543
+ init_args();
544
+
439
545
  // ../kit/src/argv.ts
440
546
  import { readFileSync, realpathSync } from "fs";
441
547
  import { resolve } from "path";
@@ -460,15 +566,73 @@ function scriptArgs(argv = process6.argv.slice(2), cmdline = commandLine(), scri
460
566
  const after = at === -1 ? [] : cmdline.slice(at + 1);
461
567
  return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
462
568
  }
569
+ // ../kit/src/chart.ts
570
+ init_format();
571
+ init_mode();
572
+ init_style();
573
+ init_theme();
574
+ // ../kit/src/ci.ts
575
+ init_args();
576
+ init_format();
577
+
463
578
  // ../kit/src/progress.ts
579
+ init_format();
580
+ init_style();
581
+ init_theme();
464
582
  var ESC = String.fromCharCode(27);
465
583
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
466
584
  var RESET_STYLE = `${ESC}[0m`;
467
585
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
586
+
587
+ // ../kit/src/ci.ts
588
+ init_style();
589
+
590
+ // ../kit/src/tool.ts
591
+ init_format();
468
592
  // ../kit/src/cli.ts
593
+ init_args();
469
594
  import { readFileSync as readFileSync2, realpathSync as realpathSync2 } from "fs";
470
595
  import { dirname as dirname2, join as join2 } from "path";
471
- import process9 from "process";
596
+ import process10 from "process";
597
+
598
+ // ../kit/src/askpass.ts
599
+ import process7 from "process";
600
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
601
+ async function askpassClient(argv) {
602
+ const socketPath = process7.env[SOCKET_VARIABLE];
603
+ if (socketPath === undefined)
604
+ return;
605
+ const request = { prompt: argv[0] ?? "", ...process7.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
606
+ const { promise, resolve } = Promise.withResolvers();
607
+ let received = "";
608
+ try {
609
+ await Bun.connect({
610
+ unix: socketPath,
611
+ socket: {
612
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
613
+ `),
614
+ data: (_, chunk) => {
615
+ received += chunk.toString();
616
+ },
617
+ close: () => resolve(received),
618
+ error: () => resolve("")
619
+ }
620
+ });
621
+ } catch {
622
+ return 1;
623
+ }
624
+ const reply = await promise;
625
+ if (reply === "")
626
+ return 1;
627
+ const { answer } = JSON.parse(reply);
628
+ if (request.notice === true)
629
+ return 0;
630
+ if (answer === undefined)
631
+ return 1;
632
+ process7.stdout.write(`${answer}
633
+ `);
634
+ return 0;
635
+ }
472
636
 
473
637
  // ../kit/src/completions.ts
474
638
  var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
@@ -531,28 +695,34 @@ compdef __kaynooo_cli_complete ${bins.join(" ")}
531
695
  }
532
696
 
533
697
  // ../kit/src/notify.ts
534
- import process7 from "process";
698
+ init_format();
699
+ init_mode();
700
+ import process8 from "process";
535
701
  var NOTIFY_AFTER_MS = 1e4;
536
702
  var CANCELLED = 130;
537
703
  function base64(text) {
538
704
  return Buffer.from(text).toString("base64");
539
705
  }
540
- function notification(title, body, env = process7.env) {
541
- const id = `kit${process7.pid}`;
706
+ function notification(title, body, env = process8.env) {
707
+ const id = `kit${process8.pid}`;
542
708
  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
709
  return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
544
710
  }
545
- function notifyEnd(command, code, ms, { stream = process7.stderr, env = process7.env } = {}) {
711
+ function notifyEnd(command, code, ms, { stream = process8.stderr, env = process8.env } = {}) {
546
712
  if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
547
713
  return;
548
714
  stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
549
715
  }
550
716
 
717
+ // ../kit/src/cli.ts
718
+ init_style();
719
+ init_text2();
720
+
551
721
  // ../kit/src/usage.ts
552
722
  import { appendFileSync, mkdirSync } from "fs";
553
723
  import { homedir } from "os";
554
724
  import { dirname, isAbsolute, join } from "path";
555
- import process8 from "process";
725
+ import process9 from "process";
556
726
 
557
727
  // ../kit/src/logs.ts
558
728
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -566,14 +736,14 @@ var usageError;
566
736
  function noteUsageError(message) {
567
737
  usageError = message;
568
738
  }
569
- function stateHome(env = process8.env) {
739
+ function stateHome(env = process9.env) {
570
740
  const dir = env.XDG_STATE_HOME;
571
741
  return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
572
742
  }
573
- function usagePath(env = process8.env) {
743
+ function usagePath(env = process9.env) {
574
744
  return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
575
745
  }
576
- function usageRecorded(env = process8.env) {
746
+ function usageRecorded(env = process9.env) {
577
747
  const off = env.KAYNOOO_CLI_NO_USAGE;
578
748
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
579
749
  }
@@ -582,12 +752,12 @@ function flagNames(argv) {
582
752
  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
753
  return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
584
754
  }
585
- function usageEntry(bin, command, argv, code, now = new Date) {
755
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
586
756
  const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
587
757
  usageError = undefined;
588
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
758
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
589
759
  }
590
- function recordUsage(entry, env = process8.env) {
760
+ function recordUsage(entry, env = process9.env) {
591
761
  if (!usageRecorded(env))
592
762
  return;
593
763
  try {
@@ -681,8 +851,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
681
851
  `);
682
852
  }
683
853
  function printError(prefix, message, hint, cause) {
684
- const colors = paint(process9.stderr);
685
- const styled = takesControlCodes(process9.stderr);
854
+ const colors = paint(process10.stderr);
855
+ const styled = takesControlCodes(process10.stderr);
686
856
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
687
857
  const under = (label, text, tint) => text === undefined ? "" : `
688
858
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -725,11 +895,11 @@ async function dispatch(level, typed, { version, redact }) {
725
895
  }
726
896
  }
727
897
  if (name === undefined && level.path.length > 1) {
728
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stderr));
898
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process10.stderr));
729
899
  return 2;
730
900
  }
731
901
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
732
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stdout));
902
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process10.stdout));
733
903
  return 0;
734
904
  }
735
905
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -875,6 +1045,9 @@ function packageVersion(entry = Bun.main) {
875
1045
  }
876
1046
  async function runCli(cli, argv = scriptArgs()) {
877
1047
  const version = cli.version ?? packageVersion();
1048
+ const answered = await askpassClient(argv);
1049
+ if (answered !== undefined)
1050
+ return answered;
878
1051
  if (argv[0] === COMPLETE)
879
1052
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
880
1053
  if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
@@ -885,7 +1058,7 @@ async function runCli(cli, argv = scriptArgs()) {
885
1058
  notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
886
1059
  if (cli.usage !== false) {
887
1060
  try {
888
- recordUsage(usageEntry(cli.name, command, argv, code));
1061
+ recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
889
1062
  } catch {}
890
1063
  }
891
1064
  return code;
@@ -905,20 +1078,55 @@ function commandPath(scope, argv) {
905
1078
  }
906
1079
  return path.length === 0 ? undefined : path.join(" ");
907
1080
  }
908
- // ../kit/src/folders.ts
909
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1081
+
1082
+ // ../kit/src/index.ts
1083
+ init_config();
1084
+
1085
+ // ../kit/src/excerpt.ts
1086
+ init_text2();
1087
+
1088
+ // ../kit/src/index.ts
1089
+ init_folders();
1090
+ init_format();
1091
+
1092
+ // ../kit/src/git.ts
1093
+ init_args();
1094
+ // ../kit/src/limit.ts
1095
+ init_args();
1096
+
1097
+ // ../kit/src/index.ts
1098
+ init_mode();
1099
+
1100
+ // ../kit/src/report.ts
1101
+ init_style();
1102
+ init_text2();
910
1103
  // ../kit/src/secrets.ts
911
1104
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
912
1105
  // ../kit/src/sessions.ts
913
1106
  var {Glob } = globalThis.Bun;
914
1107
  var SESSION_FILES = new Glob("*.json");
915
1108
  var ACCOUNT_DIRS = new Glob("*/sessions");
1109
+
1110
+ // ../kit/src/index.ts
1111
+ init_style();
1112
+ init_text2();
1113
+ init_theme();
1114
+ init_user_config();
1115
+
1116
+ // ../kit/src/watch.ts
1117
+ init_args();
1118
+ init_input();
1119
+ init_style();
1120
+ // ../kit/src/workspace-root.ts
1121
+ init_user_config();
916
1122
  // src/commands.ts
917
1123
  import { existsSync as existsSync10, rmSync as rmSync4 } from "fs";
918
- var {$: $8 } = globalThis.Bun;
1124
+ var {$: $9 } = globalThis.Bun;
919
1125
 
920
1126
  // src/errors.ts
921
1127
  import { readFileSync as readFileSync3 } from "fs";
1128
+ var {$ } = globalThis.Bun;
1129
+
922
1130
  class KnownError extends Error {
923
1131
  }
924
1132
  var BOOT_TIME_LINE = /^btime (\d+)$/m;
@@ -935,23 +1143,26 @@ function alive(pid) {
935
1143
  return error.code === "EPERM";
936
1144
  }
937
1145
  }
938
- function failKnown(error) {
1146
+ function knownMessage(error) {
939
1147
  if (error instanceof KnownError)
940
- fail(error.message, 1);
1148
+ return error.message;
1149
+ return error instanceof $.ShellError ? error.stderr.toString().trim() || error.message : undefined;
1150
+ }
1151
+ function failureText(error) {
1152
+ return knownMessage(error) ?? (error instanceof Error ? error.message : String(error));
1153
+ }
1154
+ function failKnown(error) {
1155
+ const message = knownMessage(error);
1156
+ if (message !== undefined)
1157
+ fail(message, 1);
941
1158
  throw error;
942
1159
  }
943
1160
 
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";
1161
+ // src/git.ts
1162
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readdirSync as readdirSync2, rmdirSync } from "fs";
1163
+ import { basename as basename2, dirname as dirname4, join as join5 } from "path";
948
1164
  var {$: $2 } = globalThis.Bun;
949
1165
 
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
1166
  // src/project.ts
956
1167
  import { existsSync as existsSync2, readdirSync, realpathSync as realpathSync3 } from "fs";
957
1168
  import { basename, dirname as dirname3, join as join4 } from "path";
@@ -1032,12 +1243,18 @@ function assertValid(project) {
1032
1243
  async function loadProjects() {
1033
1244
  const settings = await wtConfig();
1034
1245
  const files = existsSync2(settings.manifests) ? readdirSync(settings.manifests).filter((file) => file.endsWith(".ts")).sort() : [];
1035
- return Promise.all(files.map(async (file) => {
1246
+ const projects = await Promise.all(files.map(async (file) => {
1036
1247
  const { default: config } = await import(join4(settings.manifests, file));
1037
1248
  const project = { ...config, root: expandHome(config.root), name: basename(file, ".ts"), settings };
1038
1249
  assertValid(project);
1039
1250
  return project;
1040
1251
  }));
1252
+ for (const [index, project] of projects.entries()) {
1253
+ const twin = projects.slice(0, index).find((other) => basename(other.root) === basename(project.root));
1254
+ if (twin)
1255
+ 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`);
1256
+ }
1257
+ return projects;
1041
1258
  }
1042
1259
  async function findProject(name) {
1043
1260
  const project = (await loadProjects()).find((p) => p.name === name);
@@ -1096,7 +1313,112 @@ async function locateWorktree(cwd, task, projectName) {
1096
1313
  return worktreeOf(here.project, name);
1097
1314
  }
1098
1315
 
1316
+ // src/git.ts
1317
+ async function git2(cwd, ...args) {
1318
+ const result = await $2`git -C ${cwd} ${args}`.quiet().nothrow();
1319
+ return { ok: result.exitCode === 0, out: `${result.stdout.toString()}${result.stderr.toString()}`.trim() };
1320
+ }
1321
+ async function branchExists(repo, branch) {
1322
+ if ((await git2(repo, "show-ref", "--quiet", "--verify", `refs/heads/${branch}`)).ok)
1323
+ return true;
1324
+ return (await git2(repo, "for-each-ref", "--format=%(refname)", `refs/remotes/*/${branch}`)).out !== "";
1325
+ }
1326
+ async function onBranch(repo, dir, branch) {
1327
+ return git2(repo, "worktree", "add", ...await branchExists(repo, branch) ? [dir, branch] : ["-b", branch, dir]);
1328
+ }
1329
+ async function addWorktrees(worktree, branch) {
1330
+ const { project, dir } = worktree;
1331
+ if (existsSync3(dir))
1332
+ throw new WtError(`${dir} already exists: \`wt sync ${worktree.task} -p ${project.name}\` finishes it, \`wt rm ${worktree.task} -p ${project.name}\` removes it`);
1333
+ mkdirSync2(dirname4(dir), { recursive: true });
1334
+ const root = project.repos.length ? await git2(project.root, "worktree", "add", "--detach", dir) : await onBranch(project.root, dir, branch);
1335
+ if (!root.ok)
1336
+ throw new WtError(`git worktree add failed for the root:
1337
+ ${root.out}`);
1338
+ for (const repo of project.repos) {
1339
+ const added = await onBranch(join5(project.root, repo), join5(dir, repo), branch);
1340
+ if (!added.ok) {
1341
+ await removeWorktrees(worktree);
1342
+ throw new WtError(`git worktree add failed for ${repo}, rolled back:
1343
+ ${added.out}`);
1344
+ }
1345
+ }
1346
+ }
1347
+ async function removeWorktrees(worktree) {
1348
+ const { project, dir } = worktree;
1349
+ await Promise.all(project.repos.map(async (repo) => git2(join5(project.root, repo), "worktree", "remove", "--force", join5(dir, repo))));
1350
+ await git2(project.root, "worktree", "remove", "--force", dir);
1351
+ if (existsSync3(dir))
1352
+ await $2`docker run --rm -v ${`${dirname4(dir)}:/parent`} alpine rm -rf ${`/parent/${basename2(dir)}`}`.quiet();
1353
+ await Promise.all([".", ...project.repos].map(async (repo) => git2(join5(project.root, repo), "worktree", "prune")));
1354
+ if (existsSync3(dirname4(dir)) && !readdirSync2(dirname4(dir)).length)
1355
+ rmdirSync(dirname4(dir));
1356
+ }
1357
+ async function dirtyRepos(worktree) {
1358
+ const repos = [".", ...worktree.project.repos];
1359
+ const statuses = await Promise.all(repos.map(async (repo) => git2(join5(worktree.dir, repo), "status", "--porcelain")));
1360
+ return repos.filter((_, index) => statuses[index].ok && statuses[index].out !== "").map((repo) => repo === "." ? "root" : repo);
1361
+ }
1362
+ async function unreachableByRepo(dir, repos) {
1363
+ const all = [".", ...repos];
1364
+ const counts = await Promise.all(all.map(async (repo) => git2(join5(dir, repo), "rev-list", "--count", "HEAD", "--not", "--branches", "--remotes", "--tags")));
1365
+ return all.map((repo, index) => ({ repo: repo === "." ? "root" : repo, count: Number(counts[index].ok ? counts[index].out : 0) })).filter(({ count }) => count > 0);
1366
+ }
1367
+ async function unreachableCommits(worktree) {
1368
+ return (await unreachableByRepo(worktree.dir, worktree.project.repos)).map(({ repo, count }) => `${repo} (${count} commit${count === 1 ? "" : "s"})`);
1369
+ }
1370
+ async function unreachableCount(dir, repos) {
1371
+ return (await unreachableByRepo(dir, repos)).reduce((total, { count }) => total + count, 0);
1372
+ }
1373
+ async function isRegistered(worktree) {
1374
+ const listed = await git2(worktree.project.root, "worktree", "list", "--porcelain");
1375
+ return listed.out.split(`
1376
+ `).includes(`worktree ${worktree.dir}`);
1377
+ }
1378
+ async function currentBranch(dir) {
1379
+ const result = await git2(dir, "rev-parse", "--abbrev-ref", "HEAD");
1380
+ return result.ok ? result.out : "?";
1381
+ }
1382
+
1383
+ // src/routes.ts
1384
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3 } from "fs";
1385
+ import { join as join6 } from "path";
1386
+ var {$: $3 } = globalThis.Bun;
1387
+ var LEADING_STAR = /^\*/;
1388
+ async function mkcert(certFile, keyFile, hosts) {
1389
+ const result = await $3`mkcert -cert-file ${certFile} -key-file ${keyFile} ${hosts}`.quiet().nothrow();
1390
+ if (result.exitCode !== 0)
1391
+ throw new WtError(`mkcert failed for ${hosts.join(" ")}:
1392
+ ${result.stderr.toString()}`);
1393
+ }
1394
+ async function writeStackCerts(worktree) {
1395
+ const { project } = worktree;
1396
+ if (project.certs === undefined)
1397
+ return;
1398
+ const dir = join6(worktree.dir, project.certs);
1399
+ mkdirSync3(dir, { recursive: true });
1400
+ await Promise.all(project.routes.map(async (route) => {
1401
+ const served = worktreeHost(route.host, worktree.task);
1402
+ const name = served.replace(LEADING_STAR, "_wildcard");
1403
+ const cert = join6(dir, `${name}.pem`);
1404
+ const key = join6(dir, `${name}-key.pem`);
1405
+ return existsSync4(cert) && existsSync4(key) ? undefined : mkcert(cert, key, [served]);
1406
+ }));
1407
+ }
1408
+ function urlsOf(worktree) {
1409
+ return worktree.project.routes.filter((route) => !route.host.startsWith("*.")).map((route) => `https://${worktreeHost(route.host, worktree.task)}`);
1410
+ }
1411
+
1412
+ // src/run.ts
1413
+ import { existsSync as existsSync7, mkdirSync as mkdirSync5, readdirSync as readdirSync4, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "fs";
1414
+ import { userInfo } from "os";
1415
+ import { join as join9 } from "path";
1416
+ var {$: $5 } = globalThis.Bun;
1417
+
1099
1418
  // src/compose.ts
1419
+ import { existsSync as existsSync5, readFileSync as readFileSync4 } from "fs";
1420
+ import { join as join7 } from "path";
1421
+ var {$: $4 } = globalThis.Bun;
1100
1422
  var COMPOSE_FILES = ["compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"];
1101
1423
  var SKIP_PROFILE = "wt-skip";
1102
1424
  function composeEnv(overrides = {}) {
@@ -1104,7 +1426,7 @@ function composeEnv(overrides = {}) {
1104
1426
  return { ...Object.fromEntries(env), ...overrides };
1105
1427
  }
1106
1428
  async function composeConfig(dir, env = {}) {
1107
- const result = await $`docker compose config --format json`.cwd(dir).env(composeEnv(env)).quiet().nothrow();
1429
+ const result = await $4`docker compose config --format json`.cwd(dir).env(composeEnv(env)).quiet().nothrow();
1108
1430
  if (result.exitCode !== 0)
1109
1431
  throw new WtError(`docker compose config failed in ${dir}:
1110
1432
  ${result.stderr.toString()}`);
@@ -1113,13 +1435,13 @@ ${result.stderr.toString()}`);
1113
1435
  var COMPOSE_FILE_LINE = /^COMPOSE_FILE=(.*)$/m;
1114
1436
  var QUOTES_AROUND = /^["']|["']$/g;
1115
1437
  function baseComposeFiles(dir, overrides) {
1116
- const envFile = join5(dir, ".env");
1117
- const line = existsSync3(envFile) ? readFileSync4(envFile, "utf8").match(COMPOSE_FILE_LINE) : null;
1438
+ const envFile = join7(dir, ".env");
1439
+ const line = existsSync5(envFile) ? readFileSync4(envFile, "utf8").match(COMPOSE_FILE_LINE) : null;
1118
1440
  const files = line ? line[1].replace(QUOTES_AROUND, "").split(":").filter(Boolean) : [];
1119
1441
  const base = files.filter((file) => !file.startsWith(`${overrides}/`));
1120
1442
  if (base.length)
1121
1443
  return base;
1122
- const found = COMPOSE_FILES.find((file) => existsSync3(join5(dir, file)));
1444
+ const found = COMPOSE_FILES.find((file) => existsSync5(join7(dir, file)));
1123
1445
  if (found === undefined)
1124
1446
  throw new WtError(`no compose file in ${dir}`);
1125
1447
  return [found];
@@ -1215,432 +1537,45 @@ function overrideWarnings(worktree, config) {
1215
1537
  return warnings;
1216
1538
  }
1217
1539
  async function runningProjects() {
1218
- const result = await $`docker compose ls --format json`.quiet().nothrow();
1540
+ const result = await $4`docker compose ls --format json`.quiet().nothrow();
1219
1541
  if (result.exitCode !== 0)
1220
1542
  return new Set;
1221
1543
  return new Set(JSON.parse(result.stdout.toString()).map((stack) => stack.Name));
1222
1544
  }
1223
1545
 
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 "";
1546
+ // src/env_file.ts
1547
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
1548
+
1549
+ // ../env/src/dotenv.ts
1550
+ var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
1551
+ var INLINE_COMMENT = /\s+#.*$/;
1552
+ var CARRIAGE_RETURN = /\r$/;
1553
+ var ESCAPES = { n: `
1554
+ `, r: "\r", t: "\t", '"': '"', "\\": "\\", $: "$" };
1555
+ function closingQuote(text, quote) {
1556
+ for (let index = 0;index < text.length; index++) {
1557
+ if (quote === '"' && text[index] === "\\")
1558
+ index++;
1559
+ else if (text[index] === quote)
1560
+ return index;
1244
1561
  }
1562
+ return -1;
1245
1563
  }
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);
1564
+ function unescapeDollar(text) {
1565
+ return text.replaceAll("\\$", "$");
1566
+ }
1567
+ function unescapeDouble(text) {
1568
+ let out = "";
1569
+ for (let index = 0;index < text.length; index++) {
1570
+ const next = text[index + 1];
1571
+ if (text[index] === "\\" && next !== undefined && next in ESCAPES) {
1572
+ out += ESCAPES[next];
1573
+ index++;
1574
+ } else {
1575
+ out += text[index];
1264
1576
  }
1265
- return await work();
1266
- } finally {
1267
- release();
1268
1577
  }
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;
1578
+ return out;
1644
1579
  }
1645
1580
  function parseDotenv(text) {
1646
1581
  const physical = text.split(`
@@ -1693,7 +1628,54 @@ function entries(file) {
1693
1628
 
1694
1629
  // src/env_file.ts
1695
1630
  function readEnvFile(path) {
1696
- return existsSync7(path) ? Object.fromEntries(entries(parseDotenv(readFileSync7(path, "utf8")))) : {};
1631
+ return existsSync6(path) ? Object.fromEntries(entries(parseDotenv(readFileSync5(path, "utf8")))) : {};
1632
+ }
1633
+
1634
+ // src/queue.ts
1635
+ import { mkdirSync as mkdirSync4, readdirSync as readdirSync3, readFileSync as readFileSync6, rmSync, writeFileSync } from "fs";
1636
+ import { join as join8 } from "path";
1637
+ var queueDir = (settings, name) => join8(settings.state, "queues", name);
1638
+ var POLL_MS = 1000;
1639
+ function liveTickets(dir) {
1640
+ const names = readdirSync3(dir).sort();
1641
+ return names.filter((name) => {
1642
+ const dash = name.indexOf("-");
1643
+ if (Number(name.slice(0, dash)) >= bootTime() && alive(Number(name.slice(dash + 1))))
1644
+ return true;
1645
+ rmSync(join8(dir, name), { force: true });
1646
+ return false;
1647
+ });
1648
+ }
1649
+ function labelOf(ticket) {
1650
+ try {
1651
+ return readFileSync6(ticket, "utf8");
1652
+ } catch {
1653
+ return "";
1654
+ }
1655
+ }
1656
+ async function inLine(dir, label, waiting, work) {
1657
+ mkdirSync4(dir, { recursive: true });
1658
+ const name = `${String(Date.now()).padStart(15, "0")}-${process.pid}`;
1659
+ const ticket = join8(dir, name);
1660
+ const release = () => rmSync(ticket, { force: true });
1661
+ writeFileSync(ticket, label);
1662
+ process.once("exit", release);
1663
+ try {
1664
+ let shown = -1;
1665
+ for (;; ) {
1666
+ const ahead = liveTickets(dir).filter((other) => other < name);
1667
+ if (ahead.length === 0)
1668
+ break;
1669
+ if (ahead.length !== shown) {
1670
+ shown = ahead.length;
1671
+ waiting(ahead.length, labelOf(join8(dir, ahead[0])));
1672
+ }
1673
+ await Bun.sleep(POLL_MS);
1674
+ }
1675
+ return await work();
1676
+ } finally {
1677
+ release();
1678
+ }
1697
1679
  }
1698
1680
 
1699
1681
  // src/run.ts
@@ -1702,8 +1684,8 @@ var DEFAULT_PORT = 5432;
1702
1684
  var READY_TRIES = 60;
1703
1685
  var testContainer = (worktree) => `wt-${worktree.project.name}-test-db`;
1704
1686
  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))));
1687
+ const base = existsSync7(join9(dir, ".env")) ? ".env" : ".env.dist";
1688
+ const env = Object.assign({}, ...[base, ".env.test", ".env.test.local"].map((file) => readEnvFile(join9(dir, file))));
1707
1689
  if (env.DATABASE_URL === undefined || env.DATABASE_URL === "")
1708
1690
  throw new WtError(`no DATABASE_URL in the test env files of ${dir}`);
1709
1691
  const url = new URL(env.DATABASE_URL);
@@ -1724,7 +1706,7 @@ function runPlan(worktree, run, config, database, ids = userInfo(), tty = false)
1724
1706
  const service = config.services[run.service];
1725
1707
  if (!service)
1726
1708
  throw new WtError(`${config.name} has no service ${run.service}`);
1727
- const source = join10(worktree.project.root, run.dir);
1709
+ const source = join9(worktree.project.root, run.dir);
1728
1710
  const target = service.volumes?.find((volume) => volume.type === "bind" && volume.source === source)?.target;
1729
1711
  if (target === undefined)
1730
1712
  throw new WtError(`${run.service} does not bind-mount ${source}, so wt cannot tell where the worktree's copy goes`);
@@ -1770,7 +1752,7 @@ function runPlan(worktree, run, config, database, ids = userInfo(), tty = false)
1770
1752
  "-e",
1771
1753
  `TEST_TOKEN=${testToken(worktree.task)}`,
1772
1754
  "-v",
1773
- `${join10(worktree.dir, run.dir)}:${target}`,
1755
+ `${join9(worktree.dir, run.dir)}:${target}`,
1774
1756
  "-w",
1775
1757
  target,
1776
1758
  service.image ?? `${config.name}-${run.service}`,
@@ -1823,26 +1805,26 @@ async function forgetTestDatabases(worktree) {
1823
1805
  await $5`docker exec ${container} sh -c ${'dropdb -U "$POSTGRES_USER" --force "$0"'} ${name}`.quiet().nothrow();
1824
1806
  }
1825
1807
  const markers = worktree.project.settings.state;
1826
- if (!existsSync8(markers))
1808
+ if (!existsSync7(markers))
1827
1809
  return;
1828
1810
  for (const file of readdirSync4(markers).filter((name) => name.startsWith(`${worktree.id}.test-`)))
1829
- rmSync3(join10(markers, file), { force: true });
1811
+ rmSync2(join9(markers, file), { force: true });
1830
1812
  }
1831
1813
  async function provision(worktree, run, plan, databaseId) {
1832
1814
  const markers = worktree.project.settings.state;
1833
- const marker = join10(markers, `${worktree.id}.test-${databaseId.slice(0, 12)}`);
1834
- if (existsSync8(marker))
1815
+ const marker = join9(markers, `${worktree.id}.test-${databaseId.slice(0, 12)}`);
1816
+ if (existsSync7(marker))
1835
1817
  return;
1836
1818
  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))
1819
+ if (existsSync7(marker))
1838
1820
  return;
1839
1821
  console.error(`wt run: provisioning ${worktree.task}'s test database`);
1840
1822
  for (const step of run.provision) {
1841
1823
  if (await runInherit(["docker", ...plan.runner(["sh", "-c", step])]) !== 0)
1842
1824
  throw new WtError(`provisioning failed on \`${step}\`, run it again with \`wt run ${worktree.task} -- sh -c '${step}'\``);
1843
1825
  }
1844
- mkdirSync6(markers, { recursive: true });
1845
- writeFileSync3(marker, "");
1826
+ mkdirSync5(markers, { recursive: true });
1827
+ writeFileSync2(marker, "");
1846
1828
  });
1847
1829
  }
1848
1830
  async function runTask(task, command, project) {
@@ -1851,7 +1833,7 @@ async function runTask(task, command, project) {
1851
1833
  assertWorktreeExists(worktree);
1852
1834
  if (!run)
1853
1835
  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));
1836
+ const database = testDatabase(join9(worktree.dir, run.dir));
1855
1837
  const plan = runPlan(worktree, run, await composeConfig(root), database, userInfo(), Boolean(process.stdin.isTTY && process.stdout.isTTY));
1856
1838
  await provision(worktree, run, plan, await ensureDatabase(plan, database));
1857
1839
  return runInherit(["docker", ...plan.runner(command)]);
@@ -1862,20 +1844,20 @@ async function runHeavy(command) {
1862
1844
  }
1863
1845
 
1864
1846
  // src/stack.ts
1865
- import { existsSync as existsSync9, mkdirSync as mkdirSync7, writeFileSync as writeFileSync4 } from "fs";
1847
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, writeFileSync as writeFileSync3 } from "fs";
1866
1848
  import { homedir as homedir3 } from "os";
1867
- import { dirname as dirname7 } from "path";
1849
+ import { dirname as dirname6 } from "path";
1868
1850
  var {$: $7 } = globalThis.Bun;
1869
1851
 
1870
1852
  // src/proxy.ts
1871
- import { dirname as dirname6, join as join11 } from "path";
1853
+ import { dirname as dirname5, join as join10 } from "path";
1872
1854
  var {$: $6 } = globalThis.Bun;
1873
- function devproxyArgv() {
1874
- const onPath = Bun.which("devproxy");
1855
+ function devproxyArgv(path = process.env.PATH ?? "") {
1856
+ const onPath = Bun.which("devproxy", { PATH: path });
1875
1857
  if (onPath !== null)
1876
1858
  return [onPath];
1877
1859
  try {
1878
- return [process.execPath, join11(dirname6(Bun.resolveSync("@kaynooo/devproxy", import.meta.dir)), "..", "dist", "cli.js")];
1860
+ return [process.execPath, "--no-env-file", "--config=/dev/null", join10(dirname5(Bun.resolveSync("@kaynooo/devproxy", import.meta.dir)), "..", "dist", "cli.js")];
1879
1861
  } catch {
1880
1862
  return [];
1881
1863
  }
@@ -1904,27 +1886,37 @@ function slugOf(ref) {
1904
1886
  async function spawnInherit(argv, cwd, env = process.env) {
1905
1887
  return Bun.spawn(argv, { cwd, env, stdio: ["inherit", "inherit", "inherit"] }).exited;
1906
1888
  }
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)
1889
+ async function spawnRunner(role, argv, cwd) {
1890
+ try {
1891
+ return await spawnInherit(argv, cwd);
1892
+ } catch (error) {
1893
+ if (error.code === "ENOENT")
1894
+ throw new WtError(`\`${argv[0]}\` is not on PATH: fix runner.${role} in ${configPath()}`);
1895
+ throw error;
1896
+ }
1897
+ }
1898
+ var argvOf = (template, worktree) => fillTemplate(template, { project: worktree.project.name, task: worktree.task, dir: worktree.dir, id: worktree.id });
1899
+ async function runTemplate(role, template, worktree) {
1900
+ const argv = argvOf(template, worktree);
1901
+ if (await spawnRunner(role, argv, worktree.dir) !== 0)
1910
1902
  throw new WtError(`\`${argv.join(" ")}\` failed`);
1911
1903
  }
1912
1904
  async function runSetup(worktree, env = composeEnv()) {
1913
1905
  const setup = worktree.project.setup ?? [];
1914
1906
  const marker = worktree.files.setupMarker;
1915
- if (!setup.length || existsSync9(marker))
1907
+ if (!setup.length || existsSync8(marker))
1916
1908
  return;
1917
1909
  for (const command of setup) {
1918
1910
  if (await spawnInherit(["sh", "-c", command], worktree.dir, env) !== 0)
1919
1911
  throw new WtError(`the worktree setup failed on \`${command}\``);
1920
1912
  }
1921
- mkdirSync7(dirname7(marker), { recursive: true });
1922
- writeFileSync4(marker, "");
1913
+ mkdirSync6(dirname6(marker), { recursive: true });
1914
+ writeFileSync3(marker, "");
1923
1915
  }
1924
1916
  async function stackUp(worktree) {
1925
1917
  const { up } = worktree.project.settings.runner;
1926
1918
  if (up)
1927
- return runTemplate(up, worktree);
1919
+ return runTemplate("up", up, worktree);
1928
1920
  if (await hasDevproxy())
1929
1921
  await devproxyUp();
1930
1922
  const network = worktree.project.settings.proxyNetwork;
@@ -1936,9 +1928,9 @@ async function stackUp(worktree) {
1936
1928
  }
1937
1929
  async function stackDown(worktree) {
1938
1930
  const { down } = worktree.project.settings.runner;
1939
- if (down && existsSync9(worktree.dir))
1940
- return runTemplate(down, worktree);
1941
- const here = existsSync9(worktree.dir);
1931
+ if (down && existsSync8(worktree.dir))
1932
+ return runTemplate("down", down, worktree);
1933
+ const here = existsSync8(worktree.dir);
1942
1934
  const argv = here ? ["docker", "compose", "down", "--remove-orphans"] : ["docker", "compose", "-p", worktree.id, "down", "--remove-orphans"];
1943
1935
  if (await spawnInherit(argv, here ? worktree.dir : homedir3(), composeEnv()) !== 0)
1944
1936
  throw new WtError(`docker compose down failed for ${worktree.id}`);
@@ -1947,15 +1939,256 @@ async function afterRemove(worktree) {
1947
1939
  const { removed } = worktree.project.settings.runner;
1948
1940
  if (!removed)
1949
1941
  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}`);
1942
+ const argv = argvOf(removed, worktree);
1943
+ try {
1944
+ if (await spawnRunner("removed", argv, worktree.project.root) !== 0)
1945
+ console.warn(`wt: \`${argv.join(" ")}\` failed after removing ${worktree.id}`);
1946
+ } catch (error) {
1947
+ if (!(error instanceof WtError))
1948
+ throw error;
1949
+ console.warn(`wt: ${error.message}, after removing ${worktree.id}`);
1950
+ }
1953
1951
  }
1954
1952
  async function hasContainers(composeName) {
1955
1953
  const found = await $7`docker ps -aq --filter ${`label=com.docker.compose.project=${composeName}`}`.quiet().nothrow();
1956
1954
  return found.stdout.toString().trim() !== "";
1957
1955
  }
1958
1956
 
1957
+ // src/files.ts
1958
+ init_text();
1959
+ import { existsSync as existsSync9, lstatSync, mkdirSync as mkdirSync7, readFileSync as readFileSync7, renameSync, rmSync as rmSync3, statSync, symlinkSync, unlinkSync, writeFileSync as writeFileSync4 } from "fs";
1960
+ import { constants } from "os";
1961
+ import { basename as basename3, dirname as dirname7, join as join11 } from "path";
1962
+ var {$: $8 } = globalThis.Bun;
1963
+ var PARTIAL = ".wt-partial";
1964
+ var PAUSE_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
1965
+ function writeIfChanged(path, content) {
1966
+ if (existsSync9(path) && readFileSync7(path, "utf8") === content)
1967
+ return false;
1968
+ mkdirSync7(dirname7(path), { recursive: true });
1969
+ writeFileSync4(path, content);
1970
+ return true;
1971
+ }
1972
+ async function volumeExists(name) {
1973
+ return (await $8`docker volume inspect ${name}`.quiet().nothrow()).exitCode === 0;
1974
+ }
1975
+ async function copyFromMain(worktree) {
1976
+ const warnings = [];
1977
+ for (const entry of worktree.project.copy ?? []) {
1978
+ const source = join11(worktree.project.root, entry);
1979
+ const target = join11(worktree.dir, entry);
1980
+ if (!existsSync9(source)) {
1981
+ warnings.push(`copy: ${entry} does not exist in main`);
1982
+ continue;
1983
+ }
1984
+ if (existsSync9(target))
1985
+ continue;
1986
+ const partial = `${target}${PARTIAL}`;
1987
+ mkdirSync7(dirname7(target), { recursive: true });
1988
+ rmSync3(partial, { recursive: true, force: true });
1989
+ await $8`cp -a --reflink=auto ${source} ${partial}`.quiet();
1990
+ renameSync(partial, target);
1991
+ }
1992
+ return warnings;
1993
+ }
1994
+ function linkFromMain(worktree) {
1995
+ for (const entry of worktree.project.link ?? []) {
1996
+ const source = join11(worktree.project.root, entry);
1997
+ const target = join11(worktree.dir, entry);
1998
+ if (existsSync9(source) && !existsSync9(target)) {
1999
+ mkdirSync7(dirname7(target), { recursive: true });
2000
+ symlinkSync(source, target);
2001
+ }
2002
+ }
2003
+ }
2004
+ var WILDCARD_LABEL = /^\*\./;
2005
+ function rewriteHosts(text, routes, task) {
2006
+ const hosts = [...new Set(routes.map((route) => route.host.replace(WILDCARD_LABEL, "")))].sort((a, b) => b.length - a.length);
2007
+ const pattern = new RegExp(`(?<![\\w.-])(\\.?)(${hosts.map(U).join("|")})(?![\\w.-])`, "g");
2008
+ return text.replace(pattern, (_, dot, host) => `${dot}${worktreeHost(host, task)}`);
2009
+ }
2010
+ function setEnvValue(text, key, value) {
2011
+ const line = `${key}=${value}`;
2012
+ const pattern = new RegExp(`^${U(key)}=.*$`, "m");
2013
+ if (pattern.test(text))
2014
+ return text.replace(pattern, line);
2015
+ return `${text}${text === "" || text.endsWith(`
2016
+ `) ? "" : `
2017
+ `}${line}
2018
+ `;
2019
+ }
2020
+ function expandEnvValue(value, worktree) {
2021
+ return value.replaceAll("{task}", worktree.task).replaceAll("{port}", String(worktree.clientPort));
2022
+ }
2023
+ function writeEnvFiles(worktree) {
2024
+ const { project, task, dir } = worktree;
2025
+ const envFiles = (project.copy ?? []).filter((entry) => basename3(entry).startsWith(".env") && statSync(join11(dir, entry), { throwIfNoEntry: false })?.isFile());
2026
+ for (const entry of new Set([...envFiles, ".env"])) {
2027
+ const file = join11(dir, entry);
2028
+ let text = existsSync9(file) ? rewriteHosts(readFileSync7(file, "utf8"), project.routes, task) : "";
2029
+ for (const [key, value] of Object.entries(project.env?.[entry] ?? {}))
2030
+ text = setEnvValue(text, key, expandEnvValue(value, worktree));
2031
+ if (entry === ".env") {
2032
+ text = setEnvValue(text, "COMPOSE_PROJECT_NAME", worktree.id);
2033
+ text = setEnvValue(text, "COMPOSE_FILE", [...baseComposeFiles(dir, worktree.project.settings.overrides), worktree.files.override].join(":"));
2034
+ }
2035
+ writeIfChanged(file, text);
2036
+ }
2037
+ }
2038
+ function unlinkLegacySymlink(dir, entry) {
2039
+ let path = dir;
2040
+ for (const part of entry.split("/")) {
2041
+ path = join11(path, part);
2042
+ const stat = lstatSync(path, { throwIfNoEntry: false });
2043
+ if (!stat)
2044
+ return;
2045
+ if (stat.isSymbolicLink())
2046
+ return unlinkSync(path);
2047
+ }
2048
+ }
2049
+ async function mainContainers(main, status) {
2050
+ return (await $8`docker ps -q --filter ${`status=${status}`} --filter ${`label=com.docker.compose.project=${main.name}`}`.quiet().text()).split(`
2051
+ `).filter(Boolean);
2052
+ }
2053
+ function unpause(ids) {
2054
+ if (ids.length)
2055
+ Bun.spawnSync(["docker", "unpause", ...ids], { stdout: "ignore", stderr: "ignore" });
2056
+ }
2057
+ async function whilePaused(ids, work, abort, record) {
2058
+ const release = () => {
2059
+ unpause(ids);
2060
+ if (record !== undefined)
2061
+ rmSync3(record, { force: true });
2062
+ };
2063
+ const onSignal = (signal) => {
2064
+ abort?.();
2065
+ release();
2066
+ process.exit(128 + constants.signals[signal]);
2067
+ };
2068
+ for (const signal of PAUSE_SIGNALS)
2069
+ process.once(signal, onSignal);
2070
+ try {
2071
+ if (ids.length) {
2072
+ if (record !== undefined) {
2073
+ mkdirSync7(dirname7(record), { recursive: true });
2074
+ writeFileSync4(record, `${ids.join(`
2075
+ `)}
2076
+ `);
2077
+ }
2078
+ await $8`docker pause ${ids}`.quiet();
2079
+ }
2080
+ return await work();
2081
+ } finally {
2082
+ for (const signal of PAUSE_SIGNALS)
2083
+ process.off(signal, onSignal);
2084
+ release();
2085
+ }
2086
+ }
2087
+ async function settle(copies) {
2088
+ const results = await Promise.allSettled(copies.map(async (copy) => copy()));
2089
+ return results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
2090
+ }
2091
+ var pausedRecord = (worktree) => queueDir(worktree.project.settings, `${worktree.project.name}.paused`);
2092
+ function readPending(file) {
2093
+ return new Set(existsSync9(file) ? readFileSync7(file, "utf8").split(`
2094
+ `).filter(Boolean) : []);
2095
+ }
2096
+ function writePending(file, volumes) {
2097
+ const text = [...volumes].join(`
2098
+ `);
2099
+ if (!text)
2100
+ return rmSync3(file, { force: true });
2101
+ mkdirSync7(dirname7(file), { recursive: true });
2102
+ writeFileSync4(file, `${text}
2103
+ `);
2104
+ }
2105
+ async function cloneData(worktree, main) {
2106
+ 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 () => {
2107
+ const record = pausedRecord(worktree);
2108
+ const recorded = readPending(record);
2109
+ const leftover = recorded.size ? (await mainContainers(main, "paused")).filter((id) => recorded.has(id)) : [];
2110
+ unpause(leftover);
2111
+ rmSync3(record, { force: true });
2112
+ const warnings = leftover.length ? [`clone: unpaused ${leftover.length} of main's containers a clone cut short had left paused`] : [];
2113
+ return [...warnings, ...await cloneInLine(worktree, main)];
2114
+ });
2115
+ }
2116
+ async function cloneInLine(worktree, main) {
2117
+ const warnings = [];
2118
+ const pending = [];
2119
+ const unfinished = readPending(worktree.files.clonesPending);
2120
+ const copyLabel = `wt.clone=${worktree.id}`;
2121
+ const stopCopies = () => {
2122
+ const ids = Bun.spawnSync(["docker", "ps", "-q", "--filter", `label=${copyLabel}`]).stdout.toString().split(`
2123
+ `).filter(Boolean);
2124
+ if (ids.length)
2125
+ Bun.spawnSync(["docker", "rm", "-f", ...ids], { stdout: "ignore", stderr: "ignore" });
2126
+ };
2127
+ for (const entry of worktree.project.clone ?? []) {
2128
+ const source = join11(worktree.project.root, entry);
2129
+ if (existsSync9(source)) {
2130
+ unlinkLegacySymlink(worktree.dir, entry);
2131
+ const target = join11(worktree.dir, entry);
2132
+ if (existsSync9(target))
2133
+ continue;
2134
+ if (!statSync(source).isDirectory())
2135
+ throw new WtError(`clone: ${entry} is not a directory`);
2136
+ const partial = `/to/${basename3(target)}${PARTIAL}`;
2137
+ pending.push({
2138
+ copy: async () => {
2139
+ mkdirSync7(dirname7(target), { recursive: true });
2140
+ 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();
2141
+ }
2142
+ });
2143
+ continue;
2144
+ }
2145
+ const volume = main.volumes?.[entry];
2146
+ if (!volume) {
2147
+ warnings.push(`clone: ${entry} is neither a path in main nor a volume of its stack`);
2148
+ continue;
2149
+ }
2150
+ if (volume.driver_opts?.device !== undefined && volume.driver_opts.device !== "")
2151
+ throw new WtError(`clone: volume ${entry} is a bind to ${volume.driver_opts.device}, list that path instead`);
2152
+ const sourceVolume = volume.name ?? `${main.name}_${entry}`;
2153
+ const targetVolume = `${worktree.id}_${entry}`;
2154
+ if (await volumeExists(targetVolume)) {
2155
+ if (!unfinished.has(targetVolume))
2156
+ continue;
2157
+ const removed = await $8`docker volume rm ${targetVolume}`.quiet().nothrow();
2158
+ if (removed.exitCode !== 0)
2159
+ 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}\``);
2160
+ }
2161
+ if (!await volumeExists(sourceVolume)) {
2162
+ warnings.push(`clone: main has no volume ${sourceVolume} yet, the worktree starts with an empty one`);
2163
+ continue;
2164
+ }
2165
+ pending.push({
2166
+ volume: targetVolume,
2167
+ copy: async () => {
2168
+ await $8`docker volume create --label ${`com.docker.compose.project=${worktree.id}`} --label ${`com.docker.compose.volume=${entry}`} ${targetVolume}`.quiet();
2169
+ await $8`docker run --rm --label ${copyLabel} -v ${`${sourceVolume}:/from:ro`} -v ${`${targetVolume}:/to`} alpine cp -a /from/. /to/`.quiet();
2170
+ unfinished.delete(targetVolume);
2171
+ }
2172
+ });
2173
+ }
2174
+ if (!pending.length) {
2175
+ writePending(worktree.files.clonesPending, unfinished);
2176
+ return warnings;
2177
+ }
2178
+ for (const { volume } of pending) {
2179
+ if (volume !== undefined)
2180
+ unfinished.add(volume);
2181
+ }
2182
+ writePending(worktree.files.clonesPending, unfinished);
2183
+ const failures = await whilePaused(await mainContainers(main, "running"), async () => settle(pending.map(({ copy }) => copy)), stopCopies, pausedRecord(worktree));
2184
+ writePending(worktree.files.clonesPending, unfinished);
2185
+ if (failures.length)
2186
+ throw new WtError(`clone failed, \`wt sync ${worktree.task}\` starts it again:
2187
+ ${failures.map(failureText).join(`
2188
+ `)}`);
2189
+ return warnings;
2190
+ }
2191
+
1959
2192
  // src/sync.ts
1960
2193
  async function syncWorktree(worktree) {
1961
2194
  assertWorktreeExists(worktree);
@@ -1976,20 +2209,20 @@ async function syncWorktree(worktree) {
1976
2209
  var ANONYMOUS_VOLUME = /^[0-9a-f]{64}$/;
1977
2210
  var WHITESPACE = /\s+/;
1978
2211
  async function anonymousVolumes(worktree) {
1979
- const containers = (await $8`docker ps -aq --filter ${`label=com.docker.compose.project=${worktree.id}`}`.quiet().text()).split(`
2212
+ const containers = (await $9`docker ps -aq --filter ${`label=com.docker.compose.project=${worktree.id}`}`.quiet().text()).split(`
1980
2213
  `).filter(Boolean);
1981
2214
  if (!containers.length)
1982
2215
  return [];
1983
- const mounts = await $8`docker inspect --format ${'{{range .Mounts}}{{if eq .Type "volume"}}{{.Name}} {{end}}{{end}}'} ${containers}`.quiet().nothrow();
2216
+ const mounts = await $9`docker inspect --format ${'{{range .Mounts}}{{if eq .Type "volume"}}{{.Name}} {{end}}{{end}}'} ${containers}`.quiet().nothrow();
1984
2217
  return mounts.text().split(WHITESPACE).filter((name) => ANONYMOUS_VOLUME.test(name));
1985
2218
  }
1986
2219
  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(`
2220
+ const named = (await $9`docker volume ls -q --filter ${`label=com.docker.compose.project=${worktree.id}`}`.quiet().text()).split(`
1988
2221
  `).filter((volume) => volume.startsWith(`${worktree.id}_`));
1989
2222
  const volumes = [...new Set([...named, ...anonymous])];
1990
2223
  if (!volumes.length)
1991
2224
  return;
1992
- const removed = await $8`docker volume rm ${volumes}`.quiet().nothrow();
2225
+ const removed = await $9`docker volume rm ${volumes}`.quiet().nothrow();
1993
2226
  if (removed.exitCode !== 0)
1994
2227
  throw new WtError(`could not remove the volumes of ${worktree.id}:
1995
2228
  ${removed.stderr.toString().trim()}`);
@@ -2003,8 +2236,9 @@ async function addTask(task, branch, options) {
2003
2236
  await syncWorktree(worktree);
2004
2237
  } catch (error) {
2005
2238
  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)}
2239
+ const message = knownMessage(error);
2240
+ if (message !== undefined)
2241
+ throw new WtError(`${message}
2008
2242
  ${way}`);
2009
2243
  console.error(`wt: ${way}`);
2010
2244
  throw error;
@@ -2034,6 +2268,7 @@ async function assertRemovable(task, options) {
2034
2268
  if (!existsSync10(worktree.dir) && !Object.values(worktree.files).some((file) => existsSync10(file)) && !await isRegistered(worktree))
2035
2269
  throw new WtError(`no worktree ${worktree.task} of ${worktree.project.name}, nothing removed`);
2036
2270
  await refuseLosingWork(worktree, options.force === true);
2271
+ return worktree;
2037
2272
  }
2038
2273
  async function removeTask(task, options) {
2039
2274
  const worktree = await locateWorktree(process.cwd(), task, options.project);
@@ -2186,7 +2421,7 @@ async function initProject(dir, options) {
2186
2421
  // src/jobs.ts
2187
2422
  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
2423
  import { join as join13 } from "path";
2189
- var {$: $9 } = globalThis.Bun;
2424
+ var {$: $10 } = globalThis.Bun;
2190
2425
  var HELD_ENV = "WT_JOBS_HELD";
2191
2426
  var STARTING_MS = 30000;
2192
2427
  var TAKEOVER_MS = 5000;
@@ -2271,7 +2506,7 @@ function logTail(file, lines = 5) {
2271
2506
  }
2272
2507
  async function notify(app, title, body, critical = false) {
2273
2508
  if (Bun.which("notify-send") !== null)
2274
- await $9`notify-send -a ${app} ${critical ? ["-u", "critical"] : []} ${title} ${body}`.quiet().nothrow();
2509
+ await $10`notify-send -a ${app} ${critical ? ["-u", "critical"] : []} ${title} ${body}`.quiet().nothrow();
2275
2510
  }
2276
2511
 
2277
2512
  class Jobs {
@@ -2393,7 +2628,7 @@ class Jobs {
2393
2628
  try {
2394
2629
  return await action() ?? 0;
2395
2630
  } catch (error) {
2396
- const message = error instanceof Error ? error.message : String(error);
2631
+ const message = failureText(error);
2397
2632
  await this.failDetached(message);
2398
2633
  if (bg !== undefined)
2399
2634
  await this.notifyRefused(bg, message);
@@ -2434,7 +2669,8 @@ async function attempt(work) {
2434
2669
  await work();
2435
2670
  return 0;
2436
2671
  } catch (error) {
2437
- console.error(error instanceof KnownError ? `error: ${error.message}` : error);
2672
+ const message = knownMessage(error);
2673
+ console.error(message !== undefined ? `error: ${message}` : error);
2438
2674
  return 1;
2439
2675
  }
2440
2676
  }
@@ -2521,19 +2757,26 @@ function shellWrapper(shell) {
2521
2757
  async function jobs() {
2522
2758
  return new Jobs({ dir: (await wtConfig()).jobs, app: "wt" });
2523
2759
  }
2524
- async function guarded(action) {
2760
+ async function guarded(action, bg) {
2525
2761
  try {
2526
- return await (await jobs()).guarded(action);
2762
+ return await (await jobs()).guarded(action, bg);
2527
2763
  } catch (error) {
2528
2764
  return failKnown(error);
2529
2765
  }
2530
2766
  }
2767
+ function bgName(values, ...words) {
2768
+ return values.bg ? ["wt", ...words.filter((word) => word !== undefined)].join(" ") : undefined;
2769
+ }
2531
2770
  async function projectNames() {
2532
- return (await loadProjects()).map((project) => project.name);
2771
+ try {
2772
+ return (await loadProjects()).map((project) => project.name);
2773
+ } catch {
2774
+ return [];
2775
+ }
2533
2776
  }
2534
2777
  async function taskNames() {
2535
2778
  try {
2536
- return listTasks((await locate(process11.cwd())).project);
2779
+ return listTasks((await locate(process12.cwd())).project);
2537
2780
  } catch {
2538
2781
  return [];
2539
2782
  }
@@ -2541,8 +2784,7 @@ async function taskNames() {
2541
2784
  var TASK = { "[task]": taskNames, "<task>": taskNames };
2542
2785
  var PROJECT_OPTION = { type: "string", short: "p", candidates: projectNames, description: "manifest to use instead of the one the current directory belongs to" };
2543
2786
  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);
2787
+ async function asWorktreeJob(verb, { project, task }, options, argv, work) {
2546
2788
  const ref = `${project.name}/${task}`;
2547
2789
  const stack = { ref, slug: slugOf(ref) };
2548
2790
  const queue = await jobs();
@@ -2552,13 +2794,8 @@ async function asWorktreeJob(verb, task, options, argv, work) {
2552
2794
  queue.forget(stack);
2553
2795
  return code;
2554
2796
  }
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
- }
2797
+ const job = queue.detach(stack, verb, [import.meta.path, ...argv, "-p", project.name]);
2798
+ console.log(`wt: ${verb} ${ref} runs out of sight, its output in ${job.log}`);
2562
2799
  return 0;
2563
2800
  }
2564
2801
  var ADD_USAGE = `wt add <task> [branch] [-p <name>] [--bg]
@@ -2626,7 +2863,7 @@ var TASKS_USAGE = `wt tasks [-p <name>]
2626
2863
  Prints the worktree names of the project, one per line.
2627
2864
 
2628
2865
  Exits 0 when it printed them, 1 when there is no such project, 2 on a usage error.`;
2629
- process11.exitCode = await runCli({
2866
+ process12.exitCode = await runCli({
2630
2867
  name: "wt",
2631
2868
  about: "git worktrees of a compose project, each with its own stack, data and <task>.<host> subdomains beside main",
2632
2869
  replaces: "a second clone, port juggling and a shared database to try a branch",
@@ -2636,7 +2873,10 @@ process11.exitCode = await runCli({
2636
2873
  summary: "create a worktree, copy its files and data from main, and route its subdomains",
2637
2874
  run: async (args) => {
2638
2875
  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)));
2876
+ return guarded(async () => {
2877
+ const worktree = worktreeOf((await locate(process12.cwd(), values.project)).project, task);
2878
+ return asWorktreeJob("add", worktree, values, ["add", task, ...branch === undefined ? [] : [branch]], async () => addTask(task, branch, values));
2879
+ }, bgName(values, "add", task));
2640
2880
  }
2641
2881
  },
2642
2882
  sync: {
@@ -2644,8 +2884,9 @@ process11.exitCode = await runCli({
2644
2884
  run: async (args) => {
2645
2885
  const { values, positionals: [task] } = parse(args, SYNC_USAGE, { project: PROJECT_OPTION }, { positionals: ["[task]"], candidates: TASK });
2646
2886
  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));
2887
+ const worktree = await locateWorktree(process12.cwd(), task, values.project);
2888
+ assertWorktreeExists(worktree);
2889
+ return asWorktreeJob("sync", worktree, values, ["sync", worktree.task], async () => syncTask(worktree.task, values));
2649
2890
  });
2650
2891
  }
2651
2892
  },
@@ -2658,9 +2899,9 @@ process11.exitCode = await runCli({
2658
2899
  bg: BG_OPTION
2659
2900
  }, { positionals: ["<task>"], candidates: TASK });
2660
2901
  return guarded(async () => {
2661
- await assertRemovable(task, values);
2662
- return asWorktreeJob("rm", task, values, ["rm", task, ...values.force ? ["--force"] : []], async () => removeTask(task, values));
2663
- });
2902
+ const worktree = await assertRemovable(task, values);
2903
+ return asWorktreeJob("rm", worktree, values, ["rm", task, ...values.force ? ["--force"] : []], async () => removeTask(task, values));
2904
+ }, bgName(values, "rm", task));
2664
2905
  }
2665
2906
  },
2666
2907
  up: {
@@ -2668,9 +2909,10 @@ process11.exitCode = await runCli({
2668
2909
  run: async (args) => {
2669
2910
  const { values, positionals: [task] } = parse(args, UP_USAGE, { project: PROJECT_OPTION, bg: BG_OPTION }, { positionals: ["[task]"], candidates: TASK });
2670
2911
  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
- });
2912
+ const worktree = await locateWorktree(process12.cwd(), task, values.project);
2913
+ assertWorktreeExists(worktree);
2914
+ return asWorktreeJob("up", worktree, values, ["up", worktree.task], async () => upTask(worktree));
2915
+ }, bgName(values, "up", task));
2674
2916
  }
2675
2917
  },
2676
2918
  down: {
@@ -2678,9 +2920,10 @@ process11.exitCode = await runCli({
2678
2920
  run: async (args) => {
2679
2921
  const { values, positionals: [task] } = parse(args, DOWN_USAGE, { project: PROJECT_OPTION, bg: BG_OPTION }, { positionals: ["[task]"], candidates: TASK });
2680
2922
  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
- });
2923
+ const worktree = await locateWorktree(process12.cwd(), task, values.project);
2924
+ assertWorktreeExists(worktree);
2925
+ return asWorktreeJob("down", worktree, values, ["down", worktree.task], async () => downTask(worktree));
2926
+ }, bgName(values, "down", task));
2684
2927
  }
2685
2928
  },
2686
2929
  ls: {
@@ -2708,7 +2951,7 @@ process11.exitCode = await runCli({
2708
2951
  name: { type: "string", description: "the manifest's name, also hashed into the dev server port (the checkout's folder name)" },
2709
2952
  print: { type: "boolean", description: "print the draft instead of writing it" }
2710
2953
  }, { positionals: ["[dir]"] });
2711
- return guarded(async () => initProject(dir ?? process11.cwd(), values));
2954
+ return guarded(async () => initProject(dir ?? process12.cwd(), values));
2712
2955
  }
2713
2956
  },
2714
2957
  run: {