@wirecat/cli-base 0.96.0 → 0.98.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 (44) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/dist/commands/document.js +1 -1
  3. package/dist/commands/registry.d.ts +2 -1
  4. package/dist/dev/adopt.d.ts +6 -0
  5. package/dist/dev/adopt.js +43 -0
  6. package/dist/dev/audit.js +2 -2
  7. package/dist/dev/conformance.d.ts +5 -0
  8. package/dist/dev/conformance.js +24 -4
  9. package/dist/dev/family.d.ts +10 -0
  10. package/dist/dev/family.js +41 -0
  11. package/dist/dev/lint.d.ts +8 -0
  12. package/dist/dev/lint.js +34 -7
  13. package/dist/dev/main.js +173 -23
  14. package/dist/dev/network.js +10 -2
  15. package/dist/dev/result-shape.d.ts +19 -0
  16. package/dist/dev/result-shape.js +263 -0
  17. package/dist/http/index.d.ts +23 -2
  18. package/dist/http/index.js +61 -0
  19. package/dist/release/fragments.d.ts +17 -0
  20. package/dist/release/fragments.js +108 -0
  21. package/dist/release/index.d.ts +2 -0
  22. package/dist/release/index.js +2 -0
  23. package/dist/release/level.d.ts +2 -0
  24. package/dist/release/level.js +52 -0
  25. package/dist/standards/audit.d.ts +2 -0
  26. package/dist/standards/audit.js +2 -0
  27. package/dist/standards/flags-account.d.ts +3 -0
  28. package/dist/standards/flags-account.js +36 -0
  29. package/dist/standards/index.d.ts +1 -1
  30. package/dist/standards/lint.d.ts +18 -2
  31. package/dist/standards/lint.js +29 -6
  32. package/dist/standards/output.d.ts +12 -0
  33. package/dist/standards/tables.d.ts +1 -1
  34. package/dist/standards/tables.js +1 -1
  35. package/dist/standards/vocabulary.js +3 -0
  36. package/docs/standards/README.md +1 -1
  37. package/docs/standards/accounts.md +3 -3
  38. package/docs/standards/layout.md +1 -1
  39. package/docs/standards/lifecycle.md +4 -6
  40. package/docs/standards/output.md +42 -2
  41. package/docs/standards/releases.md +6 -4
  42. package/docs/standards/testing.md +1 -1
  43. package/docs/standards/toolchain.md +7 -3
  44. package/package.json +1 -1
package/dist/dev/main.js CHANGED
@@ -13,20 +13,23 @@ import * as v from "valibot";
13
13
  import { parseCommandsDocument } from "../commands/document.js";
14
14
  import { describeProgram } from "../commands/registry.js";
15
15
  import { taggedSection } from "../release/fold.js";
16
- import { changelogProblems, docsProblems, JOURNAL_IDS, markdownFiles, packageVersion, structureProblems, versionScript, } from "../release/index.js";
16
+ import { CHANGELOG_HEADINGS, changelogProblems, collectFragments, docsProblems, fragmentProblems, JOURNAL_IDS, levelledVersion, markdownFiles, packageVersion, readFragments, structureProblems, versionLevelProblem, versionScript, } from "../release/index.js";
17
17
  import { AUDIT_BLOCKS, defineParityGroups, PARITY_GROUPS, REQUIRED_ROOTS } from "../standards/audit.js";
18
18
  import { defineReasons } from "../standards/errors.js";
19
- import { baselineProblems, baselineSchema, LINT_RULES, OVERRIDE_BUDGET, OVERRIDE_RULE_REVIEW, overrideSchema, overridesProblems, rulesForReview, } from "../standards/lint.js";
19
+ import { baselineProblems, baselineSchema, LINT_RULES, OVERRIDE_BUDGET, OVERRIDE_RULE_REVIEW, overdue, overrideSchema, overridesDueSoon, overridesProblems, rulesForReview, } from "../standards/lint.js";
20
20
  import { issuesOf, RegistryError } from "../standards/registry.js";
21
21
  import { VOCABULARY } from "../standards/vocabulary.js";
22
22
  import { buildManifest, MANIFEST_FILE, ManifestError, manifestText } from "../wcat/manifest.js";
23
+ import { adopt } from "./adopt.js";
23
24
  import { auditClis, scorecardTable, snakeKeys } from "./audit.js";
24
25
  import { readCapabilities } from "./capabilities.js";
25
26
  import { CONFORMANCE_USAGE, conformanceCommand } from "./conformance.js";
27
+ import { familyPackages, installFamily } from "./family.js";
26
28
  import { changelogChange, landChange, landFold, newestTag, processShell, restoreChange } from "./land.js";
27
- import { baselineOf, judge, lintCommands, RUN_LOG_COMMANDS, walk } from "./lint.js";
29
+ import { baselineOf, judge, lintCommands, misfiled, RUN_LOG_COMMANDS, walk } from "./lint.js";
28
30
  import { readSources } from "./network.js";
29
31
  import { nextVersion } from "./next-version.js";
32
+ import { readDeclarations } from "./result-shape.js";
30
33
  import { slowTests } from "./slow-tests.js";
31
34
  import { matrixPage, matrixRows, parseArgvLog } from "./test-matrix.js";
32
35
  import { binNameWarnings, describeWarnings, hostsWarnings, WCAT_RULES } from "./wcat-lint.js";
@@ -48,6 +51,17 @@ const USAGE = `usage: cli-dev <command> [options]
48
51
  the tag; an entry the tag lacks missed that release and moves
49
52
  to the unreleased section. Prints a line when it changed the
50
53
  file. --land lands it on main through a pull request
54
+ adopt <x.y.z> [--package <name>] moves the CLI onto that version of a shared package
55
+ (@wirecat/cli-core): the pin in package.json, pnpm install,
56
+ then pnpm generate and ci:quick when the CLI has them
57
+ changelog fragments [--collect <x.y.z>] [--ids <A,B>] [--file <path>]
58
+ checks the changes/<branch>.md fragments (### headings of the
59
+ changelog, no journal ids); --collect adds them under that
60
+ version's section and deletes them
61
+ changelog level [--next <x.y.z>] [--file <path>]
62
+ fails when the top section's version is a lower level than its
63
+ headings need (Added: minor; a break: major, minor before
64
+ 1.0.0); --next prints the version a release of x.y.z needs
51
65
  docs-check [--rules <module>] [--ids <A,B>] [--pages]
52
66
  links, anchors and the changelog's shape; --pages also
53
67
  docs/ against docs/meta.json, the docs portal's structure
@@ -67,7 +81,7 @@ const USAGE = `usage: cli-dev <command> [options]
67
81
  is a JSON object of the CLI's own JSON Schemas by name
68
82
  audit (--cli <bin> | --commands <file>)... [--schemas <cli>=<file>]... [--reasons <cli>=<file>]...
69
83
  [--lint <cli>=<dir>]... [--capabilities <file>] [--complete] [--groups <file>] [--differences <file>]
70
- [--baseline <dir>] [--for <cli>] [--json] [--write-baseline]
84
+ [--baseline <dir>] [--for <cli>] [--json] [--write-baseline] [--family]
71
85
  several CLIs against every lint rule and against each other:
72
86
  required roots, same path same contract, same flag same
73
87
  meaning, same entity same schema, same failure same reason.
@@ -76,7 +90,12 @@ const USAGE = `usage: cli-dev <command> [options]
76
90
  rules by its own lint/ folder; the rest by --baseline
77
91
  (audit/baseline). --groups replaces PARITY_GROUPS with the
78
92
  JSON list of parity groups in that file; --differences adds
79
- to the groups in use
93
+ to the groups in use. --family takes this CLI's one --cli and
94
+ installs the latest published CLIs of the parity groups beside
95
+ it (npm, without install scripts), runs each in an empty home,
96
+ reads every CLI's commands info (so same-error-reason and
97
+ same-entity-schema are measured), and defaults --for to this
98
+ CLI, --lint to its lint/ and --groups to config/parity-groups.json
80
99
  bundle --bin <dist/bin/name.js> [--external <package>]... [--anchor <package>]... [--harmless <path>]...
81
100
  bundles the compiled bin with esbuild (a devDependency) into
82
101
  dist/bundle/ and turns the bin into its loader. --external keeps
@@ -124,10 +143,53 @@ const docsCheck = async (args, io) => {
124
143
  ...(values.pages ? structureProblems(root) : []),
125
144
  ], "docs: ok");
126
145
  };
146
+ /** `changes/<branch>.md` fragments: checked, or collected into `--collect <version>`'s section and deleted. */
147
+ const fragments = (args, io) => {
148
+ const { values } = parseArgs({
149
+ args,
150
+ options: {
151
+ collect: { type: "string" },
152
+ ids: { type: "string" },
153
+ file: { type: "string", default: "CHANGELOG.md" },
154
+ },
155
+ });
156
+ const rules = {
157
+ headings: CHANGELOG_HEADINGS,
158
+ ids: [...JOURNAL_IDS, ...(values.ids?.split(",").filter(Boolean) ?? [])],
159
+ };
160
+ const found = readFragments(io.cwd);
161
+ const problems = found.flatMap((fragment) => fragmentProblems(fragment, rules));
162
+ if (problems.length > 0 || !values.collect || found.length === 0)
163
+ return report(io, problems, `changes/: ${found.length} fragments, all well formed`);
164
+ const file = isAbsolute(values.file) ? values.file : join(io.cwd, values.file);
165
+ writeFileSync(file, collectFragments(readFileSync(file, "utf8"), values.collect, found, rules));
166
+ for (const fragment of found)
167
+ rmSync(join(io.cwd, "changes", fragment.name));
168
+ io.out(`collected ${found.length} changelog fragments into ${values.collect}`);
169
+ return 0;
170
+ };
171
+ /** The top section's version level: with `--next <x.y.z>`, the version it needs; without, whether it has it. */
172
+ const level = (args, io) => {
173
+ const { values } = parseArgs({
174
+ args,
175
+ options: { next: { type: "string" }, file: { type: "string", default: "CHANGELOG.md" } },
176
+ });
177
+ const text = readFileSync(isAbsolute(values.file) ? values.file : join(io.cwd, values.file), "utf8");
178
+ if (values.next) {
179
+ io.out(levelledVersion(text, values.next));
180
+ return 0;
181
+ }
182
+ const problem = versionLevelProblem(text);
183
+ return report(io, problem ? [problem] : [], `${values.file}: the top section's version fits its headings`);
184
+ };
127
185
  const changelog = (args, io) => {
128
186
  const [action, ...rest] = args;
187
+ if (action === "fragments")
188
+ return fragments(rest, io);
189
+ if (action === "level")
190
+ return level(rest, io);
129
191
  if (action !== "fold" && action !== "restore") {
130
- io.err(`cli-dev changelog: no action "${action ?? ""}" — the ones there are: fold, restore`);
192
+ io.err(`cli-dev changelog: no action "${action ?? ""}" — the ones there are: fold, restore, fragments, level`);
131
193
  return 2;
132
194
  }
133
195
  const { values } = parseArgs({
@@ -294,16 +356,18 @@ const readJson = (path) => {
294
356
  throw new Error(`${path}: ${error.message}`);
295
357
  }
296
358
  };
297
- const commandsJson = (io, cli, file, commandArgs = ["commands", "--json"]) => {
359
+ const commandsJson = (io, cli, file, commandArgs = ["commands", "--json"], isolated = false) => {
298
360
  if (file)
299
361
  return readJson(isAbsolute(file) ? file : join(io.cwd, file));
300
362
  const bin = cli ?? "";
301
363
  const script = /\.[cm]?js$/.test(bin);
302
- const run = spawn.sync(script ? process.execPath : bin, [...(script ? [bin] : []), ...commandArgs], {
303
- cwd: io.cwd,
304
- encoding: "utf8",
305
- maxBuffer: 64 * 1024 * 1024,
306
- });
364
+ const run = isolated
365
+ ? inEmptyHome(io.cwd, bin, process.env, (call) => call(commandArgs))
366
+ : spawn.sync(script ? process.execPath : bin, [...(script ? [bin] : []), ...commandArgs], {
367
+ cwd: io.cwd,
368
+ encoding: "utf8",
369
+ maxBuffer: 64 * 1024 * 1024,
370
+ });
307
371
  if (run.error || run.status !== 0)
308
372
  throw new Error(`${bin} commands --json failed: ${run.error?.message ?? String(run.stderr).trim().split("\n")[0]}`);
309
373
  return JSON.parse(String(run.stdout));
@@ -341,6 +405,8 @@ export const inEmptyHome = (cwd, bin, environment, body) => {
341
405
  APPDATA: join(home, "AppData", "Roaming"),
342
406
  LOCALAPPDATA: join(home, "AppData", "Local"),
343
407
  CI: "true",
408
+ // An empty HOME does not hide the keyring: D-Bus reaches it all the same.
409
+ DBUS_SESSION_BUS_ADDRESS: "disabled:",
344
410
  ...(environment.SystemRoot ? { SystemRoot: environment.SystemRoot } : {}),
345
411
  };
346
412
  const script = /\.[cm]?js$/.test(bin);
@@ -349,7 +415,7 @@ export const inEmptyHome = (cwd, bin, environment, body) => {
349
415
  env,
350
416
  encoding: "utf8",
351
417
  timeout: 60_000,
352
- maxBuffer: 16 * 1024 * 1024,
418
+ maxBuffer: 64 * 1024 * 1024,
353
419
  });
354
420
  try {
355
421
  return body(call);
@@ -458,11 +524,13 @@ const lintRun = (args, io) => {
458
524
  }
459
525
  const paths = new Set(walk(parsed.document.commands).map((command) => command.path.join(" ")));
460
526
  const hasRuns = RUN_LOG_COMMANDS.every((path) => paths.has(path));
527
+ const declarations = readDeclarations(io.cwd);
461
528
  const violations = lintCommands(parsed.document, VOCABULARY, LINT_RULES, {
462
529
  raw,
463
530
  schemas: schemas,
464
531
  ...(values.cli && hasRuns ? { runLog: probeRunLog(io.cwd, values.cli) } : {}),
465
532
  network: networkContext(io.cwd),
533
+ declarations,
466
534
  });
467
535
  const severity = new Map(LINT_RULES.map((rule) => [rule.id, rule.severity]));
468
536
  if (values["write-baseline"]) {
@@ -477,13 +545,22 @@ const lintRun = (args, io) => {
477
545
  }
478
546
  }
479
547
  const verdict = judge(violations, baseline, ruleOverrides, budget);
548
+ // A low rule is advice: it is printed and never fails, so polishing help text never holds a merge.
549
+ const advice = (rule) => severity.get(rule) === "low";
550
+ const advised = [];
480
551
  for (const id of verdict.unknownRules)
481
552
  problems.push(`no lint rule "${id}" (named in ${values.baseline} or ${values.overrides})`);
482
553
  for (const found of verdict.fresh)
483
- problems.push(`${severity.get(found.rule) ?? "?"} ${found.rule} ${found.target}: ${found.message}`);
484
- const stale = verdict.stale.map((entry) => entry.in === "baseline"
554
+ (advice(found.rule) ? advised : problems).push(`${severity.get(found.rule) ?? "?"} ${found.rule} ${found.target}: ${found.message}`);
555
+ const staleLine = (entry) => entry.in === "baseline"
485
556
  ? `stale baseline entry, fixed or overridden — remove it: ${values.baseline}/${entry.rule}.json "${entry.target}"`
486
- : `stale override, no such violation — remove it: ${entry.rule} "${entry.target}"`);
557
+ : `stale override, no such violation — remove it: ${entry.rule} "${entry.target}"`;
558
+ const stale = verdict.stale.filter((entry) => !advice(entry.rule)).map(staleLine);
559
+ advised.push(...verdict.stale.filter((entry) => advice(entry.rule)).map(staleLine));
560
+ advised.push(...overridesDueSoon(overrides, today(io)).map((line) => `${values.overrides}: ${line}`));
561
+ // Like a stale entry, a misfiled one is the CLI's cleanup when a shared package's CI lints it.
562
+ for (const line of misfiled(parsed.document, baseline, ruleOverrides))
563
+ stale.push(line);
487
564
  if (!values["allow-stale"])
488
565
  problems.push(...stale);
489
566
  const warnings = wcatWarnings(io.cwd, values.cli);
@@ -502,8 +579,14 @@ const lintRun = (args, io) => {
502
579
  if (values["allow-stale"])
503
580
  for (const line of stale)
504
581
  io.err(`warning ${line}`);
582
+ for (const line of advised)
583
+ io.err(`warning ${line}`);
505
584
  if (!existsSync(join(io.cwd, MANIFEST_FILE)))
506
585
  io.err(`undeclared-host: skipped, no ${MANIFEST_FILE}`);
586
+ if (declarations.files.length === 0)
587
+ io.err(declarations.missing.length === 0
588
+ ? "result-shape: skipped, package.json publishes no types"
589
+ : "result-shape: skipped, the types package.json publishes are not built");
507
590
  return report(io, problems, "lint: ok");
508
591
  };
509
592
  const shippedManifest = (cwd) => {
@@ -540,14 +623,54 @@ const byCli = (pairs, flag) => new Map((pairs ?? []).map((pair) => {
540
623
  }));
541
624
  const audit = (args, io) => {
542
625
  try {
543
- return auditRun(args, io);
626
+ return args.includes("--family") ? auditFamily(args, io) : auditRun(args, io);
544
627
  }
545
628
  catch (error) {
546
629
  io.err(error.message);
547
630
  return 2;
548
631
  }
549
632
  };
550
- const auditRun = (args, io) => {
633
+ /** The built CLI against the latest published one of every other CLI in the parity groups, as `scripts/audit.sh` did. */
634
+ const auditFamily = (args, io) => {
635
+ const { values } = parseArgs({
636
+ args,
637
+ strict: false,
638
+ options: {
639
+ cli: { type: "string", multiple: true },
640
+ commands: { type: "string", multiple: true },
641
+ groups: { type: "string" },
642
+ for: { type: "string" },
643
+ lint: { type: "string", multiple: true },
644
+ },
645
+ });
646
+ const [own, ...more] = (values.cli ?? []);
647
+ if (!own || more.length > 0 || values.commands) {
648
+ io.err("audit --family takes one --cli: this CLI's built bin");
649
+ return 2;
650
+ }
651
+ const name = commandsJson(io, own, undefined, undefined, true).cli;
652
+ if (typeof name !== "string")
653
+ throw new Error(`${own} commands --json names no cli`);
654
+ const local = (path) => (existsSync(join(io.cwd, path)) ? path : undefined);
655
+ const groupsFile = values.groups ?? local("config/parity-groups.json");
656
+ const groups = groupsFile ? defineParityGroups(readJson(join(io.cwd, groupsFile))) : PARITY_GROUPS;
657
+ const lintDir = values.lint ? undefined : local("lint");
658
+ const family = installFamily(familyPackages(groups, name));
659
+ try {
660
+ return auditRun([
661
+ ...args.filter((arg) => arg !== "--family"),
662
+ ...[...family.bins.values()].flatMap((bin) => ["--cli", bin]),
663
+ ...(values.for ? [] : ["--for", name]),
664
+ ...(values.groups || !groupsFile ? [] : ["--groups", groupsFile]),
665
+ ...(lintDir ? ["--lint", `${name}=${lintDir}`] : []),
666
+ ], io, true);
667
+ }
668
+ finally {
669
+ family.close();
670
+ }
671
+ };
672
+ const FAMILY_REPORTS = new Set(["same-entity-schema", "same-error-reason"]);
673
+ const auditRun = (args, io, family = false) => {
551
674
  const started = Date.now();
552
675
  const { values } = parseArgs({
553
676
  args,
@@ -568,7 +691,7 @@ const auditRun = (args, io) => {
568
691
  },
569
692
  });
570
693
  const raws = [
571
- ...(values.cli ?? []).map((bin) => commandsJson(io, bin, undefined)),
694
+ ...(values.cli ?? []).map((bin) => commandsJson(io, bin, undefined, undefined, family)),
572
695
  ...(values.commands ?? []).map((file) => commandsJson(io, undefined, file)),
573
696
  ];
574
697
  if (raws.length < 2) {
@@ -581,10 +704,11 @@ const auditRun = (args, io) => {
581
704
  const lintDirs = byCli(values.lint, "--lint");
582
705
  const problems = [];
583
706
  const evidence = new Map();
584
- if (values.complete) {
707
+ // The family audit reads every CLI's reasons and schemas, so same-error-reason and same-entity-schema are measured.
708
+ if (values.complete || family) {
585
709
  for (const [index, bin] of (values.cli ?? []).entries()) {
586
710
  const raw = raws[index];
587
- const data = commandsJson(io, bin, undefined, ["commands", "info", "--json"]);
711
+ const data = commandsJson(io, bin, undefined, ["commands", "info", "--json"], family);
588
712
  if (typeof raw.cli === "string")
589
713
  evidence.set(raw.cli, data);
590
714
  }
@@ -595,6 +719,8 @@ const auditRun = (args, io) => {
595
719
  throw new Error(`a commands document is not the shape cli-base's commandsDocument() writes: ${parsed.problems[0]}`);
596
720
  const cli = parsed.document.cli;
597
721
  const input = { document: parsed.document, raw, ...evidence.get(cli) };
722
+ if (family && input.reasons)
723
+ input.reasons = defineReasons(input.reasons);
598
724
  const schemaFile = schemas.get(cli);
599
725
  if (schemaFile)
600
726
  input.schemas = readJson(at(schemaFile));
@@ -680,6 +806,7 @@ const auditRun = (args, io) => {
680
806
  absent: v.optional(v.string()),
681
807
  only: v.optional(v.string()),
682
808
  reason: v.string(),
809
+ review_after: v.optional(v.string()),
683
810
  }));
684
811
  const parsed = v.safeParse(schema, readJson(at(values.differences)));
685
812
  if (!parsed.success)
@@ -695,6 +822,11 @@ const auditRun = (args, io) => {
695
822
  ],
696
823
  })));
697
824
  }
825
+ const differences = groups.flatMap((group) => group.differences);
826
+ for (const line of overdue(differences, today(io)))
827
+ problems.push(`parity difference: ${line}`);
828
+ for (const line of overridesDueSoon(differences, today(io), "the audit"))
829
+ io.err(`warning parity difference: ${line}`);
698
830
  const result = auditClis(inputs, {
699
831
  ...(values.capabilities ? { capabilities: readCapabilities(readJson(at(values.capabilities))) } : {}),
700
832
  groups,
@@ -727,8 +859,16 @@ const auditRun = (args, io) => {
727
859
  }));
728
860
  else
729
861
  io.out(scorecardTable(result.rows));
730
- for (const finding of result.blocking)
731
- problems.push(`new ${finding.rule} ${finding.target}: ${finding.message}`);
862
+ for (const finding of result.blocking) {
863
+ const line = `new ${finding.rule} ${finding.target}: ${finding.message}`;
864
+ // Measured for the first time by the family audit, and strict, so no baseline can hold them: shown, not failed.
865
+ if (family && FAMILY_REPORTS.has(finding.rule))
866
+ io.err(`warning ${line}`);
867
+ else
868
+ problems.push(line);
869
+ }
870
+ if (values.for === undefined && result.rows.some((row) => row.fixed > 0))
871
+ io.err(`warning ${values.baseline} holds rows no CLI has any more (the "fixed" column): remove them with --write-baseline`);
732
872
  io.err(`audit: ${inputs.length} CLIs, ${result.findings.length} findings, ${result.blocking.length} new that block${AUDIT_BLOCKS === "never" ? " (cross-CLI divergences do not block)" : ""}`);
733
873
  for (const problem of problems)
734
874
  io.err(problem);
@@ -820,6 +960,16 @@ export const main = async (argv, io) => {
820
960
  return audit(args, io);
821
961
  case "bundle":
822
962
  return bundleCommand(args, io);
963
+ case "adopt": {
964
+ const { values, positionals } = parseArgs({
965
+ args,
966
+ allowPositionals: true,
967
+ options: { package: { type: "string", default: "@wirecat/cli-core" } },
968
+ });
969
+ const [version = ""] = positionals;
970
+ const run = (command, commandArgs) => spawn.sync(command, [...commandArgs], { cwd: io.cwd, stdio: "inherit" }).status ?? 1;
971
+ return adopt(io.cwd, values.package, version, run, io.err);
972
+ }
823
973
  case "help":
824
974
  case "--help":
825
975
  case "-h":
@@ -48,8 +48,16 @@ const opensNothing = (module, clause) => {
48
48
  .filter((binding) => binding !== "" && !binding.startsWith("type "))
49
49
  .every((binding) => allowed.has(binding.split(/\s+as\s+/)[0]));
50
50
  };
51
- // A file that binds its own `fetch` (an injected FetchLike, `const fetch = hostFetch(…)`) calls that one.
52
- const BINDS_FETCH = /\b(?:const|let|var|function)\s+fetch\b|[{,(]\s*fetch\s*[,}):=]/;
51
+ // A file that binds its own `fetch` (an injected FetchLike, `const fetch = hostFetch(…)`) calls that one. Only a
52
+ // declaration binds it: a typed or defaulted parameter, a destructuring pattern, an arrow's own parameter. An object
53
+ // key (`{ fetch: deps.fetch ?? fetch }`) or an argument (`call(fetch)`) hands the global on and binds nothing.
54
+ const BINDS_FETCH = new RegExp([
55
+ String.raw `\b(?:const|let|var|function)\s+fetch\b`,
56
+ String.raw `[(,]\s*fetch\s*\??\s*:\s*(?:typeof\b|[A-Z(])`,
57
+ String.raw `[(,]\s*fetch\s*=(?![=>])`,
58
+ String.raw `\{[^{}]*(?<![\w$.:]\s*)\bfetch\b(?!\s*:)[^{}]*\}\s*(?::|=(?![=>]))`,
59
+ String.raw `(?:\(\s*fetch\s*\)|\bfetch)\s*=>`,
60
+ ].join("|"));
53
61
  const GLOBAL_FETCH = /(?<!\btypeof\s+)\b(?:globalThis|window|self)\s*\.\s*fetch\b/;
54
62
  // A call, or a value handed on to be called later (`options.fetch ?? fetch`); a key (`fetch:`) or a type reaches nothing.
55
63
  const GLOBAL_FETCH_USE = /(?<![\w$.#]|\btypeof\s+)fetch\b(?![\w$]|\s*\??\s*:)/;
@@ -0,0 +1,19 @@
1
+ import type { SourceFile } from "./network.js";
2
+ /** The `.d.ts` files a package publishes, followed from its `exports`; `missing` are declared but not built. */
3
+ export interface Declarations {
4
+ files: readonly SourceFile[];
5
+ missing: readonly string[];
6
+ }
7
+ /** Every declaration file reachable from the package's `types` entries, by their relative imports. */
8
+ export declare const readDeclarations: (cwd: string) => Declarations;
9
+ export interface ShapeFinding {
10
+ target: string;
11
+ message: string;
12
+ }
13
+ /**
14
+ * Findings in one declaration file; targets name the declaration, `AttachmentsService.list`. `pagingTypes` gains the
15
+ * file's own types that declare a limit or an offset.
16
+ */
17
+ export declare const shapeFindings: (text: string, pagingTypes?: Set<string>) => ShapeFinding[];
18
+ /** Nothing built at all is a skip the lint reports, not a violation: a test run that did not build reads no types. */
19
+ export declare const resultShape: ({ files, missing }: Declarations) => ShapeFinding[];
@@ -0,0 +1,263 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { dirname, join, relative } from "node:path";
3
+ const typesIn = (value, key) => {
4
+ if (typeof value === "string")
5
+ return key === "types" || key === "typings" ? [value] : [];
6
+ if (Array.isArray(value))
7
+ return value.flatMap((one) => typesIn(one));
8
+ if (typeof value === "object" && value !== null)
9
+ return Object.entries(value).flatMap(([at, one]) => typesIn(one, at));
10
+ return [];
11
+ };
12
+ const RELATIVE_MODULE = /(?:\bfrom\s*|\bimport\s*\(\s*)["'](\.{1,2}\/[^"']+)["']/g;
13
+ const declarationOf = (dir, specifier) => {
14
+ const base = join(dir, specifier);
15
+ const candidates = /\.[cm]?js$/.test(base)
16
+ ? [base.replace(/\.(c|m)?js$/, ".d.$1ts")]
17
+ : [`${base}.d.ts`, join(base, "index.d.ts")];
18
+ return candidates.find((path) => existsSync(path));
19
+ };
20
+ /** Every declaration file reachable from the package's `types` entries, by their relative imports. */
21
+ export const readDeclarations = (cwd) => {
22
+ const manifest = join(cwd, "package.json");
23
+ if (!existsSync(manifest))
24
+ return { files: [], missing: [] };
25
+ const pkg = JSON.parse(readFileSync(manifest, "utf8"));
26
+ const entries = [
27
+ ...new Set(typesIn({ types: pkg.types, typings: pkg.typings, exports: pkg.exports }).filter((path) => !path.includes("*"))),
28
+ ];
29
+ const missing = entries.filter((path) => !existsSync(join(cwd, path)));
30
+ const read = new Map();
31
+ const queue = entries.map((path) => join(cwd, path)).filter((path) => existsSync(path));
32
+ for (let file = queue.shift(); file !== undefined; file = queue.shift()) {
33
+ if (read.has(file))
34
+ continue;
35
+ const text = readFileSync(file, "utf8");
36
+ read.set(file, text);
37
+ for (const [, specifier] of text.matchAll(RELATIVE_MODULE)) {
38
+ const next = declarationOf(dirname(file), specifier);
39
+ if (next !== undefined && !read.has(next))
40
+ queue.push(next);
41
+ }
42
+ }
43
+ const files = [...read]
44
+ .map(([path, text]) => ({ path: relative(cwd, path).split("\\").join("/"), text }))
45
+ .sort((a, b) => (a.path < b.path ? -1 : 1));
46
+ return { files, missing };
47
+ };
48
+ const STRINGS_AND_COMMENTS = /\/\/[^\n]*|\/\*[\s\S]*?\*\/|"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`/g;
49
+ const OPEN = "([{<";
50
+ const CLOSE = ")]}>";
51
+ /** Brackets of every kind count, and the `>` of `=>` closes nothing. */
52
+ const depthStep = (text, at) => {
53
+ const char = text[at];
54
+ if (char === ">" && text[at - 1] === "=")
55
+ return 0;
56
+ return OPEN.includes(char) ? 1 : CLOSE.includes(char) ? -1 : 0;
57
+ };
58
+ /** The index just past the bracket that closes the one at `from`. */
59
+ const closing = (text, from) => {
60
+ let depth = 0;
61
+ for (let at = from; at < text.length; at += 1) {
62
+ depth += depthStep(text, at);
63
+ if (depth === 0)
64
+ return at + 1;
65
+ }
66
+ return text.length;
67
+ };
68
+ const splitTop = (text, separators) => {
69
+ const parts = [];
70
+ let depth = 0;
71
+ let start = 0;
72
+ for (let at = 0; at < text.length; at += 1) {
73
+ depth += depthStep(text, at);
74
+ if (depth === 0 && separators.includes(text[at])) {
75
+ parts.push(text.slice(start, at));
76
+ start = at + 1;
77
+ }
78
+ }
79
+ return [...parts, text.slice(start)].map((part) => part.trim()).filter((part) => part !== "");
80
+ };
81
+ const objectsIn = (type) => {
82
+ const found = [];
83
+ for (let at = 0; at < type.length; at += 1)
84
+ if (type[at] === "{") {
85
+ const end = closing(type, at);
86
+ found.push(type.slice(at + 1, end - 1));
87
+ at = end - 1;
88
+ }
89
+ return found;
90
+ };
91
+ const skipGenerics = (text) => (text.startsWith("<") ? text.slice(closing(text, 0)).trimStart() : text);
92
+ /** `(a: A) => R` as its parameters and `R`; undefined for any other type. */
93
+ const arrowOf = (type) => {
94
+ const rest = skipGenerics(type);
95
+ if (!rest.startsWith("("))
96
+ return undefined;
97
+ const end = closing(rest, 0);
98
+ const after = rest.slice(end).trimStart();
99
+ return after.startsWith("=>") ? { params: rest.slice(1, end - 1), returns: after.slice(2).trim() } : undefined;
100
+ };
101
+ const memberOf = (raw) => {
102
+ const text = raw.replace(/^(?:(?:readonly|static|public|protected|private|abstract|declare|get|set)\s+)+/, "");
103
+ const name = text.match(/^[\w$]+\??/)?.[0];
104
+ if (name === undefined)
105
+ return undefined;
106
+ const rest = skipGenerics(text.slice(name.length).trimStart());
107
+ const bare = name.replace(/\?$/, "");
108
+ if (rest.startsWith("(")) {
109
+ const end = closing(rest, 0);
110
+ return { name: bare, params: rest.slice(1, end - 1), type: rest.slice(end).trim().replace(/^:/, "").trim() };
111
+ }
112
+ if (!rest.startsWith(":"))
113
+ return undefined;
114
+ const type = rest.slice(1).trim();
115
+ const arrow = arrowOf(type);
116
+ return arrow ? { name: bare, params: arrow.params, type: arrow.returns } : { name: bare, type };
117
+ };
118
+ const unwrapPromise = (type) => {
119
+ const inner = type.match(/^Promise\s*</);
120
+ return inner && closing(type, inner[0].length - 1) === type.length ? type.slice(inner[0].length, -1).trim() : type;
121
+ };
122
+ const isArray = (type) => {
123
+ const bare = type.trim().replace(/^readonly\s+/, "");
124
+ if (splitTop(bare, "|&").length !== 1)
125
+ return false;
126
+ if (/^(?:Readonly)?Array\s*</.test(bare))
127
+ return closing(bare, bare.indexOf("<")) === bare.length;
128
+ return bare.endsWith("[]");
129
+ };
130
+ const LISTY_NAME = /^(?:list|search|find)(?:[A-Z]|$)|[a-z](?:List|Search)$/;
131
+ const PAGE_NUMBER = /\bpage\??\s*:\s*number\b/;
132
+ /** A list or search that takes a limit, an offset or a page pages; one that takes none may return everything. */
133
+ const isPaged = ({ name, params = "" }, pagingTypes) => LISTY_NAME.test(name) &&
134
+ (/\b(?:limit|offset|page)\b/.test(params) || [...params.matchAll(/[\w$]+/g)].some(([word]) => pagingTypes.has(word)));
135
+ const PAGING_KEYS = new Set([
136
+ "hasMore",
137
+ "has_more",
138
+ "limit_reached",
139
+ "limitReached",
140
+ "nextOffset",
141
+ "next_offset",
142
+ "nextPage",
143
+ "next_page",
144
+ ]);
145
+ /** A declaration or member named like a page of a list or a search. */
146
+ const RESULT_NAME = /^(?:list|search|history)(?:[A-Z]|$)|(?:Found|Page|Results?|List|Hits)$/;
147
+ const renameOf = ({ name, type }) => {
148
+ if (name === "has_more" || name === "limit_reached" || name === "limitReached")
149
+ return "hasMore";
150
+ if (name === "next_offset")
151
+ return "nextOffset";
152
+ if (name === "nextPage" || name === "next_page")
153
+ return /\bstring\b/.test(type) ? "nextCursor" : "nextOffset";
154
+ return undefined;
155
+ };
156
+ /** `inherits`: an interface that extends another may get `items` and `hasMore` from it. */
157
+ const pageFixes = (members, label, inherits) => {
158
+ const props = members.filter((member) => member.params === undefined);
159
+ const names = new Set(props.map((member) => member.name));
160
+ const lists = props.filter((member) => isArray(member.type));
161
+ const paged = lists.length > 0 && props.some((member) => PAGING_KEYS.has(member.name));
162
+ if (!paged || !RESULT_NAME.test(label.split(".").at(-1) ?? ""))
163
+ return [];
164
+ return [
165
+ ...(names.has("items") || inherits
166
+ ? []
167
+ : [`name the rows \`items\` (now ${lists.map((member) => member.name).join(", ")})`]),
168
+ ...props.flatMap((member) => {
169
+ const now = renameOf(member);
170
+ return now ? [`rename \`${member.name}\` to \`${now}\``] : [];
171
+ }),
172
+ ...([...names].some((name) => renameOf({ name, type: "" }) === "hasMore") || names.has("hasMore") || inherits
173
+ ? []
174
+ : ["add `hasMore`"]),
175
+ ];
176
+ };
177
+ const STANDARD = "return ListResult<T> from @wirecat/cli-base/standards (WC-OUT-25)";
178
+ const visitObject = (body, label, scan, inherits = false) => {
179
+ const members = splitTop(body, ";,").flatMap((raw) => memberOf(raw) ?? []);
180
+ if (!label.includes(".") && members.some(({ name }) => name === "limit" || name === "offset"))
181
+ scan.pagingTypes.add(label);
182
+ const fixes = pageFixes(members, label, inherits);
183
+ if (fixes.length > 0)
184
+ scan.found.push({ target: label, message: `${fixes.join("; ")}: ${STANDARD}` });
185
+ for (const member of members)
186
+ visitMember(member, `${label}.${member.name}`, scan);
187
+ };
188
+ const visitMember = (member, label, scan) => {
189
+ if (member.params !== undefined && isPaged(member, scan.pagingTypes)) {
190
+ const fixes = [
191
+ ...(isArray(unwrapPromise(member.type)) ? ["returns a bare array"] : []),
192
+ ...(PAGE_NUMBER.test(member.params) ? ["takes a page number; take `offset` and `limit`"] : []),
193
+ ];
194
+ if (fixes.length > 0)
195
+ scan.found.push({ target: label, message: `${fixes.join("; ")}: ${STANDARD}` });
196
+ }
197
+ for (const body of objectsIn(member.type))
198
+ visitObject(body, label, scan);
199
+ };
200
+ const DECLARATION = /\b(interface|class|type|function|const|let|var)\s+([\w$]+)/g;
201
+ const statementEnd = (text, from) => {
202
+ let depth = 0;
203
+ for (let at = from; at < text.length; at += 1) {
204
+ depth += depthStep(text, at);
205
+ if (depth < 0 || (depth === 0 && text[at] === ";"))
206
+ return at;
207
+ }
208
+ return text.length;
209
+ };
210
+ /**
211
+ * Findings in one declaration file; targets name the declaration, `AttachmentsService.list`. `pagingTypes` gains the
212
+ * file's own types that declare a limit or an offset.
213
+ */
214
+ export const shapeFindings = (text, pagingTypes = new Set()) => {
215
+ const code = text.replace(STRINGS_AND_COMMENTS, (match) => (match.startsWith("/") ? " " : '""'));
216
+ const scan = { found: [], pagingTypes };
217
+ let done = 0;
218
+ for (const match of code.matchAll(DECLARATION)) {
219
+ if (match.index < done)
220
+ continue;
221
+ const [whole, keyword, name] = match;
222
+ const start = match.index + whole.length;
223
+ if (keyword === "interface" || keyword === "class") {
224
+ const head = code.slice(start).match(/^\s*/)?.[0].length ?? 0;
225
+ const afterGenerics = code[start + head] === "<" ? closing(code, start + head) : start + head;
226
+ const open = code.indexOf("{", afterGenerics);
227
+ if (open < 0)
228
+ continue;
229
+ done = closing(code, open);
230
+ const inherits = /\b(?:extends|implements)\b/.test(code.slice(afterGenerics, open));
231
+ visitObject(code.slice(open + 1, done - 1), name, scan, inherits);
232
+ continue;
233
+ }
234
+ done = statementEnd(code, start);
235
+ const rest = code.slice(start, done);
236
+ if (keyword === "type") {
237
+ const type = skipGenerics(rest.trimStart()).replace(/^=/, "").trim();
238
+ const arrow = arrowOf(type);
239
+ visitMember(arrow ? { name, params: arrow.params, type: arrow.returns } : { name, type }, name, scan);
240
+ }
241
+ else {
242
+ const member = memberOf(`${name}${rest}`);
243
+ if (member)
244
+ visitMember(member, name, scan);
245
+ }
246
+ }
247
+ return scan.found;
248
+ };
249
+ /** Nothing built at all is a skip the lint reports, not a violation: a test run that did not build reads no types. */
250
+ export const resultShape = ({ files, missing }) => {
251
+ if (files.length === 0)
252
+ return [];
253
+ const pagingTypes = new Set();
254
+ for (const { text } of files)
255
+ shapeFindings(text, pagingTypes);
256
+ return [
257
+ ...missing.map((path) => ({
258
+ target: `${path}: not built`,
259
+ message: "package.json declares these types, but the file does not exist: build them before cli-dev lint",
260
+ })),
261
+ ...files.flatMap(({ path, text }) => shapeFindings(text, pagingTypes).map((finding) => ({ ...finding, target: `${path}: ${finding.target}` }))),
262
+ ];
263
+ };