solid-optimizer 1.0.0-next.7 → 1.0.0-next.9

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.
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Ends each statement that relies on a line break.
3
+ *
4
+ * The other passes replace a read with text that can start with `(` or a
5
+ * template literal, like `(p.close)()` for `props.close()`. After a statement
6
+ * with no semicolon, that text continues the statement instead of starting a
7
+ * new one, so `open()` and `(p.close)()` on separate lines call what `open()`
8
+ * returned. A semicolon keeps the statements the parser found.
9
+ */
10
+ import type { Node } from 'oxc-parser';
11
+ import { forEachChild } from './ast';
12
+ import type { PassContext } from './context';
13
+
14
+ const TERMINATED = new Set([
15
+ 'BreakStatement',
16
+ 'ContinueStatement',
17
+ 'DebuggerStatement',
18
+ 'DoWhileStatement',
19
+ 'ExportAllDeclaration',
20
+ 'ExpressionStatement',
21
+ 'ImportDeclaration',
22
+ 'ReturnStatement',
23
+ 'ThrowStatement',
24
+ 'TSTypeAliasDeclaration',
25
+ 'VariableDeclaration',
26
+ ]);
27
+
28
+ const LOOP_HEADS = new Set(['ForStatement', 'ForInStatement', 'ForOfStatement']);
29
+
30
+ function isTerminated(node: Node, context: PassContext): boolean {
31
+ if (node.type === 'VariableDeclaration') {
32
+ const parent = context.parents.get(node);
33
+ return !(parent && LOOP_HEADS.has(parent.type) && Reflect.get(parent, 'body') !== node);
34
+ }
35
+ if (node.type === 'ExportNamedDeclaration') {
36
+ return !node.declaration;
37
+ }
38
+ if (node.type === 'ExportDefaultDeclaration') {
39
+ const { type } = node.declaration;
40
+ return type !== 'FunctionDeclaration' && type !== 'ClassDeclaration';
41
+ }
42
+ return TERMINATED.has(node.type);
43
+ }
44
+
45
+ const TRIVIA = /(?:\s|\/\/[^\n\r\u2028\u2029]*|\/\*[\s\S]*?\*\/)*/y;
46
+
47
+ /** Whether code other than the closing brace of a block follows `position`. */
48
+ function hasCodeAfter(code: string, position: number): boolean {
49
+ TRIVIA.lastIndex = position;
50
+ TRIVIA.exec(code);
51
+ return TRIVIA.lastIndex < code.length && code[TRIVIA.lastIndex] !== '}';
52
+ }
53
+
54
+ export function terminateStatements(context: PassContext): boolean {
55
+ const { code, s } = context;
56
+ let changed = false;
57
+ const visit = (node: Node): void => {
58
+ if (isTerminated(node, context) && code[node.end - 1] !== ';' && hasCodeAfter(code, node.end)) {
59
+ s.appendLeft(node.end, ';');
60
+ changed = true;
61
+ }
62
+ forEachChild(node, visit);
63
+ };
64
+ visit(context.program);
65
+ return changed;
66
+ }
package/src/vite/index.ts CHANGED
@@ -32,6 +32,7 @@ import { collectParents, forEachChild, isIntrinsicTag, parse } from '../ast';
32
32
  import { analyzeScopes } from '../scope';
33
33
  import { CONTEXT_SAFE_PRIMITIVES } from '../provider';
34
34
  import type { ImportedConstants } from '../constants';
35
+ import { runtimeImportSources } from '../constants';
35
36
  import type { Primitive } from '../value';
36
37
  import { sharedGlobals } from './globals';
37
38
  import type { Skip } from '../context';
@@ -694,54 +695,93 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
694
695
  */
695
696
  const recorded = new Map<string, string>();
696
697
 
697
- /** The modules of the project each module imports, read from its file. */
698
+ /**
699
+ * Whether components can be copied from a module: one of the app's, or
700
+ * one of a package listed in `optimizer.packages`.
701
+ */
702
+ const isCopyable = (id: string): boolean => {
703
+ const file = stripQuery(id).replaceAll('\\', '/');
704
+ if (!file.includes('/node_modules/')) {
705
+ return true;
706
+ }
707
+ for (const name of optimizer.packages ?? []) {
708
+ if (file.includes(`/node_modules/${name}/`)) {
709
+ return true;
710
+ }
711
+ }
712
+ return false;
713
+ };
714
+
715
+ /** The modules each module imports, read from its file. */
698
716
  const localImports = new Map<string, Promise<string[]>>();
699
717
 
700
718
  /**
701
- * The modules of the project a module imports, leaving out dependencies.
702
- * They come from the file on disk, so they do not depend on the order
703
- * modules are transformed in. Modules without JSX count too, since reading
704
- * their constants can load a module with JSX.
719
+ * The code of a module as its file holds it. A module with no file, like
720
+ * a virtual module a plugin generates, is loaded instead, unless it has
721
+ * JSX: this plugin transforms such a module, so loading it could wait for
722
+ * the transform that asks. Its imports are then not followed.
723
+ */
724
+ async function readModuleCode(
725
+ context: Rollup.PluginContext,
726
+ id: string,
727
+ ): Promise<string | undefined> {
728
+ try {
729
+ return await readFile(stripQuery(id), 'utf8');
730
+ } catch {
731
+ if (isJSXModule(id)) {
732
+ return undefined;
733
+ }
734
+ }
735
+ try {
736
+ return (await context.load({ id })).code ?? undefined;
737
+ } catch {
738
+ return undefined;
739
+ }
740
+ }
741
+
742
+ /**
743
+ * The modules a module imports at runtime that a transform can wait for:
744
+ * the app's, those of packages listed in `optimizer.packages`, and virtual
745
+ * modules. A transform only waits for a module it copies from, and it only
746
+ * copies from those, so a module of another package is never in a loop of
747
+ * transforms that wait for each other. A virtual module can re-export the
748
+ * app, so a listed package can import the app back through one, like a
749
+ * docs framework that imports its theme's layout.
750
+ *
751
+ * Imports only used as types are left out, since TypeScript drops them,
752
+ * and so are Solid's own modules and Node's built-ins. The imports come
753
+ * from the file on disk, so they do not depend on the order modules are
754
+ * transformed in. Modules without JSX count too, since reading their
755
+ * constants can load a module with JSX.
705
756
  */
706
757
  async function findLocalImports(context: Rollup.PluginContext, id: string): Promise<string[]> {
707
758
  let pending = localImports.get(id);
708
759
  if (!pending) {
709
760
  pending = (async () => {
710
- let code: string;
711
- try {
712
- code = await readFile(stripQuery(id), 'utf8');
713
- } catch {
761
+ const code = await readModuleCode(context, id);
762
+ if (code === undefined) {
714
763
  return [];
715
764
  }
716
765
  let program: Program;
717
766
  try {
718
- program = parse(stripQuery(id), code);
767
+ // A loaded module is JavaScript, whatever its id says.
768
+ program = parse(
769
+ /\.[cm]?[jt]sx?$/.test(stripQuery(id)) ? stripQuery(id) : `${id}.js`,
770
+ code,
771
+ );
719
772
  } catch {
720
773
  return [];
721
774
  }
722
- const sources = new Set<string>();
723
- for (const statement of program.body) {
724
- if (
725
- (statement.type === 'ImportDeclaration' && statement.importKind !== 'type') ||
726
- ((statement.type === 'ExportNamedDeclaration' ||
727
- statement.type === 'ExportAllDeclaration') &&
728
- statement.source &&
729
- statement.exportKind !== 'type')
730
- ) {
731
- const value = statement.source?.value;
732
- if (value !== undefined && !moduleSources.includes(value)) {
733
- sources.add(value);
734
- }
735
- }
736
- }
737
775
  const resolving = [];
738
- for (const source of sources) {
739
- resolving.push(context.resolve(source, id));
776
+ for (const source of runtimeImportSources(program)) {
777
+ if (!moduleSources.includes(source) && !source.startsWith('node:')) {
778
+ resolving.push(context.resolve(source, id));
779
+ }
740
780
  }
741
781
  const resolved = await Promise.all(resolving);
742
782
  const local: string[] = [];
743
783
  for (const target of resolved) {
744
- if (target && !target.external && !target.id.includes('/node_modules/')) {
784
+ if (target && !target.external && isCopyable(target.id)) {
745
785
  local.push(target.id);
746
786
  }
747
787
  }
@@ -752,7 +792,7 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
752
792
  return pending;
753
793
  }
754
794
 
755
- /** Whether `from` imports `to`, directly or through other modules of the project. */
795
+ /** Whether `from` imports `to`, directly or through other modules. */
756
796
  async function reaches(
757
797
  context: Rollup.PluginContext,
758
798
  from: string,
@@ -954,23 +994,6 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
954
994
  readonly skips: Skip[] | undefined;
955
995
  }
956
996
 
957
- /**
958
- * Whether components can be copied from a module: one of the app's, or
959
- * one of a package listed in `optimizer.packages`.
960
- */
961
- const isCopyable = (id: string): boolean => {
962
- const file = stripQuery(id).replaceAll('\\', '/');
963
- if (!file.includes('/node_modules/')) {
964
- return true;
965
- }
966
- for (const name of optimizer.packages ?? []) {
967
- if (file.includes(`/node_modules/${name}/`)) {
968
- return true;
969
- }
970
- }
971
- return false;
972
- };
973
-
974
997
  /** The listed packages already warned about, by environment. */
975
998
  const warnedPackages = new Set<string>();
976
999
 
@@ -1089,7 +1112,20 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1089
1112
  skip('copy-external');
1090
1113
  return undefined;
1091
1114
  }
1092
- targets.set(dependency.source, target.external ? dependency.source : target.id);
1115
+ if (!target.id.startsWith('\0')) {
1116
+ targets.set(dependency.source, target.external ? dependency.source : target.id);
1117
+ continue;
1118
+ }
1119
+ // A virtual module's id cannot be imported again, so the copy keeps
1120
+ // the specifier, when it means the same module from the importer.
1121
+ // oxlint-disable-next-line no-await-in-loop
1122
+ const fromImporter = await context.resolve(dependency.source, id);
1123
+ if (fromImporter?.id !== target.id) {
1124
+ state.excluded.add(key);
1125
+ skip('copy-virtual');
1126
+ return undefined;
1127
+ }
1128
+ targets.set(dependency.source, dependency.source);
1093
1129
  }
1094
1130
  }
1095
1131
  const rename = new Map<string, string>();