-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.mjs
More file actions
505 lines (437 loc) · 13.3 KB
/
main.mjs
File metadata and controls
505 lines (437 loc) · 13.3 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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
/**
* @fileoverview Unified test runner that provides a smooth, single-script experience.
* Combines check, build, and test steps with clean, consistent output.
*/
import { spawn } from 'node:child_process'
import { existsSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import process from 'node:process'
import { getDefaultLogger } from '@socketsecurity/lib-stable/logger'
import { getDefaultSpinner } from '@socketsecurity/lib-stable/spinner'
import { printHeader } from '@socketsecurity/lib-stable/stdio/header'
import { getTestsToRun } from '../utils/changed-test-mapper.mjs'
import { parseArgs } from '../utils/parse-args.mjs'
import { onExit } from '../utils/signal-exit.mjs'
const logger = getDefaultLogger()
const spinner = getDefaultSpinner()
const WIN32 = process.platform === 'win32'
// Suppress non-fatal worker termination unhandled rejections
process.on('unhandledRejection', (reason, _promise) => {
const errorMessage = String(reason?.message || reason || '')
// Filter out known non-fatal worker termination errors
if (
errorMessage.includes('Terminating worker thread') ||
errorMessage.includes('ThreadTermination')
) {
// Ignore these - they're cleanup messages from vitest worker threads
return
}
// Re-throw other unhandled rejections
throw reason
})
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const rootPath = path.resolve(__dirname, '../..')
const nodeModulesBinPath = path.join(rootPath, 'node_modules', '.bin')
const tsconfigPath = '.config/tsconfig.check.json'
// Track running processes for cleanup
const runningProcesses = new Set()
// Setup exit handler
const removeExitHandler = onExit((_code, signal) => {
// Stop spinner first
try {
spinner.stop()
} catch {}
// Kill all running processes
for (const child of runningProcesses) {
try {
child.kill('SIGTERM')
} catch {}
}
if (signal) {
logger.log(`\nReceived ${signal}, cleaning up...`)
// Let onExit handle the exit with proper code
process.exitCode = 128 + (signal === 'SIGINT' ? 2 : 15)
}
})
async function runCommand(command, args = [], options = {}) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
stdio: 'inherit',
...(process.platform === 'win32' && { shell: true }),
...options,
})
runningProcesses.add(child)
child.on('exit', code => {
runningProcesses.delete(child)
resolve(code || 0)
})
child.on('error', error => {
runningProcesses.delete(child)
reject(error)
})
})
}
async function runCommandWithOutput(command, args = [], options = {}) {
return new Promise((resolve, reject) => {
let stdout = ''
let stderr = ''
const child = spawn(command, args, {
...(process.platform === 'win32' && { shell: true }),
...options,
})
runningProcesses.add(child)
if (child.stdout) {
child.stdout.on('data', data => {
stdout += data.toString()
})
}
if (child.stderr) {
child.stderr.on('data', data => {
stderr += data.toString()
})
}
child.on('exit', code => {
runningProcesses.delete(child)
resolve({ code: code || 0, stdout, stderr })
})
child.on('error', error => {
runningProcesses.delete(child)
reject(error)
})
})
}
async function runCheck() {
logger.step('Running checks')
// Run fix (auto-format) quietly since it has its own output
spinner.start('Formatting code...')
let exitCode = await runCommand('pnpm', ['run', 'fix'], {
stdio: 'pipe',
})
if (exitCode !== 0) {
spinner.stop()
logger.error('Formatting failed')
// Re-run with output to show errors
await runCommand('pnpm', ['run', 'fix'])
return exitCode
}
spinner.stop()
logger.success('Code formatted')
// Run oxlint to check for remaining issues
spinner.start('Running oxlint...')
exitCode = await runCommand('oxlint', ['.'], {
stdio: 'pipe',
})
if (exitCode !== 0) {
spinner.stop()
logger.error('oxlint failed')
// Re-run with output to show errors
await runCommand('oxlint', ['.'])
return exitCode
}
spinner.stop()
logger.success('oxlint passed')
// Run TypeScript check
spinner.start('Checking TypeScript...')
exitCode = await runCommand('tsgo', ['--noEmit', '-p', tsconfigPath], {
stdio: 'pipe',
})
if (exitCode !== 0) {
spinner.stop()
logger.error('TypeScript check failed')
// Re-run with output to show errors
await runCommand('tsgo', ['--noEmit', '-p', tsconfigPath])
return exitCode
}
spinner.stop()
logger.success('TypeScript check passed')
return exitCode
}
async function runBuild() {
const distIndexPath = path.join(rootPath, 'dist', 'index.js')
if (!existsSync(distIndexPath)) {
logger.step('Building project')
return runCommand('pnpm', ['run', 'build'])
}
return 0
}
async function runTests(
options,
positionals = [],
configPath = '.config/vitest.config.mts',
) {
const { all, coverage, force, staged, update } = options
const runAll = all || force
// Get tests to run
const testInfo = getTestsToRun({ staged, all: runAll })
const { mode, reason, tests: testsToRun } = testInfo
// No tests needed
if (testsToRun == null) {
logger.substep('No relevant changes detected, skipping tests')
return 0
}
// Prepare vitest command
const vitestCmd = WIN32 ? 'vitest.cmd' : 'vitest'
const vitestPath = path.join(nodeModulesBinPath, vitestCmd)
const vitestArgs = ['--config', configPath, 'run']
// Add coverage if requested
if (coverage) {
vitestArgs.push('--coverage')
}
// Add update if requested
if (update) {
vitestArgs.push('--update')
}
// Add test patterns if not running all
if (testsToRun === 'all') {
logger.step(`Running all tests (${reason})`)
} else {
const modeText = mode === 'staged' ? 'staged' : 'changed'
logger.step(`Running tests for ${modeText} files:`)
testsToRun.forEach(test => {
logger.substep(test)
})
vitestArgs.push(...testsToRun)
}
// Add any additional positional arguments
if (positionals.length > 0) {
vitestArgs.push(...positionals)
}
// Build NODE_OPTIONS with deduplication to avoid conflicts
const existingOpts = (process.env.NODE_OPTIONS || '')
.split(/\s+/)
.filter(Boolean)
// Remove existing max-old-space-size to avoid conflicts
const filteredOpts = existingOpts.filter(
opt => !opt.startsWith('--max-old-space-size'),
)
const maxOldSpace = process.env.CI ? 8192 : 4096
const nodeOptions = [
...filteredOpts,
`--max-old-space-size=${maxOldSpace}`,
'--unhandled-rejections=warn',
].join(' ')
const spawnOptions = {
cwd: rootPath,
env: {
...process.env,
NODE_OPTIONS: nodeOptions,
VITEST: '1',
},
stdio: 'inherit',
}
// Use interactive runner for interactive Ctrl+O experience when appropriate
if (process.stdout.isTTY) {
const { runTests } = await import('../utils/interactive-runner.mjs')
return runTests(vitestPath, vitestArgs, {
env: spawnOptions.env,
cwd: spawnOptions.cwd,
verbose: false,
})
}
// Fallback to execution with output capture to handle worker termination errors
const result = await runCommandWithOutput(vitestPath, vitestArgs, {
...spawnOptions,
stdio: ['inherit', 'pipe', 'pipe'],
})
// Print output
if (result.stdout) {
process.stdout.write(result.stdout)
}
if (result.stderr) {
process.stderr.write(result.stderr)
}
// Check if we have worker termination error but no test failures
const hasWorkerTerminationError =
(result.stdout + result.stderr).includes('Terminating worker thread') ||
(result.stdout + result.stderr).includes('ThreadTermination')
const output = result.stdout + result.stderr
const hasTestFailures =
output.includes('FAIL') ||
(output.includes('Test Files') && output.match(/(\d+) failed/) !== null) ||
(output.includes('Tests') && output.match(/Tests\s+\d+ failed/) !== null)
// Override exit code if we only have worker termination errors
if (result.code !== 0 && hasWorkerTerminationError && !hasTestFailures) {
return 0
}
return result.code
}
async function runIsolatedTests(options) {
const { coverage } = options
logger.step('Running isolated tests')
// Prepare vitest command
const vitestCmd = WIN32 ? 'vitest.cmd' : 'vitest'
const vitestPath = path.join(nodeModulesBinPath, vitestCmd)
const vitestArgs = ['--config', '.config/vitest.config.isolated.mts', 'run']
// Add coverage if requested
if (coverage) {
vitestArgs.push('--coverage')
}
const spawnOptions = {
cwd: rootPath,
env: {
...process.env,
NODE_OPTIONS: [
...(process.env.NODE_OPTIONS || '')
.split(/\s+/)
.filter(opt => opt && !opt.startsWith('--max-old-space-size')),
`--max-old-space-size=${process.env.CI ? 8192 : 4096}`,
'--unhandled-rejections=warn',
].join(' '),
VITEST: '1',
},
stdio: 'inherit',
}
// Always use direct execution for isolated tests (simpler, more predictable)
const result = await runCommandWithOutput(vitestPath, vitestArgs, {
...spawnOptions,
stdio: ['inherit', 'pipe', 'pipe'],
})
// Print output
if (result.stdout) {
process.stdout.write(result.stdout)
}
if (result.stderr) {
process.stderr.write(result.stderr)
}
return result.code
}
async function main() {
try {
// Parse arguments
const { positionals, values } = parseArgs({
options: {
help: {
type: 'boolean',
default: false,
},
fast: {
type: 'boolean',
default: false,
},
quick: {
type: 'boolean',
default: false,
},
'skip-build': {
type: 'boolean',
default: false,
},
staged: {
type: 'boolean',
default: false,
},
all: {
type: 'boolean',
default: false,
},
force: {
type: 'boolean',
default: false,
},
cover: {
type: 'boolean',
default: false,
},
coverage: {
type: 'boolean',
default: false,
},
update: {
type: 'boolean',
default: false,
},
},
allowPositionals: true,
strict: false,
})
// Show help if requested
if (values.help) {
logger.log('Test Runner')
logger.log('\nUsage: pnpm test [options] [-- vitest-args...]')
logger.log('\nOptions:')
logger.log(' --help Show this help message')
logger.log(
' --fast, --quick Skip lint/type checks for faster execution',
)
logger.log(' --cover, --coverage Run tests with code coverage')
logger.log(' --update Update test snapshots')
logger.log(' --all, --force Run all tests regardless of changes')
logger.log(' --staged Run tests affected by staged changes')
logger.log(' --skip-build Skip the build step')
logger.log('\nExamples:')
logger.log(
' pnpm test # Run checks, build, and tests for changed files',
)
logger.log(' pnpm test --all # Run all tests')
logger.log(' pnpm test --fast # Skip checks for quick testing')
logger.log(' pnpm test --cover # Run with coverage report')
logger.log(' pnpm test --fast --cover # Quick test with coverage')
logger.log(' pnpm test --update # Update test snapshots')
logger.log(' pnpm test -- --reporter=dot # Pass args to vitest')
process.exitCode = 0
return
}
printHeader('Test Runner')
// Handle aliases
const skipChecks = values.fast || values.quick
const withCoverage = values.cover || values.coverage
let exitCode = 0
// Run checks unless skipped
if (!skipChecks) {
exitCode = await runCheck()
if (exitCode !== 0) {
logger.error('Checks failed')
process.exitCode = exitCode
return
}
logger.success('All checks passed')
}
// Run build unless skipped
if (!values['skip-build']) {
exitCode = await runBuild()
if (exitCode !== 0) {
logger.error('Build failed')
process.exitCode = exitCode
return
}
}
// Run main tests
exitCode = await runTests(
{ ...values, coverage: withCoverage },
positionals,
)
if (exitCode !== 0) {
logger.error('Main tests failed')
process.exitCode = exitCode
return
}
// Run isolated tests
exitCode = await runIsolatedTests({ coverage: withCoverage })
if (exitCode !== 0) {
logger.error('Isolated tests failed')
process.exitCode = exitCode
} else {
logger.success('All tests passed!')
}
} catch (error) {
// Ensure spinner is stopped
try {
spinner.stop()
} catch {}
logger.error(`Test runner failed: ${error.message}`)
process.exitCode = 1
} finally {
// Ensure spinner is stopped
try {
spinner.stop()
} catch {}
removeExitHandler()
// Exit code already set via process.exitCode (line 465/475)
// Let process exit naturally to allow parent process error handlers
}
}
main().catch(error => {
logger.error(error)
process.exitCode = 1
})