@eserstack/codebase 0.0.0-stage → 5.0.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 (175) hide show
  1. package/README.md +301 -2
  2. package/dist/changelog-gen.d.ts +105 -0
  3. package/dist/changelog-gen.js +498 -0
  4. package/dist/changelog-text.d.ts +39 -0
  5. package/dist/changelog-text.js +82 -0
  6. package/dist/cli-support.d.ts +140 -0
  7. package/dist/cli-support.js +244 -0
  8. package/dist/cli-system/app-opts.d.ts +15 -0
  9. package/dist/cli-system/app-opts.js +13 -0
  10. package/dist/cli-system/app.d.ts +29 -0
  11. package/dist/cli-system/app.js +12 -0
  12. package/dist/cli-system/handlers/completions-setup.d.ts +14 -0
  13. package/dist/cli-system/handlers/completions-setup.js +139 -0
  14. package/dist/cli-system/handlers/completions.d.ts +3 -0
  15. package/dist/cli-system/handlers/completions.js +79 -0
  16. package/dist/cli-system/handlers/doctor.d.ts +8 -0
  17. package/dist/cli-system/handlers/doctor.js +146 -0
  18. package/dist/cli-system/handlers/info.d.ts +3 -0
  19. package/dist/cli-system/handlers/info.js +69 -0
  20. package/dist/cli-system/handlers/install.d.ts +8 -0
  21. package/dist/cli-system/handlers/install.js +137 -0
  22. package/dist/cli-system/handlers/mod.d.ts +12 -0
  23. package/dist/cli-system/handlers/mod.js +13 -0
  24. package/dist/cli-system/handlers/uninstall.d.ts +3 -0
  25. package/dist/cli-system/handlers/uninstall.js +60 -0
  26. package/dist/cli-system/handlers/update.d.ts +76 -0
  27. package/dist/cli-system/handlers/update.js +310 -0
  28. package/dist/cli-system/handlers/version-check.d.ts +16 -0
  29. package/dist/cli-system/handlers/version-check.js +176 -0
  30. package/dist/cli-system/handlers/version.d.ts +3 -0
  31. package/dist/cli-system/handlers/version.js +45 -0
  32. package/dist/cli-system/mod.d.ts +19 -0
  33. package/dist/cli-system/mod.js +52 -0
  34. package/dist/commitmsg.d.ts +28 -0
  35. package/dist/commitmsg.js +232 -0
  36. package/dist/directive-analysis.d.ts +75 -0
  37. package/dist/directive-analysis.js +223 -0
  38. package/dist/ffi-client.d.ts +11 -0
  39. package/dist/ffi-client.js +12 -0
  40. package/dist/file-tool.d.ts +96 -0
  41. package/dist/file-tool.js +274 -0
  42. package/dist/file-tools-shared.d.ts +81 -0
  43. package/dist/file-tools-shared.js +276 -0
  44. package/dist/gh-contributors.d.ts +89 -0
  45. package/dist/gh-contributors.js +205 -0
  46. package/dist/gh.d.ts +3 -0
  47. package/dist/gh.js +64 -0
  48. package/dist/git-listing.d.ts +27 -0
  49. package/dist/git-listing.js +69 -0
  50. package/dist/git.d.ts +172 -0
  51. package/dist/git.js +277 -0
  52. package/dist/install.d.ts +34 -0
  53. package/dist/install.js +421 -0
  54. package/dist/main.d.ts +22 -0
  55. package/dist/main.js +14 -0
  56. package/dist/mod.d.ts +25 -0
  57. package/dist/mod.js +8 -0
  58. package/dist/module.d.ts +10 -0
  59. package/dist/module.js +221 -0
  60. package/dist/native-functions.d.ts +1088 -0
  61. package/dist/native-functions.js +2 -0
  62. package/dist/npm-externals.d.ts +27 -0
  63. package/dist/npm-externals.js +34 -0
  64. package/dist/npm-workspace-specifiers.d.ts +6 -0
  65. package/dist/npm-workspace-specifiers.js +45 -0
  66. package/dist/package/loader.d.ts +34 -0
  67. package/dist/package/loader.js +203 -0
  68. package/dist/package/mod.d.ts +36 -0
  69. package/dist/package/mod.js +5 -0
  70. package/dist/package/types.d.ts +142 -0
  71. package/dist/package/types.js +32 -0
  72. package/dist/package/workspace.d.ts +33 -0
  73. package/dist/package/workspace.js +158 -0
  74. package/dist/package/writer.d.ts +52 -0
  75. package/dist/package/writer.js +278 -0
  76. package/dist/package.json +275 -0
  77. package/dist/release-notes.d.ts +90 -0
  78. package/dist/release-notes.js +236 -0
  79. package/dist/release-tag.d.ts +46 -0
  80. package/dist/release-tag.js +95 -0
  81. package/dist/release.d.ts +145 -0
  82. package/dist/release.js +584 -0
  83. package/dist/source-mask.d.ts +3 -0
  84. package/dist/source-mask.js +185 -0
  85. package/dist/validate-bom.d.ts +5 -0
  86. package/dist/validate-bom.js +43 -0
  87. package/dist/validate-case-conflict.d.ts +5 -0
  88. package/dist/validate-case-conflict.js +43 -0
  89. package/dist/validate-circular-deps.d.ts +11 -0
  90. package/dist/validate-circular-deps.js +53 -0
  91. package/dist/validate-code-conventions.d.ts +22 -0
  92. package/dist/validate-code-conventions.js +166 -0
  93. package/dist/validate-commit-msg.d.ts +50 -0
  94. package/dist/validate-commit-msg.js +182 -0
  95. package/dist/validate-docs.d.ts +20 -0
  96. package/dist/validate-docs.js +78 -0
  97. package/dist/validate-eof.d.ts +5 -0
  98. package/dist/validate-eof.js +61 -0
  99. package/dist/validate-error-coverage.d.ts +28 -0
  100. package/dist/validate-error-coverage.js +93 -0
  101. package/dist/validate-export-names.d.ts +17 -0
  102. package/dist/validate-export-names.js +56 -0
  103. package/dist/validate-filenames.d.ts +5 -0
  104. package/dist/validate-filenames.js +151 -0
  105. package/dist/validate-json.d.ts +5 -0
  106. package/dist/validate-json.js +71 -0
  107. package/dist/validate-large-files.d.ts +5 -0
  108. package/dist/validate-large-files.js +41 -0
  109. package/dist/validate-laroux-boundaries.d.ts +19 -0
  110. package/dist/validate-laroux-boundaries.js +59 -0
  111. package/dist/validate-licenses.d.ts +5 -0
  112. package/dist/validate-licenses.js +137 -0
  113. package/dist/validate-line-endings.d.ts +5 -0
  114. package/dist/validate-line-endings.js +47 -0
  115. package/dist/validate-merge-conflict.d.ts +5 -0
  116. package/dist/validate-merge-conflict.js +46 -0
  117. package/dist/validate-mod-exports.d.ts +16 -0
  118. package/dist/validate-mod-exports.js +56 -0
  119. package/dist/validate-naming-and-todos.d.ts +5 -0
  120. package/dist/validate-naming-and-todos.js +70 -0
  121. package/dist/validate-runtime-js-apis.d.ts +5 -0
  122. package/dist/validate-runtime-js-apis.js +78 -0
  123. package/dist/validate-secrets.d.ts +5 -0
  124. package/dist/validate-secrets.js +82 -0
  125. package/dist/validate-self-imports.d.ts +5 -0
  126. package/dist/validate-self-imports.js +78 -0
  127. package/dist/validate-server-loc.d.ts +32 -0
  128. package/dist/validate-server-loc.js +94 -0
  129. package/dist/validate-shebangs.d.ts +5 -0
  130. package/dist/validate-shebangs.js +33 -0
  131. package/dist/validate-stream.d.ts +25 -0
  132. package/dist/validate-stream.js +62 -0
  133. package/dist/validate-submodules.d.ts +5 -0
  134. package/dist/validate-submodules.js +43 -0
  135. package/dist/validate-symlinks.d.ts +5 -0
  136. package/dist/validate-symlinks.js +46 -0
  137. package/dist/validate-toml.d.ts +5 -0
  138. package/dist/validate-toml.js +40 -0
  139. package/dist/validate-trailing-whitespace.d.ts +5 -0
  140. package/dist/validate-trailing-whitespace.js +49 -0
  141. package/dist/validate-yaml.d.ts +5 -0
  142. package/dist/validate-yaml.js +40 -0
  143. package/dist/validation/config.d.ts +17 -0
  144. package/dist/validation/config.js +30 -0
  145. package/dist/validation/mod.d.ts +71 -0
  146. package/dist/validation/mod.js +479 -0
  147. package/dist/validation/registry.d.ts +57 -0
  148. package/dist/validation/registry.js +256 -0
  149. package/dist/validation/types.d.ts +101 -0
  150. package/dist/validation/types.js +2 -0
  151. package/dist/validation/validators/circular-deps.d.ts +7 -0
  152. package/dist/validation/validators/circular-deps.js +31 -0
  153. package/dist/validation/validators/docs.d.ts +7 -0
  154. package/dist/validation/validators/docs.js +38 -0
  155. package/dist/validation/validators/error-coverage.d.ts +2 -0
  156. package/dist/validation/validators/error-coverage.js +46 -0
  157. package/dist/validation/validators/export-names.d.ts +7 -0
  158. package/dist/validation/validators/export-names.js +31 -0
  159. package/dist/validation/validators/laroux-boundaries.d.ts +2 -0
  160. package/dist/validation/validators/laroux-boundaries.js +29 -0
  161. package/dist/validation/validators/mod-exports.d.ts +7 -0
  162. package/dist/validation/validators/mod-exports.js +32 -0
  163. package/dist/validation/validators/mod.d.ts +11 -0
  164. package/dist/validation/validators/mod.js +12 -0
  165. package/dist/validation/validators/server-loc.d.ts +2 -0
  166. package/dist/validation/validators/server-loc.js +48 -0
  167. package/dist/versions.d.ts +166 -0
  168. package/dist/versions.js +349 -0
  169. package/dist/violation-baseline.d.ts +58 -0
  170. package/dist/violation-baseline.js +144 -0
  171. package/dist/walk-stream.d.ts +24 -0
  172. package/dist/walk-stream.js +55 -0
  173. package/dist/workspace-discovery.d.ts +60 -0
  174. package/dist/workspace-discovery.js +130 -0
  175. package/package.json +222 -3
@@ -0,0 +1,185 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Tells code apart from comments and string literals in a JavaScript or
4
+ * TypeScript source, so the pattern-based validators skip a match that sits
5
+ * in a comment, a JSDoc example or a string.
6
+ *
7
+ * This is a scanner, not a lexer. It tells a regular expression literal from
8
+ * a division by the previous significant token, as the Go lexer in
9
+ * pkg/ajan/codebasefx does, so a quote or backtick inside a regex is not read
10
+ * as the start of a string. A single- or double-quoted string ends at the end
11
+ * of its line, which bounds any other misreading to one line.
12
+ *
13
+ * @module
14
+ */
15
+ /**
16
+ * Marks with 1 every position of `content` that sits inside a comment, a
17
+ * string literal or a regular expression literal. The text of a template
18
+ * literal is masked; its `${...}` interpolations are code, so
19
+ * `${process.env.X}` still counts as code.
20
+ */
21
+ const IDENT_CHAR = /[A-Za-z0-9_$]/;
22
+ // Keywords after which a slash starts a regular expression, not a division.
23
+ const REGEX_AFTER_KEYWORD = new Set([
24
+ "return",
25
+ "typeof",
26
+ "instanceof",
27
+ "in",
28
+ "of",
29
+ "new",
30
+ "delete",
31
+ "void",
32
+ "throw",
33
+ "case",
34
+ "do",
35
+ "else",
36
+ "yield",
37
+ "await",
38
+ ]);
39
+ export const codeMask = (content) => {
40
+ const mask = new Uint8Array(content.length);
41
+ const length = content.length;
42
+ // Brace depth at which each open template interpolation started; a `}` at
43
+ // that depth closes the interpolation and resumes the template text.
44
+ const interpolations = [];
45
+ let depth = 0;
46
+ let i = 0;
47
+ // The previous significant token, which decides whether a `/` starts a
48
+ // regular expression: "value" for a literal, a word, or a punctuator.
49
+ let previous = "";
50
+ // Masks template text up to the closing backtick or the next `${`.
51
+ const scanTemplateText = () => {
52
+ while (i < length) {
53
+ const ch = content[i];
54
+ if (ch === "\\") {
55
+ mask[i++] = 1;
56
+ if (i < length)
57
+ mask[i++] = 1;
58
+ continue;
59
+ }
60
+ if (ch === "`") {
61
+ mask[i++] = 1;
62
+ return;
63
+ }
64
+ if (ch === "$" && content[i + 1] === "{") {
65
+ mask[i++] = 1;
66
+ mask[i++] = 1;
67
+ interpolations.push(depth);
68
+ return;
69
+ }
70
+ mask[i++] = 1;
71
+ }
72
+ };
73
+ // Masks a single- or double-quoted string, which cannot span lines.
74
+ const scanQuoted = (quote) => {
75
+ mask[i++] = 1;
76
+ while (i < length) {
77
+ const ch = content[i];
78
+ if (ch === "\\") {
79
+ mask[i++] = 1;
80
+ if (i < length)
81
+ mask[i++] = 1;
82
+ continue;
83
+ }
84
+ if (ch === "\n")
85
+ return;
86
+ mask[i++] = 1;
87
+ if (ch === quote)
88
+ return;
89
+ }
90
+ };
91
+ // Masks a regular expression literal and its flags; it cannot span lines.
92
+ const scanRegex = () => {
93
+ let inClass = false;
94
+ mask[i++] = 1;
95
+ while (i < length) {
96
+ const ch = content[i];
97
+ if (ch === "\n")
98
+ return;
99
+ if (ch === "\\") {
100
+ mask[i++] = 1;
101
+ if (i < length && content[i] !== "\n")
102
+ mask[i++] = 1;
103
+ continue;
104
+ }
105
+ mask[i++] = 1;
106
+ if (ch === "[")
107
+ inClass = true;
108
+ else if (ch === "]")
109
+ inClass = false;
110
+ else if (ch === "/" && !inClass)
111
+ break;
112
+ }
113
+ while (i < length && IDENT_CHAR.test(content[i]))
114
+ mask[i++] = 1;
115
+ };
116
+ const regexAllowed = () => {
117
+ if (previous === "" || previous === "value") {
118
+ return previous === "";
119
+ }
120
+ if (IDENT_CHAR.test(previous[0])) {
121
+ return REGEX_AFTER_KEYWORD.has(previous);
122
+ }
123
+ return previous !== ")" && previous !== "]";
124
+ };
125
+ while (i < length) {
126
+ const ch = content[i];
127
+ const next = content[i + 1];
128
+ if (ch === "/" && next === "/") {
129
+ while (i < length && content[i] !== "\n")
130
+ mask[i++] = 1;
131
+ continue;
132
+ }
133
+ if (ch === "/" && next === "*") {
134
+ const end = content.indexOf("*/", i + 2);
135
+ const stop = end < 0 ? length : end + 2;
136
+ while (i < stop)
137
+ mask[i++] = 1;
138
+ continue;
139
+ }
140
+ if (ch === "`") {
141
+ mask[i++] = 1;
142
+ scanTemplateText();
143
+ previous = "value";
144
+ continue;
145
+ }
146
+ if (ch === '"' || ch === "'") {
147
+ scanQuoted(ch);
148
+ previous = "value";
149
+ continue;
150
+ }
151
+ if (ch === "/" && regexAllowed()) {
152
+ scanRegex();
153
+ previous = "value";
154
+ continue;
155
+ }
156
+ if (IDENT_CHAR.test(ch)) {
157
+ const start = i;
158
+ while (i < length && IDENT_CHAR.test(content[i]))
159
+ i++;
160
+ const word = content.slice(start, i);
161
+ previous = /^[0-9]/.test(word) ? "value" : word;
162
+ continue;
163
+ }
164
+ if (ch === "{") {
165
+ depth++;
166
+ }
167
+ else if (ch === "}") {
168
+ if (interpolations.at(-1) === depth) {
169
+ interpolations.pop();
170
+ mask[i++] = 1;
171
+ scanTemplateText();
172
+ previous = "value";
173
+ continue;
174
+ }
175
+ depth--;
176
+ }
177
+ if (ch !== " " && ch !== "\t" && ch !== "\n" && ch !== "\r") {
178
+ previous = ch;
179
+ }
180
+ i++;
181
+ }
182
+ return mask;
183
+ };
184
+ /** The 1-based line number of a character index in `content`. */
185
+ export const lineOf = (content, index) => content.slice(0, index).split("\n").length;
@@ -0,0 +1,5 @@
1
+ import type { FileTool } from "./file-tool.ts";
2
+ export declare const tool: FileTool;
3
+ export declare const run: FileTool["run"];
4
+ export declare const validator: FileTool["validator"];
5
+ export declare const main: FileTool["main"];
@@ -0,0 +1,43 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * BOM fixer — removes UTF-8 byte order markers.
4
+ *
5
+ * @module
6
+ */
7
+ import * as standards from "@eserstack/standards";
8
+ import * as cliSupport from "./cli-support.js";
9
+ import * as fileTool from "./file-tool.js";
10
+ /** UTF-8 BOM: 0xEF 0xBB 0xBF */
11
+ const BOM = "\uFEFF";
12
+ export const tool = fileTool.withGoValidator(fileTool.createFileTool({
13
+ name: "validate-bom",
14
+ description: "Remove UTF-8 byte order markers",
15
+ canFix: true,
16
+ stacks: [],
17
+ defaults: {},
18
+ checkFile(file, content) {
19
+ if (content === undefined) {
20
+ return [];
21
+ }
22
+ if (content.startsWith(BOM)) {
23
+ return [{ path: file.path, message: "file has UTF-8 BOM" }];
24
+ }
25
+ return [];
26
+ },
27
+ fixFile(file, content) {
28
+ if (!content.startsWith(BOM)) {
29
+ return undefined;
30
+ }
31
+ const fixed = content.slice(1);
32
+ return { path: file.path, oldContent: content, newContent: fixed };
33
+ },
34
+ }), "bom");
35
+ export const run = tool.run;
36
+ export const validator = tool.validator;
37
+ export const main = tool.main;
38
+ if (import.meta.main) {
39
+ // Entry point: the await only runs when this file is executed directly.
40
+ // oxlint-disable-next-line node/no-top-level-await
41
+ const result = await main(standards.crossRuntime.runtime.process.args);
42
+ cliSupport.runCliMain(result);
43
+ }
@@ -0,0 +1,5 @@
1
+ import type { FileTool } from "./file-tool.ts";
2
+ export declare const tool: FileTool;
3
+ export declare const run: FileTool["run"];
4
+ export declare const validator: FileTool["validator"];
5
+ export declare const main: FileTool["main"];
@@ -0,0 +1,43 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Case conflict checker — detects filenames that differ only by case.
4
+ *
5
+ * @module
6
+ */
7
+ import * as standards from "@eserstack/standards";
8
+ import * as cliSupport from "./cli-support.js";
9
+ import * as fileTool from "./file-tool.js";
10
+ export const tool = fileTool.withGoValidator(fileTool.createFileTool({
11
+ name: "validate-case-conflict",
12
+ description: "Detect filenames that differ only by case",
13
+ canFix: false,
14
+ stacks: [],
15
+ defaults: {},
16
+ checkAll(files) {
17
+ const seen = new Map();
18
+ const issues = [];
19
+ for (const file of files) {
20
+ const lower = file.path.toLowerCase();
21
+ const existing = seen.get(lower);
22
+ if (existing !== undefined) {
23
+ issues.push({
24
+ path: file.path,
25
+ message: `case conflict with "${existing}"`,
26
+ });
27
+ }
28
+ else {
29
+ seen.set(lower, file.path);
30
+ }
31
+ }
32
+ return issues;
33
+ },
34
+ }), "case-conflict");
35
+ export const run = tool.run;
36
+ export const validator = tool.validator;
37
+ export const main = tool.main;
38
+ if (import.meta.main) {
39
+ // Entry point: the await only runs when this file is executed directly.
40
+ // oxlint-disable-next-line node/no-top-level-await
41
+ const result = await main(standards.crossRuntime.runtime.process.args);
42
+ cliSupport.runCliMain(result);
43
+ }
@@ -0,0 +1,11 @@
1
+ import type * as shellArgs from "@eserstack/shell/args";
2
+ export type CheckCircularDepsOptions = {
3
+ readonly root?: string;
4
+ };
5
+ export type CheckCircularDepsResult = {
6
+ readonly hasCycles: boolean;
7
+ readonly cycles: string[][];
8
+ readonly packagesChecked: number;
9
+ };
10
+ export declare const checkCircularDeps: (options?: CheckCircularDepsOptions) => Promise<CheckCircularDepsResult>;
11
+ export declare const main: (_cliArgs?: readonly string[]) => Promise<shellArgs.CliResult<void>>;
@@ -0,0 +1,53 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Circular dependency checker for workspace packages.
4
+ *
5
+ * Detects circular dependencies between packages in the workspace.
6
+ *
7
+ * @module
8
+ */
9
+ import * as primitives from "@eserstack/primitives";
10
+ import * as span from "@eserstack/streams/span";
11
+ import * as cliSupport from "./cli-support.js";
12
+ import * as ffiClient from "./ffi-client.js";
13
+ export const checkCircularDeps = async (options = {}) => {
14
+ const { root = "." } = options;
15
+ await ffiClient.ensureLib();
16
+ const lib = ffiClient.getLib();
17
+ if (lib === null) {
18
+ throw new Error("native library not available for checkCircularDeps");
19
+ }
20
+ const result = lib.call("codebaseCheckCircularDeps", {
21
+ dir: root,
22
+ });
23
+ if (result.error) {
24
+ throw new Error(result.error);
25
+ }
26
+ return result;
27
+ };
28
+ export const main = async (_cliArgs) => {
29
+ const { output: out } = cliSupport.getCliContext();
30
+ try {
31
+ const value = await checkCircularDeps({ root: "." });
32
+ out.writeln(span.blue("ℹ"), span.text(` Checked ${value.packagesChecked} packages.`));
33
+ if (value.hasCycles) {
34
+ out.writeln(span.red("✗"), span.text(` Found ${value.cycles.length} circular dependencies:`));
35
+ for (const cycle of value.cycles) {
36
+ out.writeln(span.yellow("⚠"), span.text(` ${cycle.join(" → ")}`));
37
+ }
38
+ return primitives.results.fail({ exitCode: 1 });
39
+ }
40
+ out.writeln(span.green("✓"), span.text(" No circular dependencies found."));
41
+ return primitives.results.ok(undefined);
42
+ }
43
+ catch (err) {
44
+ out.writeln(span.red("✗"), span.text(` ${String(err)}`));
45
+ return primitives.results.fail({ exitCode: 1 });
46
+ }
47
+ };
48
+ if (import.meta.main) {
49
+ // Entry point: the await only runs when this file is executed directly.
50
+ // oxlint-disable-next-line node/no-top-level-await
51
+ const result = await main();
52
+ cliSupport.runCliMain(result, cliSupport.getCliContext().output);
53
+ }
@@ -0,0 +1,22 @@
1
+ import type { FileTool } from "./file-tool.ts";
2
+ import * as violationBaseline from "./violation-baseline.ts";
3
+ /** The rules this validator reports; each is a key of the baseline. */
4
+ export declare const RULES: readonly ["namespace-import", "or-default", "export-star"];
5
+ export type Rule = (typeof RULES)[number];
6
+ export type Violation = violationBaseline.RuleViolation<Rule>;
7
+ /** rule -> repository-relative path -> allowed violation count */
8
+ export type Baseline = violationBaseline.Baseline<Rule>;
9
+ export declare const DEFAULT_BASELINE_PATH = ".eser/baselines/code-conventions.json";
10
+ /** Finds convention violations in one TypeScript or JavaScript source. */
11
+ export declare const findViolations: (content: string) => Violation[];
12
+ export declare const readBaseline: (file: string) => Promise<Baseline>;
13
+ export declare const tool: FileTool;
14
+ /** Records every current violation as the new baseline. */
15
+ export declare const writeBaseline: (root: string, baselineFile?: string) => Promise<number>;
16
+ export declare const run: FileTool["run"];
17
+ export declare const validator: FileTool["validator"];
18
+ /**
19
+ * CLI entry: checks the tree, or with `--write-baseline` records the current
20
+ * violations as the new baseline.
21
+ */
22
+ export declare const main: FileTool["main"];
@@ -0,0 +1,166 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Code convention checker for rules that agents and reviewers keep missing:
4
+ *
5
+ * - `namespace-import`: import modules as `import * as name`. The exceptions
6
+ * are `import { runtime } from "@eserstack/standards/cross-runtime"` and the
7
+ * default import of a JSON module or a CSS module
8
+ * (`import styles from "./x.module.css"`). Type-only imports
9
+ * (`import type { ... }`) are allowed.
10
+ * - `or-default`: a default after `||` (`value || ""`, `list || []`) also
11
+ * replaces valid falsy values such as `0` and `""`. Use `??`, or an explicit
12
+ * check when an empty value must fall back too.
13
+ * - `export-star`: `export * from` (and `export type * from`) re-exports a
14
+ * whole module, so names shared by two modules collide (TS2308) and the
15
+ * public surface is hidden. Export the names explicitly, or re-export the
16
+ * module as a namespace with `export * as name from`.
17
+ *
18
+ * Existing violations are recorded per file in a baseline
19
+ * (`.eser/baselines/code-conventions.json`). A file fails only when it has
20
+ * more violations of a rule than its baseline allows, so new code follows the
21
+ * rules while old code is migrated over time. After fixing violations, shrink
22
+ * the baseline:
23
+ *
24
+ * node ./pkg/@eserstack/codebase/validate-code-conventions.ts --write-baseline
25
+ *
26
+ * @module
27
+ */
28
+ import * as primitives from "@eserstack/primitives";
29
+ import * as standards from "@eserstack/standards";
30
+ import * as patterns from "@eserstack/standards/patterns";
31
+ import * as cliSupport from "./cli-support.js";
32
+ import * as fileTool from "./file-tool.js";
33
+ import * as shared from "./file-tools-shared.js";
34
+ import * as sourceMask from "./source-mask.js";
35
+ import * as violationBaseline from "./violation-baseline.js";
36
+ /** The rules this validator reports; each is a key of the baseline. */
37
+ export const RULES = ["namespace-import", "or-default", "export-star"];
38
+ export const DEFAULT_BASELINE_PATH = ".eser/baselines/code-conventions.json";
39
+ const TOOL_NAME = "validate-code-conventions";
40
+ /** Paths that follow their own ecosystem's conventions or are scratch output. */
41
+ const IGNORED_PREFIXES = [".eser/recipes/", "etc/temp/"];
42
+ const isIgnored = (relPath) => IGNORED_PREFIXES.some((prefix) => relPath.startsWith(prefix));
43
+ const IMPORT_PATTERN = /^[ \t]*import[ \t]+(type[ \t]+)?([^"'`;]*?)[ \t\n]*from[ \t]*["']([^"']+)["']/gm;
44
+ const RUNTIME_IMPORT = /^\{\s*runtime\s*\}$/;
45
+ // A JSON module's only export is `default`, and a CSS module compiles to one,
46
+ // so for both the default import is the one form that works.
47
+ const DEFAULT_IMPORT = /^[A-Za-z_$][\w$]*$/;
48
+ const DEFAULT_ONLY_SPECIFIER = /\.(?:module\.css|json)$/;
49
+ const CROSS_RUNTIME_SPECIFIER = "@eserstack/standards/cross-runtime";
50
+ // A literal right after `||` is a default value; `a || b` between two
51
+ // expressions is left alone because it is often a real boolean condition.
52
+ const OR_DEFAULT_PATTERN = /\|\|\s*(?:["'`[{]|-?\d|null\b|undefined\b|new\s)/g;
53
+ // `export * from` and `export type * from`; `export * as name from` is a
54
+ // namespace re-export and stays allowed.
55
+ const EXPORT_STAR_PATTERN = /^[ \t]*export\s+(?:type\s+)?\*\s*from\s*["']([^"']+)["']/gm;
56
+ const isAllowedImport = (clause, specifier) => {
57
+ const trimmed = clause.trim();
58
+ if (/^\*\s+as\s+\w+$/.test(trimmed))
59
+ return true;
60
+ if (RUNTIME_IMPORT.test(trimmed) && specifier === CROSS_RUNTIME_SPECIFIER) {
61
+ return true;
62
+ }
63
+ if (DEFAULT_IMPORT.test(trimmed) && DEFAULT_ONLY_SPECIFIER.test(specifier)) {
64
+ return true;
65
+ }
66
+ // `import { type A, type B }` imports types only.
67
+ const named = trimmed.match(/^\{([\s\S]*)\}$/);
68
+ if (named !== null) {
69
+ const parts = named[1]
70
+ .split(",")
71
+ .map((p) => p.trim())
72
+ .filter((p) => p !== "");
73
+ return parts.length > 0 && parts.every((p) => p.startsWith("type "));
74
+ }
75
+ return false;
76
+ };
77
+ /** Finds convention violations in one TypeScript or JavaScript source. */
78
+ export const findViolations = (content) => {
79
+ const violations = [];
80
+ const mask = sourceMask.codeMask(content);
81
+ for (const match of content.matchAll(IMPORT_PATTERN)) {
82
+ const start = match.index + match[0].indexOf("import");
83
+ if (mask[start] === 1)
84
+ continue;
85
+ if (match[1] !== undefined)
86
+ continue; // import type { ... }
87
+ const clause = match[2];
88
+ const specifier = match[3];
89
+ if (isAllowedImport(clause, specifier))
90
+ continue;
91
+ violations.push({
92
+ rule: "namespace-import",
93
+ line: sourceMask.lineOf(content, start),
94
+ message: `import from "${specifier}" is not a namespace import; use \`import * as name from "${specifier}"\` (javascript-practices: Imports)`,
95
+ });
96
+ }
97
+ for (const match of content.matchAll(OR_DEFAULT_PATTERN)) {
98
+ if (mask[match.index] === 1)
99
+ continue;
100
+ violations.push({
101
+ rule: "or-default",
102
+ line: sourceMask.lineOf(content, match.index),
103
+ message: 'default value after `||` also replaces 0 and ""; use `??`, or an explicit check when an empty value must fall back too (javascript-practices: Explicit Checks)',
104
+ });
105
+ }
106
+ for (const match of content.matchAll(EXPORT_STAR_PATTERN)) {
107
+ const start = match.index + match[0].indexOf("export");
108
+ if (mask[start] === 1)
109
+ continue;
110
+ const specifier = match[1];
111
+ violations.push({
112
+ rule: "export-star",
113
+ line: sourceMask.lineOf(content, start),
114
+ message: `\`export * from "${specifier}"\` re-exports the whole module; export the names explicitly (\`export { name } from "${specifier}"\`) or as a namespace (\`export * as name from "${specifier}"\`) (javascript-practices: Avoid Re-exports)`,
115
+ });
116
+ }
117
+ return violations.sort((a, b) => a.line - b.line);
118
+ };
119
+ export const readBaseline = (file) => violationBaseline.readBaseline(file, RULES);
120
+ export const tool = fileTool.createFileTool({
121
+ name: TOOL_NAME,
122
+ description: "Detect non-namespace imports, `||` defaults and `export *` beyond the recorded baseline",
123
+ canFix: false,
124
+ stacks: ["javascript"],
125
+ defaults: { baseline: DEFAULT_BASELINE_PATH },
126
+ extensions: patterns.JS_FILE_EXTENSIONS,
127
+ checkAll: async (files, options) => {
128
+ const baseline = await readBaseline(violationBaseline.resolveBaselinePath(TOOL_NAME, options.root, options["baseline"]));
129
+ const found = await violationBaseline.collectViolations(options.root, files, findViolations, isIgnored);
130
+ return found.flatMap((file) => violationBaseline.issuesAboveBaseline(baseline, file));
131
+ },
132
+ });
133
+ /** Records every current violation as the new baseline. */
134
+ export const writeBaseline = async (root, baselineFile = DEFAULT_BASELINE_PATH) => {
135
+ const files = await shared.walkSourceFiles({
136
+ root,
137
+ extensions: patterns.JS_FILE_EXTENSIONS,
138
+ exclude: [],
139
+ });
140
+ const found = await violationBaseline.collectViolations(root, files, findViolations, isIgnored);
141
+ const baseline = violationBaseline.buildBaseline(RULES, found);
142
+ await violationBaseline.writeBaselineFile(violationBaseline.resolveBaselinePath(TOOL_NAME, root, baselineFile), baseline);
143
+ return violationBaseline.baselineTotal(baseline);
144
+ };
145
+ export const run = tool.run;
146
+ export const validator = tool.validator;
147
+ const writeBaselineMain = async () => {
148
+ const total = await writeBaseline(".");
149
+ const { output: out } = cliSupport.createCliContext();
150
+ out.writeln(`${TOOL_NAME}: baseline written with ${total} violation(s) to ${DEFAULT_BASELINE_PATH}`);
151
+ await out.flush();
152
+ return primitives.results.ok(undefined);
153
+ };
154
+ /**
155
+ * CLI entry: checks the tree, or with `--write-baseline` records the current
156
+ * violations as the new baseline.
157
+ */
158
+ export const main = async (cliArgs) => cliArgs?.includes("--write-baseline") === true
159
+ ? await writeBaselineMain()
160
+ : await tool.main(cliArgs);
161
+ if (import.meta.main) {
162
+ // Entry point: the await only runs when this file is executed directly.
163
+ // oxlint-disable-next-line node/no-top-level-await
164
+ const result = await main(standards.crossRuntime.runtime.process.args);
165
+ cliSupport.runCliMain(result);
166
+ }
@@ -0,0 +1,50 @@
1
+ import type * as shellArgs from "@eserstack/shell/args";
2
+ /**
3
+ * Options for commit message validation.
4
+ */
5
+ export type CommitMsgOptions = {
6
+ /** Allow `*` as a scope meaning "all packages". Default: true. */
7
+ readonly allowAsterisk?: boolean;
8
+ /** Allow comma-separated scopes like `feat(a,b): msg`. Default: true. */
9
+ readonly allowMultipleScopes?: boolean;
10
+ /** Require a scope. Default: false. */
11
+ readonly forceScope?: boolean;
12
+ /** Allowed commit types. Default: ci, chore, docs, feat, fix, perf, refactor, revert, test. */
13
+ readonly types?: readonly string[];
14
+ };
15
+ /**
16
+ * Result of validating a commit message.
17
+ */
18
+ export type CommitMsgResult = {
19
+ readonly valid: boolean;
20
+ readonly issues: readonly string[];
21
+ };
22
+ /**
23
+ * Validate a commit message against conventional commit format.
24
+ *
25
+ * The check is synchronous, so it uses the native validator only when the
26
+ * bridge has already loaded, and the TypeScript rules below otherwise. Await
27
+ * `ensureLib()` from `@eserstack/ajan/ffi/client` first to use the native one.
28
+ */
29
+ export declare const validateCommitMsg: (message: string, options?: CommitMsgOptions) => CommitMsgResult;
30
+ /**
31
+ * The TypeScript rules {@link validateCommitMsg} falls back to when the
32
+ * native library is not loaded. The Go validator implements the same rules;
33
+ * the parity test in go-validator-parity.test.ts keeps the two equal.
34
+ */
35
+ export declare const validateCommitMsgLocal: (message: string, options?: CommitMsgOptions) => CommitMsgResult;
36
+ /** The arguments of `eser codebase validate-commit-msg`. */
37
+ export type CommitMsgArgs = {
38
+ readonly help: boolean;
39
+ /** The `--message` (`-m`) text, or null when not given. */
40
+ readonly message: string | null;
41
+ /** The first positional, the commit message file, or null. */
42
+ readonly file: string | null;
43
+ };
44
+ /** Parse the validate-commit-msg arguments: `<file>`, `--message` (`-m`), `--help` (`-h`). */
45
+ export declare const parseCliArgs: (cliArgs?: readonly string[]) => CommitMsgArgs;
46
+ /**
47
+ * CLI entry point. Accepts a commit message file path as first argument
48
+ * (for use as git commit-msg hook) or --message flag.
49
+ */
50
+ export declare const main: (cliArgs?: readonly string[]) => Promise<shellArgs.CliResult<void>>;