-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathbuild.ts
More file actions
732 lines (634 loc) · 25 KB
/
build.ts
File metadata and controls
732 lines (634 loc) · 25 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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
/**
* Build script for vite-plus CLI package
*
* This script performs the following main tasks:
* 1. buildCli() - Compiles TypeScript sources (local CLI) via tsc
* 2. buildGlobalModules() - Bundles global CLI modules (create, migrate, init, mcp, version) via rolldown
* 3. buildNapiBinding() - Builds the native Rust binding via NAPI
* 4. syncCorePackageExports() - Creates shim files to re-export from @voidzero-dev/vite-plus-core
* 5. syncTestPackageExports() - Creates shim files to re-export from @voidzero-dev/vite-plus-test
* 6. copySkillDocs() - Copies docs into skills/vite-plus/docs for runtime MCP access
* 7. syncReadmeFromRoot() - Keeps package README in sync
*
* The sync functions allow this package to be a drop-in replacement for 'vite' by
* re-exporting all the same subpaths (./client, ./types/*, etc.) while delegating
* to the core package for actual implementation.
*
* IMPORTANT: The core package must be built before running this script.
* Native binding is built first because TypeScript may depend on generated binding types.
*/
import { execSync } from 'node:child_process';
import { existsSync, globSync, readFileSync, readdirSync, statSync } from 'node:fs';
import { copyFile, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseArgs } from 'node:util';
import { createBuildCommand, NapiCli } from '@napi-rs/cli';
import { format } from 'oxfmt';
import {
createCompilerHost,
createProgram,
formatDiagnostics,
parseJsonSourceFileConfigFileContent,
readJsonConfigFile,
sys,
ModuleKind,
} from 'typescript';
import { generateLicenseFile } from '../../scripts/generate-license.ts';
const projectDir = dirname(fileURLToPath(import.meta.url));
const TEST_PACKAGE_NAME = '@voidzero-dev/vite-plus-test';
const CORE_PACKAGE_NAME = '@voidzero-dev/vite-plus-core';
const {
values: { ['skip-native']: skipNative, ['skip-ts']: skipTs },
} = parseArgs({
options: {
['skip-native']: { type: 'boolean', default: false },
['skip-ts']: { type: 'boolean', default: false },
},
strict: false,
});
// Filter out custom flags before passing to NAPI CLI
const napiArgs = process.argv
.slice(2)
.filter((arg) => arg !== '--skip-native' && arg !== '--skip-ts');
if (!skipTs) {
await buildCli();
buildGlobalModules();
generateLicenseFile({
title: 'Vite-Plus CLI license',
packageName: 'Vite-Plus',
outputPath: join(projectDir, 'LICENSE'),
coreLicensePath: join(projectDir, '..', '..', 'LICENSE'),
bundledPaths: [join(projectDir, 'dist', 'global')],
resolveFrom: [projectDir],
});
if (!existsSync(join(projectDir, 'LICENSE'))) {
throw new Error('LICENSE was not generated during build');
}
}
// Build native first - TypeScript may depend on the generated binding types
if (!skipNative) {
await buildNapiBinding();
}
if (!skipTs) {
await syncCorePackageExports();
await syncTestPackageExports();
}
await copySkillDocs();
await syncReadmeFromRoot();
async function buildNapiBinding() {
const buildCommand = createBuildCommand(napiArgs);
const passedInOptions = buildCommand.getOptions();
const cli = new NapiCli();
const dtsHeader = process.env.RELEASE_BUILD
? (await import('../../rolldown/packages/rolldown/package.json', { with: { type: 'json' } }))
.default.napi.dtsHeader
: '';
if (dtsHeader) {
passedInOptions.dtsHeader = `type BindingErrorsOr<T> = T | BindingErrors;\ntype FxHashSet<T> = Set<T>;\ntype FxHashMap<K, V> = Map<K, V>;\n${dtsHeader}`;
}
const { task } = await cli.build({
...passedInOptions,
packageJsonPath: '../package.json',
cwd: 'binding',
platform: true,
jsBinding: 'index.cjs',
dts: 'index.d.cts',
release: process.env.VITE_PLUS_CLI_DEBUG !== '1',
features: process.env.RELEASE_BUILD ? ['rolldown'] : void 0,
});
const outputs = await task;
const viteConfig = await import('../../vite.config');
for (const output of outputs) {
if (output.kind !== 'node') {
const { code, errors } = await format(output.path, await readFile(output.path, 'utf8'), {
...viteConfig.default.fmt,
embeddedCode: true,
});
if (errors.length > 0) {
for (const error of errors) {
console.error(error);
}
process.exit(1);
}
await writeFile(output.path, code);
}
}
}
async function buildCli() {
const tsconfig = readJsonConfigFile(join(projectDir, 'tsconfig.json'), sys.readFile.bind(sys));
const { options: initialOptions } = parseJsonSourceFileConfigFileContent(
tsconfig,
sys,
projectDir,
);
const options = {
...initialOptions,
noEmit: false,
outDir: join(projectDir, 'dist'),
};
const cjsHost = createCompilerHost({
...options,
module: ModuleKind.CommonJS,
});
const cjsProgram = createProgram({
rootNames: ['src/define-config.ts'],
options: {
...options,
module: ModuleKind.CommonJS,
},
host: cjsHost,
});
const { diagnostics: cjsDiagnostics } = cjsProgram.emit();
if (cjsDiagnostics.length > 0) {
console.error(formatDiagnostics(cjsDiagnostics, cjsHost));
process.exit(1);
}
await rename(
join(projectDir, 'dist/define-config.js'),
join(projectDir, 'dist/define-config.cjs'),
);
const host = createCompilerHost(options);
const program = createProgram({
rootNames: globSync('src/**/*.{ts,cts}', {
cwd: projectDir,
exclude: [
'**/*/__tests__',
// Global CLI modules — bundled by rolldown instead of tsc
'src/create/**',
'src/init/**',
'src/mcp/**',
'src/migration/**',
'src/version.ts',
'src/types/**',
],
}),
options,
host,
});
const { diagnostics } = program.emit();
if (diagnostics.length > 0) {
console.error(formatDiagnostics(diagnostics, host));
process.exit(1);
}
}
function buildGlobalModules() {
execSync('npx rolldown -c rolldown.config.ts', {
cwd: projectDir,
stdio: 'inherit',
});
validateGlobalBundleExternals();
}
/**
* Scan rolldown output for unbundled workspace package imports.
*
* Rolldown silently externalizes imports it can't resolve (no error, no warning).
* If a workspace package's dist doesn't exist at bundle time (build order race,
* clean checkout, etc.), the bare specifier stays in the output. Since these
* packages are devDependencies — not installed in the global CLI's node_modules —
* this causes a runtime ERR_MODULE_NOT_FOUND crash.
*
* Fail the build loudly instead of producing a broken install.
*/
function validateGlobalBundleExternals() {
const globalDir = join(projectDir, 'dist/global');
const files = globSync('*.js', { cwd: globalDir });
const errors: string[] = [];
for (const file of files) {
const content = readFileSync(join(globalDir, file), 'utf8');
const matches = content.matchAll(/\bimport\s.*?from\s+["'](@voidzero-dev\/[^"']+)["']/g);
for (const match of matches) {
errors.push(` ${file}: unbundled import of "${match[1]}"`);
}
}
if (errors.length > 0) {
throw new Error(
`Rolldown failed to bundle workspace packages in dist/global/:\n${errors.join('\n')}\n` +
`Ensure these packages are built before running the CLI build.`,
);
}
}
/**
* Sync Vite core exports from @voidzero-dev/vite-plus-core to vite-plus
*
* Creates shim files that re-export from the core package, enabling imports like:
* - `import type { ... } from 'vite-plus/types/importGlob.d.ts'`
* - `import { ... } from 'vite-plus/module-runner'`
*
* Export paths created:
* - ./client - Triple-slash reference (ambient type declarations for CSS, assets, etc.)
* - ./module-runner - Re-exports both JS and types
* - ./internal - Re-exports both JS and types
* - ./dist/client/* - Re-exports client runtime files (.mjs, .cjs)
* - ./types/* - Type-only re-exports using `export type *`
*
* Note: In package.json exports, ./types/internal/* must come BEFORE ./types/*
* for correct precedence (more specific patterns must precede wildcards).
*
* @throws Error if core package is not built (missing dist directories)
*/
async function syncCorePackageExports() {
console.log('\nSyncing core package exports...');
const distDir = join(projectDir, 'dist');
const clientDir = join(distDir, 'client');
const typesDir = join(distDir, 'types');
// Clean up previous build
await rm(clientDir, { recursive: true, force: true });
await rm(typesDir, { recursive: true, force: true });
await mkdir(clientDir, { recursive: true });
await mkdir(typesDir, { recursive: true });
// Create ./client shim (types only) - uses triple-slash reference since client.d.ts is ambient
console.log(' Creating ./client');
await writeFile(
join(distDir, 'client.d.ts'),
`/// <reference types="${CORE_PACKAGE_NAME}/client" />\n`,
);
// Create ./module-runner shim
console.log(' Creating ./module-runner');
await writeFile(
join(distDir, 'module-runner.js'),
`export * from '${CORE_PACKAGE_NAME}/module-runner';\n`,
);
await writeFile(
join(distDir, 'module-runner.d.ts'),
`export * from '${CORE_PACKAGE_NAME}/module-runner';\n`,
);
// Create ./internal shim
console.log(' Creating ./internal');
await writeFile(join(distDir, 'internal.js'), `export * from '${CORE_PACKAGE_NAME}/internal';\n`);
await writeFile(
join(distDir, 'internal.d.ts'),
`export * from '${CORE_PACKAGE_NAME}/internal';\n`,
);
// Create ./dist/client/* shims by reading core's dist/vite/client files
console.log(' Creating ./dist/client/*');
const coreClientDir = join(projectDir, '../core/dist/vite/client');
if (!existsSync(coreClientDir)) {
throw new Error(
`Core client artifacts not found at "${coreClientDir}". ` +
`Make sure ${CORE_PACKAGE_NAME} is built before building the CLI.`,
);
}
for (const file of readdirSync(coreClientDir)) {
const srcPath = join(coreClientDir, file);
const shimPath = join(clientDir, file);
// Skip directories
if (statSync(srcPath).isDirectory()) {
continue;
}
if (file.endsWith('.js') || file.endsWith('.mjs') || file.endsWith('.cjs')) {
await writeFile(shimPath, `export * from '${CORE_PACKAGE_NAME}/dist/client/${file}';\n`);
} else if (file.endsWith('.d.ts') || file.endsWith('.d.mts') || file.endsWith('.d.cts')) {
const baseFile = file.replace(/\.d\.[mc]?ts$/, '');
await writeFile(shimPath, `export * from '${CORE_PACKAGE_NAME}/dist/client/${baseFile}';\n`);
} else {
// Copy non-JS/TS files directly (e.g., CSS, source maps)
await copyFile(srcPath, shimPath);
}
}
// Create ./types/* shims by reading core's dist/vite/types files
console.log(' Creating ./types/*');
const coreTypesDir = join(projectDir, '../core/dist/vite/types');
if (!existsSync(coreTypesDir)) {
throw new Error(
`Core type definitions not found at "${coreTypesDir}". ` +
`Make sure ${CORE_PACKAGE_NAME} is built before building the CLI.`,
);
}
await syncTypesDir(coreTypesDir, typesDir, '');
console.log('\nSynced core package exports');
}
/**
* Recursively sync type definition files from core to CLI package
*
* Creates shim .d.ts files that re-export types from the core package.
* Uses `export type * from` syntax which is valid in TypeScript 5.0+.
*
* @param srcDir - Source directory containing .d.ts files
* @param destDir - Destination directory for shim files
* @param relativePath - Current path relative to types root (empty string at top level)
*
* Special handling:
* - Skips top-level 'internal' directory (blocked by ./types/internal/* export)
* - Supports .d.ts, .d.mts, and .d.cts extensions
* - Preserves directory structure recursively
*/
async function syncTypesDir(srcDir: string, destDir: string, relativePath: string) {
const entries = readdirSync(srcDir);
for (const entry of entries) {
const srcPath = join(srcDir, entry);
const destPath = join(destDir, entry);
const entryRelPath = relativePath ? `${relativePath}/${entry}` : entry;
if (statSync(srcPath).isDirectory()) {
// Skip top-level internal directory - it's blocked by ./types/internal/* export
if (entry === 'internal' && relativePath === '') {
continue;
}
await mkdir(destPath, { recursive: true });
await syncTypesDir(srcPath, destPath, entryRelPath);
} else if (/\.d\.[mc]?ts$/.test(entry)) {
// Create shim that re-exports from core - must include extension for wildcard exports
// Use 'export type *' since we're re-exporting from a .d.ts file
await writeFile(
destPath,
`export type * from '${CORE_PACKAGE_NAME}/types/${entryRelPath}';\n`,
);
}
}
}
/**
* Sync exports from @voidzero-dev/vite-plus-test to vite-plus
*
* This function reads the test package's exports and creates shim files that
* re-export everything under the ./test/* subpath. This allows users to import
* from vite-plus/test/* instead of @voidzero-dev/vite-plus-test/*.
*/
async function syncTestPackageExports() {
console.log('\nSyncing test package exports...');
const testPkgPath = join(projectDir, '../test/package.json');
const cliPkgPath = join(projectDir, 'package.json');
const testDistDir = join(projectDir, 'dist/test');
// Read test package.json
const testPkg = JSON.parse(await readFile(testPkgPath, 'utf-8'));
const testExports = testPkg.exports as Record<string, unknown>;
// Clean up previous build
await rm(testDistDir, { recursive: true, force: true });
await mkdir(testDistDir, { recursive: true });
const generatedExports: Record<string, unknown> = {};
for (const [exportPath, exportValue] of Object.entries(testExports)) {
// Skip package.json export and wildcard exports
if (exportPath === './package.json' || exportPath.includes('*')) {
continue;
}
// Convert ./foo to ./test/foo, . to ./test
const cliExportPath = exportPath === '.' ? './test' : `./test${exportPath.slice(1)}`;
// Create shim files and build export entry
const shimExport = await createShimForExport(exportPath, exportValue, testDistDir);
if (shimExport) {
generatedExports[cliExportPath] = shimExport;
console.log(` Created ${cliExportPath}`);
}
}
// Update CLI package.json
await updateCliPackageJson(cliPkgPath, generatedExports);
console.log(`\nSynced ${Object.keys(generatedExports).length} exports from test package`);
}
/**
* Copy markdown doc files from the monorepo docs/ directory into skills/vite-plus/docs/,
* preserving the relative directory structure. This keeps stable file paths for
* skills routing and MCP page slugs.
*/
async function copySkillDocs() {
console.log('\nCopying skill docs...');
const docsSourceDir = join(projectDir, '..', '..', 'docs');
const docsTargetDir = join(projectDir, 'skills', 'vite-plus', 'docs');
if (!existsSync(docsSourceDir)) {
console.log(' Docs source directory not found, skipping skill docs copy');
return;
}
// Clean and recreate target directory
await rm(docsTargetDir, { recursive: true, force: true });
await mkdir(docsTargetDir, { recursive: true });
// Find all markdown files recursively and copy them with their relative paths.
const mdFiles = globSync('**/*.md', { cwd: docsSourceDir }).filter(
(f) => !f.includes('node_modules') && f !== 'index.md',
);
// eslint-disable-next-line unicorn/no-array-sort -- sorted traversal keeps output deterministic
mdFiles.sort();
let copied = 0;
for (const relPath of mdFiles) {
const sourcePath = join(docsSourceDir, relPath);
const targetPath = join(docsTargetDir, relPath);
await mkdir(dirname(targetPath), { recursive: true });
await copyFile(sourcePath, targetPath);
copied++;
}
console.log(` Copied ${copied} doc files to skills/vite-plus/docs/ (with paths preserved)`);
}
async function syncReadmeFromRoot() {
const rootReadmePath = join(projectDir, '..', '..', 'README.md');
const packageReadmePath = join(projectDir, 'README.md');
const [rootReadme, packageReadme] = await Promise.all([
readFile(rootReadmePath, 'utf8'),
readFile(packageReadmePath, 'utf8'),
]);
const { suffix: rootSuffix } = splitReadme(rootReadme, rootReadmePath);
const { prefix: packagePrefix } = splitReadme(packageReadme, packageReadmePath);
const nextReadme = `${packagePrefix}\n\n${rootSuffix}\n`;
if (nextReadme !== packageReadme) {
await writeFile(packageReadmePath, nextReadme);
}
}
function splitReadme(content: string, label: string) {
const match = /^---\s*$/m.exec(content);
if (!match || match.index === undefined) {
throw new Error(`Expected ${label} to include a '---' separator.`);
}
const delimiterStart = match.index;
const delimiterEnd = delimiterStart + match[0].length;
const afterDelimiter = content.slice(delimiterEnd);
const newlineMatch = /^\r?\n/.exec(afterDelimiter);
const delimiterWithNewlineEnd = delimiterEnd + (newlineMatch ? newlineMatch[0].length : 0);
return {
prefix: content.slice(0, delimiterWithNewlineEnd).trim(),
suffix: content.slice(delimiterWithNewlineEnd).trim(),
};
}
type ExportValue =
| string
| {
types?: string;
default?: string;
import?: ExportValue;
require?: ExportValue;
node?: string;
};
/**
* Create shim file(s) for a single export and return the export entry for package.json
*/
async function createShimForExport(
exportPath: string,
exportValue: unknown,
distDir: string,
): Promise<ExportValue | null> {
// Determine the import specifier for the test package
const testImportSpecifier =
exportPath === '.' ? TEST_PACKAGE_NAME : `${TEST_PACKAGE_NAME}${exportPath.slice(1)}`;
// Convert export path to file path: ./foo/bar -> foo/bar, . -> index
const shimBaseName = exportPath === '.' ? 'index' : exportPath.slice(2);
const shimDir = join(distDir, dirname(shimBaseName));
await mkdir(shimDir, { recursive: true });
const baseFileName = shimBaseName.includes('/') ? shimBaseName.split('/').pop()! : shimBaseName;
const shimDirForFile = shimBaseName.includes('/') ? shimDir : distDir;
// Handle different export value formats
if (typeof exportValue === 'string') {
// Simple string export: "./browser-compat": "./dist/browser-compat.js"
// Check if it's a type-only export
if (exportValue.endsWith('.d.ts')) {
const dtsPath = join(shimDirForFile, `${baseFileName}.d.ts`);
// Include side-effect import to preserve module augmentations (e.g., toMatchSnapshot on Assertion)
await writeFile(
dtsPath,
`import '${testImportSpecifier}';\nexport * from '${testImportSpecifier}';\n`,
);
return { types: `./dist/test/${shimBaseName}.d.ts` };
}
const jsPath = join(shimDirForFile, `${baseFileName}.js`);
await writeFile(jsPath, `export * from '${testImportSpecifier}';\n`);
return { default: `./dist/test/${shimBaseName}.js` };
}
if (typeof exportValue === 'object' && exportValue !== null) {
const value = exportValue as Record<string, unknown>;
// Check if it has import/require conditions (complex conditional export)
if ('import' in value || 'require' in value) {
return await createConditionalShim(
value,
testImportSpecifier,
shimDirForFile,
baseFileName,
shimBaseName,
);
}
// Simple object with types/default
const result: ExportValue = {};
if (value.types && typeof value.types === 'string') {
const dtsPath = join(shimDirForFile, `${baseFileName}.d.ts`);
// Include side-effect import to preserve module augmentations (e.g., toMatchSnapshot on Assertion)
await writeFile(
dtsPath,
`import '${testImportSpecifier}';\nexport * from '${testImportSpecifier}';\n`,
);
(result as Record<string, string>).types = `./dist/test/${shimBaseName}.d.ts`;
}
if (value.default && typeof value.default === 'string') {
const jsPath = join(shimDirForFile, `${baseFileName}.js`);
await writeFile(jsPath, `export * from '${testImportSpecifier}';\n`);
(result as Record<string, string>).default = `./dist/test/${shimBaseName}.js`;
}
return Object.keys(result).length > 0 ? result : null;
}
return null;
}
/**
* Handle complex conditional exports with import/require/node conditions
*
* Handles both nested structures like:
* { import: { types, node, default }, require: { types, default } }
* And flat structures like:
* { types, require, default }
*/
async function createConditionalShim(
value: Record<string, unknown>,
testImportSpecifier: string,
shimDir: string,
baseFileName: string,
shimBaseName: string,
): Promise<ExportValue> {
const result: ExportValue = {};
// Handle top-level types (flat structure like { types, require, default })
if (value.types && typeof value.types === 'string' && !value.import) {
const dtsPath = join(shimDir, `${baseFileName}.d.ts`);
// Include side-effect import to preserve module augmentations (e.g., toMatchSnapshot on Assertion)
await writeFile(
dtsPath,
`import '${testImportSpecifier}';\nexport * from '${testImportSpecifier}';\n`,
);
(result as Record<string, string>).types = `./dist/test/${shimBaseName}.d.ts`;
}
// Handle top-level default (flat structure, only when no import condition)
if (value.default && typeof value.default === 'string' && !value.import) {
const jsPath = join(shimDir, `${baseFileName}.js`);
await writeFile(jsPath, `export * from '${testImportSpecifier}';\n`);
(result as Record<string, string>).default = `./dist/test/${shimBaseName}.js`;
}
// Handle import condition
if (value.import) {
const importValue = value.import as Record<string, unknown>;
if (typeof importValue === 'string') {
const jsPath = join(shimDir, `${baseFileName}.js`);
await writeFile(jsPath, `export * from '${testImportSpecifier}';\n`);
(result as Record<string, unknown>).import = `./dist/test/${shimBaseName}.js`;
} else if (typeof importValue === 'object' && importValue !== null) {
const importResult: Record<string, string> = {};
if (importValue.types && typeof importValue.types === 'string') {
const dtsPath = join(shimDir, `${baseFileName}.d.ts`);
// Include side-effect import to preserve module augmentations (e.g., toMatchSnapshot on Assertion)
await writeFile(
dtsPath,
`import '${testImportSpecifier}';\nexport * from '${testImportSpecifier}';\n`,
);
importResult.types = `./dist/test/${shimBaseName}.d.ts`;
}
// Create main JS shim - used for both 'node' and 'default' conditions
const jsPath = join(shimDir, `${baseFileName}.js`);
await writeFile(jsPath, `export * from '${testImportSpecifier}';\n`);
if (importValue.node) {
importResult.node = `./dist/test/${shimBaseName}.js`;
}
if (importValue.default) {
importResult.default = `./dist/test/${shimBaseName}.js`;
}
result.import = importResult;
}
}
// Handle require condition
if (value.require) {
const requireValue = value.require as Record<string, unknown>;
if (typeof requireValue === 'string') {
const cjsPath = join(shimDir, `${baseFileName}.cjs`);
await writeFile(cjsPath, `module.exports = require('${testImportSpecifier}');\n`);
result.require = `./dist/test/${shimBaseName}.cjs`;
} else if (typeof requireValue === 'object' && requireValue !== null) {
const requireResult: Record<string, string> = {};
if (requireValue.types && typeof requireValue.types === 'string') {
const dctsPath = join(shimDir, `${baseFileName}.d.cts`);
// Include side-effect import to preserve module augmentations (e.g., toMatchSnapshot on Assertion)
await writeFile(
dctsPath,
`import '${testImportSpecifier}';\nexport * from '${testImportSpecifier}';\n`,
);
requireResult.types = `./dist/test/${shimBaseName}.d.cts`;
}
if (requireValue.default && typeof requireValue.default === 'string') {
const cjsPath = join(shimDir, `${baseFileName}.cjs`);
await writeFile(cjsPath, `module.exports = require('${testImportSpecifier}');\n`);
requireResult.default = `./dist/test/${shimBaseName}.cjs`;
}
result.require = requireResult;
}
}
return result;
}
/**
* Update CLI package.json with the generated exports
*/
async function updateCliPackageJson(pkgPath: string, generatedExports: Record<string, unknown>) {
const pkg = JSON.parse(await readFile(pkgPath, 'utf-8'));
// Remove old ./test/* exports (if any) to ensure clean sync
if (pkg.exports) {
for (const key of Object.keys(pkg.exports)) {
if (key.startsWith('./test')) {
delete pkg.exports[key];
}
}
}
// Add new exports
pkg.exports = {
...pkg.exports,
...generatedExports,
};
// Ensure dist/test is included in files
if (!pkg.files.includes('dist/test')) {
pkg.files.push('dist/test');
}
const { code, errors } = await format(pkgPath, JSON.stringify(pkg, null, 2) + '\n', {
experimentalSortPackageJson: true,
});
if (errors.length > 0) {
for (const error of errors) {
console.error(error);
}
process.exit(1);
}
await writeFile(pkgPath, code);
}