@antelopejs/tooling-configs 0.5.2 → 0.5.4

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/dist/bin/sync.mjs CHANGED
@@ -1,21 +1,92 @@
1
1
  #!/usr/bin/env node
2
2
  import { a as formatCeilings, l as readCeilings, s as isRetired, t as CEILINGS_FILE } from "../ceilings-B7KayYIG.mjs";
3
- import { a as packageManager, c as templatePackage, i as managedPackage, l as toolingVersions, n as bootstrapDependencies, o as parseManifest, s as repositoryTools, t as addedDevDependencies, u as withDevDependencies } from "../package-DxxcxOzp.mjs";
4
- import { i as presetConfig, n as SETUP_SCRIPT, r as lefthook, t as PRESET_CONFIGS } from "../templates-BiXgdsRN.mjs";
3
+ import { a as managedPackage, c as repositoryTools, d as toolingVersions, f as usesCaptures, l as serializeManifest, n as bootstrapDependencies, o as packageManager, p as usesNuxt, r as bootstrappedManifest, s as parseManifest, t as addedDevDependencies, u as templatePackage } from "../package-CORwvwTw.mjs";
4
+ import { t as admits } from "../semver-BDxeEcP_.mjs";
5
+ import { i as presetConfig, n as SETUP_SCRIPT, r as lefthook, t as PRESET_CONFIGS } from "../templates-DaatyItc.mjs";
5
6
  import { a as VERIFY_KINDS, c as isVerifyKind, i as SYNCED_SKILL_FILES, l as skillFolder, o as claudeLink, s as claudeLinkTarget, u as planDocsSkills } from "../shared-igPpEDpS.mjs";
6
7
  import { t as runCli } from "../cli-4Tv71vYk.mjs";
7
- import { c as CI_CONTEXT, f as ciWorkflow, i as hasChecksWorkflow, n as ciNodeCallers, p as placeholderTestScript, r as ciRenovateSyncCallers, s as renovateArtifacts, t as MISSING_CHECKS_WORKFLOW, u as CI_PATH } from "../workflow-B0FmthGv.mjs";
8
+ import { c as CI_CONTEXT, f as ciWorkflow, i as hasChecksWorkflow, n as ciNodeCallers, p as placeholderTestScript, r as ciRenovateSyncCallers, s as renovateArtifacts, t as MISSING_CHECKS_WORKFLOW, u as CI_PATH } from "../workflow-CPcNc8KL.mjs";
8
9
  import { a as gitFiles, c as repositoryRoot } from "../files-DJ0TeaTU.mjs";
9
- import { i as recordedRelease, t as measureBaseline } from "../ratchet--WWa_w2O.mjs";
10
- import { n as SUPPRESSIONS_FILE, r as adoptedBudget } from "../suppression-budget-Dvb_IqBo.mjs";
11
- import { n as stepsOf, r as planDocs, t as matchingScripts } from "../script-steps-CgH2DSsp.mjs";
10
+ import { a as stepsOf, c as workspacePatterns, i as matchingScripts, n as droppedChecksSteps, o as planDocs, s as workspaceDirectories } from "../checks-CyMCnYb4.mjs";
11
+ import { i as recordedRelease, t as measureBaseline } from "../ratchet-Al0XZtOz.mjs";
12
+ import { n as SUPPRESSIONS_FILE, r as adoptedBudget } from "../suppression-budget-DgYdu6JK.mjs";
13
+ import { u as typescript } from "../suppressions-CQTcKCi1.mjs";
12
14
  import { t as DEFAULT_SHARED } from "../map-DRyYz_Fw.mjs";
13
15
  import { createRequire } from "node:module";
14
16
  import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, rmdirSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
15
17
  import { basename, dirname, join, posix, resolve } from "node:path";
16
18
  import { execFileSync, spawnSync } from "node:child_process";
19
+ import { isAlias, isMap, isNode, isScalar, isSeq, parseDocument, stringify } from "yaml";
17
20
  import ts from "typescript";
18
21
  import { parseArgs } from "node:util";
22
+ //#region src/guardrails/docs-typescript.ts
23
+ const MARKDOWN = /\.(?:md|mdc)$/i;
24
+ const UNPUBLISHED_FOLDER = "design";
25
+ const UNPUBLISHED_FILE = /grill.*\.md$/;
26
+ const FENCE = /^[\s>]*(`{3,}|~{3,})\s*([^\s[{`]*)(.*)$/;
27
+ const TYPESCRIPT_LANGUAGES = /* @__PURE__ */ new Set([
28
+ "ts",
29
+ "typescript",
30
+ "tsx",
31
+ "mts",
32
+ "cts"
33
+ ]);
34
+ const FRAGMENT = "fragment";
35
+ const DOCS_API = /<!--\s*docs-api:/;
36
+ /** Whether one fence opener is a TypeScript fence the docs check typechecks: a TypeScript language not flagged `fragment`. */
37
+ function checkedFence(language, info) {
38
+ if (!TYPESCRIPT_LANGUAGES.has(language.toLowerCase())) return false;
39
+ return !info.replace(/\[[^\]]*\]|\{[^}]*\}/g, " ").split(/\s+/).includes(FRAGMENT);
40
+ }
41
+ /** Whether a Markdown file needs a tsconfig in the docs check: it holds a checked TypeScript fence or a `docs-api` page. */
42
+ function typed(text) {
43
+ if (DOCS_API.test(text)) return true;
44
+ let open;
45
+ for (const line of text.split(/\r?\n/)) {
46
+ const fence = FENCE.exec(line);
47
+ if (!fence) continue;
48
+ const [, marker, language, info] = fence;
49
+ if (open === void 0) {
50
+ open = marker;
51
+ if (checkedFence(language, info)) return true;
52
+ } else if (marker.startsWith(open) && language === "" && info.trim() === "") open = void 0;
53
+ }
54
+ return false;
55
+ }
56
+ /** The Markdown files a `docs-files` entry selects, as the docs check walks it. */
57
+ function markdownFiles(root, path, base = path) {
58
+ const absolute = join(root, path);
59
+ const stat = statSync(absolute, { throwIfNoEntry: false });
60
+ if (!stat) return [];
61
+ if (!stat.isDirectory()) return MARKDOWN.test(path) ? [path] : [];
62
+ return readdirSync(absolute).flatMap((name) => `${path}/${name}` === `${base}/${UNPUBLISHED_FOLDER}` || UNPUBLISHED_FILE.test(name) ? [] : markdownFiles(root, `${path}/${name}`, base));
63
+ }
64
+ /**
65
+ * The docs files, relative to `root`, that hold TypeScript fences or `docs-api`
66
+ * pages the docs check typechecks, under a CI caller job that lists them in
67
+ * `docs-files` but sets no `docs-typescript-project`.
68
+ */
69
+ function untypedDocsFiles(root) {
70
+ const path = join(root, CI_PATH);
71
+ if (!existsSync(path)) return [];
72
+ const jobs = parseDocument(readFileSync(path, "utf8")).get("jobs", true);
73
+ if (!isMap(jobs)) return [];
74
+ const found = /* @__PURE__ */ new Set();
75
+ for (const { value: job } of jobs.items) {
76
+ const inputs = isMap(job) ? job.get("with", true) : void 0;
77
+ if (!isMap(inputs)) continue;
78
+ const project = inputs.get("docs-typescript-project", true);
79
+ const files = inputs.get("docs-files", true);
80
+ if (isScalar(project) && String(project.value).trim() || !isScalar(files)) continue;
81
+ for (const entry of String(files.value).split("\n")) {
82
+ const trimmed = entry.trim().replace(/\/+$/, "");
83
+ if (!trimmed) continue;
84
+ for (const file of markdownFiles(root, trimmed)) if (typed(readFileSync(join(root, file), "utf8"))) found.add(file);
85
+ }
86
+ }
87
+ return [...found];
88
+ }
89
+ //#endregion
19
90
  //#region src/guardrails/agents-block.ts
20
91
  const AGENTS_BLOCK_START = "<!-- antelopejs-guardrails:start -->";
21
92
  const AGENTS_BLOCK_END = "<!-- antelopejs-guardrails:end -->";
@@ -185,6 +256,73 @@ function agentsBlock(context) {
185
256
  ].join("\n");
186
257
  }
187
258
  //#endregion
259
+ //#region src/guardrails/pnpm-workspace.ts
260
+ const PATH = "pnpm-workspace.yaml";
261
+ /** Whether the pinned pnpm reads settings from a `pnpm-workspace.yaml` without `packages`, which pnpm before 10.5 rejects. An unpinned pnpm counts as current. */
262
+ function readsSettings(manifest) {
263
+ const pinned = manifest.packageManager?.split("@")[1];
264
+ return pinned === void 0 || admits(">=10.5.0", pinned);
265
+ }
266
+ /**
267
+ * The dependency builds sync declares and pnpm 11 must be told to skip.
268
+ * The synced `prepare` script runs `lefthook install` itself, and `MongoMemoryServer.create()` downloads the mongod that the capture peer's postinstall would fetch.
269
+ */
270
+ function skippedBuilds(captures) {
271
+ return captures ? ["lefthook", "mongodb-memory-server"] : ["lefthook"];
272
+ }
273
+ /**
274
+ * `current` with `allowBuilds.<name>` set to `false` for each of `names` the repository does not already decide.
275
+ * pnpm 11 fails an install on a dependency build it was not told about.
276
+ */
277
+ function withBuildsDecided(names, current = "") {
278
+ const document = parseDocument(current);
279
+ if (document.errors.length) throw new Error(`${PATH}: ${document.errors.map(({ message }) => message).join("; ")}`);
280
+ if (document.toJS() == null) {
281
+ const kept = current.trimStart();
282
+ const lines = names.map((name) => ` ${name}: false\n`).join("");
283
+ return `${kept}${kept === "" || kept.endsWith("\n") ? "" : "\n"}allowBuilds:\n${lines}`;
284
+ }
285
+ if (!isMap(document.contents)) throw new Error(`${PATH} must contain a YAML mapping.`);
286
+ if (document.get("allowBuilds") == null) document.set("allowBuilds", document.createNode({}));
287
+ const builds = document.get("allowBuilds");
288
+ if (!isMap(builds)) throw new Error(`${PATH}: allowBuilds must be a mapping.`);
289
+ const undecided = names.filter((name) => builds.get(name) == null);
290
+ if (!undecided.length) return current;
291
+ document.contents.flow = false;
292
+ builds.flow = false;
293
+ for (const name of undecided) builds.set(name, false);
294
+ return document.toString({
295
+ lineWidth: 0,
296
+ flowCollectionPadding: false
297
+ });
298
+ }
299
+ /** The `pnpm-workspace.yaml` a full-profile pnpm repository needs so pnpm 11 and later install the builds sync declares without `ERR_PNPM_IGNORED_BUILDS`. */
300
+ function pnpmWorkspaceArtifacts(root, manifest, managed) {
301
+ if (!managed || packageManager(manifest) !== "pnpm") return [];
302
+ const file = join(root, PATH);
303
+ const current = existsSync(file) ? readFileSync(file, "utf8") : void 0;
304
+ if (current === void 0 && !readsSettings(manifest)) return [];
305
+ const names = skippedBuilds(usesCaptures(root));
306
+ try {
307
+ const content = withBuildsDecided(names, current);
308
+ return [content === current ? {
309
+ kind: "unchanged",
310
+ path: PATH
311
+ } : {
312
+ kind: "write",
313
+ path: PATH,
314
+ content,
315
+ mode: void 0
316
+ }];
317
+ } catch (error) {
318
+ return [{
319
+ kind: "error",
320
+ path: PATH,
321
+ message: `${error instanceof Error ? error.message : String(error)} Add \`allowBuilds: { ${names.map((name) => `${name}: false`).join(", ")} }\` to it, then rerun antelopejs-sync.`
322
+ }];
323
+ }
324
+ }
325
+ //#endregion
188
326
  //#region src/guardrails/backend-boundary.ts
189
327
  /** Where a DMS frontend layer keeps its backend boundary plugin, relative to the layer. */
190
328
  const BACKEND_BOUNDARY_FILE = "build/backend-boundary.ts";
@@ -1191,10 +1329,13 @@ const MANAGED_ARTIFACTS = [
1191
1329
  {
1192
1330
  path: "package.json",
1193
1331
  profiles: ["full", "template"],
1194
- desired: (current, context) => ({
1195
- content: context.profile === "full" ? managedPackage(current, context.versions, context) : templatePackage(current, context.versions, context),
1196
- notes: []
1197
- })
1332
+ desired: (current, context) => {
1333
+ const content = context.profile === "full" ? managedPackage(current, context.versions, context) : templatePackage(current, context.versions, context);
1334
+ return {
1335
+ content,
1336
+ notes: droppedChecksSteps(current, content)
1337
+ };
1338
+ }
1198
1339
  },
1199
1340
  {
1200
1341
  path: ".nvmrc",
@@ -1338,7 +1479,7 @@ function repositoryContext(root, current, profile, verificationSkill) {
1338
1479
  versions: toolingVersions(),
1339
1480
  tools: repositoryTools(manifest),
1340
1481
  typeAware: /\btypeAware["']?\s*:\s*true\b/.test(desiredLint),
1341
- nuxt: Boolean(manifest.dependencies?.nuxt || manifest.devDependencies?.nuxt || readdirSync(root).some((name) => name.startsWith("nuxt.config."))),
1482
+ nuxt: usesNuxt(root, manifest),
1342
1483
  claude: profile === "full" ? claudeProse(root, current) : "",
1343
1484
  baseline: "",
1344
1485
  suppressionBudget: adoptedBudget(root, current.get(SUPPRESSIONS_FILE)),
@@ -1347,7 +1488,7 @@ function repositoryContext(root, current, profile, verificationSkill) {
1347
1488
  glossary: ["GLOSSARY.md", "docs/GLOSSARY.md"].find((file) => existsSync(join(root, file))),
1348
1489
  docs: profile === "full" && current.has("package.json") ? planDocs(root, manager) : void 0,
1349
1490
  placeholderTests: current.has("package.json") && placeholderTestScript(manifest.scripts?.test),
1350
- captures: existsSync(join(root, "docs/captures.ts"))
1491
+ captures: usesCaptures(root)
1351
1492
  };
1352
1493
  }
1353
1494
  function writeArtifacts(root, artifacts) {
@@ -1383,7 +1524,11 @@ function syncRepository(root, options = {}) {
1383
1524
  const writing = planWritingSkills(root, profile, verify.kind);
1384
1525
  const actions = [...verify.actions, ...writing.actions];
1385
1526
  const context = repositoryContext(root, current, profile, verify.verificationSkill);
1386
- const standalone = [...backendBoundaryArtifacts(root), ...renovateArtifacts(root, manifest, profile === "full" || verify.kind === "template")];
1527
+ const standalone = [
1528
+ ...backendBoundaryArtifacts(root),
1529
+ ...renovateArtifacts(root, manifest, profile === "full" || verify.kind === "template"),
1530
+ ...pnpmWorkspaceArtifacts(root, manifest, profile === "full")
1531
+ ];
1387
1532
  let plan = [...planSync(current, modes, context), ...standalone];
1388
1533
  const errors = plan.filter((artifact) => artifact.kind === "error").map(({ message }) => message);
1389
1534
  const entryOnly = checkEntryOnlyConfiguration(root);
@@ -1423,6 +1568,304 @@ function syncRepository(root, options = {}) {
1423
1568
  };
1424
1569
  }
1425
1570
  //#endregion
1571
+ //#region src/guardrails/workspace-members.ts
1572
+ /** Each oxlint `options` key, which oxlint reads only from the root config, and the flag that carries it on a member's own oxlint run. */
1573
+ const OPTION_FLAGS = /* @__PURE__ */ new Map([
1574
+ ["typeAware", {
1575
+ kind: "switch",
1576
+ flag: "--type-aware"
1577
+ }],
1578
+ ["typeCheck", {
1579
+ kind: "switch",
1580
+ flag: "--type-check"
1581
+ }],
1582
+ ["denyWarnings", {
1583
+ kind: "switch",
1584
+ flag: "--deny-warnings"
1585
+ }],
1586
+ ["maxWarnings", {
1587
+ kind: "count",
1588
+ flag: "--max-warnings"
1589
+ }],
1590
+ ["reportUnusedDisableDirectives", {
1591
+ kind: "severity",
1592
+ flag: "--report-unused-disable-directives-severity"
1593
+ }]
1594
+ ]);
1595
+ /** The oxlint config names oxlint discovers in a nested directory. */
1596
+ const LINT_CONFIGS = [
1597
+ "oxlint.config.ts",
1598
+ "oxlint.config.mts",
1599
+ "oxlint.config.cts",
1600
+ "oxlint.config.js",
1601
+ "oxlint.config.mjs",
1602
+ "oxlint.config.cjs",
1603
+ ".oxlintrc.json",
1604
+ ".oxlintrc.jsonc"
1605
+ ];
1606
+ /** A command word `oxlint` in a script, not `oxlint-tsgolint` or a path ending in it. */
1607
+ const OXLINT_COMMAND = /(^|[\s;&|(])oxlint(?=$|[\s;&|)])/g;
1608
+ function unwrapped(node) {
1609
+ const compiler = typescript();
1610
+ let current = node;
1611
+ while (compiler.isParenthesizedExpression(current) || compiler.isAsExpression(current) || compiler.isSatisfiesExpression(current)) current = current.expression;
1612
+ return current;
1613
+ }
1614
+ function variableInitializer(source, name) {
1615
+ const compiler = typescript();
1616
+ for (const statement of source.statements) if (compiler.isVariableStatement(statement)) {
1617
+ for (const declaration of statement.declarationList.declarations) if (compiler.isIdentifier(declaration.name) && declaration.name.text === name) return declaration.initializer;
1618
+ }
1619
+ }
1620
+ /** The object literal a config exports: itself, the first argument of `defineConfig(...)`, or a same-file variable holding either. */
1621
+ function configLiteral(source, node, seen = /* @__PURE__ */ new Set()) {
1622
+ const compiler = typescript();
1623
+ if (node === void 0) return void 0;
1624
+ const value = unwrapped(node);
1625
+ if (compiler.isObjectLiteralExpression(value)) return value;
1626
+ if (compiler.isCallExpression(value)) return configLiteral(source, value.arguments[0], seen);
1627
+ if (!compiler.isIdentifier(value) || seen.has(value.text)) return void 0;
1628
+ seen.add(value.text);
1629
+ return configLiteral(source, variableInitializer(source, value.text), seen);
1630
+ }
1631
+ function exportedConfig(path, text) {
1632
+ const compiler = typescript();
1633
+ if (path.endsWith(".json") || path.endsWith(".jsonc")) {
1634
+ const source = compiler.parseJsonText(path, text);
1635
+ const [statement] = source.statements;
1636
+ return statement && configLiteral(source, statement.expression);
1637
+ }
1638
+ const source = compiler.createSourceFile(path, text, compiler.ScriptTarget.Latest, true);
1639
+ return configLiteral(source, source.statements.find((statement) => compiler.isExportAssignment(statement) && !statement.isExportEquals)?.expression);
1640
+ }
1641
+ function propertyName(element) {
1642
+ const compiler = typescript();
1643
+ const name = element.name;
1644
+ return name !== void 0 && (compiler.isIdentifier(name) || compiler.isStringLiteralLike(name)) ? name.text : void 0;
1645
+ }
1646
+ /** The flag that carries one option value, `""` for a switch set to `false`, or undefined when the value has no flag. */
1647
+ function optionFlag(entry, value) {
1648
+ const compiler = typescript();
1649
+ switch (entry.kind) {
1650
+ case "switch":
1651
+ if (value.kind === compiler.SyntaxKind.TrueKeyword) return entry.flag;
1652
+ return value.kind === compiler.SyntaxKind.FalseKeyword ? "" : void 0;
1653
+ case "count": return compiler.isNumericLiteral(value) ? `${entry.flag}=${value.text}` : void 0;
1654
+ case "severity": return compiler.isStringLiteralLike(value) ? `${entry.flag}=${value.text}` : void 0;
1655
+ }
1656
+ }
1657
+ /** The flags an `options` literal stands for, or the keys no flag can carry. */
1658
+ function optionFlags(options) {
1659
+ const compiler = typescript();
1660
+ const literal = unwrapped(options);
1661
+ if (!compiler.isObjectLiteralExpression(literal)) return { unsupported: ["options"] };
1662
+ const flags = [];
1663
+ const unsupported = [];
1664
+ for (const element of literal.properties) {
1665
+ const name = propertyName(element) ?? element.getText();
1666
+ const entry = OPTION_FLAGS.get(name);
1667
+ const flag = entry && compiler.isPropertyAssignment(element) ? optionFlag(entry, unwrapped(element.initializer)) : void 0;
1668
+ if (flag === void 0) unsupported.push(name);
1669
+ else if (flag) flags.push(flag);
1670
+ }
1671
+ return unsupported.length ? { unsupported } : { flags };
1672
+ }
1673
+ /** `text` without `property`, its separating comma and the line it sat on. */
1674
+ function withoutProperty(text, config, property) {
1675
+ const elements = config.properties;
1676
+ const index = elements.indexOf(property);
1677
+ const next = elements[index + 1];
1678
+ const previous = elements[index - 1];
1679
+ if (next) return text.slice(0, property.getFullStart()) + text.slice(next.getFullStart());
1680
+ if (previous) return text.slice(0, previous.end) + text.slice(property.end);
1681
+ return text.slice(0, config.getStart()) + "{}" + text.slice(config.end);
1682
+ }
1683
+ /** The config without its root-only `options`, and the flags that keep the member's own run the same. */
1684
+ function moveOptions(path, text) {
1685
+ const config = exportedConfig(path, text);
1686
+ const options = config?.properties.find((element) => propertyName(element) === "options");
1687
+ if (config === void 0 || options === void 0) return { kind: "none" };
1688
+ if (!typescript().isPropertyAssignment(options)) return {
1689
+ kind: "unsupported",
1690
+ keys: ["options"]
1691
+ };
1692
+ const result = optionFlags(options.initializer);
1693
+ if ("unsupported" in result) return {
1694
+ kind: "unsupported",
1695
+ keys: result.unsupported
1696
+ };
1697
+ return {
1698
+ kind: "moved",
1699
+ text: withoutProperty(text, config, options),
1700
+ flags: result.flags
1701
+ };
1702
+ }
1703
+ /** A shell separator that ends one command of a script. */
1704
+ const COMMAND_END = /&&|\|\||[;|]/;
1705
+ /** `script` with `flags` after each `oxlint` command word, skipping a flag that command already passes. */
1706
+ function withFlags(script, flags) {
1707
+ return script.replace(OXLINT_COMMAND, (match, before, offset) => {
1708
+ const rest = script.slice(offset + match.length);
1709
+ const command = rest.split(COMMAND_END)[0] ?? rest;
1710
+ const missing = flags.filter((flag) => !command.includes(flag.split("=")[0] ?? flag));
1711
+ return missing.length ? `${before}oxlint ${missing.join(" ")}` : match;
1712
+ });
1713
+ }
1714
+ const ALIGNED_TOOLS = [
1715
+ "@antelopejs/tooling-configs",
1716
+ "oxlint",
1717
+ "oxlint-tsgolint",
1718
+ "oxfmt",
1719
+ "knip",
1720
+ "lefthook"
1721
+ ];
1722
+ const CATALOG = "catalog:";
1723
+ /** The scalar keys of the mapping `node` holds, each with its value node, following YAML aliases and `<<` merge keys; a key the mapping sets itself comes after the merged one it overrides. */
1724
+ function mapPairs(document, node, seen = /* @__PURE__ */ new Set()) {
1725
+ const map = isAlias(node) ? node.resolve(document) : node;
1726
+ if (!isMap(map) || seen.has(map)) return [];
1727
+ const within = /* @__PURE__ */ new Set([...seen, map]);
1728
+ const merged = [];
1729
+ const own = [];
1730
+ for (const { key, value } of map.items) {
1731
+ if (!isScalar(key)) continue;
1732
+ if (key.value !== "<<") {
1733
+ own.push([String(key.value), isAlias(value) ? value.resolve(document) : value]);
1734
+ continue;
1735
+ }
1736
+ const merge = isAlias(value) ? value.resolve(document) : value;
1737
+ const sources = isSeq(merge) ? [...merge.items].reverse() : [merge];
1738
+ for (const source of sources) if (isNode(source)) merged.push(...mapPairs(document, source, within));
1739
+ }
1740
+ return [...merged, ...own];
1741
+ }
1742
+ /** The scalar keys of the mapping at `path`, each with its value node. */
1743
+ function mapEntries(document, path) {
1744
+ let pairs = mapPairs(document, document.contents);
1745
+ for (const key of path) {
1746
+ const value = new Map(pairs).get(key);
1747
+ pairs = isNode(value) ? mapPairs(document, value) : [];
1748
+ }
1749
+ return pairs;
1750
+ }
1751
+ /** The package names of the catalog at `path`, each with its range. */
1752
+ function catalogEntries(document, path) {
1753
+ return mapEntries(document, path).flatMap(([name, value]) => isScalar(value) ? [[name, String(value.value)]] : []);
1754
+ }
1755
+ function catalogSource(root) {
1756
+ const pnpm = join(root, "pnpm-workspace.yaml");
1757
+ if (existsSync(pnpm)) return {
1758
+ document: parseDocument(readFileSync(pnpm, "utf8")),
1759
+ prefixes: [[]]
1760
+ };
1761
+ return {
1762
+ document: parseDocument(readFileSync(join(root, "package.json"), "utf8")),
1763
+ prefixes: [["workspaces"], []]
1764
+ };
1765
+ }
1766
+ function workspaceCatalogs(root) {
1767
+ const { document, prefixes } = catalogSource(root);
1768
+ const catalogs = /* @__PURE__ */ new Map();
1769
+ const add = (name, path) => catalogs.set(name, new Map([...catalogs.get(name) ?? [], ...catalogEntries(document, path)]));
1770
+ for (const prefix of prefixes) {
1771
+ add("default", [...prefix, "catalog"]);
1772
+ for (const [name] of mapEntries(document, [...prefix, "catalogs"])) add(name, [
1773
+ ...prefix,
1774
+ "catalogs",
1775
+ name
1776
+ ]);
1777
+ }
1778
+ return catalogs;
1779
+ }
1780
+ /** The range `spec` installs `name` at: `spec` itself, its catalog entry for a `catalog:` spec, or undefined for another protocol or a path. */
1781
+ function resolvedRange(catalogs, name, spec) {
1782
+ if (spec.startsWith(CATALOG)) return catalogs.get(spec.slice(8) || "default")?.get(name);
1783
+ return /[:/]/.test(spec) ? void 0 : spec;
1784
+ }
1785
+ /** The spec of each pack tool at the root: the one it declares, else the one `--init` and sync add. A `catalog:` spec resolves the same in every member; another protocol or a path stays root-only, since a member would resolve it elsewhere. */
1786
+ function rootSpecs(root, versions, catalogs) {
1787
+ const declared = /* @__PURE__ */ new Map([
1788
+ ["@antelopejs/tooling-configs", `^${versions.pack}`],
1789
+ ["oxlint", versions.oxlint],
1790
+ ["oxlint-tsgolint", versions.tsgolint],
1791
+ ["oxfmt", versions.oxfmt],
1792
+ ["knip", versions.knip],
1793
+ ["lefthook", versions.lefthook]
1794
+ ]);
1795
+ for (const field of [root.dependencies, root.devDependencies]) for (const [name, spec] of Object.entries(field ?? {})) if (declared.has(name)) declared.set(name, spec);
1796
+ const specs = /* @__PURE__ */ new Map();
1797
+ for (const [name, spec] of declared) {
1798
+ const range = resolvedRange(catalogs, name, spec);
1799
+ if (range !== void 0) specs.set(name, {
1800
+ spec,
1801
+ range
1802
+ });
1803
+ }
1804
+ return specs;
1805
+ }
1806
+ /** Sets each pack tool the member declares as a plain range to the root's spec, so the workspace installs one copy of the pack, and names each member `catalog:` spec that resolves to another range; returns whether it changed one. */
1807
+ function alignRanges(member, manifestPath, specs, catalogs, failures) {
1808
+ let changed = false;
1809
+ for (const field of [member.dependencies, member.devDependencies]) for (const name of ALIGNED_TOOLS) {
1810
+ const declared = field && Object.hasOwn(field, name) ? field[name] : void 0;
1811
+ const wanted = specs.get(name);
1812
+ if (!field || declared === void 0 || wanted === void 0 || declared === wanted.spec) continue;
1813
+ if (declared.startsWith(CATALOG)) {
1814
+ const range = resolvedRange(catalogs, name, declared);
1815
+ if (range !== void 0 && range !== wanted.range) failures.push(`${manifestPath} declares ${name} as ${declared}, which resolves to ${range}, while the root resolves it to ${wanted.range}, so the workspace would install two copies. Give both the same catalog entry or range, then rerun antelopejs-sync --init.`);
1816
+ continue;
1817
+ }
1818
+ if (declared.includes(":")) continue;
1819
+ field[name] = wanted.spec;
1820
+ changed = true;
1821
+ }
1822
+ return changed;
1823
+ }
1824
+ function alignMember(root, directory, workspace, result) {
1825
+ const manifestPath = join(root, directory, "package.json");
1826
+ const current = readFileSync(manifestPath, "utf8");
1827
+ const member = parseManifest(current);
1828
+ let changed = alignRanges(member, `${directory}/package.json`, workspace.specs, workspace.catalogs, result.failures);
1829
+ for (const name of LINT_CONFIGS) {
1830
+ const relative = `${directory}/${name}`;
1831
+ const path = join(root, relative);
1832
+ if (!existsSync(path)) continue;
1833
+ const move = moveOptions(relative, readFileSync(path, "utf8"));
1834
+ if (move.kind === "unsupported") result.failures.push(`${relative} sets oxlint options that oxlint reads only from the root config and that no command-line flag carries (${move.keys.join(", ")}). Move them to the root config or remove them, then rerun antelopejs-sync --init.`);
1835
+ if (move.kind !== "moved") continue;
1836
+ writeFileSync(path, move.text);
1837
+ result.paths.push(relative);
1838
+ for (const [script, command] of Object.entries(member.scripts ?? {})) {
1839
+ const flagged = withFlags(command, move.flags);
1840
+ if (flagged === command || !member.scripts) continue;
1841
+ member.scripts[script] = flagged;
1842
+ changed = true;
1843
+ }
1844
+ }
1845
+ if (!changed) return;
1846
+ writeFileSync(manifestPath, serializeManifest(member, current));
1847
+ result.paths.push(`${directory}/package.json`);
1848
+ }
1849
+ /**
1850
+ * Prepares each workspace member for the root's lint and install: the pack
1851
+ * tools it declares move to the root's ranges, and the `options` of its oxlint
1852
+ * config, which oxlint accepts only in the root config, move to the same flags
1853
+ * on the member's `oxlint` scripts.
1854
+ */
1855
+ function alignWorkspaceMembers(root, manifest, versions) {
1856
+ const catalogs = workspaceCatalogs(root);
1857
+ const workspace = {
1858
+ specs: rootSpecs(manifest, versions, catalogs),
1859
+ catalogs
1860
+ };
1861
+ const result = {
1862
+ paths: [],
1863
+ failures: []
1864
+ };
1865
+ for (const directory of workspaceDirectories(root)) alignMember(root, directory, workspace, result);
1866
+ return result;
1867
+ }
1868
+ //#endregion
1426
1869
  //#region src/guardrails/init.ts
1427
1870
  /** The `gh` arguments that turn `delete_branch_on_merge` on; `gh` fills `{owner}/{repo}` from the git remote. */
1428
1871
  const ENABLE_ARGS = [
@@ -1480,66 +1923,204 @@ function ensureBranchCleanup(root) {
1480
1923
  reason: failureText(write)
1481
1924
  } : { kind: "enabled" };
1482
1925
  }
1483
- /** Runs the package manager's install quietly; returns its output only when it failed. */
1484
- function install(root, manager) {
1485
- const result = spawnSync(manager, ["install"], {
1926
+ /** Runs pnpm, the only manager the pack's CI installs with, with `args` quietly; returns its output only when it failed. */
1927
+ function run(root, args) {
1928
+ const command = ["pnpm", ...args].join(" ");
1929
+ const result = spawnSync("pnpm", args, {
1486
1930
  cwd: root,
1487
1931
  encoding: "utf8"
1488
1932
  });
1489
- if (result.error) return `${manager} install failed: ${result.error.message}`;
1933
+ if (result.error) return `${command} failed: ${result.error.message}`;
1490
1934
  if (result.status === 0) return void 0;
1491
- return `${manager} install failed (exit ${result.status}).\n${result.stdout}${result.stderr}`.trimEnd();
1935
+ return `${command} failed (exit ${result.status}).\n${result.stdout}${result.stderr}`.trimEnd();
1936
+ }
1937
+ function install(root) {
1938
+ return run(root, ["install"]);
1492
1939
  }
1493
1940
  function resolveOxfmt(root) {
1494
1941
  const require = createRequire(join(root, "package.json"));
1495
1942
  return join(dirname(require.resolve("oxfmt/package.json")), "bin/oxfmt");
1496
1943
  }
1497
- /** Formats `package.json` with the repository's installed oxfmt, which sorts the keys init and sync append out of order; returns its output only when it failed. */
1498
- function formatManifest(root) {
1944
+ /** Formats the repository with its installed oxfmt, as its `format` script does, so `format:check` passes on the keys init and sync append out of order and on source the repository never formatted. */
1945
+ function formatRepository(root) {
1499
1946
  let binary;
1500
1947
  try {
1501
1948
  binary = resolveOxfmt(root);
1502
1949
  } catch {
1503
- return "oxfmt is not installed in this repository, so package.json is not formatted.";
1950
+ return {
1951
+ rewritten: [],
1952
+ failure: "oxfmt is not installed in this repository, so it is not formatted."
1953
+ };
1504
1954
  }
1505
- const result = spawnSync(process.execPath, [
1955
+ const oxfmt = (flags) => spawnSync(process.execPath, [
1506
1956
  binary,
1957
+ ...flags,
1507
1958
  "--no-error-on-unmatched-pattern",
1508
- "package.json"
1959
+ "."
1509
1960
  ], {
1510
1961
  cwd: root,
1511
1962
  encoding: "utf8"
1512
1963
  });
1513
- if (result.error) return `oxfmt failed: ${result.error.message}`;
1514
- if (result.status === 0) return void 0;
1515
- return `oxfmt failed (exit ${result.status}).\n${result.stdout}${result.stderr}`.trimEnd();
1964
+ const rewritten = oxfmt(["--list-different"]).stdout.split("\n").map((line) => line.trim()).filter(Boolean);
1965
+ const result = oxfmt([]);
1966
+ if (result.error) return {
1967
+ rewritten: [],
1968
+ failure: `oxfmt failed: ${result.error.message}`
1969
+ };
1970
+ if (result.status === 0) return {
1971
+ rewritten,
1972
+ failure: void 0
1973
+ };
1974
+ return {
1975
+ rewritten: [],
1976
+ failure: `oxfmt failed (exit ${result.status}).\n${result.stdout}${result.stderr}`.trimEnd()
1977
+ };
1978
+ }
1979
+ /** The tsconfig `--init` writes for a Node repository with none, so the synced `typecheck` checks its JavaScript and TypeScript under Node's module rules. */
1980
+ const NODE_TSCONFIG = `{
1981
+ "compilerOptions": {
1982
+ "target": "ES2024",
1983
+ "module": "NodeNext",
1984
+ "moduleResolution": "NodeNext",
1985
+ "allowJs": true,
1986
+ "checkJs": true,
1987
+ "noEmit": true,
1988
+ "types": ["node"]
1989
+ }
1516
1990
  }
1991
+ `;
1517
1992
  /**
1518
- * Onboards a repository in one run: `node_modules` in `.gitignore`, the pack,
1519
- * oxlint and oxfmt as devDependencies, an install, a full-profile sync, a second
1520
- * install when sync added devDependencies, `package.json` formatted by oxfmt,
1521
- * and `delete_branch_on_merge` on GitHub, which runs whatever the file steps did.
1522
- * Every step is idempotent, so a second run changes nothing.
1993
+ * The other package managers' install state `--init` deletes once pnpm's lockfile replaces it, and whether
1994
+ * `pnpm import` reads the versions it resolved. Yarn's Plug'n'Play loaders go too: left in place, Node resolves every
1995
+ * package through them and misses what pnpm installed.
1523
1996
  */
1524
- function initRepository(root, options = {}) {
1997
+ const FOREIGN_INSTALL_FILES = [
1998
+ {
1999
+ file: "package-lock.json",
2000
+ importable: true
2001
+ },
2002
+ {
2003
+ file: "npm-shrinkwrap.json",
2004
+ importable: true
2005
+ },
2006
+ {
2007
+ file: "yarn.lock",
2008
+ importable: true
2009
+ },
2010
+ {
2011
+ file: ".pnp.cjs",
2012
+ importable: false
2013
+ },
2014
+ {
2015
+ file: ".pnp.loader.mjs",
2016
+ importable: false
2017
+ },
2018
+ {
2019
+ file: "bun.lock",
2020
+ importable: false
2021
+ },
2022
+ {
2023
+ file: "bun.lockb",
2024
+ importable: false
2025
+ }
2026
+ ];
2027
+ const LINK_WORKSPACE_PACKAGES = "link-workspace-packages=true";
2028
+ /**
2029
+ * Lists package.json `workspaces` in a new `pnpm-workspace.yaml`, since pnpm ignores the field, and, when `converting`
2030
+ * another manager's install state, links members declared by version as npm, yarn and bun do, so `pnpm import` locks
2031
+ * every member. `.npmrc` carries the link setting because the pinned pnpm reads no settings from `pnpm-workspace.yaml`
2032
+ * when importing, and an explicit setting there is kept. Returns the files it wrote.
2033
+ */
2034
+ function ensurePnpmWorkspace(root, converting) {
2035
+ const packages = workspacePatterns(root);
2036
+ if (!packages.length) return [];
2037
+ const written = [];
2038
+ const workspace = join(root, "pnpm-workspace.yaml");
2039
+ if (!existsSync(workspace)) {
2040
+ writeFileSync(workspace, stringify({ packages }));
2041
+ written.push("pnpm-workspace.yaml");
2042
+ }
2043
+ const npmrc = join(root, ".npmrc");
2044
+ const current = existsSync(npmrc) ? readFileSync(npmrc, "utf8") : "";
2045
+ if (!converting || /^\s*link-workspace-packages\s*=/m.test(current)) return written;
2046
+ const separator = current === "" || current.endsWith("\n") ? "" : "\n";
2047
+ writeFileSync(npmrc, `${current}${separator}${LINK_WORKSPACE_PACKAGES}\n`);
2048
+ return [...written, ".npmrc"];
2049
+ }
2050
+ /**
2051
+ * The file steps before the first install: `node_modules` ignored, the pnpm version the pack's CI runs pinned when
2052
+ * `packageManager` names no pnpm, the bootstrap devDependencies, a tsconfig for a Node repository without one or its
2053
+ * own `typecheck`, the pack's oxfmt config when there is none, each workspace member on the root's tool ranges with
2054
+ * its oxlint `options` moved to flags, package.json `workspaces` listed for pnpm, and the other managers' lockfiles
2055
+ * deleted once `pnpm import` carried the versions npm's or yarn's resolved into a pnpm lockfile.
2056
+ */
2057
+ function bootstrap(root) {
1525
2058
  const path = join(root, "package.json");
1526
2059
  if (!existsSync(path)) throw new Error("package.json is missing. antelopejs-sync --init needs a repository that already has one.");
1527
2060
  const current = readFileSync(path, "utf8");
1528
2061
  const manifest = parseManifest(current);
1529
- const manager = packageManager(manifest);
2062
+ packageManager(manifest);
2063
+ const versions = toolingVersions();
1530
2064
  const paths = [];
1531
2065
  if (ensureGitignore(root)) paths.push(".gitignore");
1532
- const added = bootstrapDependencies(manifest, toolingVersions());
1533
- if (added.length) {
1534
- writeFileSync(path, withDevDependencies(current, added));
2066
+ const nodeProject = !existsSync(join(root, "tsconfig.json")) && manifest.scripts?.typecheck === void 0 && !usesNuxt(root, manifest);
2067
+ const next = bootstrappedManifest(current, bootstrapDependencies(manifest, versions, nodeProject), versions.packageManager);
2068
+ if (next !== current) {
2069
+ writeFileSync(path, next);
1535
2070
  paths.push("package.json");
1536
2071
  }
1537
- const first = install(root, manager);
2072
+ if (nodeProject) {
2073
+ writeFileSync(join(root, "tsconfig.json"), NODE_TSCONFIG);
2074
+ paths.push("tsconfig.json");
2075
+ }
2076
+ const fmt = PRESET_CONFIGS[1];
2077
+ if (![fmt.path, ...fmt.legacy].some((file) => existsSync(join(root, file)))) {
2078
+ writeFileSync(join(root, fmt.path), presetConfig(void 0, fmt, repositoryTools(manifest)));
2079
+ paths.push(fmt.path);
2080
+ }
2081
+ const members = alignWorkspaceMembers(root, manifest, versions);
2082
+ paths.push(...members.paths);
2083
+ if (members.failures.length) return {
2084
+ paths,
2085
+ removed: [],
2086
+ failure: members.failures.join("\n")
2087
+ };
2088
+ const foreign = FOREIGN_INSTALL_FILES.filter(({ file }) => existsSync(join(root, file)));
2089
+ paths.push(...ensurePnpmWorkspace(root, foreign.length > 0));
2090
+ const imported = foreign.some(({ importable }) => importable) && !existsSync(join(root, "pnpm-lock.yaml")) ? run(root, ["import"]) : void 0;
2091
+ if (imported !== void 0) return {
2092
+ paths,
2093
+ removed: [],
2094
+ failure: imported
2095
+ };
2096
+ for (const { file } of foreign) unlinkSync(join(root, file));
2097
+ return {
2098
+ paths,
2099
+ removed: foreign.map(({ file }) => file),
2100
+ failure: install(root)
2101
+ };
2102
+ }
2103
+ /**
2104
+ * Onboards a repository in one run: the bootstrap file steps and an install, the repository formatted by oxfmt before
2105
+ * sync measures its lint and size baseline, a full-profile sync, a second install when sync added devDependencies, a
2106
+ * second oxfmt pass over what sync wrote, and `delete_branch_on_merge` on GitHub, which runs whatever the file steps
2107
+ * did. Every step is idempotent, so a second run changes nothing.
2108
+ */
2109
+ function initRepository(root, options = {}) {
2110
+ const { paths, removed, failure: installed } = bootstrap(root);
2111
+ const format = () => {
2112
+ const formatted = formatRepository(root);
2113
+ for (const file of formatted.rewritten) if (!paths.includes(file)) paths.push(file);
2114
+ return formatted.failure;
2115
+ };
2116
+ const first = installed ?? (existsSync(join(root, PRESET_CONFIGS[1].path)) ? format() : void 0);
1538
2117
  if (first !== void 0) return {
1539
2118
  paths,
2119
+ removed,
1540
2120
  failure: first,
1541
2121
  sync: void 0,
1542
- branchCleanup: ensureBranchCleanup(root)
2122
+ branchCleanup: ensureBranchCleanup(root),
2123
+ untypedDocs: []
1543
2124
  };
1544
2125
  const sync = syncRepository(root, {
1545
2126
  profile: "full",
@@ -1547,16 +2128,16 @@ function initRepository(root, options = {}) {
1547
2128
  });
1548
2129
  let failure;
1549
2130
  if (!sync.errors.length) {
1550
- failure = sync.dependenciesAdded ? install(root, manager) : void 0;
1551
- const unformatted = readFileSync(path, "utf8");
1552
- failure ??= formatManifest(root);
1553
- if (readFileSync(path, "utf8") !== unformatted && !paths.includes("package.json")) paths.push("package.json");
2131
+ failure = sync.dependenciesAdded ? install(root) : void 0;
2132
+ failure ??= format();
1554
2133
  }
1555
2134
  return {
1556
2135
  paths,
2136
+ removed,
1557
2137
  failure,
1558
2138
  sync,
1559
- branchCleanup: ensureBranchCleanup(root)
2139
+ branchCleanup: ensureBranchCleanup(root),
2140
+ untypedDocs: sync.errors.length ? [] : untypedDocsFiles(root)
1560
2141
  };
1561
2142
  }
1562
2143
  //#endregion
@@ -1576,10 +2157,12 @@ function init(verify) {
1576
2157
  const result = initRepository(repositoryRoot(), { verify });
1577
2158
  const reportedBySync = result.sync && !result.sync.errors.length ? result.sync.paths : [];
1578
2159
  for (const path of result.paths) if (!reportedBySync.includes(path)) process.stdout.write(`Updated: ${path}\n`);
2160
+ for (const path of result.removed) process.stdout.write(`Removed: ${path}\n`);
1579
2161
  const synced = result.sync ? printSync(result.sync, {
1580
2162
  check: false,
1581
2163
  installed: true
1582
2164
  }) : 0;
2165
+ if (result.untypedDocs.length) process.stdout.write(`Note: ${result.untypedDocs.join(", ")} hold TypeScript fences or docs-api pages the docs check typechecks. Set docs-typescript-project in ${CI_PATH} to a tsconfig whose program resolves their imports, or mark illustrative fences \`fragment\`. Without it the check uses the root tsconfig.json and fails when there is none.\n`);
1583
2166
  if (result.failure !== void 0) process.stderr.write(`${result.failure}\n`);
1584
2167
  const failed = synced !== 0 || result.failure !== void 0;
1585
2168
  if (failed) process.stderr.write("Fix the errors above, then rerun antelopejs-sync --init.\n");