@yunuseon/kayra 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/agent/skills/kayra-release/SKILL.md +1 -4
  2. package/agent/skills/kayra-rollout/SKILL.md +1 -4
  3. package/ansible/roles/app/tasks/main.yml +22 -0
  4. package/ansible/roles/platform/defaults/main.yml +3 -0
  5. package/ansible/roles/platform/tasks/main.yml +6 -86
  6. package/ansible/roles/platform/templates/platform.env.j2 +2 -0
  7. package/bin/kayra-app-hook.js +6 -0
  8. package/bin/kayra-app-init.js +6 -0
  9. package/bin/kayra-app-launch.js +6 -0
  10. package/bin/kayra-app-values.js +6 -0
  11. package/cli/dist/app-hook.js +75 -0
  12. package/cli/dist/app-init.js +65 -0
  13. package/cli/dist/app-launch.js +89 -0
  14. package/cli/dist/app-values.js +37 -0
  15. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-400-normal-BTotfTJu.woff +0 -0
  16. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-400-normal-DZqxrq2p.woff2 +0 -0
  17. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-600-normal-71GNu3SW.woff2 +0 -0
  18. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-600-normal-BGq0mW3O.woff +0 -0
  19. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-ext-400-normal-Dsrv2Tcn.woff +0 -0
  20. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-ext-400-normal-g30qAdWV.woff2 +0 -0
  21. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-ext-600-normal-Bz0x94Yp.woff +0 -0
  22. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-ext-600-normal-DUMzJB7m.woff2 +0 -0
  23. package/cli/dist/browser/assets/ibm-plex-sans-greek-400-normal-D9ESIMu3.woff +0 -0
  24. package/cli/dist/browser/assets/ibm-plex-sans-greek-400-normal-_efipK4i.woff2 +0 -0
  25. package/cli/dist/browser/assets/ibm-plex-sans-greek-600-normal-D-CqTdkO.woff +0 -0
  26. package/cli/dist/browser/assets/ibm-plex-sans-greek-600-normal-DzTrcv_p.woff2 +0 -0
  27. package/cli/dist/browser/assets/ibm-plex-sans-latin-400-normal-CDDApCn2.woff2 +0 -0
  28. package/cli/dist/browser/assets/ibm-plex-sans-latin-400-normal-CYLoc0-x.woff +0 -0
  29. package/cli/dist/browser/assets/ibm-plex-sans-latin-600-normal-Cu4Hd6ag.woff +0 -0
  30. package/cli/dist/browser/assets/ibm-plex-sans-latin-600-normal-CuJfVYMP.woff2 +0 -0
  31. package/cli/dist/browser/assets/ibm-plex-sans-latin-ext-400-normal-C5H60-Va.woff2 +0 -0
  32. package/cli/dist/browser/assets/ibm-plex-sans-latin-ext-400-normal-RBey6euL.woff +0 -0
  33. package/cli/dist/browser/assets/ibm-plex-sans-latin-ext-600-normal-DIrixKbi.woff +0 -0
  34. package/cli/dist/browser/assets/ibm-plex-sans-latin-ext-600-normal-DOrvGEcy.woff2 +0 -0
  35. package/cli/dist/browser/assets/ibm-plex-sans-vietnamese-400-normal-DG4YqDda.woff2 +0 -0
  36. package/cli/dist/browser/assets/ibm-plex-sans-vietnamese-400-normal-fK1oJ5dG.woff +0 -0
  37. package/cli/dist/browser/assets/ibm-plex-sans-vietnamese-600-normal-DgdngZtN.woff +0 -0
  38. package/cli/dist/browser/assets/ibm-plex-sans-vietnamese-600-normal-DpPYBSTl.woff2 +0 -0
  39. package/cli/dist/browser/assets/index-DzIVPXyL.css +1 -0
  40. package/cli/dist/browser/assets/index-SP8bCDrl.js +7 -0
  41. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  42. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
  43. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-500-normal-DJqRU3vO.woff +0 -0
  44. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-500-normal-DmUKJPL_.woff2 +0 -0
  45. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-600-normal-8K4wrrwR.woff +0 -0
  46. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  47. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-700-normal-BWTpRfYl.woff2 +0 -0
  48. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-700-normal-CEoEElIJ.woff +0 -0
  49. package/cli/dist/browser/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
  50. package/cli/dist/browser/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  51. package/cli/dist/browser/assets/jetbrains-mono-greek-500-normal-D7SFKleX.woff +0 -0
  52. package/cli/dist/browser/assets/jetbrains-mono-greek-500-normal-JpySY46c.woff2 +0 -0
  53. package/cli/dist/browser/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  54. package/cli/dist/browser/assets/jetbrains-mono-greek-600-normal-mc2nkWzM.woff +0 -0
  55. package/cli/dist/browser/assets/jetbrains-mono-greek-700-normal-C6CZE3T8.woff2 +0 -0
  56. package/cli/dist/browser/assets/jetbrains-mono-greek-700-normal-DEigVDxa.woff +0 -0
  57. package/cli/dist/browser/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  58. package/cli/dist/browser/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  59. package/cli/dist/browser/assets/jetbrains-mono-latin-500-normal-BWZEU5yA.woff2 +0 -0
  60. package/cli/dist/browser/assets/jetbrains-mono-latin-500-normal-CJOVTJB7.woff +0 -0
  61. package/cli/dist/browser/assets/jetbrains-mono-latin-600-normal-BfsvjouI.woff +0 -0
  62. package/cli/dist/browser/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  63. package/cli/dist/browser/assets/jetbrains-mono-latin-700-normal-BYuf6tUa.woff2 +0 -0
  64. package/cli/dist/browser/assets/jetbrains-mono-latin-700-normal-D3wTyLJW.woff +0 -0
  65. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  66. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
  67. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-500-normal-Cut-4mMH.woff2 +0 -0
  68. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-500-normal-ckzbgY84.woff +0 -0
  69. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  70. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-600-normal-DObL3zCW.woff +0 -0
  71. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-700-normal-CZipNAKV.woff2 +0 -0
  72. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-700-normal-CxPITLHs.woff +0 -0
  73. package/cli/dist/browser/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
  74. package/cli/dist/browser/assets/jetbrains-mono-vietnamese-500-normal-DNRqzVM1.woff +0 -0
  75. package/cli/dist/browser/assets/jetbrains-mono-vietnamese-600-normal-OWROknRo.woff +0 -0
  76. package/cli/dist/browser/assets/jetbrains-mono-vietnamese-700-normal-BDLVIk2r.woff +0 -0
  77. package/cli/dist/browser/index.html +10 -3
  78. package/cli/dist/clients/api/start.js +1 -1
  79. package/cli/dist/clients/cli/invocation.js +25 -0
  80. package/cli/dist/clients/cli/parser.js +24 -7
  81. package/cli/dist/clients/cli/text.js +3 -3
  82. package/cli/dist/clients/cli/values.js +0 -1
  83. package/cli/dist/clients/cli/views.js +9 -2
  84. package/cli/dist/clients/mcp/tools.js +8 -1
  85. package/cli/dist/clients/ui/assets.js +1 -0
  86. package/cli/dist/clients/wire/contract.js +2 -2
  87. package/cli/dist/clients/wire/queries.js +1 -0
  88. package/cli/dist/clients/wire/schemas.js +4 -1
  89. package/cli/dist/clients/wire/words.js +14 -0
  90. package/cli/dist/core/adapters/opentofu.js +1 -1
  91. package/cli/dist/core/app-hook/hooks.js +90 -0
  92. package/cli/dist/core/app-hook/token.js +49 -0
  93. package/cli/dist/core/app-init/plan.js +208 -0
  94. package/cli/dist/core/app-values/model.js +45 -0
  95. package/cli/dist/core/app-values/store.js +124 -0
  96. package/cli/dist/core/ctl/answers.js +14 -9
  97. package/cli/dist/core/fleet/brand.js +10 -12
  98. package/cli/dist/core/fleet/settings.js +14 -9
  99. package/cli/dist/core/operations/catalog.js +46 -1
  100. package/cli/dist/core/operations/dispatch.js +37 -6
  101. package/cli/dist/core/recipes/app-check.js +14 -1
  102. package/cli/dist/core/recipes/app-hook.js +26 -0
  103. package/cli/dist/core/recipes/app-values.js +21 -0
  104. package/cli/dist/core/recipes/doctor.js +2 -2
  105. package/cli/dist/core/recipes/launch.js +51 -0
  106. package/cli/dist/core/validation/facts.js +1 -3
  107. package/cli/dist/deployer/brand.js +8 -5
  108. package/cli/dist/deployer/build/builder.js +10 -4
  109. package/cli/dist/deployer/build/client.js +44 -0
  110. package/cli/dist/deployer/build/routes.js +27 -6
  111. package/cli/dist/deployer/ctl/answers.js +6 -2
  112. package/cli/dist/deployer/ctl/ctl.js +66 -9
  113. package/cli/dist/deployer/deployer.js +113 -196
  114. package/cli/dist/deployer/forges/forge.js +0 -12
  115. package/cli/dist/deployer/forges/notify.js +3 -3
  116. package/cli/dist/deployer/http/http.js +0 -1
  117. package/cli/dist/deployer/http/page.js +4 -2
  118. package/cli/dist/deployer/http/webhook.js +0 -1
  119. package/cli/dist/deployer/runs/effects.js +70 -0
  120. package/cli/dist/deployer/runs/queue.js +5 -4
  121. package/cli/dist/deployer/runs/records.js +22 -3
  122. package/cli/dist/deployer/runs/restore.js +6 -0
  123. package/cli/dist/deployer/runs/run.js +51 -5
  124. package/cli/dist/deployer/runs/store.js +19 -3
  125. package/cli/dist/deployer/settings.js +69 -0
  126. package/cli/dist/lib/forge-repo.js +15 -0
  127. package/cli/dist/lib/names.js +13 -0
  128. package/cli/dist/main.js +46 -25
  129. package/compose/docker-compose.ci.yml +2 -0
  130. package/package.json +2 -2
  131. package/schema/app.json +5 -0
  132. package/schema/defaults.json +8 -0
  133. package/schema/vars-platform.json +8 -0
  134. package/scripts/local/verify.sh +9 -2
  135. package/terraform/modules/platform-dns/main.tf +66 -0
  136. package/terraform/modules/platform-dns/outputs.tf +9 -0
  137. package/terraform/modules/platform-dns/tests/fleet/.cache/apps/blog/site/app.yml +3 -0
  138. package/terraform/modules/platform-dns/tests/fleet/.cache/apps/shop/app.yml +6 -0
  139. package/terraform/modules/platform-dns/tests/fleet/servers/nested/server.yml +6 -0
  140. package/terraform/modules/platform-dns/tests/fleet/servers/shop/server.yml +7 -0
  141. package/terraform/modules/platform-dns/tests/fleet/servers/uncloned/server.yml +6 -0
  142. package/terraform/modules/platform-dns/tests/platform-dns.tftest.hcl +64 -0
  143. package/terraform/modules/platform-dns/variables.tf +25 -0
  144. package/cli/dist/browser/assets/index-C4HCL022.js +0 -7
  145. package/cli/dist/browser/assets/index-Ct0Eudk4.css +0 -1
  146. package/scripts/agent/guard.sh +0 -125
@@ -5,7 +5,6 @@ import { choice, integer, string } from "@optique/core/valueparser";
5
5
  import { appNameParser, domainParser, serverNameParser, subdomainParser } from "./values.js";
6
6
  import { operation } from "../../core/operations/catalog.js";
7
7
  /** A command's one line, as the catalog says it: the same words in every client. */
8
- // eslint-disable-next-line functional/prefer-immutable-types -- Optique's Message is readonly only at the top
9
8
  const summary = (name) => message `${text(operation(name).summary)}`;
10
9
  /** Command lines, each with what it is for, aligned. Plain text: Optique folds an indent that stands alone before a command line. */
11
10
  const examples = (indent, rows) => {
@@ -40,7 +39,7 @@ export const runOptions = (version) => Object.freeze(({
40
39
  // The option form's ARG cannot be hidden from the help page; completion scripts call the command.
41
40
  completion: { command: { group: "Help" } },
42
41
  brief: message `kayra ${text(version)}: a fleet's servers, from the machine to the apps on it.`,
43
- description: message `Run it anywhere inside a fleet (the directory holding servers/); app check also outside one. Server names are the fleet's and complete in the shell.`,
42
+ description: message `Run it anywhere inside a fleet (the directory holding servers/); app init and app check also outside one. Server names are the fleet's and complete in the shell.`,
44
43
  examples: examples("", [
45
44
  ["kayra status", "every server, and whether it answers"],
46
45
  ["kayra up shop-test", "a server from nothing"],
@@ -64,10 +63,10 @@ export const parser = (fleet) => {
64
63
  // Outside a fleet there is no name to offer; main refuses every server command there.
65
64
  // Help adds the fleet's servers to its description (showChoices): kept short so they fit beside it.
66
65
  const server = argument(first === undefined ? serverNameParser : choice([first, ...rest], { metavar: "SERVER", suggest: "nearest" }), { description: message `A server` });
66
+ const valuesDir = optional(option("--dir", string({ metavar: "DIR" }), { description: message `Local app directory; otherwise use the fleet cache.` }));
67
67
  const app = argument(appNameParser, { description: message `An app in the server's server.yml.` });
68
- // eslint-disable-next-line functional/prefer-immutable-types -- Optique's Message is readonly only at the top
69
68
  const onServer = (name, brief, more = {}) => command(name, object({ name: constant(name), server }), { brief, ...more });
70
- return Object.freeze(merge(group("Options", object({
69
+ return merge(group("Options", object({
71
70
  dryRun: option("--dry-run", { description: message `Print the plan instead of running it.` }),
72
71
  verbose: option("-v", "--verbose", {
73
72
  description: message `Ansible's own output (with -v) instead of kayra's summary.`,
@@ -99,13 +98,31 @@ export const parser = (fleet) => {
99
98
  }), onServer("adopt", summary("adopt")), command("backup", command("test", object({ name: constant("backup test"), server })), {
100
99
  brief: summary("backup.test"),
101
100
  footer: footer(["kayra backup test nas", "started on the server, followed over SSH"]),
102
- }))), group("Apps on a server", or(command("app", or(group("In an app's repository", command("check", object({
101
+ }))), group("Apps on a server", or(command("app", or(group("In an app's repository", or(command("init", object({
102
+ name: constant("app init"),
103
+ dir: optional(argument(string({ metavar: "DIR" }), { description: message `The project's repository; the current directory by default.` })),
104
+ appName: optional(option("--name", string({ metavar: "NAME" }), { description: message `The app's name; the directory's by default.` })),
105
+ }), {
106
+ brief: summary("app.init"),
107
+ footer: footer(["kayra app init", "in a project with a compose file or a Dockerfile, once"]),
108
+ }), command("check", object({
103
109
  name: constant("app check"),
104
110
  dir: optional(argument(string({ metavar: "DIR" }), { description: message `The app's repository; the current directory by default.` })),
105
111
  }), {
106
112
  brief: summary("app.check"),
107
113
  footer: footer(["kayra app check", "in the app's repository, before a push"]),
108
- })), group("On a server", or(command("purge", object({ name: constant("app purge"), server, app }), {
114
+ }))), group("On a server", or(command("hook", object({ name: constant("app hook"), server, app }), { brief: summary("app.hook") }), command("launch", object({
115
+ name: constant("app launch"), server, app, dir: valuesDir,
116
+ repo: optional(option("--repo", string({ metavar: "URL" }), { description: message `The app's repository, https://; needed until server.yml registers it.` })),
117
+ ref: optional(option("--ref", string({ metavar: "REF" }), { description: message `The branch that deploys; main by default.` })),
118
+ path: optional(option("--path", string({ metavar: "PATH" }), { description: message `The app's root inside the repository; . by default.` })),
119
+ }), { brief: summary("app.launch"), footer: footer(["kayra app launch shop-prod shop --repo https://github.com/OWNER/shop.git --dir .", "register, check values, apply, deploy; again after a stop"]) }), command("values", object({ name: constant("app values"), server, app, dir: valuesDir, json: option("--json") }), { brief: summary("app.values") }), command("config", command("set", object({
120
+ name: constant("app config set"), server, app, dir: valuesDir,
121
+ key: argument(string({ metavar: "KEY" })), value: argument(string({ metavar: "VALUE" })),
122
+ }), { brief: summary("app.config.set") })), command("secret", or(command("import", object({
123
+ name: constant("app secret import"), server, app, dir: valuesDir,
124
+ key: argument(string({ metavar: "KEY" })), file: argument(string({ metavar: "FILE" })),
125
+ }), { brief: summary("app.secret.import") }), command("generate", object({ name: constant("app secret generate"), server, app, dir: valuesDir, key: argument(string({ metavar: "KEY" })) }), { brief: summary("app.secret.generate") }))), command("purge", object({ name: constant("app purge"), server, app }), {
109
126
  brief: summary("app.purge"),
110
127
  }), command("runs", object({ name: constant("app runs"), server, app }), {
111
128
  brief: summary("app.runs"),
@@ -180,5 +197,5 @@ export const parser = (fleet) => {
180
197
  }), {
181
198
  brief: summary("certs"),
182
199
  footer: footer(["kayra certs shop.test www api", "into the fleet's .cache/certs"]),
183
- })))), (chosen) => ({ command: chosen }))));
200
+ })))), (chosen) => ({ command: chosen })));
184
201
  };
@@ -37,13 +37,13 @@ export const ago = (ms) => {
37
37
  const hours = Math.floor(minutes / 60);
38
38
  return hours < 48 ? `${String(hours)}h ago` : `${String(Math.floor(hours / 24))}d ago`;
39
39
  };
40
- /** Rows of cells in columns as wide as their widest cell, two spaces apart; nothing trails a row's last cell. */
41
40
  /** Each column as wide as its widest cell. */
42
41
  const columnWidths = (rows) => rows.reduce((most, row) => Object.freeze(Array.from({ length: Math.max(most.length, row.length) }, (_, at) => Math.max(most[at] ?? 0, width(row[at] ?? [])))), []);
42
+ /** Rows of cells in columns as wide as their widest cell, two spaces apart; nothing trails a row's last cell. */
43
43
  export const table = (rows) => {
44
44
  const filled = rows.map((row) => Object.freeze(row.slice(0, row.findLastIndex((cell) => width(cell) > 0) + 1)));
45
45
  const widths = columnWidths(filled);
46
- return Object.freeze(filled.map((row) => Object.freeze(row.flatMap((cell, at) => (at === row.length - 1 ? cell : typed([...cell, " ".repeat((widths[at] ?? 0) - width(cell) + 2)]))))));
46
+ return typed(filled.map((row) => Object.freeze(row.flatMap((cell, at) => (at === row.length - 1 ? cell : typed([...cell, " ".repeat((widths[at] ?? 0) - width(cell) + 2)]))))));
47
47
  };
48
48
  /**
49
49
  * Rows for table() that fit `room` columns: the cells of the columns in
@@ -58,7 +58,7 @@ export const fit = (rows, room, shrink) => {
58
58
  const less = Math.min(Math.max(0, so.over), Math.max(0, now - width(rows[0]?.[at] ?? [])));
59
59
  return { widths: Object.freeze(so.widths.with(at, now - less)), over: so.over - less };
60
60
  }, { widths, over }).widths;
61
- return Object.freeze(rows.map((row) => Object.freeze(row.map((cell, at) => truncate(cell, cut[at] ?? width(cell))))));
61
+ return typed(rows.map((row) => Object.freeze(row.map((cell, at) => truncate(cell, cut[at] ?? width(cell))))));
62
62
  };
63
63
  /** Paths by the root they are under, the longest first: the engine may live inside the fleet. */
64
64
  export const shortener = (roots) => (text) => roots.toSorted(([a], [b]) => b.length - a.length).reduce((short, [path, name]) => short.replaceAll(path, name), text);
@@ -6,7 +6,6 @@ const minting = (metavar, mint, placeholder) => typed({
6
6
  mode: "sync",
7
7
  metavar,
8
8
  placeholder,
9
- // eslint-disable-next-line functional/prefer-immutable-types -- Optique's Message: readonly by contract, but a type the rule cannot see into
10
9
  parse: (input) => {
11
10
  const minted = mint(input);
12
11
  return minted.ok ? { success: true, value: minted.value } : { success: false, error: [text(minted.error)] };
@@ -16,6 +16,13 @@ const states = {
16
16
  success: [ok("✓ success")],
17
17
  failure: [bad("✗ failure")],
18
18
  running: [active("◆ running")],
19
+ queued: [muted("… queued")],
20
+ superseded: [muted("↷ superseded")],
21
+ };
22
+ /** Why the newest run failed, under the table: the first thing to know after a failed deploy. */
23
+ const newestError = (answer) => {
24
+ const [newest] = answer.runs;
25
+ return typed(newest?.state === "failure" && newest.error !== undefined ? [[" ", bad(`✗ ${newest.error}`)], []] : []);
19
26
  };
20
27
  const took = (run, now) => typed(run.finished === undefined ? [active(`${duration(milliseconds(now - Date.parse(run.started)))}…`)] : [duration(milliseconds(Date.parse(run.finished) - Date.parse(run.started)))]);
21
28
  const commit = (run, release) => {
@@ -34,7 +41,7 @@ export const runsView = (view, answer, now) => {
34
41
  [],
35
42
  ...(answer.runs.length === 0
36
43
  ? [[" ", muted("no runs yet")]]
37
- : [...rows.map((row) => typed([" ", ...row])), [], hint(`kayra app logs ${view.server} ${view.app} [RUN]`, "shows a run's log, the newest by default")]),
44
+ : [...rows.map((row) => typed([" ", ...row])), [], ...newestError(answer), hint(`kayra app logs ${view.server} ${view.app} [RUN]`, "shows a run's log, the newest by default")]),
38
45
  ]);
39
46
  };
40
47
  /** `kayra app rollback` without a commit: every release, the live one marked, and how to go back to one. */
@@ -42,7 +49,7 @@ export const releasesView = (view, answer, now) => {
42
49
  const earlier = answer.releases.find((release) => !release.live);
43
50
  const rows = table([
44
51
  [[muted(" COMMIT")], [muted("DEPLOYED")]],
45
- ...answer.releases.map((release) => Object.freeze([
52
+ ...answer.releases.map((release) => typed([
46
53
  release.live ? [ok("●"), " ", accent(short(release.sha))] : [" ", short(release.sha)],
47
54
  [since(release.time, now)],
48
55
  release.live ? [ok("live")] : [],
@@ -21,7 +21,14 @@ export const reaches = {
21
21
  down: { tool: "down" },
22
22
  adopt: { tool: "adopt" },
23
23
  "backup.test": { tool: "backup_test" },
24
+ "app.init": { tool: "app_init" },
24
25
  "app.check": { tool: "app_check" },
26
+ "app.values": { tool: "app_values" },
27
+ "app.launch": { tool: "app_launch" },
28
+ "app.hook": { tool: "app_hook" },
29
+ "app.config.set": { tool: "app_config_set" },
30
+ "app.secret.import": { tool: "app_secret_import" },
31
+ "app.secret.generate": { tool: "app_secret_generate" },
25
32
  "app.purge": { tool: "app_purge" },
26
33
  "app.runs": { tool: "app_runs" },
27
34
  "app.log": { tool: "app_log" },
@@ -51,7 +58,7 @@ const effectSaid = (each) => {
51
58
  return "Changes nothing.";
52
59
  if (each.effect === "destroys")
53
60
  return "Irreversible: the operator approves every call, and types the server's name before it runs.";
54
- return each.scope === "fleet" || each.scope === "repo"
61
+ return each.local === true || each.scope === "fleet" || each.scope === "repo"
55
62
  ? "Changes files on this machine."
56
63
  : "Changes the server: on one that is not multipass, the operator approves it first.";
57
64
  };
@@ -8,6 +8,7 @@ const types = {
8
8
  ".png": "image/png",
9
9
  ".ico": "image/x-icon",
10
10
  ".woff2": "font/woff2",
11
+ ".woff": "font/woff",
11
12
  ".json": "application/json; charset=utf-8",
12
13
  };
13
14
  const unbuilt = `<!doctype html><meta charset="utf-8"><title>kayra</title>
@@ -1,10 +1,10 @@
1
1
  import { z } from "zod";
2
- import { operations, operationNames } from "../../core/operations/catalog.js";
2
+ import { operations, operationNames, operation } from "../../core/operations/catalog.js";
3
3
  import { options, schemas } from "./schemas.js";
4
4
  import { typed } from "../../lib/typed.js";
5
5
  export const catalog = () => Object.freeze(operationNames.map((name) => {
6
6
  const { summary, scope, effect, kind, input } = operations[name];
7
- return { name, summary, scope, effect, kind, input: z.toJSONSchema(input, { io: "input" }) };
7
+ return { name, summary, scope, effect, kind, local: operation(name).local === true, input: z.toJSONSchema(input, { io: "input" }) };
8
8
  }));
9
9
  const isObject = (value) => typeof value === "object" && value !== null;
10
10
  const object = (value) => isObject(value) ? value : typed({});
@@ -11,6 +11,7 @@ const data = (schema, text) => {
11
11
  return value === undefined ? err("the deployer returned an unreadable answer") : ok(value);
12
12
  };
13
13
  const queries = {
14
+ "app.values": (context, input) => query(context, "app.values", input),
14
15
  validate: async (context, input) => map(await query(context, "validate", input), validateJson),
15
16
  version: (context, input) => query(context, "version", input),
16
17
  "app.runs": async (context, input) => data(runsSchema, await query(context, "app.runs", input)),
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { valuesReportSchema } from "../../core/app-values/model.js";
2
3
  import { effects, kinds, operationNames, scopes } from "../../core/operations/catalog.js";
3
4
  import { serverKinds } from "../../core/fleet/settings.js";
4
5
  import { serverTargets } from "../../core/fleet/model.js";
@@ -60,9 +61,11 @@ export const schemas = {
60
61
  kayra: z.object({ pin: z.string(), state: z.enum(runningStates), version: z.string().nullable(), error: z.string().nullable() }),
61
62
  })) }),
62
63
  Validation: z.object({ result: verdict, servers: z.array(z.object({ name: z.string(), kind: z.string(), target: z.string(), result: verdict, findings: z.array(z.object({ result: verdict, text: z.string(), hint: z.string().nullable() })) })) }),
64
+ AppValues: valuesReportSchema,
63
65
  AppRuns: runsSchema, AppReleases: releasesSchema,
64
- OperationInfo: z.object({ name: z.enum(operationNames), summary: z.string(), scope: z.enum(scopes), effect: z.enum(effects), kind: z.enum(kinds), input: z.record(z.string(), z.unknown()) }),
66
+ OperationInfo: z.object({ name: z.enum(operationNames), summary: z.string(), scope: z.enum(scopes), effect: z.enum(effects), kind: z.enum(kinds), local: z.boolean(), input: z.record(z.string(), z.unknown()) }),
65
67
  };
66
68
  export const querySchemas = {
69
+ "app.values": schemas.AppValues,
67
70
  validate: schemas.Validation, version: z.string(), "app.runs": schemas.AppRuns, "app.releases": schemas.AppReleases, "app.log": z.string(),
68
71
  };
@@ -1,6 +1,18 @@
1
1
  /** What follows the server and the app on the command line, by operation. */
2
2
  const extra = (call) => {
3
3
  switch (call.name) {
4
+ case "app.config.set":
5
+ return [call.input.key, call.input.value, ...(call.input.dir === undefined ? [] : ["--dir", call.input.dir])];
6
+ case "app.secret.import":
7
+ return [call.input.key, call.input.file, ...(call.input.dir === undefined ? [] : ["--dir", call.input.dir])];
8
+ case "app.secret.generate":
9
+ return [call.input.key, ...(call.input.dir === undefined ? [] : ["--dir", call.input.dir])];
10
+ case "app.values":
11
+ return call.input.dir === undefined ? [] : ["--dir", call.input.dir];
12
+ case "app.hook":
13
+ return [];
14
+ case "app.launch":
15
+ return ["repo", "ref", "path", "dir"].flatMap((key) => (call.input[key] === undefined ? [] : [`--${key}`, call.input[key]]));
4
16
  case "ssh.exec":
5
17
  return ["--", ...call.input.command];
6
18
  case "job":
@@ -13,6 +25,8 @@ const extra = (call) => {
13
25
  return call.input.run === undefined ? [] : [call.input.run];
14
26
  case "app.check":
15
27
  return [call.input.dir];
28
+ case "app.init":
29
+ return [call.input.dir, ...(call.input.name === undefined ? [] : ["--name", call.input.name])];
16
30
  case "certs":
17
31
  return [call.input.domain, ...call.input.subdomains];
18
32
  case "up":
@@ -14,7 +14,7 @@ export const unreadable = (stderr) => {
14
14
  export const opentofu = {
15
15
  state: async (dir) => {
16
16
  const listed = await capture(["tofu", `-chdir=${dir}`, "state", "list", "-no-color"], "capture");
17
- return listed.code === 0 ? ok(listed.stdout.split("\n").filter((line) => line.trim() !== "")) : err(unreadable(listed.stderr));
17
+ return listed.code === 0 ? ok(Object.freeze(listed.stdout.split("\n").filter((line) => line.trim() !== ""))) : err(unreadable(listed.stderr));
18
18
  },
19
19
  output: async (dir, name) => {
20
20
  const value = await capture(["tofu", `-chdir=${dir}`, "output", "-raw", name], "capture");
@@ -0,0 +1,90 @@
1
+ import { err, ok } from "../../lib/result.js";
2
+ import { typed } from "../../lib/typed.js";
3
+ export const hookUrl = (domain, app) => `https://deploy.${domain}/hook/${app}`;
4
+ const field = (value, key) => typeof value === "object" && value !== null ? Object.entries(value).find(([name]) => name === key)?.[1] : undefined;
5
+ const hookOf = (url) => (value) => {
6
+ const id = field(value, "id");
7
+ const to = url(value);
8
+ return typeof id === "number" && typeof to === "string" ? typed({ id, url: to }) : undefined;
9
+ };
10
+ const listed = (answer, of) => Array.isArray(answer.json) ? Object.freeze(answer.json.flatMap((each) => { const hook = of(each); return hook === undefined ? Object.freeze([]) : Object.freeze([hook]); })) : typed([]);
11
+ const failed = (what, answer) => err(`${what}: HTTP ${String(answer.status)}${answer.status === 401 || answer.status === 403 || answer.status === 404 ? " (does the token have admin rights on the repository?)" : ""}`);
12
+ /**
13
+ * The three forges kayra knows, the same that the deployer verifies webhooks
14
+ * for: GitHub's X-Hub-Signature-256, Forgejo's (or Gitea's) signature, GitLab's
15
+ * secret token. Each hook is a JSON push hook to the deployer.
16
+ */
17
+ export const hookApi = (repo, http) => {
18
+ const json = { "Content-Type": "application/json" };
19
+ switch (repo.kind) {
20
+ case "github": {
21
+ const base = `https://api.github.com/repos/${repo.owner}/${repo.name}`;
22
+ const auth = (token) => typed({ Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json" });
23
+ const of = hookOf((value) => field(field(value, "config"), "url"));
24
+ return {
25
+ readable: async (token) => { const answer = await http(base, { method: "GET", headers: auth(token) }); return answer.status === 200 ? ok(true) : failed("the platform's git_token cannot read the repository", answer); },
26
+ hooks: async (token) => { const answer = await http(`${base}/hooks`, { method: "GET", headers: auth(token) }); return answer.status === 200 ? ok(listed(answer, of)) : failed("listing the hooks", answer); },
27
+ save: async (token, url, secret, id) => {
28
+ const body = JSON.stringify({ active: true, events: ["push"], config: { url, content_type: "json", secret, insecure_ssl: "0" } });
29
+ const answer = await http(id === undefined ? `${base}/hooks` : `${base}/hooks/${String(id)}`, { method: id === undefined ? "POST" : "PATCH", headers: { ...auth(token), ...json }, body });
30
+ const hook = of(answer.json);
31
+ return answer.status < 300 && hook !== undefined ? ok(hook) : failed("saving the hook", answer);
32
+ },
33
+ };
34
+ }
35
+ case "forgejo": {
36
+ const base = `${repo.origin}/api/v1/repos/${repo.owner}/${repo.name}`;
37
+ const auth = (token) => typed({ Authorization: `token ${token}` });
38
+ const of = hookOf((value) => field(field(value, "config"), "url"));
39
+ return {
40
+ readable: async (token) => { const answer = await http(base, { method: "GET", headers: auth(token) }); return answer.status === 200 ? ok(true) : failed("the platform's git_token cannot read the repository", answer); },
41
+ hooks: async (token) => { const answer = await http(`${base}/hooks`, { method: "GET", headers: auth(token) }); return answer.status === 200 ? ok(listed(answer, of)) : failed("listing the hooks", answer); },
42
+ save: async (token, url, secret, id) => {
43
+ const config = { url, content_type: "json", secret };
44
+ const body = JSON.stringify(id === undefined ? { type: "gitea", active: true, events: ["push"], config } : { active: true, events: ["push"], config });
45
+ const answer = await http(id === undefined ? `${base}/hooks` : `${base}/hooks/${String(id)}`, { method: id === undefined ? "POST" : "PATCH", headers: { ...auth(token), ...json }, body });
46
+ const hook = of(answer.json);
47
+ return answer.status < 300 && hook !== undefined ? ok(hook) : failed("saving the hook", answer);
48
+ },
49
+ };
50
+ }
51
+ case "gitlab": {
52
+ const base = `${repo.origin}/api/v4/projects/${encodeURIComponent(`${repo.owner}/${repo.name}`)}`;
53
+ const auth = (token) => typed({ Authorization: `Bearer ${token}` });
54
+ const of = hookOf((value) => field(value, "url"));
55
+ return {
56
+ readable: async (token) => { const answer = await http(base, { method: "GET", headers: auth(token) }); return answer.status === 200 ? ok(true) : failed("the platform's git_token cannot read the repository", answer); },
57
+ hooks: async (token) => { const answer = await http(`${base}/hooks`, { method: "GET", headers: auth(token) }); return answer.status === 200 ? ok(listed(answer, of)) : failed("listing the hooks", answer); },
58
+ save: async (token, url, secret, id) => {
59
+ const body = JSON.stringify({ url, token: secret, push_events: true, enable_ssl_verification: true });
60
+ const answer = await http(id === undefined ? `${base}/hooks` : `${base}/hooks/${String(id)}`, { method: id === undefined ? "POST" : "PUT", headers: { ...auth(token), ...json }, body });
61
+ const hook = of(answer.json);
62
+ return answer.status < 300 && hook !== undefined ? ok(hook) : failed("saving the hook", answer);
63
+ },
64
+ };
65
+ }
66
+ }
67
+ };
68
+ /**
69
+ * The repository readable by the platform's token, and exactly one push hook
70
+ * to its deployer: an existing one is updated, so its secret is the platform's
71
+ * now, never a second added.
72
+ */
73
+ export const ensureHook = async (api, url, tokens, secret) => {
74
+ const readable = await api.readable(tokens.platform);
75
+ if (!readable.ok)
76
+ return readable;
77
+ const existing = await api.hooks(tokens.operator);
78
+ if (!existing.ok)
79
+ return existing;
80
+ const same = existing.value.filter((hook) => hook.url === url);
81
+ if (same.length > 1)
82
+ return err(`there are ${String(same.length)} hooks to ${url}; delete all but one`);
83
+ const saved = await api.save(tokens.operator, url, secret, same[0]?.id);
84
+ if (!saved.ok)
85
+ return err(saved.error.replaceAll(secret, "…"));
86
+ return ok(typed([
87
+ "✓ the platform's token reads the repository",
88
+ `✓ push hook ${same[0] === undefined ? "created" : "updated"}: ${url} (id ${String(saved.value.id)})`,
89
+ ]));
90
+ };
@@ -0,0 +1,49 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { fields } from "../../lib/yaml.js";
6
+ /** KAYRA_FORGE_TOKEN_<HOST>: github.com → KAYRA_FORGE_TOKEN_GITHUB_COM. */
7
+ export const tokenVariable = (host) => `KAYRA_FORGE_TOKEN_${host.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`;
8
+ /** A CLI's answer, if that CLI is here at all: its absence is no error, only no answer. */
9
+ const asked = (program, args) => {
10
+ const result = spawnSync(program, args, { encoding: "utf8" });
11
+ const token = result.status === 0 ? result.stdout.trim() : "";
12
+ return token === "" ? undefined : token;
13
+ };
14
+ const field = (value, key) => typeof value === "object" && value !== null ? Object.entries(value).find(([name]) => name === key)?.[1] : undefined;
15
+ const teaToken = (host, home, env) => {
16
+ const files = [
17
+ join(env["XDG_CONFIG_HOME"] ?? join(home, ".config"), "tea", "config.yml"),
18
+ join(home, "Library", "Application Support", "tea", "config.yml"),
19
+ ];
20
+ const file = files.find((each) => existsSync(each));
21
+ if (file === undefined)
22
+ return undefined;
23
+ const parsed = fields(readFileSync(file, "utf8"));
24
+ const logins = parsed.ok ? parsed.value["logins"] : undefined;
25
+ const list = Array.isArray(logins) ? logins : [];
26
+ const login = list.find((each) => {
27
+ const url = field(each, "url");
28
+ return typeof url === "string" && URL.canParse(url) && new URL(url).host === host;
29
+ });
30
+ const token = field(login, "token");
31
+ return typeof token === "string" && token !== "" ? token : undefined;
32
+ };
33
+ /**
34
+ * The operator's token for a forge (hooks need a repository admin, which the
35
+ * platform's token is not): KAYRA_FORGE_TOKEN_<HOST> first; else, only if it
36
+ * happens to be here, the forge CLI's own login (gh, tea, glab). No CLI is
37
+ * ever required.
38
+ */
39
+ export const operatorToken = (repo, env = process.env, home = homedir()) => {
40
+ const host = new URL(repo.origin).host;
41
+ const fromEnv = env[tokenVariable(host)];
42
+ if (fromEnv !== undefined && fromEnv !== "")
43
+ return { token: fromEnv, from: tokenVariable(host) };
44
+ const fallback = repo.kind === "github" ? asked("gh", ["auth", "token", "--hostname", host])
45
+ : repo.kind === "gitlab" ? asked("glab", ["config", "get", "token", "--host", host])
46
+ : teaToken(host, home, env);
47
+ const cli = repo.kind === "github" ? "gh" : repo.kind === "gitlab" ? "glab" : "tea";
48
+ return fallback === undefined ? undefined : { token: fallback, from: `${cli}'s login` };
49
+ };
@@ -0,0 +1,208 @@
1
+ import { isAbsolute, relative } from "node:path";
2
+ import { Document } from "yaml";
3
+ import { names } from "../../lib/names.js";
4
+ import { typed } from "../../lib/typed.js";
5
+ export const overlayFile = "kayra/compose.yml";
6
+ const defaultMemory = "512m";
7
+ const defaultPort = 8080;
8
+ /** What compose-policy.sh allows on a service. */
9
+ const allowed = new Set(["image", "command", "entrypoint", "environment", "labels", "networks", "volumes", "tmpfs", "healthcheck",
10
+ "depends_on", "restart", "user", "working_dir", "init", "read_only", "expose", "stop_grace_period", "stop_signal", "mem_limit",
11
+ "mem_reservation", "cpus", "deploy"]);
12
+ /** Refused by the policy, and safe to drop: the platform builds, routes and names instead. */
13
+ const dropped = ["build", "ports", "env_file", "container_name", "pull_policy", "platform", "hostname"];
14
+ const droppedKeys = new Set(dropped);
15
+ const reserved = new Set(["deploy", "auth", "traefik"]);
16
+ const secretish = /PASSWORD|SECRET|TOKEN|KEY|PRIVATE|CREDENTIAL/i;
17
+ /** Variables a compose file needs and gives no default for: `${X}`, `${X:?…}`, `${X?…}`. */
18
+ const required = (text) => Object.freeze([...text.matchAll(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?\?[^}]*)?\}/g)].flatMap((match) => (match[1] === undefined ? Object.freeze([]) : Object.freeze([match[1]]))));
19
+ const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? Object.fromEntries(Object.entries(value)) : undefined;
20
+ const list = (value) => (Array.isArray(value) ? typed(value) : typed([]));
21
+ const text = (value) => (typeof value === "string" ? value : undefined);
22
+ const imageVariable = (service) => `${service.toUpperCase().replace(/-/g, "_")}_IMAGE`;
23
+ const inside = (root, path) => {
24
+ const rel = relative(root, path);
25
+ return rel === "" ? "." : rel.startsWith("..") || isAbsolute(rel) ? undefined : rel;
26
+ };
27
+ const artifact = (app, root, service, build) => {
28
+ const spec = record(build);
29
+ const context = text(spec?.["context"]) ?? ".";
30
+ const at = inside(root, isAbsolute(context) ? context : `${root}/${context}`);
31
+ if (at === undefined)
32
+ return { written: [], todo: [`service ${service}: its build context ${context} is outside the app; the build sees only the app's checkout`] };
33
+ const dockerfile = text(spec?.["dockerfile"]) ?? "Dockerfile";
34
+ const extra = ["args", "target", "secrets", "ssh", "additional_contexts"].filter((key) => spec?.[key] !== undefined);
35
+ const manifest = { image: `${app}/${service}`, dockerfile: at === "." ? dockerfile : `${at}/${dockerfile}`, context: at, inputs: [at] };
36
+ return {
37
+ written: [typed({ path: `kayra/${service}/docker/image.json`, content: `${JSON.stringify(manifest, null, 2)}\n` })],
38
+ todo: extra.map((key) => `service ${service}: build.${key} is not passed to the platform's build; bake it into the Dockerfile`),
39
+ };
40
+ };
41
+ const routeOf = (service, ports) => {
42
+ const tcp = ports.map(record).find((port) => port !== undefined && (text(port["protocol"]) ?? "tcp") === "tcp");
43
+ const target = typeof tcp?.["target"] === "number" ? tcp["target"] : undefined;
44
+ if (target === undefined)
45
+ return { route: undefined, todo: [] };
46
+ const host = service.toLowerCase();
47
+ return names.subdomain.pattern.test(host) && !reserved.has(host)
48
+ ? { route: { host, service, port: target }, todo: [] }
49
+ : { route: undefined, todo: [`service ${service} publishes ${String(target)}, but ${host} is no host it may have: add its route to app.yml by hand`] };
50
+ };
51
+ const volumesOf = (root, service, volumes, isFile) => {
52
+ const mounts = volumes.map(record).flatMap((volume) => (volume === undefined ? Object.freeze([]) : Object.freeze([volume])));
53
+ const binds = mounts.filter((volume) => volume["type"] === "bind");
54
+ if (binds.length === 0)
55
+ return { volumes: undefined, named: [], did: [], todo: [] };
56
+ const named = (volume) => `${service}-${(text(volume["source"]) ?? "data").split("/").filter((part) => part !== "").at(-1) ?? "data"}`.toLowerCase().replace(/[^a-z0-9_-]+/g, "-");
57
+ const fileBinds = binds.filter((volume) => isFile(text(volume["source"]) ?? ""));
58
+ const directoryBinds = binds.filter((volume) => !fileBinds.includes(volume));
59
+ const where = (volume) => `${relative(root, text(volume["source"]) ?? "")} → ${text(volume["target"]) ?? ""}`;
60
+ return {
61
+ volumes: mounts
62
+ .filter((volume) => !fileBinds.includes(volume))
63
+ .map((volume) => (volume["type"] === "bind"
64
+ ? { type: "volume", source: named(volume), target: volume["target"], ...(volume["read_only"] === true ? { read_only: true } : {}) }
65
+ : volume)),
66
+ named: directoryBinds.map(named),
67
+ did: directoryBinds.map((volume) => `service ${service}: bind mount ${where(volume)} as the named volume ${named(volume)}; its data starts empty on the server`),
68
+ todo: fileBinds.map((volume) => `service ${service}: bind mount of the file ${where(volume)}; COPY it into the image instead`),
69
+ };
70
+ };
71
+ const serviceOf = (app, root, name, value, envKeys, isFile) => {
72
+ const builds = value["build"] !== undefined;
73
+ const valid = /^[a-z0-9][a-z0-9-]*$/.test(name);
74
+ const built = builds && valid ? artifact(app, root, name, value["build"]) : { written: [], todo: builds ? [`service ${name}: an image name needs lowercase letters, digits and dashes; rename the service`] : [] };
75
+ const fromFiles = list(value["env_file"]).map((entry) => text(record(entry)?.["path"]) ?? text(entry) ?? "");
76
+ const keys = fromFiles.map((path) => ({ path, keys: envKeys(path) }));
77
+ const envTodo = keys.filter((each) => each.keys === undefined).map((each) => `service ${name}: env_file ${relative(root, each.path)} could not be read; declare its keys in app.yml`);
78
+ const envFromFiles = keys.flatMap((each) => each.keys ?? []);
79
+ const { route, todo: routeTodo } = routeOf(name, list(value["ports"]));
80
+ const deploy = record(value["deploy"]);
81
+ const limited = value["mem_limit"] !== undefined || record(record(deploy?.["resources"])?.["limits"])?.["memory"] !== undefined;
82
+ const mounts = volumesOf(root, name, list(value["volumes"]), isFile);
83
+ const refused = Object.keys(value).filter((key) => !allowed.has(key) && !droppedKeys.has(key));
84
+ const resets = dropped.filter((key) => value[key] !== undefined);
85
+ const builtImage = built.written.length > 0;
86
+ return typed({
87
+ overlay: {
88
+ ...(builtImage ? { image: `\${${imageVariable(name)}:?}` } : {}),
89
+ ...(envFromFiles.length === 0 ? {} : { environment: Object.fromEntries(envFromFiles.map((key) => [key, `\${${key}:?}`])) }),
90
+ ...(limited ? {} : { mem_limit: defaultMemory }),
91
+ },
92
+ volumes: mounts.volumes,
93
+ named: mounts.named,
94
+ resets,
95
+ artifacts: built.written,
96
+ route,
97
+ declared: envFromFiles,
98
+ did: [
99
+ ...(builtImage ? [`service ${name}: built by the platform from ${built.written[0]?.path ?? ""}, deployed as \${${imageVariable(name)}}`] : []),
100
+ ...(route === undefined ? [] : [`service ${name}: route ${route.host} → ${String(route.port)} instead of its published port`]),
101
+ ...(envFromFiles.length === 0 ? [] : [`service ${name}: ${String(envFromFiles.length)} key(s) from env_file declared in app.yml, its values never read`]),
102
+ ...(limited ? [] : [`service ${name}: mem_limit ${defaultMemory}, since it had none`]),
103
+ ...mounts.did,
104
+ ...resets.filter((key) => key !== "build" && key !== "ports" && key !== "env_file").map((key) => `service ${name}: ${key} dropped`),
105
+ ],
106
+ todo: [
107
+ ...built.todo,
108
+ ...envTodo,
109
+ ...routeTodo,
110
+ ...mounts.todo,
111
+ ...refused.map((key) => `service ${name}: ${key} is not allowed by the compose policy`),
112
+ ...(route !== undefined && value["healthcheck"] === undefined ? [`service ${name}: no healthcheck; a deploy then waits only for it to start`] : []),
113
+ ],
114
+ });
115
+ };
116
+ const overlay = (services) => {
117
+ const named = services.flatMap(([, service]) => service.named);
118
+ const document = new Document({
119
+ services: Object.fromEntries(services.map(([name, service]) => [name, service.overlay])),
120
+ ...(named.length === 0 ? {} : { volumes: Object.fromEntries(named.map((volume) => [volume, {}])) }),
121
+ });
122
+ services.forEach(([name, service]) => {
123
+ if (service.volumes !== undefined) {
124
+ const node = document.createNode(service.volumes);
125
+ // eslint-disable-next-line functional/immutable-data -- the yaml library tags a node by assignment
126
+ node.tag = "!override";
127
+ document.setIn(["services", name, "volumes"], node);
128
+ }
129
+ service.resets.forEach((key) => {
130
+ const node = document.createNode(key === "ports" || key === "env_file" ? [] : null);
131
+ // eslint-disable-next-line functional/immutable-data -- the yaml library tags a node by assignment
132
+ node.tag = "!reset";
133
+ document.setIn(["services", name, key], node);
134
+ });
135
+ });
136
+ return `# Written by kayra app init: what the platform deploys on top of the project's own compose file.\n${document.toString()}`;
137
+ };
138
+ const manifest = (app, compose, routes, keys) => {
139
+ const secrets = keys.filter((key) => secretish.test(key));
140
+ const config = keys.filter((key) => !secretish.test(key));
141
+ const document = new Document({
142
+ name: app,
143
+ compose,
144
+ ...(routes.length === 0 ? {} : { routes: routes.flatMap((route) => (route === undefined ? Object.freeze([]) : Object.freeze([route]))) }),
145
+ ...(secrets.length === 0 ? {} : { secrets }),
146
+ ...(config.length === 0 ? {} : { config }),
147
+ });
148
+ return `# Written by kayra app init. Review it, then: kayra app check\n${document.toString()}`;
149
+ };
150
+ /** What `app init` writes for a compose project; `root` is the app's root, absolute. */
151
+ const fromCompose = (app, root, file, config, envKeys, isFile) => {
152
+ const services = Object.entries(record(record(config)?.["services"]) ?? {}).flatMap(([name, value]) => {
153
+ const service = record(value);
154
+ return service === undefined ? Object.freeze([]) : Object.freeze([[name, serviceOf(app, root, name, service, envKeys, isFile)]]);
155
+ });
156
+ const variables = new Set(services.map(([name]) => imageVariable(name)));
157
+ const interpolated = required(JSON.stringify(config)).filter((key) => !variables.has(key) && key !== "DOMAIN");
158
+ const keys = [...new Set([...interpolated, ...services.flatMap(([, service]) => service.declared)])].toSorted();
159
+ const routes = services.map(([, service]) => service.route).filter((route) => route !== undefined);
160
+ return typed({
161
+ files: [
162
+ { path: "app.yml", content: manifest(app, [file, overlayFile], routes, keys) },
163
+ { path: overlayFile, content: overlay(services) },
164
+ ...services.flatMap(([, service]) => service.artifacts),
165
+ ],
166
+ did: [
167
+ ...services.flatMap(([, service]) => service.did),
168
+ ...(keys.length === 0 ? [] : [`declared ${keys.join(", ")}: set them with kayra app config set / app secret import|generate`]),
169
+ ],
170
+ todo: [
171
+ ...services.flatMap(([, service]) => service.todo),
172
+ ...(routes.length === 0 ? ["no service publishes a port: add a route to app.yml for the one people reach"] : []),
173
+ ],
174
+ });
175
+ };
176
+ /** What `app init` writes for a project with a Dockerfile and no compose file: one service, `web`. */
177
+ const fromDockerfile = (app, expose) => {
178
+ const port = expose ?? defaultPort;
179
+ const overlayText = new Document({ services: { web: { image: `\${${imageVariable("web")}:?}`, mem_limit: defaultMemory } } }).toString();
180
+ return typed({
181
+ files: [
182
+ { path: "app.yml", content: manifest(app, [overlayFile], [{ host: "www", service: "web", port }], []) },
183
+ { path: overlayFile, content: `# Written by kayra app init: the project's one service, built from its Dockerfile.\n${overlayText}` },
184
+ { path: "kayra/web/docker/image.json", content: `${JSON.stringify({ image: `${app}/web`, dockerfile: "Dockerfile", context: ".", inputs: ["."] }, null, 2)}\n` },
185
+ ],
186
+ did: [`service web: built from ./Dockerfile, route www → ${String(port)}, mem_limit ${defaultMemory}`],
187
+ todo: [
188
+ ...(expose === undefined ? [`the Dockerfile EXPOSEs no port; assumed ${String(defaultPort)}, correct the route in app.yml if it listens elsewhere`] : []),
189
+ "service web: no healthcheck; a deploy then waits only for it to start",
190
+ ],
191
+ });
192
+ };
193
+ export const planInit = (app, root, source) => source.kind === "compose" ? fromCompose(app, root, source.file, source.config, source.envKeys, source.isFile) : fromDockerfile(app, source.expose);
194
+ /** The first port a Dockerfile EXPOSEs. */
195
+ export const exposed = (dockerfile) => {
196
+ const match = /^\s*EXPOSE\s+(\d+)/im.exec(dockerfile);
197
+ return match?.[1] === undefined ? undefined : Number.parseInt(match[1], 10);
198
+ };
199
+ /** The keys of an env file, never its values. */
200
+ export const envFileKeys = (content) => Object.freeze(content.split(/\r?\n/).flatMap((line) => {
201
+ const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line);
202
+ return match?.[1] === undefined ? Object.freeze([]) : Object.freeze([match[1]]);
203
+ }));
204
+ /** An app name from a directory's: lowercase, dashes for anything else. */
205
+ export const nameFrom = (directory) => {
206
+ const name = directory.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^[^a-z]+/, "").replace(/-+$/, "");
207
+ return names.app.pattern.test(name) ? name : undefined;
208
+ };