-
Notifications
You must be signed in to change notification settings - Fork 172
Expand file tree
/
Copy pathbuild.ts
More file actions
2635 lines (2324 loc) · 98.3 KB
/
build.ts
File metadata and controls
2635 lines (2324 loc) · 98.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
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Build Script for @voidzero-dev/vite-plus-test
//
// Bundles vitest and @vitest/* dependencies with browser/Node.js separation.
//
// ┌─────────────────────────────────────────────────────────────────────┐
// │ BUILD FLOW │
// ├─────────────────────────────────────────────────────────────────────┤
// │ 1. bundleVitest() Copy vitest-dev → dist/ │
// │ 2. copyVitestPackages() Copy @vitest/* → dist/@vitest/ │
// │ 3. collectLeafDependencies() Parse imports with oxc-parser │
// │ 4. bundleLeafDeps() Bundle chai, pathe, etc → dist/vendor/ │
// │ 5. rewriteVitestImports() Rewrite @vitest/*, vitest/*, vite │
// │ 6. patchVitestPkgRootPaths() Fix distRoot for relocated files │
// │ 7. patchVitestBrowserPackage() Inject vendor-aliases plugin │
// │ 8. patchBrowserProviderLocators() Fix browser-safe imports │
// │ 9. Post-processing: │
// │ - patchVendorPaths() │
// │ - createBrowserCompatShim() │
// │ - createModuleRunnerStub() Browser-safe stub │
// │ - createNodeEntry() index-node.js with browser-provider│
// │ - copyBrowserClientFiles() │
// │ - createPluginExports() dist/plugins/* for pnpm overrides │
// │ - mergePackageJson() │
// │ - validateExternalDeps() │
// └─────────────────────────────────────────────────────────────────────┘
//
// Output Structure:
// dist/@vitest/* - Copied packages (browser/Node.js safe)
// dist/vendor/* - Bundled leaf dependencies
// dist/plugins/* - Shims for pnpm overrides
// dist/index.js - Browser-safe entry
// dist/index-node.js - Node.js entry (includes browser-provider)
//
// Key Design:
// - COPY @vitest/* to preserve browser/Node.js separation
// - BUNDLE only leaf deps (chai, etc.) to reduce install size
// - Separate entries prevent __vite__injectQuery errors in browser
import { existsSync } from 'node:fs';
import {
copyFile,
glob as fsGlob,
mkdir,
readFile,
readdir,
rm,
stat,
writeFile,
} from 'node:fs/promises';
import { builtinModules } from 'node:module';
import { basename, join, parse, resolve, dirname, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseSync } from 'oxc-parser';
import { format } from 'oxfmt';
import { build } from 'rolldown';
import { dts } from 'rolldown-plugin-dts';
import { generateLicenseFile } from '../../scripts/generate-license.ts';
import pkg from './package.json' with { type: 'json' };
const projectDir = dirname(fileURLToPath(import.meta.url));
const vitestSourceDir = resolve(projectDir, 'node_modules/vitest-dev');
const distDir = resolve(projectDir, 'dist');
const vendorDir = resolve(distDir, 'vendor');
const CORE_PACKAGE_NAME = '@voidzero-dev/vite-plus-core';
const TEST_PACKAGE_NAME = '@voidzero-dev/vite-plus-test';
// @vitest/* packages to copy (not bundle) to preserve browser/Node.js separation
// These are copied from node_modules to dist/@vitest/ to avoid shared chunks
// that mix Node.js-only code with browser code
const VITEST_PACKAGES_TO_COPY = [
'@vitest/runner',
'@vitest/utils',
'@vitest/spy',
'@vitest/expect',
'@vitest/snapshot',
'@vitest/mocker',
'@vitest/pretty-format',
'@vitest/browser',
'@vitest/browser-playwright',
'@vitest/browser-webdriverio',
'@vitest/browser-preview',
] as const;
// Mapping from @vitest/* package specifiers to their paths within dist/@vitest/
// Used for import rewriting and vendor-aliases plugin
const VITEST_PACKAGE_TO_PATH: Record<string, string> = {
// @vitest/runner
'@vitest/runner': '@vitest/runner/index.js',
'@vitest/runner/utils': '@vitest/runner/utils.js',
'@vitest/runner/types': '@vitest/runner/types.js',
// @vitest/utils
'@vitest/utils': '@vitest/utils/index.js',
'@vitest/utils/source-map': '@vitest/utils/source-map.js',
'@vitest/utils/source-map/node': '@vitest/utils/source-map/node.js',
'@vitest/utils/error': '@vitest/utils/error.js',
'@vitest/utils/helpers': '@vitest/utils/helpers.js',
'@vitest/utils/display': '@vitest/utils/display.js',
'@vitest/utils/timers': '@vitest/utils/timers.js',
'@vitest/utils/highlight': '@vitest/utils/highlight.js',
'@vitest/utils/offset': '@vitest/utils/offset.js',
'@vitest/utils/resolver': '@vitest/utils/resolver.js',
'@vitest/utils/serialize': '@vitest/utils/serialize.js',
'@vitest/utils/constants': '@vitest/utils/constants.js',
'@vitest/utils/diff': '@vitest/utils/diff.js',
// @vitest/spy
'@vitest/spy': '@vitest/spy/index.js',
// @vitest/expect
'@vitest/expect': '@vitest/expect/index.js',
// @vitest/snapshot
'@vitest/snapshot': '@vitest/snapshot/index.js',
'@vitest/snapshot/environment': '@vitest/snapshot/environment.js',
'@vitest/snapshot/manager': '@vitest/snapshot/manager.js',
// @vitest/mocker
'@vitest/mocker': '@vitest/mocker/index.js',
'@vitest/mocker/node': '@vitest/mocker/node.js',
'@vitest/mocker/browser': '@vitest/mocker/browser.js',
'@vitest/mocker/redirect': '@vitest/mocker/redirect.js',
'@vitest/mocker/transforms': '@vitest/mocker/transforms.js',
'@vitest/mocker/automock': '@vitest/mocker/automock.js',
'@vitest/mocker/register': '@vitest/mocker/register.js',
// @vitest/pretty-format
'@vitest/pretty-format': '@vitest/pretty-format/index.js',
// @vitest/browser
'@vitest/browser': '@vitest/browser/index.js',
'@vitest/browser/context': '@vitest/browser/context.js',
'@vitest/browser/client': '@vitest/browser/client.js',
'@vitest/browser/locators': '@vitest/browser/locators.js',
// @vitest/browser-playwright
'@vitest/browser-playwright': '@vitest/browser-playwright/index.js',
// @vitest/browser-webdriverio
'@vitest/browser-webdriverio': '@vitest/browser-webdriverio/index.js',
// @vitest/browser-preview
'@vitest/browser-preview': '@vitest/browser-preview/index.js',
};
// Packages that should NOT be bundled into dist/vendor/ (remain external at runtime)
// There are two categories:
// 1. Runtime deps (also in package.json dependencies) - installed with the package, not bundled
// 2. Peer/optional deps (also in peerDependencies) - users must install themselves
const EXTERNAL_BLOCKLIST = new Set([
// Our own packages - resolved at runtime
CORE_PACKAGE_NAME,
`${CORE_PACKAGE_NAME}/module-runner`,
'vite',
'vitest',
// Peer dependencies - consumers must provide these
'@edge-runtime/vm',
'@opentelemetry/api',
'@standard-schema/spec', // Types-only import from @vitest/expect
'happy-dom',
'jsdom',
// Optional dependencies with bundling issues or native bindings
'debug', // environment detection broken when bundled
'playwright', // native bindings
'webdriverio', // native bindings
// Runtime deps (in package.json dependencies) - not bundled, resolved at install time
'sirv',
'ws',
'pixelmatch',
'pngjs',
// MSW (Mock Service Worker) - optional peer dep of @vitest/mocker
'msw',
'msw/browser',
'msw/core/http',
]);
// CJS packages that need their default export destructured to named exports
const CJS_REEXPORT_PACKAGES = new Set(['expect-type']);
// Node built-in modules (including node: prefix variants)
const NODE_BUILTINS = new Set([...builtinModules, ...builtinModules.map((m) => `node:${m}`)]);
// Step 1: Copy vitest-dev dist files (rewriting vite -> core package)
await bundleVitest();
// Step 1.5: Rebrand vitest CLI output as "vp test" with vite-plus version
await brandVitest();
// Step 2: Copy @vitest/* packages from node_modules to dist/@vitest/
// This preserves the original file structure to maintain browser/Node.js separation
await copyVitestPackages();
// Step 2.5: Convert tabs to spaces in all copied JS files for consistent formatting
await convertTabsToSpaces();
// Step 3: Collect leaf dependencies from copied @vitest/* files
// These are external packages like tinyrainbow, pathe, chai, etc.
const leafDeps = await collectLeafDependencies();
// Step 4: Bundle only leaf dependencies into dist/vendor/
// Unlike bundling @vitest/* directly, this avoids shared chunks that mix browser/Node.js code
const leafDepToVendorPath = await bundleLeafDeps(leafDeps);
// Step 5: Rewrite imports in copied @vitest/* and vitest-dev files
// - @vitest/* -> relative paths to dist/@vitest/
// - leaf deps -> relative paths to dist/vendor/
// - vite -> @voidzero-dev/vite-plus-core
await rewriteVitestImports(leafDepToVendorPath);
// Step 6: Fix pkgRoot resolution in all @vitest/* packages
// Files are now at dist/@vitest/*/index.js, so "../.." needs to become "../../.."
await patchVitestPkgRootPaths();
// Step 7: Patch @vitest/browser package (vendor-aliases plugin, exclude list)
await patchVitestBrowserPackage();
// Step 8: Patch browser provider locators.js files for browser-safe imports
await patchBrowserProviderLocators();
// Step 9: Post-processing
await patchVendorPaths();
await patchVitestCoreResolver();
await createBrowserCompatShim();
await createModuleRunnerStub();
await createNodeEntry();
await copyBrowserClientFiles();
await createBrowserEntryFiles();
await patchModuleAugmentations();
await patchChaiTypeReference();
await patchMockerHoistedModule();
await patchServerDepsInline();
const pluginExports = await createPluginExports();
await mergePackageJson(pluginExports);
generateLicenseFile({
title: 'Vite-Plus test license',
packageName: 'Vite-Plus',
outputPath: join(projectDir, 'LICENSE.md'),
coreLicensePath: join(projectDir, '..', '..', 'LICENSE'),
bundledPaths: [distDir],
resolveFrom: [projectDir, join(projectDir, '..', '..')],
extraPackages: [
{ packageDir: vitestSourceDir },
...VITEST_PACKAGES_TO_COPY.map((packageName) => ({
packageDir: resolve(projectDir, 'node_modules', packageName),
})),
],
});
if (!existsSync(join(projectDir, 'LICENSE.md'))) {
throw new Error('LICENSE.md was not generated during build');
}
await syncLicenseFromRoot();
await validateExternalDeps();
async function mergePackageJson(pluginExports: Array<{ exportPath: string; shimFile: string }>) {
const vitestPackageJsonPath = join(vitestSourceDir, 'package.json');
const destPackageJsonPath = resolve(projectDir, 'package.json');
const vitestPkg = JSON.parse(await readFile(vitestPackageJsonPath, 'utf-8'));
const destPkg = JSON.parse(await readFile(destPackageJsonPath, 'utf-8'));
// Fields to merge from vitest-dev package.json (excluding dependencies since we bundle them)
const fieldsToMerge = [
'imports',
'exports',
'main',
'module',
'types',
'engines',
'peerDependencies',
'peerDependenciesMeta',
] as const;
for (const field of fieldsToMerge) {
if (vitestPkg[field] !== undefined) {
destPkg[field] = vitestPkg[field];
}
}
// Remove bundled @vitest/* packages from peerDependencies
// These browser provider packages are now bundled, so users don't need to install them
const bundledPeerDeps = [
'@vitest/browser-playwright',
'@vitest/browser-webdriverio',
'@vitest/browser-preview',
];
if (destPkg.peerDependencies) {
for (const dep of bundledPeerDeps) {
delete destPkg.peerDependencies[dep];
}
}
if (destPkg.peerDependenciesMeta) {
for (const dep of bundledPeerDeps) {
delete destPkg.peerDependenciesMeta[dep];
}
}
destPkg.bundledVersions = {
...destPkg.bundledVersions,
vitest: vitestPkg.version,
};
// Add @vitest/browser compatible export (for when this package overrides @vitest/browser)
// The main "." export is what's used when code imports from @vitest/browser
if (destPkg.exports) {
// Add conditional Node.js export to the main entry
// Node.js code (like @vitest/browser-playwright) uses index-node.js which includes
// browser-provider exports. Browser code uses index.js which is safe.
// This separation prevents Node.js-only code (like __vite__injectQuery) from being
// loaded in the browser, which would cause "Identifier already declared" errors.
//
// IMPORTANT: The 'browser' condition must come BEFORE 'node' because vitest passes
// custom --conditions (like 'browser') to worker processes when frameworks like Nuxt
// set edge/cloudflare presets. Without the 'browser' condition here, Node.js would
// match 'node' first, loading index-node.js which imports @vitest/browser/index.js,
// which imports 'ws'. With --conditions browser active, 'ws' resolves to its browser
// stub (ws/browser.js) that doesn't export WebSocketServer, causing a SyntaxError.
// See: https://github.com/voidzero-dev/vite-plus/issues/831
if (destPkg.exports['.'] && destPkg.exports['.'].import) {
destPkg.exports['.'].import = {
types: destPkg.exports['.'].import.types,
browser: destPkg.exports['.'].import.default,
node: './dist/index-node.js',
default: destPkg.exports['.'].import.default,
};
}
destPkg.exports['./browser-compat'] = {
default: './dist/browser-compat.js',
};
// Add @vitest/browser-compatible subpath exports
// These are needed when this package is used as a pnpm override for @vitest/browser
// Files are copied to dist/ (not dist/vendor/) to match path resolution in bundled code
destPkg.exports['./client'] = {
default: './dist/client.js',
};
// Point to @vitest/browser/context.js so that tests and init scripts share the same module
// This is critical: the init script (locators.js) calls page.extend() on this module,
// and tests must use the SAME module instance to see the extended methods
destPkg.exports['./context'] = {
types: './browser/context.d.ts',
default: './dist/@vitest/browser/context.js',
};
// Also export ./browser/context for users importing vite-plus/test/browser/context
destPkg.exports['./browser/context'] = {
types: './browser/context.d.ts',
default: './dist/@vitest/browser/context.js',
};
destPkg.exports['./locators'] = {
default: './dist/locators.js',
};
destPkg.exports['./matchers'] = {
default: './dist/dummy.js', // Placeholder
};
destPkg.exports['./utils'] = {
default: './dist/dummy.js', // Placeholder
};
// Add @vitest/browser-playwright compatible export
// Users can import { playwright } from 'vitest/browser-playwright'
destPkg.exports['./browser-playwright'] = {
types: './dist/@vitest/browser-playwright/index.d.ts',
default: './dist/@vitest/browser-playwright/index.js',
};
// Add @vitest/browser-webdriverio compatible export
// Users can import { webdriverio } from 'vitest/browser-webdriverio'
destPkg.exports['./browser-webdriverio'] = {
types: './dist/@vitest/browser-webdriverio/index.d.ts',
default: './dist/@vitest/browser-webdriverio/index.js',
};
// Add @vitest/browser-preview compatible export
// Users can import { preview } from 'vitest/browser-preview'
destPkg.exports['./browser-preview'] = {
types: './dist/@vitest/browser-preview/index.d.ts',
default: './dist/@vitest/browser-preview/index.js',
};
// Add browser/providers/* alias exports for compatibility
// Some vitest examples use the nested path format
destPkg.exports['./browser/providers/playwright'] = {
types: './dist/@vitest/browser-playwright/index.d.ts',
default: './dist/@vitest/browser-playwright/index.js',
};
destPkg.exports['./browser/providers/webdriverio'] = {
types: './dist/@vitest/browser-webdriverio/index.d.ts',
default: './dist/@vitest/browser-webdriverio/index.js',
};
destPkg.exports['./browser/providers/preview'] = {
types: './dist/@vitest/browser-preview/index.d.ts',
default: './dist/@vitest/browser-preview/index.js',
};
// Add plugin exports for all bundled @vitest/* packages
// This allows pnpm overrides to redirect: @vitest/runner -> vitest/plugins/runner
for (const { exportPath, shimFile } of pluginExports) {
destPkg.exports[exportPath] = {
default: shimFile,
};
}
}
// Merge vitest dependencies into devDependencies (since we bundle them)
// Skip packages that are already in dependencies (runtime deps)
if (vitestPkg.dependencies) {
destPkg.devDependencies = destPkg.devDependencies || {};
for (const [dep, version] of Object.entries(vitestPkg.dependencies)) {
// Skip vite - we use our own core package
if (dep === 'vite') {
continue;
}
// Skip packages already in dependencies (they're runtime deps, not dev-only)
if (destPkg.dependencies && destPkg.dependencies[dep]) {
continue;
}
// Don't override existing devDependencies
if (!destPkg.devDependencies[dep]) {
destPkg.devDependencies[dep] = version;
}
}
}
const { code, errors } = await format(
destPackageJsonPath,
JSON.stringify(destPkg, null, 2) + '\n',
{
experimentalSortPackageJson: true,
},
);
if (errors.length > 0) {
for (const error of errors) {
console.error(error);
}
process.exit(1);
}
await writeFile(destPackageJsonPath, code);
}
async function syncLicenseFromRoot() {
const rootLicensePath = join(projectDir, '..', '..', 'LICENSE');
const packageLicensePath = join(projectDir, 'LICENSE');
await copyFile(rootLicensePath, packageLicensePath);
}
async function bundleVitest() {
const vitestDestDir = projectDir;
await mkdir(vitestDestDir, { recursive: true });
// Get all vitest files excluding node_modules and package.json
const vitestFiles = fsGlob(join(vitestSourceDir, '**/*'), {
exclude: [
join(vitestSourceDir, 'node_modules/**'),
join(vitestSourceDir, 'package.json'),
join(vitestSourceDir, 'README.md'),
],
});
for await (const file of vitestFiles) {
const stats = await stat(file);
if (!stats.isFile()) {
continue;
}
const relativePath = file.replace(vitestSourceDir, '');
const destPath = join(vitestDestDir, relativePath);
await mkdir(parse(destPath).dir, { recursive: true });
// Rewrite vite imports in .js, .mjs, and .cjs files
if (
file.endsWith('.js') ||
file.endsWith('.mjs') ||
file.endsWith('.cjs') ||
file.endsWith('.d.ts') ||
file.endsWith('.d.cts')
) {
let content = await readFile(file, 'utf-8');
content = content
.replaceAll(/from ['"]vite['"]/g, `from '${CORE_PACKAGE_NAME}'`)
.replaceAll(/import\(['"]vite['"]\)/g, `import('${CORE_PACKAGE_NAME}')`)
.replaceAll(/require\(['"]vite['"]\)/g, `require('${CORE_PACKAGE_NAME}')`)
.replaceAll(/require\("vite"\)/g, `require("${CORE_PACKAGE_NAME}")`)
.replaceAll(`import 'vite';`, `import '${CORE_PACKAGE_NAME}';`)
.replaceAll(`'vite/module-runner'`, `'${CORE_PACKAGE_NAME}/module-runner'`)
.replaceAll(`declare module "vite"`, `declare module "${CORE_PACKAGE_NAME}"`)
.replaceAll(/import\(['"]vitest['"]\)/g, `import('${TEST_PACKAGE_NAME}')`);
console.log(`Replaced vite imports in ${destPath}`);
await writeFile(destPath, content, 'utf-8');
} else {
await copyFile(file, destPath);
}
}
}
/**
* Rebrand vitest CLI output as "vp test" with Vite+ banner styling.
* Patches bundled chunks to replace vitest branding and align banner output.
*/
async function brandVitest() {
const chunksDir = resolve(projectDir, 'dist/chunks');
const cacFiles: string[] = [];
for await (const file of fsGlob(join(chunksDir, 'cac.*.js'))) {
cacFiles.push(file);
}
if (cacFiles.length === 0) {
throw new Error('brandVitest: no cac chunk found in dist/chunks/');
}
for (const cacFile of cacFiles) {
let content = await readFile(cacFile, 'utf-8');
function patchString(label: string, search: string | RegExp, replacement: string) {
const before = content;
content =
typeof search === 'string'
? content.replace(search, replacement)
: content.replace(search, replacement);
if (content === before) {
throw new Error(
`brandVitest: failed to patch "${label}" — pattern not found in ${cacFile}`,
);
}
}
// 1. CLI name: cac("vitest") → cac("vp test")
patchString('cac name', 'cac("vitest")', 'cac("vp test")');
// 2. Version: var version = "<semver>" → use VP_VERSION env var with fallback
patchString(
'version',
/var version = "(\d+\.\d+\.\d+[^"]*)"/,
'var version = process.env.VP_VERSION || "$1"',
);
// 3. Banner regex: /^vitest\/\d+\.\d+\.\d+$/ → /^vp test\/[\d.]+$/
patchString('banner regex', '/^vitest\\/\\d+\\.\\d+\\.\\d+$/', '/^vp test\\/[\\d.]+$/');
// 4. Help text: $ vitest --help → $ vp test --help
patchString('help text', '$ vitest --help --expand-help', '$ vp test --help --expand-help');
await writeFile(cacFile, content, 'utf-8');
console.log(`Branded vitest → vp test in ${cacFile}`);
}
const cliApiFiles: string[] = [];
for await (const file of fsGlob(join(chunksDir, 'cli-api.*.js'))) {
cliApiFiles.push(file);
}
if (cliApiFiles.length === 0) {
throw new Error('brandVitest: no cli-api chunk found in dist/chunks/');
}
for (const cliApiFile of cliApiFiles) {
let content = await readFile(cliApiFile, 'utf-8');
function patchString(label: string, search: string | RegExp, replacement: string) {
const before = content;
content =
typeof search === 'string'
? content.replace(search, replacement)
: content.replace(search, replacement);
if (content === before) {
throw new Error(
`brandVitest: failed to patch "${label}" — pattern not found in ${cliApiFile}`,
);
}
}
// Remove one extra leading newline before DEV/RUN banner.
patchString(
'banner leading newline',
/printBanner\(\) \{\n\t\tthis\.log\(\);\n/,
'printBanner() {\n',
);
// Use a blue badge for both DEV and RUN.
patchString(
'banner color',
/const color = this\.ctx\.config\.watch \? "blue" : "[a-z]+";\n\t\tconst mode = this\.ctx\.config\.watch \? "DEV" : "RUN";/,
'const mode = this.ctx.config.watch ? "DEV" : "RUN";\n\t\tconst label = c.bold(c.inverse(c.blue(` ${mode} `)));',
);
// Remove the version from the banner line and render a high-contrast label.
patchString(
'banner version text',
/this\.log\(withLabel\(color, mode, (?:""|`v\$\{this\.ctx\.version\} `)\) \+ c\.gray\(this\.ctx\.config\.root\)\);/,
'this.log(`${label} ${c.gray(this.ctx.config.root)}`);',
);
await writeFile(cliApiFile, content, 'utf-8');
console.log(`Branded vitest banner in ${cliApiFile}`);
}
}
/**
* Copy @vitest/* packages from node_modules to dist/@vitest/
* This preserves the original file structure to maintain browser/Node.js separation.
* Unlike bundling with Rolldown, copying avoids creating shared chunks that mix
* Node.js-only code with browser code.
*/
async function copyVitestPackages() {
console.log('\nCopying @vitest/* packages to dist/@vitest/...');
const vitestDir = resolve(distDir, '@vitest');
await rm(vitestDir, { recursive: true, force: true });
await mkdir(vitestDir, { recursive: true });
let totalCopied = 0;
for (const pkg of VITEST_PACKAGES_TO_COPY) {
const pkgName = pkg.replace('@vitest/', '');
const srcDir = resolve(projectDir, `node_modules/${pkg}/dist`);
const destPkgDir = resolve(vitestDir, pkgName);
try {
await stat(srcDir);
} catch {
console.log(` Warning: ${pkg} not installed, skipping`);
continue;
}
console.log(` Copying ${pkg}...`);
const copied = await copyDirRecursive(srcDir, destPkgDir);
totalCopied += copied;
console.log(` -> ${copied} files`);
// Copy root .d.ts files from @vitest/browser package directory.
// These are type definitions that live at the package root (not in dist/),
// e.g. context.d.ts, matchers.d.ts, aria-role.d.ts, utils.d.ts.
// Dynamically scan instead of hardcoding to handle future upstream additions.
if (pkg === '@vitest/browser') {
const pkgRoot = resolve(projectDir, `node_modules/${pkg}`);
try {
const pkgEntries = await readdir(pkgRoot);
for (const entry of pkgEntries) {
if (entry.endsWith('.d.ts')) {
await copyFile(join(pkgRoot, entry), join(destPkgDir, entry));
console.log(` + copied ${entry}`);
totalCopied++;
}
}
} catch {
// Package root not readable, skip
}
}
}
console.log(`\nCopied ${totalCopied} files to dist/@vitest/`);
}
/**
* Recursively copy a directory
*/
async function copyDirRecursive(srcDir: string, destDir: string): Promise<number> {
await mkdir(destDir, { recursive: true });
const entries = await readdir(srcDir, { withFileTypes: true });
let count = 0;
for (const entry of entries) {
const srcPath = join(srcDir, entry.name);
const destPath = join(destDir, entry.name);
if (entry.isDirectory()) {
count += await copyDirRecursive(srcPath, destPath);
} else if (entry.isFile()) {
await copyFile(srcPath, destPath);
count++;
}
}
return count;
}
/**
* Collect leaf dependencies from copied @vitest/* files AND vitest core dist files.
* These are external packages that should be bundled (tinyrainbow, pathe, chai, expect-type, etc.)
* but NOT @vitest/*, vitest/*, vite/*, node built-ins, or blocklisted packages.
*/
async function collectLeafDependencies(): Promise<Set<string>> {
console.log('\nCollecting leaf dependencies from dist/...');
const leafDeps = new Set<string>();
const vitestDir = resolve(distDir, '@vitest');
// Scan both @vitest/* packages AND vitest core dist files
const jsFiles = fsGlob([
join(vitestDir, '**/*.js'),
join(distDir, '*.js'),
join(distDir, 'chunks/*.js'),
]);
for await (const file of jsFiles) {
const content = await readFile(file, 'utf-8');
const result = parseSync(file, content, { sourceType: 'module' });
// Collect ESM static imports
for (const imp of result.module.staticImports) {
const specifier = imp.moduleRequest.value;
if (isLeafDependency(specifier)) {
leafDeps.add(specifier);
}
}
// Collect ESM static exports (re-exports)
for (const exp of result.module.staticExports) {
for (const entry of exp.entries) {
if (entry.moduleRequest) {
const specifier = entry.moduleRequest.value;
if (isLeafDependency(specifier)) {
leafDeps.add(specifier);
}
}
}
}
// Collect dynamic imports (only string literals)
for (const dynImp of result.module.dynamicImports) {
const rawText = content.slice(dynImp.moduleRequest.start, dynImp.moduleRequest.end);
if (
(rawText.startsWith("'") && rawText.endsWith("'")) ||
(rawText.startsWith('"') && rawText.endsWith('"'))
) {
const specifier = rawText.slice(1, -1);
if (isLeafDependency(specifier)) {
leafDeps.add(specifier);
}
}
}
}
console.log(`Found ${leafDeps.size} leaf dependencies:`);
for (const dep of leafDeps) {
console.log(` - ${dep}`);
}
return leafDeps;
}
/**
* Check if a specifier is a leaf dependency that should be bundled.
* Leaf deps are external packages that are NOT:
* - @vitest/* (we copy these)
* - vitest or vitest/* (we copy vitest-dev)
* - vite or vite/* (we use our core package)
* - Node.js built-ins
* - Blocklisted packages
* - Relative paths
*/
function isLeafDependency(specifier: string): boolean {
// Relative paths
if (specifier.startsWith('.') || specifier.startsWith('/')) {
return false;
}
// @vitest/* packages (we copy these)
if (specifier.startsWith('@vitest/')) {
return false;
}
// vitest or vitest/* (we copy vitest-dev)
if (specifier === 'vitest' || specifier.startsWith('vitest/')) {
return false;
}
// vite or vite/* (we use our core package)
if (specifier === 'vite' || specifier.startsWith('vite/')) {
return false;
}
// Node.js built-ins
if (NODE_BUILTINS.has(specifier)) {
return false;
}
// Blocklisted packages
if (EXTERNAL_BLOCKLIST.has(specifier)) {
return false;
}
// Node.js subpath imports (#module-evaluator, etc.)
if (specifier.startsWith('#')) {
return false;
}
// Invalid specifiers
if (!/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*/.test(specifier)) {
return false;
}
return true;
}
/**
* Bundle only leaf dependencies into dist/vendor/.
* Only bundles non-@vitest deps (tinyrainbow, pathe, chai, etc.)
* to avoid shared chunks that mix Node.js and browser code.
*/
async function bundleLeafDeps(leafDeps: Set<string>): Promise<Map<string, string>> {
console.log('\nBundling leaf dependencies...');
await rm(vendorDir, { recursive: true, force: true });
await mkdir(vendorDir, { recursive: true });
const specifierToVendorPath = new Map<string, string>();
if (leafDeps.size === 0) {
console.log(' No leaf dependencies to bundle.');
return specifierToVendorPath;
}
// Build input object with all leaf deps
const input: Record<string, string> = {};
for (const dep of leafDeps) {
const safeName = safeFileName(dep);
input[safeName] = dep;
}
try {
await build({
input,
output: {
dir: vendorDir,
format: 'esm',
entryFileNames: '[name].mjs',
chunkFileNames: 'shared-[hash].mjs',
},
platform: 'neutral',
treeshake: false,
external: [
// Keep node built-ins external
...NODE_BUILTINS,
// Keep blocklisted packages external
...EXTERNAL_BLOCKLIST,
// Keep @vitest/* external (we copy them)
/@vitest\//,
// Keep vitest external (we copy it)
/^vitest(\/.*)?$/,
// Keep vite external (we use core package)
/^vite(\/.*)?$/,
],
resolve: {
conditionNames: ['node', 'import', 'default'],
mainFields: ['module', 'main'],
},
logLevel: 'warn',
});
const dtsInput = { ...input };
for (const name of Object.keys(dtsInput)) {
const vendorDtsPath = join(vendorDir, `vendor_${name}.d.ts`);
dtsInput[name] = vendorDtsPath;
await writeFile(vendorDtsPath, `export * from '${name}';`, 'utf-8');
}
await build({
input: dtsInput,
output: {
dir: vendorDir,
format: 'esm',
entryFileNames: '[name].mts',
},
plugins: [
dts({
dtsInput: true,
oxc: true,
resolver: 'oxc',
emitDtsOnly: true,
tsconfig: false,
}),
],
});
for (const p of Object.values(dtsInput)) {
await rm(p);
}
// Register all specifiers
for (const dep of leafDeps) {
const safeName = safeFileName(dep);
const vendorFilePath = join(vendorDir, `${safeName}.mjs`);
specifierToVendorPath.set(dep, vendorFilePath);
console.log(` -> vendor/${safeName}.mjs`);
// Fix CJS packages that need named exports extracted from default
if (CJS_REEXPORT_PACKAGES.has(dep)) {
await fixCjsNamedExports(vendorFilePath, dep);
}
}
} catch (error) {
console.error('Failed to bundle leaf dependencies:', error);
throw error;
}
console.log(`\nBundled ${specifierToVendorPath.size} leaf dependencies.`);
return specifierToVendorPath;
}
/**
* Rewrite imports in all copied @vitest/* files and vitest-dev dist files.
* This handles:
* - @vitest/* -> relative paths to dist/@vitest/
* - vitest/* -> relative paths to dist/
* - vite -> @voidzero-dev/vite-plus-core
* - leaf deps -> relative paths to dist/vendor/
*/
async function rewriteVitestImports(leafDepToVendorPath: Map<string, string>) {
console.log('\nRewriting imports in @vitest/* and vitest core files...');
const vitestDir = resolve(distDir, '@vitest');
let rewrittenCount = 0;
// Scan both @vitest/* packages AND vitest core dist files
// Include .d.ts files so TypeScript type imports also get rewritten
const jsFiles = fsGlob([
join(vitestDir, '**/*.js'),
join(vitestDir, '**/*.d.ts'),
join(distDir, '*.js'),
join(distDir, '*.d.ts'),
join(distDir, 'chunks/*.js'),
join(distDir, 'chunks/*.d.ts'),
]);
for await (const file of jsFiles) {
let content = await readFile(file, 'utf-8');
const fileDir = dirname(file);
// Build specifier map for this file
const specifierMap = new Map<string, string>();
// Add @vitest/* mappings (relative paths)
for (const [pkg, destPath] of Object.entries(VITEST_PACKAGE_TO_PATH)) {
const absoluteDest = resolve(distDir, destPath);
let relativePath = relative(fileDir, absoluteDest);
relativePath = relativePath.split('\\').join('/'); // Windows fix
if (!relativePath.startsWith('.')) {
relativePath = './' + relativePath;
}
specifierMap.set(pkg, absoluteDest);
}
// Add vitest/* mappings (relative to dist/)
const vitestSubpathRewrites: Record<string, string> = {
vitest: resolve(distDir, 'index.js'),
'vitest/node': resolve(distDir, 'node.js'),
'vitest/config': resolve(distDir, 'config.js'),
// vitest/browser exports page, server, CDPSession, BrowserCommands, etc from @vitest/browser/context
// This matches vitest's own package.json exports: "./browser" -> "./browser/context.d.ts"
'vitest/browser': resolve(distDir, '@vitest/browser/context.js'),
// vitest/internal/browser exports browser-safe __INTERNAL and stringify (NOT @vitest/browser/index.js which has Node.js code)
'vitest/internal/browser': resolve(distDir, 'browser.js'),
'vitest/runners': resolve(distDir, 'runners.js'),
'vitest/suite': resolve(distDir, 'suite.js'),
'vitest/environments': resolve(distDir, 'environments.js'),
'vitest/coverage': resolve(distDir, 'coverage.js'),
'vitest/reporters': resolve(distDir, 'reporters.js'),
'vitest/snapshot': resolve(distDir, 'snapshot.js'),
'vitest/mocker': resolve(distDir, 'mocker.js'),
};
for (const [specifier, absolutePath] of Object.entries(vitestSubpathRewrites)) {
specifierMap.set(specifier, absolutePath);
}
// Add leaf dep mappings (relative to vendor/)
for (const [specifier, vendorPath] of leafDepToVendorPath) {
specifierMap.set(specifier, vendorPath);
}
// For files inside @vitest/browser/, preserve 'vitest/browser' as a bare specifier.
// These files run in browser context where the vitest:vendor-aliases plugin
// resolves 'vitest/browser' to the virtual module '\0vitest/browser',
// which provides browser-safe context API (page, server, userEvent, utils).
// Without this, 'vitest/browser' gets rewritten to './index.js' which resolves
// to the Node.js server file (~9000 lines of node:fs, ws, etc.)
if (file.includes('@vitest/browser') || file.includes('@vitest\\browser')) {
specifierMap.delete('vitest/browser');
}
// Rewrite using AST
const rewritten = rewriteImportsWithAst(content, file, false, specifierMap);
// Also rewrite vite -> core package (simple string replacement since it's a package name)
let finalContent = rewritten
.replaceAll(/from ['"]vite['"]/g, `from '${CORE_PACKAGE_NAME}'`)
.replaceAll(/import\(['"]vite['"]\)/g, `import('${CORE_PACKAGE_NAME}')`)
.replaceAll(`'vite/module-runner'`, `'${CORE_PACKAGE_NAME}/module-runner'`);
// Special handling for @vitest/mocker entry files that have redundant side-effect imports
// The original files have: import 'magic-string'; export {...} from './chunk-automock.js'; import 'estree-walker';
// This is problematic because:
// 1. Side-effect imports are redundant (chunk files already import what they need)
// 2. Having imports after exports can confuse some module parsers
// Fix: Remove redundant side-effect imports from vendor deps in entry files
if (file.includes('@vitest/mocker') || file.includes('@vitest\\mocker')) {
// Get the base filename
const baseName = file.split(/[/\\]/).pop();
// Only process entry files (not chunk files)
if (baseName && !baseName.startsWith('chunk-')) {
// Remove side-effect imports from vendor deps (these are redundant since chunk files import them)
finalContent = finalContent.replace(/import\s*['"][^'"]*vendor[^'"]*\.mjs['"];?\s*/g, '');
}
}
if (finalContent !== content) {
await writeFile(file, finalContent, 'utf-8');
rewrittenCount++;
}
}
console.log(` Rewrote imports in ${rewrittenCount} files`);