@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,196 @@
1
+ // Copyright (c) 2026 the Zuke contributors
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * `zuke upgrade --engine`: move a build another SDK hosts to another `zuke`
5
+ * release, and so to the `@zuke/engine` inside it.
6
+ *
7
+ * Such a project has no `zuke.ts` and nothing from Deno's stack: its
8
+ * launchers run a pinned `zuke` binary, which carries the engine and every
9
+ * tool wrapper, and its `zuke.json` names that engine. Moving it rewrites
10
+ * both, from the release's own `SHA256SUMS` and engine version. The project
11
+ * is found the way forwarding finds it, through the same trust gate, and
12
+ * every other field of `zuke.json` is kept.
13
+ *
14
+ * @module
15
+ */
16
+ import { ENGINE_FIELD, LAUNCHER_FILE, locateBuild, LOCK_FILE, } from "./dispatch.js";
17
+ import { binaryLauncherBash, binaryLauncherPwsh, PLAIN_BINARY_LAUNCHER, } from "./binary_launcher.js";
18
+ import { PLAIN_DENO_LAUNCHER } from "./launcher.js";
19
+ import { binaryMcpEntry, MCP_CONFIG_FILE, MCP_SERVER_NAME, mergeMcpConfig, parseMcpConfig, } from "./mcp_config.js";
20
+ import { isRecord } from "./records.js";
21
+ import { CLI_PACKAGE, registryMeta, resolveRelease } from "./upgrade.js";
22
+ import { VERSION_PATTERN } from "./version_report.js";
23
+ /** The command, as its messages name it. */
24
+ const COMMAND = "zuke upgrade --engine";
25
+ /**
26
+ * Parse the arguments following `zuke upgrade --engine`. Strict like
27
+ * `upgrade`'s own parser: this rewrites project files.
28
+ * @throws {Error} on an unknown flag, a second version, or a malformed one.
29
+ */
30
+ export function parseEnginePinFlags(args) {
31
+ const flags = { dryRun: false };
32
+ for (const arg of args) {
33
+ if (arg === "--dry-run") {
34
+ flags.dryRun = true;
35
+ }
36
+ else if (arg.startsWith("-")) {
37
+ throw new Error(`${COMMAND}: unknown option ${arg}. Usage: ${COMMAND} [<version>] ` +
38
+ "[--dry-run]");
39
+ }
40
+ else if (flags.version !== undefined) {
41
+ throw new Error(`${COMMAND}: name one version, not ${flags.version} and ${arg}.`);
42
+ }
43
+ else if (!VERSION_PATTERN.test(arg)) {
44
+ throw new Error(`${COMMAND}: "${arg}" is not a version — name a zuke release such ` +
45
+ "as 2.4.0.");
46
+ }
47
+ else {
48
+ flags.version = arg;
49
+ }
50
+ }
51
+ return flags;
52
+ }
53
+ /**
54
+ * Whether the launcher `text` is a plain one, requiring its runtime on
55
+ * `PATH`, by the line each plain variant carries. A project keeps the
56
+ * variant it chose.
57
+ */
58
+ function isPlain(text) {
59
+ return text.includes(PLAIN_BINARY_LAUNCHER) ||
60
+ text.includes(PLAIN_DENO_LAUNCHER);
61
+ }
62
+ /**
63
+ * Whether `text` is a launcher `zuke setup` wrote, of either kind, by the
64
+ * line each one opens its description with: a file of the user's own under
65
+ * the same name is never replaced.
66
+ */
67
+ function isLauncher(text) {
68
+ return /^# Zuke (bootstrap )?launcher\b/m.test(text);
69
+ }
70
+ /**
71
+ * The rewrite of a hosted build's stale `.mcp.json` server: one that runs
72
+ * an engine release on Deno (`deno run -A jsr:@zuke/engine@<v> mcp`), which
73
+ * becomes `zuke mcp`, keeping `--allow-run`. `undefined` for anything else,
74
+ * which is left as it is.
75
+ */
76
+ function mcpChange(path, text) {
77
+ const config = parseMcpConfig(text);
78
+ if (config.state !== "present")
79
+ return undefined;
80
+ const servers = config.document.mcpServers;
81
+ const entry = isRecord(servers) ? servers[MCP_SERVER_NAME] : undefined;
82
+ const args = isRecord(entry) && Array.isArray(entry.args) ? entry.args : [];
83
+ const onDeno = isRecord(entry) && entry.command === "deno" &&
84
+ args.some((arg) => typeof arg === "string" && arg.startsWith("jsr:@zuke/engine@"));
85
+ if (!onDeno)
86
+ return undefined;
87
+ return {
88
+ path,
89
+ same: false,
90
+ text: mergeMcpConfig(config.document, binaryMcpEntry(args.includes("--allow-run"))),
91
+ };
92
+ }
93
+ /**
94
+ * Run `zuke upgrade --engine <args>` for the project at or above `cwd`: move
95
+ * a build another SDK hosts to the latest (or given) `zuke` release, by
96
+ * rewriting its launchers to run that release and its `zuke.json` to pin the
97
+ * engine it carries. A project still on the Deno launchers moves to the
98
+ * binary ones. Reports through `log` and returns the exit code.
99
+ * @throws {Error} with a message for the user when there is no project, when
100
+ * it has its own `zuke.ts`, or when the release cannot be resolved.
101
+ */
102
+ export async function runEnginePin(args, log, host, paint, cwd, probe) {
103
+ const flags = parseEnginePinFlags(args);
104
+ const location = await locateBuild(cwd, probe);
105
+ if (location === null) {
106
+ throw new Error(`${COMMAND}: no zuke.json in this directory or any parent, so there ` +
107
+ "is no project to work on.");
108
+ }
109
+ if (location.engine === null) {
110
+ throw new Error(`${COMMAND}: the project at ${location.root} has its own ${location.build}, ` +
111
+ "so no engine pin to move: its Zuke version is the @zuke/core in its " +
112
+ "lock, which zuke relock moves.");
113
+ }
114
+ const version = resolveRelease(await registryMeta(() => host.cliMeta(), CLI_PACKAGE, COMMAND), flags.version, CLI_PACKAGE, COMMAND);
115
+ let pin;
116
+ try {
117
+ pin = await host.binaryPin(version);
118
+ }
119
+ catch (error) {
120
+ throw new Error(`${COMMAND}: ${error instanceof Error ? error.message : String(error)}` +
121
+ (flags.version === undefined
122
+ ? ". A release's binaries are published shortly after it; name " +
123
+ "the one before to move now."
124
+ : "."));
125
+ }
126
+ // Every file this writes, with what it holds now and what it will hold.
127
+ const configPath = `${location.root}/zuke.json`;
128
+ if (await host.entry(configPath) !== "file") {
129
+ throw new Error(`${COMMAND}: ${configPath} is not a regular file, so it is not ` +
130
+ "rewritten: a write would follow it out of the project. Edit it by hand.");
131
+ }
132
+ const config = JSON.parse(await host.readText(configPath));
133
+ const document = isRecord(config) ? config : {};
134
+ const moved = { ...document, [ENGINE_FIELD]: pin.engine };
135
+ const changes = [{
136
+ path: configPath,
137
+ same: JSON.stringify(document) === JSON.stringify(moved),
138
+ text: `${JSON.stringify(moved, null, 2)}\n`,
139
+ }];
140
+ const notes = [];
141
+ let launchers = 0;
142
+ for (const [name, render] of [
143
+ [LAUNCHER_FILE, binaryLauncherBash],
144
+ [`${LAUNCHER_FILE}.ps1`, binaryLauncherPwsh],
145
+ ]) {
146
+ const path = `${location.root}/${name}`;
147
+ const entry = await host.entry(path);
148
+ if (entry === "missing")
149
+ continue;
150
+ const before = entry === "file" ? await host.readText(path) : null;
151
+ if (before === null || !isLauncher(before)) {
152
+ notes.push(`${path} is ${before === null ? "a directory or a link" : "not a Zuke launcher"}, so it is left as it is.`);
153
+ continue;
154
+ }
155
+ launchers++;
156
+ const text = render({ download: !isPlain(before) }, pin);
157
+ changes.push({ path, same: before === text, text });
158
+ }
159
+ if (launchers === 0) {
160
+ notes.push(`No ./${LAUNCHER_FILE} or ${LAUNCHER_FILE}.ps1 launcher here was ` +
161
+ "rewritten: a launcher kept under another name still runs its old " +
162
+ "zuke release.");
163
+ }
164
+ const mcpPath = `${location.root}/${MCP_CONFIG_FILE}`;
165
+ if (await host.entry(mcpPath) === "file") {
166
+ const change = mcpChange(mcpPath, await host.readText(mcpPath));
167
+ if (change !== undefined)
168
+ changes.push(change);
169
+ }
170
+ const moving = changes.filter((change) => !change.same);
171
+ for (const note of notes)
172
+ log(` note ${note}`);
173
+ if (moving.length === 0) {
174
+ log(paint.ok(`zuke ${pin.version} (@zuke/engine ${pin.engine}) is already pinned` +
175
+ (flags.version === undefined ? ", and is the latest release" : "") +
176
+ "."));
177
+ return 0;
178
+ }
179
+ const summary = `zuke ${pin.version}, with @zuke/engine ${pin.engine}`;
180
+ if (flags.dryRun) {
181
+ log(`Would move ${location.root} to ${summary}, rewriting:`);
182
+ for (const change of moving)
183
+ log(` ${change.path}`);
184
+ return 0;
185
+ }
186
+ for (const change of moving)
187
+ await host.writeText(change.path, change.text);
188
+ log(paint.ok(`Moved ${location.root} to ${summary}.`));
189
+ if (location.frozen) {
190
+ // The binary carries exact releases, so a lock written for Deno to run
191
+ // the engine is no longer read by anything.
192
+ log(` note zuke reads no ${location.root}/${LOCK_FILE}: it carries ` +
193
+ "the exact releases it runs, so the file can be removed.");
194
+ }
195
+ return 0;
196
+ }
package/src/fs.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The one filesystem probe the package's hosts share, so the scaffolder's
3
+ * host and the dispatcher's probe agree on what "absent" means.
4
+ *
5
+ * @module
6
+ */
7
+ import { type PathInfo } from "@zuke/core";
8
+ /**
9
+ * `FileTasks.lstat` a path, or `null` when nothing is there. Reads the link itself
10
+ * rather than its target, so a symlink is reported as a symlink instead of as
11
+ * whatever it points at. A `NotFound` maps to `null`; any other error (e.g. a
12
+ * permission failure) is rethrown rather than masked as absence.
13
+ */
14
+ export declare function lstatOrNull(path: string): Promise<PathInfo | null>;
package/src/fs.js ADDED
@@ -0,0 +1,25 @@
1
+ // Copyright (c) 2026 the Zuke contributors
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * The one filesystem probe the package's hosts share, so the scaffolder's
5
+ * host and the dispatcher's probe agree on what "absent" means.
6
+ *
7
+ * @module
8
+ */
9
+ import { FileTasks } from "@zuke/core";
10
+ /**
11
+ * `FileTasks.lstat` a path, or `null` when nothing is there. Reads the link itself
12
+ * rather than its target, so a symlink is reported as a symlink instead of as
13
+ * whatever it points at. A `NotFound` maps to `null`; any other error (e.g. a
14
+ * permission failure) is rethrown rather than masked as absence.
15
+ */
16
+ export async function lstatOrNull(path) {
17
+ try {
18
+ return await FileTasks.lstat(path);
19
+ }
20
+ catch (error) {
21
+ if (FileTasks.isNotFound(error))
22
+ return null;
23
+ throw error;
24
+ }
25
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * The engine behind `zuke import`: read an existing project's task definitions —
3
+ * `package.json` scripts, a `Makefile`, or a Python project's `pyproject.toml`
4
+ * task table — and scaffold an equivalent build, so migrating to Zuke starts
5
+ * from a working translation instead of a blank page.
6
+ *
7
+ * Each discovered task becomes a `target()`. A command maps to
8
+ * {@link https://jsr.io/@zuke/cmd CmdTasks.exec} (typed, injection-safe); an
9
+ * `&&` chain becomes sequential steps; a reference to another task becomes a
10
+ * `dependsOn`; and a command too shell-specific to translate faithfully (pipes,
11
+ * redirects, substitutions, env assignments) is preserved verbatim behind a
12
+ * `// TODO` so the file still compiles and the few tricky scripts are flagged.
13
+ *
14
+ * A `pyproject.toml` (the first of `[tool.poe.tasks]`, `[tool.pdm.scripts]`,
15
+ * `[tool.hatch.envs.default.scripts]`, `[tool.taskipy.tasks]` and
16
+ * `[tool.rye.scripts]` it carries) scaffolds a **Python** build instead — the
17
+ * project `zuke setup --sdk python` makes, with a generated `build.py` whose
18
+ * targets run each command through `ctx.sh(...)` (see `./python_build.ts`).
19
+ *
20
+ * The parsing and generation are pure functions; {@link runImport} adds the
21
+ * file I/O (reusing `zuke setup`'s scaffolder via its `buildContent` hook).
22
+ *
23
+ * @module
24
+ */
25
+ import type { BinaryPin } from "./binary_pin.ts";
26
+ import { type McpSetupOptions, type ScaffoldImports, type SetupHost, type SetupResult } from "./setup.ts";
27
+ /** A task discovered in an existing project, before identifier normalisation. */
28
+ export interface RawTask {
29
+ /** The task's original name (a `package.json` script key, a Makefile target). */
30
+ readonly name: string;
31
+ /** The shell command to run (may be empty for an aggregate/phony target). */
32
+ readonly command: string;
33
+ /** Names of other tasks this one depends on / delegates to. */
34
+ readonly deps: readonly string[];
35
+ }
36
+ /**
37
+ * Parse the `scripts` block of a `package.json` document into tasks, in
38
+ * declaration order. A script segment that merely delegates to another script
39
+ * (`npm run lint`, `pnpm test`, …) is recorded as a dependency rather than an
40
+ * inlined command.
41
+ */
42
+ export declare function parsePackageJson(text: string): RawTask[];
43
+ /**
44
+ * Parse a `Makefile` into tasks: each rule (`target: prerequisites`) becomes a
45
+ * task whose recipe lines are its command and whose prerequisites become
46
+ * dependencies. Pattern rules, variable assignments, and directives are
47
+ * skipped.
48
+ */
49
+ export declare function parseMakefile(text: string): RawTask[];
50
+ /** One statement in a generated target body. */
51
+ interface BodyItem {
52
+ /** The code — a `CmdTasks.exec(...)` call or a `// TODO` comment. */
53
+ readonly code: string;
54
+ /** Whether this is a runnable command (vs. a comment placeholder). */
55
+ readonly runnable: boolean;
56
+ }
57
+ /**
58
+ * Translate a shell command into target-body statements: each `&&`-separated
59
+ * segment becomes a `CmdTasks.exec(...)` call, or a `// TODO` comment
60
+ * preserving the raw text when it is too shell-specific to translate.
61
+ */
62
+ export declare function translateCommand(command: string): BodyItem[];
63
+ /**
64
+ * Turn a task name into a valid, camelCase JavaScript identifier for a target
65
+ * field — `build:prod` → `buildProd`, `test-watch` → `testWatch`. Falls back to
66
+ * `task` for an empty result and prefixes a leading digit.
67
+ */
68
+ export declare function toIdentifier(name: string): string;
69
+ /** A generated `zuke.ts`, with the import map its bare specifiers need. */
70
+ export interface GeneratedBuild {
71
+ /** The `zuke.ts` source text. */
72
+ readonly source: string;
73
+ /**
74
+ * The `deno.json` `imports` entries {@link GeneratedBuild.source} resolves
75
+ * through — always `@zuke/core`, plus `@zuke/cmd` when a task translated to a
76
+ * command. {@link runImport} hands these to the scaffolder, which merges them
77
+ * into `deno.json`.
78
+ */
79
+ readonly imports: ScaffoldImports;
80
+ }
81
+ /**
82
+ * Generate a `zuke.ts` build class named `className` from imported tasks.
83
+ * Exposed for tools and tests; {@link runImport} writes the result to disk.
84
+ */
85
+ export declare function generateBuild(className: string, raw: readonly RawTask[]): GeneratedBuild;
86
+ /** The kinds of project `zuke import` can read. */
87
+ export type ImportSource = "package.json" | "Makefile" | "pyproject.toml";
88
+ /** Options controlling {@link runImport}. */
89
+ export interface ImportOptions {
90
+ /** Directory to import from and scaffold into. */
91
+ dir: string;
92
+ /** Overwrite existing scaffolded files instead of skipping them. */
93
+ force: boolean;
94
+ /** Build class name for the generated build file. */
95
+ name: string;
96
+ /** The TypeScript build file's name (`--build-file`); see `runSetup`. */
97
+ buildFile?: string;
98
+ /**
99
+ * Force a specific source; auto-detected (package.json, then Makefile, then
100
+ * pyproject.toml) when unset.
101
+ */
102
+ from?: ImportSource;
103
+ /** Also register the build's MCP server in `.mcp.json` (see {@link "./setup.ts".SetupOptions.mcp}). */
104
+ mcp?: McpSetupOptions;
105
+ /** Which launchers to scaffold (see {@link "./setup.ts".SetupOptions.bootstrapDeno}). */
106
+ bootstrapDeno?: boolean;
107
+ /**
108
+ * Resolve the pin of the `zuke` release a Python build's launchers run,
109
+ * whose engine its `zuke.json` pins. Called only when a `pyproject.toml` is
110
+ * imported, so importing a `package.json` or a `Makefile` never needs the
111
+ * network.
112
+ */
113
+ pin: () => Promise<BinaryPin>;
114
+ }
115
+ /** The outcome of {@link runImport}. */
116
+ export interface ImportResult extends SetupResult {
117
+ /** The source that was imported, or `null` when none was found. */
118
+ source: ImportSource | null;
119
+ /** The number of tasks discovered. */
120
+ taskCount: number;
121
+ }
122
+ /**
123
+ * Import an existing project's tasks into a generated build, then scaffold
124
+ * the launchers and the rest around it (via `zuke setup`): a `zuke.ts` and
125
+ * `deno.json` for `package.json` scripts or a `Makefile`, a `build.py` and a
126
+ * `zuke.json` and launchers pinning a `zuke` release ({@link ImportOptions.pin}) for a
127
+ * `pyproject.toml`. Detects the source automatically — `package.json`, then a
128
+ * `Makefile`, then `pyproject.toml` — unless {@link ImportOptions.from} pins
129
+ * one. Returns `source: null` when nothing was found (and writes nothing).
130
+ */
131
+ export declare function runImport(options: ImportOptions, host: SetupHost): Promise<ImportResult>;
132
+ export {};
package/src/import.js ADDED
@@ -0,0 +1,289 @@
1
+ // Copyright (c) 2026 the Zuke contributors
2
+ // SPDX-License-Identifier: MIT
3
+ import { parsePyproject } from "./pyproject.js";
4
+ import { generatePythonBuild } from "./python_build.js";
5
+ import { isRecord, joinPath, runSetup, } from "./setup.js";
6
+ import { STARTER_IMPORTS, zukeDependency } from "./starter.js";
7
+ import { literal, normalize, oneLine, order, segments, splitChain, tokenize, } from "./translate.js";
8
+ // --- package.json ---------------------------------------------------------
9
+ /** The package managers whose `run` delegations become dependencies. */
10
+ const RUNNERS = ["npm", "pnpm", "yarn", "bun", "deno"];
11
+ /**
12
+ * Parse the `scripts` block of a `package.json` document into tasks, in
13
+ * declaration order. A script segment that merely delegates to another script
14
+ * (`npm run lint`, `pnpm test`, …) is recorded as a dependency rather than an
15
+ * inlined command.
16
+ */
17
+ export function parsePackageJson(text) {
18
+ const parsed = JSON.parse(text);
19
+ if (!isRecord(parsed) || !isRecord(parsed.scripts))
20
+ return [];
21
+ const names = new Set(Object.keys(parsed.scripts));
22
+ const tasks = [];
23
+ for (const [name, value] of Object.entries(parsed.scripts)) {
24
+ if (typeof value !== "string")
25
+ continue;
26
+ const deps = [];
27
+ const kept = [];
28
+ for (const segment of splitChain(value)) {
29
+ const target = delegatedScript(segment, names);
30
+ if (target !== undefined && target !== name)
31
+ deps.push(target);
32
+ else
33
+ kept.push(segment.trim());
34
+ }
35
+ tasks.push({ name, command: kept.join(" && "), deps });
36
+ }
37
+ return tasks;
38
+ }
39
+ /** If `segment` is a `<runner> [run] <script>` delegation, the script name. */
40
+ function delegatedScript(segment, scripts) {
41
+ const tokens = tokenize(segment.trim());
42
+ if (tokens === undefined)
43
+ return undefined;
44
+ if (tokens.length === 0 || !RUNNERS.includes(tokens[0]))
45
+ return undefined;
46
+ const rest = tokens[1] === "run" ? tokens.slice(2) : tokens.slice(1);
47
+ // A pure delegation is exactly the runner and one known script name.
48
+ if (rest.length === 1 && scripts.has(rest[0]))
49
+ return rest[0];
50
+ return undefined;
51
+ }
52
+ // --- Makefile -------------------------------------------------------------
53
+ /**
54
+ * Parse a `Makefile` into tasks: each rule (`target: prerequisites`) becomes a
55
+ * task whose recipe lines are its command and whose prerequisites become
56
+ * dependencies. Pattern rules, variable assignments, and directives are
57
+ * skipped.
58
+ */
59
+ export function parseMakefile(text) {
60
+ const lines = text.split(/\r?\n/);
61
+ const tasks = [];
62
+ let current;
63
+ const flush = () => {
64
+ if (current !== undefined) {
65
+ tasks.push({
66
+ name: current.name,
67
+ command: current.recipe.join(" && "),
68
+ deps: current.deps,
69
+ });
70
+ }
71
+ current = undefined;
72
+ };
73
+ for (const line of lines) {
74
+ // Recipe lines are tab-indented and belong to the open rule.
75
+ if (current !== undefined && line.startsWith("\t")) {
76
+ const recipe = stripRecipePrefix(line.slice(1).trim());
77
+ if (recipe !== "")
78
+ current.recipe.push(recipe);
79
+ continue;
80
+ }
81
+ const rule = line.match(/^([A-Za-z0-9_.-]+)\s*:(?!=)\s*(.*)$/);
82
+ // Skip non-rules and special targets (`.PHONY`, `.DEFAULT`, …).
83
+ if (rule === null || rule[1].startsWith(".")) {
84
+ flush();
85
+ continue;
86
+ }
87
+ flush();
88
+ const deps = rule[2].trim().split(/\s+/).filter((d) => d !== "");
89
+ current = { name: rule[1], deps, recipe: [] };
90
+ }
91
+ flush();
92
+ // Prerequisites that are not themselves targets (files) are not dependencies.
93
+ const targetNames = new Set(tasks.map((t) => t.name));
94
+ return tasks.map((t) => ({
95
+ ...t,
96
+ deps: t.deps.filter((d) => targetNames.has(d)),
97
+ }));
98
+ }
99
+ /** Drop a leading recipe modifier (`@` silent, `-` ignore-errors) from a line. */
100
+ function stripRecipePrefix(recipe) {
101
+ return recipe.replace(/^[@-]+/, "");
102
+ }
103
+ /**
104
+ * Translate a shell command into target-body statements: each `&&`-separated
105
+ * segment becomes a `CmdTasks.exec(...)` call, or a `// TODO` comment
106
+ * preserving the raw text when it is too shell-specific to translate.
107
+ */
108
+ export function translateCommand(command) {
109
+ return segments(command).map((segment) => {
110
+ if ("raw" in segment) {
111
+ return {
112
+ code: `// TODO: translate this shell command: ${oneLine(segment.raw)}`,
113
+ runnable: false,
114
+ };
115
+ }
116
+ const [bin, ...args] = segment.argv;
117
+ const call = args.length === 0
118
+ ? `CmdTasks.exec(${literal(bin)})`
119
+ : `CmdTasks.exec(${literal(bin)}, (s) => s.args(${args.map(literal).join(", ")}))`;
120
+ return { code: call, runnable: true };
121
+ });
122
+ }
123
+ // --- identifiers ----------------------------------------------------------
124
+ /**
125
+ * Turn a task name into a valid, camelCase JavaScript identifier for a target
126
+ * field — `build:prod` → `buildProd`, `test-watch` → `testWatch`. Falls back to
127
+ * `task` for an empty result and prefixes a leading digit.
128
+ */
129
+ export function toIdentifier(name) {
130
+ const parts = name.split(/[^A-Za-z0-9]+/).filter((p) => p !== "");
131
+ if (parts.length === 0)
132
+ return "task";
133
+ const head = parts[0];
134
+ const camel = head.charAt(0).toLowerCase() + head.slice(1) +
135
+ parts.slice(1)
136
+ .map((p) => p.charAt(0).toUpperCase() + p.slice(1))
137
+ .join("");
138
+ return /^[0-9]/.test(camel) ? `task_${camel}` : camel;
139
+ }
140
+ // --- generation -----------------------------------------------------------
141
+ /** Render a target body from its statements (single-expression when it can). */
142
+ function renderBody(items) {
143
+ if (items.length === 0)
144
+ return "() => {}";
145
+ if (items.length === 1 && items[0].runnable)
146
+ return `() => ${items[0].code}`;
147
+ const runnable = items.some((i) => i.runnable);
148
+ const lines = items
149
+ .map((i) => ` ${i.runnable ? `await ${i.code};` : i.code}`)
150
+ .join("\n");
151
+ return `${runnable ? "async " : ""}() => {\n${lines}\n }`;
152
+ }
153
+ /**
154
+ * Generate a `zuke.ts` build class named `className` from imported tasks.
155
+ * Exposed for tools and tests; {@link runImport} writes the result to disk.
156
+ */
157
+ export function generateBuild(className, raw) {
158
+ const { ordered, dropped } = order(normalize(raw, toIdentifier, new Set()));
159
+ const bodies = new Map(ordered.map((t) => [t.id, translateCommand(t.task.command)]));
160
+ const usesCmd = [...bodies.values()].some((b) => b.some((i) => i.runnable));
161
+ const fields = ordered.map((task) => {
162
+ const body = bodies.get(task.id) ?? [];
163
+ const chain = [` ${task.id} = target()`];
164
+ chain.push(` .description(${literal(`imported: ${task.task.name}`)})`);
165
+ if (task.deps.length > 0) {
166
+ const refs = task.deps.map((d) => `this.${d}`).join(", ");
167
+ chain.push(` .dependsOn(${refs})`);
168
+ }
169
+ const skipped = dropped.get(task.id);
170
+ if (skipped !== undefined && skipped.length > 0) {
171
+ chain.push(` // TODO: dependency cycle — dropped .dependsOn(${skipped.map((d) => `this.${d}`).join(", ")})`);
172
+ }
173
+ chain.push(` .executes(${renderBody(body)});`);
174
+ return chain.join("\n");
175
+ });
176
+ // Import by bare specifier and declare the `jsr:` dependency in `deno.json`,
177
+ // exactly as `zuke setup` scaffolds it — an inline `jsr:` specifier trips
178
+ // Deno's default `no-import-prefix` lint rule on the generated file. The
179
+ // caret-major pin lives in the map, via the one definition of it.
180
+ const imports = { ...STARTER_IMPORTS };
181
+ const lines = [`import { Build, run, target } from "@zuke/core";`];
182
+ if (usesCmd) {
183
+ imports["@zuke/cmd"] = zukeDependency("cmd");
184
+ lines.push(`import { CmdTasks } from "@zuke/cmd";`);
185
+ }
186
+ const body = fields.length > 0
187
+ ? fields.join("\n\n")
188
+ : " // No tasks were found to import — add targets here.";
189
+ const source = `${lines.join("\n")}
190
+
191
+ /** Imported build — refine these targets into typed Zuke tasks. */
192
+ class ${className} extends Build {
193
+ ${body}
194
+ }
195
+
196
+ await run(${className});
197
+ `;
198
+ return { source, imports };
199
+ }
200
+ /** Translate tasks into a `zuke.ts`. */
201
+ function typescript(tasks, name) {
202
+ const generated = generateBuild(name, tasks);
203
+ return {
204
+ taskCount: tasks.length,
205
+ buildContent: generated.source,
206
+ imports: generated.imports,
207
+ python: false,
208
+ };
209
+ }
210
+ /** The source files probed during auto-detection, in priority order. */
211
+ const SOURCE_FILES = [
212
+ {
213
+ source: "package.json",
214
+ file: "package.json",
215
+ translate: (text, name) => typescript(parsePackageJson(text), name),
216
+ },
217
+ {
218
+ source: "Makefile",
219
+ file: "Makefile",
220
+ translate: (text, name) => typescript(parseMakefile(text), name),
221
+ },
222
+ {
223
+ source: "pyproject.toml",
224
+ file: "pyproject.toml",
225
+ translate: (text, name) => {
226
+ const tasks = parsePyproject(text);
227
+ return {
228
+ taskCount: tasks.length,
229
+ buildContent: generatePythonBuild(name, tasks),
230
+ python: true,
231
+ };
232
+ },
233
+ },
234
+ ];
235
+ /**
236
+ * Import an existing project's tasks into a generated build, then scaffold
237
+ * the launchers and the rest around it (via `zuke setup`): a `zuke.ts` and
238
+ * `deno.json` for `package.json` scripts or a `Makefile`, a `build.py` and a
239
+ * `zuke.json` and launchers pinning a `zuke` release ({@link ImportOptions.pin}) for a
240
+ * `pyproject.toml`. Detects the source automatically — `package.json`, then a
241
+ * `Makefile`, then `pyproject.toml` — unless {@link ImportOptions.from} pins
242
+ * one. Returns `source: null` when nothing was found (and writes nothing).
243
+ */
244
+ export async function runImport(options, host) {
245
+ const candidates = options.from === undefined
246
+ ? SOURCE_FILES
247
+ : SOURCE_FILES.filter((c) => c.source === options.from);
248
+ for (const candidate of candidates) {
249
+ const path = joinPath(options.dir, candidate.file);
250
+ if (!(await host.exists(path)))
251
+ continue;
252
+ // The source file's name is chosen here, not by the caller, so a repository
253
+ // that ships a link at it decides what gets read — and whatever is read is
254
+ // parsed into the generated build file, which import then writes back into
255
+ // the repository. Refuse rather than follow, exactly as scaffolding does.
256
+ if (await host.isSymlink(path)) {
257
+ throw new Error(`zuke import: refusing to read "${candidate.file}" — ${path} is a ` +
258
+ `symbolic link, so its contents would come from the file it points ` +
259
+ `at and end up in the generated build. Replace the link with a ` +
260
+ `regular file (or remove it), then re-run import.`);
261
+ }
262
+ const translation = candidate.translate(await host.readText(path), options.name);
263
+ host.log(`Importing ${translation.taskCount} task(s) from ${candidate.file} ` +
264
+ `into ${options.dir === "." ? "the current directory" : options.dir}:`);
265
+ const setup = await runSetup({
266
+ dir: options.dir,
267
+ force: options.force,
268
+ name: options.name,
269
+ buildFile: options.buildFile,
270
+ buildContent: translation.buildContent,
271
+ imports: translation.imports,
272
+ mcp: options.mcp,
273
+ bootstrapDeno: options.bootstrapDeno,
274
+ sdk: translation.python ? { pin: await options.pin() } : undefined,
275
+ }, host);
276
+ return {
277
+ ...setup,
278
+ source: candidate.source,
279
+ taskCount: translation.taskCount,
280
+ };
281
+ }
282
+ return {
283
+ files: [],
284
+ manualSteps: [],
285
+ notes: [],
286
+ source: null,
287
+ taskCount: 0,
288
+ };
289
+ }