forked from solidjs/vite-plugin-solid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
947 lines (864 loc) · 36.1 KB
/
Copy pathindex.ts
File metadata and controls
947 lines (864 loc) · 36.1 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
import * as babel from '@babel/core';
import type { TransformOptions as JsxCompilerOptions } from '@dom-expressions/compiler';
import remapping from '@ampproject/remapping';
import solid from 'babel-preset-solid';
import { existsSync, readFileSync } from 'fs';
import { mergeAndConcat } from 'merge-anything';
import { createRequire } from 'module';
import {
createDevAssetResolver,
registerDevAssetResolver,
DEV_MANIFEST_REGISTRY_KEY,
} from './dev-manifest.js';
import {
CLIENT_MANIFEST_ID,
RESOLVED_CLIENT_MANIFEST_ID,
CLIENT_MANIFEST_PLACEHOLDER,
buildClientAssetMap,
buildClientAssetMapFromManifest,
substituteClientManifest,
} from './client-manifest.js';
import { serverFunctions, type ServerFunctionsOptions } from './server-functions/index.js';
import { ssrServe, type SsrOptions } from './ssr/index.js';
export { devStylePatch } from './dev-manifest.js';
export type { ClientAssetMap } from './client-manifest.js';
export { serverFunctions };
export type { ServerFunctionsOptions };
export type { ServerFunctionsFilter } from './server-functions/index.js';
export type { SsrOptions };
import path from 'path';
import type { FilterPattern, Plugin } from 'vite';
import { createFilter, version } from 'vite';
import { crawlFrameworkPkgs } from 'vitefu';
const require = createRequire(import.meta.url);
/**
* The `lazy()` module-URL placeholder contract, shared with the native
* compiler's `transformLazy` pass: `lazy(() => import("spec"))` calls gain a
* second string-literal argument of the form
* `"__SOLID_LAZY_MODULE__:" + spec`, which `resolveLazyModuleUrls` swaps for
* the project-relative resolved module path. The prefix and shape are FROZEN
* — the emitting side lives in @dom-expressions/compiler and must match.
*/
const LAZY_PLACEHOLDER_PREFIX = '__SOLID_LAZY_MODULE__:';
/**
* The HMR runtime: the dev-only `solid-js/refresh` core entry. Refresh
* wrappers are compiled by the native `transformRefresh` pass in every mode
* and import the runtime through normal module resolution (the legacy
* solid-refresh package — whose runtime carries a known Solid 2.0 HMR bug,
* solid-refresh#85 — is no longer used at all).
*/
const REFRESH_RUNTIME_SOURCE = 'solid-js/refresh';
const viteVersionMajor = +version.split('.')[0];
const isVite8 = viteVersionMajor >= 8;
const VIRTUAL_MANIFEST_ID = 'virtual:solid-manifest';
const RESOLVED_VIRTUAL_MANIFEST_ID = '\0' + VIRTUAL_MANIFEST_ID;
// In dev the virtual manifest exports a `{ resolve, resolveSync }` resolver:
// lazy modules resolve to their dev URL plus transitively imported CSS as
// inline-style descriptors collected from the live module graph. The resolver
// itself lives plugin-side (it closes over the dev server) and is reached
// through a global registry; isolated module runners that don't share globals
// fall back to js-only resolution, which matches the previous dev behavior.
const devManifestCode = (root: string) => `const registry = globalThis[Symbol.for(${JSON.stringify(
DEV_MANIFEST_REGISTRY_KEY,
)})];
const fallback = key => ({ js: ["/" + key], css: [] });
export default (registry && registry[${JSON.stringify(root)}]) || { resolve: fallback, resolveSync: fallback };`;
const SOLID_BUILT_INS = [
'For',
'Show',
'Switch',
'Match',
'Loading',
'Reveal',
'Portal',
'Repeat',
'Dynamic',
'Errored',
];
/** Possible options for the extensions property */
export interface ExtensionOptions {
typescript?: boolean;
}
export type Compiler = 'babel' | 'native';
export type SolidOptions = Omit<JsxCompilerOptions, 'filename' | 'sourceMap'>;
type NativeCompiler = typeof import('@dom-expressions/compiler');
let nativeCompilerPromise: Promise<NativeCompiler> | undefined;
async function loadNativeCompiler() {
try {
return await (nativeCompilerPromise ??= import('@dom-expressions/compiler'));
} catch (error) {
nativeCompilerPromise = undefined;
const reason = error instanceof Error ? `\n\nCause: ${error.message}` : '';
throw new Error(
'vite-plugin-solid: failed to load @dom-expressions/compiler, which is required ' +
'in every mode (it drives the lazy, refresh, and server-function transforms; ' +
'compiler: "babel" only switches the JSX transform). Your platform should get ' +
'a prebuilt native binary or the @dom-expressions/compiler-wasm32-wasi fallback ' +
'— check that optional dependencies were installed.' +
reason,
);
}
}
/** Configuration options for vite-plugin-solid. */
export interface Options {
/**
* A [picomatch](https://github.com/micromatch/picomatch) pattern, or array of patterns, which specifies the files
* the plugin should operate on.
*/
include?: FilterPattern;
/**
* A [picomatch](https://github.com/micromatch/picomatch) pattern, or array of patterns, which specifies the files
* to be ignored by the plugin.
*/
exclude?: FilterPattern;
/**
* This will inject solid-js/dev in place of solid-js in dev mode. Has no
* effect in prod. If set to `false`, it won't inject it in dev. This is
* useful for extra logs and debugging.
*
* @default true
*/
dev?: boolean;
/**
* SSR support. `true` enables the SSR transforms only (hydratable client
* code, SSR server code) — you provide the entries and the server, as
* before.
*
* The object form (even empty: `ssr: {}`) additionally turns on turnkey
* serving:
*
* - Dev: a middleware on the Vite dev server streams the rendered app for
* HTML-accepting GET requests — `vite` just works, no server file.
* - Build: a plain `vite build` produces both bundles (client to
* `dist/client`, server to `dist/server` via the environments/builder
* API). The server bundle's entry is `virtual:solid-ssr-handler`, whose
* `handleRequest(request)` export maps a web `Request` to a streamed
* `Response` — mount it on any server or adapter in one line.
* - Entries: `src/entry-server.*` / `src/entry-client.*` are used when
* present (or set via `ssr.entryServer` / `ssr.entryClient`); when
* absent, both are generated from a root component (`ssr.app`, default
* `src/App.*`) wrapped in a document shell (`ssr.document`, default
* `src/Document.*`, else a built-in one).
* - With `serverFunctions` also enabled, the prod handler serves the
* server-function endpoint too (in dev the server-function middleware
* already runs first).
*
* @default false
*/
ssr?: boolean | SsrOptions;
/**
* JSX compiler backend to use. The default `"native"` compiles through
* `@dom-expressions/compiler`; `"babel"` is the escape hatch running
* `babel-preset-solid` instead — if native output ever differs from your
* expectations, set `compiler: "babel"` and file an issue (the behavioral
* diff between the modes is the bug report). Platforms without a prebuilt
* native binary (e.g. StackBlitz WebContainers) automatically use the wasm
* fallback; the compiler package itself is required in every mode.
*
* @default "native"
*/
compiler?: Compiler;
/**
* This will inject HMR runtime in dev mode. Has no effect in prod. If
* set to `false`, it won't inject the runtime in dev.
*
* @default true
* @deprecated use `refresh` instead
*/
hot?: boolean;
/**
* This registers additional extensions that should be processed by
* vite-plugin-solid.
*
* @default undefined
*/
extensions?: (string | [string, ExtensionOptions])[];
/**
* Pass any additional babel transform options. They will be merged with
* the transformations required by Solid.
*
* Note: with `compiler: "native"` the plugin is normally fully Babel-free
* (native lazy/refresh/JSX passes). Supplying custom babel options
* reintroduces a Babel support pass ahead of the native JSX transform to
* host them.
*
* @default {}
*/
babel?:
| babel.TransformOptions
| ((source: string, id: string, ssr: boolean) => babel.TransformOptions)
| ((source: string, id: string, ssr: boolean) => Promise<babel.TransformOptions>);
/**
* Pass any additional [babel-plugin-jsx-dom-expressions](https://github.com/ryansolid/dom-expressions/tree/main/packages/babel-plugin-jsx-dom-expressions#plugin-options).
* They will be merged with the defaults sets by [babel-preset-solid](https://github.com/solidjs/solid/blob/main/packages/babel-preset-solid/index.js#L8-L25).
*
* @default {}
*/
solid?: SolidOptions;
/**
* Enable `"use server"` server function compilation (experimental). Pass
* `true` for the defaults (runtime from @solidjs/web/server-functions) or
* an options object to customize. The directive transform sub-plugins are
* emitted ahead of the JSX transform in the returned plugin array.
*
* Turnkey setup: in dev, a middleware on the Vite server handles the
* endpoint (default `/_server`, joined with `base`) end to end — no
* server-function code needed in the server entry. For production SSR
* builds, import `virtual:solid-server-function-handler` in the server
* entry and mount its `handleServerFunctionRequest(request)` export on the
* endpoint; it eagerly imports every module containing server functions so
* registrations survive tree-shaking.
*
* Meta-frameworks that need to control plugin ordering themselves (e.g.
* relative to a file-system router) and dispatch requests through their
* own server should use the standalone `serverFunctions()` export instead,
* which never installs the dev middleware.
*
* @default undefined
*/
serverFunctions?: boolean | ServerFunctionsOptions;
/** Options for the solid-refresh HMR transform (dev only). */
refresh?: RefreshOptions;
}
/** Options for the solid-refresh HMR transform (dev only). */
export interface RefreshOptions {
/**
* Disable the refresh transform entirely (equivalent to the deprecated
* `hot: false`).
*/
disabled?: boolean;
/**
* Emit per-component `signature`/`dependencies` metadata so edits only
* remount components whose code actually changed.
*
* @default true
*/
granular?: boolean;
}
function getExtension(filename: string): string {
const index = filename.lastIndexOf('.');
return index < 0 ? '' : filename.substring(index).replace(/\?.+$/, '');
}
function containsSolidField(fields: Record<string, any>) {
const keys = Object.keys(fields);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key === 'solid') return true;
if (typeof fields[key] === 'object' && fields[key] != null && containsSolidField(fields[key]))
return true;
}
return false;
}
function getJestDomExport(setupFiles: string[]) {
return setupFiles?.some((path) => /jest-dom/.test(path))
? undefined
: ['@testing-library/jest-dom/vitest', '@testing-library/jest-dom/extend-expect'].find(
(path) => {
try {
require.resolve(path);
return true;
} catch (e) {
return false;
}
},
);
}
function getSolidOptions(options: Partial<Options>, isSsr: boolean, dev: boolean): SolidOptions {
let solidOptions: Pick<SolidOptions, 'generate' | 'hydratable'>;
if (options.ssr) {
if (isSsr) {
solidOptions = { generate: 'ssr', hydratable: true };
} else {
solidOptions = { generate: 'dom', hydratable: true };
}
} else {
solidOptions = { generate: 'dom', hydratable: false };
}
return {
moduleName: '@solidjs/web',
builtIns: SOLID_BUILT_INS,
contextToCustomElements: true,
wrapConditionals: true,
...solidOptions,
dev,
...(options.solid || {}),
};
}
async function getBabelUserOptions(
options: Partial<Options>,
source: string,
id: string,
isSsr: boolean,
) {
if (!options.babel) return {};
if (typeof options.babel !== 'function') return options.babel;
const babelOptions = options.babel(source, id, isSsr);
return babelOptions instanceof Promise ? await babelOptions : babelOptions;
}
function normalizeSourceMap(
map: string | babel.TransformOptions['inputSourceMap'] | null | undefined,
) {
if (typeof map === 'string') return JSON.parse(map);
return map || null;
}
type ChainableMap = string | babel.TransformOptions['inputSourceMap'] | null | undefined;
/**
* Merges the sourcemaps of sequential whole-file transforms (given in
* application order, earliest first) into one map tracing back to the
* original source.
*/
function combineSourcemaps(maps: ChainableMap[]) {
const chain = maps.filter((map): map is NonNullable<ChainableMap> => !!map);
if (chain.length === 0) return null;
if (chain.length === 1) return normalizeSourceMap(chain[0]);
// remapping expects most-recent-first.
return JSON.parse(remapping(chain.reverse() as any, () => null).toString());
}
/**
* Chunks emitted for lazy() targets are marked `isEntry` by Rollup even
* though they are semantically dynamic entries. Reclassify any entry that is
* dynamically imported by another chunk so the runtime's entry-asset
* detection (which keys off `isEntry`) can't pick a lazy facade instead of
* the real client entry. Works on both the Vite manifest.json shape and the
* raw Rollup output bundle — both key entries by name and expose
* `dynamicImports` / `isEntry` with the same meaning.
*/
function normalizeEmittedLazyEntries(manifest: Record<string, any>) {
const dynamicKeys = new Set<string>();
for (const key in manifest) {
const imports: string[] | undefined = manifest[key].dynamicImports;
if (imports) for (const dep of imports) dynamicKeys.add(dep);
}
for (const key of dynamicKeys) {
const entry = manifest[key];
if (entry && entry.isEntry) {
entry.isEntry = false;
entry.isDynamicEntry = true;
}
}
}
export default function solidPlugin(options: Partial<Options> = {}): Plugin[] {
const filter = createFilter(options.include, options.exclude);
let needHmr = false;
let replaceDev = false;
let projectRoot = process.cwd();
let isTestMode = false;
let isBuild = false;
let isSsrBuild = false;
let base = '/';
let clientOutDir: string | null = null;
let solidPkgsConfig: Awaited<ReturnType<typeof crawlFrameworkPkgs>>;
// The client build's manifest, read back by SSR builds. In builder-mode
// (single process, e.g. SolidStart's nitro plugin) the client build runs
// first and generateBundle records its actual outDir — authoritative, since
// such setups relocate it. Two-invocation builds (`vite build --outDir
// dist/client` then `vite build --ssr`) run in separate processes, so the
// SSR process falls back to the `dist/client` convention.
function clientManifestPath(): string | null {
for (const dir of [clientOutDir, 'dist/client']) {
if (!dir) continue;
const manifestPath = path.resolve(projectRoot, dir, '.vite/manifest.json');
if (existsSync(manifestPath)) return manifestPath;
}
return null;
}
// Dynamically imported project modules in the client build. Each is
// emitted as an explicit chunk so it always gets its own manifest entry
// keyed by source path — even when manualChunks or dual static/dynamic
// imports would otherwise fold it facade-less into a shared chunk (which
// would break resolveAssets lookups and hydration module preloading).
// Driven from moduleParsed so it covers every lazy() target, including
// import.meta.glob entries that never pass through the moduleUrl transform.
const emittedLazyChunks = new Set<string>();
// Keep the emitted references because a lazy module's importer may be
// removed from the final bundle, leaving no dynamic-import edge to identify
// its facade chunk during generateBundle.
const emittedLazyChunkRefs: string[] = [];
// Whether the current hook invocation belongs to a client (browser) build.
// Builder-mode builds (e.g. SolidStart's nitro plugin) run the client and
// ssr environments through one Vite process with shared plugins, so the
// process-wide isSsrBuild flag from configResolved can't tell them apart —
// the per-environment consumer can. Classic two-invocation builds
// (`vite build` / `vite build --ssr`) fall back to the flag.
function isClientBuild(ctx: { environment?: { config?: { consumer?: string } } }): boolean {
const consumer = ctx.environment?.config?.consumer;
if (consumer) return consumer === 'client';
return !isSsrBuild;
}
/**
* Replaces lazy() moduleUrl placeholders injected by the babel plugin with
* project-relative module paths resolved through Vite's resolver.
*/
async function resolveLazyModuleUrls(ctx: any, code: string, importer: string): Promise<string> {
const placeholderRe = new RegExp('"' + LAZY_PLACEHOLDER_PREFIX + '([^"]+)"', 'g');
let match;
const resolutions: Array<{ placeholder: string; resolved: string }> = [];
while ((match = placeholderRe.exec(code)) !== null) {
const specifier = match[1];
const resolved = await ctx.resolve(specifier, importer);
if (resolved) {
const cleanId = resolved.id.split('?')[0];
const relativeId = path.relative(projectRoot, cleanId).split(path.sep).join('/');
resolutions.push({
placeholder: match[0],
resolved: '"' + relativeId + '"',
});
}
}
for (const { placeholder, resolved } of resolutions) {
code = code.replace(placeholder, resolved);
}
return code;
}
/**
* SSR transforms append a `$$moduleUrl` export carrying the module's
* client-manifest key (project-relative source path). Server-side `lazy()`
* reads it off the resolved module when the callsite has no static import
* specifier to transform — e.g. `lazy` over an `import.meta.glob` entry —
* so asset resolution and hydration preloading still work. Client builds
* are untouched.
*/
function injectSsrModuleId(code: string, id: string, isSsr: boolean): string {
if (!isSsr || /node_modules/.test(id) || code.includes('$$moduleUrl')) return code;
const relativeId = path.relative(projectRoot, id).split(path.sep).join('/');
return code + `\nexport const $$moduleUrl = ${JSON.stringify(relativeId)};\n`;
}
const mainPlugin: Plugin = {
name: 'solid',
enforce: 'pre',
async config(userConfig, { command }) {
// We inject the dev mode only if the user explicitly wants it or if we are in dev (serve) mode
replaceDev = options.dev === true || (options.dev !== false && command === 'serve');
projectRoot = userConfig.root || projectRoot;
isTestMode = userConfig.mode === 'test';
solidPkgsConfig = await crawlFrameworkPkgs({
viteUserConfig: userConfig,
root: projectRoot || process.cwd(),
isBuild: command === 'build',
isFrameworkPkgByJson(pkgJson) {
return containsSolidField(pkgJson.exports || {});
},
});
// fix for bundling dev in production
const nestedDeps = replaceDev ? ['solid-js', '@solidjs/web'] : [];
const userTest = (userConfig as any).test ?? {};
const test = {} as any;
if (userConfig.mode === 'test') {
// to simplify the processing of the config, we normalize the setupFiles to an array
const userSetupFiles: string[] =
typeof userTest.setupFiles === 'string'
? [userTest.setupFiles]
: userTest.setupFiles || [];
if (!userTest.environment && !options.ssr) {
test.environment = 'jsdom';
}
if (
!userTest.server?.deps?.external?.find((item: string | RegExp) =>
/solid-js/.test(item.toString()),
)
) {
test.server = { deps: { external: [/solid-js/] } };
}
if (!userTest.browser?.enabled) {
// vitest browser mode already has bundled jest-dom assertions
// https://main.vitest.dev/guide/browser/assertion-api.html#assertion-api
const jestDomImport = getJestDomExport(userSetupFiles);
if (jestDomImport) {
test.setupFiles = [jestDomImport];
}
}
}
return {
/**
* We only need esbuild on .ts or .js files.
* .tsx & .jsx files are handled by us
*/
// esbuild: { include: /\.ts$/ },
// resolve.conditions is handled per-environment in configEnvironment.
resolve: {
dedupe: nestedDeps,
},
optimizeDeps: {
include: [
...nestedDeps,
// Dev refresh wrappers import the solid-js/refresh runtime in
// every mode; pre-bundle it up front so its discovery doesn't
// trigger a re-optimize + full reload on first use.
...(command === 'serve' && options.hot !== false && !options.refresh?.disabled
? [REFRESH_RUNTIME_SOURCE]
: []),
...solidPkgsConfig.optimizeDeps.include,
],
exclude: solidPkgsConfig.optimizeDeps.exclude,
// Vite 8+ uses Rolldown for dependency scanning. Rolldown defaults to
// React's automatic JSX runtime for .tsx files, injecting a
// react/jsx-dev-runtime import. Tell it to preserve JSX as-is since
// this plugin handles JSX transformation via babel-preset-solid.
...(isVite8 ? { rolldownOptions: { transform: { jsx: 'preserve' as const } } } : {}),
},
...(test.server ? { test } : {}),
};
},
// @ts-ignore This hook only works in Vite 6
async configEnvironment(name, config, opts) {
config.resolve ??= {};
// Emulate Vite default fallback for `resolve.conditions` if not set
if (config.resolve.conditions == null) {
// @ts-ignore These exports only exist in Vite 6
const { defaultClientConditions, defaultServerConditions } = await import('vite');
if (config.consumer === 'client' || name === 'client' || opts.isSsrTargetWebworker) {
config.resolve.conditions = [...defaultClientConditions];
} else {
config.resolve.conditions = [...defaultServerConditions];
}
}
config.resolve.conditions = [
'solid',
...(replaceDev ? ['development'] : []),
...(isTestMode && !opts.isSsrTargetWebworker && !options.ssr ? ['browser'] : []),
...config.resolve.conditions,
];
// Set resolve.noExternal and resolve.external for the SSR environment.
// Only set resolve.external if noExternal is not true (to avoid conflicts with plugins like Cloudflare)
if (name === 'ssr' && solidPkgsConfig) {
if (config.resolve.noExternal !== true) {
config.resolve.noExternal = [
...(Array.isArray(config.resolve.noExternal) ? config.resolve.noExternal : []),
...solidPkgsConfig.ssr.noExternal,
];
config.resolve.external = [
...(Array.isArray(config.resolve.external) ? config.resolve.external : []),
...solidPkgsConfig.ssr.external,
];
}
}
},
configResolved(config) {
isBuild = config.command === 'build';
isSsrBuild = !!config.build.ssr;
base = config.base;
projectRoot = config.root;
needHmr =
config.command === 'serve' &&
config.mode !== 'production' &&
options.hot !== false &&
!options.refresh?.disabled;
},
configureServer(server) {
// Dev asset resolution for SSR: the virtual manifest module (evaluated
// in the SSR environment) picks this resolver up through the global
// registry keyed by project root.
if (options.ssr) {
registerDevAssetResolver(server.config.root, createDevAssetResolver(server));
}
if (!needHmr) return;
// When a module has a syntax error, Vite sends the error overlay via
// WebSocket but the failed import triggers invalidation in solid-refresh.
// This propagates up to @refresh reload boundaries (e.g. document-level
// App components in SSR), causing a full-reload that overrides the overlay.
// We suppress update/full-reload messages that immediately follow an error.
const hot = server.hot ?? (server as any).ws;
if (!hot) return;
let lastErrorTime = 0;
const origSend = hot.send.bind(hot);
hot.send = function (this: any, ...args: any[]) {
const payload = args[0];
if (typeof payload === 'object' && payload) {
if (payload.type === 'error') {
lastErrorTime = Date.now();
} else if (
lastErrorTime &&
(payload.type === 'full-reload' || payload.type === 'update')
) {
if (Date.now() - lastErrorTime < 200) return;
lastErrorTime = 0;
}
}
return origSend(...args);
} as typeof hot.send;
},
hotUpdate({ modules }) {
// solid-refresh only injects HMR boundaries into client modules, so
// non-client environments have no accept handlers. Without this, Vite
// would see no boundaries and send full-reload messages that race with
// client-side HMR updates.
if (this.environment.name !== 'client') {
// Returning [] also suppresses the signal environment-runner based
// servers (e.g. nitro's dev worker) rely on to re-evaluate modules,
// leaving SSR stale until a manual restart. Send the reload on this
// environment's own channel — for runner-based environments that is
// the runner, for the default ssr environment a no-op, and never the
// browser websocket, so client HMR stays free of full-reload races.
if (modules.length > 0) {
this.environment.hot.send({ type: 'full-reload' });
}
return [];
}
},
resolveId(id) {
if (id === VIRTUAL_MANIFEST_ID) return RESOLVED_VIRTUAL_MANIFEST_ID;
if (id === CLIENT_MANIFEST_ID) return RESOLVED_CLIENT_MANIFEST_ID;
},
moduleParsed(info) {
// SSR-mode client builds only: give every dynamically imported project
// module its own facade chunk (exports-only preserves `default`
// re-exports) so it keeps a manifest entry keyed by its source path
// even when chunk grouping would otherwise absorb it. Plain SPA builds
// have no manifest lookups to protect.
if (!isBuild || !options.ssr || !isClientBuild(this)) return;
for (const depId of info.dynamicallyImportedIds || []) {
const cleanId = depId.split('?')[0];
if (/node_modules/.test(cleanId) || cleanId.startsWith('\0')) continue;
if (!/\.[mc]?[tj]sx?$/i.test(cleanId)) continue;
if (emittedLazyChunks.has(depId)) continue;
emittedLazyChunks.add(depId);
emittedLazyChunkRefs.push(
this.emitFile({ type: 'chunk', id: depId, preserveSignature: 'exports-only' }),
);
}
},
load(id) {
if (id === RESOLVED_VIRTUAL_MANIFEST_ID) {
if (!isBuild) return devManifestCode(projectRoot);
const manifestPath = clientManifestPath();
if (manifestPath) {
const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));
normalizeEmittedLazyEntries(manifest);
manifest._base = base;
return `export default ${JSON.stringify(manifest)};`;
}
// SSR build before the client build produced a manifest: bake in the
// dev-shaped fallback (registry miss degrades to js-only resolution).
return devManifestCode(projectRoot);
}
if (id === RESOLVED_CLIENT_MANIFEST_ID) {
// Client-side flavor: dynamic-entry source keys → resolved client
// asset URLs, for routers managing route CSS/preloads on navigation.
// Dev exports an empty map (Vite's client owns dev CSS lifecycle).
if (!isBuild) return 'export default {};';
if (isClientBuild(this)) {
// The map is only known once the client bundle exists; emit a
// placeholder that generateBundle substitutes.
return `export default ${JSON.stringify(CLIENT_MANIFEST_PLACEHOLDER)};`;
}
const manifestPath = clientManifestPath();
if (manifestPath) {
const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));
normalizeEmittedLazyEntries(manifest);
return `export default ${JSON.stringify(buildClientAssetMapFromManifest(manifest, base))};`;
}
return 'export default {};';
}
},
augmentChunkHash(chunkInfo) {
// The client-manifest chunk's final content (substituted in
// generateBundle, after hashing) is a function of every css source and
// the dynamic-import graph. Fold those inputs into the hash so a
// content change can't hide under an unchanged filename.
if (
!isBuild ||
!isClientBuild(this) ||
!chunkInfo.moduleIds?.includes(RESOLVED_CLIENT_MANIFEST_ID)
) {
return;
}
let acc = '';
for (const id of this.getModuleIds()) {
const info = this.getModuleInfo(id);
if (/\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)$/.test(id.split('?')[0])) {
acc += id + '\0' + (info?.code || '');
} else if (info?.dynamicallyImportedIds?.length) {
acc += id + '>' + info.dynamicallyImportedIds.join(',') + '\0';
}
}
return acc;
},
generateBundle(outputOptions, bundle) {
if (!isBuild || !isClientBuild(this)) return;
clientOutDir = outputOptions.dir ?? null;
// Reclassify emitted lazy facade chunks in the raw bundle (not just the
// serialized manifest read back later) so downstream plugins inspecting
// the bundle don't mistake them for application entries. Must precede
// the client asset map build, which keys off dynamic entries.
if (options.ssr) {
for (const ref of emittedLazyChunkRefs) {
let fileName: string;
try {
fileName = this.getFileName(ref);
} catch {
// Ignore references retained from a previous watch build.
continue;
}
const chunk = bundle[fileName];
if (!chunk || chunk.type !== 'chunk') continue;
chunk.isEntry = false;
chunk.isDynamicEntry = true;
}
normalizeEmittedLazyEntries(bundle);
}
substituteClientManifest(bundle, buildClientAssetMap(bundle, projectRoot, base));
},
async transform(source, id, transformOptions) {
const isSsr = transformOptions && transformOptions.ssr;
const currentFileExtension = getExtension(id);
const extensionsToWatch = options.extensions || [];
const allExtensions = extensionsToWatch.map((extension) =>
// An extension can be a string or a tuple [extension, options]
typeof extension === 'string' ? extension : extension[0],
);
if (!filter(id)) {
return null;
}
id = id.replace(/\?.*$/, '');
if (!(/\.[mc]?[tj]sx$/i.test(id) || allExtensions.includes(currentFileExtension))) {
return null;
}
const inNodeModules = /node_modules/.test(id);
const solidOptions = getSolidOptions(options, !!isSsr, replaceDev);
// We need to know if the current file extension has a typescript options tied to it
const shouldBeProcessedWithTypescript =
/\.[mc]?tsx$/i.test(id) ||
extensionsToWatch.some((extension) => {
if (typeof extension === 'string') {
return extension.includes('tsx');
}
const [extensionName, extensionOptions] = extension;
if (extensionName !== currentFileExtension) return false;
return extensionOptions.typescript;
});
const plugins: NonNullable<NonNullable<babel.TransformOptions['parserOpts']>['plugins']> = [
'jsx',
'decorators',
];
if (shouldBeProcessedWithTypescript) {
plugins.push('typescript');
}
const needRefresh = needHmr && !isSsr && !inNodeModules;
const babelUserOptions = await getBabelUserOptions(options, source, id, !!isSsr);
// The native compiler picks its parser dialect from the file
// extension; custom extensions registered through `options.extensions`
// are unknown to it, so borrow a standard one matching the configured
// TypeScript-ness.
const nativeFilename = /\.(?:[mc]?[jt]s|[jt]sx)$/i.test(id)
? id
: id + (shouldBeProcessedWithTypescript ? '.tsx' : '.jsx');
// Shared native prelude for every mode: the lazy() module-URL pass,
// then (dev/client/non-node_modules) the solid-refresh HMR pass, both
// operating on pre-JSX source. Only the JSX transform itself differs
// between compiler backends. Sourcemaps are collected in application
// order and merged at the end.
const compiler = await loadNativeCompiler();
let code = source;
const maps: ChainableMap[] = [];
const lazyResult = await compiler.transformLazyAsync(code, {
filename: nativeFilename,
sourceMap: true,
});
code = lazyResult.code;
maps.push(lazyResult.map);
if (needRefresh) {
const refreshResult = await compiler.transformRefreshAsync(code, {
filename: nativeFilename,
bundler: 'vite',
fixRender: true,
// The napi validator rejects explicit undefined; omit to get the
// pass's default (true).
...(typeof options.refresh?.granular === 'boolean'
? { granular: options.refresh.granular }
: {}),
jsx: false,
importSource: REFRESH_RUNTIME_SOURCE,
sourceMap: true,
});
code = refreshResult.code;
maps.push(refreshResult.map);
}
const babelBaseOptions: babel.TransformOptions = {
root: projectRoot,
filename: id,
sourceFileName: id,
ast: false,
sourceMaps: true,
configFile: false,
babelrc: false,
parserOpts: {
plugins,
},
};
if (options.compiler !== 'babel') {
if (options.babel) {
// Custom babel options reintroduce a Babel support pass hosting
// only the user's plugins, ahead of the native JSX transform.
const supportOptions = mergeAndConcat(
babelUserOptions,
babelBaseOptions,
) as babel.TransformOptions;
const supportResult = await babel.transformAsync(code, supportOptions);
if (!supportResult) {
return undefined;
}
code = supportResult.code || '';
maps.push(supportResult.map);
}
const result = await compiler.transformAsync(code, {
...solidOptions,
filename: id,
sourceMap: true,
});
maps.push(result.map);
const finalCode = injectSsrModuleId(
await resolveLazyModuleUrls(this, result.code || '', id),
id,
!!isSsr,
);
return { code: finalCode, map: combineSourcemaps(maps) };
}
// Babel JSX backend: one babel.transformAsync hosting the user's
// options plus babel-preset-solid.
const babelOptions = mergeAndConcat(babelUserOptions, {
...babelBaseOptions,
presets: [[solid, solidOptions]],
}) as babel.TransformOptions;
const result = await babel.transformAsync(code, babelOptions);
if (!result) {
return undefined;
}
maps.push(result.map);
const finalCode = injectSsrModuleId(
await resolveLazyModuleUrls(this, result.code || '', id),
id,
!!isSsr,
);
return { code: finalCode, map: combineSourcemaps(maps) };
},
};
// The directive transform must run before the JSX transform (it operates
// on raw directives, and client-mode module-level extraction must happen
// before templates are generated), so its sub-plugins go first.
const plugins: Plugin[] = options.serverFunctions
? [
...serverFunctions(options.serverFunctions === true ? {} : options.serverFunctions, {
devMiddleware: true,
}),
mainPlugin,
]
: [mainPlugin];
// The object form of `ssr` opts into turnkey serving on top of the
// transforms (`ssr: true` keeps the historical transform-only behavior).
if (typeof options.ssr === 'object' && options.ssr !== null) {
plugins.push(...ssrServe(options.ssr, { serverFunctions: !!options.serverFunctions }));
}
return plugins;
}
export type ViteManifest = Record<
string,
{
file: string;
css?: string[];
isEntry?: boolean;
isDynamicEntry?: boolean;
imports?: string[];
}
> & {
_base?: string;
};