@zuke-build/cli 2.7.0 → 2.9.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.
package/src/setup.js CHANGED
@@ -9,12 +9,13 @@
9
9
  * so the logic stays pure and unit-testable; {@link defaultHost} is the real
10
10
  * `Deno`-backed implementation used in production.
11
11
  */
12
- import { binaryMcpEntry, MCP_CONFIG_FILE, mcpServerEntry, mergeMcpConfig, nodeMcpEntry, parseMcpConfig, } from "./mcp_config.js";
12
+ import { binaryMcpEntry, isServerEntry, MCP_CONFIG_FILE, MCP_SERVER_NAME, mcpServerEntry, mergeMcpConfig, nodeMcpEntry, parseMcpConfig, } from "./mcp_config.js";
13
13
  import { FileTasks, RuntimeTasks } from "@zuke/core";
14
- import { isRecord } from "./records.js";
14
+ import { forgivingField, isRecord, parsedRecord } from "./records.js";
15
15
  import { assertBuildFileName, BUILD_FILE, buildFileNamed, NEW_BUILD_FILE, } from "./build_file.js";
16
16
  import { launcherBash, launcherPwsh } from "./launcher.js";
17
17
  import { nodeLauncherBash, nodeLauncherPowerShell } from "./node_launcher.js";
18
+ import { runtimeNamed } from "./runtime_field.js";
18
19
  import { binaryLauncherBash, binaryLauncherPwsh } from "./binary_launcher.js";
19
20
  import { lstatOrNull } from "./fs.js";
20
21
  import { output } from "./output.js";
@@ -191,6 +192,11 @@ export const defaultHost = {
191
192
  // pre-write check. The temporary name is created exclusively, so it cannot
192
193
  // itself be a link someone left waiting.
193
194
  const temp = `${path}.zuke-${crypto.randomUUID().slice(0, 8)}.tmp`;
195
+ // `--dir` may name a directory that is not there yet; every path written
196
+ // is that directory joined with a file name.
197
+ const parent = path.lastIndexOf("/");
198
+ if (parent > 0)
199
+ await FileTasks.createDirectory(path.slice(0, parent));
194
200
  try {
195
201
  await FileTasks.writeText(temp, content, (s) => s.createNew());
196
202
  await FileTasks.move(temp, path);
@@ -212,6 +218,8 @@ export const defaultHost = {
212
218
  export function joinPath(dir, name) {
213
219
  return dir === "." ? name : `${dir}/${name}`;
214
220
  }
221
+ /** The line every launcher setup writes opens its description with. */
222
+ const ZUKE_LAUNCHER = /^# Zuke (?:bootstrap )?launcher\b/m;
215
223
  /** The default launcher base name. */
216
224
  export const DEFAULT_LAUNCHER = "zuke";
217
225
  /**
@@ -262,6 +270,30 @@ export async function existingBuildFile(dir, host) {
262
270
  }
263
271
  return await host.exists(joinPath(dir, BUILD_FILE)) ? BUILD_FILE : undefined;
264
272
  }
273
+ /**
274
+ * Whether the project in `dir` is one another SDK hosts: its `zuke.json`
275
+ * names an `sdk`. A `zuke.json` that is a link is not read.
276
+ */
277
+ async function hostedBySdk(dir, host) {
278
+ const config = joinPath(dir, "zuke.json");
279
+ return await host.exists(config) && !(await host.isSymlink(config)) &&
280
+ forgivingField(await host.readText(config), "sdk") !== undefined;
281
+ }
282
+ /**
283
+ * The runtime the TypeScript project in `dir` already runs on: the one its
284
+ * `zuke.json` names, Deno for one that names none or has a build file and no
285
+ * `zuke.json` yet. `undefined` for a new project.
286
+ *
287
+ * @throws {Error} when `zuke.json` names a runtime Zuke does not run on.
288
+ */
289
+ export async function existingRuntime(dir, host) {
290
+ if (await existingBuildFile(dir, host) === undefined)
291
+ return undefined;
292
+ const config = joinPath(dir, "zuke.json");
293
+ return await host.exists(config) && !(await host.isSymlink(config))
294
+ ? runtimeNamed(await host.readText(config))
295
+ : "deno";
296
+ }
265
297
  /**
266
298
  * Whether `name` in `dir` is a file of the project's own that is not a Zuke
267
299
  * build: it exists and does not import `@zuke/core`. A new project must not
@@ -326,6 +358,22 @@ export async function runSetup(options, host = defaultHost) {
326
358
  throw new Error("zuke setup: --runtime picks the runtime of a TypeScript build; " +
327
359
  "--sdk python builds run on the zuke binary.");
328
360
  }
361
+ if (sdk === undefined && await hostedBySdk(options.dir, host)) {
362
+ throw new Error("zuke setup: this project's build is hosted by another SDK (zuke.json " +
363
+ 'names an "sdk"), so it has no TypeScript build to scaffold. Re-run ' +
364
+ "with --sdk python.");
365
+ }
366
+ const was = sdk === undefined
367
+ ? await existingRuntime(options.dir, host)
368
+ : undefined;
369
+ if (was === "node" && !node) {
370
+ throw new Error("zuke setup: this project's build runs on Node (zuke.json's " +
371
+ '"runtime": "node"); setup does not move it back to Deno.');
372
+ }
373
+ // A Deno project asked for Node is converted in place: its launchers and
374
+ // zuke.json are rewritten whether or not --force is given, since that is
375
+ // what the conversion is, and its build file and deno.json are kept.
376
+ const converting = node && was === "deno";
329
377
  if (sdk !== undefined && options.buildFile !== undefined) {
330
378
  throw new Error("zuke setup: --build-file names a TypeScript build file; a Python " +
331
379
  `build is always ${PYTHON_BUILD_FILE}.`);
@@ -356,6 +404,7 @@ export async function runSetup(options, host = defaultHost) {
356
404
  : binaryLauncherBash({ download: variant.bootstrapDeno }, sdk.pin),
357
405
  mode: 0o755,
358
406
  launcher: true,
407
+ converted: converting,
359
408
  },
360
409
  {
361
410
  name: `${launcher}.ps1`,
@@ -365,12 +414,16 @@ export async function runSetup(options, host = defaultHost) {
365
414
  ? launcherPwsh(variant)
366
415
  : binaryLauncherPwsh({ download: variant.bootstrapDeno }, sdk.pin),
367
416
  launcher: true,
417
+ converted: converting,
368
418
  },
369
419
  {
370
420
  name: "zuke.json",
371
- content: sdk === undefined
372
- ? starterConfig(options.name, buildFile, options.runtime)
373
- : starterSdkConfig(options.name, sdk.pin.engine),
421
+ content: converting
422
+ ? await convertedConfig(options.dir, options.name, buildFile, host)
423
+ : sdk === undefined
424
+ ? starterConfig(options.name, buildFile, options.runtime)
425
+ : starterSdkConfig(options.name, sdk.pin.engine),
426
+ converted: converting,
374
427
  },
375
428
  ];
376
429
  // Fail before writing anything if a target name is occupied by a directory —
@@ -382,8 +435,12 @@ export async function runSetup(options, host = defaultHost) {
382
435
  ...(sdk === undefined
383
436
  ? [{ name: node ? "package.json" : "deno.json", launcher: false }]
384
437
  : []),
438
+ // A conversion reads deno.json's imports, so it is held to the same rule.
439
+ ...(converting ? [{ name: "deno.json", launcher: false }] : []),
385
440
  { name: ".gitignore", launcher: false },
386
- ...(options.mcp ? [{ name: MCP_CONFIG_FILE, launcher: false }] : []),
441
+ ...(options.mcp || converting
442
+ ? [{ name: MCP_CONFIG_FILE, launcher: false }]
443
+ : []),
387
444
  ];
388
445
  for (const item of collisionTargets) {
389
446
  const path = joinPath(options.dir, item.name);
@@ -413,7 +470,11 @@ export async function runSetup(options, host = defaultHost) {
413
470
  for (const item of scaffold) {
414
471
  const path = joinPath(options.dir, item.name);
415
472
  const existed = await host.exists(path);
416
- if (existed && !options.force) {
473
+ // A conversion rewrites zuke.json, and a launcher only when what is there
474
+ // is one of Zuke's: a file of the project's own at that name is kept.
475
+ const rewrite = existed && item.converted === true &&
476
+ (item.launcher !== true || ZUKE_LAUNCHER.test(await host.readText(path)));
477
+ if (existed && !options.force && !rewrite) {
417
478
  host.log(` skip ${item.name} (already exists)`);
418
479
  files.push({ path: item.name, status: "skipped" });
419
480
  continue;
@@ -432,11 +493,27 @@ export async function runSetup(options, host = defaultHost) {
432
493
  files.push({ path: item.name, status });
433
494
  }
434
495
  if (node) {
435
- files.push(await setupPackageJson(options.dir, host, manualSteps, notes));
496
+ // What the build file imports, plus, when converting, what the Deno
497
+ // project already declared: an imported build brings its own imports.
498
+ const declared = npmDependencies(Object.keys(options.imports ?? STARTER_IMPORTS));
499
+ const dependencies = converting
500
+ ? [
501
+ ...new Map([
502
+ ...declared,
503
+ ...await convertedDependencies(options.dir, buildFile, host, manualSteps, notes),
504
+ ]),
505
+ ]
506
+ : declared;
507
+ files.push(await setupPackageJson(options.dir, dependencies, host, manualSteps, notes));
436
508
  }
437
509
  else if (sdk === undefined) {
438
510
  files.push(await setupDenoJson(options.dir, options.imports ?? STARTER_IMPORTS, buildFile, host, manualSteps, notes));
439
511
  }
512
+ if (converting) {
513
+ const mcp = await convertMcpConfig(options.dir, buildFile, host, notes);
514
+ if (mcp !== undefined)
515
+ files.push(mcp);
516
+ }
440
517
  files.push(await setupGitignore(options.dir, host, node ? [GITIGNORE_ENTRY, "node_modules/"] : [GITIGNORE_ENTRY]));
441
518
  if (options.mcp) {
442
519
  files.push(await setupMcpConfig(options.dir, options.force, host, notes,
@@ -486,6 +563,48 @@ async function setupMcpConfig(dir, force, host, notes, entry) {
486
563
  host.log(` update ${name}`);
487
564
  return { path: name, status: "overwritten" };
488
565
  }
566
+ /**
567
+ * Point the `zuke` server of a converted project's `.mcp.json` at Node: an
568
+ * entry that runs the build file with `deno run` becomes `node`, keeping the
569
+ * arguments after the build file. Any other entry is the project's own and is
570
+ * left alone with a note; a project with no `.mcp.json`, or no `zuke` server
571
+ * in it, has nothing to convert.
572
+ */
573
+ async function convertMcpConfig(dir, buildFile, host, notes) {
574
+ const name = MCP_CONFIG_FILE;
575
+ const path = joinPath(dir, name);
576
+ if (!(await host.exists(path)))
577
+ return undefined;
578
+ const config = parseMcpConfig(await host.readText(path));
579
+ if (config.state === "unparseable") {
580
+ notes.push(`${path} could not be parsed, so its zuke server was not moved to ` +
581
+ `Node. Point it at node ${buildFile} mcp by hand.`);
582
+ return undefined;
583
+ }
584
+ const servers = config.document.mcpServers;
585
+ const entry = isRecord(servers) ? servers[MCP_SERVER_NAME] : undefined;
586
+ // A bare deno, a path to one, or deno.exe.
587
+ if (!isServerEntry(entry) || !/(?:^|[\\/])deno(?:\.exe)?$/i.test(entry.command)) {
588
+ return undefined;
589
+ }
590
+ // Only the form setup writes: any other Deno option, such as --env-file,
591
+ // has meaning Node would lose, so that entry is the user's to move.
592
+ const [run, all, file, ...rest] = entry.args;
593
+ if (run !== "run" || !["-A", "--allow-all"].includes(all) || file !== buildFile) {
594
+ notes.push(`${path}'s zuke server runs deno in a way setup does not recognise, ` +
595
+ `so it was kept. Point it at node ${buildFile} mcp by hand.`);
596
+ return undefined;
597
+ }
598
+ await host.writeText(path,
599
+ // The entry's own keys (env, cwd, type) are the user's, and kept.
600
+ mergeMcpConfig(config.document, {
601
+ ...entry,
602
+ command: "node",
603
+ args: [buildFile, ...rest],
604
+ }));
605
+ host.log(` update ${name}`);
606
+ return { path: name, status: "overwritten" };
607
+ }
489
608
  /** The line `setup` ensures is present in `.gitignore` for generated output. */
490
609
  const GITIGNORE_ENTRY = ".zuke/";
491
610
  /**
@@ -516,35 +635,105 @@ function packageNameFor(dir) {
516
635
  .replace(/^[._-]+/, "");
517
636
  return name === "" ? "zuke-build" : name;
518
637
  }
638
+ /** The dependency every Node build has: `@zuke/core`, through its npm alias. */
639
+ const STARTER_NPM_DEPENDENCY = [
640
+ "@zuke/core",
641
+ zukeNpmDependency("core"),
642
+ ];
643
+ /** A Zuke package's bare specifier, `@zuke/<name>`, without a subpath. */
644
+ const ZUKE_PACKAGE = /^@zuke\/([a-z0-9][a-z0-9-]*)$/;
645
+ /** An inline `jsr:@zuke/<name>` specifier, with or without a version and subpath. */
646
+ const INLINE_ZUKE_JSR = /["']jsr:@zuke\/([a-z0-9][a-z0-9-]*)(?:@[^"'/]*)?(?:\/[^"']*)?["']/g;
647
+ /** The npm alias of each `@zuke/<name>` among `specifiers`; others are dropped. */
648
+ function npmDependencies(specifiers) {
649
+ return specifiers.flatMap((specifier) => {
650
+ const zuke = ZUKE_PACKAGE.exec(specifier);
651
+ return zuke === null ? [] : [[specifier, zukeNpmDependency(zuke[1])]];
652
+ });
653
+ }
654
+ /**
655
+ * The `zuke.json` of the Deno project in `dir`, converted to Node: its own
656
+ * fields, with `"runtime": "node"`. A project with no `zuke.json` yet gets
657
+ * none of its own, so it gets the starter one.
658
+ *
659
+ * @throws {Error} when `zuke.json` is a link, which setup never reads or
660
+ * writes through, or not a JSON object, which nothing can merge into without
661
+ * losing it.
662
+ */
663
+ async function convertedConfig(dir, name, buildFile, host) {
664
+ const path = joinPath(dir, "zuke.json");
665
+ if (!(await host.exists(path)))
666
+ return starterConfig(name, buildFile, "node");
667
+ if (await host.isSymlink(path)) {
668
+ throw new Error(`zuke setup: refusing to convert ${path} — it is a symbolic link. ` +
669
+ "Replace it with a regular file, then re-run setup.");
670
+ }
671
+ const parsed = parsedRecord(await host.readText(path));
672
+ if (parsed === undefined) {
673
+ throw new Error(`zuke setup: ${path} is not a JSON object, so it cannot be converted ` +
674
+ 'to Node. Fix it, or add "runtime": "node" to it by hand.');
675
+ }
676
+ return `${JSON.stringify({ ...parsed, runtime: "node" }, null, 2)}\n`;
677
+ }
519
678
  /**
520
- * Create or merge `package.json` for a Node project: `type: module` and the
521
- * `@zuke/core` dependency, each only when absent. A different `type` is kept
522
- * and noted, since a CommonJS package cannot load the starter build; a file
523
- * that is not JSON is left alone and reported as a manual step.
679
+ * The dependencies a Deno project converted to Node declares in
680
+ * `package.json`: `@zuke/core`, and the npm alias of every other `@zuke/*`
681
+ * package its `deno.json` imports. What else `deno.json` imports is named in
682
+ * a note, since npm cannot install it under that name; a build file that
683
+ * still imports a `jsr:` specifier is a manual step, since Node cannot load
684
+ * one.
524
685
  */
525
- async function setupPackageJson(dir, host, steps, notes) {
686
+ async function convertedDependencies(dir, buildFile, host, steps, notes) {
687
+ const build = joinPath(dir, buildFile);
688
+ const source = await host.readText(build);
689
+ // A build that inlines its jsr: specifiers declares them nowhere else.
690
+ const inlined = [...source.matchAll(INLINE_ZUKE_JSR)].map((m) => `@zuke/${m[1]}`);
691
+ const dependencies = new Map([
692
+ STARTER_NPM_DEPENDENCY,
693
+ ...npmDependencies(inlined),
694
+ ]);
695
+ const denoJson = joinPath(dir, "deno.json");
696
+ if (await host.exists(denoJson)) {
697
+ const imports = parsedRecord(await host.readText(denoJson))?.imports;
698
+ const others = [];
699
+ for (const specifier of isRecord(imports) ? Object.keys(imports) : []) {
700
+ const [dependency] = npmDependencies([specifier]);
701
+ if (dependency === undefined)
702
+ others.push(specifier);
703
+ else
704
+ dependencies.set(...dependency);
705
+ }
706
+ notes.push(`${denoJson} is kept, but the build no longer reads it on Node. ` +
707
+ (others.length === 0
708
+ ? "Remove it once nothing else uses it."
709
+ : `If ${buildFile} imports ${others.join(", ")}, add an npm equivalent to package.json.`));
710
+ }
711
+ if (/["']jsr:/.test(source)) {
712
+ steps.push(`${build} imports a jsr: specifier, which Node cannot load. Import ` +
713
+ "@zuke/* by bare specifier instead, as package.json declares it.");
714
+ }
715
+ return [...dependencies];
716
+ }
717
+ /**
718
+ * Create or merge `package.json` for a Node project: `type: module` and
719
+ * `dependencies`, each only when absent. A different `type` is kept and
720
+ * noted, since a CommonJS package cannot load the starter build; a file that
721
+ * is not JSON is left alone and reported as a manual step.
722
+ */
723
+ async function setupPackageJson(dir, dependency, host, steps, notes) {
526
724
  const name = "package.json";
527
725
  const path = joinPath(dir, name);
528
- const dependency = [
529
- ["@zuke/core", zukeNpmDependency("core")],
530
- ];
531
726
  const exists = await host.exists(path);
532
727
  const root = {};
533
728
  let original = "";
534
729
  if (exists) {
535
- let parsed;
536
- try {
537
- parsed = JSON.parse(await host.readText(path));
538
- }
539
- catch {
540
- parsed = undefined;
541
- }
730
+ const parsed = parsedRecord(await host.readText(path));
542
731
  // Not JSON, or JSON that is not an object: either way not a manifest setup
543
732
  // can merge into, so it is left exactly as it is.
544
- if (!isRecord(parsed)) {
733
+ if (parsed === undefined) {
545
734
  host.log(` skip ${name} (not a JSON object, edit by hand)`);
546
- steps.push(`${path} is not a JSON object. Add "type": "module" and a dependency ` +
547
- `"@zuke/core": "${dependency[0][1]}" — the scaffolded build will ` +
735
+ steps.push(`${path} is not a JSON object. Add "type": "module" and the ` +
736
+ `dependencies ${npmDependencyLines(dependency)} — the build will ` +
548
737
  "not run until you do.");
549
738
  return { path: name, status: "skipped" };
550
739
  }
@@ -562,25 +751,30 @@ async function setupPackageJson(dir, host, steps, notes) {
562
751
  'the scaffolded build uses import syntax and needs "type": "module".');
563
752
  }
564
753
  const declared = root.dependencies;
565
- const added = !(isRecord(declared) && dependency[0][0] in declared);
754
+ const added = dependency.filter(([dep]) => !(isRecord(declared) && dep in declared));
566
755
  mergeMissing(root, "dependencies", dependency);
567
756
  // The launcher runs npm ci, which refuses a lockfile that no longer matches
568
757
  // package.json, so a dependency added beside an existing lock needs one
569
758
  // npm install to record it.
570
759
  const lock = joinPath(dir, "package-lock.json");
571
- if (added && await host.exists(lock)) {
760
+ if (added.length > 0 && await host.exists(lock)) {
572
761
  steps.push(`Run \`npm install --ignore-scripts\` in ${dir} once to add ` +
573
- `${dependency[0][0]} to package-lock.json: ./zuke installs with ` +
762
+ `${added.map(([dep]) => dep).join(", ")} to package-lock.json: ` +
763
+ "./zuke installs with " +
574
764
  "npm ci, which refuses a lockfile that does not match package.json.");
575
765
  }
576
766
  if (exists && JSON.stringify(root) === original) {
577
- host.log(` skip ${name} (type and @zuke/core already declared)`);
767
+ host.log(` skip ${name} (type and dependencies already declared)`);
578
768
  return { path: name, status: "skipped" };
579
769
  }
580
770
  await host.writeText(path, `${JSON.stringify(root, null, 2)}\n`);
581
771
  host.log(` ${exists ? "update" : "create"} ${name}`);
582
772
  return { path: name, status: exists ? "overwritten" : "created" };
583
773
  }
774
+ /** The `dependencies` entries `steps` tells the reader to add, as JSON. */
775
+ function npmDependencyLines(dependencies) {
776
+ return dependencies.map(([dep, spec]) => `"${dep}": "${spec}"`).join(", ");
777
+ }
584
778
  /** The `imports` entries `steps` tells the reader to add, as JSON lines. */
585
779
  function importLines(imports) {
586
780
  return Object.entries(imports)
package/src/toml.js CHANGED
@@ -250,7 +250,7 @@ class Reader {
250
250
  /** `ch` unchanged, unless it is a control character TOML forbids in a string. */
251
251
  plain(ch) {
252
252
  // deno-lint-ignore no-control-regex -- matching control characters is the point
253
- if (/[\x00-\x08\x0a-\x1f\x7f]/.test(ch)) {
253
+ if (/[\x00-\x08\x0a-\x1f\x7f]/.test(ch)) { // oxlint-disable-line no-control-regex
254
254
  this.fail("control character in string");
255
255
  }
256
256
  return ch;
package/src/translate.js CHANGED
@@ -135,7 +135,7 @@ export function literal(value) {
135
135
  */
136
136
  export function oneLine(text) {
137
137
  // deno-lint-ignore no-control-regex -- matching control characters is the point
138
- return text.replace(/[\s\x00-\x1f\x7f]+/g, " ").trim();
138
+ return text.replace(/[\s\x00-\x1f\x7f]+/g, " ").trim(); // oxlint-disable-line no-control-regex
139
139
  }
140
140
  /**
141
141
  * Give each task a unique identifier — `toId` of its name, suffixed with `_`
package/src/version.js CHANGED
@@ -10,4 +10,4 @@
10
10
  * reads it — the annotation is what keeps that from mattering if it is ever
11
11
  * exported.
12
12
  */
13
- export const VERSION = "2.7.0"; // x-release-please-version
13
+ export const VERSION = "2.9.0"; // x-release-please-version