@oya-ai/cli 1.0.232 → 1.0.235

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.
Files changed (3) hide show
  1. package/README.md +8 -0
  2. package/dist/index.js +1642 -156
  3. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -59,6 +59,7 @@ var VALUE_FLAGS = {
59
59
  provider: "--provider cdp",
60
60
  "queue-ms": "--queue-ms 30000",
61
61
  role: "--role operator",
62
+ target: "--target k8s",
62
63
  tz: "--tz Europe/Berlin",
63
64
  url: "--url http://127.0.0.1:3100",
64
65
  "ws-url": "--ws-url ws://127.0.0.1:9222"
@@ -122,8 +123,8 @@ function readJsonFile(file) {
122
123
  }
123
124
 
124
125
  // src/install.ts
125
- import { writeFileSync as writeFileSync3 } from "fs";
126
- import { join as join5 } from "path";
126
+ import { writeFileSync as writeFileSync4 } from "fs";
127
+ import { join as join7 } from "path";
127
128
 
128
129
  // src/prompt/style.ts
129
130
  import { stdout } from "process";
@@ -133,6 +134,13 @@ var DEFAULT_COLUMNS = 80;
133
134
  var DEFAULT_ROWS = 24;
134
135
  var MAX_RULE_WIDTH = 74;
135
136
  var SPINNER_FRAME_MS = 80;
137
+ var SETUP_CONTENT_COLUMNS = 72;
138
+ var SETUP_INSET = 4;
139
+ var TAB_COLUMNS = 8;
140
+ var PRINTABLE_START = 32;
141
+ var DELETE_CODE = 127;
142
+ var WIDE_CELL_WIDTH = 2;
143
+ var CHOICE_INSET = 2;
136
144
 
137
145
  // src/prompt/style.ts
138
146
  var ESC = "\x1B";
@@ -228,14 +236,144 @@ function plainSpinner(label) {
228
236
 
229
237
  // src/prompt/lines.ts
230
238
  import { createInterface } from "readline";
231
- import { stdin, stdout as stdout3 } from "process";
239
+ import { stdin, stdout as stdout4 } from "process";
240
+
241
+ // src/prompt/layout.ts
242
+ import { stdout as stdout3 } from "process";
243
+ var ANSI = new RegExp(`${ESC}\\[[0-9;]*m`, "g");
244
+ var ZERO_WIDTH = /(?:\p{Mark}|\u200d|\ufe0e|\ufe0f)/u;
245
+ var WIDE = /[\u1100-\u115f\u2329\u232a\u2e80-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe10-\ufe6f\uff01-\uff60\uffe0-\uffe6\u{1f300}-\u{1faff}]/u;
246
+ var EMOJI = /(?:\p{Emoji_Presentation}|\p{Regional_Indicator}|\u20e3|\ufe0f)/u;
247
+ var GRAPHEMES = new Intl.Segmenter(void 0, { granularity: "grapheme" });
248
+ var displayText = (value) => Array.from(value.replace(ANSI, "")).filter((char) => !controlCharacter(char)).join("");
249
+ function controlCharacter(char) {
250
+ const code = char.charCodeAt(0);
251
+ return code < PRINTABLE_START || code === DELETE_CODE;
252
+ }
253
+ function cellWidth(value) {
254
+ return Array.from(GRAPHEMES.segment(value.replace(ANSI, "")), (part) => part.segment).reduce((width2, char) => {
255
+ if (char === " ") return width2 + TAB_COLUMNS - width2 % TAB_COLUMNS;
256
+ if (Array.from(char).every((part) => ZERO_WIDTH.test(part)) || controlCharacter(char)) return width2;
257
+ return width2 + (WIDE.test(char) || EMOJI.test(char) ? WIDE_CELL_WIDTH : 1);
258
+ }, 0);
259
+ }
260
+ var contentColumns = () => Math.max(1, Math.min((stdout3.columns || DEFAULT_COLUMNS) - SETUP_INSET, SETUP_CONTENT_COLUMNS));
261
+ function wrapProse(value, columns = contentColumns()) {
262
+ const lines = [];
263
+ for (const word of displayText(value).split(/\s+/).filter(Boolean)) {
264
+ const last = lines.at(-1);
265
+ if (!last || cellWidth(`${last} ${word}`) > columns) lines.push(word);
266
+ else lines[lines.length - 1] += ` ${word}`;
267
+ }
268
+ return lines.length ? lines : [""];
269
+ }
270
+ var terminalRows = (value, columns = stdout3.columns || DEFAULT_COLUMNS) => Math.max(1, Math.ceil(cellWidth(value) / columns));
271
+ function labelValue(label, value) {
272
+ const safe = displayText(value), line = `${label} ${safe}`;
273
+ return cellWidth(line) <= contentColumns() ? [line] : [label, ` ${safe}`];
274
+ }
275
+
276
+ // src/prompt/plain-input.ts
277
+ var emptySnapshot = () => ({ value: "", cursor: 0, width: 0 });
278
+ var PlainInput = class {
279
+ /** The existing reader supplies its accepted editing state. */
280
+ line;
281
+ /** Destination chosen by the existing reader. */
282
+ output;
283
+ /** Current visible prompt, including its rail. */
284
+ prompt;
285
+ /** Last state actually rendered. */
286
+ previous = emptySnapshot();
287
+ constructor(line, output, prompt) {
288
+ this.line = line;
289
+ this.output = output;
290
+ this.prompt = prompt;
291
+ }
292
+ /** Each question starts without retaining the previous answer. */
293
+ reset() {
294
+ this.previous = emptySnapshot();
295
+ }
296
+ /** Internal ANSI refresh calls are replaced with the reader's current nonsecret state. */
297
+ write(text) {
298
+ if (text.includes("\n")) return this.newLine();
299
+ const next = this.snapshot();
300
+ if (next.value === this.previous.value && next.cursor === this.previous.cursor) return;
301
+ this.render(next);
302
+ this.previous = next;
303
+ }
304
+ /** A submitted line ends its display snapshot before the next question starts. */
305
+ newLine() {
306
+ this.output.write("\n");
307
+ this.reset();
308
+ }
309
+ /** Measure the current line without interpreting control bytes as display instructions. */
310
+ snapshot() {
311
+ const value = this.line.line || "", cursor = this.line.cursor ?? value.length;
312
+ return { value: displayText(value), cursor: cellWidth(value.slice(0, cursor)), width: cellWidth(value) };
313
+ }
314
+ /** Ordinary typing appends; corrections repaint only a short active input row. */
315
+ render(next) {
316
+ if (this.appending(next)) {
317
+ this.output.write(next.value.slice(this.previous.value.length));
318
+ return;
319
+ }
320
+ const width2 = cellWidth(this.prompt()) + Math.max(next.width, this.previous.width);
321
+ if (this.output.isTTY && width2 < (this.output.columns || DEFAULT_COLUMNS)) this.replace(next);
322
+ else this.output.write(`
323
+ ${this.prompt()}${next.value}`);
324
+ }
325
+ /** Fast-path appends keep ordinary plain transcripts concise. */
326
+ appending(next) {
327
+ return next.value.startsWith(this.previous.value) && this.previous.cursor === this.previous.width && next.cursor === next.width;
328
+ }
329
+ /** Basic carriage return/backspace edits stay inside the one input row and emit no ANSI. */
330
+ replace(next) {
331
+ const padding = Math.max(0, this.previous.width - next.width);
332
+ const back = next.width - next.cursor + padding;
333
+ this.output.write(`\r${this.prompt()}${next.value}${" ".repeat(padding)}${"\b".repeat(back)}`);
334
+ }
335
+ };
336
+
337
+ // src/prompt/readline-output.ts
338
+ function completeWrite(args) {
339
+ const callback = args.at(-1);
340
+ if (typeof callback === "function") callback();
341
+ }
342
+ function filteredWrite(output, filter) {
343
+ return (...args) => {
344
+ if (!filter(String(args[0]))) return Reflect.apply(output.write, output, args);
345
+ completeWrite(args);
346
+ return true;
347
+ };
348
+ }
349
+ function streamProperty(output, key, write) {
350
+ if (key === "write") return write;
351
+ const value = Reflect.get(output, key, output);
352
+ return typeof value === "function" ? value.bind(output) : value;
353
+ }
354
+ function readlineOutput(output, filter) {
355
+ const write = filteredWrite(output, filter);
356
+ return new Proxy(output, { get: (target, key) => streamProperty(target, key, write) });
357
+ }
358
+
359
+ // src/prompt/lines.ts
232
360
  var rl = null;
233
361
  var masked = false;
362
+ var maskCells = 0;
234
363
  var pending = [];
235
364
  var waiter = null;
236
365
  var ended = false;
237
366
  var linesRead = 0;
367
+ var interrupted = false;
368
+ var eofLine = false;
369
+ var currentPrompt = "";
370
+ var setupPlainInput = false;
371
+ var setupInput = false;
372
+ var plainInput = null;
373
+ var readerKeys = [];
374
+ var readerResize = [];
238
375
  function readLine(line) {
376
+ eofLine = false;
239
377
  linesRead++;
240
378
  deliver(line);
241
379
  }
@@ -248,33 +386,94 @@ function deliver(line) {
248
386
  }
249
387
  function close() {
250
388
  ended = true;
251
- if (waiter) deliver("");
389
+ if (waiter) {
390
+ eofLine = true;
391
+ deliver("");
392
+ }
393
+ }
394
+ function interruptLine() {
395
+ interrupted = true;
396
+ stdout4.write("\n");
397
+ rl?.close();
252
398
  }
253
399
  function maskEcho(line) {
254
400
  const asAny = line;
255
- asAny._writeToOutput = (s) => {
256
- if (masked) asAny.output.write(s.includes("\n") ? "\n" : "*");
257
- else asAny.output.write(s);
401
+ const output = asAny.output;
402
+ const display = new PlainInput(line, output, () => currentPrompt);
403
+ plainInput = display;
404
+ connectEcho(asAny, output, display);
405
+ }
406
+ function connectEcho(echo, output, display) {
407
+ echo.output = readlineOutput(output, (text) => plainWrite(display, output, text));
408
+ echo._writeToOutput = (s) => {
409
+ if (masked) writeMask(output, s.includes("\n"));
410
+ else if (setupPlainInput) display.write(s);
411
+ else output.write(s);
258
412
  };
259
413
  }
414
+ function plainWrite(display, output, text) {
415
+ if (!setupPlainInput) return false;
416
+ if (!masked) display.write(text);
417
+ else if (!text.includes(ESC)) writeMask(output, text.includes("\n"));
418
+ return true;
419
+ }
420
+ function writeMask(output, newline) {
421
+ if (!newline) maskCells++;
422
+ output.write(newline ? "\n" : "*");
423
+ }
424
+ var maskedCells = () => maskCells;
260
425
  function iface() {
261
426
  if (rl) return rl;
262
- rl = createInterface({ input: stdin, output: stdout3, terminal: !!stdin.isTTY });
427
+ rl = createReader();
428
+ rl.setPrompt(currentPrompt);
263
429
  rl.on("line", readLine);
264
430
  rl.on("close", close);
431
+ rl.on("SIGINT", interruptLine);
265
432
  maskEcho(rl);
266
433
  return rl;
267
434
  }
435
+ function createReader() {
436
+ const keys = new Set(stdin.listeners("keypress")), resize = new Set(stdout4.listeners("resize"));
437
+ const line = openReader();
438
+ readerKeys = addedListeners(keys, stdin.listeners("keypress"));
439
+ readerResize = addedListeners(resize, stdout4.listeners("resize"));
440
+ return line;
441
+ }
442
+ function openReader() {
443
+ return createInterface({
444
+ input: stdin,
445
+ output: stdout4,
446
+ terminal: !!stdin.isTTY,
447
+ historySize: setupInput ? 0 : void 0
448
+ });
449
+ }
450
+ function addedListeners(before, after) {
451
+ return after.filter((listener) => !before.has(listener));
452
+ }
453
+ function setLinePrompt(value, setup = false) {
454
+ currentPrompt = value;
455
+ setupInput = setup;
456
+ setupPlainInput = setup && plain;
457
+ plainInput?.reset();
458
+ rl?.setPrompt(value);
459
+ }
268
460
  function nextLine() {
269
461
  const queued = pending.shift();
270
- if (queued !== void 0) return Promise.resolve(queued);
271
- if (ended) return Promise.resolve("");
462
+ if (queued !== void 0) return resolvedLine(queued, false);
463
+ if (ended) return resolvedLine("", true);
272
464
  iface();
273
- return new Promise((resolve) => {
274
- waiter = resolve;
465
+ return new Promise((resolve2) => {
466
+ waiter = resolve2;
275
467
  });
276
468
  }
469
+ function resolvedLine(value, eof) {
470
+ eofLine = eof;
471
+ return Promise.resolve(value);
472
+ }
473
+ var inputInterrupted = () => interrupted;
474
+ var lineWasEOF = () => eofLine;
277
475
  function setMasked(on) {
476
+ if (on) maskCells = 0;
278
477
  masked = on;
279
478
  }
280
479
  function answered() {
@@ -284,39 +483,59 @@ function inputExhausted() {
284
483
  return ended && !pending.length;
285
484
  }
286
485
  function pauseLines() {
287
- rl?.pause();
486
+ for (const listener of readerKeys) stdin.off("keypress", listener);
487
+ for (const listener of readerResize) stdout4.off("resize", listener);
488
+ if (rl && !ended) rl.pause();
288
489
  }
289
490
  function resumeLines() {
290
- rl?.resume();
491
+ if (!rl || ended) return;
492
+ for (const listener of readerKeys)
493
+ if (!stdin.listeners("keypress").includes(listener)) stdin.on("keypress", listener);
494
+ for (const listener of readerResize)
495
+ if (!stdout4.listeners("resize").includes(listener)) stdout4.on("resize", listener);
496
+ rl.resume();
291
497
  }
292
498
  function closePrompts() {
293
499
  if (stdin.isTTY && stdin.isRaw) stdin.setRawMode(false);
294
500
  rl?.close();
295
501
  rl = null;
502
+ plainInput = null;
503
+ readerKeys = [];
504
+ readerResize = [];
505
+ stdin.pause();
296
506
  }
297
507
 
298
508
  // src/prompt/ask.ts
299
- import { stdin as stdin2, stdout as stdout4 } from "process";
509
+ import { stdin as stdin2, stdout as stdout5 } from "process";
300
510
  var InputError = class extends Error {
301
511
  };
302
512
  function unmask() {
303
513
  setMasked(false);
304
- stdout4.write("\n");
514
+ stdout5.write("\n");
305
515
  }
306
- async function readAnswer(fallback, secret) {
307
- setMasked(secret);
516
+ async function readAnswer(fallback, options) {
517
+ setMasked(!!options.secret);
308
518
  try {
309
- return (await nextLine()).trim() || fallback;
519
+ const raw = await nextLine();
520
+ options.presentation?.input(options.secret ? maskedCells() : cellWidth(raw));
521
+ return acceptedLine(raw, fallback, options);
310
522
  } finally {
311
- if (secret) unmask();
523
+ if (options.secret) unmask();
312
524
  }
313
525
  }
526
+ function acceptedLine(raw, fallback, options) {
527
+ if (inputInterrupted()) throw new InputError("Cancelled.");
528
+ if ((options.requireInput || options.presentation) && lineWasEOF())
529
+ throw new InputError("Input ended before setup was complete. Use --yes or --config for unattended installs.");
530
+ return raw.trim() || fallback;
531
+ }
314
532
  function check(answer, options) {
315
- if (!stdin2.isTTY && !options.secret) stdout4.write(`${answer}
533
+ if (!stdin2.isTTY && !options.secret) stdout5.write(`${answer}
316
534
  `);
317
535
  const problem = options.validate?.(answer);
318
536
  if (!problem) return answer;
319
- stdout4.write(` ${icon.fail} ${style.red(problem)}
537
+ if (options.presentation) options.presentation.problem(problem);
538
+ else stdout5.write(` ${icon.fail} ${style.red(problem)}
320
539
  `);
321
540
  if (inputExhausted()) throw new InputError(problem);
322
541
  return void 0;
@@ -324,19 +543,33 @@ function check(answer, options) {
324
543
  async function readValidated(render, fallback, options) {
325
544
  for (; ; ) {
326
545
  render();
327
- const accepted = check(await readAnswer(fallback, !!options.secret), options);
328
- if (accepted !== void 0) return accepted;
546
+ const accepted = check(await readAnswer(fallback, options), options);
547
+ if (accepted !== void 0) {
548
+ options.presentation?.complete(options.secret ? "Provided" : accepted);
549
+ return accepted;
550
+ }
329
551
  }
330
552
  }
331
553
  function ask(question, fallback = "", options = {}) {
332
- return readValidated(
333
- () => stdout4.write(` ${style.green("?")} ${question}${fallback ? style.grey(` (${fallback})`) : ""} `),
334
- fallback,
335
- options
336
- );
554
+ options.presentation?.begin(question, fallback, !!options.secret);
555
+ return questionResult(() => renderPrompt(question, fallback, options), fallback, options);
556
+ }
557
+ function questionResult(render, fallback, options) {
558
+ return readValidated(render, fallback, options).catch((err) => {
559
+ if (inputInterrupted()) options.presentation?.cancel();
560
+ throw err;
561
+ });
562
+ }
563
+ function promptText(question, fallback, options) {
564
+ return options.presentation?.prompt() ?? ` ${style.green("?")} ${question}${fallback ? style.grey(` (${fallback})`) : ""} `;
565
+ }
566
+ function renderPrompt(question, fallback, options) {
567
+ const text = promptText(question, fallback, options);
568
+ setLinePrompt(text, !!options.presentation || !!options.requireInput);
569
+ stdout5.write(text);
337
570
  }
338
571
  function askSecret(question, options = {}) {
339
- return readValidated(() => stdout4.write(` ${style.green("?")} ${question} `), "", { ...options, secret: true });
572
+ return ask(question, "", { ...options, secret: true });
340
573
  }
341
574
  async function confirm(question, fallback = false) {
342
575
  const answer = await ask(`${question} ${style.grey(fallback ? "[Y/n]" : "[y/N]")}`, fallback ? "y" : "n");
@@ -344,8 +577,8 @@ async function confirm(question, fallback = false) {
344
577
  }
345
578
 
346
579
  // src/prompt/menu.ts
347
- import { stdin as stdin3, stdout as stdout5 } from "process";
348
- var hint = () => style.grey(" \u2191\u2193 move \xB7 enter select");
580
+ import { stdin as stdin3, stdout as stdout6 } from "process";
581
+ var hint = (presentation) => style.grey(presentation ? " \u2514 \u2191\u2193 move \xB7 Enter \xB7 Ctrl+C cancel" : " \u2191\u2193 move \xB7 enter select");
349
582
  function optionLine(o, i, chosen, interactive) {
350
583
  const bullet = chosen ? icon.arrow : " ";
351
584
  const number = interactive ? "" : style.grey(`${i + 1}) `);
@@ -353,22 +586,25 @@ function optionLine(o, i, chosen, interactive) {
353
586
  const label = o.disabled ? style.grey(o.label) : chosen ? style.green(o.label) : o.label;
354
587
  return ` ${bullet} ${number}${label}${note2 ? style.grey(` ${note2}`) : ""}`;
355
588
  }
356
- function renderOptions(options, active, interactive) {
357
- const columns = stdout5.columns || DEFAULT_COLUMNS;
358
- let rows = 0;
359
- options.forEach((o, i) => {
360
- const line = optionLine(o, i, interactive && i === active, interactive);
361
- stdout5.write(`${line}${clearLine}
589
+ function renderOptions(options, active, interactive, presentation) {
590
+ return options.reduce((rows, option, index) => {
591
+ const lines = presentation?.option(option, index, interactive && index === active, interactive);
592
+ return rows + writeOptions(lines ?? [optionLine(option, index, interactive && index === active, interactive)]);
593
+ }, 0);
594
+ }
595
+ function writeOptions(lines) {
596
+ const columns = stdout6.columns || DEFAULT_COLUMNS;
597
+ return lines.reduce((rows, line) => {
598
+ stdout6.write(`${clearLine}${line}
362
599
  `);
363
- rows += Math.max(1, Math.ceil(visible(line) / columns));
364
- });
365
- return rows;
600
+ return rows + Math.max(1, Math.ceil(visible(line) / columns));
601
+ }, 0);
366
602
  }
367
603
  function redraw(menu) {
368
604
  if (!menu.canRedraw) return;
369
- stdout5.write(up(menu.rows));
370
- menu.rows = renderOptions(menu.options, menu.active, true) + 1;
371
- stdout5.write(`${hint()}
605
+ stdout6.write(up(menu.rows));
606
+ menu.rows = renderOptions(menu.options, menu.active, true, menu.presentation) + 1;
607
+ stdout6.write(`${hint(menu.presentation)}
372
608
  `);
373
609
  }
374
610
  var move = (delta) => (menu) => {
@@ -398,59 +634,80 @@ function actionFor(key) {
398
634
  return /^[1-9]$/.test(key) ? jump(key) : void 0;
399
635
  }
400
636
  function collapse(menu, chosen) {
401
- stdout5.write(up(menu.rows));
402
- for (let i = 0; i < menu.rows; i++) stdout5.write(`${clearLine}
637
+ stdout6.write(up(menu.rows));
638
+ for (let i = 0; i < menu.rows; i++) stdout6.write(`${clearLine}
403
639
  `);
404
- stdout5.write(up(menu.rows));
405
- stdout5.write(`${chosen}${clearLine}
640
+ stdout6.write(up(menu.rows));
641
+ stdout6.write(`${chosen}${clearLine}
406
642
  `);
407
643
  }
408
644
  function recordChoice(menu) {
645
+ if (menu.presentation) return recordPresented(menu);
409
646
  const chosen = ` ${icon.arrow} ${style.green(menu.options[menu.active].label)}`;
410
647
  if (menu.canRedraw) collapse(menu, chosen);
411
- else stdout5.write(`${chosen}
648
+ else stdout6.write(`${chosen}
412
649
  `);
413
650
  }
651
+ function recordPresented(menu) {
652
+ menu.presentation.menuRows(menu.rows);
653
+ menu.presentation.complete(menu.options[menu.active].label);
654
+ }
414
655
  var findOption = (options, v) => options[Number(v) - 1] || options.find((o) => o.id === v);
415
656
  function pipedProblem(options, v) {
416
657
  const picked = findOption(options, v);
417
658
  if (!picked) return "Pick one of the numbers above.";
418
659
  if (picked.disabled) return `${picked.label} is ${picked.disabled}. Pick another.`;
419
660
  }
420
- async function choosePiped(options, pickable) {
421
- renderOptions(options, -1, false);
422
- const answer = await ask("choice:", String(pickable[0] + 1), { validate: (v) => pipedProblem(options, v) });
423
- return findOption(options, answer).id;
424
- }
425
- function openMenu(options, pickable) {
426
- const rows = renderOptions(options, pickable[0], true) + 1;
427
- const canRedraw = rows < (stdout5.rows || DEFAULT_ROWS) - 1;
428
- return { options, pickable, active: pickable[0], rows, canRedraw };
429
- }
430
- function finish(menu, outcome, resolve, reject) {
431
- if (outcome.id === null) {
432
- stdout5.write("\n");
433
- reject(new InputError("Cancelled."));
434
- } else {
435
- recordChoice(menu);
436
- resolve(outcome.id);
437
- }
661
+ async function choosePiped(options, pickable, presentation) {
662
+ presentation?.appendOnly();
663
+ renderOptions(options, -1, false, presentation);
664
+ const answer = await pipedAnswer(options, pickable[0], !!presentation);
665
+ const picked = findOption(options, answer);
666
+ presentation?.complete(picked.label);
667
+ return picked.id;
668
+ }
669
+ function pipedAnswer(options, first2, requireInput) {
670
+ return ask("choice:", String(first2 + 1), { validate: (value) => pipedProblem(options, value), requireInput });
671
+ }
672
+ function openMenu(options, pickable, presentation) {
673
+ const rows = renderOptions(options, pickable[0], true, presentation) + 1;
674
+ const canRedraw = rows < (stdout6.rows || DEFAULT_ROWS) - 1;
675
+ return { options, pickable, active: pickable[0], rows, canRedraw, presentation };
676
+ }
677
+ function finish(menu, outcome, resolve2, reject) {
678
+ if (outcome.id === null) return cancelMenu(menu, reject);
679
+ recordChoice(menu);
680
+ resolve2(outcome.id);
681
+ }
682
+ function cancelMenu(menu, reject) {
683
+ menu.presentation?.menuRows(menu.rows);
684
+ menu.presentation?.cancel();
685
+ stdout6.write("\n");
686
+ reject(new InputError("Cancelled."));
438
687
  }
439
688
  function release(onData, wasRaw) {
440
689
  stdin3.off("data", onData);
441
690
  if (!wasRaw) stdin3.setRawMode(false);
442
691
  resumeLines();
443
692
  }
444
- function listen(menu, wasRaw, resolve, reject) {
693
+ function listen(menu, wasRaw, resolve2, reject) {
445
694
  const onData = (buf) => {
695
+ if (windowChanged(menu, buf)) return resizeFallback(menu, onData, wasRaw, resolve2, reject);
446
696
  const outcome = actionFor(buf.toString())?.(menu);
447
697
  if (!outcome) return;
448
698
  release(onData, wasRaw);
449
- finish(menu, outcome, resolve, reject);
699
+ finish(menu, outcome, resolve2, reject);
450
700
  };
451
701
  stdin3.on("data", onData);
452
702
  }
453
- var readKeys = (menu, wasRaw) => new Promise((resolve, reject) => listen(menu, wasRaw, resolve, reject));
703
+ function windowChanged(menu, buffer) {
704
+ return buffer.toString() !== "" && !!menu.presentation && !menu.presentation.canNavigate(menu.options);
705
+ }
706
+ function resizeFallback(menu, onData, wasRaw, resolve2, reject) {
707
+ release(onData, wasRaw);
708
+ choosePiped(menu.options, menu.pickable, menu.presentation).then(resolve2, reject);
709
+ }
710
+ var readKeys = (menu, wasRaw) => new Promise((resolve2, reject) => listen(menu, wasRaw, resolve2, reject));
454
711
  function enterRaw() {
455
712
  pauseLines();
456
713
  const wasRaw = !!stdin3.isRaw;
@@ -458,10 +715,10 @@ function enterRaw() {
458
715
  stdin3.resume();
459
716
  return wasRaw;
460
717
  }
461
- async function chooseInteractive(options, pickable) {
462
- const menu = openMenu(options, pickable);
718
+ async function chooseInteractive(options, pickable, presentation) {
719
+ const menu = openMenu(options, pickable, presentation);
463
720
  const wasRaw = enterRaw();
464
- stdout5.write(`${hint()}
721
+ stdout6.write(`${hint(presentation)}
465
722
  `);
466
723
  try {
467
724
  return await readKeys(menu, wasRaw);
@@ -469,12 +726,145 @@ async function chooseInteractive(options, pickable) {
469
726
  if (!wasRaw && stdin3.isTTY && stdin3.isRaw) stdin3.setRawMode(false);
470
727
  }
471
728
  }
472
- async function choose(question, options) {
729
+ async function choose(question, options, presentation) {
473
730
  const pickable = options.map((o, i) => o.disabled ? -1 : i).filter((i) => i >= 0);
474
731
  if (!pickable.length) throw new Error(`No option available for: ${question}`);
475
- stdout5.write(` ${style.green("?")} ${style.bold(question)}
732
+ if (presentation) presentation.begin(question, "", false);
733
+ else stdout6.write(` ${style.green("?")} ${style.bold(question)}
734
+ `);
735
+ return chooseInput(options, pickable, presentation);
736
+ }
737
+ function chooseInput(options, pickable, presentation) {
738
+ const interactive = presentation ? presentation.canNavigate(options) : stdin3.isTTY;
739
+ return interactive ? chooseInteractive(options, pickable, presentation) : choosePiped(options, pickable, presentation);
740
+ }
741
+
742
+ // src/prompt/presentation.ts
743
+ import { stdin as stdin4, stdout as stdout7 } from "process";
744
+ var QuestionFrame = class {
745
+ /** Immutable help associated with this field. */
746
+ help;
747
+ /** Printed rows which belong to this question only. */
748
+ rows = 0;
749
+ /** Resize disables rewinding to prevent touching older transcript content. */
750
+ columns = stdout7.columns || DEFAULT_COLUMNS;
751
+ /** A shorter window must not rewind into an earlier screen region. */
752
+ height = stdout7.rows || DEFAULT_ROWS;
753
+ /** Secret input contributes mask cells and is completed as Provided. */
754
+ secret = false;
755
+ /** A matching stream and cursor-capable terminal are required. */
756
+ interactive = !!stdin4.isTTY && !!stdout7.isTTY && !plain;
757
+ constructor(help2) {
758
+ this.help = help2;
759
+ }
760
+ /** Essential help uses normal foreground; only the rail is subdued. */
761
+ begin(_label, _fallback, secret) {
762
+ this.secret = secret;
763
+ this.line(`
764
+ ${style.cyan("\u25C6")} ${style.bold(this.help.question || this.help.title)}`);
765
+ for (const text of helpParagraphs(this.help)) this.prose(text);
766
+ if (this.help.command) this.line(` ${style.grey("\u2502")} ${displayText(this.help.command)}`);
767
+ this.prose(this.help.behavior);
768
+ }
769
+ /** Text input always begins below its guidance. */
770
+ prompt() {
771
+ return ` ${style.cyan("\u2514")} \u203A `;
772
+ }
773
+ /** Readline has already echoed input and advanced to the following row. */
774
+ input(cells) {
775
+ this.rows += Math.max(1, Math.ceil((cellWidth(this.prompt()) + cells) / this.columns));
776
+ if (this.secret) this.rows += 1;
777
+ }
778
+ /** A retry retains every earlier answer and only adds the active field's error. */
779
+ problem(message) {
780
+ this.prose(`Check: ${message}`, true);
781
+ }
782
+ /** Secrets are not passed in; they can only display a fixed status. */
783
+ complete(value) {
784
+ this.rewind();
785
+ setupAnswer(this.help.title, this.secret ? "Provided" : value);
786
+ }
787
+ /** Cancellation does not pretend a question was answered. */
788
+ cancel() {
789
+ this.rewind();
790
+ stdout7.write(` ${style.yellow("!")} Setup cancelled.
791
+ `);
792
+ }
793
+ /** Menu rows are replaced on redraw and counted only once at completion. */
794
+ menuRows(rows) {
795
+ this.rows += rows;
796
+ }
797
+ /** Once fallback occurs, this question never resumes cursor navigation. */
798
+ appendOnly() {
799
+ this.interactive = false;
800
+ }
801
+ /** Choice descriptions wrap separately from labels instead of competing on one long line. */
802
+ option(value, index, active, interactive) {
803
+ const columns = Math.max(1, contentColumns() - CHOICE_INSET);
804
+ const mark = interactive ? active ? style.cyan("\u25CF") : "\u25CB" : `${index + 1}.`;
805
+ const first2 = wrapProse(value.label, columns).map(
806
+ (text, row2) => ` ${style.grey("\u2502")} ${row2 ? " " : `${mark} `}${active ? style.bold(text) : text}`
807
+ );
808
+ return [...first2, ...choiceDescription(value.disabled || value.note, columns)];
809
+ }
810
+ /** A tall menu or resized terminal falls back to visible numbered input. */
811
+ canNavigate(options) {
812
+ const rows = options.flatMap((value, index) => this.option(value, index, false, true)).reduce((sum, line) => sum + terminalRows(line), 1);
813
+ return this.canRewind() && this.rows + rows < (stdout7.rows || DEFAULT_ROWS) - 1;
814
+ }
815
+ /** Each printed line is accounted for, including native wrapping. */
816
+ line(value) {
817
+ stdout7.write(`${value}
818
+ `);
819
+ this.rows += value.split("\n").reduce((sum, line) => sum + terminalRows(line), 0);
820
+ }
821
+ /** Wrap prose to the available rail width. */
822
+ prose(value, error = false) {
823
+ for (const line of wrapProse(value)) this.line(` ${style.grey("\u2502")} ${error ? style.red(line) : line}`);
824
+ }
825
+ /** Rewind only when the complete owned block remains visible in the same geometry. */
826
+ canRewind() {
827
+ return this.interactive && this.columns === (stdout7.columns || DEFAULT_COLUMNS) && this.height === (stdout7.rows || DEFAULT_ROWS) && this.rows < this.height - 1;
828
+ }
829
+ /** Erase only the current question, never scrollback or previous answers. */
830
+ rewind() {
831
+ if (this.canRewind()) stdout7.write(`${up(this.rows)}${ESC}[J`);
832
+ }
833
+ };
834
+ function choiceDescription(value, columns) {
835
+ return !value ? [] : wrapProse(value, columns).map((text) => ` ${style.grey("\u2502")} ${style.grey(text)}`);
836
+ }
837
+ function setupAnswer(label, value) {
838
+ labelValue(label, value).forEach(
839
+ (line, index) => stdout7.write(`${index ? " " : ` ${style.green("\u2713")} `}${line}
840
+ `)
841
+ );
842
+ }
843
+ function helpParagraphs(help2) {
844
+ return [help2.purpose, help2.example ? `Example: ${help2.example}` : "", `Find: ${help2.find}`].filter(Boolean);
845
+ }
846
+ var presentQuestion = (help2) => new QuestionFrame(help2);
847
+ function setupPhase(phase) {
848
+ const phases = ["Target", "Configure", "Deploy", "Verify"];
849
+ stdout7.write(
850
+ `
851
+ ${phases.map((name) => name === phase ? style.cyan(style.bold(`[${name}]`)) : style.grey(name)).join(" \u203A ")}
852
+ `
853
+ );
854
+ }
855
+ function setupIntro() {
856
+ stdout7.write(`
857
+ ${style.cyan("\u25C7")} ${style.bold("Oya Browser")}
858
+ Self-host setup
859
+ `);
860
+ setupPhase("Target");
861
+ }
862
+ function setupSection(title, values) {
863
+ stdout7.write(`
864
+ ${style.bold(title)}
865
+ `);
866
+ for (const [label, value] of values) for (const line of labelValue(label, value)) stdout7.write(` ${line}
476
867
  `);
477
- return stdin3.isTTY ? chooseInteractive(options, pickable) : choosePiped(options, pickable);
478
868
  }
479
869
 
480
870
  // src/install/repo.ts
@@ -510,33 +900,37 @@ var Status = {
510
900
  FORBIDDEN: 403
511
901
  };
512
902
  var NATIVE_LINUX_DIRECTORY = process.env.OYA_NATIVE_LINUX_DIRECTORY || "";
903
+ var DEPLOY_PROBE_MS = 15e3;
904
+ var DEPLOY_PROBE_BYTES = 65536;
905
+ var DEPLOY_KILL_MS = 4e4;
906
+ var DEPLOYMENT_PLAN_VERSION = 2;
513
907
 
514
908
  // src/install/shell.ts
515
- function settle(cmd, args, resolve, reject) {
516
- return (code) => code === 0 ? resolve() : reject(new Error(`${cmd} ${args.join(" ")} exited ${code}`));
909
+ function settle(cmd, args, resolve2, reject) {
910
+ return (code) => code === 0 ? resolve2() : reject(new Error(`${cmd} ${args.join(" ")} exited ${code}`));
517
911
  }
518
912
  function run(cmd, args, opts = { cwd: process.cwd() }) {
519
- return new Promise((resolve, reject) => {
913
+ return new Promise((resolve2, reject) => {
520
914
  const child = spawn(cmd, args, { cwd: opts.cwd, stdio: opts.quiet ? "ignore" : "inherit" });
521
915
  child.on("error", reject);
522
- child.on("close", settle(cmd, args, resolve, reject));
916
+ child.on("close", settle(cmd, args, resolve2, reject));
523
917
  });
524
918
  }
525
- function pipeTo(cmd, args, stdin4, cwd) {
526
- return new Promise((resolve, reject) => {
919
+ function pipeTo(cmd, args, stdin5, cwd) {
920
+ return new Promise((resolve2, reject) => {
527
921
  const child = spawn(cmd, args, { cwd, stdio: ["pipe", "inherit", "inherit"] });
528
922
  child.on("error", reject);
529
- child.on("close", settle(cmd, args, resolve, reject));
530
- child.stdin.end(stdin4);
923
+ child.on("close", settle(cmd, args, resolve2, reject));
924
+ child.stdin.end(stdin5);
531
925
  });
532
926
  }
533
927
  async function capture(cmd, args, cwd = process.cwd()) {
534
- return new Promise((resolve) => {
928
+ return new Promise((resolve2) => {
535
929
  const child = spawn(cmd, args, { cwd, stdio: ["ignore", "pipe", "ignore"] });
536
930
  const out2 = [];
537
931
  child.stdout.on("data", (d) => out2.push(String(d)));
538
- child.on("error", () => resolve(null));
539
- child.on("close", (code) => resolve(code === 0 ? out2.join("").trim() : null));
932
+ child.on("error", () => resolve2(null));
933
+ child.on("close", (code) => resolve2(code === 0 ? out2.join("").trim() : null));
540
934
  });
541
935
  }
542
936
  var has = async (cmd) => await capture(cmd, ["--version"]) !== null;
@@ -545,16 +939,16 @@ function atLeast(version2, major, minor) {
545
939
  if (!m) return false;
546
940
  return Number(m[1]) > major || Number(m[1]) === major && Number(m[2]) >= minor;
547
941
  }
548
- function watchProbe(socket, resolve) {
942
+ function watchProbe(socket, resolve2) {
549
943
  const settle2 = (free) => {
550
944
  socket.destroy();
551
- resolve(free);
945
+ resolve2(free);
552
946
  };
553
- socket.on("connect", () => settle2(false)).on("error", () => resolve(true));
947
+ socket.on("connect", () => settle2(false)).on("error", () => resolve2(true));
554
948
  setTimeout(() => settle2(true), PORT_PROBE_MS);
555
949
  }
556
950
  function portFree(port) {
557
- return new Promise((resolve) => watchProbe(createConnection({ port, host: "127.0.0.1" }), resolve));
951
+ return new Promise((resolve2) => watchProbe(createConnection({ port, host: "127.0.0.1" }), resolve2));
558
952
  }
559
953
 
560
954
  // src/install/repo.ts
@@ -570,10 +964,14 @@ function findRepoRoot(from = process.cwd()) {
570
964
  }
571
965
  return null;
572
966
  }
573
- var DEFAULT_CLONE = () => join(process.cwd(), "oya-browser");
967
+ var DEFAULT_CLONE = () => process.env.OYA_DIR || join(process.cwd(), "oya-browser");
574
968
  var REPO_URL = "https://github.com/OyadotAI/oya-browser.git";
969
+ function selectedRepo() {
970
+ const requested = process.env.OYA_DIR;
971
+ return requested ? isRepoRoot(requested) ? requested : null : findRepoRoot();
972
+ }
575
973
  async function locateRepo(dryRun = false, yes = false) {
576
- const found = findRepoRoot();
974
+ const found = selectedRepo();
577
975
  if (found) return found;
578
976
  console.log("\nThis does not look like an oya-browser checkout.");
579
977
  const where = yes ? DEFAULT_CLONE() : await ask("Clone it to:", DEFAULT_CLONE());
@@ -691,13 +1089,7 @@ async function verifyLlm(baseUrl, key, model) {
691
1089
  }
692
1090
 
693
1091
  // src/install/interview.ts
694
- var HOST_OPTIONS = [
695
- { id: "docker", label: "Docker on this machine", note: "one command, no cluster" },
696
- { id: "k8s", label: "Kubernetes", disabled: "not in this build yet" },
697
- { id: "ecs", label: "Amazon ECS", disabled: "not in this build yet" },
698
- { id: "fly", label: "Fly.io", disabled: "coming soon" },
699
- { id: "exe", label: "exe.dev", disabled: "coming soon" }
700
- ];
1092
+ var HOST_OPTIONS = [{ id: "docker", label: "Docker on this machine", note: "one command, no cluster" }];
701
1093
  var DB_OPTIONS = [
702
1094
  { id: "sqlite", label: "SQLite", note: "zero config, one replica, API keys only" },
703
1095
  { id: "supabase", label: "Supabase", note: "adds email sign-in and the dashboard" },
@@ -754,9 +1146,9 @@ var K8S_QUESTIONS = [
754
1146
  ["proxyUrl", "Egress proxy URL, as reachable from the cluster:", "http://oya-server.oya-browser.svc:3128"]
755
1147
  ];
756
1148
  var FLEET_SECRETS = { "oya-cloud": "OYA_CLOUD_API_KEY", cdp: "OYA_CDP_WS_URL" };
757
- function secretFor(s, field, hidden = true) {
758
- if (s.replay) return Promise.resolve(process.env[field] || "");
759
- return hidden ? askSecret(`${field}:`) : ask(`${field}:`);
1149
+ function secretFor(s, field2, hidden = true) {
1150
+ if (s.replay) return Promise.resolve(process.env[field2] || "");
1151
+ return hidden ? askSecret(`${field2}:`) : ask(`${field2}:`);
760
1152
  }
761
1153
  function isPostgresUrl(v) {
762
1154
  if (!v) return;
@@ -803,8 +1195,8 @@ async function askWorkers(s, fleet) {
803
1195
  return Number(answer);
804
1196
  }
805
1197
  async function askFleetSecrets(s, fleet) {
806
- for (const field of VENDOR_KEYS[fleet] || []) {
807
- s.secrets[field] = await secretFor(s, field, !field.endsWith("PROJECT_ID"));
1198
+ for (const field2 of VENDOR_KEYS[fleet] || []) {
1199
+ s.secrets[field2] = await secretFor(s, field2, !field2.endsWith("PROJECT_ID"));
808
1200
  }
809
1201
  if (Object.hasOwn(FLEET_SECRETS, fleet)) {
810
1202
  s.secrets[FLEET_SECRETS[fleet]] = await secretFor(s, FLEET_SECRETS[fleet]);
@@ -815,7 +1207,7 @@ async function askK8s(s, fleet) {
815
1207
  step("Kubernetes fleet", "One pod per session.");
816
1208
  note("The image must be digest-pinned: a tag can move between verification and scheduling.");
817
1209
  const answers = {};
818
- for (const [field, question, fallback] of K8S_QUESTIONS) answers[field] = await ask(question, fallback);
1210
+ for (const [field2, question, fallback] of K8S_QUESTIONS) answers[field2] = await ask(question, fallback);
819
1211
  return answers;
820
1212
  }
821
1213
  async function llmFor(s) {
@@ -1137,26 +1529,26 @@ async function resolveKekConflict(volume, root) {
1137
1529
  // src/install/migrate.ts
1138
1530
  import { spawn as spawn2 } from "child_process";
1139
1531
  import { join as join3 } from "path";
1140
- var startMigrations = (root, databaseUrl) => spawn2(process.execPath, [join3(root, "server", "migrations", "run.mjs")], {
1532
+ var startMigrations = (root, databaseUrl2) => spawn2(process.execPath, [join3(root, "server", "migrations", "run.mjs")], {
1141
1533
  cwd: root,
1142
1534
  stdio: ["ignore", "pipe", "pipe"],
1143
- env: { ...process.env, DATABASE_URL: databaseUrl }
1535
+ env: { ...process.env, DATABASE_URL: databaseUrl2 }
1144
1536
  });
1145
- function runMigrations(root, databaseUrl) {
1146
- return new Promise((resolve, reject) => {
1147
- const child = startMigrations(root, databaseUrl);
1537
+ function runMigrations(root, databaseUrl2) {
1538
+ return new Promise((resolve2, reject) => {
1539
+ const child = startMigrations(root, databaseUrl2);
1148
1540
  let err = "";
1149
1541
  child.stderr.on("data", (d) => err += d);
1150
1542
  child.on("error", reject);
1151
1543
  const failure2 = (code) => new Error(err.trim() || `migrations exited ${code}`);
1152
- child.on("close", (code) => code === 0 ? resolve() : reject(failure2(code)));
1544
+ child.on("close", (code) => code === 0 ? resolve2() : reject(failure2(code)));
1153
1545
  });
1154
1546
  }
1155
1547
  var RETRY = "Fix the database, then re-run: DATABASE_URL=\u2026 make migrate";
1156
- async function migrate(root, databaseUrl) {
1548
+ async function migrate(root, databaseUrl2) {
1157
1549
  const spin = spinner("applying migrations");
1158
1550
  try {
1159
- await runMigrations(root, databaseUrl);
1551
+ await runMigrations(root, databaseUrl2);
1160
1552
  spin.done();
1161
1553
  } catch (e) {
1162
1554
  spin.fail();
@@ -1363,6 +1755,1099 @@ function defaultInstall(env2 = process.env) {
1363
1755
  return { answers: { ...LOCAL, optional: { ...LOCAL.optional }, llm }, secrets };
1364
1756
  }
1365
1757
 
1758
+ // src/install/deployment.ts
1759
+ import { renameSync, writeFileSync as writeFileSync3 } from "fs";
1760
+ import { join as join6 } from "path";
1761
+
1762
+ // src/install/deployment-targets.ts
1763
+ var DEPLOYMENT_TARGETS = {
1764
+ docker: {
1765
+ label: "Docker",
1766
+ note: "This machine \xB7 Postgres + HTTPS",
1767
+ options: { domain: "string", "browser-image": "string", "server-image": "string" },
1768
+ defaults: { domain: "localhost" },
1769
+ globals: [],
1770
+ tools: [],
1771
+ resources: "Docker Compose: control plane, Postgres, Caddy, browser containers",
1772
+ secrets: "deployments/docker/.env and Docker data volumes (kept on redeploy)"
1773
+ },
1774
+ k8s: {
1775
+ label: "Kubernetes",
1776
+ note: "Existing cluster \xB7 browser pods",
1777
+ options: {
1778
+ context: "string",
1779
+ namespace: "string",
1780
+ registry: "string",
1781
+ image: "string",
1782
+ platform: "string",
1783
+ "in-cluster-postgres": "boolean",
1784
+ host: "string",
1785
+ "tls-secret": "string",
1786
+ "cluster-issuer": "string",
1787
+ "ingress-class": "string",
1788
+ replicas: "string",
1789
+ "browser-ttl": "string",
1790
+ "browser-image": "string",
1791
+ "env-file": "string"
1792
+ },
1793
+ defaults: { namespace: "oya" },
1794
+ globals: ["context", "namespace"],
1795
+ tools: ["kubectl", "python3"],
1796
+ resources: "Namespace, control plane, RBAC, isolated browser pods; managed or in-cluster Postgres",
1797
+ secrets: "Kubernetes Secrets oya-secrets and oya-settings (kept on redeploy)"
1798
+ },
1799
+ ecs: {
1800
+ label: "Amazon ECS",
1801
+ note: "AWS Fargate + RDS",
1802
+ options: {
1803
+ region: "string",
1804
+ stack: "string",
1805
+ "certificate-arn": "string",
1806
+ "http-only": "boolean",
1807
+ "vpc-id": "string",
1808
+ "public-subnets": "string",
1809
+ "private-subnets": "string",
1810
+ "allowed-cidr": "string",
1811
+ replicas: "string",
1812
+ "db-class": "string",
1813
+ "single-az-db": "boolean",
1814
+ "browser-image": "string",
1815
+ "server-image": "string",
1816
+ "env-file": "string"
1817
+ },
1818
+ defaults: { region: "us-east-1", stack: "oya" },
1819
+ globals: ["region", "stack"],
1820
+ tools: ["aws"],
1821
+ resources: "CloudFormation: VPC, ECS/Fargate, HTTPS load balancer, RDS Postgres, IAM and ECR",
1822
+ secrets: "AWS Secrets Manager and RDS (kept on redeploy)"
1823
+ },
1824
+ gcloud: {
1825
+ label: "Google Cloud",
1826
+ note: "GKE Autopilot + Cloud SQL",
1827
+ options: {
1828
+ project: "string",
1829
+ region: "string",
1830
+ name: "string",
1831
+ domain: "string",
1832
+ replicas: "string",
1833
+ "db-tier": "string",
1834
+ "single-zone-db": "boolean",
1835
+ "browser-image": "string",
1836
+ "env-file": "string"
1837
+ },
1838
+ defaults: { region: "us-central1", name: "oya" },
1839
+ globals: ["project", "region", "name"],
1840
+ tools: ["gcloud", "kubectl", "python3", "gke-gcloud-auth-plugin"],
1841
+ resources: "GKE Autopilot, Cloud SQL, Artifact Registry, Workload Identity; optional HTTPS",
1842
+ secrets: "Kubernetes Secrets and Cloud SQL (kept on redeploy)"
1843
+ }
1844
+ };
1845
+ function deploymentTarget(value) {
1846
+ if (typeof value !== "string" || !Object.hasOwn(DEPLOYMENT_TARGETS, value))
1847
+ throw new Error("Choose a deployment target: docker, k8s, ecs, or gcloud.");
1848
+ return value;
1849
+ }
1850
+ function optionArguments(options) {
1851
+ return Object.entries(options).flatMap(([key, value]) => {
1852
+ if (!value) return [];
1853
+ return value === true ? [`--${key}`] : [`--${key}`, value];
1854
+ });
1855
+ }
1856
+ function destinationOptions(target, options) {
1857
+ return Object.fromEntries(
1858
+ DEPLOYMENT_TARGETS[target].globals.filter((key) => options[key]).map((key) => [key, options[key]])
1859
+ );
1860
+ }
1861
+
1862
+ // src/install/deployment-plan.ts
1863
+ function record(value) {
1864
+ return !!value && typeof value === "object" && !Array.isArray(value);
1865
+ }
1866
+ function validateOption(key, value, expected) {
1867
+ if (!expected || typeof value !== expected) throw new Error(`Unsupported or invalid deployment option: ${key}.`);
1868
+ if (typeof value === "string" && /[\r\n\0]/.test(value)) throw new Error(`Invalid deployment option: ${key}.`);
1869
+ if (typeof value === "string" && /(?:postgres(?:ql)?:\/\/|https?:\/\/[^/]*@)/i.test(value))
1870
+ throw new Error(`Credentials cannot be saved in ${key}. Use OYA_DEPLOY_DATABASE_URL for Kubernetes Postgres.`);
1871
+ }
1872
+ function requireOption(ok, message) {
1873
+ if (!ok) throw new Error(message);
1874
+ }
1875
+ function validateKubernetes(o) {
1876
+ requireOption(o.context, "Kubernetes needs an explicit context. List yours with: kubectl config get-contexts");
1877
+ requireOption(!!o.registry !== !!o.image, "Kubernetes needs exactly one of registry or image.");
1878
+ validateKubernetesTls(o);
1879
+ requireOption(
1880
+ !String(o.context).split("/").includes(".."),
1881
+ "Kubernetes context must not contain a parent path segment."
1882
+ );
1883
+ }
1884
+ function validateKubernetesTls(o) {
1885
+ const valid = !o.host || !!o["tls-secret"] !== !!o["cluster-issuer"];
1886
+ requireOption(valid, "Kubernetes HTTPS needs exactly one TLS secret or cluster issuer.");
1887
+ }
1888
+ function validateEcs(o, publicUrl) {
1889
+ requireOption(
1890
+ !!o["certificate-arn"] !== !!o["http-only"],
1891
+ "ECS needs a certificate-arn or explicit http-only trial mode."
1892
+ );
1893
+ requireOption(!o["certificate-arn"] || publicUrl, "ECS HTTPS needs publicUrl matching your ACM certificate and DNS.");
1894
+ validateNetworking(o);
1895
+ }
1896
+ function validateNetworking(o) {
1897
+ const networking = [o["vpc-id"], o["public-subnets"], o["private-subnets"]];
1898
+ requireOption(
1899
+ networking.every(Boolean) || !networking.some(Boolean),
1900
+ "An existing VPC needs vpc-id, public-subnets and private-subnets together."
1901
+ );
1902
+ }
1903
+ function validateValues(o) {
1904
+ for (const key of ["replicas", "browser-ttl"])
1905
+ if (o[key]) requireOption(/^[1-9]\d*$/.test(String(o[key])), `${key} must be a whole number of 1 or more.`);
1906
+ validateImages(o);
1907
+ validateDnsValues(o);
1908
+ }
1909
+ function validateImages(o) {
1910
+ for (const key of ["registry", "image", "browser-image", "server-image"])
1911
+ if (o[key])
1912
+ requireOption(
1913
+ /^[\w][\w.:/@-]*$/.test(String(o[key])),
1914
+ `${key} must be a container image reference without credentials.`
1915
+ );
1916
+ }
1917
+ function validateDnsValues(o) {
1918
+ for (const key of ["namespace", "host", "domain", "ingress-class", "tls-secret", "cluster-issuer"])
1919
+ if (o[key]) requireOption(/^[a-z0-9][a-z0-9.-]*$/.test(String(o[key])), `${key} must be a DNS name.`);
1920
+ }
1921
+ function deploymentFieldProblem(key, value) {
1922
+ try {
1923
+ validateValues({ [key]: value });
1924
+ } catch (err) {
1925
+ return err.message;
1926
+ }
1927
+ }
1928
+ function validatePublicUrl(value) {
1929
+ if (value === void 0) return;
1930
+ const url = safePublicUrl(value);
1931
+ requireOption(
1932
+ url?.protocol === "https:" && !url.username && !url.password && url.pathname === "/" && !url.search && !url.hash,
1933
+ "publicUrl must be an HTTPS origin without credentials, a path or query."
1934
+ );
1935
+ return url.origin;
1936
+ }
1937
+ function safePublicUrl(value) {
1938
+ try {
1939
+ return typeof value === "string" ? new URL(value) : null;
1940
+ } catch {
1941
+ return null;
1942
+ }
1943
+ }
1944
+ function planRecord(value) {
1945
+ if (!record(value) || value.version !== DEPLOYMENT_PLAN_VERSION || !record(value.options))
1946
+ throw new Error("Expected a version 2 deployment plan with target and options.");
1947
+ for (const key of Object.keys(value))
1948
+ requireOption(
1949
+ ["version", "target", "options", "publicUrl"].includes(key),
1950
+ `Unknown deployment plan field: ${key}.`
1951
+ );
1952
+ return value;
1953
+ }
1954
+ function validatedOptions(target, value) {
1955
+ const spec = DEPLOYMENT_TARGETS[target];
1956
+ for (const [key, entry] of Object.entries(value))
1957
+ validateOption(key, entry, Object.hasOwn(spec.options, key) ? spec.options[key] : void 0);
1958
+ const options = { ...spec.defaults, ...value };
1959
+ validateValues(options);
1960
+ return options;
1961
+ }
1962
+ function parseDeploymentPlan(value) {
1963
+ const input = planRecord(value), target = deploymentTarget(input.target);
1964
+ const options = validatedOptions(target, input.options), publicUrl = validatePublicUrl(input.publicUrl);
1965
+ if (target === "k8s") validateKubernetes(options);
1966
+ if (target === "ecs") validateEcs(options, publicUrl);
1967
+ if (target === "gcloud") requireOption(options.project, "Google Cloud needs an explicit project.");
1968
+ return { version: DEPLOYMENT_PLAN_VERSION, target, options, ...publicUrl ? { publicUrl } : {} };
1969
+ }
1970
+
1971
+ // src/install/deployment-help-basic.ts
1972
+ var BASIC_HELP = {
1973
+ target: [
1974
+ "Target",
1975
+ "Deploy the control plane, Postgres and browsers together.",
1976
+ "Choose the infrastructure you want to use.",
1977
+ "",
1978
+ "Enter selects the highlighted option."
1979
+ ],
1980
+ context: [
1981
+ "Kubernetes context",
1982
+ "The cluster that will receive Oya.",
1983
+ "List the context names configured on this machine.",
1984
+ "my-cluster",
1985
+ "Enter the exact context name. Required.",
1986
+ "kubectl config get-contexts -o name"
1987
+ ],
1988
+ namespace: [
1989
+ "Namespace",
1990
+ "Keeps Oya resources together inside the selected cluster.",
1991
+ "Use an existing namespace or choose a new name; setup creates it.",
1992
+ "oya",
1993
+ "Enter uses oya.",
1994
+ "kubectl --context {context} get namespaces"
1995
+ ],
1996
+ "ecs:region": [
1997
+ "AWS region",
1998
+ "Where ECS, RDS and the load balancer will run.",
1999
+ "Use the region selector in your AWS console, or inspect your CLI default.",
2000
+ "us-east-1",
2001
+ "Enter uses us-east-1.",
2002
+ "aws configure get region"
2003
+ ],
2004
+ "gcloud:region": [
2005
+ "Google Cloud region",
2006
+ "Where GKE and Cloud SQL will run.",
2007
+ "Choose a region close to your users; list available regions below.",
2008
+ "us-central1",
2009
+ "Enter uses us-central1.",
2010
+ "gcloud compute regions list"
2011
+ ],
2012
+ stack: [
2013
+ "Stack name",
2014
+ "Names this Oya deployment and its AWS resources.",
2015
+ "Choose a name yourself. Reuse it when updating the same deployment.",
2016
+ "oya",
2017
+ "Enter uses oya."
2018
+ ],
2019
+ project: [
2020
+ "Google Cloud project",
2021
+ "The Google Cloud project that owns this deployment.",
2022
+ "Copy the PROJECT_ID column, rather than the display name.",
2023
+ "my-project-123",
2024
+ "A project ID is required.",
2025
+ "gcloud projects list"
2026
+ ],
2027
+ name: [
2028
+ "Deployment name",
2029
+ "Names the GKE cluster, database and registry.",
2030
+ "Choose a name yourself. Keep it the same when updating.",
2031
+ "oya",
2032
+ "Enter uses oya."
2033
+ ],
2034
+ "docker:domain": [
2035
+ "Domain",
2036
+ "The address you will open to use Oya.",
2037
+ "Use a hostname you control. Point its DNS at this machine for public HTTPS.",
2038
+ "oya.example.com",
2039
+ "Enter uses localhost with a local certificate."
2040
+ ],
2041
+ "gcloud:domain": [
2042
+ "Public domain",
2043
+ "Adds public HTTPS with a Google-managed certificate.",
2044
+ "Use a hostname you control; setup prints the IP for its DNS A record.",
2045
+ "oya.example.com",
2046
+ "Leave blank to keep access private through a port-forward."
2047
+ ],
2048
+ "image-source": [
2049
+ "Control-plane image",
2050
+ "Build the checkout or use an image you have already published.",
2051
+ "Use a repository you can push to, or an image built from deployments/image.",
2052
+ "",
2053
+ "Enter selects the highlighted option."
2054
+ ],
2055
+ registry: [
2056
+ "Registry repository",
2057
+ "Where setup pushes the control-plane image it builds.",
2058
+ "Copy a repository path from your container registry. Sign in with docker login first.",
2059
+ "ghcr.io/YOUR-ORG/oya-control-plane",
2060
+ "Repository path only, without a tag. Required."
2061
+ ],
2062
+ image: [
2063
+ "Deployment image",
2064
+ "An already-published control-plane deployment image.",
2065
+ "Open your registry and copy an image built from deployments/image, including migrations.",
2066
+ "ghcr.io/YOUR-ORG/oya-control-plane@sha256:DIGEST",
2067
+ "Use a tag or digest-pinned reference. Required."
2068
+ ],
2069
+ "database-source": [
2070
+ "Postgres",
2071
+ "Stores Oya sessions, credentials and browser state.",
2072
+ "Use your managed database for production, or create an in-cluster trial database.",
2073
+ "",
2074
+ "Enter selects the highlighted option."
2075
+ ],
2076
+ access: [
2077
+ "Public access",
2078
+ "Choose HTTPS for production or plain HTTP for a trial.",
2079
+ "For HTTPS, have an issued ACM certificate in the selected AWS region.",
2080
+ "",
2081
+ "Enter selects HTTPS. HTTP is unencrypted."
2082
+ ],
2083
+ "certificate-arn": [
2084
+ "ACM certificate ARN",
2085
+ "The certificate used by the HTTPS load balancer.",
2086
+ "AWS console \u2192 Certificate Manager \u2192 selected region \u2192 issued certificate \u2192 ARN.",
2087
+ "arn:aws:acm:REGION:ACCOUNT:certificate/ID",
2088
+ "Copy the complete ARN. Required.",
2089
+ "aws acm list-certificates --region {region}"
2090
+ ],
2091
+ "public-url": [
2092
+ "Public HTTPS URL",
2093
+ "The public address matching your ACM certificate.",
2094
+ "Use a domain on the certificate. Point its DNS at the load balancer printed during deploy.",
2095
+ "https://oya.example.com",
2096
+ "HTTPS origin only, without a path. Required."
2097
+ ],
2098
+ "database-url": [
2099
+ "Database credentials",
2100
+ "Connects Oya to your managed Postgres database.",
2101
+ "Database provider \u2192 connection settings \u2192 PostgreSQL connection URI. Paste the complete URI.",
2102
+ "postgres://USER:PASSWORD@HOST:5432/DB",
2103
+ "Required. Input is masked; credentials are never saved in the plan."
2104
+ ],
2105
+ advanced: [
2106
+ "Advanced settings",
2107
+ "Defaults already configure the database and browser runtime.",
2108
+ "Customize only if you need different sizing, images or networking.",
2109
+ "",
2110
+ "Enter keeps the recommended defaults."
2111
+ ]
2112
+ };
2113
+
2114
+ // src/install/deployment-help-advanced.ts
2115
+ var ADVANCED_HELP = {
2116
+ "in-cluster-postgres": [
2117
+ "In-cluster Postgres",
2118
+ "Creates one persistent trial database pod.",
2119
+ "Choose this in the Postgres menu when you do not have a managed database.",
2120
+ "",
2121
+ "Managed Postgres remains the production recommendation."
2122
+ ],
2123
+ "http-only": [
2124
+ "HTTP trial",
2125
+ "Serves the deployment without TLS for a trial.",
2126
+ "Choose HTTP trial in the public access menu.",
2127
+ "",
2128
+ "HTTPS remains the production recommendation."
2129
+ ],
2130
+ replicas: [
2131
+ "Control-plane replicas",
2132
+ "How many control-plane instances will serve requests.",
2133
+ "Choose a whole number based on availability and expected load.",
2134
+ "2",
2135
+ "Blank keeps the script default of 2 replicas."
2136
+ ],
2137
+ host: [
2138
+ "Public hostname",
2139
+ "Creates a Kubernetes Ingress for this hostname.",
2140
+ "Use a DNS name you control and point it at your Ingress controller.",
2141
+ "oya.example.com",
2142
+ "Blank keeps access private. A hostname needs a TLS secret or cluster issuer."
2143
+ ],
2144
+ "tls-secret": [
2145
+ "TLS secret name",
2146
+ "An existing Kubernetes TLS certificate for the Ingress.",
2147
+ "Copy a TLS Secret name in the selected namespace. Do not paste certificate contents.",
2148
+ "oya-tls",
2149
+ "Blank uses the cluster issuer instead, or leaves public access off.",
2150
+ "kubectl --context {context} -n {namespace} get secrets --field-selector type=kubernetes.io/tls"
2151
+ ],
2152
+ "cluster-issuer": [
2153
+ "Certificate issuer",
2154
+ "Lets cert-manager issue the Ingress certificate.",
2155
+ "Copy the name of an installed ClusterIssuer.",
2156
+ "letsencrypt",
2157
+ "Blank uses an existing TLS secret instead, or leaves public access off.",
2158
+ "kubectl --context {context} get clusterissuers"
2159
+ ],
2160
+ "ingress-class": [
2161
+ "Ingress class",
2162
+ "Chooses the controller that serves public traffic.",
2163
+ "Copy the name of an installed IngressClass.",
2164
+ "nginx",
2165
+ "Blank keeps the cluster default.",
2166
+ "kubectl --context {context} get ingressclasses"
2167
+ ],
2168
+ "browser-ttl": [
2169
+ "Browser lifetime",
2170
+ "Maximum session lifetime in minutes, plus 10 minutes for cleanup.",
2171
+ "Choose a positive whole number of minutes.",
2172
+ "60",
2173
+ "Blank keeps the 60-minute script default."
2174
+ ],
2175
+ "browser-image": [
2176
+ "Browser image",
2177
+ "The Oya Linux image used for each browser.",
2178
+ "Copy the image reference from your registry, or keep the published Oya image.",
2179
+ "ghcr.io/oyadotai/oya-browser:latest",
2180
+ "Blank keeps the published Oya image. Setup pins its digest."
2181
+ ],
2182
+ "server-image": [
2183
+ "Server base image",
2184
+ "Use a published Oya server image instead of building its base.",
2185
+ "Copy a server image reference from your registry. The deployment wrapper is still built.",
2186
+ "ghcr.io/oyadotai/oya-browser-server:VERSION",
2187
+ "Blank builds the server from this checkout."
2188
+ ],
2189
+ "env-file": [
2190
+ "Optional settings file",
2191
+ "Adds LLM, CAPTCHA, proxy and other optional settings.",
2192
+ "Copy deployments/oya.env.example to your own file; see deployments/ENVIRONMENT.md.",
2193
+ "deployments/k8s/oya.env",
2194
+ "Blank uses this target\u2019s oya.env if it exists. File contents are never printed."
2195
+ ],
2196
+ platform: [
2197
+ "Build platform",
2198
+ "The operating system and CPU architecture for the control-plane image.",
2199
+ "Use a Docker platform supported by your cluster nodes.",
2200
+ "linux/amd64",
2201
+ "Blank keeps linux/amd64."
2202
+ ],
2203
+ "vpc-id": [
2204
+ "Existing VPC",
2205
+ "Use your AWS network instead of creating a new VPC.",
2206
+ "AWS console \u2192 VPC \u2192 Your VPCs \u2192 VPC ID.",
2207
+ "vpc-0123456789abcdef0",
2208
+ "Blank creates a VPC. An existing VPC also needs public and private subnet IDs."
2209
+ ],
2210
+ "public-subnets": [
2211
+ "Public subnet IDs",
2212
+ "The public subnets used by the load balancer.",
2213
+ "AWS console \u2192 VPC \u2192 Subnets; select public subnets in your chosen VPC.",
2214
+ "subnet-AAA,subnet-BBB",
2215
+ "Comma-separated IDs. Required when using an existing VPC."
2216
+ ],
2217
+ "private-subnets": [
2218
+ "Private subnet IDs",
2219
+ "The private subnets used by tasks and the database.",
2220
+ "AWS console \u2192 VPC \u2192 Subnets; select private subnets in your chosen VPC.",
2221
+ "subnet-CCC,subnet-DDD",
2222
+ "Comma-separated IDs. Required when using an existing VPC."
2223
+ ],
2224
+ "allowed-cidr": [
2225
+ "Allowed client network",
2226
+ "Which client IP range can reach the load balancer.",
2227
+ "Use your office or VPN\u2019s public CIDR, or the default for public access.",
2228
+ "203.0.113.10/32",
2229
+ "Blank keeps the script default: 0.0.0.0/0."
2230
+ ],
2231
+ "db-class": [
2232
+ "RDS instance class",
2233
+ "The CPU and memory size of the managed Postgres database.",
2234
+ "AWS console \u2192 RDS \u2192 instance sizing, or choose the default for a small deployment.",
2235
+ "db.t4g.small",
2236
+ "Blank keeps db.t4g.small."
2237
+ ],
2238
+ "single-az-db": [
2239
+ "Use a single-zone database?",
2240
+ "Removes the RDS standby to reduce trial cost.",
2241
+ "Choose No for a Multi-AZ database; choose Yes only when a standby is unnecessary.",
2242
+ "",
2243
+ "No keeps the production default: Multi-AZ."
2244
+ ],
2245
+ "db-tier": [
2246
+ "Cloud SQL machine",
2247
+ "The CPU and memory size of the managed Postgres database.",
2248
+ "Google Cloud console \u2192 SQL \u2192 machine configuration.",
2249
+ "db-custom-1-3840",
2250
+ "Blank keeps db-custom-1-3840."
2251
+ ],
2252
+ "single-zone-db": [
2253
+ "Use a single-zone database?",
2254
+ "Removes the Cloud SQL standby to reduce trial cost.",
2255
+ "Choose No for regional availability; choose Yes only when a standby is unnecessary.",
2256
+ "",
2257
+ "No keeps the production default: regional availability."
2258
+ ]
2259
+ };
2260
+
2261
+ // src/install/deployment-help.ts
2262
+ var HELP = { ...BASIC_HELP, ...ADVANCED_HELP };
2263
+ var quoted = (value) => `'${value.replaceAll("'", "'\\''")}'`;
2264
+ function commandFor(command, options) {
2265
+ return command?.replace(
2266
+ /\{(context|namespace|region|project)\}/g,
2267
+ (_, key) => quoted(String(options[key] || key.toUpperCase()))
2268
+ );
2269
+ }
2270
+ function deploymentHelp(target, field2, options = {}) {
2271
+ const key = Object.hasOwn(HELP, `${target}:${field2}`) ? `${target}:${field2}` : field2;
2272
+ if (!Object.hasOwn(HELP, key)) throw new Error(`Missing setup guidance for ${field2}.`);
2273
+ const [title, purpose, find, example, behavior, command] = HELP[key];
2274
+ const question = field2 === "target" ? "Where should Oya run?" : void 0;
2275
+ return { title, question, purpose, find, example, behavior, command: commandFor(command, options) };
2276
+ }
2277
+ function deploymentQuestion(target, field2, options = {}) {
2278
+ return presentQuestion(deploymentHelp(target, field2, options));
2279
+ }
2280
+
2281
+ // src/install/deployment-process.ts
2282
+ import { spawn as spawn3 } from "child_process";
2283
+ function startProbe(command, args) {
2284
+ return spawn3(command, args, { stdio: "pipe", detached: process.platform !== "win32" });
2285
+ }
2286
+ var Probe = class {
2287
+ /** The inspection process and its owned helpers. */
2288
+ child;
2289
+ /** One promise settlement, independent of pipe closure. */
2290
+ resolve;
2291
+ /** Only bounded stdout is retained. */
2292
+ output = "";
2293
+ /** Timeout/error/close may race; the first outcome owns cleanup. */
2294
+ settled = false;
2295
+ /** The hard deadline is released on every outcome. */
2296
+ timer;
2297
+ constructor(child, resolve2, timeoutMs) {
2298
+ this.child = child;
2299
+ this.resolve = resolve2;
2300
+ this.timer = setTimeout(() => this.finish(null), timeoutMs);
2301
+ }
2302
+ /** Drain stderr and close stdin so a probe cannot request interactive input. */
2303
+ watch() {
2304
+ this.child.stdin.end();
2305
+ this.child.stderr.resume();
2306
+ this.child.stdout.on("data", (chunk) => this.append(String(chunk)));
2307
+ this.child.on("error", () => this.finish(null));
2308
+ this.child.on("close", (code) => this.finish(code === 0 ? this.output.trim() : null));
2309
+ }
2310
+ /** Enforce the output ceiling without waiting for a noisy process to exit. */
2311
+ append(chunk) {
2312
+ this.output += chunk;
2313
+ if (this.output.length > DEPLOY_PROBE_BYTES) this.finish(null);
2314
+ }
2315
+ /** Destroy pipes and stop helpers before resolving, rather than depending on a future close event. */
2316
+ finish(value) {
2317
+ if (this.settled) return;
2318
+ this.settled = true;
2319
+ clearTimeout(this.timer);
2320
+ terminate(this.child.pid, "SIGKILL");
2321
+ this.child.stdin.destroy();
2322
+ this.child.stdout.destroy();
2323
+ this.child.stderr.destroy();
2324
+ this.resolve(value);
2325
+ }
2326
+ };
2327
+ function deploymentProbe(command, args, timeoutMs = DEPLOY_PROBE_MS) {
2328
+ return new Promise((resolve2) => new Probe(startProbe(command, args), resolve2, timeoutMs).watch());
2329
+ }
2330
+ function terminate(pid, signal) {
2331
+ if (!pid) return;
2332
+ try {
2333
+ process.kill(process.platform === "win32" ? pid : -pid, signal);
2334
+ } catch {
2335
+ }
2336
+ }
2337
+ var ScriptSignals = class {
2338
+ /** Cancellation must still fail if a script handles TERM by exiting zero. */
2339
+ cancelled = false;
2340
+ /** The script and its children belong to this group. */
2341
+ child;
2342
+ /** Give cleanup a bounded grace period. */
2343
+ timer;
2344
+ constructor(child) {
2345
+ this.child = child;
2346
+ process.once("SIGINT", this.stop);
2347
+ process.once("SIGTERM", this.stop);
2348
+ }
2349
+ /** Forward interruption, then stop any processes which ignored it. */
2350
+ stop = () => {
2351
+ this.cancelled = true;
2352
+ this.child.kill("SIGTERM");
2353
+ this.timer ??= setTimeout(() => terminate(this.child.pid, "SIGKILL"), DEPLOY_KILL_MS);
2354
+ };
2355
+ /** Release process-global handlers once this script ends. */
2356
+ close() {
2357
+ clearTimeout(this.timer);
2358
+ if (this.cancelled) terminate(this.child.pid, "SIGKILL");
2359
+ process.removeListener("SIGINT", this.stop);
2360
+ process.removeListener("SIGTERM", this.stop);
2361
+ }
2362
+ };
2363
+ function startScript(script, args, cwd, env2) {
2364
+ return spawn3("bash", [script, ...args], { cwd, env: env2, stdio: "inherit", detached: process.platform !== "win32" });
2365
+ }
2366
+ function watchScript(child, operation, resolve2, reject) {
2367
+ const signals = new ScriptSignals(child);
2368
+ child.on("error", () => reject(startFailure(signals, operation)));
2369
+ child.on("close", (code, signal) => {
2370
+ signals.close();
2371
+ if (code === 0 && !signals.cancelled) resolve2();
2372
+ else reject(scriptFailure(operation, signals.cancelled, code, signal));
2373
+ });
2374
+ }
2375
+ function startFailure(signals, operation) {
2376
+ signals.close();
2377
+ return new Error(`Could not start deployment ${operation}. Check bash and the checkout.`);
2378
+ }
2379
+ function scriptFailure(operation, cancelled, code, signal) {
2380
+ return new Error(`Deployment ${operation} failed (${cancelled ? "cancelled" : signal || `exit ${code}`}).`);
2381
+ }
2382
+ function runDeploymentScript(script, args, cwd, env2) {
2383
+ return new Promise((resolve2, reject) => watchScript(startScript(script, args, cwd, env2), args[0], resolve2, reject));
2384
+ }
2385
+
2386
+ // src/install/deployment-interview.ts
2387
+ var IMAGE_OPTIONS = [
2388
+ { id: "registry", label: "Build and push", note: "Use a registry you can push to" },
2389
+ {
2390
+ id: "image",
2391
+ label: "Use a published image",
2392
+ note: "Built from deployments/image"
2393
+ }
2394
+ ];
2395
+ var DATABASE_OPTIONS = [
2396
+ { id: "managed", label: "Managed Postgres", note: "Production \xB7 use your existing database" },
2397
+ { id: "cluster", label: "Postgres in this cluster", note: "Trial \xB7 create a persistent database pod" }
2398
+ ];
2399
+ var ACCESS_OPTIONS = [
2400
+ { id: "https", label: "HTTPS", note: "Production \xB7 use an ACM certificate" },
2401
+ { id: "http", label: "HTTP trial", note: "unencrypted; for trying it out only" }
2402
+ ];
2403
+ var ADVANCED_OPTIONS = [
2404
+ { id: "no", label: "Use the defaults", note: "recommended; change settings later in oya.env" },
2405
+ { id: "yes", label: "Customize", note: "replicas, images, networking and optional settings" }
2406
+ ];
2407
+ var BOOLEAN_OPTIONS = [
2408
+ { id: "no", label: "No" },
2409
+ { id: "yes", label: "Yes" }
2410
+ ];
2411
+ var QUESTIONS = {
2412
+ docker: [["domain", "Domain (localhost for a local certificate):", "localhost"]],
2413
+ k8s: [
2414
+ ["context", "Kubernetes context:", ""],
2415
+ ["namespace", "Namespace:", "oya"]
2416
+ ],
2417
+ ecs: [
2418
+ ["region", "AWS region:", "us-east-1"],
2419
+ ["stack", "Stack name:", "oya"]
2420
+ ],
2421
+ gcloud: [
2422
+ ["project", "Google Cloud project ID:", ""],
2423
+ ["region", "Region:", "us-central1"],
2424
+ ["name", "Deployment name:", "oya"],
2425
+ ["domain", "Domain (blank keeps access private):", ""]
2426
+ ]
2427
+ };
2428
+ var ADVANCED = {
2429
+ docker: ["browser-image", "server-image"],
2430
+ k8s: [
2431
+ "replicas",
2432
+ "host",
2433
+ "tls-secret",
2434
+ "cluster-issuer",
2435
+ "ingress-class",
2436
+ "browser-ttl",
2437
+ "browser-image",
2438
+ "env-file",
2439
+ "platform"
2440
+ ],
2441
+ ecs: [
2442
+ "replicas",
2443
+ "vpc-id",
2444
+ "public-subnets",
2445
+ "private-subnets",
2446
+ "allowed-cidr",
2447
+ "db-class",
2448
+ "single-az-db",
2449
+ "browser-image",
2450
+ "server-image",
2451
+ "env-file"
2452
+ ],
2453
+ gcloud: ["replicas", "db-tier", "single-zone-db", "browser-image", "env-file"]
2454
+ };
2455
+ async function chooseDeploymentTarget() {
2456
+ const options = Object.entries(DEPLOYMENT_TARGETS).map(([id, value]) => ({
2457
+ id,
2458
+ label: value.label,
2459
+ note: value.note
2460
+ }));
2461
+ return deploymentTarget(await choose("Where should Oya run?", options, deploymentQuestion("docker", "target")));
2462
+ }
2463
+ async function field(s, key, label, fallback, required2 = true) {
2464
+ if (s.options[key] !== void 0 || s.unattended) return;
2465
+ const presentation = deploymentQuestion(s.target, key, s.options);
2466
+ s.options[key] = await ask(label, fallback, { validate: (v) => fieldProblem(key, v, required2), presentation });
2467
+ }
2468
+ function fieldProblem(key, value, required2) {
2469
+ if (required2 && !value) return "Required for this destination.";
2470
+ if (/[\r\n\0]/.test(value)) return "Use a single line.";
2471
+ return deploymentFieldProblem(key, value);
2472
+ }
2473
+ async function kubernetes2(s) {
2474
+ if (s.target !== "k8s" || s.unattended) return;
2475
+ const source = await choose("Control-plane image:", IMAGE_OPTIONS, deploymentQuestion(s.target, "image-source"));
2476
+ await field(s, source, source === "registry" ? "Registry repository:" : "Deployment image:", "");
2477
+ const database = await choose("Postgres:", DATABASE_OPTIONS, deploymentQuestion(s.target, "database-source"));
2478
+ s.options["in-cluster-postgres"] = database === "cluster";
2479
+ }
2480
+ async function ecs(s) {
2481
+ if (s.target !== "ecs" || s.unattended) return;
2482
+ const access = await choose("Public access:", ACCESS_OPTIONS, deploymentQuestion(s.target, "access"));
2483
+ if (access === "http") {
2484
+ s.options["http-only"] = true;
2485
+ return;
2486
+ }
2487
+ await field(s, "certificate-arn", "ACM certificate ARN:", "");
2488
+ return publicUrlQuestion();
2489
+ }
2490
+ function publicUrlQuestion() {
2491
+ return ask("Public HTTPS URL matching that certificate:", "", {
2492
+ presentation: deploymentQuestion("ecs", "public-url"),
2493
+ validate: (v) => /^https:\/\/[^\s/@]+\/?$/.test(v) ? void 0 : "Enter an HTTPS origin, such as https://oya.example.com."
2494
+ });
2495
+ }
2496
+ async function advanced(s) {
2497
+ if (s.unattended) return;
2498
+ const choice = await choose("Advanced settings?", ADVANCED_OPTIONS, deploymentQuestion(s.target, "advanced"));
2499
+ if (choice === "no") return;
2500
+ for (const key of ADVANCED[s.target]) await advancedField(s, key);
2501
+ }
2502
+ async function advancedField(s, key) {
2503
+ if (DEPLOYMENT_TARGETS[s.target].options[key] === "boolean")
2504
+ s.options[key] = await choose(`${key}?`, BOOLEAN_OPTIONS, deploymentQuestion(s.target, key, s.options)) === "yes";
2505
+ else await field(s, key, `${key} (blank keeps the default):`, "", false);
2506
+ }
2507
+ async function interviewDeployment(target, unattended) {
2508
+ const s = { target, unattended, options: unattended ? { ...DEPLOYMENT_TARGETS[target].defaults } : {} };
2509
+ setupPhase("Configure");
2510
+ for (const [key, label, fallback] of QUESTIONS[target]) await field(s, key, label, fallback, key !== "domain");
2511
+ await kubernetes2(s);
2512
+ const publicUrl = await ecs(s);
2513
+ await advanced(s);
2514
+ return finishInterview(s, publicUrl);
2515
+ }
2516
+ function finishInterview(s, publicUrl) {
2517
+ return parseDeploymentPlan({
2518
+ version: DEPLOYMENT_PLAN_VERSION,
2519
+ target: s.target,
2520
+ options: s.options,
2521
+ ...publicUrl ? { publicUrl } : {}
2522
+ });
2523
+ }
2524
+ async function deploymentDatabase(plan2, unattended) {
2525
+ if (plan2.target !== "k8s" || plan2.options["in-cluster-postgres"]) return "";
2526
+ const existing = process.env.OYA_DEPLOY_DATABASE_URL || process.env.DATABASE_URL;
2527
+ if (existing) return checkedDatabase(existing);
2528
+ return askDatabase2(unattended);
2529
+ }
2530
+ function checkedDatabase(value) {
2531
+ const url = databaseUrl(value);
2532
+ if (!url || !["postgres:", "postgresql:"].includes(url.protocol) || !url.hostname || /[\r\n\0]/.test(value))
2533
+ throw new Error("OYA_DEPLOY_DATABASE_URL must be a Postgres connection string. Its value was not printed.");
2534
+ return value;
2535
+ }
2536
+ function databaseUrl(value) {
2537
+ try {
2538
+ return new URL(value);
2539
+ } catch {
2540
+ return null;
2541
+ }
2542
+ }
2543
+ function askDatabase2(unattended) {
2544
+ if (unattended)
2545
+ throw new Error(
2546
+ "Managed Kubernetes Postgres needs OYA_DEPLOY_DATABASE_URL in the environment; it is never saved in the plan."
2547
+ );
2548
+ return askSecret("Postgres connection string:", {
2549
+ presentation: deploymentQuestion("k8s", "database-url"),
2550
+ validate: (v) => /^postgres(?:ql)?:\/\/\S+$/.test(v) ? void 0 : "Enter a postgres:// connection string."
2551
+ });
2552
+ }
2553
+ async function showContextHint(target) {
2554
+ if (target !== "k8s") return;
2555
+ const current = await deploymentProbe("kubectl", ["config", "current-context"]);
2556
+ if (current) note(`Current context: ${current}. Confirm it by entering the context below.`);
2557
+ }
2558
+
2559
+ // src/install/deployment-preflight.ts
2560
+ import { existsSync as existsSync4 } from "fs";
2561
+ import { join as join5, resolve } from "path";
2562
+ var VERSION_ARGS = {
2563
+ openssl: ["version"],
2564
+ kubectl: ["version", "--client=true", "-o", "json"]
2565
+ };
2566
+ var REMEDIES = {
2567
+ docker: "Install Docker Desktop or Docker Engine, then start it.",
2568
+ aws: "Install AWS CLI v2 and run aws sso login or configure your AWS identity.",
2569
+ gcloud: "Install the Google Cloud CLI and run gcloud auth login.",
2570
+ kubectl: "Install kubectl and configure access to your cluster.",
2571
+ "gke-gcloud-auth-plugin": "Install the Google Cloud gke-gcloud-auth-plugin component."
2572
+ };
2573
+ var KUBE_PROBE_ARGS = ["get", "namespace", "kube-system", "-o", "name", "--request-timeout=10s"];
2574
+ var AWS_PROBE_ARGS = ["sts", "get-caller-identity", "--query", "Account", "--output", "text"];
2575
+ var PREVIEW_CHECK = {
2576
+ ok: true,
2577
+ label: "Cloud credentials and destination access",
2578
+ detail: "not checked in preview; checked before a real deploy"
2579
+ };
2580
+ async function toolCheck(tool) {
2581
+ const args = Object.hasOwn(VERSION_ARGS, tool) ? VERSION_ARGS[tool] : ["--version"];
2582
+ const value = await deploymentProbe(tool, args), ok = value !== null;
2583
+ const remedy = REMEDIES[tool] || `Install ${tool} and put it on PATH.`;
2584
+ return { ok, label: tool, fatal: true, detail: ok ? "available" : remedy };
2585
+ }
2586
+ async function dockerCheck(args, label, remedy) {
2587
+ const result = await deploymentProbe("docker", args);
2588
+ return { ok: !!result, label, fatal: true, detail: result ? "available" : remedy };
2589
+ }
2590
+ async function dockerChecks2(target) {
2591
+ const checks = [
2592
+ await dockerCheck(["info", "--format", "{{.ID}}"], "Docker daemon", "Start Docker Desktop or the Docker daemon."),
2593
+ await dockerCheck(["buildx", "version"], "Docker buildx", "Install the Docker buildx plugin.")
2594
+ ];
2595
+ if (target === "docker") checks.push(await composeCheck2());
2596
+ return checks;
2597
+ }
2598
+ async function composeCheck2() {
2599
+ const version2 = await deploymentProbe("docker", ["compose", "version", "--short"]);
2600
+ const ok = atLeast(version2, COMPOSE_MIN.major, COMPOSE_MIN.minor);
2601
+ return { ok, label: "Docker Compose \u2265 2.24", fatal: true, detail: "Update Docker Compose if this check fails." };
2602
+ }
2603
+ async function kubernetesIdentity(p) {
2604
+ const args = ["--context", String(p.options.context), ...KUBE_PROBE_ARGS];
2605
+ return identity("kubectl", args, "Kubernetes context", "Check the context and your cluster access.");
2606
+ }
2607
+ async function awsIdentity(p) {
2608
+ const args = ["--region", String(p.options.region), ...AWS_PROBE_ARGS];
2609
+ return identity("aws", args, "AWS account", "Sign in with aws sso login and check the selected region.");
2610
+ }
2611
+ async function googleIdentity(p) {
2612
+ const project = String(p.options.project), args = ["--project", project, "projects", "describe", project, "--format=value(projectId)"];
2613
+ return identity("gcloud", args, "Google Cloud project", "Run gcloud auth login and check project permissions.");
2614
+ }
2615
+ var IDENTITIES = { docker: async () => [], k8s: kubernetesIdentity, ecs: awsIdentity, gcloud: googleIdentity };
2616
+ async function identity(command, args, label, remedy) {
2617
+ const result = await deploymentProbe(command, args);
2618
+ return { ok: !!result, label, fatal: true, detail: result || remedy };
2619
+ }
2620
+ function settingsChecks(root, p) {
2621
+ const settings = p.options["env-file"];
2622
+ if (!settings) return [];
2623
+ const ok = existsSync4(resolve(root, String(settings)));
2624
+ return [{ ok, label: "Optional settings file", fatal: true, detail: "The selected env-file must exist." }];
2625
+ }
2626
+ function fileChecks(root, p) {
2627
+ const script = join5(root, "deployments", p.target, "deploy.sh"), ok = existsSync4(script);
2628
+ const detail = "Use an up-to-date Oya checkout containing deployments/.";
2629
+ return [{ ok, label: `deployments/${p.target}/deploy.sh`, fatal: true, detail }, ...settingsChecks(root, p)];
2630
+ }
2631
+ async function destinationChecks(p, preview2, toolsReady) {
2632
+ if (preview2) return [PREVIEW_CHECK];
2633
+ if (!toolsReady || !Object.hasOwn(IDENTITIES, p.target)) return [];
2634
+ return [await IDENTITIES[p.target](p)].flat();
2635
+ }
2636
+ async function deploymentPreflight(root, p, preview2) {
2637
+ const tools = ["bash", "git", "docker", "jq", "openssl", "curl", ...DEPLOYMENT_TARGETS[p.target].tools];
2638
+ const checks = await Promise.all(tools.map(toolCheck));
2639
+ checks.push(...await dockerChecks2(p.target), ...fileChecks(root, p));
2640
+ const ready = checks.every((c) => c.ok);
2641
+ checks.push(...await destinationChecks(p, preview2, ready));
2642
+ return checks;
2643
+ }
2644
+
2645
+ // src/install/deployment-report.ts
2646
+ var DESTINATION_FIELDS = /* @__PURE__ */ new Set(["context", "namespace", "region", "stack", "project", "name"]);
2647
+ var ACCESS_FIELDS = /* @__PURE__ */ new Set([
2648
+ "domain",
2649
+ "host",
2650
+ "tls-secret",
2651
+ "cluster-issuer",
2652
+ "ingress-class",
2653
+ "http-only",
2654
+ "certificate-arn",
2655
+ "allowed-cidr"
2656
+ ]);
2657
+ var quoteDeploymentArg = (value) => `'${value.replaceAll("'", "'\\''")}'`;
2658
+ function deploymentCommand(p, command) {
2659
+ const args = optionArguments(destinationOptions(p.target, p.options));
2660
+ const line = ["bash", `deployments/${p.target}/deploy.sh`, command, ...args].map(quoteDeploymentArg).join(" ");
2661
+ return p.publicUrl && command === "smoke" ? `OYA_DEPLOY_PUBLIC_URL=${quoteDeploymentArg(p.publicUrl)} ${line}` : line;
2662
+ }
2663
+ function printDeploymentPlan(p, root) {
2664
+ setupSection("Destination", [
2665
+ ["Target", DEPLOYMENT_TARGETS[p.target].label],
2666
+ ...planFields(p, (key) => DESTINATION_FIELDS.has(key))
2667
+ ]);
2668
+ printResourcePlan(p, root);
2669
+ printAccessPlan(p);
2670
+ printVerificationPlan(p);
2671
+ }
2672
+ function printResourcePlan(p, root) {
2673
+ setupSection("Resources", [
2674
+ ["Creates or updates", DEPLOYMENT_TARGETS[p.target].resources],
2675
+ ["Checkout", root],
2676
+ ["Secrets", DEPLOYMENT_TARGETS[p.target].secrets],
2677
+ ...planFields(p, (key) => !DESTINATION_FIELDS.has(key) && !ACCESS_FIELDS.has(key))
2678
+ ]);
2679
+ }
2680
+ function printAccessPlan(p) {
2681
+ setupSection("Access", [...planFields(p, (key) => ACCESS_FIELDS.has(key)), ["Public URL", plannedAddress(p)]]);
2682
+ }
2683
+ function plannedAddress(p) {
2684
+ if (p.publicUrl) return p.publicUrl;
2685
+ if (p.target === "docker") return `https://${p.options.domain || "localhost"}`;
2686
+ if (p.options.host || p.options.domain) return `https://${p.options.host || p.options.domain}`;
2687
+ return p.target === "ecs" ? "Assigned by AWS after deploy" : "Private \xB7 use a port-forward";
2688
+ }
2689
+ function planFields(p, include) {
2690
+ return Object.entries(p.options).filter(([key, value]) => value && include(key)).map(([key, value]) => {
2691
+ const label = key === "http-only" ? "HTTP trial" : deploymentHelp(p.target, key).title;
2692
+ return [label, value === true ? "Yes" : String(value)];
2693
+ });
2694
+ }
2695
+ function printVerificationPlan(p) {
2696
+ setupSection("Verification", [
2697
+ ["Control plane", "Wait for rollout and /readyz"],
2698
+ ["Browser", "Start \u2192 connect \u2192 navigate \u2192 stop"]
2699
+ ]);
2700
+ if (p.target === "ecs" || p.target === "gcloud")
2701
+ note("Cloud resources are billable. Existing secrets and data are retained on redeploy.");
2702
+ }
2703
+ function printDeploymentChecks(checks) {
2704
+ const rows = checks.map((check2) => [check2.label, checkResult(check2)]);
2705
+ setupSection("Preflight", rows);
2706
+ }
2707
+ function checkResult(check2) {
2708
+ if (/not checked/i.test(check2.detail || "")) return `Skipped \xB7 ${check2.detail}`;
2709
+ const status = check2.ok ? "Ready" : check2.fatal ? "Required" : "Check";
2710
+ return `${status}${check2.detail ? ` \xB7 ${check2.detail}` : ""}`;
2711
+ }
2712
+ function endpoint(p) {
2713
+ directEndpoint(p);
2714
+ clusterEndpoint(p);
2715
+ if (p.target === "k8s" && !p.options.host || p.target === "gcloud" && !p.options.domain) privateAccess(p);
2716
+ }
2717
+ function directEndpoint(p) {
2718
+ if (p.target === "docker")
2719
+ note(
2720
+ `Endpoint: https://${p.options.domain || "localhost"}${p.options.domain === "localhost" ? " (local certificate)" : ""}`
2721
+ );
2722
+ if (p.target === "ecs") note(`Endpoint: ${p.publicUrl || "the load-balancer URL printed above"}`);
2723
+ }
2724
+ function clusterEndpoint(p) {
2725
+ if (p.target === "k8s" && p.options.host)
2726
+ note(`Public URL: https://${p.options.host}; DNS/TLS must resolve separately.`);
2727
+ if (p.target === "gcloud" && p.options.domain)
2728
+ note(
2729
+ `Public URL: https://${p.options.domain}; follow the DNS instructions above; certificate issuance may still be pending.`
2730
+ );
2731
+ }
2732
+ function privateAccess(p) {
2733
+ const context = p.target === "k8s" ? String(p.options.context) : `gke_${p.options.project}_${p.options.region}_${p.options.name}`;
2734
+ const namespace = String(p.options.namespace || "oya");
2735
+ const args = ["kubectl", "--context", context, "-n", namespace, "port-forward", "svc/oya-control-plane", "3100:3100"];
2736
+ note("Access is private. To open the dashboard at http://localhost:3100:");
2737
+ note(args.map(quoteDeploymentArg).join(" "));
2738
+ }
2739
+ function printDeploymentRecovery(p, root) {
2740
+ note(`Run these from ${root}:`);
2741
+ for (const command of ["status", "logs", "keys", "smoke"]) note(deploymentCommand(p, command));
2742
+ note(`Retry: oya install --config ${quoteDeploymentArg(`${root}/oya-install.json`)}`);
2743
+ }
2744
+ function printDeploymentDone(p, root) {
2745
+ success("Oya is ready. Control-plane readiness and browser smoke check passed.");
2746
+ if (p.target === "k8s" || p.target === "gcloud")
2747
+ note("Verified through a private port-forward; public DNS/TLS was not tested.");
2748
+ endpoint(p);
2749
+ note("Sign in with the API key printed by the deployment, or retrieve it with the keys command.");
2750
+ printDeploymentRecovery(p, root);
2751
+ }
2752
+ function printDeploymentIncomplete(p, root) {
2753
+ warn("Deployment verification incomplete. Existing resources and secrets were kept.");
2754
+ printDeploymentRecovery(p, root);
2755
+ }
2756
+
2757
+ // src/install/deployment.ts
2758
+ var PLAN_FILE = "oya-install.json";
2759
+ function savedPlan(flags) {
2760
+ if (typeof flags.config !== "string") return null;
2761
+ const plan2 = readJsonFile(flags.config);
2762
+ if (!plan2 || plan2.version !== 1 && plan2.version !== DEPLOYMENT_PLAN_VERSION)
2763
+ throw new Error("Unsupported install configuration version. Expected version 1 or 2.");
2764
+ if (plan2.version === 1 && flags.target) throw new Error("--target cannot override a version 1 saved installation.");
2765
+ return plan2;
2766
+ }
2767
+ function legacy(flags, saved) {
2768
+ if (saved) return saved.version === 1;
2769
+ return flags.yes === true && !flags.target;
2770
+ }
2771
+ async function gatherDeployment(flags, saved) {
2772
+ if (saved) return replayDeployment(flags, saved);
2773
+ const target = flags.target ? deploymentTarget(flags.target) : await chooseDeploymentTarget();
2774
+ if (flags.target) setupAnswer("Target", DEPLOYMENT_TARGETS[target].label);
2775
+ if (!flags.yes) await showContextHint(target);
2776
+ return interviewDeployment(target, flags.yes === true);
2777
+ }
2778
+ function replayDeployment(flags, saved) {
2779
+ const plan2 = parseDeploymentPlan(saved);
2780
+ if (flags.target && flags.target !== plan2.target)
2781
+ throw new Error("--target conflicts with the saved deployment target.");
2782
+ setupAnswer("Target", DEPLOYMENT_TARGETS[plan2.target].label);
2783
+ setupPhase("Configure");
2784
+ return plan2;
2785
+ }
2786
+ function saveDeploymentPlan(root, p) {
2787
+ const path = join6(root, PLAN_FILE), temporary = `${path}.${process.pid}.tmp`;
2788
+ writeFileSync3(temporary, `${JSON.stringify(p, null, JSON_INDENT)}
2789
+ `, { mode: ENV_FILE_MODE, flag: "wx" });
2790
+ renameSync(temporary, path);
2791
+ note(`Saved ${path}; credentials stay in the target's secret store.`);
2792
+ }
2793
+ async function executeDeployment(root, p, databaseUrl2) {
2794
+ try {
2795
+ await deployAndVerify(root, p, databaseUrl2);
2796
+ } catch (err) {
2797
+ printDeploymentIncomplete(p, root);
2798
+ throw err;
2799
+ }
2800
+ printDeploymentDone(p, root);
2801
+ }
2802
+ async function deployAndVerify(root, p, databaseUrl2) {
2803
+ const script = join6(root, "deployments", p.target, "deploy.sh");
2804
+ const env2 = deploymentEnvironment(p, databaseUrl2);
2805
+ setupPhase("Deploy");
2806
+ await runDeploymentScript(script, ["deploy", ...optionArguments(p.options)], root, env2);
2807
+ setupPhase("Verify");
2808
+ note("Verifying control-plane readiness and a complete browser session\u2026");
2809
+ await runDeploymentScript(script, ["smoke", ...optionArguments(destinationOptions(p.target, p.options))], root, env2);
2810
+ }
2811
+ function deploymentEnvironment(p, databaseUrl2) {
2812
+ return {
2813
+ ...process.env,
2814
+ OYA_INSTALLER: "1",
2815
+ OYA_DEPLOY_DATABASE_URL: databaseUrl2,
2816
+ OYA_DEPLOY_PUBLIC_URL: p.publicUrl || ""
2817
+ };
2818
+ }
2819
+ function announceDeployment() {
2820
+ setupIntro();
2821
+ steps(0);
2822
+ }
2823
+ async function installDeployment(flags) {
2824
+ const saved = savedPlan(flags);
2825
+ if (legacy(flags, saved)) return false;
2826
+ if (flags.target) deploymentTarget(flags.target);
2827
+ announceDeployment();
2828
+ const plan2 = await gatherDeployment(flags, saved);
2829
+ const root = await locateRepo(flags["dry-run"] === true, true);
2830
+ await applyDeployment(root, plan2, flags, !!saved);
2831
+ return true;
2832
+ }
2833
+ async function applyDeployment(root, p, flags, replay) {
2834
+ const checks = await deploymentPreflight(root, p, flags["dry-run"] === true);
2835
+ showDeployment(p, root, checks);
2836
+ if (flags["dry-run"] === true) return printPreview();
2837
+ saveDeploymentPlan(root, p);
2838
+ if (checks.some((c) => !c.ok && c.fatal))
2839
+ throw new Error("Cannot deploy: fix the failed preflight checks, then rerun the saved plan.");
2840
+ const databaseUrl2 = await deploymentDatabase(p, replay || flags.yes === true);
2841
+ await executeDeployment(root, p, databaseUrl2);
2842
+ }
2843
+ function showDeployment(p, root, checks) {
2844
+ printDeploymentPlan(p, root);
2845
+ printDeploymentChecks(checks);
2846
+ }
2847
+ function printPreview() {
2848
+ note("Preview only. No files or resources changed. Database credentials are hidden and checked during deployment.");
2849
+ }
2850
+
1366
2851
  // src/install.ts
1367
2852
  var ANSWERS_FILE = "oya-install.json";
1368
2853
  function presetFor(m) {
@@ -1391,8 +2876,8 @@ async function checkMachine(root, answers, dryRun) {
1391
2876
  throw new Error(`Install cannot continue: ${blocking.map((c) => c.label).join(", ")}`);
1392
2877
  }
1393
2878
  }
1394
- function warnLocalDatabase(answers, databaseUrl = "") {
1395
- if (answers.host !== "docker" || !/(localhost|127\.0\.0\.1)/.test(databaseUrl)) return;
2879
+ function warnLocalDatabase(answers, databaseUrl2 = "") {
2880
+ if (answers.host !== "docker" || !/(localhost|127\.0\.0\.1)/.test(databaseUrl2)) return;
1396
2881
  warn("DATABASE_URL points at localhost, which inside a container means the container itself.");
1397
2882
  note("Use host.docker.internal (macOS, Windows) or the host IP so the server can reach it.");
1398
2883
  }
@@ -1415,14 +2900,14 @@ async function plan(m) {
1415
2900
  const { root, answers, secrets } = interviewed;
1416
2901
  await checkMachine(root, answers, m.dryRun);
1417
2902
  warnLocalDatabase(answers, secrets.DATABASE_URL);
1418
- const envPath = join5(root, ".env");
2903
+ const envPath = join7(root, ".env");
1419
2904
  const existing = readEnv(envPath);
1420
2905
  await guardKek(existing, answers, root, m);
1421
2906
  return { ...interviewed, envPath, existing, env: buildEnv(answers, secrets, existing) };
1422
2907
  }
1423
2908
  function writeFiles(p) {
1424
2909
  writeEnv(p.envPath, renderEnv(p.env.values, p.env.extra));
1425
- writeFileSync3(join5(p.root, ANSWERS_FILE), JSON.stringify(p.answers, null, JSON_INDENT) + "\n");
2910
+ writeFileSync4(join7(p.root, ANSWERS_FILE), JSON.stringify(p.answers, null, JSON_INDENT) + "\n");
1426
2911
  success(`wrote ${p.envPath}`);
1427
2912
  if (p.existing.OYA_PROFILE_SECRET) return;
1428
2913
  warn("OYA_PROFILE_SECRET was generated, back it up.");
@@ -1444,6 +2929,7 @@ async function apply2(p) {
1444
2929
  printDone(p.answers.publicUrl, p.env.apiKey);
1445
2930
  }
1446
2931
  async function cmdInstall(flags) {
2932
+ if (await installDeployment(flags)) return;
1447
2933
  const configPath2 = typeof flags.config === "string" ? flags.config : null;
1448
2934
  const m = { configPath: configPath2, yes: flags.yes === true, dryRun: flags["dry-run"] === true };
1449
2935
  const p = await plan(m);
@@ -1453,9 +2939,9 @@ async function cmdInstall(flags) {
1453
2939
  }
1454
2940
 
1455
2941
  // src/config.ts
1456
- import { readFileSync as readFileSync3, writeFileSync as writeFileSync4, mkdirSync as mkdirSync2, chmodSync as chmodSync2 } from "fs";
2942
+ import { readFileSync as readFileSync3, writeFileSync as writeFileSync5, mkdirSync as mkdirSync2, chmodSync as chmodSync2 } from "fs";
1457
2943
  import { homedir } from "os";
1458
- import { join as join6, dirname as dirname2 } from "path";
2944
+ import { join as join8, dirname as dirname2 } from "path";
1459
2945
 
1460
2946
  // src/constants.ts
1461
2947
  var ARGV_SKIP = 2;
@@ -1504,7 +2990,7 @@ var Status2 = {
1504
2990
  var MODELS_SHOWN = 8;
1505
2991
 
1506
2992
  // src/config.ts
1507
- var FILE = join6(process.env.OYA_CONFIG_HOME || join6(homedir(), ".oya"), "config.json");
2993
+ var FILE = join8(process.env.OYA_CONFIG_HOME || join8(homedir(), ".oya"), "config.json");
1508
2994
  function load() {
1509
2995
  try {
1510
2996
  return JSON.parse(readFileSync3(FILE, "utf8"));
@@ -1515,7 +3001,7 @@ function load() {
1515
3001
  function save(values) {
1516
3002
  const merged = { ...load(), ...values };
1517
3003
  mkdirSync2(dirname2(FILE), { recursive: true });
1518
- writeFileSync4(FILE, JSON.stringify(merged, null, JSON_INDENT2), { mode: CONFIG_FILE_MODE });
3004
+ writeFileSync5(FILE, JSON.stringify(merged, null, JSON_INDENT2), { mode: CONFIG_FILE_MODE });
1519
3005
  chmodSync2(FILE, CONFIG_FILE_MODE);
1520
3006
  }
1521
3007
  var configPath = FILE;
@@ -1606,8 +3092,8 @@ var OyaError = class extends Error {
1606
3092
  this.body = body;
1607
3093
  }
1608
3094
  };
1609
- function refusal(message, field, suggestion) {
1610
- const body = { error: message, code: "invalid_request", field, ...suggestion ? { suggestion } : {} };
3095
+ function refusal(message, field2, suggestion) {
3096
+ const body = { error: message, code: "invalid_request", field: field2, ...suggestion ? { suggestion } : {} };
1611
3097
  return new OyaError(message, Status3.BAD_REQUEST, body);
1612
3098
  }
1613
3099
  var node = () => globalThis.process;
@@ -1777,8 +3263,8 @@ function modelHeaders({ model }) {
1777
3263
  ["name", "X-Oya-Llm-Model"],
1778
3264
  ["apiKey", "X-Oya-Llm-Api-Key"]
1779
3265
  ];
1780
- const set = fields.filter(([field]) => model[field]);
1781
- return Object.fromEntries(set.map(([field, name]) => [name, headerSafe(model[field], `model.${field}`, MODEL_FIX)]));
3266
+ const set = fields.filter(([field2]) => model[field2]);
3267
+ return Object.fromEntries(set.map(([field2, name]) => [name, headerSafe(model[field2], `model.${field2}`, MODEL_FIX)]));
1782
3268
  }
1783
3269
  var LOCAL_HOST = /^(localhost|127\.)/i;
1784
3270
  function webAddress({ value, from }) {
@@ -1797,22 +3283,22 @@ function notInAHeader(ch) {
1797
3283
  const code = ch.codePointAt(0);
1798
3284
  return code < SPACE && code !== TAB || code === DEL || code > LATIN1_MAX;
1799
3285
  }
1800
- function headerSafe(value, field, ending) {
3286
+ function headerSafe(value, field2, ending) {
1801
3287
  const trimmed = value.trim();
1802
3288
  const chars = Array.from(trimmed);
1803
3289
  const at = chars.findIndex(notInAHeader);
1804
3290
  if (at < 0) return trimmed;
1805
3291
  const leading = Array.from(value).length - Array.from(value.trimStart()).length;
1806
3292
  const where = `position ${leading + at + 1} (${codePoint(chars[at])})`;
1807
- throw refusal(`${field} has a character HTTP headers cannot carry at ${where}. ${ending}`, field);
3293
+ throw refusal(`${field2} has a character HTTP headers cannot carry at ${where}. ${ending}`, field2);
1808
3294
  }
1809
3295
  var codePoint = (ch) => `U+${ch.codePointAt(0).toString(HEX).toUpperCase().padStart(CODE_POINT_DIGITS, "0")}`;
1810
3296
  var shown = (value) => typeof value === "string" ? JSON.stringify(value) : String(value);
1811
- function segment(value, field = "id") {
3297
+ function segment(value, field2 = "id") {
1812
3298
  if (typeof value !== "string" || !value)
1813
- throw refusal(`${field} must be a non-empty string, not ${shown(value)}`, field);
3299
+ throw refusal(`${field2} must be a non-empty string, not ${shown(value)}`, field2);
1814
3300
  if (value.includes("/") || value === "." || value === "..")
1815
- throw refusal(`${field} must be a single path segment (no "/" and not "." or ".."), not ${shown(value)}`, field);
3301
+ throw refusal(`${field2} must be a single path segment (no "/" and not "." or ".."), not ${shown(value)}`, field2);
1816
3302
  return encodeURIComponent(value);
1817
3303
  }
1818
3304
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -1967,8 +3453,8 @@ var Browser = class {
1967
3453
  * answered for you; a confirm() or prompt() waits for this, and every other
1968
3454
  * command fails fast with the dialog's text until it is answered.
1969
3455
  */
1970
- async handleDialog(accept, promptText) {
1971
- return this.command("handle_dialog", { accept, prompt_text: promptText });
3456
+ async handleDialog(accept, promptText2) {
3457
+ return this.command("handle_dialog", { accept, prompt_text: promptText2 });
1972
3458
  }
1973
3459
  /** `at` aims the wheel at an inner scroller (a results panel, a chat pane) instead of the page. */
1974
3460
  async scroll(direction, amount, at) {
@@ -2747,10 +4233,10 @@ async function askModelDetails(current, choice) {
2747
4233
  return llmUpdates(current, choice.id, key, model);
2748
4234
  }
2749
4235
  var needsNote = (p) => p.needs.some((f) => f.endsWith("_url")) ? "needs its ws:// address" : "needs an API key";
2750
- function fieldLabel(p, field) {
2751
- if (field.endsWith("_url")) return "Chrome DevTools address, such as ws://127.0.0.1:9222:";
2752
- if (field.endsWith("_api_key")) return `${p.label} API key:`;
2753
- return `${p.label} ${field.replace(/^[a-z]+_/, "").replace(/_/g, " ")}:`;
4236
+ function fieldLabel(p, field2) {
4237
+ if (field2.endsWith("_url")) return "Chrome DevTools address, such as ws://127.0.0.1:9222:";
4238
+ if (field2.endsWith("_api_key")) return `${p.label} API key:`;
4239
+ return `${p.label} ${field2.replace(/^[a-z]+_/, "").replace(/_/g, " ")}:`;
2754
4240
  }
2755
4241
  function providerOptions(current) {
2756
4242
  const note2 = (p) => p.needs.length ? p.configured ? "configured" : needsNote(p) : void 0;
@@ -2761,13 +4247,13 @@ async function askProvider(current, updates) {
2761
4247
  const provider = await choose("Browser provider:", providerOptions(current));
2762
4248
  updates.browser_provider = provider;
2763
4249
  const info = current.providers.find((p) => p.id === provider);
2764
- for (const field of info?.needs || []) await askField(info, field, updates);
4250
+ for (const field2 of info?.needs || []) await askField(info, field2, updates);
2765
4251
  return provider;
2766
4252
  }
2767
- async function askField(info, field, updates) {
2768
- const label = fieldLabel(info, field);
2769
- const value = field.endsWith("_url") ? await ask(label) : await askSecret(label);
2770
- if (value) updates[field] = value;
4253
+ async function askField(info, field2, updates) {
4254
+ const label = fieldLabel(info, field2);
4255
+ const value = field2.endsWith("_url") ? await ask(label) : await askSecret(label);
4256
+ if (value) updates[field2] = value;
2771
4257
  }
2772
4258
  var CAPTCHA_OPTIONS2 = [
2773
4259
  { id: "", label: "No", note: "providers that solve natively still will" },
@@ -2811,7 +4297,7 @@ async function cmdInit(flags) {
2811
4297
  }
2812
4298
 
2813
4299
  // src/commands/browsers.ts
2814
- import { spawn as spawn3 } from "child_process";
4300
+ import { spawn as spawn4 } from "child_process";
2815
4301
  function identityOptions(flags) {
2816
4302
  return {
2817
4303
  persona: flagStr(flags, "persona") || "default",
@@ -2915,7 +4401,7 @@ function opener(url) {
2915
4401
  async function cmdOpen(flags) {
2916
4402
  const browser = await targetBrowser(client(flags), flags);
2917
4403
  const [command, args] = opener(browser.liveViewUrl());
2918
- spawn3(command, args, { detached: true, stdio: "ignore" }).unref();
4404
+ spawn4(command, args, { detached: true, stdio: "ignore" }).unref();
2919
4405
  out(flags, { ok: true, id: browser.id }, () => console.log(`Opening the live view of ${browser.id}`));
2920
4406
  }
2921
4407
 
@@ -3021,7 +4507,7 @@ async function cmdPersonas(args, flags) {
3021
4507
  }
3022
4508
 
3023
4509
  // src/commands/cookies.ts
3024
- import { chmodSync as chmodSync3, writeFileSync as writeFileSync5 } from "fs";
4510
+ import { chmodSync as chmodSync3, writeFileSync as writeFileSync6 } from "fs";
3025
4511
  var FORMATS = ["json", "playwright"];
3026
4512
  function formatOf(flags) {
3027
4513
  const format = flagStr(flags, "format") || "json";
@@ -3029,7 +4515,7 @@ function formatOf(flags) {
3029
4515
  throw usage(`Unknown format "${format}". Use --format json or --format playwright.`);
3030
4516
  }
3031
4517
  function writeJar(file, cookies) {
3032
- writeFileSync5(file, JSON.stringify(cookies, null, JSON_INDENT2) + "\n", { mode: PRIVATE_FILE_MODE });
4518
+ writeFileSync6(file, JSON.stringify(cookies, null, JSON_INDENT2) + "\n", { mode: PRIVATE_FILE_MODE });
3033
4519
  chmodSync3(file, PRIVATE_FILE_MODE);
3034
4520
  }
3035
4521
  var exportJar = async (oya, rest, flags) => {
@@ -3077,7 +4563,7 @@ async function cmdCookies(args, flags) {
3077
4563
  }
3078
4564
 
3079
4565
  // src/commands/playbooks.ts
3080
- import { writeFileSync as writeFileSync6 } from "fs";
4566
+ import { writeFileSync as writeFileSync7 } from "fs";
3081
4567
  var list2 = async (oya, _rest, flags) => {
3082
4568
  const playbooks = await oya.playbooks.list();
3083
4569
  out(flags, playbooks, () => {
@@ -3090,7 +4576,7 @@ var exportOne = async (oya, rest, flags) => {
3090
4576
  const doc = await oya.playbooks.export(rest[0]);
3091
4577
  const file = flagStr(flags, "out");
3092
4578
  if (!file) return console.log(JSON.stringify(doc, null, JSON_INDENT2));
3093
- writeFileSync6(file, JSON.stringify(doc, null, JSON_INDENT2) + "\n");
4579
+ writeFileSync7(file, JSON.stringify(doc, null, JSON_INDENT2) + "\n");
3094
4580
  out(flags, { ok: true, name: rest[0], file }, () => console.log(`\u2705 ${rest[0]} written to ${file}`));
3095
4581
  };
3096
4582
  var importOne = async (oya, rest, flags) => {
@@ -3140,18 +4626,18 @@ async function cmdWhoami(flags) {
3140
4626
  }
3141
4627
 
3142
4628
  // src/commands/stealth.ts
3143
- import { spawn as spawn4 } from "child_process";
4629
+ import { spawn as spawn5 } from "child_process";
3144
4630
  var HARNESS = "tests/integration/stealth.test.js";
3145
- var spawnHarness = (flags) => spawn4("node", [HARNESS, ...flags.live ? ["--live"] : []], {
4631
+ var spawnHarness = (flags) => spawn5("node", [HARNESS, ...flags.live ? ["--live"] : []], {
3146
4632
  cwd: process.env.OYA_SERVER_DIR || "server",
3147
4633
  stdio: "inherit"
3148
4634
  });
3149
4635
  function cmdStealthTest(flags) {
3150
- return new Promise((resolve, reject) => {
4636
+ return new Promise((resolve2, reject) => {
3151
4637
  const child = spawnHarness(flags);
3152
4638
  const missing = "Could not find the stealth harness. Run it from a checkout, or set OYA_SERVER_DIR.";
3153
4639
  child.on("error", () => reject(new Error(missing)));
3154
- child.on("exit", (code) => code === 0 ? resolve() : reject(new Error(`stealth test exited ${code}`)));
4640
+ child.on("exit", (code) => code === 0 ? resolve2() : reject(new Error(`stealth test exited ${code}`)));
3155
4641
  });
3156
4642
  }
3157
4643
 
@@ -3236,13 +4722,13 @@ async function runControl(command, args, flags) {
3236
4722
  }
3237
4723
 
3238
4724
  // src/help.ts
3239
- var HELP = `oya, thousands of browsers, one API
4725
+ var HELP2 = `oya, thousands of browsers, one API
3240
4726
 
3241
4727
  Usage: oya <command> [arguments] [options]
3242
4728
 
3243
4729
  Set up
3244
- oya install [--yes] [--dry-run] [--config <file>]
3245
- Stand up a self-hosted control plane;
4730
+ oya install [--target docker|k8s|ecs|gcloud] [--yes] [--dry-run] [--config <file>]
4731
+ Deploy using the examples in deployments/;
3246
4732
  --yes: SQLite + Docker here, no questions
3247
4733
  oya login [--key <key>] [--url <url>] Save an API key for this machine
3248
4734
  oya init Set your model, browser provider and sign-ins
@@ -3317,7 +4803,7 @@ Config: ${configPath}
3317
4803
 
3318
4804
  // src/commands/index.ts
3319
4805
  import { createRequire } from "module";
3320
- var help = async () => console.log(HELP);
4806
+ var help = async () => console.log(HELP2);
3321
4807
  function packageVersion() {
3322
4808
  const require2 = createRequire(import.meta.url);
3323
4809
  for (const path of ["../package.json", "../../package.json"]) {