-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
446 lines (374 loc) · 13.6 KB
/
index.ts
File metadata and controls
446 lines (374 loc) · 13.6 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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
#!/usr/bin/env node
import { join, relative } from 'node:path'
import type { Logger as ReactCompilerLogger } from 'babel-plugin-react-compiler'
import { parseArgs } from './args.js'
import * as babel from './babel.js'
import { loadConfig } from './config.js'
import type { FileErrors } from './records-file.js'
import * as recordsFile from './records-file.js'
import * as sourceFiles from './source-files.js'
import { pluralize } from './utils.js'
const compilerErrors: Map<string, FileErrors> = new Map()
type ErrorDetailWithCount = {
kind: 'CompileError' | 'CompileSkip' | 'PipelineError'
line: number | null
reason: string
count: number
}
const compilerErrorDetails: Map<string, Map<string, ErrorDetailWithCount>> = new Map()
const customReactCompilerLogger: ReactCompilerLogger = {
logEvent: (filename, event) => {
if (!filename) return
const relativePath = relative(process.cwd(), filename)
if (
event.kind === 'CompileError' ||
event.kind === 'CompileSkip' ||
event.kind === 'PipelineError'
) {
const current = compilerErrors.get(relativePath) || {}
current[event.kind] = (current[event.kind] ?? 0) + 1
compilerErrors.set(relativePath, current)
let line: number | null
let reason: string
if (event.kind === 'CompileError') {
// Use primaryLocation() for precise error location, fall back to fnLoc
// primaryLocation() may return a symbol (GeneratedSource), so check for object
const loc = event.detail.primaryLocation()
line =
(loc && typeof loc === 'object' ? loc.start.line : null) ??
event.fnLoc?.start.line ??
null
reason = event.detail.reason
} else if (event.kind === 'CompileSkip') {
// CompileSkip has its own loc field for the precise location
line = event.loc?.start.line ?? event.fnLoc?.start.line ?? null
reason = event.reason
} else {
// PipelineError only has fnLoc
line = event.fnLoc?.start.line ?? null
reason = String(event.data)
}
const detailsMap = compilerErrorDetails.get(relativePath) || new Map()
const errorKey = `${line}|${reason}`
const existing = detailsMap.get(errorKey)
if (existing) {
existing.count += 1
} else {
detailsMap.set(errorKey, { kind: event.kind, line, reason, count: 1 })
}
compilerErrorDetails.set(relativePath, detailsMap)
}
},
}
main().catch(console.error)
async function main() {
const config = loadConfig()
const { command, filePaths: filePathParams, showErrors } = parseArgs(process.argv.slice(2))
try {
switch (command) {
case 'stage-record-file': {
const filePaths = sourceFiles.filterByGlob({
filePaths: sourceFiles.normalizeFilePaths(filePathParams),
globPattern: config.sourceGlob,
})
return await runStageRecords({
filePaths,
recordsFilePath: config.recordsFile,
showErrors,
})
}
case 'overwrite': {
return await runOverwriteRecords({
sourceGlob: config.sourceGlob,
recordsFilePath: config.recordsFile,
showErrors,
})
}
case 'check-files': {
const filePaths = sourceFiles.filterByGlob({
filePaths: sourceFiles.normalizeFilePaths(filePathParams),
globPattern: config.sourceGlob,
})
sourceFiles.validateFilesExist(filePaths)
return await runCheckFiles({
filePaths,
recordsFilePath: config.recordsFile,
showErrors,
})
}
default: {
return await runCheckAllFiles({ sourceGlob: config.sourceGlob, showErrors })
}
}
} catch (error: unknown) {
if (error instanceof Error) {
exitWithError(error.message)
} else {
exitWithError('Failed to compile files')
}
}
}
/**
* Handles the `--overwrite` flag by re-recording errors across all files.
*/
async function runOverwriteRecords({
sourceGlob,
recordsFilePath,
showErrors,
}: {
sourceGlob: string
recordsFilePath: string
showErrors: boolean
}) {
const filePaths = sourceFiles.getAll({
globPattern: sourceGlob,
})
if (!filePaths.length) {
exitWithWarning('No files to check')
}
console.log(
`🔍 Checking all ${filePaths.length} source files for React Compiler errors and recreating records…`,
)
//
// Compile files and update `compilerErrors` with `customReactCompilerLogger`
//
await babel.compileFiles({
filePaths,
customReactCompilerLogger: customReactCompilerLogger,
})
//
// Overwrite records file
//
recordsFile.save({
filePaths,
recordsPath: recordsFilePath,
compilerErrors: Object.fromEntries(compilerErrors.entries()),
records: null,
})
//
// Report error stats
//
const totalErrors = getErrorCount()
if (totalErrors > 0) {
let message = `✅ Records saved to ${recordsFilePath}. Found ${totalErrors} total React Compiler issues across ${compilerErrors.size} files`
if (showErrors) {
message += '\n\nErrors:'
message += formatErrorDetails()
}
console.log(message)
} else {
console.log(`🎉 Records saved to ${recordsFilePath}. No React Compiler errors found`)
}
}
/**
* Handles the `--stage-record-file` flag by checking provided files and updating the records file.
*
* If errors have increased, the process will exit with code 1 and the records file will not be updated.
* Deleted files are automatically detected by checking which recorded files no longer exist on disk.
*/
async function runStageRecords({
filePaths,
recordsFilePath,
showErrors,
}: {
filePaths: string[]
recordsFilePath: string
showErrors: boolean
}) {
const records = recordsFile.load(recordsFilePath)
const recordedFilePaths = records ? Object.keys(records.files) : []
const { deleted: deletedFromRecords } = sourceFiles.partitionByExistence(recordedFilePaths)
const { existing: existingFilePaths, deleted: deletedFromInput } =
sourceFiles.partitionByExistence(filePaths)
const allDeletedFilePaths = [...new Set([...deletedFromRecords, ...deletedFromInput])]
const allFilePaths = [...new Set([...filePaths, ...deletedFromRecords])]
if (!allFilePaths.length) {
console.log('✅ No files to check')
return
}
if (allDeletedFilePaths.length > 0) {
const deletedFileWord = pluralize(allDeletedFilePaths.length, 'file', 'files')
const fileList = allDeletedFilePaths.map((f) => ` • ${f}`).join('\n')
console.log(
`🗑️ Removing ${allDeletedFilePaths.length} deleted ${deletedFileWord} from records:\n${fileList}`,
)
}
if (!existingFilePaths.length) {
console.log('📁 No existing files to check.')
} else {
const fileWord = pluralize(existingFilePaths.length, 'file', 'files')
console.log(
`🔍 Checking ${existingFilePaths.length} ${fileWord} for React Compiler errors and updating records…`,
)
}
//
// Compile only existing files and update `compilerErrors` with `customReactCompilerLogger`
//
await babel.compileFiles({
filePaths: existingFilePaths,
customReactCompilerLogger: customReactCompilerLogger,
})
checkErrorChanges({ filePaths: existingFilePaths, recordsFilePath, records, showErrors })
//
// Update and stage records file (includes deleted files so they get removed from records)
//
recordsFile.save({
filePaths: allFilePaths,
recordsPath: recordsFilePath,
compilerErrors: Object.fromEntries(compilerErrors.entries()),
records: records?.files ?? null,
})
const recordsFileRelativePath = join(process.cwd(), recordsFilePath)
try {
recordsFile.stage(recordsFileRelativePath)
} catch {
exitWithWarning(`Failed to stage records file at ${recordsFileRelativePath}`)
}
console.log(`✅ Records saved to ${recordsFilePath}. No new React Compiler errors`)
}
/**
* Handles the `--check-files` flag by checking the files passed as arguments.
*
* If errors have increased, the process will exit with code 1.
*/
async function runCheckFiles({
filePaths,
recordsFilePath,
showErrors,
}: {
filePaths: string[]
recordsFilePath: string
showErrors: boolean
}) {
if (!filePaths.length) {
console.log('✅ No files to check')
return
}
const fileWord = pluralize(filePaths.length, 'file', 'files')
console.log(`🔍 Checking ${filePaths.length} ${fileWord} for React Compiler errors…`)
//
// Compile files and update `compilerErrors` with `customReactCompilerLogger`
//
await babel.compileFiles({
filePaths: filePaths,
customReactCompilerLogger: customReactCompilerLogger,
})
checkErrorChanges({ filePaths, recordsFilePath, showErrors })
console.log('✅ No new React Compiler errors in checked files')
}
/**
* Handles the no flag case by checking all files and reporting the total number of errors.
*
* The records file is not updated.
*/
async function runCheckAllFiles({
sourceGlob,
showErrors,
}: {
sourceGlob: string
showErrors: boolean
}) {
const filePaths = sourceFiles.getAll({
globPattern: sourceGlob,
})
if (!filePaths.length) {
exitWithWarning('No files to check')
}
console.log(`🔍 Checking all ${filePaths.length} source files for React Compiler errors…`)
//
// Compile files and update `compilerErrors` with `customReactCompilerLogger`
//
await babel.compileFiles({
filePaths,
customReactCompilerLogger: customReactCompilerLogger,
})
//
// Report error stats
//
const totalErrors = getErrorCount()
if (totalErrors > 0) {
let message = `Found ${totalErrors} React Compiler issues across ${compilerErrors.size} files`
if (showErrors) {
message += '\n\nErrors:'
message += formatErrorDetails()
}
exitWithWarning(message)
}
console.log('🎉 No React Compiler errors found')
}
function getErrorCount() {
return Array.from(compilerErrors.values()).reduce(
(sum, errors) => sum + Object.values(errors).reduce((a, b) => a + b, 0),
0,
)
}
function formatErrorDetails(filePaths?: string[]): string {
let result = ''
for (const [filePath, detailsMap] of compilerErrorDetails) {
if (filePaths && !filePaths.includes(filePath)) continue
for (const detail of detailsMap.values()) {
const lineInfo = detail.line ? `Line ${detail.line}` : 'Unknown location'
const countSuffix = detail.count > 1 ? ` (x${detail.count})` : ''
result += `\n - ${filePath}: ${lineInfo}: ${detail.reason}${countSuffix}`
}
}
return result
}
/**
* Compare error changes between the existing records and errors captured during this session in `compilerErrors`.
* If errors have increased, exit with an error message.
* If errors have decreased, report the good news.
*/
function checkErrorChanges({
filePaths,
recordsFilePath,
records: providedRecords,
showErrors,
}: {
filePaths: string[]
recordsFilePath: string
records?: recordsFile.Records | null
showErrors: boolean
}) {
const records = providedRecords ?? recordsFile.load(recordsFilePath)
const { increases, decreases } = recordsFile.getErrorChanges({
filePaths,
existingRecords: records?.files ?? {},
newRecords: Object.fromEntries(compilerErrors.entries()),
})
const increaseEntries = Object.entries(increases)
// Report decreases first so users see their progress even if there are also increases
const decreaseEntries = Object.entries(decreases)
if (decreaseEntries.length) {
const decreaseList = decreaseEntries.map(
([filePath, count]) => ` • ${filePath}: -${count}`,
)
console.log(`🎉 React Compiler errors have decreased in:\n${decreaseList.join('\n')}`)
if (increaseEntries.length) {
console.log() // blank line separator
}
}
// Show detailed errors for all checked files if requested
if (showErrors) {
const errorDetails = formatErrorDetails(filePaths)
if (errorDetails) {
console.log(`Errors:${errorDetails}`)
}
}
// Report increases (exit with error)
if (increaseEntries.length) {
const errorList = increaseEntries.map(([filePath, count]) => ` • ${filePath}: +${count}`)
let errorMessage = `React Compiler errors have increased in:\n${errorList.join('\n')}`
errorMessage += '\n\nPlease fix the errors and run the command again.'
exitWithError(errorMessage)
}
return records
}
function exitWithWarning(message: string): never {
console.warn(`⚠️ ${message}`)
process.exit(0)
}
function exitWithError(message: string): never {
console.error(`❌ ${message}`)
process.exit(1)
}