@octanejs/rspack-plugin 0.1.58 → 0.2.1

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/README.md CHANGED
@@ -7,7 +7,7 @@ integration lives in `@octanejs/rsbuild-plugin`.
7
7
  ## Install
8
8
 
9
9
  ```sh
10
- pnpm add octane
10
+ pnpm add octane @tsrx/oxc@0.20.0
11
11
  pnpm add -D @rspack/core @octanejs/rspack-plugin
12
12
  ```
13
13
 
@@ -104,6 +104,19 @@ default and does not change development, HMR, or watch output. See
104
104
  [CSS-module constants](../../docs/compiler-css-module-constants.md) for the
105
105
  provider contract and stylesheet-ownership rules.
106
106
 
107
+ One-shot production client builds also specialize imported components whose
108
+ body never returns a value, as the Vite plugin does. A `createRoot` or
109
+ `hydrateRoot` root and a `<Component />` call over such an import skip the
110
+ generic return-value path, so a small app can tree-shake that path out of its
111
+ bundle. An import is proven only when Octane compiled it as a void export and
112
+ the provider's final JavaScript, after SWC and every later loader, still cannot
113
+ return a value. The importer's final code must also still bind it to the same
114
+ module and export. An importer that uses a proof is compiled once more and is
115
+ not stored in the persistent module cache. A proven module that changes after
116
+ that fails the build. Watch, development, HMR and profiling builds, and builds
117
+ with a custom `runtime`, `universalRuntime` or `layerSpecializations`, keep the
118
+ generic paths.
119
+
107
120
  Rspack layers can compile the same authored module against distinct universal
108
121
  renderer graphs. Configure the background graph at the top level, then key
109
122
  `layerSpecializations` by the exact value of `module.layer`:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@octanejs/rspack-plugin",
3
- "version": "0.1.58",
3
+ "version": "0.2.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "engines": {
@@ -45,7 +45,7 @@
45
45
  },
46
46
  "peerDependencies": {
47
47
  "@rspack/core": "^2.0.0",
48
- "octane": "^0.10.0"
48
+ "octane": "^0.11.0"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@rspack/core": "^2.1.4",
@@ -53,7 +53,7 @@
53
53
  "@types/node": "^24.13.3",
54
54
  "css-loader": "6.11.0",
55
55
  "jsdom": "^30.0.1",
56
- "octane": "0.10.0",
56
+ "octane": "0.11.0",
57
57
  "vitest": "^4.1.10"
58
58
  },
59
59
  "scripts": {
@@ -9,46 +9,23 @@ import {
9
9
  CSS_MODULE_CONTEXT_KEY,
10
10
  cssModuleSourceHash,
11
11
  } from './css-module-data.js';
12
+ import {
13
+ currentModules,
14
+ identifier,
15
+ iterable,
16
+ JAVASCRIPT_TYPES,
17
+ moduleSource,
18
+ oneShotProduction,
19
+ rebuildModules,
20
+ sameStrings,
21
+ targetForRequest,
22
+ targetsForRequests,
23
+ } from './module-graph.js';
12
24
 
13
25
  const PLUGIN_NAME = 'OctaneRspackCssModuleConstants';
14
26
  const DIAGNOSTIC_OWNER = '@octanejs/rspack-plugin';
15
- const JAVASCRIPT_TYPES = new Set(['javascript/auto', 'javascript/esm']);
16
27
  const HASH = /^[a-f0-9]{64}$/;
17
28
 
18
- function iterable(value) {
19
- return value != null && typeof value[Symbol.iterator] === 'function' ? value : [];
20
- }
21
-
22
- function identifier(module) {
23
- if (typeof module?.identifier !== 'function') return null;
24
- const id = module.identifier();
25
- return typeof id === 'string' ? id : null;
26
- }
27
-
28
- function moduleSource(module) {
29
- const source = module?.originalSource?.()?.source();
30
- if (typeof source === 'string') return source;
31
- return Buffer.isBuffer(source) ? source.toString('utf8') : null;
32
- }
33
-
34
- /** Reacquire current-build objects; native-backed Modules never enter our state. */
35
- function currentModules(modules) {
36
- const result = new Map();
37
- const seen = new Set();
38
- const visit = (module) => {
39
- if (module == null || seen.has(module)) return;
40
- seen.add(module);
41
- // Concatenation can move a provider under another module. Prefer the
42
- // original child if a wrapper happens to share its identifier.
43
- for (const child of iterable(module.modules)) visit(child);
44
- if (module.rootModule != null) visit(module.rootModule);
45
- const id = identifier(module);
46
- if (id !== null && !result.has(id)) result.set(id, module);
47
- };
48
- for (const module of iterable(modules)) visit(module);
49
- return result;
50
- }
51
-
52
29
  function candidateInfo(module) {
53
30
  const info = module?.buildInfo?.[CSS_MODULE_BUILD_INFO_KEY];
54
31
  if (
@@ -73,60 +50,6 @@ function changed(importer, request, reason) {
73
50
  throw new Error(`${DIAGNOSTIC_OWNER}: CSS-module proof changed for ${location}: ${reason}.`);
74
51
  }
75
52
 
76
- /**
77
- * A resource path is not an import identity: issuer rules, layers, queries,
78
- * dependency categories, and replacements can select different modules. Read
79
- * the effective target of the actual ESM edge after the make phase instead.
80
- */
81
- function targetForRequest(compilation, importer, request) {
82
- const targets = new Map();
83
- for (const connection of compilation.moduleGraph.getOutgoingConnections(importer)) {
84
- const dependency = connection.dependency;
85
- if (dependency?.request !== request || dependency.category !== 'esm') continue;
86
- if (dependency.attributes != null && Object.keys(dependency.attributes).length > 0) {
87
- return null;
88
- }
89
- const target = connection.module;
90
- const id = identifier(target);
91
- if (id === null) return null;
92
- targets.set(id, target);
93
- }
94
- return targets.size === 1 ? targets.values().next().value : null;
95
- }
96
-
97
- /** Resolve several exact requests with one fresh walk of the current graph. */
98
- function targetsForRequests(compilation, importer, requests) {
99
- const states = new Map();
100
- for (const request of requests) {
101
- states.set(request, { id: null, target: null, invalid: false });
102
- }
103
- let invalid = 0;
104
- for (const connection of compilation.moduleGraph.getOutgoingConnections(importer)) {
105
- const dependency = connection.dependency;
106
- if (dependency?.category !== 'esm') continue;
107
- const state = states.get(dependency.request);
108
- if (state === undefined || state.invalid) continue;
109
- const target = connection.module;
110
- const id =
111
- dependency.attributes != null && Object.keys(dependency.attributes).length > 0
112
- ? null
113
- : identifier(target);
114
- if (id === null || (state.id !== null && state.id !== id)) {
115
- state.invalid = true;
116
- state.target = null;
117
- invalid++;
118
- if (invalid === states.size) break;
119
- continue;
120
- }
121
- state.id = id;
122
- state.target = target;
123
- }
124
- for (const [request, state] of states) {
125
- states.set(request, state.invalid ? null : state.target);
126
- }
127
- return states;
128
- }
129
-
130
53
  function sortedStrings(values) {
131
54
  return [...new Set([...iterable(values)].filter((value) => typeof value === 'string'))].sort();
132
55
  }
@@ -202,12 +125,6 @@ function readTargetProof(module, option, environment, cache) {
202
125
  return proof;
203
126
  }
204
127
 
205
- function sameStrings(left, right) {
206
- const a = [...new Set(left)].sort();
207
- const b = [...new Set(right)].sort();
208
- return a.length === b.length && a.every((value, index) => value === b[index]);
209
- }
210
-
211
128
  function verifyResolvedTarget(importer, entry, target) {
212
129
  if (identifier(target) !== entry.id)
213
130
  changed(identifier(importer), entry.request, 'the effective module identity differs');
@@ -319,24 +236,7 @@ async function collectAndRebuild(compilation, state, option, environment) {
319
236
  if (imports.length === 0) state.proofs.delete(id);
320
237
  else if (imports.length !== proof.imports.length) state.proofs.set(id, { ...proof, imports });
321
238
  }
322
- // Rspack owns graph mutation. Do not write source objects, synthesize entry
323
- // dependencies, or invoke importModule (which executes application modules).
324
- // Its public rebuildModule dispatcher batches synchronous requests. Ignore
325
- // callback Module values: Rspack may return those in a different order, and
326
- // only the current graph's exact identifiers authenticate the rebuilt inputs.
327
- const pending = (() => {
328
- const modules = currentModules(compilation.modules);
329
- return [...state.proofs.keys()].map((id) => {
330
- const importer = modules.get(id);
331
- if (importer === undefined)
332
- changed(id, undefined, 'the importer disappeared before rebuilding');
333
- return new Promise((resolve, reject) => {
334
- compilation.rebuildModule(importer, (error) => (error ? reject(error) : resolve()));
335
- });
336
- });
337
- })();
338
- const results = await Promise.allSettled(pending);
339
- for (const result of results) if (result.status === 'rejected') throw result.reason;
239
+ await rebuildModules(compilation, [...state.proofs.keys()], changed);
340
240
  const rebuiltModules = currentModules(compilation.modules);
341
241
  for (const [id, proof] of state.proofs) {
342
242
  const rebuilt = rebuiltModules.get(id);
@@ -359,12 +259,6 @@ async function collectAndRebuild(compilation, state, option, environment) {
359
259
  verifyGraph(compilation, state);
360
260
  }
361
261
 
362
- function oneShotProduction(compiler) {
363
- return (
364
- compiler.options.mode === 'production' && compiler.watchMode !== true && !compiler.options.watch
365
- );
366
- }
367
-
368
262
  /** Install the opt-in, main-thread, same-compilation CSS proof controller. */
369
263
  export function installCssModuleConstants(compiler, { option, environment }) {
370
264
  if (option === undefined || option === false) return;
@@ -1,13 +1,11 @@
1
- import { createHash } from 'node:crypto';
1
+ import { sourceHash as cssModuleSourceHash } from './module-graph.js';
2
2
 
3
3
  // Only plain data crosses Rspack's worker boundary. The provider callback and
4
4
  // native module graph stay on the main thread for the current compilation.
5
5
  export const CSS_MODULE_CONTEXT_KEY = '__octaneCssModuleConstants';
6
6
  export const CSS_MODULE_BUILD_INFO_KEY = 'octaneCssModuleConstants';
7
7
 
8
- export function cssModuleSourceHash(source) {
9
- return createHash('sha256').update(String(source)).digest('hex');
10
- }
8
+ export { cssModuleSourceHash };
11
9
 
12
10
  export function clearCssModuleBuildInfo(module) {
13
11
  if (module?.buildInfo && typeof module.buildInfo === 'object') {
@@ -3,6 +3,11 @@ import {
3
3
  CSS_MODULE_BUILD_INFO_KEY,
4
4
  CSS_MODULE_CONTEXT_KEY,
5
5
  } from './css-module-data.js';
6
+ import {
7
+ clearVoidComponentBuildInfo,
8
+ VOID_COMPONENT_BUILD_INFO_KEY,
9
+ VOID_COMPONENT_CONTEXT_KEY,
10
+ } from './void-component-data.js';
6
11
 
7
12
  /**
8
13
  * Rspack does not copy a module's layer or buildInfo into parallel-loader
@@ -12,7 +17,9 @@ export function pitch() {
12
17
  this.data ??= {};
13
18
  this.data.octaneLayer = this._module?.layer ?? null;
14
19
  this.data[CSS_MODULE_CONTEXT_KEY] = this[CSS_MODULE_CONTEXT_KEY] ?? null;
20
+ this.data[VOID_COMPONENT_CONTEXT_KEY] = this[VOID_COMPONENT_CONTEXT_KEY] ?? null;
15
21
  clearCssModuleBuildInfo(this._module);
22
+ clearVoidComponentBuildInfo(this._module);
16
23
  if (this._module?.buildInfo && typeof this._module.buildInfo === 'object') {
17
24
  delete this._module.buildInfo.octane;
18
25
  }
@@ -33,6 +40,12 @@ export default function finalizeOctaneLoader(source, sourceMap, metadata) {
33
40
  }
34
41
  this._module.buildInfo[CSS_MODULE_BUILD_INFO_KEY] = result.cssModuleBuildInfo;
35
42
  }
43
+ if (result?.voidComponentBuildInfo) {
44
+ if (!this._module.buildInfo || typeof this._module.buildInfo !== 'object') {
45
+ this._module.buildInfo = {};
46
+ }
47
+ this._module.buildInfo[VOID_COMPONENT_BUILD_INFO_KEY] = result.voidComponentBuildInfo;
48
+ }
36
49
  for (const dependency of result?.missingDependencies ?? []) {
37
50
  this.addMissingDependency(dependency);
38
51
  }
package/src/loader.js CHANGED
@@ -16,6 +16,11 @@ import {
16
16
  } from './shared.js';
17
17
  import { loadDescriptorChildrenImports } from './descriptor-children.js';
18
18
  import { textTypeFactsForLoader } from './text-types.js';
19
+ import {
20
+ clearVoidComponentBuildInfo,
21
+ finishVoidComponents,
22
+ prepareVoidComponents,
23
+ } from './void-component-data.js';
19
24
 
20
25
  function realRoot(path) {
21
26
  try {
@@ -95,6 +100,7 @@ export default function octaneLoader(source, inputSourceMap) {
95
100
  this.cacheable?.(true);
96
101
  clearBuildInfo(this._module);
97
102
  clearCssModuleBuildInfo(this._module);
103
+ clearVoidComponentBuildInfo(this._module);
98
104
 
99
105
  try {
100
106
  const options = normalizeLoaderOptions(this.getOptions?.() ?? {});
@@ -182,6 +188,12 @@ export default function octaneLoader(source, inputSourceMap) {
182
188
  dev,
183
189
  })
184
190
  : null;
191
+ const voidComponents = prepareVoidComponents(this, authoredSource, id, {
192
+ environment,
193
+ hmr,
194
+ dev,
195
+ profile,
196
+ });
185
197
  const finish = (clientOnlyImports, isDescriptorChildrenImport, textTypeFacts, callback) => {
186
198
  try {
187
199
  const result = compiler.transform(authoredSource, id, {
@@ -193,8 +205,10 @@ export default function octaneLoader(source, inputSourceMap) {
193
205
  ...(isDescriptorChildrenImport === null ? null : { isDescriptorChildrenImport }),
194
206
  ...(textTypeFacts === undefined ? null : { textTypeFacts }),
195
207
  ...cssModuleConstants?.transformOptions,
208
+ ...voidComponents?.transformOptions,
196
209
  });
197
210
 
211
+ finishVoidComponents(this, voidComponents, result);
198
212
  if (result === null) {
199
213
  callback(null, source, this.sourceMap === false ? undefined : inputSourceMap);
200
214
  return;
@@ -0,0 +1,137 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ // Main-thread helpers shared by the cross-module proof controllers. Each walk
4
+ // reads the current compilation; native-backed Modules never enter retained
5
+ // proof state, only their identifiers and source fingerprints do.
6
+
7
+ export const JAVASCRIPT_TYPES = new Set(['javascript/auto', 'javascript/esm']);
8
+
9
+ export function sourceHash(source) {
10
+ return createHash('sha256').update(String(source)).digest('hex');
11
+ }
12
+
13
+ export function iterable(value) {
14
+ return value != null && typeof value[Symbol.iterator] === 'function' ? value : [];
15
+ }
16
+
17
+ export function identifier(module) {
18
+ if (typeof module?.identifier !== 'function') return null;
19
+ const id = module.identifier();
20
+ return typeof id === 'string' ? id : null;
21
+ }
22
+
23
+ export function moduleSource(module) {
24
+ const source = module?.originalSource?.()?.source();
25
+ if (typeof source === 'string') return source;
26
+ return Buffer.isBuffer(source) ? source.toString('utf8') : null;
27
+ }
28
+
29
+ /** Reacquire current-build objects; native-backed Modules never enter our state. */
30
+ export function currentModules(modules) {
31
+ const result = new Map();
32
+ const seen = new Set();
33
+ const visit = (module) => {
34
+ if (module == null || seen.has(module)) return;
35
+ seen.add(module);
36
+ // Concatenation can move a provider under another module. Prefer the
37
+ // original child if a wrapper happens to share its identifier.
38
+ for (const child of iterable(module.modules)) visit(child);
39
+ if (module.rootModule != null) visit(module.rootModule);
40
+ const id = identifier(module);
41
+ if (id !== null && !result.has(id)) result.set(id, module);
42
+ };
43
+ for (const module of iterable(modules)) visit(module);
44
+ return result;
45
+ }
46
+
47
+ /**
48
+ * A resource path is not an import identity: issuer rules, layers, queries,
49
+ * dependency categories, and replacements can select different modules. Read
50
+ * the effective target of the actual ESM edge after the make phase instead.
51
+ */
52
+ export function targetForRequest(compilation, importer, request) {
53
+ const targets = new Map();
54
+ for (const connection of compilation.moduleGraph.getOutgoingConnections(importer)) {
55
+ const dependency = connection.dependency;
56
+ if (dependency?.request !== request || dependency.category !== 'esm') continue;
57
+ if (dependency.attributes != null && Object.keys(dependency.attributes).length > 0) {
58
+ return null;
59
+ }
60
+ const target = connection.module;
61
+ const id = identifier(target);
62
+ if (id === null) return null;
63
+ targets.set(id, target);
64
+ }
65
+ return targets.size === 1 ? targets.values().next().value : null;
66
+ }
67
+
68
+ /** Resolve several exact requests with one fresh walk of the current graph. */
69
+ export function targetsForRequests(compilation, importer, requests) {
70
+ const states = new Map();
71
+ for (const request of requests) {
72
+ states.set(request, { id: null, target: null, invalid: false });
73
+ }
74
+ let invalid = 0;
75
+ for (const connection of compilation.moduleGraph.getOutgoingConnections(importer)) {
76
+ const dependency = connection.dependency;
77
+ if (dependency?.category !== 'esm') continue;
78
+ const state = states.get(dependency.request);
79
+ if (state === undefined || state.invalid) continue;
80
+ const target = connection.module;
81
+ const id =
82
+ dependency.attributes != null && Object.keys(dependency.attributes).length > 0
83
+ ? null
84
+ : identifier(target);
85
+ if (id === null || (state.id !== null && state.id !== id)) {
86
+ state.invalid = true;
87
+ state.target = null;
88
+ invalid++;
89
+ if (invalid === states.size) break;
90
+ continue;
91
+ }
92
+ state.id = id;
93
+ state.target = target;
94
+ }
95
+ for (const [request, state] of states) {
96
+ states.set(request, state.invalid ? null : state.target);
97
+ }
98
+ return states;
99
+ }
100
+
101
+ /** Resolve one request, or several with a single walk. */
102
+ export function targetsFor(compilation, importer, requests) {
103
+ if (requests.length !== 1) return targetsForRequests(compilation, importer, requests);
104
+ return new Map([[requests[0], targetForRequest(compilation, importer, requests[0])]]);
105
+ }
106
+
107
+ export function sameStrings(left, right) {
108
+ const a = [...new Set(left)].sort();
109
+ const b = [...new Set(right)].sort();
110
+ return a.length === b.length && a.every((value, index) => value === b[index]);
111
+ }
112
+
113
+ /**
114
+ * Rspack owns graph mutation. Do not write source objects, synthesize entry
115
+ * dependencies, or invoke importModule (which executes application modules).
116
+ * Its public rebuildModule dispatcher batches synchronous requests. Ignore
117
+ * callback Module values: Rspack may return those in a different order, and
118
+ * only the current graph's exact identifiers authenticate the rebuilt inputs.
119
+ */
120
+ export async function rebuildModules(compilation, ids, changed) {
121
+ const modules = currentModules(compilation.modules);
122
+ const pending = ids.map((id) => {
123
+ const module = modules.get(id);
124
+ if (module === undefined) changed(id, undefined, 'the importer disappeared before rebuilding');
125
+ return new Promise((resolve, reject) => {
126
+ compilation.rebuildModule(module, (error) => (error ? reject(error) : resolve()));
127
+ });
128
+ });
129
+ const results = await Promise.allSettled(pending);
130
+ for (const result of results) if (result.status === 'rejected') throw result.reason;
131
+ }
132
+
133
+ export function oneShotProduction(compiler) {
134
+ return (
135
+ compiler.options.mode === 'production' && compiler.watchMode !== true && !compiler.options.watch
136
+ );
137
+ }
@@ -1,5 +1,9 @@
1
1
  import octaneLoader from './loader.js';
2
2
  import { CSS_MODULE_BUILD_INFO_KEY, CSS_MODULE_CONTEXT_KEY } from './css-module-data.js';
3
+ import {
4
+ VOID_COMPONENT_BUILD_INFO_KEY,
5
+ VOID_COMPONENT_CONTEXT_KEY,
6
+ } from './void-component-data.js';
3
7
 
4
8
  /**
5
9
  * Run the unchanged public Octane loader inside Rspack's worker pool. Rspack
@@ -12,6 +16,8 @@ export default function parallelOctaneLoader(source, sourceMap) {
12
16
  const finalizer = this.loaders[this.loaderIndex - 1];
13
17
  module.layer = finalizer?.loaderItem?.data?.octaneLayer ?? undefined;
14
18
  this[CSS_MODULE_CONTEXT_KEY] = finalizer?.loaderItem?.data?.[CSS_MODULE_CONTEXT_KEY] ?? undefined;
19
+ this[VOID_COMPONENT_CONTEXT_KEY] =
20
+ finalizer?.loaderItem?.data?.[VOID_COMPONENT_CONTEXT_KEY] ?? undefined;
15
21
 
16
22
  const callback = this.callback.bind(this);
17
23
  const async = this.async.bind(this);
@@ -27,6 +33,9 @@ export default function parallelOctaneLoader(source, sourceMap) {
27
33
  ...(module.buildInfo?.[CSS_MODULE_BUILD_INFO_KEY] === undefined
28
34
  ? null
29
35
  : { cssModuleBuildInfo: module.buildInfo[CSS_MODULE_BUILD_INFO_KEY] }),
36
+ ...(module.buildInfo?.[VOID_COMPONENT_BUILD_INFO_KEY] === undefined
37
+ ? null
38
+ : { voidComponentBuildInfo: module.buildInfo[VOID_COMPONENT_BUILD_INFO_KEY] }),
30
39
  missingDependencies,
31
40
  },
32
41
  });
package/src/plugin.js CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  } from 'octane/compiler/bundler';
12
12
  import { installCssModuleConstants } from './css-module-constants.js';
13
13
  import { createStreamedSignalHmrRuntimeModule } from './streamed-signals-hmr.js';
14
+ import { installVoidComponentProofs } from './void-component-proofs.js';
14
15
  import {
15
16
  getOctaneRspackBuildInfo,
16
17
  inferRspackEnvironment,
@@ -522,6 +523,18 @@ export class OctaneRspackPlugin {
522
523
  compiler.options.mode === 'production' &&
523
524
  !dev &&
524
525
  !hotModuleReplacement;
526
+ // Imported void components specialize roots and component calls, as the
527
+ // Vite plugin does for production builds. Profiling keeps generic roots,
528
+ // and only the DOM runtime is known to export the specialized helpers.
529
+ const voidComponents =
530
+ environment === 'client' &&
531
+ compiler.options.mode === 'production' &&
532
+ !dev &&
533
+ !profile &&
534
+ !hotModuleReplacement &&
535
+ this.options.runtime === undefined &&
536
+ this.options.universalRuntime === undefined &&
537
+ this.options.layerSpecializations === undefined;
525
538
  // Loader worker pools cannot share one TypeScript Program. Watch and HMR
526
539
  // use syntax-only compilation, including production-mode watch builds.
527
540
  const textTypes =
@@ -551,6 +564,7 @@ export class OctaneRspackPlugin {
551
564
  requireDirective: this.options.requireDirective === true,
552
565
  transpile: this.options.transpile !== false,
553
566
  cssModuleConstants,
567
+ voidComponents,
554
568
  textTypes: tsconfig,
555
569
  });
556
570
  if (tsconfig !== undefined) {
@@ -566,6 +580,7 @@ export class OctaneRspackPlugin {
566
580
  environment,
567
581
  });
568
582
  }
583
+ if (voidComponents) installVoidComponentProofs(compiler);
569
584
  const neutralCompiler = createDiscoveryCompiler(this.options, root, profile);
570
585
  const discoveryCompilers = [neutralCompiler];
571
586
  for (const specialization of Object.values(this.options.layerSpecializations ?? {})) {
@@ -0,0 +1,107 @@
1
+ import { analyzeCompiledModule, findVoidComponentImports } from 'octane/compiler/bundler';
2
+ import { sourceHash } from './module-graph.js';
3
+
4
+ // Only plain data crosses Rspack's worker boundary. The module graph and every
5
+ // proof decision stay with the main-thread controller for one compilation.
6
+ export const VOID_COMPONENT_CONTEXT_KEY = '__octaneVoidComponents';
7
+ export const VOID_COMPONENT_BUILD_INFO_KEY = 'octaneVoidComponents';
8
+
9
+ // Only a relative import can name a component the controller proves.
10
+ const RELATIVE_IMPORT = /\bfrom\s*['"]\.\.?\//;
11
+ // Outside compiled JSX, only a root from an imported Octane root factory can
12
+ // use a proof; a supplied proof makes the hook pass consult such a module.
13
+ const ROOT_FACTORY_IMPORT =
14
+ /\bimport\s*\{[^}]*\b(?:createRoot|hydrateRoot)\b[^}]*\}\s*from\s*['"]octane['"]/;
15
+
16
+ export function voidImportKey(request, imported) {
17
+ return `${request}\0${imported}`;
18
+ }
19
+
20
+ export function clearVoidComponentBuildInfo(module) {
21
+ if (module?.buildInfo && typeof module.buildInfo === 'object') {
22
+ delete module.buildInfo[VOID_COMPONENT_BUILD_INFO_KEY];
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Prepare this exact authored loader input's void-component facts. Every build
28
+ * the controller enables records its own void exports and candidate imports,
29
+ * so cached modules carry the same facts in a watch and a one-shot build. Only
30
+ * a one-shot build's proof pass supplies proven imports.
31
+ */
32
+ export function prepareVoidComponents(context, source, id, options) {
33
+ const data = context[VOID_COMPONENT_CONTEXT_KEY];
34
+ if (
35
+ data?.enabled !== true ||
36
+ options.environment !== 'client' ||
37
+ options.hmr ||
38
+ options.dev ||
39
+ options.profile ||
40
+ context.mode !== 'production' ||
41
+ context.hot === true
42
+ ) {
43
+ return null;
44
+ }
45
+ const hash = data.proof == null ? null : sourceHash(source);
46
+ const proven =
47
+ hash !== null && data.proof.sourceHash === hash
48
+ ? new Set(data.proof.imports.map(({ request, imported }) => voidImportKey(request, imported)))
49
+ : null;
50
+ // A proof is a fact about other modules' final output, outside this module's
51
+ // cache key. Output that may consume one is never cached.
52
+ if (proven !== null) context.cacheable?.(false);
53
+ const consumed = new Set();
54
+ return {
55
+ source,
56
+ id,
57
+ sourceHash: hash,
58
+ consumed,
59
+ transformOptions: {
60
+ collectVoidComponentExports: true,
61
+ ...(proven === null
62
+ ? null
63
+ : {
64
+ isVoidComponentImport(request, imported) {
65
+ const key = voidImportKey(request, imported);
66
+ if (!proven.has(key)) return false;
67
+ consumed.add(key);
68
+ return true;
69
+ },
70
+ }),
71
+ },
72
+ };
73
+ }
74
+
75
+ /**
76
+ * Publish this build's exports, candidate imports, and the proofs it consumed
77
+ * with the import bindings Octane's output reads them through. Only a module
78
+ * that can consume a proof pays for the scans.
79
+ */
80
+ export function finishVoidComponents(context, prepared, result) {
81
+ const module = context._module;
82
+ if (prepared === null || !module) return;
83
+ const compiled = result?.kind === 'compile';
84
+ const exports =
85
+ compiled && Array.isArray(result.voidComponentExports) ? result.voidComponentExports : [];
86
+ const imports =
87
+ RELATIVE_IMPORT.test(prepared.source) && (compiled || ROOT_FACTORY_IMPORT.test(prepared.source))
88
+ ? findVoidComponentImports(prepared.source, prepared.id)
89
+ : [];
90
+ if (exports.length === 0 && imports.length === 0) return;
91
+ const consumed = [...prepared.consumed].sort();
92
+ // null (unparseable output) can never match the final code's bindings.
93
+ const bindings =
94
+ consumed.length === 0
95
+ ? []
96
+ : (analyzeCompiledModule(result?.code ?? prepared.source, prepared.id)?.importBindings.filter(
97
+ ({ request, imported }) => prepared.consumed.has(voidImportKey(request, imported)),
98
+ ) ?? null);
99
+ if (!module.buildInfo || typeof module.buildInfo !== 'object') module.buildInfo = {};
100
+ module.buildInfo[VOID_COMPONENT_BUILD_INFO_KEY] = {
101
+ sourceHash: prepared.sourceHash ?? sourceHash(prepared.source),
102
+ exports: [...exports],
103
+ imports: imports.map(({ request, imported }) => ({ request, imported })),
104
+ consumed,
105
+ bindings,
106
+ };
107
+ }
@@ -0,0 +1,321 @@
1
+ import { analyzeCompiledModule } from 'octane/compiler/bundler';
2
+ import {
3
+ currentModules,
4
+ identifier,
5
+ JAVASCRIPT_TYPES,
6
+ moduleSource,
7
+ oneShotProduction,
8
+ rebuildModules,
9
+ sameStrings,
10
+ sourceHash,
11
+ targetsFor,
12
+ } from './module-graph.js';
13
+ import {
14
+ VOID_COMPONENT_BUILD_INFO_KEY,
15
+ VOID_COMPONENT_CONTEXT_KEY,
16
+ voidImportKey,
17
+ } from './void-component-data.js';
18
+
19
+ const PLUGIN_NAME = 'OctaneRspackVoidComponents';
20
+ const DIAGNOSTIC_OWNER = '@octanejs/rspack-plugin';
21
+ const HASH = /^[a-f0-9]{64}$/;
22
+ // After every other finishMake tap: an earlier proof controller may rebuild a
23
+ // module this one proves, and a proof must describe the provider's final build.
24
+ const FINISH_MAKE_STAGE = 100;
25
+
26
+ function strings(value) {
27
+ return Array.isArray(value) && value.every((item) => typeof item === 'string');
28
+ }
29
+
30
+ function importEntries(value, local) {
31
+ return (
32
+ Array.isArray(value) &&
33
+ value.every(
34
+ (entry) =>
35
+ typeof entry?.request === 'string' &&
36
+ typeof entry.imported === 'string' &&
37
+ (!local || typeof entry.local === 'string'),
38
+ )
39
+ );
40
+ }
41
+
42
+ function candidateInfo(module) {
43
+ const info = module?.buildInfo?.[VOID_COMPONENT_BUILD_INFO_KEY];
44
+ if (
45
+ info == null ||
46
+ typeof info.sourceHash !== 'string' ||
47
+ !HASH.test(info.sourceHash) ||
48
+ !strings(info.exports) ||
49
+ !strings(info.consumed) ||
50
+ !importEntries(info.imports, false) ||
51
+ (info.bindings !== null && !importEntries(info.bindings, true))
52
+ ) {
53
+ return null;
54
+ }
55
+ return info;
56
+ }
57
+
58
+ function changed(importer, request, reason) {
59
+ const location =
60
+ request === undefined
61
+ ? JSON.stringify(importer)
62
+ : `${JSON.stringify(importer)} (${JSON.stringify(request)})`;
63
+ throw new Error(`${DIAGNOSTIC_OWNER}: void component proof changed for ${location}: ${reason}.`);
64
+ }
65
+
66
+ function requestsOf(entries) {
67
+ return [...new Set(entries.map((entry) => entry.request))].sort();
68
+ }
69
+
70
+ /** Final-code facts by module identifier, reused while its source is unchanged. */
71
+ function finalFacts(module, id, analyses) {
72
+ const code = moduleSource(module);
73
+ if (code === null) return null;
74
+ const fingerprint = sourceHash(code);
75
+ let facts = analyses.get(id);
76
+ if (facts === undefined || facts.fingerprint !== fingerprint) {
77
+ const analysis = analyzeCompiledModule(code, module.resource ?? id);
78
+ facts = {
79
+ fingerprint,
80
+ exports: new Set(analysis?.voidComponentExports),
81
+ bindings:
82
+ analysis === null
83
+ ? null
84
+ : new Map(analysis.importBindings.map((binding) => [binding.local, binding])),
85
+ };
86
+ analyses.set(id, facts);
87
+ }
88
+ return facts;
89
+ }
90
+
91
+ /**
92
+ * The provider half of a proof: Octane compiled `imported` as a void export of
93
+ * this module in this build, and the module's final JavaScript, after every
94
+ * later loader, still exports a function that cannot return a value. A loader
95
+ * that rewrites the export or its return behavior fails the second check.
96
+ *
97
+ * While proofs are collected, a provider that can consume proofs itself is
98
+ * usually about to be rebuilt, so its current code is not what will run. Its
99
+ * final code is proven after the rebuild instead (`deferred`).
100
+ */
101
+ function provenProvider(target, imported, analyses, deferred = false) {
102
+ const id = identifier(target);
103
+ if (id === null || !JAVASCRIPT_TYPES.has(target.type)) return null;
104
+ const info = candidateInfo(target);
105
+ if (!info?.exports.includes(imported)) return null;
106
+ if (deferred && info.imports.length > 0) return { id };
107
+ const facts = finalFacts(target, id, analyses);
108
+ return facts?.exports.has(imported) ? { id, fingerprint: facts.fingerprint } : null;
109
+ }
110
+
111
+ /**
112
+ * The importer half: its final code still binds every local that Octane's
113
+ * output read a consumed proof through to the same request and export. A
114
+ * later loader that rebinds one would redirect a specialized call elsewhere.
115
+ */
116
+ function bindingsHold(info, facts) {
117
+ if (info.bindings === null || facts.bindings === null) return false;
118
+ const bound = new Set(info.bindings.map((entry) => voidImportKey(entry.request, entry.imported)));
119
+ if (!info.consumed.every((key) => bound.has(key))) return false;
120
+ return info.bindings.every((entry) => {
121
+ const binding = facts.bindings.get(entry.local);
122
+ return binding?.request === entry.request && binding.imported === entry.imported;
123
+ });
124
+ }
125
+
126
+ /**
127
+ * Receipt every rebuilt importer whose consumed proofs still hold on the final
128
+ * graph. Returns the importers whose proofs a later loader invalidated.
129
+ */
130
+ function receiptRebuilt(compilation, state, analyses) {
131
+ const modules = currentModules(compilation.modules);
132
+ const invalid = [];
133
+ for (const [id, proof] of state.proofs) {
134
+ const importer = modules.get(id);
135
+ const info = candidateInfo(importer);
136
+ if (info === null || info.sourceHash !== proof.sourceHash) {
137
+ changed(id, undefined, 'the authored source changed while rebuilding');
138
+ }
139
+ if (info.consumed.length === 0) continue;
140
+ const supplied = new Map(
141
+ proof.imports.map((entry) => [voidImportKey(entry.request, entry.imported), entry]),
142
+ );
143
+ if (info.consumed.some((key) => !supplied.has(key))) {
144
+ changed(id, undefined, 'the compiler consumed an unprovided import');
145
+ }
146
+ const consumed = info.consumed.map((key) => supplied.get(key));
147
+ const targets = targetsFor(compilation, importer, requestsOf(consumed));
148
+ const imports = [];
149
+ for (const { request, imported } of consumed) {
150
+ const provider = provenProvider(targets.get(request), imported, analyses);
151
+ if (provider === null) break;
152
+ imports.push({ request, imported, ...provider });
153
+ }
154
+ const facts = finalFacts(importer, id, analyses);
155
+ if (imports.length !== consumed.length || facts === null || !bindingsHold(info, facts)) {
156
+ invalid.push(id);
157
+ continue;
158
+ }
159
+ state.receipts.set(id, {
160
+ sourceHash: proof.sourceHash,
161
+ fingerprint: facts.fingerprint,
162
+ consumed: info.consumed,
163
+ imports,
164
+ });
165
+ }
166
+ return invalid;
167
+ }
168
+
169
+ /** Each consumed proof still names the modules and exact sources it was proven on. */
170
+ function verifyGraph(compilation, state) {
171
+ if (state.receipts.size === 0) return;
172
+ const modules = currentModules(compilation.modules);
173
+ for (const [id, receipt] of state.receipts) {
174
+ const importer = modules.get(id);
175
+ const info = candidateInfo(importer);
176
+ if (
177
+ info === null ||
178
+ info.sourceHash !== receipt.sourceHash ||
179
+ !sameStrings(info.consumed, receipt.consumed)
180
+ ) {
181
+ changed(id, undefined, 'the authored importer or committed-use receipt differs');
182
+ }
183
+ const source = moduleSource(importer);
184
+ if (source === null || sourceHash(source) !== receipt.fingerprint) {
185
+ changed(id, undefined, 'the final importer source differs');
186
+ }
187
+ const targets = targetsFor(compilation, importer, requestsOf(receipt.imports));
188
+ for (const entry of receipt.imports) {
189
+ const target = targets.get(entry.request);
190
+ if (identifier(target) !== entry.id)
191
+ changed(id, entry.request, 'the effective module identity differs');
192
+ const provided = moduleSource(target);
193
+ if (provided === null || sourceHash(provided) !== entry.fingerprint)
194
+ changed(id, entry.request, 'the final provider source differs');
195
+ }
196
+ }
197
+ }
198
+
199
+ function verifyFinalSources(compilation, state) {
200
+ if (state.receipts.size === 0) return;
201
+ const modules = currentModules(compilation.modules);
202
+ const expected = new Map();
203
+ for (const [id, receipt] of state.receipts) {
204
+ expected.set(id, receipt.fingerprint);
205
+ for (const entry of receipt.imports) expected.set(entry.id, entry.fingerprint);
206
+ }
207
+ for (const [id, fingerprint] of expected) {
208
+ const module = modules.get(id);
209
+ // The full graph was checked at seal, before optimization. A module that
210
+ // optimization removed since then no longer runs at all.
211
+ if (module === undefined) continue;
212
+ const source = moduleSource(module);
213
+ if (source === null || sourceHash(source) !== fingerprint) {
214
+ changed(id, undefined, 'the emitted module source differs');
215
+ }
216
+ }
217
+ }
218
+
219
+ async function collectAndRebuild(compilation, state) {
220
+ if (state.started) return;
221
+ state.started = true;
222
+ const analyses = new Map();
223
+ // Collect from the complete first graph before rebuilding anything, so the
224
+ // proofs never depend on the order Rspack happened to build modules in.
225
+ {
226
+ const modules = currentModules(compilation.modules);
227
+ const candidates = [...modules]
228
+ .filter(([, module]) => candidateInfo(module)?.imports.length > 0)
229
+ .map(([id]) => id)
230
+ .sort();
231
+ for (const id of candidates) {
232
+ const importer = modules.get(id);
233
+ const info = candidateInfo(importer);
234
+ const targets = targetsFor(compilation, importer, requestsOf(info.imports));
235
+ const imports = info.imports.filter(
236
+ ({ request, imported }) =>
237
+ targets.get(request) != null &&
238
+ provenProvider(targets.get(request), imported, analyses, true) !== null,
239
+ );
240
+ if (imports.length > 0) state.proofs.set(id, { sourceHash: info.sourceHash, imports });
241
+ }
242
+ }
243
+ if (state.proofs.size === 0) return;
244
+ await rebuildModules(compilation, [...state.proofs.keys()], changed);
245
+ // Every consumed provider is proven on its final code here, including one
246
+ // rebuilt as an importer in this batch. A later loader can also rewrite
247
+ // what Octane specialized; an importer whose proof does not hold is rebuilt
248
+ // once more without one. Any change after that fails closed.
249
+ const invalid = receiptRebuilt(compilation, state, analyses);
250
+ if (invalid.length > 0) {
251
+ for (const id of invalid) state.proofs.delete(id);
252
+ await rebuildModules(compilation, invalid, changed);
253
+ const modules = currentModules(compilation.modules);
254
+ for (const id of invalid) {
255
+ if (candidateInfo(modules.get(id))?.consumed.length > 0) {
256
+ changed(id, undefined, 'a generic rebuild consumed a proof');
257
+ }
258
+ }
259
+ state.receipts.clear();
260
+ const unstable = receiptRebuilt(compilation, state, analyses);
261
+ if (unstable.length > 0) changed(unstable[0], undefined, 'a consumed proof no longer holds');
262
+ }
263
+ verifyGraph(compilation, state);
264
+ }
265
+
266
+ /**
267
+ * Prove imported void components for production client builds. Rspack runs a
268
+ * loader before it knows its module's outgoing edges or their final output, so
269
+ * the proof is established after make from the effective graph, then supplied
270
+ * to a rebuild of each importer that can use it. A one-shot build consumes
271
+ * proofs and fails closed if any proven module changes later; a watch build
272
+ * only records the facts its cached modules need for a later one-shot build.
273
+ */
274
+ export function installVoidComponentProofs(compiler) {
275
+ const NormalModule = compiler.webpack?.NormalModule;
276
+ if (
277
+ typeof NormalModule?.getCompilationHooks !== 'function' ||
278
+ typeof compiler.hooks.thisCompilation?.tap !== 'function' ||
279
+ typeof compiler.hooks.finishMake?.tapPromise !== 'function'
280
+ ) {
281
+ return;
282
+ }
283
+ const states = new WeakMap();
284
+ compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
285
+ const state = {
286
+ discoverOnly: !oneShotProduction(compiler),
287
+ started: false,
288
+ proofs: new Map(),
289
+ receipts: new Map(),
290
+ };
291
+ states.set(compilation, state);
292
+ NormalModule.getCompilationHooks(compilation).loader.tap(PLUGIN_NAME, (context, module) => {
293
+ context[VOID_COMPONENT_CONTEXT_KEY] = {
294
+ enabled: true,
295
+ proof: state.proofs.get(identifier(module)) ?? null,
296
+ };
297
+ });
298
+ if (state.discoverOnly) return;
299
+ // All finishModules taps have completed, and module concatenation has not
300
+ // yet rewritten the effective graph. This catches later rebuilds.
301
+ compilation.hooks.seal.tap({ name: PLUGIN_NAME, stage: Number.MAX_SAFE_INTEGER }, () =>
302
+ verifyGraph(compilation, state),
303
+ );
304
+ compilation.hooks.processAssets.tap(
305
+ {
306
+ name: PLUGIN_NAME,
307
+ stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT,
308
+ },
309
+ () => verifyFinalSources(compilation, state),
310
+ );
311
+ });
312
+ compiler.hooks.finishMake.tapPromise(
313
+ { name: PLUGIN_NAME, stage: FINISH_MAKE_STAGE },
314
+ async (compilation) => {
315
+ const state = states.get(compilation);
316
+ if (state !== undefined && !state.discoverOnly && oneShotProduction(compiler)) {
317
+ await collectAndRebuild(compilation, state);
318
+ }
319
+ },
320
+ );
321
+ }