@ecopages/react 0.6.0 → 0.7.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.
Files changed (95) hide show
  1. package/README.md +50 -87
  2. package/package.json +32 -14
  3. package/src/bundling/bootstrap-package-paths.d.ts +13 -1
  4. package/src/bundling/bootstrap-package-paths.js +25 -3
  5. package/src/bundling/bundle.d.ts +8 -36
  6. package/src/bundling/bundle.js +42 -73
  7. package/src/client-graph/ast-transform-eco-page.d.ts +10 -6
  8. package/src/client-graph/ast-transform-eco-page.js +56 -35
  9. package/src/client-graph/ast-transform-import-edits.d.ts +10 -2
  10. package/src/client-graph/ast-transform-import-edits.js +36 -6
  11. package/src/client-graph/ast-transform-stripped-imports.d.ts +37 -0
  12. package/src/client-graph/ast-transform-stripped-imports.js +191 -0
  13. package/src/client-graph/ast-transform-walk-imports.d.ts +4 -0
  14. package/src/client-graph/ast-transform-walk-imports.js +15 -1
  15. package/src/client-graph/ast-transform.d.ts +12 -3
  16. package/src/client-graph/ast-transform.js +41 -56
  17. package/src/client-graph/boundary-plugin-read-file-inline.d.ts +3 -0
  18. package/src/client-graph/boundary-plugin-read-file-inline.js +14 -10
  19. package/src/client-graph/boundary-plugin-transform.d.ts +5 -4
  20. package/src/client-graph/boundary-plugin-transform.js +6 -13
  21. package/src/client-graph/boundary-plugin.d.ts +47 -1
  22. package/src/client-graph/boundary-plugin.js +267 -53
  23. package/src/client-graph/foreign-boundary-rewrite.d.ts +31 -0
  24. package/src/client-graph/foreign-boundary-rewrite.js +360 -0
  25. package/src/client-graph/foreign-jsx-reach.d.ts +25 -0
  26. package/src/client-graph/foreign-jsx-reach.js +68 -0
  27. package/src/client-graph/module-classification.js +3 -10
  28. package/src/client-graph/reachability-traverse.js +35 -105
  29. package/src/client-graph/requested-exports-plan.d.ts +62 -0
  30. package/src/client-graph/requested-exports-plan.js +125 -0
  31. package/src/client-graph/scope-walk.d.ts +37 -0
  32. package/src/client-graph/scope-walk.js +407 -0
  33. package/src/client-graph/specifier-classification.d.ts +2 -1
  34. package/src/client-graph/specifier-classification.js +9 -7
  35. package/src/contracts/router-adapter.d.ts +9 -24
  36. package/src/dev-transform/react-dev-transform-contributor.d.ts +4 -4
  37. package/src/dev-transform/react-dev-transform-contributor.js +6 -7
  38. package/src/hmr/hmr-strategy-process.d.ts +7 -5
  39. package/src/hmr/hmr-strategy-process.js +21 -16
  40. package/src/hmr/hmr-strategy.d.ts +11 -10
  41. package/src/hmr/hmr-strategy.js +32 -53
  42. package/src/hmr/page-metadata-cache.js +1 -1
  43. package/src/hydration/browser/foreign-boundary.d.ts +29 -0
  44. package/src/hydration/browser/foreign-boundary.js +128 -0
  45. package/src/hydration/browser/island-hydration.d.ts +3 -4
  46. package/src/hydration/browser/island-hydration.js +3 -4
  47. package/src/hydration/browser/page-hydration-hmr.d.ts +8 -7
  48. package/src/hydration/browser/page-hydration-hmr.js +53 -10
  49. package/src/hydration/browser/page-hydration.d.ts +6 -5
  50. package/src/hydration/browser/page-hydration.js +8 -6
  51. package/src/hydration/foreign-subtree.d.ts +27 -0
  52. package/src/hydration/foreign-subtree.js +69 -0
  53. package/src/hydration/hydration-asset.d.ts +37 -29
  54. package/src/hydration/hydration-asset.js +74 -138
  55. package/src/hydration/hydration-island-entry-source.d.ts +17 -0
  56. package/src/hydration/hydration-island-entry-source.js +32 -0
  57. package/src/hydration/hydration-page-entry-source.d.ts +20 -2
  58. package/src/hydration/hydration-page-entry-source.js +17 -12
  59. package/src/hydration/page-data-reader.d.ts +4 -7
  60. package/src/hydration/page-data-reader.js +5 -10
  61. package/src/mdx/mdx-config-dependency.d.ts +10 -15
  62. package/src/mdx/mdx-config-dependency.js +9 -22
  63. package/src/mdx/mdx-loader-plugin.d.ts +2 -0
  64. package/src/mdx/mdx-loader-plugin.js +1 -0
  65. package/src/page/page-module.js +1 -1
  66. package/src/plugin/react.plugin.d.ts +0 -7
  67. package/src/plugin/react.plugin.js +4 -33
  68. package/src/plugin/react.types.d.ts +0 -29
  69. package/src/render/component-ssr.d.ts +18 -0
  70. package/src/render/component-ssr.js +37 -0
  71. package/src/render/layout-compose.d.ts +4 -2
  72. package/src/render/layout-compose.js +13 -6
  73. package/src/render/layout-render-tracker.d.ts +20 -0
  74. package/src/render/layout-render-tracker.js +33 -0
  75. package/src/render/react-renderer.d.ts +28 -10
  76. package/src/render/react-renderer.js +103 -38
  77. package/src/render/react-runtime.js +2 -2
  78. package/src/bundling/runtime-alias-map.d.ts +0 -12
  79. package/src/bundling/runtime-alias-map.js +0 -110
  80. package/src/bundling/runtime-bundle.d.ts +0 -70
  81. package/src/bundling/runtime-bundle.js +0 -233
  82. package/src/bundling/runtime-interop-plugin.d.ts +0 -5
  83. package/src/bundling/runtime-interop-plugin.js +0 -32
  84. package/src/bundling/runtime-mode.d.ts +0 -1
  85. package/src/bundling/runtime-mode.js +0 -10
  86. package/src/bundling/runtime-modules.d.ts +0 -21
  87. package/src/bundling/runtime-modules.js +0 -28
  88. package/src/hydration/bootstrap-imports.d.ts +0 -25
  89. package/src/hydration/bootstrap-imports.js +0 -33
  90. package/src/hydration/compiled-page-hydration-options.d.ts +0 -19
  91. package/src/hydration/compiled-page-hydration-options.js +0 -1
  92. package/src/hydration/hydration-script-compiler.d.ts +0 -47
  93. package/src/hydration/hydration-script-compiler.js +0 -213
  94. package/src/runtime/use-sync-external-store-with-selector.d.ts +0 -3
  95. package/src/runtime/use-sync-external-store-with-selector.js +0 -54
@@ -4,35 +4,40 @@
4
4
  * Build plugin securing the Ecopages isomorphic compilation pipeline.
5
5
  */
6
6
  import { fileSystem } from '@ecopages/file-system';
7
- import path from 'node:path';
7
+ import { path } from '@ecopages/file-system/path';
8
+ import { parseModuleSource, resolveProjectModulePath } from '@ecopages/core/build';
8
9
  import { parseDeclaredModules, toModuleBaseSpecifier } from './specifier-classification.js';
9
10
  import { classifyClientGraphModule } from './module-classification.js';
10
11
  import { transformClientGraphModule } from './boundary-plugin-transform.js';
11
- const SOURCE_FILE_FILTER = /\.(tsx?|jsx?)$/;
12
+ import { inlineReadFileSyncCalls } from './boundary-plugin-read-file-inline.js';
13
+ import { scanForeignJsxReach, toRealPath } from './foreign-jsx-reach.js';
14
+ import { isReactBoundaryVariant, rewriteForeignImports } from './foreign-boundary-rewrite.js';
15
+ import { createRequestedExportsPlan, } from './requested-exports-plan.js';
16
+ /** Source modules the boundary may transform; virtual ids and installed packages never reach it. */
17
+ const SOURCE_FILES = {
18
+ filter: /\.(tsx?|jsx?)(?:\?eco-variant=[\w-]+)?$/,
19
+ exclude: /^\0|\/node_modules\//,
20
+ };
21
+ const buildContexts = new WeakMap();
12
22
  /**
13
- * Shares transitive export reachability among boundary plugins in one grouped build.
14
- *
15
23
  * @remarks
16
- * Grouped entries load one shared copy of each helper, so every entry's root analysis
17
- * must be visible to whichever boundary plugin transforms that helper first.
24
+ * Every path is named relative to the project root, as no plugin key may hold an absolute path: the key joins
25
+ * the dependency key of each React entry, which a moved build must still find in its ledger.
18
26
  */
19
- const groupedRequestedExports = new WeakMap();
20
- const buildRequestedExports = new WeakMap();
21
- const buildContexts = new WeakMap();
22
- function getRequestedExports(groupedEntrypointFiles) {
23
- if (!groupedEntrypointFiles) {
24
- return new Map();
25
- }
26
- const existing = groupedRequestedExports.get(groupedEntrypointFiles);
27
- if (existing) {
28
- return existing;
29
- }
30
- const requestedExports = new Map();
31
- groupedRequestedExports.set(groupedEntrypointFiles, requestedExports);
32
- return requestedExports;
27
+ function createBoundaryCacheKey(options) {
28
+ const keyRoot = options.projectRoot ?? options.absWorkingDir;
29
+ const toKeyPath = (filePath) => path.relative(keyRoot, filePath);
30
+ return JSON.stringify({
31
+ workingDir: toKeyPath(options.absWorkingDir),
32
+ entrypointFile: options.entrypointFile ? toKeyPath(options.entrypointFile) : undefined,
33
+ groupedEntrypointFiles: [...options.groupedEntrypointFiles].map(toKeyPath).sort(),
34
+ groupedDeclaredModules: [...options.groupedDeclaredModules].sort(),
35
+ declaredModules: [...options.declaredModules].sort(),
36
+ alwaysAllowSpecifiers: [...options.alwaysAllowSpecifiers].sort(),
37
+ });
33
38
  }
34
39
  function normalizeClientGraphBoundaryOptions(options) {
35
- const absWorkingDir = path.resolve(options?.absWorkingDir ?? process.cwd());
40
+ const absWorkingDir = path.resolve(options?.absWorkingDir ?? path.cwd());
36
41
  const projectRoot = options?.projectRoot ? path.resolve(absWorkingDir, options.projectRoot) : undefined;
37
42
  const entrypointFile = options?.entrypointFile ? path.resolve(absWorkingDir, options.entrypointFile) : undefined;
38
43
  const groupedEntrypointFiles = new Set([entrypointFile, ...(options?.groupedEntrypointFiles ?? [])]
@@ -41,16 +46,7 @@ function normalizeClientGraphBoundaryOptions(options) {
41
46
  const declaredModules = [...(options?.declaredModules ?? [])];
42
47
  const groupedDeclaredModules = [...(options?.groupedDeclaredModules ?? declaredModules)];
43
48
  const alwaysAllowSpecifiers = [...(options?.alwaysAllowSpecifiers ?? [])];
44
- const cacheKey = JSON.stringify({
45
- projectRoot,
46
- absWorkingDir,
47
- entrypointFile,
48
- groupedEntrypointFiles: [...groupedEntrypointFiles].sort(),
49
- groupedDeclaredModules: [...groupedDeclaredModules].sort(),
50
- declaredModules: [...declaredModules].sort(),
51
- alwaysAllowSpecifiers: [...alwaysAllowSpecifiers].sort(),
52
- });
53
- return {
49
+ const normalized = {
54
50
  absWorkingDir,
55
51
  projectRoot,
56
52
  entrypointFile,
@@ -58,10 +54,92 @@ function normalizeClientGraphBoundaryOptions(options) {
58
54
  groupedDeclaredModules,
59
55
  declaredModules,
60
56
  alwaysAllowSpecifiers,
61
- cacheKey,
62
57
  };
58
+ return { ...normalized, cacheKey: createBoundaryCacheKey(normalized) };
63
59
  }
64
- function loadClientGraphBoundaryModule(args, options, requestedExports, isEntrypoint = options.entrypointFile === path.resolve(options.absWorkingDir, args.path)) {
60
+ function readBoundaryModule(filePath, absWorkingDir) {
61
+ let source;
62
+ try {
63
+ source = fileSystem.readFileSync(filePath);
64
+ }
65
+ catch {
66
+ return undefined;
67
+ }
68
+ const inlining = inlineReadFileSyncCalls(source, filePath, absWorkingDir);
69
+ let program;
70
+ try {
71
+ program = parseModuleSource(filePath, inlining.transformed).program;
72
+ }
73
+ catch {
74
+ program = undefined;
75
+ }
76
+ return { source: inlining.transformed, program, inlined: inlining.modified, inlinedFiles: inlining.inlinedFiles };
77
+ }
78
+ /**
79
+ * Resolves an import for the requested-export scan through the build's own resolver.
80
+ *
81
+ * @remarks
82
+ * A module outside `node_modules` that the build bundles is followed, so a workspace package imported by
83
+ * name counts like a relative import. Without a build resolver (a plugin driven outside Rolldown, as in
84
+ * unit tests) relative and tsconfig path imports still resolve from the project. A resolve that throws is
85
+ * an import the build itself rejects, such as a Node builtin in a browser build, so it is not followed.
86
+ */
87
+ async function resolveScanImport(build, specifier, importer, projectRoot) {
88
+ let resolved;
89
+ try {
90
+ resolved = await build.resolve(specifier, importer);
91
+ }
92
+ catch {
93
+ return { kind: 'skip' };
94
+ }
95
+ const local = path.isAbsolute(specifier)
96
+ ? fileSystem.exists(specifier)
97
+ ? specifier
98
+ : undefined
99
+ : resolveProjectModulePath(projectRoot, importer, specifier, { preserveBarrel: true });
100
+ const id = resolved ? (resolved.external ? undefined : resolved.id) : local;
101
+ if (!resolved && !local)
102
+ return { kind: 'unresolved' };
103
+ if (!id || id.startsWith('\0') || id.split('/').includes('node_modules'))
104
+ return { kind: 'skip' };
105
+ return { kind: 'module', filePath: toRealPath(id.replace(/[?#].*$/, '')) };
106
+ }
107
+ /** The load of a module's source file: a module variant reads the same file as the plain module. */
108
+ function stripVariant(args) {
109
+ return { path: args.path.replace(/\?eco-variant=[\w-]+$/, '') };
110
+ }
111
+ function isTransformedSource(filePath, projectRoot) {
112
+ const category = classifyClientGraphModule(filePath, projectRoot);
113
+ return SOURCE_FILES.filter.test(filePath) && (category === 'app' || category === 'workspace');
114
+ }
115
+ /**
116
+ * Reads one module for its load: from the plan when the scan reached it, otherwise from disk.
117
+ *
118
+ * @remarks
119
+ * The first module to load that is not an entry makes the plan, with that load's resolver; every other
120
+ * load waits for the same plan.
121
+ */
122
+ async function takeModule(build, state, sourcePath, options, transforms) {
123
+ const realPath = toRealPath(sourcePath);
124
+ if (!state.plan && !state.seeds.has(realPath)) {
125
+ const projectRoot = options.projectRoot ?? options.absWorkingDir;
126
+ state.plan = createRequestedExportsPlan({
127
+ seeds: state.seeds,
128
+ resolveImport: (specifier, importer) => resolveScanImport(build, specifier, importer, projectRoot),
129
+ readModule: (filePath) => state.loadedEntries.has(filePath)
130
+ ? state.loadedEntries.get(filePath)
131
+ : readBoundaryModule(filePath, options.absWorkingDir),
132
+ transforms: transforms(),
133
+ });
134
+ void state.plan.then(() => state.loadedEntries.clear());
135
+ }
136
+ const plan = await state.plan;
137
+ const module = plan?.takeModule(realPath) ?? readBoundaryModule(sourcePath, options.absWorkingDir);
138
+ if (!plan)
139
+ state.loadedEntries.set(realPath, module);
140
+ return { module, plan };
141
+ }
142
+ async function loadClientGraphBoundaryModule(build, args, options, state, transforms, isEntrypoint = options.entrypointFile === path.resolve(options.absWorkingDir, args.path)) {
65
143
  const sourcePath = path.resolve(options.absWorkingDir, args.path);
66
144
  if (options.entrypointFile &&
67
145
  options.groupedEntrypointFiles.has(sourcePath) &&
@@ -79,20 +157,17 @@ function loadClientGraphBoundaryModule(args, options, requestedExports, isEntryp
79
157
  if (category === 'package' || category === 'vendored' || category === 'virtual') {
80
158
  return undefined;
81
159
  }
82
- let source;
83
- try {
84
- source = fileSystem.readFileSync(args.path);
85
- }
86
- catch {
160
+ const { module, plan } = await takeModule(build, state, sourcePath, options, transforms);
161
+ if (!module)
87
162
  return undefined;
88
- }
163
+ for (const inlinedFile of module.inlinedFiles)
164
+ build.addWatchFile(inlinedFile);
89
165
  return transformClientGraphModule({
90
166
  filePath: args.path,
91
- source,
92
- absWorkingDir: options.absWorkingDir,
167
+ module,
93
168
  category,
94
169
  globallyDeclaredSources,
95
- requestedExports,
170
+ requestedExports: plan?.requestedExports(sourcePath),
96
171
  preserveUnreachableSideEffectImports: !isEntrypoint,
97
172
  });
98
173
  }
@@ -122,18 +197,21 @@ function getBuildContext(entrypoints, options) {
122
197
  const context = {
123
198
  configs: [],
124
199
  entrypointFiles,
125
- requestedExports: buildRequestedExports.get(entrypoints) ?? new Map(),
200
+ seeds: new Set(Object.values(entrypoints).map((entry) => toRealPath(path.resolve(options.absWorkingDir, entry)))),
201
+ loadedEntries: new Map(),
126
202
  };
127
- buildRequestedExports.set(entrypoints, context.requestedExports);
128
203
  buildContexts.set(entrypoints, context);
129
204
  return context;
130
205
  }
131
- function loadBuildClientGraphBoundaryModule(args, context) {
132
- const sourcePath = path.resolve(context.configs[0]?.absWorkingDir ?? process.cwd(), args.path);
133
- const rootConfigs = context.configs.filter((config) => config.entrypointFile === sourcePath);
134
- const reactEntrypointFiles = new Set(context.configs
206
+ function getReactEntrypointFiles(context) {
207
+ return new Set(context.configs
135
208
  .flatMap((config) => [config.entrypointFile, ...config.groupedEntrypointFiles])
136
209
  .filter((filePath) => filePath !== undefined));
210
+ }
211
+ function loadBuildClientGraphBoundaryModule(build, args, context) {
212
+ const sourcePath = path.resolve(context.configs[0]?.absWorkingDir ?? path.cwd(), args.path);
213
+ const rootConfigs = context.configs.filter((config) => config.entrypointFile === sourcePath);
214
+ const reactEntrypointFiles = getReactEntrypointFiles(context);
137
215
  if (context.entrypointFiles.has(sourcePath) && !reactEntrypointFiles.has(sourcePath)) {
138
216
  return undefined;
139
217
  }
@@ -150,28 +228,164 @@ function loadBuildClientGraphBoundaryModule(args, context) {
150
228
  groupedDeclaredModules,
151
229
  alwaysAllowSpecifiers: [...new Set(context.configs.flatMap((config) => config.alwaysAllowSpecifiers))],
152
230
  };
153
- return loadClientGraphBoundaryModule(args, options, context.requestedExports);
231
+ return loadClientGraphBoundaryModule(build, args, options, context, () => isTransformedByBuild(context));
232
+ }
233
+ /** Whether the shared build transforms a file: a source file that is not another Integration's entry. */
234
+ function isTransformedByBuild(context) {
235
+ const projectRoot = context.configs[0]?.projectRoot;
236
+ const entrypointFiles = new Set([...context.entrypointFiles].map(toRealPath));
237
+ const reactEntrypointFiles = new Set([...getReactEntrypointFiles(context)].map(toRealPath));
238
+ return (filePath) => isTransformedSource(filePath, projectRoot) &&
239
+ (!entrypointFiles.has(filePath) || reactEntrypointFiles.has(filePath));
240
+ }
241
+ function getForeignJsxReach(context, projectRoot, isForeignFile) {
242
+ if (!context.foreignJsxReach) {
243
+ const reactEntryFiles = new Set([...getReactEntrypointFiles(context)].map(toRealPath));
244
+ context.foreignJsxReach = scanForeignJsxReach({
245
+ projectRoot,
246
+ reactEntryFiles,
247
+ otherEntryFiles: [...context.entrypointFiles].map(toRealPath).filter((file) => !reactEntryFiles.has(file)),
248
+ isForeignFile,
249
+ });
250
+ }
251
+ return context.foreignJsxReach;
252
+ }
253
+ /**
254
+ * Scope for React's foreign-JSX override: a file another JSX Integration owns gets React's JSX runtime only when
255
+ * a React entry file reaches it.
256
+ *
257
+ * @remarks
258
+ * Reach comes from a static import scan of the build's entry files before any module loads, so it does not
259
+ * depend on load order. A foreign file only another Integration's entry reaches keeps its owner's runtime. One
260
+ * that both reach fails the build, since it has one URL and so one compiled form. A build without boundary
261
+ * plugins, and a file the scan does not find, keep the override, as in a React-only build.
262
+ */
263
+ export function createForeignJsxScope(options) {
264
+ const isForeignFile = (filePath) => options.findForeignOwner(filePath) !== undefined;
265
+ return (build) => (sourcePath) => {
266
+ const context = build.entrypoints ? buildContexts.get(build.entrypoints) : undefined;
267
+ const owner = options.findForeignOwner(sourcePath);
268
+ if (!context || context.configs.length === 0 || owner === undefined)
269
+ return true;
270
+ const reach = getForeignJsxReach(context, options.projectRoot, isForeignFile);
271
+ const filePath = toRealPath(sourcePath);
272
+ const otherEntry = reach.others.get(filePath);
273
+ if (otherEntry === undefined)
274
+ return true;
275
+ if (!reach.react.has(filePath))
276
+ return false;
277
+ throw new Error(`[ecopages] ${filePath} is a ${owner} file that both ${options.hostIntegrationName} browser entries and ` +
278
+ `another browser entry (${otherEntry}) import. ${options.hostIntegrationName} compiles it with its ` +
279
+ `own JSX runtime and ${owner} with its runtime, but one module has one compiled form. Import it ` +
280
+ `from one of them only.`);
281
+ };
154
282
  }
155
283
  /**
156
284
  * Instantiates the client graph boundary build plugin.
285
+ *
286
+ * @remarks
287
+ * In a build shared with other Integrations it decides by file, never by the entry that reached a module: it
288
+ * leaves an entry file no boundary instance declares to its own Integration and transforms every other source
289
+ * module the same way, since a module has one URL and so one compiled form. The instances of one build share
290
+ * their options through the build's `entrypoints`, and only the first registers a handler, so each module is
291
+ * read and analysed once whatever the number of React entries.
292
+ *
293
+ * A boundary without entry options, or in a build without `entrypoints`, works alone and starts its plan
294
+ * from the build's entries, or from its own entry files.
157
295
  */
158
296
  export function createClientGraphBoundaryPlugin(options) {
159
297
  const normalizedOptions = normalizeClientGraphBoundaryOptions(options);
160
- const requestedExports = getRequestedExports(options?.groupedEntrypointFiles);
161
298
  return {
162
299
  name: 'ecopages-client-graph-boundary',
163
300
  cacheKey: normalizedOptions.cacheKey,
164
- bundleGroupKey: 'react-client-graph-boundary',
165
301
  setup(build) {
166
302
  if (!build.entrypoints ||
167
303
  (!normalizedOptions.entrypointFile && normalizedOptions.groupedEntrypointFiles.size === 0)) {
168
304
  const entrypointFiles = new Set(Object.values(build.entrypoints ?? {}).map((entrypoint) => path.resolve(normalizedOptions.absWorkingDir, entrypoint)));
169
- build.onLoad({ filter: SOURCE_FILE_FILTER }, (args) => loadClientGraphBoundaryModule(args, normalizedOptions, requestedExports, entrypointFiles.has(path.resolve(normalizedOptions.absWorkingDir, args.path))));
305
+ const state = {
306
+ seeds: new Set([...(build.entrypoints ? entrypointFiles : normalizedOptions.groupedEntrypointFiles)].map(toRealPath)),
307
+ loadedEntries: new Map(),
308
+ };
309
+ const transforms = () => (filePath) => isTransformedSource(filePath, normalizedOptions.projectRoot);
310
+ build.onLoad(SOURCE_FILES, (loaded) => loadClientGraphBoundaryModule(build, stripVariant(loaded), normalizedOptions, state, transforms, entrypointFiles.has(path.resolve(normalizedOptions.absWorkingDir, stripVariant(loaded).path))));
170
311
  return;
171
312
  }
172
313
  const context = getBuildContext(build.entrypoints, normalizedOptions);
173
314
  context.configs.push(normalizedOptions);
174
- build.onLoad({ filter: SOURCE_FILE_FILTER }, (args) => loadBuildClientGraphBoundaryModule(args, context));
315
+ if (context.configs.length > 1)
316
+ return;
317
+ build.onLoad(SOURCE_FILES, (loaded) => loadBuildClientGraphBoundaryModule(build, stripVariant(loaded), context));
318
+ },
319
+ };
320
+ }
321
+ /** The files React entries reach and the files other entries reach, by a static scan of the build's entries. */
322
+ function getEntryReach(context, projectRoot) {
323
+ if (!context.entryReach) {
324
+ const reactEntryFiles = new Set([...getReactEntrypointFiles(context)].map(toRealPath));
325
+ const otherEntryFiles = [...context.entrypointFiles]
326
+ .map(toRealPath)
327
+ .filter((file) => !reactEntryFiles.has(file));
328
+ const reach = scanForeignJsxReach({
329
+ projectRoot,
330
+ reactEntryFiles,
331
+ otherEntryFiles,
332
+ isForeignFile: () => true,
333
+ });
334
+ context.entryReach = {
335
+ reactEntryFiles,
336
+ otherEntryFiles: new Set(otherEntryFiles),
337
+ react: reach.react,
338
+ others: new Set(reach.others.keys()),
339
+ };
340
+ }
341
+ return context.entryReach;
342
+ }
343
+ /**
344
+ * Instantiates the build plugin that gives React modules the boundary of every Eco Component another Integration
345
+ * owns, in the production bundle and the development transform alike.
346
+ *
347
+ * @remarks
348
+ * It rewrites the imports of foreign-owned Components in a module's source after it loads, so MDX, which
349
+ * compiles to such imports, is covered too. A module that imports none is left untouched.
350
+ *
351
+ * A module has one compiled form per id, so a module that another entry also reaches and that imports a foreign
352
+ * Component gets two: React's graph imports it under the id `<path>?eco-variant=react-boundary`, which this plugin
353
+ * rewrites, and the other graph keeps the plain id, which it leaves alone. The variant's own imports follow the
354
+ * same rule. In a build without entries to compare, `isSharedFile` says which modules another graph uses.
355
+ */
356
+ export function createForeignBoundaryPlugin(options) {
357
+ return {
358
+ name: 'ecopages-react-foreign-boundary',
359
+ environments: ['browser'],
360
+ setup(build) {
361
+ build.onLoad({ filter: /\?eco-variant=[\w-]+$/, exclude: /^\0|\/node_modules\// }, (loaded) => {
362
+ const filePath = stripVariant(loaded).path;
363
+ build.addWatchFile(filePath);
364
+ return {
365
+ contents: fileSystem.readFileSync(filePath),
366
+ loader: path.extname(filePath).slice(1),
367
+ };
368
+ });
369
+ build.transform({ filter: /\.(?:[cm]?[jt]sx?|mdx?)$/, exclude: /^\0|\/node_modules\// }, (code, id) => {
370
+ const filePath = toRealPath(id.replace(/[?#].*$/, ''));
371
+ if (options.isForeignFile(filePath))
372
+ return undefined;
373
+ const context = build.entrypoints ? buildContexts.get(build.entrypoints) : undefined;
374
+ const reach = context && context.configs.length > 0 ? getEntryReach(context, options.projectRoot) : undefined;
375
+ const inReactGraph = !reach ||
376
+ isReactBoundaryVariant(id) ||
377
+ reach.reactEntryFiles.has(filePath) ||
378
+ (reach.react.has(filePath) && !reach.others.has(filePath));
379
+ if (!inReactGraph)
380
+ return undefined;
381
+ return rewriteForeignImports(code, filePath, {
382
+ projectRoot: options.projectRoot,
383
+ isForeignFile: options.isForeignFile,
384
+ isSharedFile: reach
385
+ ? (file) => reach.others.has(file) && reach.react.has(file)
386
+ : options.isSharedFile,
387
+ });
388
+ });
175
389
  },
176
390
  };
177
391
  }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Source rewrite that gives a React module the boundary of every Eco Component another Integration owns.
3
+ */
4
+ /** The module variant a React graph imports of a module that another graph also uses and that imports a foreign Component. */
5
+ export declare const REACT_BOUNDARY_VARIANT = "react-boundary";
6
+ /** Whether the module id or specifier names the React boundary variant of its module. */
7
+ export declare function isReactBoundaryVariant(idOrSpecifier: string): boolean;
8
+ export type ForeignBoundaryRewriteOptions = {
9
+ projectRoot: string;
10
+ /** Whether `filePath` belongs to an Integration other than React. */
11
+ isForeignFile: (filePath: string) => boolean;
12
+ /**
13
+ * Whether another module graph also uses `filePath`, so React needs its own compiled form of it.
14
+ *
15
+ * @remarks
16
+ * A module has one compiled form per id. A shared module that imports a foreign Component would otherwise give
17
+ * the other graph a React boundary, so React imports it under a variant id and the other graph keeps the plain one.
18
+ */
19
+ isSharedFile?: (filePath: string) => boolean;
20
+ };
21
+ /**
22
+ * Rewrites the static imports of foreign-owned Components in `code`, barrels that re-export them included, or
23
+ * returns `undefined`.
24
+ *
25
+ * @remarks
26
+ * A module without such an import is not touched: the caller gets `undefined`, so a React-only module compiles
27
+ * to the same output as before and ships no boundary code. A module already rewritten is returned as `undefined`
28
+ * too, since a build can hold more than one instance of the plugin. A namespace import is wrapped in a proxy.
29
+ * Dynamic `import()` of a foreign module is left as it is.
30
+ */
31
+ export declare function rewriteForeignImports(code: string, filePath: string, options: ForeignBoundaryRewriteOptions): string | undefined;