@yunuseon/kayra 0.17.1 → 0.17.2

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 (77) hide show
  1. package/agent/skills/kayra-release/SKILL.md +6 -1
  2. package/ansible/roles/platform/tasks/main.yml +10 -2
  3. package/cli/dist/clients/api/auth.js +1 -1
  4. package/cli/dist/clients/api/commands.js +1 -1
  5. package/cli/dist/clients/api/contract.js +1 -1
  6. package/cli/dist/clients/api/directories.js +1 -1
  7. package/cli/dist/clients/api/discovery.js +1 -1
  8. package/cli/dist/clients/api/queries.js +1 -1
  9. package/cli/dist/clients/api/runs.js +1 -1
  10. package/cli/dist/clients/api/start.js +2 -2
  11. package/cli/dist/clients/cli/explain.js +1 -1
  12. package/cli/dist/clients/cli/framed.js +1 -1
  13. package/cli/dist/clients/cli/invocation.js +1 -1
  14. package/cli/dist/clients/cli/questions.js +1 -1
  15. package/cli/dist/clients/cli/status.js +1 -1
  16. package/cli/dist/clients/cli/terminal.js +1 -1
  17. package/cli/dist/clients/cli/text.js +1 -1
  18. package/cli/dist/clients/cli/validate.js +1 -1
  19. package/cli/dist/clients/cli/values.js +1 -1
  20. package/cli/dist/clients/cli/views.js +1 -1
  21. package/cli/dist/core/adapters/fs.js +1 -1
  22. package/cli/dist/core/adapters/network.js +1 -1
  23. package/cli/dist/core/adapters/opentofu.js +1 -1
  24. package/cli/dist/core/fleet/brand.js +23 -14
  25. package/cli/dist/core/fleet/docs.js +2 -2
  26. package/cli/dist/core/fleet/load.js +3 -2
  27. package/cli/dist/core/fleet/parse.js +59 -91
  28. package/cli/dist/core/fleet/settings.js +38 -13
  29. package/cli/dist/core/fleet/shape.js +5 -20
  30. package/cli/dist/core/interpreter/events.js +1 -1
  31. package/cli/dist/core/interpreter/loop.js +1 -1
  32. package/cli/dist/core/interpreter/needs.js +1 -1
  33. package/cli/dist/core/interpreter/process.js +2 -2
  34. package/cli/dist/core/interpreter/progress.js +1 -1
  35. package/cli/dist/core/interpreter/pty.js +1 -1
  36. package/cli/dist/core/operations/dispatch.js +2 -2
  37. package/cli/dist/core/plan/model.js +1 -1
  38. package/cli/dist/core/recipes/app-check.js +5 -8
  39. package/cli/dist/core/recipes/apps.js +2 -2
  40. package/cli/dist/core/recipes/backup.js +1 -1
  41. package/cli/dist/core/recipes/certs.js +1 -1
  42. package/cli/dist/core/recipes/doctor.js +1 -1
  43. package/cli/dist/core/recipes/host.js +2 -2
  44. package/cli/dist/core/recipes/ssh.js +2 -2
  45. package/cli/dist/core/recipes/steps.js +2 -2
  46. package/cli/dist/core/status/look.js +1 -1
  47. package/cli/dist/core/text/spans.js +1 -1
  48. package/cli/dist/core/validation/facts.js +3 -2
  49. package/cli/dist/core/validation/findings.js +3 -3
  50. package/cli/dist/deployer/app.js +2 -2
  51. package/cli/dist/deployer/brand.js +1 -1
  52. package/cli/dist/deployer/build/builder.js +2 -2
  53. package/cli/dist/deployer/build/bundle.js +2 -2
  54. package/cli/dist/deployer/build/compose.js +1 -1
  55. package/cli/dist/deployer/cron.js +1 -1
  56. package/cli/dist/deployer/ctl/answers.js +1 -1
  57. package/cli/dist/deployer/deployer.js +2 -2
  58. package/cli/dist/deployer/forges/forge.js +1 -1
  59. package/cli/dist/deployer/forges/forgejo.js +1 -1
  60. package/cli/dist/deployer/forges/github.js +1 -1
  61. package/cli/dist/deployer/forges/gitlab.js +1 -1
  62. package/cli/dist/deployer/forges/issues.js +2 -2
  63. package/cli/dist/deployer/forges/notify.js +2 -2
  64. package/cli/dist/deployer/runs/queue.js +1 -1
  65. package/cli/dist/deployer/runs/records.js +1 -1
  66. package/cli/dist/deployer/runs/run.js +2 -2
  67. package/cli/dist/deployer/runs/store.js +1 -1
  68. package/cli/dist/lib/brand.js +2 -0
  69. package/cli/dist/lib/closest.js +17 -0
  70. package/cli/dist/lib/schema.js +7 -0
  71. package/cli/dist/lib/yaml.js +21 -0
  72. package/cli/dist/main.js +1 -1
  73. package/package.json +1 -1
  74. package/schema/app.json +4 -2
  75. package/schema/server.json +10 -5
  76. /package/cli/dist/{result.js → lib/result.js} +0 -0
  77. /package/cli/dist/{typed.js → lib/typed.js} +0 -0
@@ -47,13 +47,18 @@ In the worktree:
47
47
  ```bash
48
48
  git -C "$W" switch -c release-<version>
49
49
  npm --prefix "$W" version <version> --no-git-tag-version # package.json + package-lock.json only
50
- git -C "$W" add package.json package-lock.json
50
+ npm --prefix "$W" run contract # openapi.json carries the version
51
+ git -C "$W" add package.json package-lock.json cli/src/clients/api/openapi.json
51
52
  git -C "$W" commit -s -F <message file> # DCO sign-off; the message summarises the PRs
52
53
  git -C "$W" push -u origin release-<version>
53
54
  gh pr create --repo yunuseon/kayra --base main --head release-<version> --title "<version>" --body-file <file>
54
55
  gh pr checks release-<version> --repo yunuseon/kayra --watch --interval 20
55
56
  ```
56
57
 
58
+ The generated API contract names the version: a bump without `npm run
59
+ contract` fails the checks (0.17.2's first push did, and 0.17.1 needed a
60
+ follow-up commit).
61
+
57
62
  Write commit messages and PR bodies to a file first (quoted heredoc):
58
63
  backticks inside `-m "…"` or a double-quoted `--body` are executed by the
59
64
  shell.
@@ -123,12 +123,20 @@
123
123
  mode: "0644"
124
124
  loop:
125
125
  - deployer/
126
- - "result.{{ 'ts' if deployer_source.stat.exists else 'js' }}"
127
- - "typed.{{ 'ts' if deployer_source.stat.exists else 'js' }}"
126
+ - lib/
128
127
  vars:
129
128
  code: "{{ 'src' if deployer_source.stat.exists else 'dist' }}"
130
129
  become: true
131
130
 
131
+ # result and typed used to sit next to deployer/, before lib/. Drop this
132
+ # once every fleet's servers have deployed lib/.
133
+ - name: Remove the deployer's shared files of earlier versions
134
+ ansible.builtin.file:
135
+ path: "{{ platform_dir }}/deployer/app/{{ item.0 }}.{{ item.1 }}"
136
+ state: absent
137
+ loop: "{{ ['result', 'typed'] | product(['ts', 'js']) | list }}"
138
+ become: true
139
+
132
140
  # The deployer's files used to sit flat in deployer/; those now in folders
133
141
  # are removed here, since a copy adds and never removes. Idempotent; drop it
134
142
  # once every fleet's servers have deployed the folders.
@@ -1,5 +1,5 @@
1
1
  import { timingSafeEqual } from "node:crypto";
2
- import { typed } from "../../typed.js";
2
+ import { typed } from "../../lib/typed.js";
3
3
  /** Cookies are shared by every port of a host: the name carries the port, so another local server's cookie is not ours. */
4
4
  export const cookieName = (port) => `kayra_ui_${String(port)}`;
5
5
  const origins = (port) => typed([`127.0.0.1:${String(port)}`, `localhost:${String(port)}`]);
@@ -1,4 +1,4 @@
1
- import { typed } from "../../typed.js";
1
+ import { typed } from "../../lib/typed.js";
2
2
  export const offered = (server) => typed([
3
3
  ...(server.kind === "platform" ? ["deploy", "apps", "verify"] : []),
4
4
  "setup", "plan",
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { operations, operationNames } from "../../core/operations/catalog.js";
3
3
  import { options, schemas, querySchemas } from "./protocol.js";
4
- import { typed } from "../../typed.js";
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
7
  return { name, summary, scope, effect, kind, input: z.toJSONSchema(input, { io: "input" }) };
@@ -1,6 +1,6 @@
1
1
  import { readdir, realpath, stat } from "node:fs/promises";
2
2
  import { dirname, resolve } from "node:path";
3
- import { err, ok } from "../../result.js";
3
+ import { err, ok } from "../../lib/result.js";
4
4
  export const directories = async (path, root) => {
5
5
  try {
6
6
  const absolute = await realpath(resolve(root, path));
@@ -1,7 +1,7 @@
1
1
  import { existsSync, lstatSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { dirname } from "node:path";
3
3
  import { z } from "zod";
4
- import { err, ok } from "../../result.js";
4
+ import { err, ok } from "../../lib/result.js";
5
5
  const entry = z.object({ url: z.string(), token: z.string(), pid: z.number().int().positive() });
6
6
  const alive = (pid) => {
7
7
  try {
@@ -2,7 +2,7 @@ import { z } from "zod";
2
2
  import { query } from "../../core/operations/dispatch.js";
3
3
  import { validateJson } from "./validate.js";
4
4
  import { parsed, releasesSchema, runsSchema } from "../../core/ctl/answers.js";
5
- import { err, map, ok } from "../../result.js";
5
+ import { err, map, ok } from "../../lib/result.js";
6
6
  // eslint-disable-next-line functional/prefer-immutable-types -- Zod schemas are immutable; each method returns a new schema
7
7
  const data = (schema, text) => {
8
8
  if (!text.ok)
@@ -1,4 +1,4 @@
1
- import { typed } from "../../typed.js";
1
+ import { typed } from "../../lib/typed.js";
2
2
  /** Sortable by time (an ISO 8601 instant), unique by its tail. */
3
3
  export const runId = (iso, random) => `${iso.replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z")}-${random}`;
4
4
  export const stateOf = (events) => {
@@ -8,8 +8,8 @@ import { interpret } from "../../core/interpreter/loop.js";
8
8
  import { operation } from "../../core/operations/catalog.js";
9
9
  import { hasPlan, planOf, serverOf } from "../../core/operations/dispatch.js";
10
10
  import { verbose } from "../../core/recipes/steps.js";
11
- import { err, ok } from "../../result.js";
12
- import { typed } from "../../typed.js";
11
+ import { err, ok } from "../../lib/result.js";
12
+ import { typed } from "../../lib/typed.js";
13
13
  import { words } from "./commands.js";
14
14
  import { busy, readRecord, recordLine, runId } from "./runs.js";
15
15
  /** Every run there is: the live ones, then those recorded, newest first. */
@@ -4,7 +4,7 @@ import { position } from "../../core/interpreter/progress.js";
4
4
  import { steps as count } from "../../core/interpreter/events.js";
5
5
  import { wrap } from "./text.js";
6
6
  import { drawnAs } from "./views.js";
7
- import { typed } from "../../typed.js";
7
+ import { typed } from "../../lib/typed.js";
8
8
  const kinds = { guard: warn, check: active, run: active, confirm: bad, note: muted };
9
9
  const tag = (step) => {
10
10
  const kind = kindOf(step);
@@ -6,7 +6,7 @@ import { spread, truncate } from "./text.js";
6
6
  import { paint } from "./paint.js";
7
7
  import { escapes, spinner } from "./terminal.js";
8
8
  import { milliseconds } from "../../core/fleet/brand.js";
9
- import { typed } from "../../typed.js";
9
+ import { typed } from "../../lib/typed.js";
10
10
  /** A run of this long earns a notification when it ends: the operator has looked away. */
11
11
  const worthNotifying = 30_000;
12
12
  /** Frames on stderr: a heading, each step as it runs and how it went, a footer; on a terminal also spinners, the window title, a notification. */
@@ -1,4 +1,4 @@
1
- import { typed } from "../../typed.js";
1
+ import { typed } from "../../lib/typed.js";
2
2
  /**
3
3
  * The parsed command line as the operation it names. `app rollback` without a
4
4
  * commit lists the releases (`app.releases`), with one it rolls back.
@@ -1,5 +1,5 @@
1
1
  import { createInterface } from "node:readline/promises";
2
- import { typed } from "../../typed.js";
2
+ import { typed } from "../../lib/typed.js";
3
3
  /** The command line's questions: secret typing stays unseen, piped answers keep their order. */
4
4
  export const questions = (render) => {
5
5
  // eslint-disable-next-line functional/prefer-immutable-types -- resources belong to this reader and close with the plan
@@ -1,7 +1,7 @@
1
1
  import { active, bad, ok as fine, link, muted, pointing, strong, warn } from "../../core/text/spans.js";
2
2
  import { fit, table } from "./text.js";
3
3
  import { authUrl } from "../../core/status/look.js";
4
- import { typed } from "../../typed.js";
4
+ import { typed } from "../../lib/typed.js";
5
5
  /** A spinner as wide as most answers, so the columns hardly move when they come. */
6
6
  const waiting = (frame, width) => typed([active(frame), " ".repeat(width - 1)]);
7
7
  const machineCell = (machine, frame) => {
@@ -43,7 +43,7 @@ export const escapes = {
43
43
  up: (count) => (count > 0 ? `\u001b[${String(count)}F` : ""),
44
44
  clearDown: "\u001b[J",
45
45
  };
46
- import { typed } from "../../typed.js";
46
+ import { typed } from "../../lib/typed.js";
47
47
  const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
48
48
  const frameOf = (ms) => frames[Math.floor(ms / 80) % frames.length] ?? "";
49
49
  /** Draws a line in place, again every frame, until stopped; stopping clears it. */
@@ -1,5 +1,5 @@
1
1
  import { characters, width } from "../../core/text/spans.js";
2
- import { typed } from "../../typed.js";
2
+ import { typed } from "../../lib/typed.js";
3
3
  /** `left`, then `right` flush with the last column, at least two spaces apart. */
4
4
  export const spread = (left, right, columns) => typed([
5
5
  ...left,
@@ -1,7 +1,7 @@
1
1
  import { bad, muted, ok, pointing, strong } from "../../core/text/spans.js";
2
2
  import { count } from "../../core/text/plural.js";
3
3
  import { overall, tally } from "../../core/validation/findings.js";
4
- import { typed } from "../../typed.js";
4
+ import { typed } from "../../lib/typed.js";
5
5
  const marks = { problem: bad("✗"), unchecked: muted("·"), passed: ok("✓") };
6
6
  /** "✗ 3 servers · 1 problem · 2 not checked" */
7
7
  export const summary = (reports) => {
@@ -1,6 +1,6 @@
1
1
  import { text } from "@optique/core/message";
2
2
  import { appName, domain, examples, serverName, subdomain } from "../../core/fleet/brand.js";
3
- import { typed } from "../../typed.js";
3
+ import { typed } from "../../lib/typed.js";
4
4
  /** An Optique value parser that mints a brand: arguments arrive already validated. */
5
5
  const minting = (metavar, mint, placeholder) => typed({
6
6
  mode: "sync",
@@ -4,7 +4,7 @@ import { duration } from "../../core/text/time.js";
4
4
  import { parsed, releasesSchema, runsSchema } from "../../core/ctl/answers.js";
5
5
  import { count } from "../../core/text/plural.js";
6
6
  import { milliseconds } from "../../core/fleet/brand.js";
7
- import { typed } from "../../typed.js";
7
+ import { typed } from "../../lib/typed.js";
8
8
  /** Lines as printing them one by one gives the text back: newline-ended, as a ctl writes. */
9
9
  const linesOf = (text) => (text === "" ? typed([]) : text.replace(/\n$/, "").split("\n"));
10
10
  const short = (sha) => sha.slice(0, 7);
@@ -1,5 +1,5 @@
1
1
  import { existsSync, readdirSync, readFileSync } from "node:fs";
2
- import { typed } from "../../typed.js";
2
+ import { typed } from "../../lib/typed.js";
3
3
  /** A file's text; undefined where there is none. */
4
4
  export const textAt = (path) => (existsSync(path) ? readFileSync(path, "utf8") : undefined);
5
5
  /** The folders in a directory, by name; none where it is missing. */
@@ -2,7 +2,7 @@ import { Agent, request } from "node:https";
2
2
  import { connect } from "node:net";
3
3
  import { getCACertificates } from "node:tls";
4
4
  import { milliseconds } from "../fleet/brand.js";
5
- import { typed } from "../../typed.js";
5
+ import { typed } from "../../lib/typed.js";
6
6
  /** Why a connection failed, by Node's error code. */
7
7
  export const failure = (code) => {
8
8
  if (code === "ECONNREFUSED")
@@ -1,5 +1,5 @@
1
1
  import { capture } from "../interpreter/process.js";
2
- import { err, ok } from "../../result.js";
2
+ import { err, ok } from "../../lib/result.js";
3
3
  /** Why tofu could not read the state, in a few words: the first line of its error. */
4
4
  export const unreadable = (stderr) => {
5
5
  if (stderr.includes("tofu init"))
@@ -1,16 +1,28 @@
1
1
  import { homedir } from "node:os";
2
2
  import { isAbsolute, join, normalize } from "node:path";
3
- import { err, ok } from "../../result.js";
4
- export const serverName = (value) => /^[a-z0-9][a-z0-9-]*$/.test(value)
5
- ? ok(value)
6
- : err(`'${value}' is not a server name (lowercase letters, digits, dashes)`);
7
- export const appName = (value) => /^[a-z][a-z0-9-]*$/.test(value)
8
- ? ok(value)
9
- : err(`'${value}' is not an app name (lowercase letters, digits, dashes)`);
10
- export const subdomain = (value) => /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(value) ? ok(value) : err(`'${value}' is not a subdomain`);
11
- export const domain = (value) => /^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z][a-z0-9-]*$/.test(value)
12
- ? ok(value)
13
- : err(`'${value}' is not a domain`);
3
+ import { z } from "zod";
4
+ import { branded } from "../../lib/brand.js";
5
+ import { err, ok } from "../../lib/result.js";
6
+ import { minting } from "../../lib/schema.js";
7
+ /** A string matching `regex`: brand it, and it is the schema the fleet's files are parsed with and the constructor everything else mints with. */
8
+ // eslint-disable-next-line functional/prefer-immutable-types -- a RegExp, and a Zod schema: immutable once built, but classes the rule cannot see into
9
+ const pattern = (regex, what) => z.string().regex(regex, { error: (issue) => `'${String(issue.input)}' is not ${what}` });
10
+ export const serverNameSchema = pattern(/^[a-z0-9][a-z0-9-]*$/, "a server name (lowercase letters, digits, dashes)").transform(branded());
11
+ export const appNameSchema = pattern(/^[a-z][a-z0-9-]*$/, "an app name (lowercase letters, digits, dashes)").transform(branded());
12
+ export const subdomainSchema = pattern(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/, "a subdomain").transform(branded());
13
+ export const domainSchema = pattern(/^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z][a-z0-9-]*$/, "a domain").transform(branded());
14
+ /** A path inside a repository, never above it. */
15
+ export const repoPathSchema = z
16
+ .string()
17
+ .refine((value) => !`/${value}/`.includes("/../"), { error: "path must stay inside its repo" })
18
+ .transform(branded());
19
+ /** Where an app's repository is cloned from: which schemes, the server's target says. */
20
+ export const repoUrlSchema = z.string().transform(branded());
21
+ export const serverName = minting(serverNameSchema);
22
+ export const appName = minting(appNameSchema);
23
+ export const subdomain = minting(subdomainSchema);
24
+ export const domain = minting(domainSchema);
25
+ export const repoPath = minting(repoPathSchema);
14
26
  /** `~/…` is the operator's home, as Ansible reads it in vault_password_file. */
15
27
  export const absolutePath = (value) => {
16
28
  const expanded = value === "~" || value.startsWith("~/") ? join(homedir(), value.slice(1)) : value;
@@ -36,9 +48,6 @@ export const keyFile = word("a key file", (value) => value);
36
48
  /** Where ssh listens unless the inventory says otherwise. */
37
49
  export const sshDefaultPort = "22";
38
50
  export const port = (value) => /^\d+$/.test(value) && Number(value) >= 1 && Number(value) <= 65535 ? ok(value) : err(`'${value}' is not a port`);
39
- /** HTTPS, or also plain HTTP where `schemes` allow it (a multipass server, a test machine by definition). */
40
- export const repoUrl = (value, schemes) => schemes.some((scheme) => value.startsWith(scheme)) ? ok(value) : err(`'${value}' is not a ${schemes.join(" or ")} URL`);
41
- export const repoPath = (value) => `/${value}/`.includes("/../") ? err(`'${value}' leaves its repository`) : ok(value);
42
51
  export const remotePath = (value) => value.startsWith("/") ? ok(value) : err(`'${value}' is not an absolute path`);
43
52
  export const milliseconds = (value) => Math.max(0, value);
44
53
  export const exitCode = (value) => value;
@@ -1,9 +1,9 @@
1
1
  import { z } from "zod";
2
2
  import { appManifestSchema, appValuesSchema, defaultsSchema, serverKinds, serverSchema, settings, varsSchema, } from "./settings.js";
3
- import { typed } from "../../typed.js";
3
+ import { typed } from "../../lib/typed.js";
4
4
  const version = "https://json-schema.org/draft/2020-12/schema";
5
5
  const jsonSchema = (title, schema) => typed({
6
- ...z.toJSONSchema(schema, { target: "draft-2020-12", unrepresentable: "any" }),
6
+ ...z.toJSONSchema(schema, { target: "draft-2020-12", unrepresentable: "any", io: "input" }),
7
7
  $schema: version,
8
8
  title,
9
9
  });
@@ -2,8 +2,9 @@ import { existsSync } from "node:fs";
2
2
  import { join, sep } from "node:path";
3
3
  import { filesIn, foldersIn, textAt } from "../adapters/fs.js";
4
4
  import { fleetRoot, serverDir, serverName, within } from "./brand.js";
5
- import { fields, parseServer } from "./parse.js";
6
- import { all, attempt, err, flatMap, map, ok } from "../../result.js";
5
+ import { parseServer } from "./parse.js";
6
+ import { fields } from "../../lib/yaml.js";
7
+ import { all, attempt, err, flatMap, map, ok } from "../../lib/result.js";
7
8
  import { defaultsSchema } from "./settings.js";
8
9
  import { checkSettings, knownSettings } from "./shape.js";
9
10
  /** The fleet is the nearest directory, from `from` upwards, with a servers/defaults.yml. */
@@ -1,66 +1,49 @@
1
- import { parseDocument } from "yaml";
2
- import { absolutePath, appName, domain, host, sshDefaultPort, keyFile, port, remotePath, repoPath, repoUrl, sshUser, vaultPasswordFile } from "./brand.js";
3
- import { all, err, map, ok } from "../../result.js";
4
- import { serverKinds, serverSchema, varsSchema } from "./settings.js";
5
- import { checkSettings, checkShape, knownSettings } from "./shape.js";
6
- import { serverTargets } from "./model.js";
7
- import { typed } from "../../typed.js";
8
- export const mapping = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? typed(Object.fromEntries(Object.entries(value))) : undefined;
9
- /** YAML text as a value; a syntax error is a value too, not an exception. */
10
- export const yamlOf = (text) => {
11
- const document = parseDocument(text);
12
- const problem = document.errors.at(0);
13
- return problem === undefined ? ok(document.toJS()) : err(`is not valid YAML: ${problem.message.split("\n")[0] ?? ""}`);
14
- };
15
- /** YAML text as a mapping; empty for an empty file. */
16
- export const fields = (text) => {
17
- const parsed = yamlOf(text);
18
- if (!parsed.ok)
19
- return parsed;
20
- const value = parsed.value;
21
- if (value === null || value === undefined)
22
- return ok({});
23
- const result = mapping(value);
24
- return result === undefined ? err("is not a YAML mapping") : ok(result);
25
- };
1
+ import { absolutePath, host, sshDefaultPort, keyFile, port, remotePath, sshUser, vaultPasswordFile } from "./brand.js";
2
+ import { err, map, ok } from "../../lib/result.js";
3
+ import { serverSchema, varsSchema } from "./settings.js";
4
+ import { checkSettings, knownSettings } from "./shape.js";
5
+ import { typed } from "../../lib/typed.js";
6
+ import { fields, mapping } from "../../lib/yaml.js";
26
7
  export const isVaulted = (text) => text.startsWith("$ANSIBLE_VAULT");
27
- const oneOf = (allowed, value, field) => {
28
- const match = allowed.find((candidate) => candidate === value);
29
- return match === undefined
30
- ? err(`${field} must be ${allowed.join(", ")}, not '${String(value)}'`)
31
- : ok(match);
32
- };
33
8
  const vault = (descriptor) => {
34
- const file = descriptor["vault_password_file"];
35
- if (descriptor["vault"] !== true)
9
+ const file = descriptor.vault_password_file;
10
+ if (!descriptor.vault)
36
11
  return ok({ kind: "none" });
37
12
  if (file === undefined)
38
13
  return ok({ kind: "ask" });
39
- return typeof file === "string"
40
- ? map(absolutePath(file), (path) => typed({ kind: "file", file: vaultPasswordFile(path) }))
41
- : err("vault_password_file must be a path");
14
+ return map(absolutePath(file), (path) => typed({ kind: "file", file: vaultPasswordFile(path) }));
15
+ };
16
+ /** What Zod's expected types are called in a fleet's YAML. */
17
+ const expected = { string: "a string", boolean: "true or false", array: "a list", object: "a mapping" };
18
+ /** What the file says at a path Zod reports: Zod's issues leave the input out. */
19
+ const written = (value, path) => {
20
+ // Recursive: a path one key at a time.
21
+ const [key, ...rest] = path;
22
+ if (key === undefined)
23
+ return value;
24
+ const next = Array.isArray(value) && typeof key === "number" ? value[key] : mapping(value)?.[String(key)];
25
+ return written(next, rest);
42
26
  };
43
27
  /**
44
- * Apps live in their own repo: the builder clones it over HTTPS, and the app
45
- * root stays inside it. A multipass server, a test machine by definition, may
46
- * clone over plain HTTP too: the upgrade lab serves its fixture app that way.
28
+ * The first thing wrong with server.yml, said as the operator wrote it: an
29
+ * app by its name, a missing key as required. The schema's own messages are
30
+ * whole sentences already.
47
31
  */
48
- const app = (target) => (value) => {
49
- const entry = mapping(value);
50
- if (entry === undefined)
51
- return err("an app must be a mapping");
52
- const name = typeof entry["name"] === "string" ? appName(entry["name"]) : err("an app needs a name");
53
- if (!name.ok)
54
- return name;
55
- const declared = entry["repo"];
56
- const repo = typeof declared === "string" ? repoUrl(declared, target === "multipass" ? ["https://", "http://"] : ["https://"]) : undefined;
57
- if (repo?.ok !== true)
58
- return err(`app ${name.value}: repo must be an https:// URL${target === "multipass" ? " (or http:// on multipass)" : ""}`);
59
- const within = entry["path"] ?? ".";
60
- const path = typeof within === "string" ? repoPath(within) : undefined;
61
- if (path?.ok !== true)
62
- return err(`app ${name.value}: path must stay inside its repo`);
63
- return ok({ name: name.value, repo: repo.value, path: path.value, entry });
32
+ const serverProblem = (error, descriptor) => {
33
+ const issue = error.issues.at(0);
34
+ if (issue === undefined)
35
+ return "server.yml is invalid";
36
+ const [first, index] = issue.path;
37
+ const name = index === undefined ? undefined : written(descriptor, ["apps", index, "name"]);
38
+ const app = first === "apps" && typeof index === "number" ? `app ${typeof name === "string" ? name : `#${String(index + 1)}`}: ` : "";
39
+ const key = String(issue.path.at(-1) ?? "");
40
+ if (issue.code === "unrecognized_keys") {
41
+ const where = issue.path.length === 0 ? "" : ` (in ${issue.path.join(".")})`;
42
+ return `server.yml: '${issue.keys.at(0) ?? ""}' is not a key it knows${where}`;
43
+ }
44
+ if (issue.code === "invalid_type")
45
+ return `${app}${key} ${written(descriptor, issue.path) === undefined ? "is required" : `must be ${expected[issue.expected] ?? issue.expected}`}`;
46
+ return `${app}${issue.message}`;
64
47
  };
65
48
  const inventoryField = (inventory, key) => new RegExp(`${key}=([^ \\n]*)`).exec(inventory)?.[1] ?? "";
66
49
  /** A field the inventory may leave out: undefined where it does. */
@@ -101,33 +84,16 @@ export const parseServer = (files) => {
101
84
  const descriptor = fields(files.descriptor);
102
85
  if (!descriptor.ok)
103
86
  return descriptor;
104
- const kind = oneOf(serverKinds, descriptor.value["kind"] ?? "platform", "kind");
105
- if (!kind.ok)
106
- return kind;
107
- const target = oneOf(serverTargets, descriptor.value["target"], "target");
108
- if (!target.ok)
109
- return target;
110
- const declared = descriptor.value["domain"];
111
- const serverDomain = typeof declared === "string" ? domain(declared) : err("domain is required");
112
- if (!serverDomain.ok)
113
- return serverDomain;
114
- const serverVault = vault(descriptor.value);
87
+ const parsed = serverSchema.safeParse(descriptor.value);
88
+ if (!parsed.success)
89
+ return err(serverProblem(parsed.error, descriptor.value));
90
+ const { kind, target, domain, apps } = parsed.data;
91
+ const serverVault = vault(parsed.data);
115
92
  if (!serverVault.ok)
116
93
  return serverVault;
117
- const declaredApps = descriptor.value["apps"] ?? [];
118
- if (!Array.isArray(declaredApps))
119
- return err("apps must be a list");
120
- if (kind.value !== "platform" && declaredApps.length > 0)
121
- return err("apps run on platform servers only");
122
- const apps = all(declaredApps.map(app(target.value)));
123
- if (!apps.ok)
124
- return apps;
125
- const shape = checkShape("server.yml", descriptor.value, serverSchema);
126
- if (!shape.ok)
127
- return shape;
128
- if (target.value === "home" && files.inventory === undefined)
94
+ if (target === "home" && files.inventory === undefined)
129
95
  return err("target home needs a hand-written inventory.ini next to it");
130
- if (target.value !== "home" && !files.hasTerraform)
96
+ if (target !== "home" && !files.hasTerraform)
131
97
  return err("no terraform/ next to it");
132
98
  if (files.vars === undefined)
133
99
  return err("no vars.yml next to it");
@@ -135,17 +101,17 @@ export const parseServer = (files) => {
135
101
  return err("no secrets.yml next to it");
136
102
  if (isVaulted(files.vars))
137
103
  return err("vars.yml is vault-encrypted; it holds settings only — secrets go in secrets.yml");
138
- if (target.value !== "multipass" && serverVault.value.kind === "none")
139
- return err(`target ${target.value} requires vault: true`);
140
- if (target.value !== "multipass" && !isVaulted(files.secrets))
141
- return err(`target ${target.value} requires a vault-encrypted secrets.yml`);
142
- const appValues = appValuesProblem(files.appValues, target.value !== "multipass");
104
+ if (target !== "multipass" && serverVault.value.kind === "none")
105
+ return err(`target ${target} requires vault: true`);
106
+ if (target !== "multipass" && !isVaulted(files.secrets))
107
+ return err(`target ${target} requires a vault-encrypted secrets.yml`);
108
+ const appValues = appValuesProblem(files.appValues, target !== "multipass");
143
109
  if (appValues !== undefined)
144
110
  return err(appValues);
145
111
  const vars = fields(files.vars);
146
112
  if (!vars.ok)
147
113
  return err(`vars.yml ${vars.error}`);
148
- const varsChecked = checkSettings("vars.yml", vars.value, varsSchema(kind.value), knownSettings(kind.value));
114
+ const varsChecked = checkSettings("vars.yml", vars.value, varsSchema(kind), knownSettings(kind));
149
115
  if (!varsChecked.ok)
150
116
  return varsChecked;
151
117
  const backup = mapping(vars.value["restic_backup"])?.["dir"];
@@ -155,21 +121,23 @@ export const parseServer = (files) => {
155
121
  const inventory = files.inventory === undefined ? ok(undefined) : inventoryOf(files.inventory);
156
122
  if (!inventory.ok)
157
123
  return inventory;
124
+ const declared = descriptor.value["apps"];
125
+ const entries = Array.isArray(declared) ? declared : [];
158
126
  return ok({
159
127
  name: files.name,
160
128
  dir: files.dir,
161
- kind: kind.value,
162
- target: target.value,
163
- domain: serverDomain.value,
129
+ kind,
130
+ target,
131
+ domain,
164
132
  vault: serverVault.value,
165
133
  hasVaultedSecrets: isVaulted(files.secrets),
166
- apps: apps.value,
134
+ apps: apps.map((app, index) => typed({ name: app.name, repo: app.repo, path: app.path, entry: mapping(entries[index]) ?? {} })),
167
135
  hasTerraform: files.hasTerraform,
168
- buildsVm: target.value === "home" && vars.value["vm"] !== undefined,
136
+ buildsVm: target === "home" && vars.value["vm"] !== undefined,
169
137
  usesAcmeDns: typeof vars.value["acme_dns"] === "string" && vars.value["acme_dns"] !== "",
170
138
  inventory: inventory.value,
171
139
  backupDir: backupDir.value,
172
- stackHosts: stackHosts(files.stacks.flatMap((stack) => Object.freeze(stack.compose ?? [])), serverDomain.value),
140
+ stackHosts: stackHosts(files.stacks.flatMap((stack) => Object.freeze(stack.compose ?? [])), domain),
173
141
  vars: vars.value,
174
142
  files: { vars: files.vars, secrets: files.secrets, stacks: files.stacks.map((stack) => stack.name), appValues: files.appValues },
175
143
  });
@@ -1,5 +1,7 @@
1
1
  import { z } from "zod";
2
- import { typed } from "../../typed.js";
2
+ import { typed } from "../../lib/typed.js";
3
+ import { appNameSchema, domainSchema, repoPathSchema, repoUrlSchema, subdomainSchema } from "./brand.js";
4
+ import { serverTargets } from "./model.js";
3
5
  /** The server kinds, each with its playbook; settings say which kinds read them. */
4
6
  export const serverKinds = ["platform", "edge", "nas"];
5
7
  // eslint-disable-next-line functional/prefer-immutable-types -- holds a Zod schema: immutable once built, but a class the rule cannot see into
@@ -115,28 +117,51 @@ export const defaultsSchema = z.strictObject(shape(settings.filter((each) => !ea
115
117
  /** secrets.yml: the known secrets typed; other keys may be helpers that vars.yml references. */
116
118
  // eslint-disable-next-line functional/prefer-immutable-types -- a Zod schema: immutable once built, but a class the rule cannot see into
117
119
  export const secretsSchema = (kind) => z.looseObject(shape(settingsFor(kind, true)));
118
- /** server.yml: topology only. */
119
- export const serverSchema = z.strictObject({
120
- kind: z.enum(serverKinds).optional().describe("Which playbook: platform (default; Traefik, Authelia, the deployer, apps), edge or nas."),
121
- target: z.enum(["hetzner", "multipass", "home"]).describe("Where it runs: hetzner, multipass (a local VM) or home (a machine nothing creates)."),
122
- domain: z.string().describe("The server's domain; platform subdomains and the apps' hang off it."),
123
- vault: z.boolean().optional().describe("secrets.yml is vault-encrypted (required outside multipass)."),
120
+ /**
121
+ * A multipass server, a test machine by definition, may clone an app over
122
+ * plain HTTP too: the upgrade lab serves its fixture app that way.
123
+ */
124
+ const schemes = (target) => typed(target === "multipass" ? ["https://", "http://"] : ["https://"]);
125
+ /** server.yml: topology only. What it says is checked here, once: the parser, the editors' schema and the docs read it. */
126
+ export const serverSchema = z
127
+ .strictObject({
128
+ kind: z
129
+ .enum(serverKinds, { error: (issue) => `kind must be ${serverKinds.join(", ")}, not '${String(issue.input)}'` })
130
+ .default("platform")
131
+ .describe("Which playbook: platform (default; Traefik, Authelia, the deployer, apps), edge or nas."),
132
+ target: z
133
+ .enum(serverTargets, { error: (issue) => `target must be ${serverTargets.join(", ")}, not '${String(issue.input)}'` })
134
+ .describe("Where it runs: hetzner, multipass (a local VM) or home (a machine nothing creates)."),
135
+ domain: domainSchema.describe("The server's domain; platform subdomains and the apps' hang off it."),
136
+ vault: z.boolean().default(false).describe("secrets.yml is vault-encrypted (required outside multipass)."),
124
137
  vault_password_file: z.string().optional().describe("The vault password file; without it, Ansible asks."),
125
138
  apps: z
126
139
  .array(z.strictObject({
127
- name: z.string(),
128
- repo: z.string().describe("The app's repository, https://."),
140
+ name: appNameSchema,
141
+ repo: repoUrlSchema.describe("The app's repository, https://."),
129
142
  ref: z.string().optional().describe("The branch to build and deploy (default main)."),
130
- path: z.string().optional().describe("The app's root inside the repository (default .)."),
143
+ path: repoPathSchema.prefault(".").describe("The app's root inside the repository (default .)."),
131
144
  }))
132
- .optional()
145
+ .default([])
133
146
  .describe("The apps this server runs (platform only)."),
147
+ })
148
+ .superRefine((server, context) => {
149
+ if (server.kind !== "platform" && server.apps.length > 0)
150
+ context.addIssue({ code: "custom", path: ["apps"], message: "apps run on platform servers only" });
151
+ server.apps.forEach((app, index) => {
152
+ if (!schemes(server.target).some((scheme) => app.repo.startsWith(scheme)))
153
+ context.addIssue({
154
+ code: "custom",
155
+ path: ["apps", index, "repo"],
156
+ message: `repo must be an https:// URL${server.target === "multipass" ? " (or http:// on multipass)" : ""}`,
157
+ });
158
+ });
134
159
  });
135
160
  /** app.yml, at the root of an app's repository: the app contract. */
136
161
  export const appManifestSchema = z.strictObject({
137
- name: z.string().describe("The app's name, as in the server.yml entry."),
162
+ name: appNameSchema.describe("The app's name, as in the server.yml entry."),
138
163
  compose: z.array(z.string()).describe("Compose files, relative to the app root, in order."),
139
- subdomains: z.array(z.string()).describe("Hostnames the app claims: <sub>.<domain>."),
164
+ subdomains: z.array(subdomainSchema).describe("Hostnames the app claims: <sub>.<domain>."),
140
165
  secrets: z.array(z.string()).optional().describe("Secret keys; their values come from the fleet's apps/<app>.secrets.yml."),
141
166
  config: z.array(z.string()).optional().describe("Config keys; their values come from the fleet's apps/<app>.yml."),
142
167
  });