-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathvalidate-export-names.ts
More file actions
281 lines (244 loc) · 7.16 KB
/
validate-export-names.ts
File metadata and controls
281 lines (244 loc) · 7.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
/**
* Export naming convention checker.
*
* Validates that export paths in deno.json follow kebab-case convention.
*
* Library usage:
* ```typescript
* import * as exportNames from "@eserstack/codebase/validate-export-names";
*
* const result = await exportNames.checkExportNames();
* if (!result.isValid) {
* console.log("Violations:", result.violations);
* }
* ```
*
* CLI usage:
* deno run --allow-all ./validate-export-names.ts
*
* @module
*/
import * as primitives from "@eserstack/primitives";
import * as functions from "@eserstack/functions";
import * as standards from "@eserstack/standards";
import type * as shellArgs from "@eserstack/shell/args";
import * as span from "@eserstack/streams/span";
import * as workspaceDiscovery from "./workspace-discovery.ts";
import { createCliOutput, runCliMain } from "./cli-support.ts";
const out = createCliOutput();
/**
* Options for export name checking.
*/
export type CheckExportNamesOptions = {
/** Root directory (default: ".") */
readonly root?: string;
/** Words to ignore in kebab-case validation */
readonly ignoreWords?: string[];
};
/**
* Information about a naming violation.
*/
export type ExportNameViolation = {
/** Package name */
readonly packageName: string;
/** Export path that violates convention */
readonly exportPath: string;
/** Suggested fix */
readonly suggestion: string;
};
/**
* Result of export name check.
*/
export type CheckExportNamesResult = {
/** Whether all export names are valid */
readonly isValid: boolean;
/** Naming violations */
readonly violations: ExportNameViolation[];
/** Number of packages checked */
readonly packagesChecked: number;
};
/**
* Converts a string to kebab-case.
*
* @param str - String to convert
* @returns Kebab-case string
*/
const toKebabCase = (str: string): string => {
return str
.replace(/([a-z])([A-Z])/g, "$1-$2")
.replace(/[_\s]+/g, "-")
.toLowerCase();
};
/**
* Checks if a string is in kebab-case.
*
* @param str - String to check
* @param ignoreWords - Words to ignore
* @returns Whether the string is kebab-case
*/
const isKebabCase = (str: string, ignoreWords: string[] = []): boolean => {
// Check each path segment
const segments = str.split("/").filter((s) => s.length > 0);
for (const segment of segments) {
// Skip the leading dot for relative paths
let cleanSegment = segment.startsWith(".") ? segment.slice(1) : segment;
if (cleanSegment.length === 0) {
continue;
}
// Strip file extension using path helpers (language-agnostic)
const ext = standards.crossRuntime.runtime.path.extname(cleanSegment);
if (ext.length > 0) {
cleanSegment = cleanSegment.slice(0, -ext.length);
}
if (cleanSegment.length === 0) {
continue;
}
// Check if it's an ignored word
if (ignoreWords.includes(cleanSegment)) {
continue;
}
// Check for kebab-case pattern: lowercase letters, numbers, and hyphens
if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(cleanSegment)) {
return false;
}
}
return true;
};
/**
* Checks export naming conventions for all workspace packages.
*
* @param options - Check options
* @returns Check result
*/
export const checkExportNames = async (
options: CheckExportNamesOptions = {},
): Promise<CheckExportNamesResult> => {
const { root = ".", ignoreWords = [] } = options;
const packages = await workspaceDiscovery.discoverPackages(root);
const violations: ExportNameViolation[] = [];
for (const pkg of packages) {
const exports = pkg.config.exports?.value;
if (exports === null || exports === undefined) {
continue;
}
if (typeof exports === "string") {
// Single export, check the path
if (!isKebabCase(exports, ignoreWords)) {
violations.push({
packageName: pkg.name,
exportPath: exports,
suggestion: toKebabCase(exports),
});
}
continue;
}
if (exports !== null && typeof exports === "object") {
for (const [key, value] of Object.entries(exports)) {
// Check the export key (e.g., "./myModule")
if (!isKebabCase(key, ignoreWords)) {
violations.push({
packageName: pkg.name,
exportPath: key,
suggestion: toKebabCase(key),
});
}
// Check the export value (file path)
if (typeof value === "string" && !isKebabCase(value, ignoreWords)) {
violations.push({
packageName: pkg.name,
exportPath: value,
suggestion: toKebabCase(value),
});
}
}
}
}
return {
isValid: violations.length === 0,
violations,
packagesChecked: packages.length,
};
};
// --- Handler ---
/**
* Handler wrapping checkExportNames as a Task.
*/
export const checkExportNamesHandler: functions.handler.Handler<
CheckExportNamesOptions,
CheckExportNamesResult,
Error
> = (input) => functions.task.fromPromise(() => checkExportNames(input));
// --- CLI Adapter ---
/**
* Adapter that produces default CheckExportNamesOptions from a CLI event.
*/
const cliAdapter: functions.handler.Adapter<
functions.triggers.CliEvent,
CheckExportNamesOptions
> = (
_event,
) => primitives.results.ok({ root: "." });
// --- CLI ResponseMapper ---
/**
* Maps the handler result to CLI output.
*/
const cliResponseMapper: functions.handler.ResponseMapper<
CheckExportNamesResult,
Error | functions.handler.AdaptError,
shellArgs.CliResult<void>
> = (result) => {
if (primitives.results.isFail(result)) {
out.writeln(span.red("✗"), span.text(" " + String(result.error)));
return primitives.results.fail({ exitCode: 1 });
}
const { value } = result;
out.writeln(
span.blue("ℹ"),
span.text(` Checked ${value.packagesChecked} packages.`),
);
if (!value.isValid) {
out.writeln(
span.red("✗"),
span.text(
` Found ${value.violations.length} naming violations:`,
),
);
for (const violation of value.violations) {
out.writeln(span.yellow("⚠"), span.text(" " + violation.packageName));
out.writeln(
span.blue("ℹ"),
span.text(` Export: ${violation.exportPath}`),
);
out.writeln(
span.blue("ℹ"),
span.text(` Suggestion: ${violation.suggestion}`),
);
}
return primitives.results.fail({ exitCode: 1 });
}
out.writeln(
span.green("✓"),
span.text(" All export names follow conventions."),
);
return primitives.results.ok(undefined);
};
// --- CLI Trigger ---
/**
* CLI trigger for check-export-names.
*/
export const handleCli: (
event: functions.triggers.CliEvent,
) => Promise<shellArgs.CliResult<void>> = functions.handler.createTrigger({
handler: checkExportNamesHandler,
adaptInput: cliAdapter,
adaptOutput: cliResponseMapper,
});
/** CLI entry point for dispatcher compatibility. */
export const main = async (
_cliArgs?: readonly string[],
): Promise<shellArgs.CliResult<void>> =>
await handleCli({ command: "validate-export-names", args: [], flags: {} });
if (import.meta.main) {
runCliMain(await main(), out);
}