solid-optimizer 0.3.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/dist/vite.mjs CHANGED
@@ -1,17 +1,93 @@
1
- import { a as lookup, c as forEachChild, i as analyzeScopes, l as parse, n as readModuleConstants, o as scopeAt, r as CONTEXT_SAFE_PRIMITIVES, s as collectParents, t as compile, u as unwrap } from "./compile-ocDYvJUW.mjs";
1
+ import { a as lookup, c as forEachChild, d as unwrap, i as analyzeScopes, l as isIntrinsicTag, n as readModuleConstants, o as scopeAt, r as CONTEXT_SAFE_PRIMITIVES, s as collectParents, t as compile, u as parse } from "./compile-Cz6hbiQv.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import remapping from "@jridgewell/remapping";
4
4
  import MagicString from "magic-string";
5
5
  import { parseSync } from "oxc-parser";
6
6
  import { readFile } from "node:fs/promises";
7
+ import path from "node:path";
8
+ import solidPlugin from "@solidjs/vite-plugin";
7
9
  import { createFilter, transformWithOxc } from "vite";
8
- import solidPlugin from "vite-plugin-solid";
10
+ //#region src/vite/globals.ts
11
+ /**
12
+ * The `define` entries and `import.meta.env` values that are the same in
13
+ * every build environment, as global constants. A value that differs, like
14
+ * `import.meta.env.SSR`, could make the server and client builds fold, and
15
+ * then inline, differently, so their hydration keys would not match.
16
+ */
17
+ function sharedGlobals(config) {
18
+ const globals = {};
19
+ for (const [key, value] of Object.entries(config.env)) if (key !== "SSR" && (typeof value === "string" || typeof value === "number" || typeof value === "boolean")) globals[`import.meta.env.${key}`] = value;
20
+ const environments = Object.values(config.environments);
21
+ const defines = environments.length > 0 ? environments.map((environment) => environment.define ?? config.define ?? {}) : [config.define ?? {}];
22
+ const keys = new Set(defines.flatMap((define) => Object.keys(define)));
23
+ for (const key of keys) {
24
+ const values = defines.map((define) => defineValue(define[key]));
25
+ const first = values.at(0);
26
+ if (first !== void 0 && values.every((value) => value !== void 0 && Object.is(value.value, first.value))) globals[key] = first.value;
27
+ }
28
+ return globals;
29
+ }
30
+ /**
31
+ * The primitive a `define` entry replaces its key with. A string is code,
32
+ * so only one that is a JSON literal counts.
33
+ */
34
+ function defineValue(value) {
35
+ let parsed = value;
36
+ if (typeof value === "string") try {
37
+ parsed = JSON.parse(value);
38
+ } catch {
39
+ return;
40
+ }
41
+ if (parsed === null || typeof parsed === "string" || typeof parsed === "number" || typeof parsed === "boolean") return { value: parsed };
42
+ }
43
+ //#endregion
44
+ //#region src/vite/report.ts
45
+ /**
46
+ * Groups skips by pass and reason, most frequent first.
47
+ */
48
+ function summarizeSkips(skips) {
49
+ const groups = /* @__PURE__ */ new Map();
50
+ for (const skip of skips) {
51
+ const key = `${skip.pass}\0${skip.reason}`;
52
+ const group = groups.get(key) ?? {
53
+ pass: skip.pass,
54
+ reason: skip.reason,
55
+ names: /* @__PURE__ */ new Map()
56
+ };
57
+ group.names.set(skip.name, (group.names.get(skip.name) ?? 0) + 1);
58
+ groups.set(key, group);
59
+ }
60
+ return [...groups.values()].map(({ pass, reason, names }) => ({
61
+ pass,
62
+ reason,
63
+ count: [...names.values()].reduce((sum, count) => sum + count, 0),
64
+ names: [...names].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
65
+ })).sort((a, b) => b.count - a.count || a.pass.localeCompare(b.pass) || a.reason.localeCompare(b.reason));
66
+ }
67
+ /** The most names listed for a reason. */
68
+ const NAMES_SHOWN = 6;
69
+ /**
70
+ * The report as text, one line per reason.
71
+ */
72
+ function formatReport(report) {
73
+ const lines = [`solid-optimizer: what stays as written in ${report.environment}`];
74
+ const summaries = summarizeSkips(report.skips);
75
+ if (summaries.length === 0) lines.push(" nothing");
76
+ const reasonWidth = Math.max(0, ...summaries.map((summary) => summary.reason.length));
77
+ for (const summary of summaries) {
78
+ const shown = summary.names.slice(0, NAMES_SHOWN).map(([name, count]) => count > 1 ? `${name}×${String(count)}` : name);
79
+ if (summary.names.length > NAMES_SHOWN) shown.push(`${String(summary.names.length - NAMES_SHOWN)} more`);
80
+ lines.push(` ${summary.pass.padEnd(8)} ${summary.reason.padEnd(reasonWidth)} ${String(summary.count).padStart(4)} ${shown.join(", ")}`);
81
+ }
82
+ return lines.join("\n");
83
+ }
84
+ //#endregion
9
85
  //#region src/vite/runtime.ts
10
86
  /**
11
87
  * Keeps Solid's runtime helpers reachable while JSX waits in a bundled chunk.
12
88
  *
13
89
  * Solid's JSX transform imports helpers like `template` and `insert` from
14
- * `solid-js/web`. When the transform runs on a chunk, the bundle is already
90
+ * `@solidjs/web`. When the transform runs on a chunk, the bundle is already
15
91
  * built, so a new bare import cannot be resolved or bundled anymore. Instead,
16
92
  * every module imports the helpers it will need before bundling, and passes
17
93
  * them to a marker call. The bundler keeps the call, since it could have side
@@ -34,7 +110,7 @@ var MissingHelperError = class extends Error {
34
110
  };
35
111
  const HELPER_PREFIX = "helper:";
36
112
  const BUILT_IN_PREFIX = "builtin:";
37
- function generateMap$1(s, filename) {
113
+ function generateMap$2(s, filename) {
38
114
  return s.generateMap({
39
115
  source: filename,
40
116
  hires: true,
@@ -156,7 +232,7 @@ function addMarker(code, filename, options) {
156
232
  s.append(`\nimport { ${specifiers.join(", ")} } from ${JSON.stringify(options.moduleName)};\n` + (outside ? `${call};\n` : ""));
157
233
  return {
158
234
  code: s.toString(),
159
- map: generateMap$1(s, filename)
235
+ map: generateMap$2(s, filename)
160
236
  };
161
237
  }
162
238
  /**
@@ -185,7 +261,7 @@ function repairJSXSequences(code, filename) {
185
261
  }
186
262
  return {
187
263
  code: s.toString(),
188
- map: generateMap$1(s, filename)
264
+ map: generateMap$2(s, filename)
189
265
  };
190
266
  }
191
267
  function propertyKey(node) {
@@ -226,7 +302,7 @@ function readMarkers(code, filename) {
226
302
  if (markers.length === 0) return;
227
303
  return {
228
304
  code: s.toString(),
229
- map: generateMap$1(s, filename),
305
+ map: generateMap$2(s, filename),
230
306
  helpers,
231
307
  builtInAliases
232
308
  };
@@ -259,7 +335,7 @@ function linkHelpers(code, filename, moduleName, helpers) {
259
335
  }
260
336
  return {
261
337
  code: s.toString(),
262
- map: generateMap$1(s, filename)
338
+ map: generateMap$2(s, filename)
263
339
  };
264
340
  }
265
341
  //#endregion
@@ -293,7 +369,7 @@ function isContext(binding, scopes, moduleSources) {
293
369
  }
294
370
  /** The prefix of the name a module exports a local binding under. */
295
371
  const LOCAL_EXPORT = "__so_local$";
296
- function generateMap(s, filename) {
372
+ function generateMap$1(s, filename) {
297
373
  return s.generateMap({
298
374
  source: filename,
299
375
  hires: true,
@@ -386,10 +462,30 @@ function exposeLocals(code, filename) {
386
462
  s.append(`\nexport { ${specifiers.join(", ")} };\n`);
387
463
  return {
388
464
  code: s.toString(),
389
- map: generateMap(s, filename)
465
+ map: generateMap$1(s, filename)
390
466
  };
391
467
  }
392
468
  /**
469
+ * Whether a function returns JSX whose root calls a component declared at
470
+ * the top of its own module. A context's provider does not count, since the
471
+ * provider pass can remove it from a copy.
472
+ */
473
+ function returnsLocalCall(fn, scopes, moduleSources) {
474
+ if (fn.type !== "FunctionDeclaration" && fn.type !== "FunctionExpression" && fn.type !== "ArrowFunctionExpression") return false;
475
+ const { body } = fn;
476
+ if (!body) return false;
477
+ let root;
478
+ if (body.type === "BlockStatement") {
479
+ const last = body.body.at(-1);
480
+ root = last?.type === "ReturnStatement" ? last.argument : void 0;
481
+ } else root = body;
482
+ if (!root) return false;
483
+ const inner = unwrap(root);
484
+ if (inner.type !== "JSXElement" || inner.openingElement.name.type !== "JSXIdentifier") return false;
485
+ const binding = scopes.references.get(inner.openingElement.name);
486
+ return binding !== void 0 && binding.scope === scopes.root && binding.kind !== "import" && !isContext(binding, scopes, moduleSources);
487
+ }
488
+ /**
393
489
  * Reads the component a module exports under `exportName`, from the module
394
490
  * as the bundler loaded it. `undefined` when that export is not a function
395
491
  * component, or it refers to a top-level binding the module cannot export.
@@ -448,7 +544,8 @@ function readExportedComponent(code, filename, exportName, moduleSources) {
448
544
  };
449
545
  return {
450
546
  dependencies,
451
- copy
547
+ copy,
548
+ wrapsLocal: returnsLocalCall(component.fn, scopes, moduleSources)
452
549
  };
453
550
  }
454
551
  //#endregion
@@ -500,6 +597,72 @@ function nameNamespaceTags(code, filename) {
500
597
  };
501
598
  }
502
599
  //#endregion
600
+ //#region src/vite/refs.ts
601
+ const REF_MARKER = "__SO_REF__";
602
+ function generateMap(s, filename) {
603
+ return s.generateMap({
604
+ source: filename,
605
+ hires: true,
606
+ includeContent: true
607
+ }).toString();
608
+ }
609
+ function isRefAttribute(node) {
610
+ return node.type === "JSXAttribute" && node.name.type === "JSXIdentifier" && node.name.name === "ref";
611
+ }
612
+ /**
613
+ * Wraps each `ref` whose value is a `let` or `var` binding, so the bundler
614
+ * sees it written. `undefined` when there is none.
615
+ */
616
+ function protectRefs(code, filename) {
617
+ if (!code.includes("ref")) return;
618
+ const program = parse(filename, code);
619
+ const scopes = analyzeScopes(program);
620
+ const s = new MagicString(code);
621
+ const visit = (node) => {
622
+ if (isRefAttribute(node) && node.value?.type === "JSXExpressionContainer") {
623
+ const { expression } = node.value;
624
+ const binding = expression.type === "Identifier" ? scopes.references.get(expression) : void 0;
625
+ if (expression.type === "Identifier" && (binding?.kind === "let" || binding?.kind === "var")) {
626
+ const { name } = expression;
627
+ s.overwrite(expression.start, expression.end, `${REF_MARKER}(${name}, (__so_ref) => (${name} = __so_ref))`);
628
+ }
629
+ }
630
+ forEachChild(node, visit);
631
+ };
632
+ visit(program);
633
+ return s.hasChanged() ? {
634
+ code: s.toString(),
635
+ map: generateMap(s, filename)
636
+ } : void 0;
637
+ }
638
+ /**
639
+ * Turns each wrapped `ref` back into its variable. `undefined` when there
640
+ * is none.
641
+ */
642
+ function restoreRefs(code, filename) {
643
+ if (!code.includes("__SO_REF__")) return;
644
+ const program = parse(filename, code);
645
+ const s = new MagicString(code);
646
+ const visit = (node) => {
647
+ if (isRefAttribute(node) && node.value?.type === "JSXExpressionContainer") {
648
+ const { expression } = node.value;
649
+ if (isMarkerCall(expression)) {
650
+ const target = expression.arguments.at(0);
651
+ if (target?.type === "Identifier") s.overwrite(expression.start, expression.end, target.name);
652
+ }
653
+ }
654
+ forEachChild(node, visit);
655
+ };
656
+ visit(program);
657
+ return s.hasChanged() ? {
658
+ code: s.toString(),
659
+ map: generateMap(s, filename)
660
+ } : void 0;
661
+ }
662
+ function isMarkerCall(node) {
663
+ return node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "__SO_REF__";
664
+ }
665
+ //#endregion
503
666
  //#region src/vite/usage.ts
504
667
  /** The name a use counts under when it is not inside an exported declaration. */
505
668
  const UNEXPORTED = "";
@@ -708,10 +871,10 @@ async function buildUsageIndex(entries, host) {
708
871
  //#endregion
709
872
  //#region src/vite/index.ts
710
873
  /**
711
- * `solid-optimizer/vite`: `vite-plugin-solid` with the optimizer built in.
874
+ * `solid-optimizer/vite`: `@solidjs/vite-plugin` with the optimizer built in.
712
875
  *
713
- * It takes the same options as `vite-plugin-solid`, plus `optimizer`, and
714
- * returns the official plugin with the optimizer wired in. It runs in one of
876
+ * It takes the same options as `@solidjs/vite-plugin`, plus `optimizer`, and
877
+ * returns the official plugins with the optimizer wired in. It runs in one of
715
878
  * two modes.
716
879
  *
717
880
  * - Chunk mode keeps JSX through bundling. Each chunk is optimized as a whole
@@ -723,19 +886,7 @@ async function buildUsageIndex(entries, host) {
723
886
  * differently, and hydration needs both to render the same tree, so
724
887
  * hydrating builds only optimize within a module.
725
888
  */
726
- const DEFAULT_MODULE_NAME = "solid-js/web";
727
- const DEFAULT_BUILT_INS = [
728
- "For",
729
- "Show",
730
- "Switch",
731
- "Match",
732
- "Suspense",
733
- "SuspenseList",
734
- "Portal",
735
- "Index",
736
- "Dynamic",
737
- "ErrorBoundary"
738
- ];
889
+ const DEFAULT_MODULE_NAME = "@solidjs/web";
739
890
  const JSX_MODULE = /\.[mc]?[jt]sx$/i;
740
891
  /**
741
892
  * Helpers the JSX transform picks between for the same attribute. Inlining
@@ -752,43 +903,47 @@ function withRelated(helpers) {
752
903
  for (const helper of helpers) for (const related of RELATED_HELPERS[helper] ?? []) result.add(related);
753
904
  return result;
754
905
  }
755
- function loadCompiler() {
756
- const require = createRequire(import.meta.url);
757
- const pluginRequire = createRequire(require.resolve("vite-plugin-solid"));
758
- const babel = createRequire(pluginRequire.resolve("babel-preset-solid"))("@babel/core");
759
- const preset = pluginRequire("babel-preset-solid");
760
- if (typeof preset !== "function") throw new TypeError("[solid-optimizer] babel-preset-solid did not load");
761
- return {
762
- babel,
763
- preset
764
- };
765
- }
906
+ const LAZY_PLACEHOLDER = /"__SOLID_LAZY_MODULE__:([^"]+)"/g;
766
907
  /**
767
- * Lowers JSX with `babel-preset-solid`, as `vite-plugin-solid` does.
908
+ * The common kinds of attribute: a class, any other attribute, events, and
909
+ * children. Inlining a component turns a spread onto an element into
910
+ * attributes like these, in a module that may not use their helpers itself.
911
+ * A rarer kind, like `style`, can still need a helper no module imports.
912
+ * The chunk is then lowered without optimizing it.
768
913
  */
769
- function lower(compiler, code, filename, options) {
770
- const result = compiler.babel.transformSync(code, {
771
- filename,
772
- sourceFileName: filename,
773
- presets: [[compiler.preset, options]],
774
- ast: false,
775
- sourceMaps: true,
776
- configFile: false,
777
- babelrc: false,
778
- parserOpts: { plugins: /\.[mc]?tsx$/i.test(filename) ? ["jsx", "typescript"] : ["jsx"] }
779
- });
780
- if (typeof result?.code !== "string") throw new Error(`[solid-optimizer] babel-preset-solid produced no code for ${filename}`);
781
- return {
782
- code: result.code,
783
- map: result.map ? JSON.stringify(result.map) : void 0
914
+ const ATTRIBUTE_SAMPLE = `const a = () => 0;
915
+ export const Sample = () => (
916
+ <div class={a()} id={a()} onClick={a()} onScroll={a()}>{a()}</div>
917
+ );`;
918
+ /** Whether the code spreads anything onto an intrinsic element. */
919
+ function spreadsOntoElement(code, filename) {
920
+ if (!code.includes("...")) return false;
921
+ let found = false;
922
+ const visit = (node) => {
923
+ if (found) return;
924
+ if (node.type === "JSXOpeningElement" && node.name.type === "JSXIdentifier" && isIntrinsicTag(node.name.name) && node.attributes.some((attribute) => attribute.type === "JSXSpreadAttribute")) {
925
+ found = true;
926
+ return;
927
+ }
928
+ forEachChild(node, visit);
784
929
  };
930
+ visit(parse(filename, code));
931
+ return found;
932
+ }
933
+ function loadCompiler() {
934
+ const require = createRequire(import.meta.url);
935
+ return createRequire(require.resolve("@solidjs/vite-plugin"))("@solidjs/compiler");
785
936
  }
786
937
  function stripQuery(id) {
787
938
  return id.replace(/\?.*$/, "");
788
939
  }
789
- function combineMaps(maps) {
940
+ /**
941
+ * Chains the maps of each step into one, or `null` when the build writes no
942
+ * source maps, since chaining the maps of a large chunk takes a while.
943
+ */
944
+ function combineMaps(wanted, maps) {
790
945
  const present = maps.filter((map) => typeof map === "string");
791
- if (present.length === 0) return null;
946
+ if (!wanted || present.length === 0) return null;
792
947
  return remapping(present.reverse(), () => null).toString();
793
948
  }
794
949
  /**
@@ -820,8 +975,8 @@ function isClient(context) {
820
975
  }
821
976
  function solidOptimizer(options = {}) {
822
977
  const { optimizer: optimizerOption, ...solidOptions } = options;
823
- const main = solidPlugin(solidOptions);
824
- if (optimizerOption === false) return [main];
978
+ const plugins = solidPlugin(solidOptions);
979
+ if (optimizerOption === false) return plugins;
825
980
  const optimizer = optimizerOption ?? {};
826
981
  const moduleName = solidOptions.solid?.moduleName ?? DEFAULT_MODULE_NAME;
827
982
  const moduleSources = [.../* @__PURE__ */ new Set([
@@ -829,7 +984,18 @@ function solidOptimizer(options = {}) {
829
984
  DEFAULT_MODULE_NAME,
830
985
  moduleName
831
986
  ])];
832
- const builtIns = new Set(solidOptions.solid?.builtIns ?? DEFAULT_BUILT_INS);
987
+ const builtIns = new Set(solidOptions.solid?.builtIns ?? [
988
+ "For",
989
+ "Show",
990
+ "Switch",
991
+ "Match",
992
+ "Loading",
993
+ "Reveal",
994
+ "Portal",
995
+ "Repeat",
996
+ "Dynamic",
997
+ "Errored"
998
+ ]);
833
999
  const compileOptions = {
834
1000
  fold: optimizer.fold,
835
1001
  inline: optimizer.inline,
@@ -838,9 +1004,21 @@ function solidOptimizer(options = {}) {
838
1004
  memos: optimizer.memos,
839
1005
  maxPasses: optimizer.maxPasses,
840
1006
  builtIns: [...builtIns],
841
- moduleSources
1007
+ moduleSources,
1008
+ report: optimizer.report !== void 0 && optimizer.report !== false
1009
+ };
1010
+ /** What the final compile of each chunk or module left alone, by environment. */
1011
+ const skips = /* @__PURE__ */ new Map();
1012
+ const addSkips = (context, list) => {
1013
+ if (!list) return;
1014
+ const environment = context.environment?.name ?? "client";
1015
+ const entries = skips.get(environment) ?? [];
1016
+ entries.push(...list);
1017
+ skips.set(environment, entries);
842
1018
  };
843
1019
  let config;
1020
+ /** The `define` entries and `import.meta.env` values every environment shares. */
1021
+ let globals = {};
844
1022
  let compiler;
845
1023
  let filter;
846
1024
  const getCompiler = () => {
@@ -848,95 +1026,172 @@ function solidOptimizer(options = {}) {
848
1026
  return compiler;
849
1027
  };
850
1028
  const isBuild = () => config?.command === "build";
1029
+ /** Whether the output needs source maps: while serving, or when the build writes them. */
1030
+ const wantsMaps = () => !isBuild() || Boolean(config?.build.sourcemap);
851
1031
  /**
852
1032
  * The JSX options the official plugin passes for a posture, so the
853
- * lowering here matches it. Mirrors the `transform` hook of `vite-plugin-solid`.
1033
+ * lowering here matches it. Mirrors `getSolidOptions` in `@solidjs/vite-plugin`.
854
1034
  */
855
1035
  const jsxOptions = (isSsr) => {
856
- let posture = {
857
- generate: "dom",
1036
+ let posture;
1037
+ if (solidOptions.start && !solidOptions.ssr) posture = {
1038
+ generate: isSsr ? "ssr" : "dom",
858
1039
  hydratable: false
859
1040
  };
860
- if (solidOptions.ssr) posture = {
1041
+ else if (solidOptions.ssr) posture = {
861
1042
  generate: isSsr ? "ssr" : "dom",
862
1043
  hydratable: true
863
1044
  };
1045
+ else posture = {
1046
+ generate: "dom",
1047
+ hydratable: false
1048
+ };
1049
+ const dev = solidOptions.dev === true || solidOptions.dev !== false && !isBuild();
1050
+ const names = dev || solidOptions.observe === true;
1051
+ const { sourceNames, ...rest } = solidOptions.solid ?? {};
1052
+ let resolvedNames = false;
1053
+ if (typeof sourceNames === "boolean") resolvedNames = sourceNames;
1054
+ else if (sourceNames !== void 0 || names) {
1055
+ const components = sourceNames?.components ?? names;
1056
+ const bindings = sourceNames?.bindings ?? names;
1057
+ resolvedNames = components || bindings ? {
1058
+ components,
1059
+ bindings
1060
+ } : false;
1061
+ }
864
1062
  return {
865
1063
  ...posture,
866
- ...solidOptions.solid
1064
+ dev,
1065
+ sourceNames: resolvedNames,
1066
+ ...rest
867
1067
  };
868
1068
  };
1069
+ let sampleHelpers;
1070
+ /** The helpers the JSX transform uses for attributes in chunk mode. */
1071
+ const attributeHelpers = () => {
1072
+ sampleHelpers ??= generatedImports(getCompiler().transform(ATTRIBUTE_SAMPLE, {
1073
+ ...jsxOptions(false),
1074
+ filename: "sample.jsx"
1075
+ }).code, "sample.jsx", moduleName);
1076
+ return sampleHelpers;
1077
+ };
869
1078
  /**
870
1079
  * Whether client builds keep JSX until chunks are rendered.
871
1080
  */
872
1081
  const chunkMode = () => {
873
1082
  if (!isBuild() || (optimizer.mode ?? "auto") !== "auto") return false;
874
- if (solidOptions.babel) return false;
1083
+ if (solidOptions.babel || solidOptions.compiler === "babel") return false;
875
1084
  const client = jsxOptions(false);
876
1085
  return client.generate === "dom" && client.hydratable !== true;
877
1086
  };
878
1087
  const isJSXModule = (id) => {
879
- filter ??= createFilter(solidOptions.include, solidOptions.exclude);
1088
+ filter ??= createFilter(solidOptions.include, solidOptions.exclude, { resolve: config?.root });
880
1089
  return filter(id) && JSX_MODULE.test(stripQuery(id));
881
1090
  };
882
1091
  /** Modules that keep their JSX, which the bundler must parse as JSX. */
883
1092
  const preserved = /* @__PURE__ */ new Set();
884
- /** What each module imports and the constants it exports, by module id. */
885
- const moduleConstants = /* @__PURE__ */ new Map();
886
1093
  /**
887
- * The module an import resolves to, when its constants can be read.
1094
+ * What each module imports and the constants it exports, by module id,
1095
+ * once read in full. A module whose constants needed a module with JSX
1096
+ * that could not be loaded, to avoid a cycle, is not kept, since another
1097
+ * transform may load it.
888
1098
  *
889
- * A module with JSX is skipped. This plugin's transform may be waiting for
890
- * it, and it may be waiting for this one, so loading it could deadlock.
891
- * Dependencies are skipped to keep the build fast.
1099
+ * A read in progress is never shared. It can wait for a module with JSX,
1100
+ * and a read that waited for it would wait for that module too, without
1101
+ * the cycle checks knowing. Two reads of modules that import each other
1102
+ * would also wait for each other.
1103
+ */
1104
+ const moduleConstants = /* @__PURE__ */ new Map();
1105
+ /**
1106
+ * The module an import resolves to, when its constants can be read, and
1107
+ * whether it has JSX. Dependencies are skipped to keep the build fast.
892
1108
  */
893
1109
  async function resolveConstantModule(context, specifier, importer) {
894
1110
  if (moduleSources.includes(specifier)) return;
895
1111
  const resolved = await context.resolve(specifier, importer);
896
- if (!resolved || resolved.external || resolved.id.includes("/node_modules/") || isJSXModule(resolved.id)) return;
897
- return resolved.id;
1112
+ if (!resolved || resolved.external || resolved.id.includes("/node_modules/")) return;
1113
+ return {
1114
+ id: resolved.id,
1115
+ jsx: isJSXModule(resolved.id)
1116
+ };
1117
+ }
1118
+ /**
1119
+ * The code of a module with JSX to read constants from, as this plugin's
1120
+ * transform returns it. `transform` is the module whose transform waits for
1121
+ * it, which the cycle checks are about. `undefined` when that could wait
1122
+ * for itself.
1123
+ */
1124
+ async function loadJSXModule(context, transform, target) {
1125
+ return chunkMode() && isClient(context) ? loadModule(context, transform, target) : loadRecorded(context, transform, target);
898
1126
  }
899
1127
  /**
900
1128
  * The constants of the modules `code` imports, keyed by import specifier.
901
1129
  *
902
1130
  * Each module is read as the bundler loads it, after every plugin has
903
- * transformed it, so a plugin that replaces or rewrites a module is seen.
904
- * A module that imports constants itself resolves them first, and a cycle
905
- * leaves the modules in it without them.
1131
+ * transformed it. A module with JSX is read from this plugin's own output
1132
+ * for it, unless its transform could be waiting for `transform`.
906
1133
  */
907
- async function importedConstants(context, imports, importer, visiting) {
1134
+ async function importedConstants(context, imports, importer, visiting, transform) {
1135
+ let partial = false;
908
1136
  const entries = await Promise.all(imports.map(async (specifier) => {
909
- const id = await resolveConstantModule(context, specifier, importer);
910
- if (id === void 0 || visiting.has(id)) return;
911
- const constants = await constantsOf(context, id, visiting);
912
- if (!constants || Object.keys(constants.exports).length === 0) return;
913
- return [specifier, constants.exports];
1137
+ const target = await resolveConstantModule(context, specifier, importer);
1138
+ if (target === void 0 || visiting.has(target.id)) return;
1139
+ const result = await constantsOf(context, target, visiting, transform);
1140
+ partial ||= result.partial;
1141
+ if (!result.constants || Object.keys(result.constants.exports).length === 0) return;
1142
+ return [specifier, result.constants.exports];
914
1143
  }));
915
- return Object.fromEntries(entries.filter((entry) => entry !== void 0));
1144
+ return {
1145
+ constants: Object.fromEntries(entries.filter((entry) => entry !== void 0)),
1146
+ partial
1147
+ };
916
1148
  }
917
- async function constantsOf(context, id, visiting) {
918
- let pending = moduleConstants.get(id);
919
- if (!pending) {
920
- pending = (async () => {
921
- const { code } = await context.load({ id });
922
- if (code === null) return;
923
- const filename = `${stripQuery(id)}.js`;
924
- try {
925
- const own = readModuleConstants(code, { filename });
926
- if (own.imports.length === 0) return own;
927
- const imported = await importedConstants(context, own.imports, id, /* @__PURE__ */ new Set([...visiting, id]));
928
- return readModuleConstants(code, {
1149
+ async function constantsOf(context, target, visiting, transform) {
1150
+ const { id } = target;
1151
+ const known = moduleConstants.get(id);
1152
+ if (known) return known;
1153
+ const result = await (async () => {
1154
+ let code;
1155
+ if (target.jsx) {
1156
+ code = await loadJSXModule(context, transform, id);
1157
+ if (code === void 0) return {
1158
+ constants: void 0,
1159
+ partial: true
1160
+ };
1161
+ } else ({code} = await context.load({ id }));
1162
+ if (code === null) return {
1163
+ constants: void 0,
1164
+ partial: false
1165
+ };
1166
+ const filename = `${stripQuery(id)}.${target.jsx ? "jsx" : "js"}`;
1167
+ try {
1168
+ const own = readModuleConstants(code, {
1169
+ filename,
1170
+ globalConstants: globals
1171
+ });
1172
+ if (own.imports.length === 0) return {
1173
+ constants: own,
1174
+ partial: false
1175
+ };
1176
+ const imported = await importedConstants(context, own.imports, id, /* @__PURE__ */ new Set([...visiting, id]), transform);
1177
+ return {
1178
+ constants: readModuleConstants(code, {
929
1179
  filename,
930
- importedConstants: imported
931
- });
932
- } catch (error) {
933
- if (error instanceof SyntaxError) return;
934
- throw error;
935
- }
936
- })();
937
- moduleConstants.set(id, pending);
938
- }
939
- return pending;
1180
+ importedConstants: imported.constants,
1181
+ globalConstants: globals
1182
+ }),
1183
+ partial: imported.partial
1184
+ };
1185
+ } catch (error) {
1186
+ if (error instanceof SyntaxError) return {
1187
+ constants: void 0,
1188
+ partial: false
1189
+ };
1190
+ throw error;
1191
+ }
1192
+ })();
1193
+ if (!result.partial) moduleConstants.set(id, result);
1194
+ return result;
940
1195
  }
941
1196
  /**
942
1197
  * The compile options for a module, with the constants of its imports.
@@ -945,15 +1200,36 @@ function solidOptimizer(options = {}) {
945
1200
  const filename = stripQuery(id);
946
1201
  if (optimizer.fold === false || !isBuild()) return {
947
1202
  ...compileOptions,
948
- filename
1203
+ filename,
1204
+ sourceMap: wantsMaps()
949
1205
  };
950
1206
  const { imports } = readModuleConstants(code, { filename });
1207
+ const imported = await importedConstants(context, imports, filename, /* @__PURE__ */ new Set([filename]), id);
951
1208
  return {
952
1209
  ...compileOptions,
953
1210
  filename,
954
- importedConstants: await importedConstants(context, imports, filename, /* @__PURE__ */ new Set([filename]))
1211
+ sourceMap: wantsMaps(),
1212
+ importedConstants: imported.constants,
1213
+ globalConstants: globals
955
1214
  };
956
1215
  }
1216
+ async function resolveLazyModuleUrls(context, code, importer) {
1217
+ const root = config?.root ?? process.cwd();
1218
+ let result = code;
1219
+ for (const match of code.matchAll(LAZY_PLACEHOLDER)) {
1220
+ const specifier = match.at(1);
1221
+ if (specifier === void 0) continue;
1222
+ const resolved = await context.resolve(specifier, importer);
1223
+ if (resolved) {
1224
+ const queryIndex = resolved.id.indexOf("?");
1225
+ const file = queryIndex === -1 ? resolved.id : resolved.id.slice(0, queryIndex);
1226
+ const query = queryIndex === -1 ? "" : resolved.id.slice(queryIndex);
1227
+ const relative = path.relative(root, file).split(path.sep).join("/") + query;
1228
+ result = result.replace(match[0], JSON.stringify(relative));
1229
+ }
1230
+ }
1231
+ return result;
1232
+ }
957
1233
  /** The modules each transform waits for, so two never wait for each other. */
958
1234
  const waiting = /* @__PURE__ */ new Map();
959
1235
  /** Whether the transform of `from` waits, directly or not, for `to`. */
@@ -991,14 +1267,16 @@ function solidOptimizer(options = {}) {
991
1267
  * copies components from it.
992
1268
  */
993
1269
  const recorded = /* @__PURE__ */ new Map();
994
- /** The modules with JSX each module imports, read from its file. */
995
- const jsxImports = /* @__PURE__ */ new Map();
1270
+ /** The modules of the project each module imports, read from its file. */
1271
+ const localImports = /* @__PURE__ */ new Map();
996
1272
  /**
997
- * The modules with JSX a module imports. They come from the file on disk,
998
- * so they do not depend on the order modules are transformed in.
1273
+ * The modules of the project a module imports, leaving out dependencies.
1274
+ * They come from the file on disk, so they do not depend on the order
1275
+ * modules are transformed in. Modules without JSX count too, since reading
1276
+ * their constants can load a module with JSX.
999
1277
  */
1000
- async function jsxImportsOf(context, id) {
1001
- let pending = jsxImports.get(id);
1278
+ async function localImportsOf(context, id) {
1279
+ let pending = localImports.get(id);
1002
1280
  if (!pending) {
1003
1281
  pending = (async () => {
1004
1282
  let code;
@@ -1018,20 +1296,20 @@ function solidOptimizer(options = {}) {
1018
1296
  const value = statement.source?.value;
1019
1297
  if (value !== void 0 && !moduleSources.includes(value)) sources.add(value);
1020
1298
  }
1021
- return (await Promise.all([...sources].map(async (source) => context.resolve(source, id)))).filter((target) => target && !target.external && isJSXModule(target.id)).map((target) => target?.id ?? "");
1299
+ return (await Promise.all([...sources].map(async (source) => context.resolve(source, id)))).filter((target) => target && !target.external && !target.id.includes("/node_modules/")).map((target) => target?.id ?? "");
1022
1300
  })();
1023
- jsxImports.set(id, pending);
1301
+ localImports.set(id, pending);
1024
1302
  }
1025
1303
  return pending;
1026
1304
  }
1027
- /** Whether `from` imports `to`, directly or through other modules with JSX. */
1305
+ /** Whether `from` imports `to`, directly or through other modules of the project. */
1028
1306
  async function reaches(context, from, to) {
1029
1307
  const seen = /* @__PURE__ */ new Set();
1030
1308
  let frontier = [from];
1031
1309
  while (frontier.length > 0) {
1032
1310
  if (frontier.includes(to)) return true;
1033
1311
  for (const id of frontier) seen.add(id);
1034
- const next = await Promise.all(frontier.map(async (id) => jsxImportsOf(context, id)));
1312
+ const next = await Promise.all(frontier.map(async (id) => localImportsOf(context, id)));
1035
1313
  frontier = [...new Set(next.flat())].filter((id) => !seen.has(id));
1036
1314
  }
1037
1315
  return false;
@@ -1119,14 +1397,44 @@ function solidOptimizer(options = {}) {
1119
1397
  * needs into the importer. `undefined` when it cannot be copied.
1120
1398
  */
1121
1399
  async function copyImported(context, id, source, imported, state) {
1400
+ const skip = (reason) => {
1401
+ state.skips?.push({
1402
+ pass: "inline",
1403
+ reason,
1404
+ name: `${imported} (${source})`
1405
+ });
1406
+ };
1122
1407
  const resolved = await context.resolve(source, id);
1123
- if (!resolved || resolved.external || resolved.id === id || resolved.id.includes("/node_modules/") || !isJSXModule(resolved.id)) return;
1408
+ if (!resolved || resolved.external) {
1409
+ skip("copy-external");
1410
+ return;
1411
+ }
1412
+ if (resolved.id.includes("/node_modules/")) {
1413
+ skip("copy-package");
1414
+ return;
1415
+ }
1416
+ if (resolved.id === id) return;
1417
+ if (!isJSXModule(resolved.id)) {
1418
+ skip("copy-not-jsx");
1419
+ return;
1420
+ }
1124
1421
  const key = `${resolved.id}\0${imported}`;
1125
1422
  if (state.excluded.has(key)) return;
1126
1423
  const loaded = await state.load(resolved.id);
1127
- const component = loaded ? readExportedComponent(loaded, stripQuery(resolved.id), imported, moduleSources) : void 0;
1424
+ if (loaded === void 0) {
1425
+ state.excluded.add(key);
1426
+ skip("copy-cycle");
1427
+ return;
1428
+ }
1429
+ const component = readExportedComponent(loaded, stripQuery(resolved.id), imported, moduleSources);
1128
1430
  if (!component) {
1129
1431
  state.excluded.add(key);
1432
+ skip("copy-shape");
1433
+ return;
1434
+ }
1435
+ if (component.wrapsLocal) {
1436
+ state.excluded.add(key);
1437
+ skip("copy-wrapper");
1130
1438
  return;
1131
1439
  }
1132
1440
  const targets = /* @__PURE__ */ new Map();
@@ -1134,6 +1442,7 @@ function solidOptimizer(options = {}) {
1134
1442
  const target = await context.resolve(dependency.source, resolved.id);
1135
1443
  if (!target) {
1136
1444
  state.excluded.add(key);
1445
+ skip("copy-external");
1137
1446
  return;
1138
1447
  }
1139
1448
  targets.set(dependency.source, target.external ? dependency.source : target.id);
@@ -1163,9 +1472,10 @@ function solidOptimizer(options = {}) {
1163
1472
  * every call is left out, so a component is never in both places. Copies
1164
1473
  * can import components in turn, which a few more rounds take in.
1165
1474
  */
1166
- async function inlineImports(context, source, id, compileOptionsOfModule, load) {
1475
+ async function inlineImports(context, source, id, compileOptionsOfModule, load, copySkips) {
1167
1476
  const filename = stripQuery(id);
1168
1477
  const maps = [];
1478
+ let skipped;
1169
1479
  const excluded = /* @__PURE__ */ new Set();
1170
1480
  const usage = await usageIndex(context);
1171
1481
  const absorbed = /* @__PURE__ */ new Map();
@@ -1175,6 +1485,7 @@ function solidOptimizer(options = {}) {
1175
1485
  };
1176
1486
  const contexts = /* @__PURE__ */ new Map();
1177
1487
  let code = source;
1488
+ const copyNames = /* @__PURE__ */ new Map();
1178
1489
  for (let round = 0; round < 4; round += 1) {
1179
1490
  const program = parse(filename, code);
1180
1491
  const scopes = analyzeScopes(program);
@@ -1212,8 +1523,10 @@ function solidOptimizer(options = {}) {
1212
1523
  excluded,
1213
1524
  contexts,
1214
1525
  importAs,
1215
- load
1526
+ load,
1527
+ skips: copySkips
1216
1528
  });
1529
+ if (copy && copySkips) copyNames.set(copy.key, `${binding.imported} (${statement.source.value})`);
1217
1530
  if (copy) {
1218
1531
  const name = fresh(specifier.local.name);
1219
1532
  copies.push({
@@ -1238,7 +1551,7 @@ function solidOptimizer(options = {}) {
1238
1551
  result = compile(edit.toString(), {
1239
1552
  ...compileOptionsOfModule,
1240
1553
  filename,
1241
- sourceMap: true,
1554
+ sourceMap: wantsMaps(),
1242
1555
  importedContexts: Object.fromEntries([...contexts].map(([module, exported]) => [module, [...exported]])),
1243
1556
  sharedComponents: Object.fromEntries(copies.map((copy) => [copy.name, usersOf(copy)]).filter(([, users]) => users !== 1))
1244
1557
  });
@@ -1248,6 +1561,12 @@ function solidOptimizer(options = {}) {
1248
1561
  for (const copy of stuck) {
1249
1562
  excluded.add(copy.key);
1250
1563
  copies.splice(copies.indexOf(copy), 1);
1564
+ const reason = result.skipped?.find((entry) => entry.name === copy.name)?.reason;
1565
+ copySkips?.push({
1566
+ pass: "inline",
1567
+ reason: `copy-${reason ?? "left"}`,
1568
+ name: copyNames.get(copy.key) ?? copy.name
1569
+ });
1251
1570
  }
1252
1571
  result = void 0;
1253
1572
  }
@@ -1256,39 +1575,47 @@ function solidOptimizer(options = {}) {
1256
1575
  const [module = "", exported = ""] = copy.key.split("\0");
1257
1576
  absorbed.set(module, /* @__PURE__ */ new Set([...absorbed.get(module) ?? [], exported]));
1258
1577
  }
1259
- maps.push(edit.generateMap({
1578
+ if (wantsMaps()) maps.push(edit.generateMap({
1260
1579
  source: filename,
1261
1580
  hires: true,
1262
1581
  includeContent: true
1263
1582
  }).toString());
1264
1583
  if (result.map) maps.push(result.map.toString());
1265
1584
  code = result.code;
1585
+ ({skipped} = result);
1266
1586
  }
1267
1587
  return code === source ? void 0 : {
1268
1588
  code,
1269
- maps
1589
+ maps,
1590
+ skipped
1270
1591
  };
1271
1592
  }
1272
1593
  /**
1273
- * Prepares a client module for chunk mode. It adds the helper marker
1274
- * instead of lowering JSX. Vite strips the types afterwards.
1594
+ * Prepares a client module for chunk mode. It runs the passes the official
1595
+ * plugin runs before lowering JSX, and adds the helper marker instead of
1596
+ * lowering.
1275
1597
  */
1276
1598
  async function keepJSX(context, source, id) {
1277
1599
  const filename = stripQuery(id);
1278
- const moduleCompileOptions = await moduleOptions(context, source, id);
1279
- const local = compile(source, {
1600
+ const solidCompiler = getCompiler();
1601
+ const maps = [];
1602
+ let code = source;
1603
+ const moduleCompileOptions = await moduleOptions(context, code, id);
1604
+ const local = compile(code, {
1280
1605
  ...moduleCompileOptions,
1281
1606
  inline: false
1282
1607
  });
1283
- let code = local.code;
1284
- const maps = [local.map?.toString()];
1608
+ code = local.code;
1609
+ if (local.map) maps.push(local.map.toString());
1285
1610
  const named = nameNamespaceTags(code, filename);
1286
1611
  if (named) {
1287
1612
  code = named.code;
1288
1613
  maps.push(named.map);
1289
1614
  }
1290
1615
  if (moduleCompileOptions.inline !== false) {
1291
- const imported = await inlineImports(context, code, id, moduleCompileOptions, async (target) => loadModule(context, id, target));
1616
+ const copySkips = compileOptions.report ? [] : void 0;
1617
+ const imported = await inlineImports(context, code, id, moduleCompileOptions, async (target) => loadModule(context, id, target), copySkips);
1618
+ addSkips(context, copySkips);
1292
1619
  if (imported) {
1293
1620
  code = imported.code;
1294
1621
  maps.push(...imported.maps);
@@ -1299,164 +1626,216 @@ function solidOptimizer(options = {}) {
1299
1626
  code = exposed.code;
1300
1627
  maps.push(exposed.map);
1301
1628
  }
1629
+ const lazy = await solidCompiler.transformLazyAsync(code, {
1630
+ filename,
1631
+ sourceMap: wantsMaps()
1632
+ });
1633
+ code = lazy.code;
1634
+ maps.push(lazy.map);
1635
+ const lowering = jsxOptions(false);
1636
+ const needed = /* @__PURE__ */ new Set();
1302
1637
  const inlined = moduleCompileOptions.inline === false ? void 0 : compile(code, {
1303
1638
  ...moduleCompileOptions,
1304
1639
  sourceMap: false
1305
1640
  });
1306
- const needed = /* @__PURE__ */ new Set();
1307
1641
  for (const version of /* @__PURE__ */ new Set([code, inlined?.code ?? code])) {
1308
- const dryRun = lower(getCompiler(), version, filename, jsxOptions(false));
1642
+ const dryRun = await solidCompiler.transformAsync(version, {
1643
+ ...lowering,
1644
+ filename
1645
+ });
1309
1646
  for (const helper of generatedImports(dryRun.code, filename, moduleName)) needed.add(helper);
1310
1647
  }
1648
+ if (moduleCompileOptions.inline !== false && spreadsOntoElement(code, filename)) for (const helper of attributeHelpers()) needed.add(helper);
1649
+ if (needed.size > 0) {
1650
+ const marked = addMarker(code, filename, {
1651
+ moduleName,
1652
+ helpers: withRelated([...needed]),
1653
+ moduleSources,
1654
+ builtIns: /* @__PURE__ */ new Set([
1655
+ ...builtIns,
1656
+ "createContext",
1657
+ "render",
1658
+ "children",
1659
+ ...CONTEXT_SAFE_PRIMITIVES
1660
+ ])
1661
+ });
1662
+ if (marked) {
1663
+ code = marked.code;
1664
+ maps.push(marked.map);
1665
+ }
1666
+ }
1667
+ const protectedRefs = protectRefs(code, filename);
1668
+ if (protectedRefs) {
1669
+ code = protectedRefs.code;
1670
+ maps.push(protectedRefs.map);
1671
+ }
1672
+ code = await resolveLazyModuleUrls(context, code, filename);
1311
1673
  preserved.add(id);
1312
- if (needed.size === 0) return code === source ? null : {
1313
- code,
1314
- map: combineMaps(maps)
1315
- };
1316
- const marked = addMarker(code, filename, {
1317
- moduleName,
1318
- helpers: withRelated([...needed]),
1319
- moduleSources,
1320
- builtIns: /* @__PURE__ */ new Set([
1321
- ...builtIns,
1322
- "createContext",
1323
- ...CONTEXT_SAFE_PRIMITIVES
1324
- ])
1325
- });
1326
- if (!marked) return code === source ? null : {
1327
- code,
1328
- map: combineMaps(maps)
1329
- };
1330
1674
  return {
1331
- code: marked.code,
1332
- map: combineMaps([...maps, marked.map])
1675
+ code,
1676
+ map: combineMaps(wantsMaps(), maps)
1333
1677
  };
1334
1678
  }
1335
- const originalTransform = main.transform;
1679
+ const main = plugins.find((plugin) => plugin.name === "solid");
1680
+ const originalTransform = main?.transform;
1336
1681
  const originalHandler = typeof originalTransform === "function" ? originalTransform : originalTransform?.handler;
1337
- if (originalHandler) main.transform = async function transform(code, id, transformOptions) {
1682
+ if (main && originalHandler) main.transform = async function transform(code, id, transformOptions) {
1338
1683
  if (chunkMode() && isClient(this) && isJSXModule(id)) return keepJSX(this, code, id);
1339
1684
  return originalHandler.call(this, code, id, transformOptions);
1340
1685
  };
1341
- return [
1342
- {
1343
- name: "solid-optimizer:module",
1344
- enforce: "pre",
1345
- configResolved(resolved) {
1346
- config = resolved;
1347
- },
1348
- buildStart() {
1349
- moduleConstants.clear();
1350
- jsxImports.clear();
1351
- usageIndexes.clear();
1352
- },
1353
- watchChange() {
1354
- moduleConstants.clear();
1355
- jsxImports.clear();
1356
- usageIndexes.clear();
1357
- },
1358
- async transform(source, id) {
1359
- if (!isBuild() && optimizer.dev !== true) return null;
1360
- if (chunkMode() && isClient(this) || !isJSXModule(id)) return null;
1361
- const filename = stripQuery(id);
1362
- const sourceOptions = {
1363
- ...await moduleOptions(this, source, id),
1364
- server: optimizer.server !== false && !isClient(this)
1365
- };
1366
- const result = compile(source, sourceOptions);
1367
- let code = result.code;
1368
- const maps = [result.map?.toString()];
1369
- if (isBuild() && sourceOptions.inline !== false) {
1370
- const imported = await inlineImports(this, code, id, sourceOptions, async (target) => loadRecorded(this, id, target));
1371
- if (imported) {
1372
- code = imported.code;
1373
- maps.push(...imported.maps);
1374
- }
1375
- const exposed = exposeLocals(code, filename);
1376
- if (exposed) {
1377
- code = exposed.code;
1378
- maps.push(exposed.map);
1379
- }
1380
- }
1381
- recorded.set(environmentKey(this, id), code);
1382
- if (code === source) return null;
1383
- return {
1384
- code,
1385
- map: combineMaps(maps)
1386
- };
1387
- }
1686
+ const modulePlugin = {
1687
+ name: "solid-optimizer:module",
1688
+ enforce: "pre",
1689
+ configResolved(resolved) {
1690
+ config = resolved;
1691
+ globals = sharedGlobals(resolved);
1388
1692
  },
1389
- main,
1390
- {
1391
- name: "solid-optimizer:module-type",
1392
- transform(code, id) {
1393
- if (!preserved.has(id)) return null;
1394
- const repaired = repairJSXSequences(code, stripQuery(id));
1395
- return repaired ? {
1396
- code: repaired.code,
1397
- map: repaired.map,
1398
- moduleType: "jsx"
1399
- } : {
1400
- code,
1401
- moduleType: "jsx"
1402
- };
1693
+ buildStart() {
1694
+ moduleConstants.clear();
1695
+ localImports.clear();
1696
+ usageIndexes.clear();
1697
+ skips.delete(this.environment.name);
1698
+ },
1699
+ watchChange() {
1700
+ moduleConstants.clear();
1701
+ localImports.clear();
1702
+ usageIndexes.clear();
1703
+ },
1704
+ async transform(source, id) {
1705
+ if (!isBuild() && optimizer.dev !== true) return null;
1706
+ if (chunkMode() && isClient(this) || !isJSXModule(id)) return null;
1707
+ const filename = stripQuery(id);
1708
+ const sourceOptions = await moduleOptions(this, source, id);
1709
+ const result = compile(source, sourceOptions);
1710
+ let code = result.code;
1711
+ const maps = [result.map?.toString()];
1712
+ let { skipped } = result;
1713
+ if (isBuild() && sourceOptions.inline !== false) {
1714
+ const copySkips = compileOptions.report ? [] : void 0;
1715
+ const imported = await inlineImports(this, code, id, sourceOptions, async (target) => loadRecorded(this, id, target), copySkips);
1716
+ addSkips(this, copySkips);
1717
+ if (imported) {
1718
+ code = imported.code;
1719
+ maps.push(...imported.maps);
1720
+ skipped = imported.skipped ?? skipped;
1721
+ }
1722
+ const exposed = exposeLocals(code, filename);
1723
+ if (exposed) {
1724
+ code = exposed.code;
1725
+ maps.push(exposed.map);
1726
+ }
1403
1727
  }
1728
+ addSkips(this, skipped);
1729
+ recorded.set(environmentKey(this, id), code);
1730
+ if (code === source) return null;
1731
+ return {
1732
+ code,
1733
+ map: combineMaps(wantsMaps(), maps)
1734
+ };
1735
+ }
1736
+ };
1737
+ const chunkPlugin = {
1738
+ name: "solid-optimizer:chunk",
1739
+ enforce: "post",
1740
+ config(_, env) {
1741
+ if (env.command !== "build") return;
1742
+ return {
1743
+ oxc: { jsx: "preserve" },
1744
+ build: { rolldownOptions: { transform: { jsx: "preserve" } } }
1745
+ };
1404
1746
  },
1405
- {
1406
- name: "solid-optimizer:chunk",
1407
- enforce: "post",
1408
- config(_, env) {
1409
- if (env.command !== "build") return;
1747
+ renderChunk: {
1748
+ order: "pre",
1749
+ handler(code, chunk) {
1750
+ if (!chunkMode() || !isClient(this) || !code.includes("__SOLID_OPTIMIZER_KEEP__")) return null;
1751
+ const filename = chunk.fileName;
1752
+ let repaired;
1753
+ let runtime;
1754
+ try {
1755
+ runtime = readMarkers(code, filename);
1756
+ } catch (error) {
1757
+ repaired = error instanceof SyntaxError ? repairJSXSequences(code, filename) : void 0;
1758
+ if (!repaired) throw error;
1759
+ runtime = readMarkers(repaired.code, filename);
1760
+ }
1761
+ if (!runtime) return null;
1762
+ const restored = restoreRefs(runtime.code, filename);
1763
+ const chunkCode = restored?.code ?? runtime.code;
1764
+ const lowerChunk = (source) => getCompiler().transform(source, {
1765
+ ...jsxOptions(false),
1766
+ filename: `${filename}.jsx`,
1767
+ sourceMap: wantsMaps()
1768
+ });
1769
+ let optimized = compile(chunkCode, {
1770
+ ...compileOptions,
1771
+ filename,
1772
+ sourceMap: wantsMaps(),
1773
+ constantVars: true,
1774
+ builtInAliases: runtime.builtInAliases
1775
+ });
1776
+ let linked;
1777
+ let lowered;
1778
+ try {
1779
+ lowered = lowerChunk(optimized.code);
1780
+ linked = linkHelpers(lowered.code, filename, moduleName, runtime.helpers);
1781
+ addSkips(this, optimized.skipped);
1782
+ } catch (error) {
1783
+ if (!(error instanceof MissingHelperError)) throw error;
1784
+ this.warn(`${error.message} ${filename} is not optimized.`);
1785
+ optimized = void 0;
1786
+ addSkips(this, [{
1787
+ pass: "inline",
1788
+ reason: "missing-helper",
1789
+ name: filename
1790
+ }]);
1791
+ lowered = lowerChunk(chunkCode);
1792
+ linked = linkHelpers(lowered.code, filename, moduleName, runtime.helpers);
1793
+ }
1410
1794
  return {
1411
- oxc: { jsx: "preserve" },
1412
- build: { rolldownOptions: { transform: { jsx: "preserve" } } }
1795
+ code: linked.code,
1796
+ map: combineMaps(wantsMaps(), [
1797
+ repaired?.map,
1798
+ runtime.map,
1799
+ restored?.map,
1800
+ optimized?.map?.toString(),
1801
+ lowered.map,
1802
+ linked.map
1803
+ ])
1413
1804
  };
1414
- },
1415
- renderChunk: {
1416
- order: "pre",
1417
- handler(code, chunk) {
1418
- if (!chunkMode() || !isClient(this) || !code.includes("__SOLID_OPTIMIZER_KEEP__")) return null;
1419
- const filename = chunk.fileName;
1420
- let repaired;
1421
- let runtime;
1422
- try {
1423
- runtime = readMarkers(code, filename);
1424
- } catch (error) {
1425
- repaired = error instanceof SyntaxError ? repairJSXSequences(code, filename) : void 0;
1426
- if (!repaired) throw error;
1427
- runtime = readMarkers(repaired.code, filename);
1428
- }
1429
- if (!runtime) return null;
1430
- let optimized = compile(runtime.code, {
1431
- ...compileOptions,
1432
- filename,
1433
- constantVars: true,
1434
- builtInAliases: runtime.builtInAliases
1435
- });
1436
- let lowered = lower(getCompiler(), optimized.code, filename, jsxOptions(false));
1437
- let linked;
1438
- try {
1439
- linked = linkHelpers(lowered.code, filename, moduleName, runtime.helpers);
1440
- } catch (error) {
1441
- if (!(error instanceof MissingHelperError)) throw error;
1442
- this.warn(`${error.message} ${filename} is not optimized.`);
1443
- optimized = void 0;
1444
- lowered = lower(getCompiler(), runtime.code, filename, jsxOptions(false));
1445
- linked = linkHelpers(lowered.code, filename, moduleName, runtime.helpers);
1446
- }
1447
- return {
1448
- code: linked.code,
1449
- map: combineMaps([
1450
- repaired?.map,
1451
- runtime.map,
1452
- optimized?.map?.toString(),
1453
- lowered.map,
1454
- linked.map
1455
- ])
1456
- };
1457
- }
1458
1805
  }
1459
1806
  }
1807
+ };
1808
+ chunkPlugin.generateBundle = function generateBundle() {
1809
+ const { report } = optimizer;
1810
+ if (report === void 0 || report === false) return;
1811
+ const environment = this.environment.name;
1812
+ const result = {
1813
+ environment,
1814
+ skips: skips.get(environment) ?? []
1815
+ };
1816
+ if (typeof report === "function") report(result);
1817
+ else this.environment.logger.info(formatReport(result));
1818
+ };
1819
+ const moduleTypePlugin = {
1820
+ name: "solid-optimizer:module-type",
1821
+ transform(code, id) {
1822
+ if (!preserved.has(id)) return null;
1823
+ const repaired = repairJSXSequences(code, stripQuery(id));
1824
+ return repaired ? {
1825
+ code: repaired.code,
1826
+ map: repaired.map,
1827
+ moduleType: "jsx"
1828
+ } : {
1829
+ code,
1830
+ moduleType: "jsx"
1831
+ };
1832
+ }
1833
+ };
1834
+ return [
1835
+ modulePlugin,
1836
+ ...plugins,
1837
+ moduleTypePlugin,
1838
+ chunkPlugin
1460
1839
  ];
1461
1840
  }
1462
1841
  //#endregion