solid-optimizer 0.4.0 → 1.0.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/vite/index.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
- * `solid-optimizer/vite`: `vite-plugin-solid` with the optimizer built in.
2
+ * `solid-optimizer/vite`: `@solidjs/vite-plugin` with the optimizer built in.
3
3
  *
4
- * It takes the same options as `vite-plugin-solid`, plus `optimizer`, and
5
- * returns the official plugin with the optimizer wired in. It runs in one of
4
+ * It takes the same options as `@solidjs/vite-plugin`, plus `optimizer`, and
5
+ * returns the official plugins with the optimizer wired in. It runs in one of
6
6
  * two modes.
7
7
  *
8
8
  * - Chunk mode keeps JSX through bundling. Each chunk is optimized as a whole
@@ -18,13 +18,13 @@ import { readFile } from 'node:fs/promises';
18
18
  import { createRequire } from 'node:module';
19
19
  import path from 'node:path';
20
20
  import remapping from '@jridgewell/remapping';
21
- import type * as Babel from '@babel/core';
22
21
  import MagicString from 'magic-string';
22
+ import type * as SolidCompiler from '@solidjs/compiler';
23
+ import type { Options as SolidPluginOptions } from '@solidjs/vite-plugin';
24
+ import solidPlugin from '@solidjs/vite-plugin';
23
25
  import type { Node, Program } from 'oxc-parser';
24
26
  import type { Plugin, ResolvedConfig, Rollup } from 'vite';
25
27
  import { createFilter, transformWithOxc } from 'vite';
26
- import type { Options as SolidPluginOptions } from 'vite-plugin-solid';
27
- import solidPlugin from 'vite-plugin-solid';
28
28
  import type { CompileOptions, CompileResult, ModuleConstants } from '../compile';
29
29
  import { compile, readModuleConstants } from '../compile';
30
30
  import { collectParents, forEachChild, isIntrinsicTag, parse } from '../ast';
@@ -32,6 +32,7 @@ import { analyzeScopes } from '../scope';
32
32
  import { CONTEXT_SAFE_PRIMITIVES } from '../provider';
33
33
  import type { ImportedConstants } from '../constants';
34
34
  import type { Primitive } from '../value';
35
+ import { sharedGlobals } from './globals';
35
36
  import type { Skip } from '../context';
36
37
  import type { OptimizerReport } from './report';
37
38
  import { formatReport } from './report';
@@ -44,6 +45,7 @@ import {
44
45
  MARKER,
45
46
  MissingHelperError,
46
47
  addMarker,
48
+ generatedImports,
47
49
  linkHelpers,
48
50
  readMarkers,
49
51
  repairJSXSequences,
@@ -53,13 +55,6 @@ export interface OptimizerOptions extends Pick<
53
55
  CompileOptions,
54
56
  'fold' | 'inline' | 'alwaysInline' | 'contexts' | 'memos' | 'maxPasses'
55
57
  > {
56
- /**
57
- * Reduce Solid's reactive primitives to what they do on the server, in
58
- * server builds. See the `server` option of `compile`.
59
- *
60
- * @default true
61
- */
62
- server?: boolean;
63
58
  /**
64
59
  * Where the optimizer runs.
65
60
  *
@@ -89,35 +84,14 @@ export interface OptimizerOptions extends Pick<
89
84
  export type { OptimizerReport } from './report';
90
85
 
91
86
  export interface Options extends Partial<SolidPluginOptions> {
92
- /** Set to `false` to use `vite-plugin-solid` as it is. */
87
+ /** Set to `false` to use `@solidjs/vite-plugin` as it is. */
93
88
  optimizer?: OptimizerOptions | false;
94
89
  }
95
90
 
96
- /** The options `babel-preset-solid` takes. */
97
- type JSXOptions = NonNullable<SolidPluginOptions['solid']> & {
98
- generate?: 'dom' | 'ssr' | 'universal';
99
- hydratable?: boolean;
100
- };
91
+ type Compiler = typeof SolidCompiler;
92
+ type JSXOptions = SolidCompiler.TransformOptions;
101
93
 
102
- interface Compiler {
103
- readonly babel: typeof Babel;
104
- readonly preset: Babel.PluginTarget;
105
- }
106
-
107
- const DEFAULT_MODULE_NAME = 'solid-js/web';
108
-
109
- const DEFAULT_BUILT_INS = [
110
- 'For',
111
- 'Show',
112
- 'Switch',
113
- 'Match',
114
- 'Suspense',
115
- 'SuspenseList',
116
- 'Portal',
117
- 'Index',
118
- 'Dynamic',
119
- 'ErrorBoundary',
120
- ];
94
+ const DEFAULT_MODULE_NAME = '@solidjs/web';
121
95
 
122
96
  const JSX_MODULE = /\.[mc]?[jt]sx$/i;
123
97
 
@@ -142,6 +116,8 @@ function withRelated(helpers: readonly string[]): Set<string> {
142
116
  return result;
143
117
  }
144
118
 
119
+ const LAZY_PLACEHOLDER = /"__SOLID_LAZY_MODULE__:([^"]+)"/g;
120
+
145
121
  /**
146
122
  * The common kinds of attribute: a class, any other attribute, events, and
147
123
  * children. Inlining a component turns a spread onto an element into
@@ -180,84 +156,11 @@ function spreadsOntoElement(code: string, filename: string): boolean {
180
156
  }
181
157
 
182
158
  function loadCompiler(): Compiler {
183
- // Use the Babel and preset `vite-plugin-solid` uses, so both lower JSX the same way.
159
+ // Use the compiler `@solidjs/vite-plugin` uses, so both lower JSX the same way.
184
160
  const require = createRequire(import.meta.url);
185
- const pluginRequire = createRequire(require.resolve('vite-plugin-solid'));
186
- const presetRequire = createRequire(pluginRequire.resolve('babel-preset-solid'));
161
+ const pluginRequire = createRequire(require.resolve('@solidjs/vite-plugin'));
187
162
  // oxlint-disable-next-line typescript/no-unsafe-type-assertion
188
- const babel = presetRequire('@babel/core') as typeof Babel;
189
- const preset: unknown = pluginRequire('babel-preset-solid');
190
- if (typeof preset !== 'function') {
191
- throw new TypeError('[solid-optimizer] babel-preset-solid did not load');
192
- }
193
- return { babel, preset };
194
- }
195
-
196
- /**
197
- * Lowers JSX with `babel-preset-solid`, as `vite-plugin-solid` does.
198
- */
199
- function lower(
200
- compiler: Compiler,
201
- code: string,
202
- filename: string,
203
- options: JSXOptions,
204
- sourceMaps: boolean,
205
- ): { code: string; map: string | undefined } {
206
- const result = compiler.babel.transformSync(code, {
207
- filename,
208
- sourceFileName: filename,
209
- presets: [[compiler.preset, options]],
210
- ast: false,
211
- sourceMaps,
212
- configFile: false,
213
- babelrc: false,
214
- parserOpts: {
215
- plugins: /\.[mc]?tsx$/i.test(filename) ? ['jsx', 'typescript'] : ['jsx'],
216
- },
217
- });
218
- // An empty module, like a chunk a library build left empty, lowers to ''.
219
- if (typeof result?.code !== 'string') {
220
- throw new Error(`[solid-optimizer] babel-preset-solid produced no code for ${filename}`);
221
- }
222
- return { code: result.code, map: result.map ? JSON.stringify(result.map) : undefined };
223
- }
224
-
225
- /**
226
- * The helpers `babel-preset-solid` imports from `moduleName` to lower `code`.
227
- * Only the AST is built, since its code would only be read for its imports.
228
- */
229
- function helpersOf(
230
- compiler: Compiler,
231
- code: string,
232
- filename: string,
233
- options: JSXOptions,
234
- moduleName: string,
235
- ): string[] {
236
- const result = compiler.babel.transformSync(code, {
237
- filename,
238
- presets: [[compiler.preset, options]],
239
- ast: true,
240
- code: false,
241
- configFile: false,
242
- babelrc: false,
243
- parserOpts: {
244
- plugins: /\.[mc]?tsx$/i.test(filename) ? ['jsx', 'typescript'] : ['jsx'],
245
- },
246
- });
247
- const names: string[] = [];
248
- for (const statement of result?.ast?.program.body ?? []) {
249
- if (statement.type !== 'ImportDeclaration' || statement.source.value !== moduleName) {
250
- continue;
251
- }
252
- for (const specifier of statement.specifiers) {
253
- // Generated imports are named `_$helper`, which the module's own are not.
254
- if (specifier.type === 'ImportSpecifier' && specifier.local.name.startsWith('_$')) {
255
- const { imported } = specifier;
256
- names.push(imported.type === 'StringLiteral' ? imported.value : imported.name);
257
- }
258
- }
259
- }
260
- return names;
163
+ return pluginRequire('@solidjs/compiler') as Compiler;
261
164
  }
262
165
 
263
166
  function stripQuery(id: string): string {
@@ -319,14 +222,27 @@ function isClient(context: { environment?: { config: { consumer: string } } }):
319
222
 
320
223
  export default function solidOptimizer(options: Options = {}): Plugin[] {
321
224
  const { optimizer: optimizerOption, ...solidOptions } = options;
322
- const main = solidPlugin(solidOptions);
225
+ const plugins = solidPlugin(solidOptions);
323
226
  if (optimizerOption === false) {
324
- return [main];
227
+ return plugins;
325
228
  }
326
229
  const optimizer = optimizerOption ?? {};
327
230
  const moduleName = solidOptions.solid?.moduleName ?? DEFAULT_MODULE_NAME;
328
231
  const moduleSources = [...new Set(['solid-js', DEFAULT_MODULE_NAME, moduleName])];
329
- const builtIns = new Set(solidOptions.solid?.builtIns ?? DEFAULT_BUILT_INS);
232
+ const builtIns = new Set(
233
+ solidOptions.solid?.builtIns ?? [
234
+ 'For',
235
+ 'Show',
236
+ 'Switch',
237
+ 'Match',
238
+ 'Loading',
239
+ 'Reveal',
240
+ 'Portal',
241
+ 'Repeat',
242
+ 'Dynamic',
243
+ 'Errored',
244
+ ],
245
+ );
330
246
  const compileOptions: CompileOptions = {
331
247
  fold: optimizer.fold,
332
248
  inline: optimizer.inline,
@@ -339,20 +255,6 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
339
255
  report: optimizer.report !== undefined && optimizer.report !== false,
340
256
  };
341
257
 
342
- let config: ResolvedConfig | undefined;
343
- /**
344
- * A skip's name with the module it names, like `Card (/app/src/card.tsx)`,
345
- * relative to the project root, or to `node_modules` for a package.
346
- */
347
- const shortName = (name: string): string =>
348
- name.replace(/\((\/.*)\)$/, (whole, file: string) => {
349
- const index = file.lastIndexOf('/node_modules/');
350
- if (index !== -1) {
351
- return `(${file.slice(index + '/node_modules/'.length)})`;
352
- }
353
- return config ? `(${path.relative(config.root, file)})` : whole;
354
- });
355
-
356
258
  /** What the final compile of each chunk or module left alone, by environment. */
357
259
  const skips = new Map<string, Skip[]>();
358
260
  const addSkips = (context: { environment?: { name: string } }, list?: readonly Skip[]): void => {
@@ -361,10 +263,13 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
361
263
  }
362
264
  const environment = context.environment?.name ?? 'client';
363
265
  const entries = skips.get(environment) ?? [];
364
- entries.push(...list.map((skip) => ({ ...skip, name: shortName(skip.name) })));
266
+ entries.push(...list);
365
267
  skips.set(environment, entries);
366
268
  };
367
269
 
270
+ let config: ResolvedConfig | undefined;
271
+ /** The `define` entries and `import.meta.env` values every environment shares. */
272
+ let globals: Record<string, Primitive> = {};
368
273
  let compiler: Compiler | undefined;
369
274
  let filter: ((id: string) => boolean) | undefined;
370
275
  const getCompiler = (): Compiler => {
@@ -378,24 +283,38 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
378
283
 
379
284
  /**
380
285
  * The JSX options the official plugin passes for a posture, so the
381
- * lowering here matches it. Mirrors the `transform` hook of `vite-plugin-solid`.
286
+ * lowering here matches it. Mirrors `getSolidOptions` in `@solidjs/vite-plugin`.
382
287
  */
383
288
  const jsxOptions = (isSsr: boolean): JSXOptions => {
384
- let posture: JSXOptions = { generate: 'dom', hydratable: false };
385
- if (solidOptions.ssr) {
289
+ let posture: Pick<JSXOptions, 'generate' | 'hydratable'>;
290
+ if (solidOptions.start && !solidOptions.ssr) {
291
+ posture = { generate: isSsr ? 'ssr' : 'dom', hydratable: false };
292
+ } else if (solidOptions.ssr) {
386
293
  posture = { generate: isSsr ? 'ssr' : 'dom', hydratable: true };
294
+ } else {
295
+ posture = { generate: 'dom', hydratable: false };
296
+ }
297
+ const dev = solidOptions.dev === true || (solidOptions.dev !== false && !isBuild());
298
+ const names = dev || solidOptions.observe === true;
299
+ const { sourceNames, ...rest } = solidOptions.solid ?? {};
300
+ let resolvedNames: JSXOptions['sourceNames'] = false;
301
+ if (typeof sourceNames === 'boolean') {
302
+ resolvedNames = sourceNames;
303
+ } else if (sourceNames !== undefined || names) {
304
+ const components = sourceNames?.components ?? names;
305
+ const bindings = sourceNames?.bindings ?? names;
306
+ resolvedNames = components || bindings ? { components, bindings } : false;
387
307
  }
388
- return { ...posture, ...solidOptions.solid };
308
+ return { ...posture, dev, sourceNames: resolvedNames, ...rest };
389
309
  };
390
310
 
391
311
  let sampleHelpers: string[] | undefined;
392
312
  /** The helpers the JSX transform uses for attributes in chunk mode. */
393
313
  const attributeHelpers = (): string[] => {
394
- sampleHelpers ??= helpersOf(
395
- getCompiler(),
396
- ATTRIBUTE_SAMPLE,
314
+ sampleHelpers ??= generatedImports(
315
+ getCompiler().transform(ATTRIBUTE_SAMPLE, { ...jsxOptions(false), filename: 'sample.jsx' })
316
+ .code,
397
317
  'sample.jsx',
398
- jsxOptions(false),
399
318
  moduleName,
400
319
  );
401
320
  return sampleHelpers;
@@ -408,8 +327,8 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
408
327
  if (!isBuild() || (optimizer.mode ?? 'auto') !== 'auto') {
409
328
  return false;
410
329
  }
411
- // The user's Babel plugins have to see the modules, which chunk mode skips.
412
- if (solidOptions.babel) {
330
+ // A Babel pass or backend has to see the modules, which chunk mode skips.
331
+ if (solidOptions.babel || solidOptions.compiler === 'babel') {
413
332
  return false;
414
333
  }
415
334
  const client = jsxOptions(false);
@@ -417,114 +336,162 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
417
336
  };
418
337
 
419
338
  const isJSXModule = (id: string): boolean => {
420
- filter ??= createFilter(solidOptions.include, solidOptions.exclude);
339
+ filter ??= createFilter(solidOptions.include, solidOptions.exclude, {
340
+ resolve: config?.root,
341
+ });
421
342
  return filter(id) && JSX_MODULE.test(stripQuery(id));
422
343
  };
423
344
 
424
345
  /** Modules that keep their JSX, which the bundler must parse as JSX. */
425
346
  const preserved = new Set<string>();
426
347
 
427
- /** What each module imports and the constants it exports, by module id. */
428
- const moduleConstants = new Map<string, Promise<ModuleConstants | undefined>>();
429
-
430
348
  /**
431
- * The module an import resolves to, when its constants can be read.
349
+ * What each module imports and the constants it exports, by module id,
350
+ * once read in full. A module whose constants needed a module with JSX
351
+ * that could not be loaded, to avoid a cycle, is not kept, since another
352
+ * transform may load it.
432
353
  *
433
- * A module with JSX is skipped. This plugin's transform may be waiting for
434
- * it, and it may be waiting for this one, so loading it could deadlock.
435
- * Dependencies are skipped to keep the build fast.
354
+ * A read in progress is never shared. It can wait for a module with JSX,
355
+ * and a read that waited for it would wait for that module too, without
356
+ * the cycle checks knowing. Two reads of modules that import each other
357
+ * would also wait for each other.
358
+ */
359
+ const moduleConstants = new Map<string, ConstantsResult>();
360
+
361
+ interface ConstantsResult {
362
+ readonly constants: ModuleConstants | undefined;
363
+ /** Whether a module with JSX was left out to avoid a cycle. */
364
+ readonly partial: boolean;
365
+ }
366
+
367
+ /**
368
+ * The module an import resolves to, when its constants can be read, and
369
+ * whether it has JSX. Dependencies are skipped to keep the build fast.
436
370
  */
437
371
  async function resolveConstantModule(
438
372
  context: Rollup.PluginContext,
439
373
  specifier: string,
440
374
  importer: string,
441
- ): Promise<string | undefined> {
375
+ ): Promise<{ id: string; jsx: boolean } | undefined> {
442
376
  if (moduleSources.includes(specifier)) {
443
377
  return undefined;
444
378
  }
445
379
  const resolved = await context.resolve(specifier, importer);
446
- if (
447
- !resolved ||
448
- resolved.external ||
449
- resolved.id.includes('/node_modules/') ||
450
- isJSXModule(resolved.id)
451
- ) {
380
+ if (!resolved || resolved.external || resolved.id.includes('/node_modules/')) {
452
381
  return undefined;
453
382
  }
454
- return resolved.id;
383
+ return { id: resolved.id, jsx: isJSXModule(resolved.id) };
384
+ }
385
+
386
+ /**
387
+ * The code of a module with JSX to read constants from, as this plugin's
388
+ * transform returns it. `transform` is the module whose transform waits for
389
+ * it, which the cycle checks are about. `undefined` when that could wait
390
+ * for itself.
391
+ */
392
+ async function loadJSXModule(
393
+ context: Rollup.PluginContext,
394
+ transform: string,
395
+ target: string,
396
+ ): Promise<string | undefined> {
397
+ return chunkMode() && isClient(context)
398
+ ? loadModule(context, transform, target)
399
+ : loadRecorded(context, transform, target);
455
400
  }
456
401
 
457
402
  /**
458
403
  * The constants of the modules `code` imports, keyed by import specifier.
459
404
  *
460
405
  * Each module is read as the bundler loads it, after every plugin has
461
- * transformed it, so a plugin that replaces or rewrites a module is seen.
462
- * A module that imports constants itself resolves them first, and a cycle
463
- * leaves the modules in it without them.
406
+ * transformed it. A module with JSX is read from this plugin's own output
407
+ * for it, unless its transform could be waiting for `transform`.
464
408
  */
465
409
  async function importedConstants(
466
410
  context: Rollup.PluginContext,
467
411
  imports: readonly string[],
468
412
  importer: string,
469
413
  visiting: ReadonlySet<string>,
470
- ): Promise<ImportedConstants> {
414
+ transform: string,
415
+ ): Promise<{ constants: ImportedConstants; partial: boolean }> {
416
+ let partial = false;
471
417
  const entries = await Promise.all(
472
418
  imports.map(async (specifier) => {
473
- const id = await resolveConstantModule(context, specifier, importer);
474
- if (id === undefined || visiting.has(id)) {
419
+ const target = await resolveConstantModule(context, specifier, importer);
420
+ if (target === undefined || visiting.has(target.id)) {
475
421
  return undefined;
476
422
  }
477
- const constants = await constantsOf(context, id, visiting);
478
- if (!constants || Object.keys(constants.exports).length === 0) {
423
+ const result = await constantsOf(context, target, visiting, transform);
424
+ partial ||= result.partial;
425
+ if (!result.constants || Object.keys(result.constants.exports).length === 0) {
479
426
  return undefined;
480
427
  }
481
- return [specifier, constants.exports] as const;
428
+ return [specifier, result.constants.exports] as const;
482
429
  }),
483
430
  );
484
- return Object.fromEntries(
485
- entries.filter(
486
- (entry): entry is readonly [string, Record<string, Primitive>] => entry !== undefined,
487
- ),
488
- );
431
+ return {
432
+ constants: Object.fromEntries(entries.filter((entry) => entry !== undefined)),
433
+ partial,
434
+ };
489
435
  }
490
436
 
491
437
  async function constantsOf(
492
438
  context: Rollup.PluginContext,
493
- id: string,
439
+ target: { id: string; jsx: boolean },
494
440
  visiting: ReadonlySet<string>,
495
- ): Promise<ModuleConstants | undefined> {
496
- let pending = moduleConstants.get(id);
497
- if (!pending) {
498
- pending = (async () => {
499
- const { code } = await context.load({ id });
500
- if (code === null) {
501
- return undefined;
441
+ transform: string,
442
+ ): Promise<ConstantsResult> {
443
+ const { id } = target;
444
+ const known = moduleConstants.get(id);
445
+ if (known) {
446
+ return known;
447
+ }
448
+ const result = await (async (): Promise<ConstantsResult> => {
449
+ let code: string | null | undefined;
450
+ if (target.jsx) {
451
+ code = await loadJSXModule(context, transform, id);
452
+ if (code === undefined) {
453
+ return { constants: undefined, partial: true };
502
454
  }
503
- // Loaded code is JavaScript, whatever the module was written in.
504
- const filename = `${stripQuery(id)}.js`;
505
- try {
506
- const own = readModuleConstants(code, { filename });
507
- if (own.imports.length === 0) {
508
- return own;
509
- }
510
- const imported = await importedConstants(
511
- context,
512
- own.imports,
513
- id,
514
- new Set([...visiting, id]),
515
- );
516
- return readModuleConstants(code, { filename, importedConstants: imported });
517
- } catch (error) {
518
- // A module the parser rejects fails its own transform, with a better error.
519
- if (error instanceof SyntaxError) {
520
- return undefined;
521
- }
522
- throw error;
455
+ } else {
456
+ ({ code } = await context.load({ id }));
457
+ }
458
+ if (code === null) {
459
+ return { constants: undefined, partial: false };
460
+ }
461
+ // Loaded code is JavaScript, whatever the module was written in, and keeps its JSX.
462
+ const filename = `${stripQuery(id)}.${target.jsx ? 'jsx' : 'js'}`;
463
+ try {
464
+ const own = readModuleConstants(code, { filename, globalConstants: globals });
465
+ if (own.imports.length === 0) {
466
+ return { constants: own, partial: false };
523
467
  }
524
- })();
525
- moduleConstants.set(id, pending);
468
+ const imported = await importedConstants(
469
+ context,
470
+ own.imports,
471
+ id,
472
+ new Set([...visiting, id]),
473
+ transform,
474
+ );
475
+ return {
476
+ constants: readModuleConstants(code, {
477
+ filename,
478
+ importedConstants: imported.constants,
479
+ globalConstants: globals,
480
+ }),
481
+ partial: imported.partial,
482
+ };
483
+ } catch (error) {
484
+ // A module the parser rejects fails its own transform, with a better error.
485
+ if (error instanceof SyntaxError) {
486
+ return { constants: undefined, partial: false };
487
+ }
488
+ throw error;
489
+ }
490
+ })();
491
+ if (!result.partial) {
492
+ moduleConstants.set(id, result);
526
493
  }
527
- return pending;
494
+ return result;
528
495
  }
529
496
 
530
497
  /**
@@ -541,14 +508,41 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
541
508
  return { ...compileOptions, filename, sourceMap: wantsMaps() };
542
509
  }
543
510
  const { imports } = readModuleConstants(code, { filename });
511
+ const imported = await importedConstants(context, imports, filename, new Set([filename]), id);
544
512
  return {
545
513
  ...compileOptions,
546
514
  filename,
547
515
  sourceMap: wantsMaps(),
548
- importedConstants: await importedConstants(context, imports, filename, new Set([filename])),
516
+ importedConstants: imported.constants,
517
+ globalConstants: globals,
549
518
  };
550
519
  }
551
520
 
521
+ async function resolveLazyModuleUrls(
522
+ context: Rollup.TransformPluginContext,
523
+ code: string,
524
+ importer: string,
525
+ ): Promise<string> {
526
+ const root = config?.root ?? process.cwd();
527
+ let result = code;
528
+ for (const match of code.matchAll(LAZY_PLACEHOLDER)) {
529
+ const specifier = match.at(1);
530
+ if (specifier === undefined) {
531
+ continue;
532
+ }
533
+ // oxlint-disable-next-line no-await-in-loop
534
+ const resolved = await context.resolve(specifier, importer);
535
+ if (resolved) {
536
+ const queryIndex = resolved.id.indexOf('?');
537
+ const file = queryIndex === -1 ? resolved.id : resolved.id.slice(0, queryIndex);
538
+ const query = queryIndex === -1 ? '' : resolved.id.slice(queryIndex);
539
+ const relative = path.relative(root, file).split(path.sep).join('/') + query;
540
+ result = result.replace(match[0], JSON.stringify(relative));
541
+ }
542
+ }
543
+ return result;
544
+ }
545
+
552
546
  /** The modules each transform waits for, so two never wait for each other. */
553
547
  const waiting = new Map<string, Set<string>>();
554
548
 
@@ -599,15 +593,17 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
599
593
  */
600
594
  const recorded = new Map<string, string>();
601
595
 
602
- /** The modules with JSX each module imports, read from its file. */
603
- const jsxImports = new Map<string, Promise<string[]>>();
596
+ /** The modules of the project each module imports, read from its file. */
597
+ const localImports = new Map<string, Promise<string[]>>();
604
598
 
605
599
  /**
606
- * The modules with JSX a module imports. They come from the file on disk,
607
- * so they do not depend on the order modules are transformed in.
600
+ * The modules of the project a module imports, leaving out dependencies.
601
+ * They come from the file on disk, so they do not depend on the order
602
+ * modules are transformed in. Modules without JSX count too, since reading
603
+ * their constants can load a module with JSX.
608
604
  */
609
- async function jsxImportsOf(context: Rollup.PluginContext, id: string): Promise<string[]> {
610
- let pending = jsxImports.get(id);
605
+ async function localImportsOf(context: Rollup.PluginContext, id: string): Promise<string[]> {
606
+ let pending = localImports.get(id);
611
607
  if (!pending) {
612
608
  pending = (async () => {
613
609
  let code: string;
@@ -641,15 +637,15 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
641
637
  [...sources].map(async (source) => context.resolve(source, id)),
642
638
  );
643
639
  return resolved
644
- .filter((target) => target && !target.external && isJSXModule(target.id))
640
+ .filter((target) => target && !target.external && !target.id.includes('/node_modules/'))
645
641
  .map((target) => target?.id ?? '');
646
642
  })();
647
- jsxImports.set(id, pending);
643
+ localImports.set(id, pending);
648
644
  }
649
645
  return pending;
650
646
  }
651
647
 
652
- /** Whether `from` imports `to`, directly or through other modules with JSX. */
648
+ /** Whether `from` imports `to`, directly or through other modules of the project. */
653
649
  async function reaches(
654
650
  context: Rollup.PluginContext,
655
651
  from: string,
@@ -665,7 +661,7 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
665
661
  seen.add(id);
666
662
  }
667
663
  // oxlint-disable-next-line no-await-in-loop
668
- const next = await Promise.all(frontier.map(async (id) => jsxImportsOf(context, id)));
664
+ const next = await Promise.all(frontier.map(async (id) => localImportsOf(context, id)));
669
665
  frontier = [...new Set(next.flat())].filter((id) => !seen.has(id));
670
666
  }
671
667
  return false;
@@ -1076,23 +1072,31 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1076
1072
  }
1077
1073
 
1078
1074
  /**
1079
- * Prepares a client module for chunk mode. It adds the helper marker
1080
- * instead of lowering JSX. Vite strips the types afterwards.
1075
+ * Prepares a client module for chunk mode. It runs the passes the official
1076
+ * plugin runs before lowering JSX, and adds the helper marker instead of
1077
+ * lowering.
1081
1078
  */
1082
1079
  async function keepJSX(
1083
- context: Rollup.PluginContext,
1080
+ context: Rollup.TransformPluginContext,
1084
1081
  source: string,
1085
1082
  id: string,
1086
1083
  ): Promise<Rollup.TransformResult> {
1087
1084
  const filename = stripQuery(id);
1085
+ const solidCompiler = getCompiler();
1086
+ const maps: (string | null | undefined)[] = [];
1087
+ let code = source;
1088
+
1088
1089
  // Fold and inline memos before bundling. A branch that folds away takes
1089
1090
  // its imports and `lazy()` chunks out of the module graph, which the
1090
1091
  // chunk step can no longer do. Inlining waits for the chunk, where the
1091
1092
  // components it can reach are known.
1092
- const moduleCompileOptions = await moduleOptions(context, source, id);
1093
- const local = compile(source, { ...moduleCompileOptions, inline: false });
1094
- let code = local.code;
1095
- const maps: (string | null | undefined)[] = [local.map?.toString()];
1093
+ const moduleCompileOptions = await moduleOptions(context, code, id);
1094
+ const local = compile(code, { ...moduleCompileOptions, inline: false });
1095
+ // `map` is `null` when nothing changed, and when the build writes no maps.
1096
+ code = local.code;
1097
+ if (local.map) {
1098
+ maps.push(local.map.toString());
1099
+ }
1096
1100
  // `<Ns.Member>` would keep a namespace object, which lowered code does not.
1097
1101
  const named = nameNamespaceTags(code, filename);
1098
1102
  if (named) {
@@ -1125,22 +1129,24 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1125
1129
  code = exposed.code;
1126
1130
  maps.push(exposed.map);
1127
1131
  }
1132
+
1133
+ const lazy = await solidCompiler.transformLazyAsync(code, { filename, sourceMap: wantsMaps() });
1134
+ code = lazy.code;
1135
+ maps.push(lazy.map);
1136
+
1128
1137
  // The helpers the module's JSX needs, as written and with its own
1129
1138
  // components inlined. Inlining can turn a spread into attributes, which
1130
1139
  // need helpers the spread did not.
1140
+ const lowering = jsxOptions(false);
1141
+ const needed = new Set<string>();
1131
1142
  const inlined =
1132
1143
  moduleCompileOptions.inline === false
1133
1144
  ? undefined
1134
1145
  : compile(code, { ...moduleCompileOptions, sourceMap: false });
1135
- const needed = new Set<string>();
1136
1146
  for (const version of new Set([code, inlined?.code ?? code])) {
1137
- for (const helper of helpersOf(
1138
- getCompiler(),
1139
- version,
1140
- filename,
1141
- jsxOptions(false),
1142
- moduleName,
1143
- )) {
1147
+ // oxlint-disable-next-line no-await-in-loop
1148
+ const dryRun = await solidCompiler.transformAsync(version, { ...lowering, filename });
1149
+ for (const helper of generatedImports(dryRun.code, filename, moduleName)) {
1144
1150
  needed.add(helper);
1145
1151
  }
1146
1152
  }
@@ -1151,36 +1157,46 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1151
1157
  needed.add(helper);
1152
1158
  }
1153
1159
  }
1160
+
1161
+ if (needed.size > 0) {
1162
+ const marked = addMarker(code, filename, {
1163
+ moduleName,
1164
+ helpers: withRelated([...needed]),
1165
+ moduleSources,
1166
+ // The passes also recognize these primitives, which a chunk renames
1167
+ // too. `render` takes a callback that statements can move into, and
1168
+ // `children` can be inlined like a memo.
1169
+ builtIns: new Set([
1170
+ ...builtIns,
1171
+ 'createContext',
1172
+ 'render',
1173
+ 'children',
1174
+ ...CONTEXT_SAFE_PRIMITIVES,
1175
+ ]),
1176
+ });
1177
+ if (marked) {
1178
+ code = marked.code;
1179
+ maps.push(marked.map);
1180
+ }
1181
+ }
1182
+
1154
1183
  // The bundler has to see that a `ref` writes its variable. See `refs.ts`.
1155
1184
  const protectedRefs = protectRefs(code, filename);
1156
1185
  if (protectedRefs) {
1157
1186
  code = protectedRefs.code;
1158
1187
  maps.push(protectedRefs.map);
1159
1188
  }
1189
+
1190
+ code = await resolveLazyModuleUrls(context, code, filename);
1160
1191
  preserved.add(id);
1161
- if (needed.size === 0) {
1162
- return code === source ? null : { code, map: combineMaps(wantsMaps(), maps) };
1163
- }
1164
- const marked = addMarker(code, filename, {
1165
- moduleName,
1166
- helpers: withRelated([...needed]),
1167
- moduleSources,
1168
- // The passes also recognize these primitives, which a chunk renames too.
1169
- builtIns: new Set([...builtIns, 'createContext', ...CONTEXT_SAFE_PRIMITIVES]),
1170
- });
1171
- if (!marked) {
1172
- return code === source ? null : { code, map: combineMaps(wantsMaps(), maps) };
1173
- }
1174
- return {
1175
- code: marked.code,
1176
- map: combineMaps(wantsMaps(), [...maps, marked.map]),
1177
- };
1192
+ return { code, map: combineMaps(wantsMaps(), maps) };
1178
1193
  }
1179
1194
 
1180
- const originalTransform = main.transform;
1195
+ const main = plugins.find((plugin) => plugin.name === 'solid');
1196
+ const originalTransform = main?.transform;
1181
1197
  const originalHandler =
1182
1198
  typeof originalTransform === 'function' ? originalTransform : originalTransform?.handler;
1183
- if (originalHandler) {
1199
+ if (main && originalHandler) {
1184
1200
  main.transform = async function transform(code, id, transformOptions) {
1185
1201
  if (chunkMode() && isClient(this) && isJSXModule(id)) {
1186
1202
  return keepJSX(this, code, id);
@@ -1194,16 +1210,17 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1194
1210
  enforce: 'pre',
1195
1211
  configResolved(resolved) {
1196
1212
  config = resolved;
1213
+ globals = sharedGlobals(resolved);
1197
1214
  },
1198
1215
  buildStart() {
1199
1216
  moduleConstants.clear();
1200
- jsxImports.clear();
1217
+ localImports.clear();
1201
1218
  usageIndexes.clear();
1202
1219
  skips.delete(this.environment.name);
1203
1220
  },
1204
1221
  watchChange() {
1205
1222
  moduleConstants.clear();
1206
- jsxImports.clear();
1223
+ localImports.clear();
1207
1224
  usageIndexes.clear();
1208
1225
  },
1209
1226
  async transform(source, id) {
@@ -1214,11 +1231,7 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1214
1231
  return null;
1215
1232
  }
1216
1233
  const filename = stripQuery(id);
1217
- const sourceOptions: CompileOptions = {
1218
- ...(await moduleOptions(this, source, id)),
1219
- // The server renders once, so its reactive primitives reduce to plain calls.
1220
- server: optimizer.server !== false && !isClient(this),
1221
- };
1234
+ const sourceOptions = await moduleOptions(this, source, id);
1222
1235
  const result = compile(source, sourceOptions);
1223
1236
  let code = result.code;
1224
1237
  const maps: (string | null | undefined)[] = [result.map?.toString()];
@@ -1295,6 +1308,13 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1295
1308
  }
1296
1309
  const restored = restoreRefs(runtime.code, filename);
1297
1310
  const chunkCode = restored?.code ?? runtime.code;
1311
+ const lowerChunk = (source: string): SolidCompiler.TransformResult =>
1312
+ getCompiler().transform(source, {
1313
+ ...jsxOptions(false),
1314
+ // The compiler picks its parser by extension, and a chunk is a `.js` file with JSX.
1315
+ filename: `${filename}.jsx`,
1316
+ sourceMap: wantsMaps(),
1317
+ });
1298
1318
  let optimized: CompileResult | undefined = compile(chunkCode, {
1299
1319
  ...compileOptions,
1300
1320
  filename,
@@ -1302,15 +1322,10 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1302
1322
  constantVars: true,
1303
1323
  builtInAliases: runtime.builtInAliases,
1304
1324
  });
1305
- let lowered = lower(
1306
- getCompiler(),
1307
- optimized.code,
1308
- filename,
1309
- jsxOptions(false),
1310
- wantsMaps(),
1311
- );
1312
1325
  let linked: { code: string; map: string };
1326
+ let lowered: SolidCompiler.TransformResult;
1313
1327
  try {
1328
+ lowered = lowerChunk(optimized.code);
1314
1329
  linked = linkHelpers(lowered.code, filename, moduleName, runtime.helpers);
1315
1330
  addSkips(this, optimized.skipped);
1316
1331
  } catch (error) {
@@ -1324,7 +1339,7 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1324
1339
  this.warn(`${error.message} ${filename} is not optimized.`);
1325
1340
  optimized = undefined;
1326
1341
  addSkips(this, [{ pass: 'inline', reason: 'missing-helper', name: filename }]);
1327
- lowered = lower(getCompiler(), chunkCode, filename, jsxOptions(false), wantsMaps());
1342
+ lowered = lowerChunk(chunkCode);
1328
1343
  linked = linkHelpers(lowered.code, filename, moduleName, runtime.helpers);
1329
1344
  }
1330
1345
  return {
@@ -1374,5 +1389,5 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1374
1389
  },
1375
1390
  };
1376
1391
 
1377
- return [modulePlugin, main, moduleTypePlugin, chunkPlugin];
1392
+ return [modulePlugin, ...plugins, moduleTypePlugin, chunkPlugin];
1378
1393
  }