@cavelon/cli 0.1.1 → 0.1.3

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 (52) hide show
  1. package/README.md +50 -20
  2. package/dist/agents.js +43 -19
  3. package/dist/choose.js +112 -0
  4. package/dist/command.js +1 -1
  5. package/dist/commands/api.js +76 -6
  6. package/dist/commands/index.js +2 -0
  7. package/dist/commands/init.js +196 -29
  8. package/dist/commands/limits-set.js +17 -8
  9. package/dist/commands/limits.js +2 -2
  10. package/dist/commands/loops.js +12 -6
  11. package/dist/commands/sandboxes.js +27 -20
  12. package/dist/commands/session.js +179 -45
  13. package/dist/commands/setup.js +426 -0
  14. package/dist/commands/solution.js +137 -91
  15. package/dist/commands/tenants.js +33 -22
  16. package/dist/commands/values.js +8 -5
  17. package/dist/commands/work.js +33 -16
  18. package/dist/context.js +5 -1
  19. package/dist/contracts.js +83 -38
  20. package/dist/embedded.js +7 -0
  21. package/dist/features.js +15 -0
  22. package/dist/fsutil.js +3 -0
  23. package/dist/git.js +14 -9
  24. package/dist/harness-ref.js +54 -0
  25. package/dist/http.js +44 -18
  26. package/dist/install.js +94 -0
  27. package/dist/invoke.js +17 -13
  28. package/dist/limits.js +9 -1
  29. package/dist/local-state.js +18 -0
  30. package/dist/main.js +31 -2
  31. package/dist/markers.js +53 -0
  32. package/dist/mcp.js +9 -2
  33. package/dist/openapi.js +10 -0
  34. package/dist/operations.js +1 -1
  35. package/dist/package-check.js +1 -1
  36. package/dist/package-files.js +103 -38
  37. package/dist/paths.js +53 -4
  38. package/dist/principal.js +43 -0
  39. package/dist/project.js +23 -4
  40. package/dist/prompt.js +55 -11
  41. package/dist/results.js +47 -9
  42. package/dist/run-program.js +92 -0
  43. package/dist/session.js +100 -19
  44. package/dist/setup-agents.js +544 -0
  45. package/dist/skills/cavelon-authoring/SKILL.md +13 -3
  46. package/dist/skills/cavelon-long-running/SKILL.md +5 -1
  47. package/dist/skills/cavelon-loop/SKILL.md +15 -9
  48. package/dist/skills/cavelon-testing/SKILL.md +9 -2
  49. package/dist/tenant-choice.js +93 -0
  50. package/dist/update-check.js +118 -0
  51. package/dist/version.js +2 -1
  52. package/package.json +5 -2
@@ -0,0 +1,94 @@
1
+ import { existsSync, realpathSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { embeddedContent } from "./embedded.js";
5
+ export const REPOSITORY = "goodguys-gmbh/cavelon-dev-kit";
6
+ export const NPM_PACKAGE = "@cavelon/cli";
7
+ const WINGET_ID = "goodguys.Cavelon";
8
+ const RELEASES = `https://github.com/${REPOSITORY}/releases/latest`;
9
+ const LABELS = {
10
+ script: "the install script",
11
+ executable: "a downloaded executable",
12
+ homebrew: "Homebrew",
13
+ winget: "winget",
14
+ npm: "npm i -g",
15
+ npx: "npx",
16
+ package: "a package manager",
17
+ source: "a source checkout",
18
+ };
19
+ export function installLabel(method) {
20
+ return LABELS[method];
21
+ }
22
+ export function detectInstall(facts) {
23
+ const { file, platform } = facts;
24
+ const p = platform === "win32" ? path.win32 : path.posix;
25
+ const segments = file.split(/[\\/]/);
26
+ if (facts.executable) {
27
+ if (segments.includes("Cellar") && segments[segments.indexOf("Cellar") + 1] === "cavelon") {
28
+ return { method: "homebrew", path: file, update: "brew upgrade cavelon", source: "github" };
29
+ }
30
+ const lower = segments.map((s) => s.toLowerCase());
31
+ const packages = lower.indexOf("packages");
32
+ if (platform === "win32" && packages > 0 && lower[packages - 1] === "winget" && lower[packages + 1]?.startsWith(`${WINGET_ID.toLowerCase()}_`)) {
33
+ return { method: "winget", path: file, update: `winget upgrade ${WINGET_ID}`, source: "github" };
34
+ }
35
+ const name = p.basename(file).toLowerCase();
36
+ if (name !== (platform === "win32" ? "cavelon.exe" : "cavelon")) {
37
+ return { method: "executable", path: file, advice: `Download the new one from ${RELEASES}.`, source: "github" };
38
+ }
39
+ return { method: "script", path: file, update: scriptUpdate(facts, p.dirname(file)), source: "github" };
40
+ }
41
+ if (segments.includes("_npx")) {
42
+ return { method: "npx", path: file, advice: "npx starts the newest release of the version range it is given each time; nothing to update." };
43
+ }
44
+ const end = segments.slice(-3).join("/");
45
+ if (end !== `node_modules/${NPM_PACKAGE}`)
46
+ return { method: "source", path: file };
47
+ const modules = p.dirname(p.dirname(file));
48
+ const shim = platform === "win32"
49
+ ? p.join(p.dirname(modules), "cavelon.cmd")
50
+ : p.basename(p.dirname(modules)) === "lib"
51
+ ? p.join(p.dirname(p.dirname(modules)), "bin", "cavelon")
52
+ : undefined;
53
+ if (shim && facts.exists(shim))
54
+ return { method: "npm", path: file, update: `npm i -g ${NPM_PACKAGE}`, source: "npm" };
55
+ return { method: "package", path: file, advice: `Update ${NPM_PACKAGE} with the package manager that installed it.`, source: "npm" };
56
+ }
57
+ function scriptUpdate(facts, dir) {
58
+ const { env } = facts;
59
+ if (facts.platform === "win32") {
60
+ const command = `irm https://github.com/${REPOSITORY}/releases/latest/download/install.ps1 | iex`;
61
+ const local = env.LOCALAPPDATA;
62
+ const usual = local ? path.win32.join(local, "Programs", "cavelon") : undefined;
63
+ if (usual && sameFolder(facts, usual, dir, true))
64
+ return command;
65
+ return `$env:CAVELON_INSTALL_DIR = '${dir.replaceAll("'", "''")}'; ${command}`;
66
+ }
67
+ const command = `curl -fsSL https://github.com/${REPOSITORY}/releases/latest/download/install.sh | sh`;
68
+ const home = env.HOME;
69
+ if (home && sameFolder(facts, path.posix.join(home, ".local", "bin"), dir, false))
70
+ return command;
71
+ return `${command} -s -- --dir ${shellQuote(dir)}`;
72
+ }
73
+ function sameFolder(facts, usual, dir, fold) {
74
+ const norm = (p) => (fold ? p.toLowerCase() : p);
75
+ return norm(usual) === norm(dir) || (facts.real !== undefined && norm(facts.real(usual)) === norm(dir));
76
+ }
77
+ function shellQuote(value) {
78
+ return /^[A-Za-z0-9_./~+-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
79
+ }
80
+ function realOrSame(file) {
81
+ try {
82
+ return realpathSync(file);
83
+ }
84
+ catch {
85
+ return file;
86
+ }
87
+ }
88
+ export function currentInstall(env) {
89
+ const executable = embeddedContent() !== undefined;
90
+ const file = executable
91
+ ? realOrSame(process.execPath)
92
+ : realOrSame(path.join(path.dirname(fileURLToPath(import.meta.url)), ".."));
93
+ return detectInstall({ executable, file, platform: process.platform, env, exists: existsSync, real: realOrSame });
94
+ }
package/dist/invoke.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { CavelonError, ExitCode, validationError } from "./errors.js";
4
+ import { bodyBytes } from "./http.js";
4
5
  import { coerceParameter, isArrayParameter, operationAt, validateBody } from "./openapi.js";
5
6
  export async function openapiOrWarn(ctx) {
6
7
  try {
@@ -18,13 +19,14 @@ export function buildRequest(op, args) {
18
19
  const given = { ...(args.params ?? {}) };
19
20
  const query = {};
20
21
  const headers = { ...(args.headers ?? {}) };
22
+ const sentHeaders = new Set(Object.keys(headers).map((h) => h.toLowerCase()));
21
23
  let filled = op.path;
22
24
  const missing = [];
23
25
  for (const param of op.parameters) {
24
26
  const values = given[param.name];
25
27
  delete given[param.name];
26
28
  if (!values || values.length === 0) {
27
- if (param.required)
29
+ if (param.required && !(param.in === "header" && sentHeaders.has(param.name.toLowerCase())))
28
30
  missing.push(`${param.name} (${param.in})`);
29
31
  continue;
30
32
  }
@@ -56,13 +58,21 @@ export function buildRequest(op, args) {
56
58
  }
57
59
  return { path: filled, query, headers };
58
60
  }
61
+ function isMultipart(op, args) {
62
+ const contentTypes = Object.keys(op.requestBody?.content ?? {});
63
+ return (contentTypes.includes("multipart/form-data") && !contentTypes.includes("application/json")) || Boolean(args.files?.length);
64
+ }
65
+ export function previewRequest(doc, op, args) {
66
+ const { path: target, query, headers } = buildRequest(op, args);
67
+ if (!isMultipart(op, args) && args.body !== undefined && doc)
68
+ validateBody(doc, op, args.body);
69
+ return { method: op.method, path: target, query, headers, body: args.body ?? null };
70
+ }
59
71
  export async function callOperation(ctx, client, doc, op, args) {
60
72
  const { path: target, query, headers } = buildRequest(op, args);
61
- const contentTypes = Object.keys(op.requestBody?.content ?? {});
62
- const multipart = contentTypes.includes("multipart/form-data") && !contentTypes.includes("application/json");
63
73
  let form;
64
74
  let json;
65
- if (multipart || args.files?.length) {
75
+ if (isMultipart(op, args)) {
66
76
  form = new FormData();
67
77
  if (args.body && typeof args.body === "object") {
68
78
  for (const [key, value] of Object.entries(args.body)) {
@@ -81,16 +91,10 @@ export async function callOperation(ctx, client, doc, op, args) {
81
91
  validateBody(doc, op, args.body);
82
92
  json = args.body;
83
93
  }
84
- const response = await client.fetchRaw(op.method, target, {
85
- query,
86
- headers,
87
- json,
88
- form,
89
- sendTenant: args.sendTenant,
90
- signal: AbortSignal.timeout(args.timeoutMs ?? (Number(ctx.io.env.CAVELON_HTTP_TIMEOUT_MS) || 30_000)),
91
- });
94
+ const signal = AbortSignal.timeout(args.timeoutMs ?? (Number(ctx.io.env.CAVELON_HTTP_TIMEOUT_MS) || 30_000));
95
+ const response = await client.fetchRaw(op.method, target, { query, headers, json, form, sendTenant: args.sendTenant, signal });
92
96
  const contentType = response.headers.get("content-type") ?? "";
93
- const bytes = new Uint8Array(await response.arrayBuffer());
97
+ const bytes = await bodyBytes(response, client.resolve(target), signal);
94
98
  const isText = /json|text|xml|yaml|markdown|event-stream/.test(contentType) || bytes.length === 0;
95
99
  const text = isText ? new TextDecoder().decode(bytes) : "";
96
100
  let data = text;
package/dist/limits.js CHANGED
@@ -243,8 +243,16 @@ export async function readQuotas(ctx, limits) {
243
243
  if (!link)
244
244
  return undefined;
245
245
  const client = await ctx.client();
246
- const response = await client.get(link.path, { allow: [400, 403, 404] });
247
246
  const base = { path: link.path, docs: link.docs ?? null };
247
+ let response;
248
+ try {
249
+ response = await client.get(link.path, { allow: [400, 403, 404] });
250
+ }
251
+ catch (error) {
252
+ if (!(error instanceof CavelonError))
253
+ throw error;
254
+ return { ...base, items: [], unavailable: `${link.path}: ${error.message}` };
255
+ }
248
256
  if (response.status !== 200 || !response.data || typeof response.data !== "object") {
249
257
  return { ...base, items: [], unavailable: `${link.path} answered ${response.status}.` };
250
258
  }
@@ -21,6 +21,24 @@ export async function writeState(root, name, content) {
21
21
  export async function readPull(root) {
22
22
  return readJsonFile(path.join(stateDir(root), "pull.json"));
23
23
  }
24
+ const PULLED_FILES = "pulled-files.json";
25
+ export async function fileDigest(file) {
26
+ const bytes = await fs.readFile(file).catch(() => undefined);
27
+ return bytes && createHash("sha256").update(bytes).digest("hex");
28
+ }
29
+ export async function writePulledFiles(root, files) {
30
+ const digests = {};
31
+ for (const file of files) {
32
+ const value = await fileDigest(path.join(root, file));
33
+ if (value)
34
+ digests[file] = value;
35
+ }
36
+ await writeState(root, PULLED_FILES, JSON.stringify({ digests }, null, 2));
37
+ }
38
+ export async function readPulledFiles(root) {
39
+ const stored = await readJsonFile(path.join(stateDir(root), PULLED_FILES));
40
+ return stored?.digests && typeof stored.digests === "object" ? stored.digests : {};
41
+ }
24
42
  export function digest(value) {
25
43
  return createHash("sha256").update(JSON.stringify(value)).digest("hex");
26
44
  }
package/dist/main.js CHANGED
@@ -4,17 +4,20 @@ import { createContext, withWarnings } from "./context.js";
4
4
  import { asCavelonError, ExitCode, usageError } from "./errors.js";
5
5
  import { blockerLines } from "./format.js";
6
6
  import { KIT_VERSION } from "./version.js";
7
+ import { currentInstall, installLabel } from "./install.js";
8
+ import { startUpdateCheck } from "./update-check.js";
7
9
  import { COMMANDS } from "./commands/index.js";
8
- export async function run(argv, io, commands = COMMANDS) {
10
+ export async function run(argv, io, commands = COMMANDS, updates = {}) {
9
11
  const json = argv.includes("--json");
10
12
  let ctx;
13
+ let notice;
11
14
  try {
12
15
  if (argv.length === 0) {
13
16
  io.stderr.write(rootHelp(commands));
14
17
  return ExitCode.usage;
15
18
  }
16
19
  if (argv[0] === "--version" || argv[0] === "-v" || argv[0] === "version") {
17
- io.stdout.write(json ? `${JSON.stringify({ version: KIT_VERSION })}\n` : `${KIT_VERSION}\n`);
20
+ io.stdout.write(versionText(updates.install ?? currentInstall(io.env), json));
18
21
  return ExitCode.ok;
19
22
  }
20
23
  const found = findCommand(argv, commands);
@@ -42,16 +45,42 @@ export async function run(argv, io, commands = COMMANDS) {
42
45
  tenant: typeof parsed.options.tenant === "string" ? parsed.options.tenant : undefined,
43
46
  solutionEnv: spec.options?.env && typeof parsed.options.env === "string" ? parsed.options.env : undefined,
44
47
  });
48
+ notice = startUpdateCheck({
49
+ io,
50
+ version: KIT_VERSION,
51
+ install: updates.install ?? currentInstall(io.env),
52
+ json: ctx.json,
53
+ command: spec.name,
54
+ fetch: updates.fetch,
55
+ });
45
56
  const result = await spec.run(ctx, parsed);
46
57
  printResult(ctx, result);
58
+ await printNotice(io, notice);
47
59
  return result.exitCode ?? ExitCode.ok;
48
60
  }
49
61
  catch (error) {
50
62
  const err = asCavelonError(error);
51
63
  printError(io, ctx?.json ?? json, err, ctx?.warnings ?? []);
64
+ await printNotice(io, notice);
52
65
  return err.exitCode;
53
66
  }
54
67
  }
68
+ function versionText(install, json) {
69
+ if (json) {
70
+ return `${JSON.stringify({ version: KIT_VERSION, install: { method: install.method, path: install.path, update: install.update ?? null } })}\n`;
71
+ }
72
+ const lines = [KIT_VERSION, `installed with: ${installLabel(install.method)} (${install.path})`];
73
+ if (install.update)
74
+ lines.push(`update with: ${install.update}`);
75
+ else if (install.advice)
76
+ lines.push(install.advice);
77
+ return `${lines.join("\n")}\n`;
78
+ }
79
+ async function printNotice(io, notice) {
80
+ const text = await notice;
81
+ if (text)
82
+ io.stderr.write(`\n${text}`);
83
+ }
55
84
  function findCommand(argv, commands) {
56
85
  const words = [];
57
86
  for (let i = 0; i < argv.length; i++) {
package/dist/markers.js CHANGED
@@ -43,6 +43,25 @@ export function upsertBlock(existing, body, style, options = {}) {
43
43
  const next = [...lines.slice(0, found.begin + 1), ...bodyLines, ...lines.slice(found.end)].join(eol);
44
44
  return next === existing ? { outcome: "unchanged" } : { outcome: "updated", content: next };
45
45
  }
46
+ export function removeBlock(existing, style) {
47
+ if (existing === undefined)
48
+ return { outcome: "unchanged" };
49
+ const eol = lineEnding(existing);
50
+ const lines = existing.split(/\r?\n/);
51
+ const found = locate(lines, style);
52
+ if (!found)
53
+ return { outcome: "unchanged" };
54
+ if ("error" in found)
55
+ return { outcome: "skipped", reason: found.error };
56
+ let begin = found.begin;
57
+ if (begin > 0 && lines[begin - 1].trim() === "")
58
+ begin--;
59
+ const rest = [...lines.slice(0, begin), ...lines.slice(found.end + 1)];
60
+ const content = rest.join(eol);
61
+ if (!content.trim())
62
+ return { outcome: "updated", content: "", empty: true };
63
+ return { outcome: "updated", content };
64
+ }
46
65
  export function isGenerated(content) {
47
66
  return content !== undefined && content.includes(GENERATED_TOKEN);
48
67
  }
@@ -81,6 +100,40 @@ export function upsertJsonEntry(existing, keys, value) {
81
100
  setPath(parsed, keys, value);
82
101
  return { outcome: current === undefined ? "appended" : "updated", content: serialize(parsed) };
83
102
  }
103
+ export function removeJsonEntry(existing, keys, matches, keep = 0) {
104
+ if (existing === undefined)
105
+ return { outcome: "unchanged" };
106
+ let parsed;
107
+ try {
108
+ parsed = JSON.parse(existing);
109
+ }
110
+ catch {
111
+ return { outcome: "skipped", reason: "it is not plain JSON (comments or a syntax error)" };
112
+ }
113
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
114
+ return { outcome: "skipped", reason: "it is not a JSON object" };
115
+ const current = getPath(parsed, keys);
116
+ if (current === undefined)
117
+ return { outcome: "unchanged" };
118
+ if (!matches(current))
119
+ return { outcome: "skipped", reason: `its "${keys.join(".")}" was changed since cavelon wrote it` };
120
+ const indent = detectIndent(existing);
121
+ const eol = lineEnding(existing);
122
+ const serialize = (v) => {
123
+ const text = JSON.stringify(v, null, indent).replace(/\n/g, eol);
124
+ return /\r?\n$/.test(existing) ? text + eol : text;
125
+ };
126
+ if (serialize(parsed) !== existing)
127
+ return { outcome: "skipped", reason: "rewriting it would change its formatting" };
128
+ for (let depth = keys.length; depth > 0; depth--) {
129
+ const parent = (depth === 1 ? parsed : getPath(parsed, keys.slice(0, depth - 1)));
130
+ const key = keys[depth - 1];
131
+ if (depth < keys.length && (depth <= keep || Object.keys(parent[key]).length > 0))
132
+ break;
133
+ delete parent[key];
134
+ }
135
+ return { outcome: "updated", content: serialize(parsed), empty: Object.keys(parsed).length === 0 };
136
+ }
84
137
  function detectIndent(text) {
85
138
  const match = /^\{\r?\n([ \t]+)"/.exec(text);
86
139
  if (!match)
package/dist/mcp.js CHANGED
@@ -6,8 +6,15 @@ import { KIT_VERSION } from "./version.js";
6
6
  const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a person stored with `cavelon login` " +
7
7
  "(or CAVELON_TOKEN). You never see or pass the token. Tools that start work (kb_upload, test_run, " +
8
8
  "loop_start, sandbox_seed, artifacts_export) return operation ids at once; read them with operation_status, " +
9
- "and follow a loop with loop_iterations. Tools marked destructive change nothing without confirm: true; " +
10
- "show the person what they would do first. Read limits before planning a solution: it lists what the " +
9
+ "and follow a loop with loop_iterations. What needs confirmation: apply imports only with confirm set to a preview's id; " +
10
+ "limits_set, models_set_limit, loop_cancel, sandbox_seed, trigger_identity, and api for an operation that is not read-only, " +
11
+ "return what they would do and change nothing without confirm: true; show the person that first. " +
12
+ "init and pull write files in the solution folder without confirm (pull refuses to replace package files with uncommitted changes unless force), " +
13
+ "and the other changing tools act at once. api refuses, even with confirm, an operation the instance marks for a person " +
14
+ "(x-cavelon-person-only; its reason is in the error), or on an instance that marks none, one that changes a secret, " +
15
+ "creates or revokes a credential (tokens, API keys, sign-in) or decides an approval. Tools read and write files only " +
16
+ "inside the solution folder (the folder of cavelon.yaml, or the one the server started in), never in cavelon's own " +
17
+ "config or cache directory. Read limits before planning a solution: it lists what the " +
11
18
  "instance allows this tenant (upload sizes and types, run and tool limits, timeouts, quotas) and who changes each. " +
12
19
  "Never change a limit on your own: propose the old and new value (limits_set for a limit a tenant admin changes, " +
13
20
  "models_set_limit for an endpoint's max_concurrent_requests) and let the person decide; an operator's limit goes to the operator. " +
package/dist/openapi.js CHANGED
@@ -38,12 +38,22 @@ export function operations(doc) {
38
38
  requestBody: raw.requestBody ? deref(doc, raw.requestBody) : undefined,
39
39
  responses: raw.responses ?? {},
40
40
  readOnly: method === "get" || method === "head" || method === "options",
41
+ personOnly: personOnlyOf(raw),
41
42
  });
42
43
  }
43
44
  }
44
45
  indexCache.set(doc, out);
45
46
  return out;
46
47
  }
48
+ function personOnlyOf(raw) {
49
+ if (!("x-cavelon-person-only" in raw))
50
+ return undefined;
51
+ const reason = raw["x-cavelon-person-only-reason"];
52
+ return {
53
+ marked: raw["x-cavelon-person-only"] === true,
54
+ ...(typeof reason === "string" && reason.trim() ? { reason: reason.trim() } : {}),
55
+ };
56
+ }
47
57
  export function deref(doc, value) {
48
58
  let current = value;
49
59
  for (let i = 0; i < 10 && current && typeof current === "object" && typeof current.$ref === "string"; i++) {
@@ -6,7 +6,7 @@ export function isSettled(op) {
6
6
  }
7
7
  export function exitCodeFor(op, note) {
8
8
  if (note?.result_failure)
9
- return ExitCode.failure;
9
+ return note.result_failure.exit_code;
10
10
  switch (op.status) {
11
11
  case "succeeded":
12
12
  return ExitCode.ok;
@@ -32,7 +32,7 @@ export const KIT_CODES = [
32
32
  {
33
33
  code: "package_file_invalid",
34
34
  area: "package",
35
- message: "A package file is not valid YAML or JSON.",
35
+ message: "A package file is not valid YAML or JSON, or is a link to a file outside the solution or to none.",
36
36
  hint: "Fix the syntax at the line the finding names.",
37
37
  docs: PACKAGE_DOCS,
38
38
  },
@@ -1,7 +1,8 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { LineCounter, parseDocument, stringify } from "yaml";
4
- import { readTextFile, writeFileAtomic } from "./fsutil.js";
4
+ import { CavelonError, ExitCode } from "./errors.js";
5
+ import { readTextFile, withoutBom, writeFileAtomic } from "./fsutil.js";
5
6
  export const DEFAULT_LAYOUT = { package: "package", items: {} };
6
7
  const PACKAGE_FILE = /\.(ya?ml|json)$/i;
7
8
  export function layoutFrom(raw) {
@@ -39,10 +40,16 @@ function rel(root, file) {
39
40
  async function listFiles(dir) {
40
41
  try {
41
42
  const entries = await fs.readdir(dir, { withFileTypes: true });
42
- return entries
43
- .filter((e) => e.isFile() && !e.name.startsWith(".") && PACKAGE_FILE.test(e.name))
44
- .map((e) => e.name)
45
- .sort((a, b) => a.localeCompare(b, "en"));
43
+ const names = [];
44
+ for (const e of entries) {
45
+ if (e.name.startsWith(".") || !PACKAGE_FILE.test(e.name))
46
+ continue;
47
+ if (e.isFile())
48
+ names.push(e.name);
49
+ else if (e.isSymbolicLink() && !(await fs.stat(path.join(dir, e.name)).then((st) => st.isDirectory(), () => false)))
50
+ names.push(e.name);
51
+ }
52
+ return names.sort((a, b) => a.localeCompare(b, "en"));
46
53
  }
47
54
  catch (error) {
48
55
  if (error.code === "ENOENT")
@@ -50,6 +57,31 @@ async function listFiles(dir) {
50
57
  throw error;
51
58
  }
52
59
  }
60
+ export async function contentPath(root, file) {
61
+ let real;
62
+ try {
63
+ real = await fs.realpath(file);
64
+ }
65
+ catch {
66
+ return file;
67
+ }
68
+ const relative = path.relative(await fs.realpath(root).catch(() => root), real);
69
+ return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative) ? real : undefined;
70
+ }
71
+ async function readSource(root, file) {
72
+ const relative = rel(root, file);
73
+ const target = await contentPath(root, file);
74
+ const invalid = (message, hint) => ({
75
+ finding: { code: "package_file_invalid", severity: "error", file: relative, message, hint },
76
+ });
77
+ if (target === undefined) {
78
+ return invalid("It is a link to a file outside the solution folder.", "Move the file into the solution folder and link to it there, or copy it in.");
79
+ }
80
+ const text = await readTextFile(target);
81
+ if (text === undefined)
82
+ return invalid("It is a link to a file that does not exist.", "Point the link at an existing file, or remove it.");
83
+ return { text: withoutBom(text) };
84
+ }
53
85
  async function exists(dir) {
54
86
  try {
55
87
  return (await fs.stat(dir)).isDirectory();
@@ -107,7 +139,13 @@ export async function readPackage(root, layout) {
107
139
  });
108
140
  continue;
109
141
  }
110
- const parsed = parseFile(root, file, (await readTextFile(file)) ?? "");
142
+ const read = await readSource(root, file);
143
+ if ("finding" in read) {
144
+ sources[section] = { file: rel(root, file) };
145
+ findings.push(read.finding);
146
+ continue;
147
+ }
148
+ const parsed = parseFile(root, file, read.text);
111
149
  sources[section] = parsed.source;
112
150
  if (parsed.finding)
113
151
  findings.push(parsed.finding);
@@ -118,7 +156,11 @@ export async function readPackage(root, layout) {
118
156
  const itemDir = path.join(root, folder);
119
157
  if (!(await exists(itemDir)))
120
158
  continue;
121
- empty = false;
159
+ const names = await listFiles(itemDir);
160
+ if (names.length)
161
+ empty = false;
162
+ else if (section in sources)
163
+ continue;
122
164
  if (section in sources) {
123
165
  findings.push({
124
166
  code: "package_file_duplicate",
@@ -130,9 +172,15 @@ export async function readPackage(root, layout) {
130
172
  }
131
173
  const items = [];
132
174
  const itemSources = [];
133
- for (const name of await listFiles(itemDir)) {
175
+ for (const name of names) {
134
176
  const file = path.join(itemDir, name);
135
- const parsed = parseFile(root, file, (await readTextFile(file)) ?? "");
177
+ const read = await readSource(root, file);
178
+ if ("finding" in read) {
179
+ itemSources.push({ file: rel(root, file) });
180
+ findings.push(read.finding);
181
+ continue;
182
+ }
183
+ const parsed = parseFile(root, file, read.text);
136
184
  itemSources.push(parsed.source);
137
185
  if (parsed.finding)
138
186
  findings.push(parsed.finding);
@@ -197,16 +245,18 @@ export function canonical(value) {
197
245
  export function toYaml(value) {
198
246
  return stringify(value, { lineWidth: 0, aliasDuplicateObjects: false });
199
247
  }
200
- async function readValue(file) {
201
- const text = await readTextFile(file);
248
+ async function readValue(root, file) {
249
+ const target = await contentPath(root, file);
250
+ const text = target === undefined ? undefined : await readTextFile(target);
202
251
  if (text === undefined)
203
252
  return { ok: false };
204
253
  try {
205
- const value = /\.json$/i.test(file) ? JSON.parse(text) : parseDocument(text, { uniqueKeys: true }).toJS({ maxAliasCount: 1000 });
206
- return { text, value, ok: true };
254
+ const plain = withoutBom(text);
255
+ const value = /\.json$/i.test(file) ? JSON.parse(plain) : parseDocument(plain, { uniqueKeys: true }).toJS({ maxAliasCount: 1000 });
256
+ return { value, ok: true };
207
257
  }
208
258
  catch {
209
- return { text, ok: false };
259
+ return { ok: false };
210
260
  }
211
261
  }
212
262
  function itemFileName(item, index, taken) {
@@ -234,6 +284,7 @@ export async function writePackage(root, layout, pkg, schema, options = {}) {
234
284
  existing.set(name.replace(PACKAGE_FILE, ""), name);
235
285
  const plans = [];
236
286
  const same = [];
287
+ const removals = [];
237
288
  for (const [section, value] of Object.entries(pkg)) {
238
289
  if (section in layout.items && Array.isArray(value))
239
290
  continue;
@@ -243,7 +294,7 @@ export async function writePackage(root, layout, pkg, schema, options = {}) {
243
294
  }
244
295
  const current = existing.get(section);
245
296
  const file = path.join(dir, current ?? `${section}.yaml`);
246
- const old = await readValue(file);
297
+ const old = await readValue(root, file);
247
298
  if (old.ok && canonical(old.value) === canonical(value))
248
299
  same.push({ file, section });
249
300
  else
@@ -256,7 +307,7 @@ export async function writePackage(root, layout, pkg, schema, options = {}) {
256
307
  const itemDir = path.join(root, folder);
257
308
  const before = new Map();
258
309
  for (const name of await listFiles(itemDir)) {
259
- const old = await readValue(path.join(itemDir, name));
310
+ const old = await readValue(root, path.join(itemDir, name));
260
311
  if (old.ok)
261
312
  before.set(name, old.value);
262
313
  }
@@ -280,40 +331,54 @@ export async function writePackage(root, layout, pkg, schema, options = {}) {
280
331
  }
281
332
  plans.push({ file: path.join(itemDir, itemFileName(item, index, taken)), section, content: toYaml(item) });
282
333
  });
283
- for (const name of before.keys()) {
284
- if (!taken.has(name)) {
285
- if (!dryRun)
286
- await fs.rm(path.join(itemDir, name), { force: true });
287
- report.removed.push(rel(root, path.join(itemDir, name)));
288
- }
289
- }
334
+ for (const name of before.keys())
335
+ if (!taken.has(name))
336
+ removals.push(path.join(itemDir, name));
290
337
  if (!dryRun)
291
338
  await fs.mkdir(itemDir, { recursive: true });
292
339
  }
340
+ for (const [section, name] of existing) {
341
+ if (section in pkg)
342
+ continue;
343
+ const file = path.join(dir, name);
344
+ if (known.has(section))
345
+ removals.push(file);
346
+ else
347
+ report.kept.push(rel(root, file));
348
+ }
293
349
  const othersChanged = plans.some((p) => !required.has(p.section));
350
+ const writes = [];
351
+ const outside = [];
294
352
  for (const plan of plans) {
295
353
  if (required.has(plan.section) && !othersChanged && existing.has(plan.section)) {
296
354
  same.push({ file: plan.file, section: plan.section });
297
355
  continue;
298
356
  }
357
+ const target = await contentPath(root, plan.file);
358
+ if (target === undefined)
359
+ outside.push(rel(root, plan.file));
360
+ else
361
+ writes.push({ file: plan.file, target, content: plan.content });
362
+ }
363
+ if (outside.length) {
364
+ throw new CavelonError(ExitCode.conflict, {
365
+ code: "package_file_outside",
366
+ message: `${outside.join(", ")} ${outside.length === 1 ? "is a link" : "are links"} to a file outside the solution folder; nothing was written.`,
367
+ hint: "Move the file into the solution folder and link to it there, or replace the link with the file.",
368
+ details: { files: outside },
369
+ });
370
+ }
371
+ for (const write of writes) {
299
372
  if (!dryRun)
300
- await writeFileAtomic(plan.file, plan.content);
301
- report.written.push(rel(root, plan.file));
373
+ await writeFileAtomic(write.target, write.content);
374
+ report.written.push(rel(root, write.file));
302
375
  }
303
- report.unchanged.push(...same.map((s) => rel(root, s.file)));
304
- for (const [section, name] of existing) {
305
- if (section in pkg)
306
- continue;
307
- const file = path.join(dir, name);
308
- if (known.has(section)) {
309
- if (!dryRun)
310
- await fs.rm(file, { force: true });
311
- report.removed.push(rel(root, file));
312
- }
313
- else {
314
- report.kept.push(rel(root, file));
315
- }
376
+ for (const file of removals) {
377
+ if (!dryRun)
378
+ await fs.rm(file, { force: true });
379
+ report.removed.push(rel(root, file));
316
380
  }
381
+ report.unchanged.push(...same.map((s) => rel(root, s.file)));
317
382
  for (const list of Object.values(report))
318
383
  list.sort();
319
384
  return report;