@zuke-build/cli 0.0.0-stage → 2.7.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 (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -2
  3. package/mod.d.ts +102 -0
  4. package/mod.js +931 -0
  5. package/package.json +35 -4
  6. package/src/binary_launcher.d.ts +49 -0
  7. package/src/binary_launcher.js +325 -0
  8. package/src/binary_pin.d.ts +47 -0
  9. package/src/binary_pin.js +117 -0
  10. package/src/build_file.d.ts +25 -0
  11. package/src/build_file.js +58 -0
  12. package/src/cache.d.ts +23 -0
  13. package/src/cache.js +26 -0
  14. package/src/deno_isolated.d.ts +14 -0
  15. package/src/deno_isolated.js +70 -0
  16. package/src/deno_path.d.ts +115 -0
  17. package/src/deno_path.js +205 -0
  18. package/src/deno_pin.d.ts +37 -0
  19. package/src/deno_pin.js +32 -0
  20. package/src/dependencies.d.ts +48 -0
  21. package/src/dependencies.js +80 -0
  22. package/src/dispatch.d.ts +229 -0
  23. package/src/dispatch.js +549 -0
  24. package/src/embedded_engine.d.ts +28 -0
  25. package/src/embedded_engine.js +21 -0
  26. package/src/engine_pin.d.ts +56 -0
  27. package/src/engine_pin.js +196 -0
  28. package/src/fs.d.ts +14 -0
  29. package/src/fs.js +25 -0
  30. package/src/import.d.ts +132 -0
  31. package/src/import.js +289 -0
  32. package/src/install_source.d.ts +79 -0
  33. package/src/install_source.js +104 -0
  34. package/src/launcher.d.ts +37 -0
  35. package/src/launcher.js +405 -0
  36. package/src/launcher_shared.d.ts +25 -0
  37. package/src/launcher_shared.js +91 -0
  38. package/src/mcp_config.d.ts +71 -0
  39. package/src/mcp_config.js +96 -0
  40. package/src/node_launcher.d.ts +19 -0
  41. package/src/node_launcher.js +416 -0
  42. package/src/node_pin.d.ts +25 -0
  43. package/src/node_pin.js +30 -0
  44. package/src/output.d.ts +38 -0
  45. package/src/output.js +43 -0
  46. package/src/paint.d.ts +42 -0
  47. package/src/paint.js +38 -0
  48. package/src/project.d.ts +69 -0
  49. package/src/project.js +132 -0
  50. package/src/pyproject.d.ts +30 -0
  51. package/src/pyproject.js +156 -0
  52. package/src/python_build.d.ts +27 -0
  53. package/src/python_build.js +197 -0
  54. package/src/records.d.ts +18 -0
  55. package/src/records.js +31 -0
  56. package/src/relock.d.ts +11 -0
  57. package/src/relock.js +182 -0
  58. package/src/runtime_field.d.ts +15 -0
  59. package/src/runtime_field.js +29 -0
  60. package/src/setup.d.ts +259 -0
  61. package/src/setup.js +693 -0
  62. package/src/star.d.ts +44 -0
  63. package/src/star.js +100 -0
  64. package/src/starter.d.ts +64 -0
  65. package/src/starter.js +138 -0
  66. package/src/toml.d.ts +32 -0
  67. package/src/toml.js +354 -0
  68. package/src/translate.d.ts +69 -0
  69. package/src/translate.js +198 -0
  70. package/src/upgrade.d.ts +113 -0
  71. package/src/upgrade.js +344 -0
  72. package/src/version.d.ts +11 -0
  73. package/src/version.js +13 -0
  74. package/src/version_report.d.ts +55 -0
  75. package/src/version_report.js +187 -0
  76. package/zuke.js +8 -0
@@ -0,0 +1,69 @@
1
+ import { type BuildLocation, type BuildProbe } from "./dispatch.ts";
2
+ /**
3
+ * What the project commands reach outside the process, injectable so they
4
+ * are testable without a real `deno`.
5
+ */
6
+ export interface ProjectHost {
7
+ /**
8
+ * What is at `path`, not following a link: a regular `file`, nothing
9
+ * (`missing`), or `other` — a directory, or a link, which a write would
10
+ * follow out of the project.
11
+ */
12
+ entry(path: string): Promise<"file" | "missing" | "other">;
13
+ /** Read a text file, rejecting when it cannot be read. */
14
+ readText(path: string): Promise<string>;
15
+ /** Write a text file, replacing what is there. */
16
+ writeText(path: string, text: string): Promise<void>;
17
+ /** Remove a file. */
18
+ remove(path: string): Promise<void>;
19
+ /** Run `deno <denoArgs>` in `cwd`, returning its exit code. */
20
+ deno(denoArgs: string[], cwd: string): Promise<number>;
21
+ /** The version of the Deno that runs the command. */
22
+ denoVersion(): string;
23
+ }
24
+ /** The real {@link ProjectHost}: the file system, and `deno` in the root. */
25
+ export declare const defaultProjectHost: ProjectHost;
26
+ /**
27
+ * The project at or above `cwd`, through the trust gate: its root, and the
28
+ * build file its `zuke.json` names.
29
+ *
30
+ * Every caller works on the project's own Deno code — its build file, its
31
+ * `deno.json` and the lock beside them — so a build another SDK hosts, which
32
+ * has neither, is refused by name rather than handed to a `deno` command
33
+ * that fails on a missing build file or writes a `deno.json` nothing reads.
34
+ *
35
+ * @throws {Error} naming `command` when there is no project, when the trust
36
+ * gate refuses the one there is, or when it is a build another SDK hosts.
37
+ */
38
+ export declare function projectLocation(cwd: string, probe: BuildProbe, command: string): Promise<BuildLocation>;
39
+ /** Flags accepted by the commands that resolve the build's module graph. */
40
+ export interface InstallFlags {
41
+ /**
42
+ * Entrypoints to resolve beside the build file — the other programs that share
43
+ * the lock, such as an app's own `main.ts`.
44
+ */
45
+ entrypoints: string[];
46
+ /** Deno's `--minimum-dependency-age` value, when one was given. */
47
+ minDepAge?: string;
48
+ /** Report what would run, and change nothing. */
49
+ dryRun: boolean;
50
+ }
51
+ /**
52
+ * Parse `relock`'s or `cache`'s arguments: further entrypoints, then
53
+ * `--min-dep-age <value>` (or `=<value>`) and `--dry-run`. Strict, so a
54
+ * mistyped option is refused rather than ignored by a command that rewrites
55
+ * the lock.
56
+ *
57
+ * @throws {Error} naming `command` on an unknown option or a missing value.
58
+ */
59
+ export declare function parseInstallFlags(command: string, args: readonly string[]): InstallFlags;
60
+ /**
61
+ * The `deno install` argv that resolves the module graph of `build`, the
62
+ * project's build file — and any
63
+ * further entrypoints — into the lock, honouring `--min-dep-age` when one was
64
+ * given.
65
+ *
66
+ * @throws {Error} naming `command` when a `--min-dep-age` was given and Deno
67
+ * `denoVersion` does not accept the flag.
68
+ */
69
+ export declare function installArgs(command: string, flags: InstallFlags, denoVersion: string, build: string): string[];
package/src/project.js ADDED
@@ -0,0 +1,132 @@
1
+ // Copyright (c) 2026 the Zuke contributors
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * What the global CLI's project commands share: `relock`, `cache`, `add` and
5
+ * `remove` each run a `deno` command in the project root, so that working on
6
+ * a Zuke project needs only `zuke`.
7
+ *
8
+ * They are the CLI's own rather than the build's because they must work
9
+ * whatever core the project is on — including one too old, or too broken, to
10
+ * update itself. The project is found the way forwarding finds it, through
11
+ * the same trust gate.
12
+ *
13
+ * @module
14
+ */
15
+ import { FileTasks, RuntimeTasks } from "@zuke/core";
16
+ import { spawnDeno } from "./deno_path.js";
17
+ import { locateBuild, } from "./dispatch.js";
18
+ import { acceptsMinimumDependencyAge } from "./upgrade.js";
19
+ /** The real {@link ProjectHost}: the file system, and `deno` in the root. */
20
+ export const defaultProjectHost = {
21
+ entry: async (path) => {
22
+ try {
23
+ return (await FileTasks.lstat(path)).isFile ? "file" : "other";
24
+ }
25
+ catch (error) {
26
+ if (FileTasks.isNotFound(error))
27
+ return "missing";
28
+ throw error;
29
+ }
30
+ },
31
+ readText: (path) => FileTasks.readText(path),
32
+ writeText: (path, text) => FileTasks.writeText(path, text),
33
+ remove: async (path) => {
34
+ await FileTasks.remove(path);
35
+ },
36
+ deno: async (denoArgs, cwd) => {
37
+ const child = spawnDeno(denoArgs, {
38
+ cwd,
39
+ stdin: "null",
40
+ stdout: "inherit",
41
+ stderr: "inherit",
42
+ });
43
+ return (await child.status).code;
44
+ },
45
+ // The cli runs on Deno, so the runtime is the Deno that runs the command.
46
+ denoVersion: () => RuntimeTasks.facts().version,
47
+ };
48
+ /**
49
+ * The project at or above `cwd`, through the trust gate: its root, and the
50
+ * build file its `zuke.json` names.
51
+ *
52
+ * Every caller works on the project's own Deno code — its build file, its
53
+ * `deno.json` and the lock beside them — so a build another SDK hosts, which
54
+ * has neither, is refused by name rather than handed to a `deno` command
55
+ * that fails on a missing build file or writes a `deno.json` nothing reads.
56
+ *
57
+ * @throws {Error} naming `command` when there is no project, when the trust
58
+ * gate refuses the one there is, or when it is a build another SDK hosts.
59
+ */
60
+ export async function projectLocation(cwd, probe, command) {
61
+ const location = await locateBuild(cwd, probe);
62
+ if (location === null) {
63
+ throw new Error(`zuke ${command}: no zuke.json in this directory or any parent, so ` +
64
+ "there is no project to work on.");
65
+ }
66
+ if (location.engine !== null) {
67
+ throw new Error(`zuke ${command}: the project at ${location.root} is a build another ` +
68
+ `SDK hosts, run on @zuke/engine ${location.engine}, with no ` +
69
+ `${location.build} or deno.json of its own to work on. Its tool ` +
70
+ "wrappers come with the SDK (zuke.tools in Python), and " +
71
+ "zuke upgrade --engine moves the engine it runs on.");
72
+ }
73
+ return location;
74
+ }
75
+ /**
76
+ * Parse `relock`'s or `cache`'s arguments: further entrypoints, then
77
+ * `--min-dep-age <value>` (or `=<value>`) and `--dry-run`. Strict, so a
78
+ * mistyped option is refused rather than ignored by a command that rewrites
79
+ * the lock.
80
+ *
81
+ * @throws {Error} naming `command` on an unknown option or a missing value.
82
+ */
83
+ export function parseInstallFlags(command, args) {
84
+ const flags = { entrypoints: [], dryRun: false };
85
+ const missing = () => new Error(`zuke ${command}: --min-dep-age needs a value, such as 0 or P2D.`);
86
+ for (let i = 0; i < args.length; i++) {
87
+ const arg = args[i];
88
+ if (arg === "--dry-run") {
89
+ flags.dryRun = true;
90
+ }
91
+ else if (arg.startsWith("--min-dep-age=")) {
92
+ flags.minDepAge = arg.slice("--min-dep-age=".length);
93
+ if (flags.minDepAge === "")
94
+ throw missing();
95
+ }
96
+ else if (arg === "--min-dep-age") {
97
+ const value = args[i + 1];
98
+ if (value === undefined || value === "" || value.startsWith("-")) {
99
+ throw missing();
100
+ }
101
+ flags.minDepAge = value;
102
+ i++;
103
+ }
104
+ else if (!arg.startsWith("-")) {
105
+ flags.entrypoints.push(arg);
106
+ }
107
+ else {
108
+ throw new Error(`zuke ${command}: unknown option ${arg}. It takes further ` +
109
+ "entrypoints, --min-dep-age <value> and --dry-run.");
110
+ }
111
+ }
112
+ return flags;
113
+ }
114
+ /**
115
+ * The `deno install` argv that resolves the module graph of `build`, the
116
+ * project's build file — and any
117
+ * further entrypoints — into the lock, honouring `--min-dep-age` when one was
118
+ * given.
119
+ *
120
+ * @throws {Error} naming `command` when a `--min-dep-age` was given and Deno
121
+ * `denoVersion` does not accept the flag.
122
+ */
123
+ export function installArgs(command, flags, denoVersion, build) {
124
+ const args = ["install", "--entrypoint", build, ...flags.entrypoints];
125
+ if (flags.minDepAge === undefined)
126
+ return args;
127
+ if (!acceptsMinimumDependencyAge(denoVersion)) {
128
+ throw new Error(`zuke ${command}: Deno ${denoVersion} does not accept ` +
129
+ "--minimum-dependency-age; upgrade Deno, or run without --min-dep-age.");
130
+ }
131
+ return [...args, `--minimum-dependency-age=${flags.minDepAge}`];
132
+ }
@@ -0,0 +1,30 @@
1
+ /** One step of an imported Python task, in the order it runs. */
2
+ export type PyStep =
3
+ /** A shell command line, translated by `segments`. */
4
+ {
5
+ readonly command: string;
6
+ }
7
+ /** An argv the task file already split (pdm's and rye's `cmd = [...]`). */
8
+ | {
9
+ readonly argv: readonly string[];
10
+ }
11
+ /** What no command expresses, kept verbatim for a `TODO` comment. */
12
+ | {
13
+ readonly todo: string;
14
+ };
15
+ /** A task read from a `pyproject.toml`, before identifier normalisation. */
16
+ export interface PyTask {
17
+ /** The task's name, its key in the task table. */
18
+ readonly name: string;
19
+ /** Its commands, in order. */
20
+ readonly steps: readonly PyStep[];
21
+ /** Names of the other tasks it runs first, without repeats. */
22
+ readonly deps: readonly string[];
23
+ }
24
+ /**
25
+ * Parse a `pyproject.toml` document into tasks, in declaration order, from
26
+ * the first task table it carries. No task table: no tasks.
27
+ *
28
+ * @throws {Error} naming the line, when the document is not TOML this reads.
29
+ */
30
+ export declare function parsePyproject(text: string): PyTask[];
@@ -0,0 +1,156 @@
1
+ // Copyright (c) 2026 the Zuke contributors
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * `zuke import`'s reader for a Python project: the task table of a
5
+ * `pyproject.toml`, turned into tasks the Python generator renders.
6
+ *
7
+ * The first of these tables present is read, each mapping a name to a task:
8
+ * `[tool.poe.tasks]` (poethepoet), `[tool.pdm.scripts]`,
9
+ * `[tool.hatch.envs.default.scripts]`, `[tool.taskipy.tasks]` and
10
+ * `[tool.rye.scripts]`. A task is a command string; an array of steps (hatch
11
+ * scripts, poe's sequence shorthand); or a table whose `cmd` (a string, or an
12
+ * argv array) or `shell` is the command and whose `sequence` (poe),
13
+ * `composite` (pdm) or `chain` (rye) lists steps. A step that names another
14
+ * task — and a poe `deps` entry, or a `ref` that names one — becomes a
15
+ * dependency, unless a command comes before it: a dependency would run it
16
+ * first, so it stays a `TODO` in its place. Any other step is a command. What no command expresses (a
17
+ * Python `call`/`script`, an `expr`, a `ref` with arguments, a task runner's
18
+ * `{args}` placeholder) is kept verbatim as a step the generator writes as a
19
+ * `TODO` comment. Settings such as `help` and `env` are not carried over.
20
+ *
21
+ * @module
22
+ */
23
+ import { isRecord } from "./records.js";
24
+ import { parseToml } from "./toml.js";
25
+ /** The task tables read, in the order they are looked for. */
26
+ const TABLES = [
27
+ ["tool", "poe", "tasks"],
28
+ ["tool", "pdm", "scripts"],
29
+ ["tool", "hatch", "envs", "default", "scripts"],
30
+ ["tool", "taskipy", "tasks"],
31
+ ["tool", "rye", "scripts"],
32
+ ];
33
+ /** A runner placeholder (`{args}`, `{args:tests}`, `{env:HOME}`) no argv carries. */
34
+ const PLACEHOLDER = /\{[^{}]*\}/;
35
+ /**
36
+ * Parse a `pyproject.toml` document into tasks, in declaration order, from
37
+ * the first task table it carries. No task table: no tasks.
38
+ *
39
+ * @throws {Error} naming the line, when the document is not TOML this reads.
40
+ */
41
+ export function parsePyproject(text) {
42
+ let document;
43
+ try {
44
+ document = parseToml(text);
45
+ }
46
+ catch (error) {
47
+ // parseToml throws only its own SyntaxError, which names the line.
48
+ throw new Error(`zuke import: cannot read pyproject.toml — ${error instanceof Error ? error.message : String(error)}`);
49
+ }
50
+ const table = TABLES.map((path) => lookup(document, path)).find(isRecord);
51
+ if (table === undefined)
52
+ return [];
53
+ // pdm keeps options shared by every script under `_`; it is not a task.
54
+ const entries = Object.entries(table).filter(([name]) => name !== "_");
55
+ const names = new Set(entries.map(([name]) => name));
56
+ return entries.map(([name, value]) => {
57
+ const draft = { steps: [], deps: [] };
58
+ readTask(value, names, draft);
59
+ return { name, ...draft };
60
+ });
61
+ }
62
+ /** The value at `path` under `value`, or `undefined` when any step is missing. */
63
+ function lookup(value, path) {
64
+ let current = value;
65
+ for (const key of path) {
66
+ if (!isRecord(current) || !Object.hasOwn(current, key))
67
+ return undefined;
68
+ current = current[key];
69
+ }
70
+ return current;
71
+ }
72
+ /** Read one task definition (a string, an array of steps, or a table) into `into`. */
73
+ function readTask(value, names, into) {
74
+ if (typeof value === "string")
75
+ command(value, into);
76
+ else if (Array.isArray(value))
77
+ steps(value, names, into);
78
+ else if (isRecord(value))
79
+ readTable(value, names, into);
80
+ else {
81
+ into.steps.push({
82
+ todo: `translate this task: ${JSON.stringify(value)}`,
83
+ });
84
+ }
85
+ }
86
+ /** Read a list of steps: a name of another task is a dependency. */
87
+ function steps(list, names, into) {
88
+ for (const item of list) {
89
+ if (typeof item === "string" && names.has(item))
90
+ runTask(item, into);
91
+ else
92
+ readTask(item, names, into);
93
+ }
94
+ }
95
+ /** Read a task's table form, by whichever key names its kind. */
96
+ function readTable(table, names, into) {
97
+ // poe runs a task's `deps` before it, whatever its kind.
98
+ if (Array.isArray(table.deps)) {
99
+ for (const dep of table.deps) {
100
+ if (typeof dep === "string" && names.has(dep))
101
+ dependOn(dep, into);
102
+ }
103
+ }
104
+ const { cmd, shell, ref } = table;
105
+ const list = table.sequence ?? table.composite ?? table.chain;
106
+ if (typeof cmd === "string")
107
+ command(cmd, into);
108
+ else if (isStringArray(cmd))
109
+ argv(cmd, into);
110
+ else if (typeof shell === "string")
111
+ command(shell, into);
112
+ else if (Array.isArray(list))
113
+ steps(list, names, into);
114
+ else if (typeof ref === "string" && names.has(ref))
115
+ runTask(ref, into);
116
+ else {
117
+ into.steps.push({ todo: `translate this task: ${JSON.stringify(table)}` });
118
+ }
119
+ }
120
+ /** A command line, unless it carries a placeholder only the task runner fills. */
121
+ function command(text, into) {
122
+ into.steps.push(PLACEHOLDER.test(text)
123
+ ? { todo: `translate this task runner placeholder: ${text}` }
124
+ : { command: text });
125
+ }
126
+ /** An argv, unless one of its entries carries a placeholder. */
127
+ function argv(list, into) {
128
+ into.steps.push(list.some((arg) => PLACEHOLDER.test(arg))
129
+ ? { todo: `translate this task runner placeholder: ${list.join(" ")}` }
130
+ : { argv: list });
131
+ }
132
+ /**
133
+ * Run another task at this point of the steps. Before any step it is a
134
+ * dependency, which runs first just as it would; after one, a dependency would
135
+ * run it too early, so it is kept in its place as a TODO instead.
136
+ */
137
+ function runTask(name, into) {
138
+ if (into.steps.length === 0)
139
+ dependOn(name, into);
140
+ else {
141
+ into.steps.push({
142
+ todo: `run the ${name} task here; it follows a command, so it is ` +
143
+ "not a dependency",
144
+ });
145
+ }
146
+ }
147
+ /** Record a dependency once. */
148
+ function dependOn(name, into) {
149
+ if (!into.deps.includes(name))
150
+ into.deps.push(name);
151
+ }
152
+ /** Whether `value` is a non-empty array of strings. */
153
+ function isStringArray(value) {
154
+ return Array.isArray(value) && value.length > 0 &&
155
+ value.every((v) => typeof v === "string");
156
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * `zuke import`'s Python generator: the `build.py` a `pyproject.toml`'s tasks
3
+ * translate to, in the shape of `zuke setup --sdk python`'s starter — the
4
+ * same script metadata, `from zuke import …` line, class and `run(...)` —
5
+ * with one `target()` field per task. Each task's commands run in a
6
+ * module-level `async def` body through `await ctx.sh("prog", "arg", …)`,
7
+ * split with the same rules as the TypeScript path; what cannot be translated
8
+ * is kept as a `# TODO` comment. The output is laid out as ruff formats it
9
+ * (4-space indent, double quotes, 88 columns), so a project's own formatter
10
+ * leaves it alone.
11
+ *
12
+ * @module
13
+ */
14
+ import type { PyTask } from "./pyproject.ts";
15
+ /**
16
+ * Turn a task name into a snake_case Python identifier for a target field —
17
+ * `test-watch` → `test_watch`, `buildProd` → `build_prod`, `lint:fix` →
18
+ * `lint_fix`. Falls back to `task` for an empty result and prefixes a leading
19
+ * digit. Never starts or ends with `_`, so no result is private or mangled.
20
+ */
21
+ export declare function toPythonIdentifier(name: string): string;
22
+ /**
23
+ * Generate a `build.py` whose build class is named `className` from tasks a
24
+ * `pyproject.toml` declared. Every string it emits goes through the one
25
+ * escaper (`literal`), and every comment through `oneLine`.
26
+ */
27
+ export declare function generatePythonBuild(className: string, tasks: readonly PyTask[]): string;
@@ -0,0 +1,197 @@
1
+ // Copyright (c) 2026 the Zuke contributors
2
+ // SPDX-License-Identifier: MIT
3
+ import { PYTHON_SCRIPT_METADATA } from "./starter.js";
4
+ import { literal, normalize, oneLine, order, segments } from "./translate.js";
5
+ /** The line length ruff formats to by default. */
6
+ const LINE_LENGTH = 88;
7
+ /**
8
+ * Names a target field may not take: Python's keywords, the `target` the
9
+ * class body calls (a field of that name would shadow it for every field
10
+ * below), and the attributes `zuke.Build` defines itself. A task normalising
11
+ * to one is suffixed with `_` instead.
12
+ */
13
+ const RESERVED = new Set([
14
+ // keyword.kwlist, less the capitalised three no snake_case name can be
15
+ "and",
16
+ "as",
17
+ "assert",
18
+ "async",
19
+ "await",
20
+ "break",
21
+ "class",
22
+ "continue",
23
+ "def",
24
+ "del",
25
+ "elif",
26
+ "else",
27
+ "except",
28
+ "finally",
29
+ "for",
30
+ "from",
31
+ "global",
32
+ "if",
33
+ "import",
34
+ "in",
35
+ "is",
36
+ "lambda",
37
+ "nonlocal",
38
+ "not",
39
+ "or",
40
+ "pass",
41
+ "raise",
42
+ "return",
43
+ "try",
44
+ "while",
45
+ "with",
46
+ "yield",
47
+ // the class body's own name
48
+ "target",
49
+ // zuke.Build's attributes
50
+ "deadline",
51
+ "unforceable",
52
+ "targets_",
53
+ "parameters_",
54
+ "groups_",
55
+ "ci_",
56
+ "on_start",
57
+ "on_target_start",
58
+ "on_target_end",
59
+ "on_finish",
60
+ "hooks_",
61
+ "describe",
62
+ "configure",
63
+ "target_",
64
+ "service_",
65
+ ]);
66
+ /**
67
+ * Turn a task name into a snake_case Python identifier for a target field —
68
+ * `test-watch` → `test_watch`, `buildProd` → `build_prod`, `lint:fix` →
69
+ * `lint_fix`. Falls back to `task` for an empty result and prefixes a leading
70
+ * digit. Never starts or ends with `_`, so no result is private or mangled.
71
+ */
72
+ export function toPythonIdentifier(name) {
73
+ const id = name
74
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
75
+ .split(/[^A-Za-z0-9]+/)
76
+ .filter((word) => word !== "")
77
+ .map((word) => word.toLowerCase())
78
+ .join("_");
79
+ if (id === "")
80
+ return "task";
81
+ return /^[0-9]/.test(id) ? `task_${id}` : id;
82
+ }
83
+ /**
84
+ * Generate a `build.py` whose build class is named `className` from tasks a
85
+ * `pyproject.toml` declared. Every string it emits goes through the one
86
+ * escaper (`literal`), and every comment through `oneLine`.
87
+ */
88
+ export function generatePythonBuild(className, tasks) {
89
+ const { ordered, dropped } = order(normalize(tasks, toPythonIdentifier, RESERVED));
90
+ const functions = [];
91
+ const fields = [];
92
+ for (const { id, task, deps } of ordered) {
93
+ const body = bodyLines(task.steps);
94
+ const fn = body.length > 0 ? `_${id}` : undefined;
95
+ if (fn !== undefined) {
96
+ const def = `async def ${fn}(ctx: Context) -> None:`;
97
+ // ruff explodes a signature that does not fit, with a trailing comma.
98
+ const head = def.length <= LINE_LENGTH
99
+ ? def
100
+ : `async def ${fn}(\n ctx: Context,\n) -> None:`;
101
+ functions.push(`${head}\n${body.join("\n")}`);
102
+ }
103
+ const calls = [
104
+ [".description", [literal(`imported: ${task.name}`)]],
105
+ ];
106
+ if (deps.length > 0)
107
+ calls.push([".depends_on", [...deps]]);
108
+ if (fn !== undefined)
109
+ calls.push([".executes", [fn]]);
110
+ const lines = [];
111
+ const skipped = dropped.get(id);
112
+ if (skipped !== undefined) {
113
+ lines.push(` # TODO: dependency cycle, dropped .depends_on(${skipped.join(", ")})`);
114
+ }
115
+ lines.push(...field(id, calls));
116
+ fields.push(lines.join("\n"));
117
+ }
118
+ const names = functions.length > 0
119
+ ? "Build, Context, run, target"
120
+ : "Build, run, target";
121
+ const members = fields.length > 0
122
+ ? fields.join("\n\n")
123
+ : " # No tasks were found to import, add targets here.";
124
+ const sections = [
125
+ `${PYTHON_SCRIPT_METADATA}"""Imported build: refine these targets into typed Zuke tasks."""\n\nfrom zuke import ${names}`,
126
+ ...functions,
127
+ `class ${className}(Build):\n """The targets imported from pyproject.toml."""\n\n${members}`,
128
+ `run(${className})\n`,
129
+ ];
130
+ return sections.join("\n\n\n");
131
+ }
132
+ /** The statements of a body, indented: `await ctx.sh(...)` and `# TODO` lines. */
133
+ function bodyLines(steps) {
134
+ const lines = [];
135
+ let runnable = false;
136
+ const run = (argv) => {
137
+ runnable = true;
138
+ lines.push(...call(4, "await ctx.sh", argv.map(literal)));
139
+ };
140
+ const todo = (text) => lines.push(` # TODO: ${oneLine(text)}`);
141
+ for (const step of steps) {
142
+ if ("todo" in step)
143
+ todo(step.todo);
144
+ else if ("argv" in step)
145
+ run(step.argv);
146
+ else {
147
+ for (const segment of segments(step.command)) {
148
+ if ("raw" in segment) {
149
+ todo(`translate this shell command: ${segment.raw}`);
150
+ }
151
+ else
152
+ run(segment.argv);
153
+ }
154
+ }
155
+ }
156
+ // A body of comments alone is not a statement Python accepts.
157
+ if (lines.length > 0 && !runnable)
158
+ lines.push(" pass");
159
+ return lines;
160
+ }
161
+ /**
162
+ * A target field, `id = target().description(...)…`, on one line when it
163
+ * fits; otherwise as ruff lays out a long method chain — wrapped in
164
+ * parentheses, one call per line — or, for a lone call, with its argument
165
+ * moved to the next line.
166
+ */
167
+ function field(id, calls) {
168
+ const chain = calls.map(([name, args]) => `${name}(${args.join(", ")})`);
169
+ const flat = ` ${id} = target()${chain.join("")}`;
170
+ if (flat.length <= LINE_LENGTH)
171
+ return [flat];
172
+ if (calls.length === 1) {
173
+ return call(4, `${id} = target()${calls[0][0]}`, calls[0][1]);
174
+ }
175
+ return [
176
+ ` ${id} = (`,
177
+ " target()",
178
+ ...calls.flatMap(([name, args]) => call(8, name, args)),
179
+ " )",
180
+ ];
181
+ }
182
+ /**
183
+ * `head(args)` at `indent` spaces, as ruff splits a call that does not fit:
184
+ * on one line; else the arguments together on the next line; else one per
185
+ * line with a trailing comma. A single argument is never exploded further.
186
+ */
187
+ function call(indent, head, args) {
188
+ const pad = " ".repeat(indent);
189
+ const flat = `${pad}${head}(${args.join(", ")})`;
190
+ if (flat.length <= LINE_LENGTH)
191
+ return [flat];
192
+ const inner = `${pad} ${args.join(", ")}`;
193
+ if (args.length === 1 || inner.length <= LINE_LENGTH) {
194
+ return [`${pad}${head}(`, inner, `${pad})`];
195
+ }
196
+ return [`${pad}${head}(`, ...args.map((a) => `${pad} ${a},`), `${pad})`];
197
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The JSON-shape guards the scaffolder's file merges share (`deno.json`,
3
+ * `.mcp.json`), and the one forgiving read of a `zuke.json` field that the
4
+ * readers of its `build` and `runtime` fields share. Kept apart from all of
5
+ * them so none has to import another for it.
6
+ *
7
+ * @module
8
+ */
9
+ /** Whether `value` is a plain object (a JSON object, not an array or null). */
10
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
11
+ /**
12
+ * Field `field` of the JSON object `text`, or `undefined` when there is no such
13
+ * field, and also when `text` is not JSON or not an object: a `zuke.json`'s
14
+ * presence alone marked a project before its fields existed, so an empty or
15
+ * malformed one means every field's default. Each field's reader decides
16
+ * whether the value it gets is valid.
17
+ */
18
+ export declare function forgivingField(text: string, field: string): unknown;
package/src/records.js ADDED
@@ -0,0 +1,31 @@
1
+ // Copyright (c) 2026 the Zuke contributors
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * The JSON-shape guards the scaffolder's file merges share (`deno.json`,
5
+ * `.mcp.json`), and the one forgiving read of a `zuke.json` field that the
6
+ * readers of its `build` and `runtime` fields share. Kept apart from all of
7
+ * them so none has to import another for it.
8
+ *
9
+ * @module
10
+ */
11
+ /** Whether `value` is a plain object (a JSON object, not an array or null). */
12
+ export function isRecord(value) {
13
+ return typeof value === "object" && value !== null && !Array.isArray(value);
14
+ }
15
+ /**
16
+ * Field `field` of the JSON object `text`, or `undefined` when there is no such
17
+ * field, and also when `text` is not JSON or not an object: a `zuke.json`'s
18
+ * presence alone marked a project before its fields existed, so an empty or
19
+ * malformed one means every field's default. Each field's reader decides
20
+ * whether the value it gets is valid.
21
+ */
22
+ export function forgivingField(text, field) {
23
+ let config;
24
+ try {
25
+ config = JSON.parse(text);
26
+ }
27
+ catch {
28
+ return undefined;
29
+ }
30
+ return isRecord(config) ? config[field] : undefined;
31
+ }
@@ -0,0 +1,11 @@
1
+ import type { BuildProbe } from "./dispatch.ts";
2
+ import type { CliPaint } from "./paint.ts";
3
+ import { type ProjectHost } from "./project.ts";
4
+ /**
5
+ * Run `zuke relock <args>` from `cwd`, reporting through `log`, and return
6
+ * the exit code.
7
+ *
8
+ * @throws {Error} with a message for the user when the request cannot be
9
+ * carried out. `main` prints the message and exits 1.
10
+ */
11
+ export declare function runRelock(args: string[], log: (line: string) => void, host: ProjectHost, paint: CliPaint, cwd: string, probe: BuildProbe): Promise<number>;