@codefast/cli 0.13.0 → 0.15.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 (72) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/README.md +124 -40
  3. package/dist/arrange/simplify/variant-classname-probe.js +2 -11
  4. package/dist/audit/command.js +57 -16
  5. package/dist/audit/comments/domain/comment-content.d.ts +12 -0
  6. package/dist/audit/comments/domain/comment-content.js +17 -4
  7. package/dist/audit/comments/domain/comment-dividers.js +8 -1
  8. package/dist/audit/display-names/domain/display-names.js +4 -3
  9. package/dist/audit/domain/types.d.ts +119 -24
  10. package/dist/audit/engines/cli-result.d.ts +13 -0
  11. package/dist/audit/engines/cli-result.js +22 -0
  12. package/dist/audit/engines/cli-schema.d.ts +18 -0
  13. package/dist/audit/{constants → engines}/cli-schema.js +3 -3
  14. package/dist/audit/engines/domain/node-floor.d.ts +34 -0
  15. package/dist/audit/engines/domain/node-floor.js +40 -0
  16. package/dist/audit/engines/domain/range-gaps.d.ts +21 -0
  17. package/dist/audit/engines/domain/range-gaps.js +136 -0
  18. package/dist/audit/engines/output.d.ts +7 -0
  19. package/dist/audit/engines/output.js +40 -0
  20. package/dist/audit/engines/prepare.d.ts +16 -0
  21. package/dist/audit/engines/prepare.js +12 -0
  22. package/dist/audit/engines/run.d.ts +18 -0
  23. package/dist/audit/engines/run.js +225 -0
  24. package/dist/audit/layers/cli-result.d.ts +13 -0
  25. package/dist/audit/{constants → layers}/cli-result.js +6 -6
  26. package/dist/audit/layers/cli-schema.d.ts +29 -0
  27. package/dist/audit/layers/cli-schema.js +17 -0
  28. package/dist/audit/layers/domain/layering.d.ts +46 -0
  29. package/dist/audit/layers/domain/layering.js +191 -0
  30. package/dist/audit/layers/output.d.ts +7 -0
  31. package/dist/audit/layers/output.js +21 -0
  32. package/dist/audit/layers/prepare.d.ts +25 -0
  33. package/dist/audit/layers/prepare.js +66 -0
  34. package/dist/audit/layers/run.d.ts +19 -0
  35. package/dist/audit/layers/run.js +62 -0
  36. package/dist/audit/prepare.d.ts +13 -1
  37. package/dist/audit/prepare.js +16 -1
  38. package/dist/audit/props/cli-result.d.ts +13 -0
  39. package/dist/audit/props/cli-result.js +22 -0
  40. package/dist/audit/props/cli-schema.d.ts +18 -0
  41. package/dist/audit/props/cli-schema.js +12 -0
  42. package/dist/audit/props/domain/props-intersection.d.ts +56 -0
  43. package/dist/audit/props/domain/props-intersection.js +189 -0
  44. package/dist/audit/props/output.d.ts +7 -0
  45. package/dist/audit/{constants → props}/output.js +5 -5
  46. package/dist/audit/props/prepare.d.ts +13 -0
  47. package/dist/audit/props/prepare.js +9 -0
  48. package/dist/audit/props/run.d.ts +17 -0
  49. package/dist/audit/props/run.js +57 -0
  50. package/dist/audit/props/type-probe.d.ts +23 -0
  51. package/dist/audit/props/type-probe.js +85 -0
  52. package/dist/core/config/schema.d.ts +13 -4
  53. package/dist/core/config/schema.js +14 -1
  54. package/dist/core/type-server.d.ts +21 -0
  55. package/dist/core/type-server.js +32 -0
  56. package/dist/tag/cli-result.d.ts +3 -0
  57. package/dist/tag/cli-result.js +8 -2
  58. package/dist/tag/domain/types.d.ts +15 -0
  59. package/dist/tag/output.js +13 -6
  60. package/dist/tag/run.js +2 -0
  61. package/dist/tag/writer/since-writer.d.ts +5 -0
  62. package/dist/tag/writer/since-writer.js +41 -9
  63. package/package.json +6 -5
  64. package/dist/audit/constants/cli-result.d.ts +0 -13
  65. package/dist/audit/constants/cli-schema.d.ts +0 -18
  66. package/dist/audit/constants/domain/constants.d.ts +0 -8
  67. package/dist/audit/constants/domain/constants.js +0 -66
  68. package/dist/audit/constants/output.d.ts +0 -7
  69. package/dist/audit/constants/prepare.d.ts +0 -16
  70. package/dist/audit/constants/prepare.js +0 -37
  71. package/dist/audit/constants/run.d.ts +0 -14
  72. package/dist/audit/constants/run.js +0 -64
@@ -0,0 +1,85 @@
1
+ /** Type probe that resolves what each part of a props intersection is. */
2
+ import { loadTypeServer, loadTypeServerSyntax } from "#core/type-server";
3
+ // ── Type inspection ──────────────────────────────────────────────────────────────────────────────────────────────────
4
+ /** True when a type argument leaves a mapped type's keys unknown until instantiation. */
5
+ function isGenericArgument(type, mappedFlag) {
6
+ if (type.isTypeParameter() || type.isIndexType()) {
7
+ return true;
8
+ }
9
+ if (type.isUnionType() || type.isIntersectionType()) {
10
+ return (type.getTypes() ?? []).some((part) => isGenericArgument(part, mappedFlag));
11
+ }
12
+ return isGenericMappedType(type, mappedFlag);
13
+ }
14
+ /** True for a mapped type over a type parameter (`Partial<T>`, `Omit<T, K>`), whose members are not statically known. */
15
+ function isGenericMappedType(type, mappedFlag) {
16
+ return (type.isObjectType() &&
17
+ (type.objectFlags & mappedFlag) !== 0 &&
18
+ type.getAliasTypeArguments().some((argument) => isGenericArgument(argument, mappedFlag)));
19
+ }
20
+ /** Classifies a resolved part by whether an interface may extend it — TypeScript's own valid-base-type rule. */
21
+ function kindOfType(type, mappedFlag) {
22
+ if (type.isErrorType()) {
23
+ return "unresolved";
24
+ }
25
+ if (type.isUnionType()) {
26
+ return "union";
27
+ }
28
+ if (type.isTypeParameter() || isGenericMappedType(type, mappedFlag)) {
29
+ return "type-parameter";
30
+ }
31
+ if (type.isIntersectionType()) {
32
+ const kinds = (type.getTypes() ?? []).map((part) => kindOfType(part, mappedFlag));
33
+ return kinds.includes("unresolved") ? "unresolved" : (kinds.find((kind) => kind !== "object") ?? "object");
34
+ }
35
+ return type.isObjectType() ? "object" : "other";
36
+ }
37
+ // ── Probe lifecycle ──────────────────────────────────────────────────────────────────────────────────────────────────
38
+ /**
39
+ * Creates a type probe over the native TypeScript type server for `audit props`.
40
+ *
41
+ * @throws AppError when the `typescript` package providing the type server cannot be loaded.
42
+ *
43
+ * @since 0.15.0
44
+ */
45
+ export async function createPropsTypeProbe() {
46
+ const sync = await loadTypeServer("audit props");
47
+ const syntax = await loadTypeServerSyntax("audit props");
48
+ const api = new sync.API();
49
+ const mappedFlag = sync.ObjectFlags.Mapped;
50
+ /** Indexes every intersection part in a file by its span, the key oxc reports it under. */
51
+ function indexParts(sourceFile) {
52
+ const parts = new Map();
53
+ const visit = (node) => {
54
+ if (syntax.isIntersectionTypeNode(node)) {
55
+ for (const part of node.types) {
56
+ parts.set(`${syntax.getTokenPosOfNode(part, sourceFile)}:${part.end}`, part);
57
+ }
58
+ }
59
+ node.forEachChild(visit);
60
+ };
61
+ sourceFile.forEachChild(visit);
62
+ return parts;
63
+ }
64
+ function classifierFor(checker, sourceFile) {
65
+ const partsBySpan = indexParts(sourceFile);
66
+ return (parts) => parts.map(({ start, end }) => {
67
+ const node = partsBySpan.get(`${start}:${end}`);
68
+ const type = node === undefined ? undefined : checker.getTypeFromTypeNode(node);
69
+ return type === undefined ? "unresolved" : kindOfType(type, mappedFlag);
70
+ });
71
+ }
72
+ return {
73
+ forFile(filePath) {
74
+ const project = api.updateSnapshot({ openFiles: [filePath] }).getDefaultProjectForFile(filePath);
75
+ const sourceFile = project?.program.getSourceFile(filePath);
76
+ if (project === undefined || sourceFile === undefined) {
77
+ return (parts) => parts.map(() => "unresolved");
78
+ }
79
+ return classifierFor(project.checker, sourceFile);
80
+ },
81
+ dispose() {
82
+ api.close();
83
+ },
84
+ };
85
+ }
@@ -62,6 +62,17 @@ export interface CodefastArrangeConfig {
62
62
  interface CodefastAuditAllowlistConfig {
63
63
  allowlist?: Array<string> | undefined;
64
64
  }
65
+ /** One package's layering: `layers` bottom to top, each naming the directories and module files it holds under `root`. */
66
+ interface CodefastAuditLayersPackageConfig {
67
+ /** The directory the layers sit under, relative to the package directory. Defaults to `src`. */
68
+ root?: string | undefined;
69
+ layers: Array<Array<string>>;
70
+ }
71
+ /** The `audit layers` defaults: the layered packages by name, and the entries to ignore. */
72
+ interface CodefastAuditLayersConfig {
73
+ packages?: Record<string, CodefastAuditLayersPackageConfig> | undefined;
74
+ allowlist?: Array<string> | undefined;
75
+ }
65
76
  /** Per-audit defaults grouped under `audit`; the scan always starts at the repo root. */
66
77
  interface CodefastAuditConfig {
67
78
  rtl?: {
@@ -73,10 +84,8 @@ interface CodefastAuditConfig {
73
84
  imports?: CodefastAuditAllowlistConfig | undefined;
74
85
  assertions?: CodefastAuditAllowlistConfig | undefined;
75
86
  displayNames?: CodefastAuditAllowlistConfig | undefined;
76
- constants?: {
77
- target?: string | undefined;
78
- allowlist?: Array<string> | undefined;
79
- } | undefined;
87
+ props?: CodefastAuditAllowlistConfig | undefined;
88
+ layers?: CodefastAuditLayersConfig | undefined;
80
89
  }
81
90
  /**
82
91
  * The validated root `codefast.config` shape.
@@ -52,6 +52,18 @@ const codefastAuditAllowlistConfigSchema = z
52
52
  allowlist: z.array(z.string()).optional(),
53
53
  })
54
54
  .strict();
55
+ const codefastAuditLayersPackageConfigSchema = z
56
+ .object({
57
+ root: z.string().min(1).optional(),
58
+ layers: z.array(z.array(z.string().min(1)).min(1)).min(1),
59
+ })
60
+ .strict();
61
+ const codefastAuditLayersConfigSchema = z
62
+ .object({
63
+ packages: z.record(z.string(), codefastAuditLayersPackageConfigSchema).optional(),
64
+ allowlist: z.array(z.string()).optional(),
65
+ })
66
+ .strict();
55
67
  const codefastAuditConfigSchema = z
56
68
  .object({
57
69
  rtl: codefastAuditRtlConfigSchema.optional(),
@@ -60,7 +72,8 @@ const codefastAuditConfigSchema = z
60
72
  imports: codefastAuditAllowlistConfigSchema.optional(),
61
73
  assertions: codefastAuditAllowlistConfigSchema.optional(),
62
74
  displayNames: codefastAuditAllowlistConfigSchema.optional(),
63
- constants: codefastAuditRtlConfigSchema.optional(),
75
+ props: codefastAuditAllowlistConfigSchema.optional(),
76
+ layers: codefastAuditLayersConfigSchema.optional(),
64
77
  })
65
78
  .strict();
66
79
  /**
@@ -0,0 +1,21 @@
1
+ /** Loads the native TypeScript type server, and the syntax tree it serves, for the type-aware commands. */
2
+ import type * as TypeServerSyntax from "typescript/unstable/ast";
3
+ import type * as TypeServer from "typescript/unstable/sync";
4
+ /**
5
+ * Loads the native TypeScript type-server API on demand, since `typescript` is an optional peer.
6
+ *
7
+ * @param purpose - The command or flag that needs the type server, named in the error when it is missing.
8
+ * @throws AppError when the `typescript` package providing the type server cannot be loaded.
9
+ *
10
+ * @since 0.15.0
11
+ */
12
+ export declare function loadTypeServer(purpose: string): Promise<typeof TypeServer>;
13
+ /**
14
+ * Loads the syntax-tree helpers for the nodes the type server returns, on the same optional peer.
15
+ *
16
+ * @param purpose - The command or flag that needs the helpers, named in the error when they are missing.
17
+ * @throws AppError when the `typescript` package providing them cannot be loaded.
18
+ *
19
+ * @since 0.15.0
20
+ */
21
+ export declare function loadTypeServerSyntax(purpose: string): Promise<typeof TypeServerSyntax>;
@@ -0,0 +1,32 @@
1
+ /** Loads the native TypeScript type server, and the syntax tree it serves, for the type-aware commands. */
2
+ import { AppError, messageFrom } from "#core/errors";
3
+ async function loadOptionalPeer(purpose, load) {
4
+ try {
5
+ return await load();
6
+ }
7
+ catch (cause) {
8
+ throw new AppError("INFRA_FAILURE", `${purpose} needs the "typescript" package (v7) resolvable from the target: ${messageFrom(cause)}`, cause);
9
+ }
10
+ }
11
+ /**
12
+ * Loads the native TypeScript type-server API on demand, since `typescript` is an optional peer.
13
+ *
14
+ * @param purpose - The command or flag that needs the type server, named in the error when it is missing.
15
+ * @throws AppError when the `typescript` package providing the type server cannot be loaded.
16
+ *
17
+ * @since 0.15.0
18
+ */
19
+ export async function loadTypeServer(purpose) {
20
+ return loadOptionalPeer(purpose, () => import("typescript/unstable/sync"));
21
+ }
22
+ /**
23
+ * Loads the syntax-tree helpers for the nodes the type server returns, on the same optional peer.
24
+ *
25
+ * @param purpose - The command or flag that needs the helpers, named in the error when they are missing.
26
+ * @throws AppError when the `typescript` package providing them cannot be loaded.
27
+ *
28
+ * @since 0.15.0
29
+ */
30
+ export async function loadTypeServerSyntax(purpose) {
31
+ return loadOptionalPeer(purpose, () => import("typescript/unstable/ast"));
32
+ }
@@ -2,6 +2,9 @@ import type { TagResult } from "#tag/domain/types";
2
2
  /**
3
3
  * Maps a tag run's result to the process exit code.
4
4
  *
5
+ * @remarks A blocked declaration fails the run: once its release ships unstamped, the only stamp a
6
+ * later run can add names a version that did not introduce it.
7
+ *
5
8
  * @since 0.3.16-canary.0
6
9
  */
7
10
  export declare function exitCodeForTagResult(result: TagResult): number;
@@ -2,6 +2,9 @@ import { CLI_EXIT_GENERAL_ERROR, CLI_EXIT_SUCCESS } from "#core/exit-codes";
2
2
  /**
3
3
  * Maps a tag run's result to the process exit code.
4
4
  *
5
+ * @remarks A blocked declaration fails the run: once its release ships unstamped, the only stamp a
6
+ * later run can add names a version that did not introduce it.
7
+ *
5
8
  * @since 0.3.16-canary.0
6
9
  */
7
10
  export function exitCodeForTagResult(result) {
@@ -9,7 +12,10 @@ export function exitCodeForTagResult(result) {
9
12
  return CLI_EXIT_GENERAL_ERROR;
10
13
  }
11
14
  const hasRunErrors = result.targetResults.some((targetResult) => targetResult.runError !== null);
12
- return hasRunErrors || result.hookError !== null ? CLI_EXIT_GENERAL_ERROR : CLI_EXIT_SUCCESS;
15
+ const hasBlockedDeclarations = result.blockedDeclarations.length > 0;
16
+ return hasRunErrors || hasBlockedDeclarations || result.hookError !== null
17
+ ? CLI_EXIT_GENERAL_ERROR
18
+ : CLI_EXIT_SUCCESS;
13
19
  }
14
20
  /**
15
21
  * Serializes a tag run's result as the `--json` output string.
@@ -19,7 +25,7 @@ export function exitCodeForTagResult(result) {
19
25
  export function formatTagJsonOutput(result, rootDir) {
20
26
  return JSON.stringify({
21
27
  schemaVersion: 1,
22
- ok: result.hookError === null,
28
+ ok: exitCodeForTagResult(result) === CLI_EXIT_SUCCESS,
23
29
  cwd: rootDir,
24
30
  result,
25
31
  });
@@ -1,4 +1,17 @@
1
1
  import type { CodefastConfig } from "#core/config/schema";
2
+ /**
3
+ * An exported declaration left unstamped because it has no doc block and a `//` comment holds the line above it.
4
+ *
5
+ * @remarks A block written there would stack under a note or split a directive from the code it governs, so the
6
+ * writer leaves the whole file as it is until a person writes that doc block.
7
+ *
8
+ * @since 0.14.0
9
+ */
10
+ export type TagBlockedDeclaration = {
11
+ filePath: string;
12
+ line: number;
13
+ name: string;
14
+ };
2
15
  /**
3
16
  * Per-file outcome of a tag run.
4
17
  *
@@ -7,6 +20,7 @@ import type { CodefastConfig } from "#core/config/schema";
7
20
  export type TagFileResult = {
8
21
  filePath: string;
9
22
  taggedDeclarations: number;
23
+ blockedDeclarations: Array<TagBlockedDeclaration>;
10
24
  changed: boolean;
11
25
  };
12
26
  /**
@@ -93,6 +107,7 @@ export type TagResult = {
93
107
  filesScanned: number;
94
108
  filesChanged: number;
95
109
  taggedDeclarations: number;
110
+ blockedDeclarations: Array<TagBlockedDeclaration>;
96
111
  versionSummary: string;
97
112
  distinctVersions: Array<string>;
98
113
  modifiedFiles: Array<string>;
@@ -1,3 +1,4 @@
1
+ import path from "node:path";
1
2
  import { logger } from "#core/logger";
2
3
  /**
3
4
  * A progress listener that prints a line as each tag target starts and completes.
@@ -37,7 +38,7 @@ export function presentTagResult(result, rootDir) {
37
38
  logger.err("No packages found in workspace. Check your pnpm-workspace.yaml or provide an explicit target path.");
38
39
  return;
39
40
  }
40
- const warningsAndErrorsSection = formatWarningsAndErrors(result);
41
+ const warningsAndErrorsSection = formatWarningsAndErrors(result, rootDir);
41
42
  if (warningsAndErrorsSection) {
42
43
  logger.err(warningsAndErrorsSection);
43
44
  }
@@ -46,13 +47,16 @@ export function presentTagResult(result, rootDir) {
46
47
  function withColorizedLine(line, colorCode) {
47
48
  return `${colorCode}${line}${colorReset}`;
48
49
  }
49
- function warningsAndErrorsFromResult(result) {
50
+ function warningsAndErrorsFromResult(result, rootDir) {
50
51
  const entries = [];
51
52
  for (const targetResult of result.targetResults) {
52
53
  if (targetResult.runError) {
53
54
  entries.push(targetResult.runError);
54
55
  }
55
56
  }
57
+ for (const blocked of result.blockedDeclarations) {
58
+ entries.push(`${path.relative(rootDir, blocked.filePath)}:${blocked.line} \`${blocked.name}\` left unstamped: it has no doc block and a // comment holds the line above it — write the block by hand, then rerun`);
59
+ }
56
60
  if (result.hookError) {
57
61
  entries.push(result.hookError);
58
62
  }
@@ -72,8 +76,8 @@ function formatTargetTable(targets, rootDir) {
72
76
  }
73
77
  return lines.join("\n");
74
78
  }
75
- function formatWarningsAndErrors(result) {
76
- const entries = warningsAndErrorsFromResult(result);
79
+ function formatWarningsAndErrors(result, rootDir) {
80
+ const entries = warningsAndErrorsFromResult(result, rootDir);
77
81
  if (entries.length === 0) {
78
82
  return null;
79
83
  }
@@ -89,10 +93,13 @@ function formatSummary(result) {
89
93
  const versionSuffix = result.versionSummary === "mixed" && result.distinctVersions.length > 0
90
94
  ? ` [${result.distinctVersions.join(", ")}]`
91
95
  : "";
92
- const hasError = result.targetResults.some((targetResult) => targetResult.runError !== null) || result.hookError !== null;
96
+ const hasError = result.targetResults.some((targetResult) => targetResult.runError !== null) ||
97
+ result.blockedDeclarations.length > 0 ||
98
+ result.hookError !== null;
93
99
  const summaryColor = hasError ? colors.red : isDryRun ? colors.yellow : colors.green;
100
+ const blockedSuffix = result.blockedDeclarations.length > 0 ? ` blocked=${result.blockedDeclarations.length}` : "";
94
101
  const lines = [
95
- withColorizedLine(`${summaryPrefix} version=${result.versionSummary}${versionSuffix} files=${result.filesChanged}/${result.filesScanned} declarations=${result.taggedDeclarations}`, summaryColor),
102
+ withColorizedLine(`${summaryPrefix} version=${result.versionSummary}${versionSuffix} files=${result.filesChanged}/${result.filesScanned} declarations=${result.taggedDeclarations}${blockedSuffix}`, summaryColor),
96
103
  ];
97
104
  if (result.skippedPackages.length > 0) {
98
105
  lines.push(`[tag] Skipped: ${result.skippedPackages.length} package(s)`);
package/dist/tag/run.js CHANGED
@@ -33,6 +33,7 @@ export async function runTag(fs, input) {
33
33
  taggedDeclarations += runResult.taggedDeclarations;
34
34
  }
35
35
  const modifiedFiles = allFileResults.filter((entry) => entry.changed).map((entry) => entry.filePath);
36
+ const blockedDeclarations = allFileResults.flatMap((entry) => entry.blockedDeclarations);
36
37
  const hookError = input.write && modifiedFiles.length > 0
37
38
  ? await runTagOnAfterWriteHook(tagConfig?.onAfterWrite, modifiedFiles)
38
39
  : null;
@@ -46,6 +47,7 @@ export async function runTag(fs, input) {
46
47
  filesScanned,
47
48
  filesChanged,
48
49
  taggedDeclarations,
50
+ blockedDeclarations,
49
51
  versionSummary: summarizeVersions(versionsSet),
50
52
  distinctVersions,
51
53
  modifiedFiles,
@@ -28,5 +28,10 @@ export declare class TagSinceWriter {
28
28
  private jsDocHasSinceTag;
29
29
  private makeJSDocSinceLine;
30
30
  private makeSinceOnlyJSDocBlock;
31
+ /**
32
+ * Returns whether the line above `anchor` holds a `//` note, which a fresh block would stack under,
33
+ * or a directive, which would then govern the block instead of the declaration.
34
+ */
35
+ private isDocBlockLineTaken;
31
36
  private makeDeclarationSinceLine;
32
37
  }
@@ -1,12 +1,15 @@
1
1
  import { parseSync } from "oxc-parser";
2
+ import { isDirectiveLine, isNoteLine } from "#audit/comments/domain/comment-content";
2
3
  import { isOxcNode, programStatements } from "#core/oxc-node";
4
+ import { lineOfOffset } from "#core/source-position";
3
5
  import { applyEditsDescending, indentOfLineContaining } from "#core/source-text-edit";
4
6
  /**
5
- * Top-level statement kinds that carry a `@since` tag: function, class, interface,
6
- * type alias, enum, and variable declaration.
7
+ * Top-level statement kinds that carry a `@since` tag. `TSDeclareFunction` is a function with no body —
8
+ * an overload signature or a `declare function` — which the `.d.ts` keeps with its own doc block.
7
9
  */
8
10
  const TAGGABLE_DECLARATION_TYPES = new Set([
9
11
  "FunctionDeclaration",
12
+ "TSDeclareFunction",
10
13
  "ClassDeclaration",
11
14
  "TSInterfaceDeclaration",
12
15
  "TSTypeAliasDeclaration",
@@ -19,6 +22,14 @@ function identifierName(node) {
19
22
  }
20
23
  return undefined;
21
24
  }
25
+ function lineAboveOffset(sourceText, offset) {
26
+ const lineStart = sourceText.lastIndexOf("\n", offset - 1) + 1;
27
+ if (lineStart === 0) {
28
+ return undefined;
29
+ }
30
+ const lineAboveStart = lineStart >= 2 ? sourceText.lastIndexOf("\n", lineStart - 2) + 1 : 0;
31
+ return sourceText.slice(lineAboveStart, lineStart - 1);
32
+ }
22
33
  /**
23
34
  * The writer that adds missing `@since` tags to a file's exported declarations.
24
35
  *
@@ -36,20 +47,34 @@ export class TagSinceWriter {
36
47
  const statements = programStatements(program);
37
48
  const jsDocComments = comments.filter((comment) => comment.type === "Block" && comment.value.startsWith("*"));
38
49
  const edits = [];
50
+ const blockedDeclarations = [];
39
51
  for (const declaration of this.collectExportedDeclarations(statements)) {
40
- const edit = this.makeDeclarationSinceLine(declaration, jsDocComments, sourceText, version);
52
+ const existing = this.associatedJsDoc(declaration, jsDocComments, sourceText);
53
+ if (existing === undefined && this.isDocBlockLineTaken(declaration, sourceText)) {
54
+ const names = this.taggableDeclarationOf(declaration)?.names ?? [];
55
+ blockedDeclarations.push({
56
+ filePath,
57
+ line: lineOfOffset(sourceText, declaration.start),
58
+ name: names.length > 0 ? names.join(", ") : "default",
59
+ });
60
+ continue;
61
+ }
62
+ const edit = this.makeDeclarationSinceLine(declaration, existing, sourceText, version);
41
63
  if (edit) {
42
64
  edits.push(edit);
43
65
  }
44
66
  }
45
- if (edits.length > 0 && write) {
46
- const updated = applyEditsDescending(sourceText, edits);
67
+ // A blocked declaration holds its whole file back, so every reported line matches the file on disk.
68
+ const appliedEdits = blockedDeclarations.length > 0 ? [] : edits;
69
+ if (appliedEdits.length > 0 && write) {
70
+ const updated = applyEditsDescending(sourceText, appliedEdits);
47
71
  this.fs.writeFileSync(filePath, updated, "utf8");
48
72
  }
49
73
  return {
50
74
  filePath,
51
- taggedDeclarations: edits.length,
52
- changed: edits.length > 0,
75
+ taggedDeclarations: appliedEdits.length,
76
+ blockedDeclarations,
77
+ changed: appliedEdits.length > 0,
53
78
  };
54
79
  }
55
80
  /**
@@ -211,8 +236,15 @@ export class TagSinceWriter {
211
236
  const tag = this.sinceDocumentationTag;
212
237
  return `/**\n${declarationIndent} * ${tag} ${version}\n${declarationIndent} */`;
213
238
  }
214
- makeDeclarationSinceLine(anchor, jsDocComments, sourceText, version) {
215
- const existing = this.associatedJsDoc(anchor, jsDocComments, sourceText);
239
+ /**
240
+ * Returns whether the line above `anchor` holds a `//` note, which a fresh block would stack under,
241
+ * or a directive, which would then govern the block instead of the declaration.
242
+ */
243
+ isDocBlockLineTaken(anchor, sourceText) {
244
+ const lineAbove = lineAboveOffset(sourceText, anchor.start);
245
+ return lineAbove !== undefined && (isNoteLine(lineAbove) || isDirectiveLine(lineAbove));
246
+ }
247
+ makeDeclarationSinceLine(anchor, existing, sourceText, version) {
216
248
  if (existing) {
217
249
  if (this.jsDocHasSinceTag(existing)) {
218
250
  return undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codefast/cli",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "description": "Developer CLI for the Codefast monorepo (arrange, audit, mirror, pack-slim, tag)",
5
5
  "keywords": [
6
6
  "cli",
@@ -51,13 +51,14 @@
51
51
  "access": "public"
52
52
  },
53
53
  "dependencies": {
54
- "@microsoft/tsdoc": "^0.17.0",
54
+ "@microsoft/tsdoc": "^0.17.1",
55
55
  "commander": "^15.0.0",
56
56
  "jiti": "^2.7.0",
57
- "oxc-parser": "^0.151.0",
57
+ "oxc-parser": "^0.153.0",
58
58
  "picomatch": "^4.0.7",
59
+ "semver": "^7.8.5",
59
60
  "yaml": "^2.9.1",
60
- "zod": "^4.6.5"
61
+ "zod": "^4.6.7"
61
62
  },
62
63
  "peerDependencies": {
63
64
  "typescript": ">=7.0.0"
@@ -68,6 +69,6 @@
68
69
  }
69
70
  },
70
71
  "engines": {
71
- "node": ">=24.0.0"
72
+ "node": ">=22.12.0"
72
73
  }
73
74
  }
@@ -1,13 +0,0 @@
1
- import type { ConstantAuditResult } from "#audit/domain/types";
2
- /**
3
- * Exit `1` when any non-allowlisted numeric constant is unlabelled.
4
- *
5
- * @since 0.11.0
6
- */
7
- export declare function exitCodeForConstantAuditResult(result: ConstantAuditResult): number;
8
- /**
9
- * Machine-readable numeric-constant summary for `--json`.
10
- *
11
- * @since 0.11.0
12
- */
13
- export declare function formatConstantAuditJsonOutput(result: ConstantAuditResult, rootDir: string): string;
@@ -1,18 +0,0 @@
1
- import * as z from "zod";
2
- /**
3
- * Resolved request for a single numeric-constant audit run.
4
- *
5
- * @since 0.11.0
6
- */
7
- export type ConstantAuditRunRequest = {
8
- readonly rootDir: string;
9
- readonly targetPath: string;
10
- readonly allowlist?: ReadonlyArray<string> | undefined;
11
- readonly json: boolean;
12
- };
13
- /**
14
- * Zod schema for {@link ConstantAuditRunRequest}.
15
- *
16
- * @since 0.11.0
17
- */
18
- export declare const constantAuditRunRequestSchema: z.ZodType<ConstantAuditRunRequest>;
@@ -1,8 +0,0 @@
1
- /** The numeric-constant convention: a `const NAME = <number>` in a source tree names the kind of number it is. */
2
- import type { ConstantViolation } from "#audit/domain/types";
3
- /**
4
- * Scans one TypeScript source for numeric constants whose comment names none of the three kinds.
5
- *
6
- * @since 0.11.0
7
- */
8
- export declare function auditNumericConstants(sourceText: string): Array<ConstantViolation>;
@@ -1,66 +0,0 @@
1
- /**
2
- * The three kinds a numeric constant may be, each named by one phrase in the comment above it.
3
- *
4
- * @remarks A width of the machine, a value the contract fixes, or a figure derived from the data a
5
- * bind hands in. A count that merely looks reasonable is none of them, and the audit says so.
6
- */
7
- const KIND_PHRASES = [
8
- "a constant of the machine",
9
- "a value the contract fixes",
10
- "derived from bind-time data",
11
- ];
12
- /** An upper-case `const` bound to a numeric literal, with an optional type annotation. */
13
- const NUMERIC_CONST = /^\s*(?:export\s+)?const\s+([A-Z][A-Z0-9_]*)\s*(?::[^=]+)?=\s*(-?\d[\d_]*(?:\.\d+)?)(?![\w.])/;
14
- /** Values that stand for absence or identity, never for a tuned size: any distinct value would do. */
15
- const SENTINEL_VALUES = new Set(["0", "1", "-1"]);
16
- /**
17
- * Scans one TypeScript source for numeric constants whose comment names none of the three kinds.
18
- *
19
- * @since 0.11.0
20
- */
21
- export function auditNumericConstants(sourceText) {
22
- const lines = sourceText.split("\n");
23
- const violations = [];
24
- for (let index = 0; index < lines.length; index += 1) {
25
- const match = NUMERIC_CONST.exec(lines[index]);
26
- if (match === null || SENTINEL_VALUES.has(match[2])) {
27
- continue;
28
- }
29
- const comment = commentAbove(lines, index);
30
- if (KIND_PHRASES.some((phrase) => comment.includes(phrase))) {
31
- continue;
32
- }
33
- violations.push({
34
- line: index + 1,
35
- raw: `${match[1]} = ${match[2]}`,
36
- reason: `no kind named above it — say which it is: ${KIND_PHRASES.join(" · ")}`,
37
- });
38
- }
39
- return violations;
40
- }
41
- /** The doc block or run of `//` lines directly above a line, as one text; empty when there is none. */
42
- function commentAbove(lines, index) {
43
- let cursor = index - 1;
44
- const gathered = [];
45
- while (cursor >= 0) {
46
- const line = lines[cursor].trim();
47
- if (line.startsWith("//")) {
48
- gathered.unshift(line);
49
- cursor -= 1;
50
- continue;
51
- }
52
- if (line.endsWith("*/")) {
53
- // Walk back to the opening of the block, collecting it whole.
54
- while (cursor >= 0) {
55
- gathered.unshift(lines[cursor].trim());
56
- if (lines[cursor].trim().startsWith("/*")) {
57
- break;
58
- }
59
- cursor -= 1;
60
- }
61
- break;
62
- }
63
- break;
64
- }
65
- return gathered.join(" ");
66
- }
@@ -1,7 +0,0 @@
1
- import type { ConstantAuditResult } from "#audit/domain/types";
2
- /**
3
- * Human-readable numeric-constant report.
4
- *
5
- * @since 0.11.0
6
- */
7
- export declare function presentConstantAuditResult(result: ConstantAuditResult): void;
@@ -1,16 +0,0 @@
1
- import type { AuditCommandPrelude } from "#audit/prepare";
2
- import { AppError } from "#core/errors";
3
- import type { Filesystem } from "#core/filesystem/filesystem";
4
- import type { Result } from "#core/result";
5
- /**
6
- * Loads config and resolves the scan target for `audit constants`.
7
- *
8
- * @remarks The target is the library tree the convention holds over, from `audit.constants.target`
9
- * unless the command names one.
10
- *
11
- * @since 0.11.0
12
- */
13
- export declare function prepareConstantAudit(fs: Filesystem, args: {
14
- readonly currentWorkingDirectory: string;
15
- readonly rawTarget: string | undefined;
16
- }): Promise<Result<AuditCommandPrelude, AppError>>;
@@ -1,37 +0,0 @@
1
- import { resolveRepoRelativePath } from "#audit/prepare";
2
- import { loadCodefastConfig } from "#core/config";
3
- import { AppError, messageFrom } from "#core/errors";
4
- import { err, ok } from "#core/result";
5
- import { resolveProjectRoot } from "#core/workspace/resolver";
6
- /**
7
- * Loads config and resolves the scan target for `audit constants`.
8
- *
9
- * @remarks The target is the library tree the convention holds over, from `audit.constants.target`
10
- * unless the command names one.
11
- *
12
- * @since 0.11.0
13
- */
14
- export async function prepareConstantAudit(fs, args) {
15
- let rootDir;
16
- try {
17
- rootDir = fs.canonicalPathSync(resolveProjectRoot(args.currentWorkingDirectory, fs).rootDir);
18
- }
19
- catch (caughtError) {
20
- return err(new AppError("INFRA_FAILURE", messageFrom(caughtError), caughtError));
21
- }
22
- const loadedOutcome = await loadCodefastConfig(rootDir, fs);
23
- if (!loadedOutcome.ok) {
24
- return loadedOutcome;
25
- }
26
- const { config } = loadedOutcome.value;
27
- const constantsConfig = config.audit?.constants ?? {};
28
- const resolvedTargetInput = args.rawTarget ?? constantsConfig.target;
29
- if (resolvedTargetInput === undefined) {
30
- return err(new AppError("VALIDATION_ERROR", "audit constants needs a target: pass one, or set audit.constants.target in codefast.config"));
31
- }
32
- const targetPath = resolveRepoRelativePath(args.rawTarget !== undefined ? args.currentWorkingDirectory : rootDir, resolvedTargetInput);
33
- if (!fs.existsSync(targetPath)) {
34
- return err(new AppError("NOT_FOUND", `Not found: ${targetPath}`));
35
- }
36
- return ok({ rootDir, targetPath: fs.canonicalPathSync(targetPath), allowlist: constantsConfig.allowlist ?? [] });
37
- }