@css-modules-kit/codegen 0.6.0 → 0.7.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.
package/src/runner.ts CHANGED
@@ -1,61 +1,18 @@
1
- import { readFile, rm } from 'node:fs/promises';
2
- import type {
3
- CMKConfig,
4
- CSSModule,
5
- Diagnostic,
6
- DiagnosticWithLocation,
7
- MatchesPattern,
8
- ParseCSSModuleResult,
9
- Resolver,
10
- } from '@css-modules-kit/core';
11
- import {
12
- checkCSSModule,
13
- createDts,
14
- createExportBuilder,
15
- createMatchesPattern,
16
- createResolver,
17
- getFileNamesByPattern,
18
- parseCSSModule,
19
- readConfigFile,
20
- } from '@css-modules-kit/core';
21
- import ts from 'typescript';
22
- import type { ParsedArgs } from './cli.js';
23
- import { writeDtsFile } from './dts-writer.js';
24
- import { ReadCSSModuleFileError } from './error.js';
1
+ import type { Stats } from 'node:fs';
2
+ import { rm } from 'node:fs/promises';
3
+ import chokidar, { type FSWatcher } from 'chokidar';
25
4
  import type { Logger } from './logger/logger.js';
5
+ import { createProject, type Project } from './project.js';
26
6
 
27
- /**
28
- * @throws {ReadCSSModuleFileError} When failed to read CSS Module file.
29
- */
30
- async function parseCSSModuleByFileName(fileName: string, config: CMKConfig): Promise<ParseCSSModuleResult> {
31
- let text: string;
32
- try {
33
- text = await readFile(fileName, 'utf-8');
34
- } catch (error) {
35
- throw new ReadCSSModuleFileError(fileName, error);
36
- }
37
- return parseCSSModule(text, { fileName, safe: false, keyframes: config.keyframes });
7
+ interface RunnerArgs {
8
+ project: string;
9
+ clean: boolean;
38
10
  }
39
11
 
40
- /**
41
- * @throws {WriteDtsFileError}
42
- */
43
- async function writeDtsByCSSModule(
44
- cssModule: CSSModule,
45
- { dtsOutDir, basePath, arbitraryExtensions, namedExports, prioritizeNamedImports }: CMKConfig,
46
- resolver: Resolver,
47
- matchesPattern: MatchesPattern,
48
- ): Promise<void> {
49
- const dts = createDts(
50
- cssModule,
51
- { resolver, matchesPattern },
52
- { namedExports, prioritizeNamedImports, forTsPlugin: false },
53
- );
54
- await writeDtsFile(dts.text, cssModule.fileName, {
55
- outDir: dtsOutDir,
56
- basePath,
57
- arbitraryExtensions,
58
- });
12
+ export interface Watcher {
13
+ /** Exported for testing purposes */
14
+ project: Project;
15
+ close(): Promise<void>;
59
16
  }
60
17
 
61
18
  /**
@@ -63,70 +20,144 @@ async function writeDtsByCSSModule(
63
20
  * @param project The absolute path to the project directory or the path to `tsconfig.json`.
64
21
  * @throws {ReadCSSModuleFileError} When failed to read CSS Module file.
65
22
  * @throws {WriteDtsFileError}
23
+ * @returns Whether the process succeeded without errors.
66
24
  */
67
- export async function runCMK(args: ParsedArgs, logger: Logger): Promise<void> {
68
- const config = readConfigFile(args.project);
69
- if (config.diagnostics.length > 0) {
70
- logger.logDiagnostics(config.diagnostics);
71
- // eslint-disable-next-line n/no-process-exit
72
- process.exit(1);
25
+ export async function runCMK(args: RunnerArgs, logger: Logger): Promise<boolean> {
26
+ const project = createProject(args);
27
+ if (args.clean) {
28
+ await rm(project.config.dtsOutDir, { recursive: true, force: true });
73
29
  }
30
+ await project.emitDtsFiles();
31
+ const diagnostics = project.getDiagnostics();
32
+ if (diagnostics.length > 0) {
33
+ logger.logDiagnostics(diagnostics);
34
+ return false;
35
+ }
36
+ return true;
37
+ }
74
38
 
75
- const getCanonicalFileName = (fileName: string) =>
76
- ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
77
- const moduleResolutionCache = ts.createModuleResolutionCache(
78
- config.basePath,
79
- getCanonicalFileName,
80
- config.compilerOptions,
81
- );
82
- const resolver = createResolver(config.compilerOptions, moduleResolutionCache);
83
- const matchesPattern = createMatchesPattern(config);
84
-
85
- const cssModuleMap = new Map<string, CSSModule>();
86
- const syntacticDiagnostics: DiagnosticWithLocation[] = [];
39
+ /**
40
+ * Run css-modules-kit .d.ts generation in watch mode.
41
+ *
42
+ * The promise resolves when the initial diagnostics report, emit, and watcher initialization are complete.
43
+ * Errors are reported through the logger.
44
+ *
45
+ * NOTE: For implementation simplicity, config file changes are not watched.
46
+ * @param project The absolute path to the project directory or the path to `tsconfig.json`.
47
+ * @throws {TsConfigFileNotFoundError}
48
+ * @throws {ReadCSSModuleFileError}
49
+ * @throws {WriteDtsFileError}
50
+ */
51
+ export async function runCMKInWatchMode(args: RunnerArgs, logger: Logger): Promise<Watcher> {
52
+ const fsWatchers: FSWatcher[] = [];
53
+ const project = createProject(args);
54
+ let emitAndReportDiagnosticsTimer: NodeJS.Timeout | undefined = undefined;
87
55
 
88
- const fileNames = getFileNamesByPattern(config);
89
- if (fileNames.length === 0) {
90
- logger.logDiagnostics([
91
- {
92
- category: 'warning',
93
- text: `The file specified in tsconfig.json not found.`,
94
- },
95
- ]);
96
- return;
97
- }
98
- const parseResults = await Promise.all(fileNames.map(async (fileName) => parseCSSModuleByFileName(fileName, config)));
99
- for (const parseResult of parseResults) {
100
- cssModuleMap.set(parseResult.cssModule.fileName, parseResult.cssModule);
101
- syntacticDiagnostics.push(...parseResult.diagnostics);
56
+ if (args.clean) {
57
+ await rm(project.config.dtsOutDir, { recursive: true, force: true });
102
58
  }
59
+ await emitAndReportDiagnostics();
60
+
61
+ // Watch project files and report diagnostics on changes
62
+ const readyPromises: Promise<void>[] = [];
63
+ for (const wildcardDirectory of project.config.wildcardDirectories) {
64
+ const { promise, resolve } = promiseWithResolvers<void>();
65
+ readyPromises.push(promise);
66
+ fsWatchers.push(
67
+ chokidar
68
+ .watch(wildcardDirectory.fileName, {
69
+ ignored: (fileName: string, stats?: Stats) => {
70
+ // The ignored function is called twice for the same path. The first time with stats undefined,
71
+ // and the second time with stats provided.
72
+ // In the first call, we can't determine if the path is a directory or file.
73
+ // So we include it in the watch target considering it might be a directory.
74
+ if (!stats) return false;
103
75
 
104
- if (syntacticDiagnostics.length > 0) {
105
- logger.logDiagnostics(syntacticDiagnostics);
106
- // eslint-disable-next-line n/no-process-exit
107
- process.exit(1);
76
+ // In the second call, we include directories or files that match wildcards in the watch target.
77
+ // However, `dtsOutDir` is excluded from the watch target.
78
+ if (stats.isDirectory()) {
79
+ return fileName === project.config.dtsOutDir;
80
+ } else {
81
+ return !project.isWildcardMatchedFile(fileName);
82
+ }
83
+ },
84
+ ignoreInitial: true,
85
+ ...(wildcardDirectory.recursive ? {} : { depth: 0 }),
86
+ })
87
+ .on('add', (fileName) => {
88
+ try {
89
+ project.addFile(fileName);
90
+ } catch (e) {
91
+ logger.logError(e);
92
+ return;
93
+ }
94
+ scheduleEmitAndReportDiagnostics();
95
+ })
96
+ .on('change', (fileName) => {
97
+ try {
98
+ project.updateFile(fileName);
99
+ } catch (e) {
100
+ logger.logError(e);
101
+ return;
102
+ }
103
+ scheduleEmitAndReportDiagnostics();
104
+ })
105
+ .on('unlink', (fileName: string) => {
106
+ project.removeFile(fileName);
107
+ scheduleEmitAndReportDiagnostics();
108
+ })
109
+ .on('error', (e) => logger.logError(e))
110
+ .on('ready', () => resolve()),
111
+ );
108
112
  }
113
+ await Promise.all(readyPromises);
114
+
115
+ function scheduleEmitAndReportDiagnostics() {
116
+ // Switching between git branches results in numerous file changes occurring rapidly.
117
+ // Reporting diagnostics for each file change would overwhelm users.
118
+ // Therefore, we batch the processing.
109
119
 
110
- const getCSSModule = (path: string) => cssModuleMap.get(path);
111
- const exportBuilder = createExportBuilder({ getCSSModule, matchesPattern, resolver });
112
- const semanticDiagnostics: Diagnostic[] = [];
113
- for (const { cssModule } of parseResults) {
114
- const diagnostics = checkCSSModule(cssModule, config, exportBuilder, matchesPattern, resolver, getCSSModule);
115
- semanticDiagnostics.push(...diagnostics);
120
+ if (emitAndReportDiagnosticsTimer !== undefined) clearTimeout(emitAndReportDiagnosticsTimer);
121
+
122
+ emitAndReportDiagnosticsTimer = setTimeout(() => {
123
+ emitAndReportDiagnosticsTimer = undefined;
124
+ emitAndReportDiagnostics().catch(logger.logError.bind(logger));
125
+ }, 250);
116
126
  }
117
127
 
118
- if (semanticDiagnostics.length > 0) {
119
- logger.logDiagnostics(semanticDiagnostics);
120
- // eslint-disable-next-line n/no-process-exit
121
- process.exit(1);
128
+ /**
129
+ * @throws {WriteDtsFileError}
130
+ */
131
+ async function emitAndReportDiagnostics() {
132
+ logger.clearScreen();
133
+ await project.emitDtsFiles();
134
+ const diagnostics = project.getDiagnostics();
135
+ if (diagnostics.length > 0) {
136
+ logger.logDiagnostics(diagnostics);
137
+ }
138
+ logger.logMessage(
139
+ `Found ${diagnostics.length} error${diagnostics.length === 1 ? '' : 's'}. Watching for file changes.`,
140
+ { time: true },
141
+ );
122
142
  }
123
143
 
124
- if (args.clean) {
125
- await rm(config.dtsOutDir, { recursive: true, force: true });
144
+ async function close() {
145
+ await Promise.all(fsWatchers.map(async (watcher) => watcher.close()));
126
146
  }
127
- await Promise.all(
128
- parseResults.map(async (parseResult) =>
129
- writeDtsByCSSModule(parseResult.cssModule, config, resolver, matchesPattern),
130
- ),
131
- );
147
+
148
+ return { project, close };
149
+ }
150
+
151
+ function promiseWithResolvers<T>() {
152
+ let resolve;
153
+ let reject;
154
+ const promise = new Promise<T>((res, rej) => {
155
+ resolve = res;
156
+ reject = rej;
157
+ });
158
+ return {
159
+ promise,
160
+ resolve: resolve as unknown as (value: T) => void,
161
+ reject: reject as unknown as (reason?: unknown) => void,
162
+ };
132
163
  }