@ecopages/react 0.6.1 → 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
@@ -6,99 +6,65 @@
6
6
  *
7
7
  * @module
8
8
  */
9
- import { createClientGraphBoundaryPlugin } from '../client-graph/boundary-plugin.js';
10
- import { getReactClientGraphAllowSpecifiers, getReactRuntimeExternalSpecifiers } from './runtime-alias-map.js';
11
- import { createBrowserRuntimePlugin } from '@ecopages/core/build';
12
- import { getHostScopedJsxOwnershipPlugins } from '@ecopages/core/build';
13
- import { RuntimeBundleService } from './runtime-bundle.js';
14
- import { isReactProductionRuntime } from './runtime-mode.js';
9
+ import { createClientGraphBoundaryPlugin, createForeignBoundaryPlugin, createForeignJsxScope, } from '../client-graph/boundary-plugin.js';
10
+ import { findIntegrationForFile, findJsxExtensionOwner, getHostScopedJsxOwnershipPlugins, isProductionRuntime, } from '@ecopages/core/build';
11
+ import { getReactBrowserPackages } from './bootstrap-package-paths.js';
12
+ /**
13
+ * Packages whose imports the client-graph boundary keeps whatever a module's declared `modules` say.
14
+ *
15
+ * @remarks
16
+ * Hydration needs core and every package React's browser entries import, the configured router included.
17
+ */
18
+ export function getReactClientGraphAllowSpecifiers(routerAdapter) {
19
+ return ['@ecopages/core', ...getReactBrowserPackages(routerAdapter)];
20
+ }
15
21
  /**
16
22
  * Manages bundle configuration and plugin creation for React page/component builds.
17
23
  */
18
24
  export class BundleService {
19
- runtimeBundleService;
20
25
  config;
21
26
  foreignJsxOverridePlugin;
22
- runtimeRewritePlugin;
23
- pageLayoutNormalizationVendorPromise;
24
27
  mdxLoaderPlugin;
25
28
  constructor(config) {
26
29
  this.config = config;
27
- this.runtimeBundleService = new RuntimeBundleService({
28
- rootDir: config.rootDir,
29
- routerAdapter: config.routerAdapter,
30
- runtimeModules: config.runtimeModules,
31
- });
32
- [this.foreignJsxOverridePlugin] = getHostScopedJsxOwnershipPlugins(config.appConfig, config.hostIntegrationName, { name: 'react-renderer-foreign-jsx-override' });
33
- this.runtimeRewritePlugin = createBrowserRuntimePlugin({
34
- name: 'react-renderer-runtime-import-rewrite',
35
- manifest: this.runtimeBundleService.getRuntimeManifest(),
30
+ [this.foreignJsxOverridePlugin] = getHostScopedJsxOwnershipPlugins(config.appConfig, config.hostIntegrationName, {
31
+ name: 'react-renderer-foreign-jsx-override',
32
+ scope: createForeignJsxScope({
33
+ projectRoot: config.appConfig?.absolutePaths?.projectDir ?? config.rootDir,
34
+ hostIntegrationName: config.hostIntegrationName,
35
+ findForeignOwner: (filePath) => {
36
+ const owner = findJsxExtensionOwner(config.appConfig, filePath);
37
+ return owner === config.hostIntegrationName ? undefined : owner;
38
+ },
39
+ }),
36
40
  });
37
41
  }
38
- /**
39
- * Returns resolved runtime import paths for the React runtime.
40
- */
41
- getRuntimeImports() {
42
- return this.runtimeBundleService.getRuntimeImports();
43
- }
44
- /**
45
- * Processes the MDX-only page-layout-normalization vendor once per BundleService instance.
46
- *
47
- * @remarks
48
- * Concurrent callers share the same in-flight promise. Asset processing itself caches
49
- * by dependency key, so repeats after success remain cheap.
50
- */
51
- async ensurePageLayoutNormalizationVendorProcessed(assetProcessingService) {
52
- if (!this.pageLayoutNormalizationVendorPromise) {
53
- this.pageLayoutNormalizationVendorPromise = assetProcessingService
54
- .processDependencies(this.runtimeBundleService.getPageLayoutNormalizationDependencies(), this.config.assetProcessingIntegration)
55
- .then(() => undefined)
56
- .catch((error) => {
57
- this.pageLayoutNormalizationVendorPromise = undefined;
58
- throw error;
59
- });
60
- }
61
- await this.pageLayoutNormalizationVendorPromise;
62
- }
63
42
  /**
64
43
  * Creates bundle options for a page or component entry.
65
44
  *
66
45
  * @remarks
67
- * React derives runtime specifier mappings from the core browser runtime manifest
68
- * so ESM imports resolve to concrete runtime asset URLs during module loading.
46
+ * React, React DOM and the router are ordinary packages of the build, so the bundler resolves and shares them
47
+ * like any other import.
69
48
  *
70
49
  * @param componentName - Generated unique component name for output naming
71
- * @param isMdx - Whether the source file is an MDX file
72
50
  * @param declaredModules - Explicitly declared browser module specifiers
73
51
  * @returns Bundle options object for the build adapter
74
52
  */
75
- async createBundleOptions(componentName, isMdx, declaredModules, bundleOptions = {}, entrypointFile, groupedEntrypointFiles, groupedDeclaredModules) {
76
- const runtimeImports = this.getRuntimeImports();
77
- const options = {
53
+ async createBundleOptions(componentName, declaredModules, entrypointFile, groupedEntrypointFiles, groupedDeclaredModules) {
54
+ return {
78
55
  mainFields: ['module', 'browser', 'main'],
79
56
  naming: `${componentName}.[ext]`,
80
- ...(isReactProductionRuntime() && {
57
+ ...(isProductionRuntime() && {
81
58
  minify: true,
82
59
  treeshaking: true,
83
60
  }),
84
- ...(bundleOptions.splitting === undefined ? {} : { splitting: bundleOptions.splitting }),
61
+ plugins: this.createClientBuildPlugins({
62
+ declaredModules,
63
+ entrypointFile,
64
+ groupedEntrypointFiles,
65
+ groupedDeclaredModules,
66
+ }),
85
67
  };
86
- if (!bundleOptions.includeRuntime) {
87
- const reactRuntimeSpecifiers = new Set(getReactRuntimeExternalSpecifiers());
88
- options.external = [
89
- ...Object.values(runtimeImports).filter((specifier) => Boolean(specifier) &&
90
- !reactRuntimeSpecifiers.has(specifier)),
91
- ];
92
- }
93
- options.plugins = this.createClientBuildPlugins({
94
- declaredModules,
95
- entrypointFile,
96
- groupedEntrypointFiles,
97
- groupedDeclaredModules,
98
- includeRuntime: bundleOptions.includeRuntime,
99
- isMdx,
100
- });
101
- return options;
102
68
  }
103
69
  createClientBuildPlugins(options) {
104
70
  const graphBoundaryPlugin = createClientGraphBoundaryPlugin({
@@ -108,16 +74,19 @@ export class BundleService {
108
74
  groupedEntrypointFiles: options.groupedEntrypointFiles,
109
75
  groupedDeclaredModules: options.groupedDeclaredModules,
110
76
  declaredModules: options.declaredModules,
111
- alwaysAllowSpecifiers: getReactClientGraphAllowSpecifiers(this.runtimeBundleService.getConfiguredRuntimeModuleSpecifiers(), this.config.routerAdapter),
77
+ alwaysAllowSpecifiers: getReactClientGraphAllowSpecifiers(this.config.routerAdapter),
112
78
  });
113
- const runtimePlugins = options.includeRuntime
114
- ? []
115
- : [this.runtimeRewritePlugin].filter((plugin) => plugin !== null);
116
- const mdxPlugin = options.isMdx ? this.getMdxLoaderPlugin() : undefined;
79
+ const mdxPlugin = this.getMdxLoaderPlugin();
117
80
  return [
118
81
  ...(this.foreignJsxOverridePlugin ? [this.foreignJsxOverridePlugin] : []),
119
82
  graphBoundaryPlugin,
120
- ...runtimePlugins,
83
+ createForeignBoundaryPlugin({
84
+ projectRoot: this.config.appConfig?.absolutePaths?.projectDir ?? this.config.rootDir,
85
+ isForeignFile: (filePath) => {
86
+ const owner = findIntegrationForFile(this.config.appConfig?.integrations ?? [], filePath);
87
+ return owner !== undefined && owner.name !== this.config.hostIntegrationName;
88
+ },
89
+ }),
121
90
  ...(mdxPlugin ? [mdxPlugin] : []),
122
91
  ];
123
92
  }
@@ -1,10 +1,14 @@
1
1
  /**
2
- * Strips server-only `eco.page(...)` option keys from browser-bound modules.
2
+ * Finds the server-only `eco.page(...)` options of browser-bound modules.
3
3
  */
4
+ import type { SourceEdit } from './ast-transform-import-edits.js';
5
+ export type ServerOnlyPageCode = {
6
+ /** Edits that remove the server-only code. */
7
+ edits: SourceEdit[];
8
+ /** Nodes whose subtrees the edits remove; references inside them do not reach the browser. */
9
+ strippedNodes: Set<unknown>;
10
+ };
4
11
  /**
5
- * Removes server-only `eco.page(...)` options from browser-bound modules.
12
+ * Collects the server-only `eco.page(...)` options of a browser-bound module and the edits that remove them.
6
13
  */
7
- export declare function stripServerOnlyEcoPageOptions(source: string, program: any): {
8
- transformed: string;
9
- modified: boolean;
10
- };
14
+ export declare function collectServerOnlyPageCode(program: any): ServerOnlyPageCode;
@@ -1,8 +1,7 @@
1
1
  /**
2
- * Strips server-only `eco.page(...)` option keys from browser-bound modules.
2
+ * Finds the server-only `eco.page(...)` options of browser-bound modules.
3
3
  */
4
4
  import { walkAstNodes } from './ast-walk.js';
5
- import { applySourceEdits } from './ast-transform-import-edits.js';
6
5
  const SERVER_ONLY_ECO_PAGE_OPTION_KEYS = new Set([
7
6
  'cache',
8
7
  'middleware',
@@ -21,31 +20,6 @@ function isEcoPageOptionsCall(node) {
21
20
  node.callee.property.name === 'page' &&
22
21
  node.arguments?.[0]?.type === 'ObjectExpression');
23
22
  }
24
- function collectEcoPageOptionStripEdit(node, source, edits) {
25
- if (!isEcoPageOptionsCall(node))
26
- return;
27
- const objectExpression = node.arguments[0];
28
- const keptProperties = [];
29
- let removedProperty = false;
30
- for (const property of objectExpression.properties ?? []) {
31
- if (property?.type === 'Property') {
32
- const keyName = getObjectPropertyKeyName(property.key);
33
- if (keyName && SERVER_ONLY_ECO_PAGE_OPTION_KEYS.has(keyName)) {
34
- removedProperty = true;
35
- continue;
36
- }
37
- }
38
- keptProperties.push(source.slice(property.start, property.end));
39
- }
40
- if (!removedProperty)
41
- return;
42
- const replacement = keptProperties.length > 0 ? `{ ${keptProperties.join(', ')} }` : '{}';
43
- edits.push({
44
- start: objectExpression.start,
45
- end: objectExpression.end,
46
- replacement,
47
- });
48
- }
49
23
  function getObjectPropertyKeyName(node) {
50
24
  if (!node)
51
25
  return undefined;
@@ -56,16 +30,63 @@ function getObjectPropertyKeyName(node) {
56
30
  }
57
31
  return undefined;
58
32
  }
33
+ function isServerOnlyOption(property) {
34
+ if (property?.type !== 'Property' || property.computed)
35
+ return false;
36
+ const keyName = getObjectPropertyKeyName(property.key);
37
+ return keyName !== undefined && SERVER_ONLY_ECO_PAGE_OPTION_KEYS.has(keyName);
38
+ }
59
39
  /**
60
- * Removes server-only `eco.page(...)` options from browser-bound modules.
40
+ * Returns the range that removes one property and its separating comma.
41
+ *
42
+ * @remarks
43
+ * A property followed by another one is removed up to the next property's start. The last
44
+ * property is removed from the end of the one before it (or from its own start) up to the
45
+ * closing brace, so a trailing comma goes with it.
61
46
  */
62
- export function stripServerOnlyEcoPageOptions(source, program) {
63
- const edits = [];
47
+ function getPropertyRemovalRange(objectExpression, index) {
48
+ const properties = objectExpression.properties;
49
+ const property = properties[index];
50
+ const next = properties[index + 1];
51
+ if (next)
52
+ return { start: property.start, end: next.start };
53
+ const previous = properties[index - 1];
54
+ return { start: previous ? previous.end : property.start, end: objectExpression.end - 1 };
55
+ }
56
+ function mergeRanges(ranges) {
57
+ const merged = [];
58
+ for (const range of [...ranges].sort((a, b) => a.start - b.start)) {
59
+ const last = merged.at(-1);
60
+ if (last && range.start <= last.end) {
61
+ last.end = Math.max(last.end, range.end);
62
+ }
63
+ else {
64
+ merged.push({ ...range });
65
+ }
66
+ }
67
+ return merged;
68
+ }
69
+ function collectPageOptionEdits(node, code) {
70
+ const objectExpression = node.arguments[0];
71
+ const ranges = [];
72
+ objectExpression.properties.forEach((property, index) => {
73
+ if (!isServerOnlyOption(property))
74
+ return;
75
+ code.strippedNodes.add(property);
76
+ ranges.push(getPropertyRemovalRange(objectExpression, index));
77
+ });
78
+ for (const range of mergeRanges(ranges))
79
+ code.edits.push({ ...range, replacement: '' });
80
+ }
81
+ /**
82
+ * Collects the server-only `eco.page(...)` options of a browser-bound module and the edits that remove them.
83
+ */
84
+ export function collectServerOnlyPageCode(program) {
85
+ const code = { edits: [], strippedNodes: new Set() };
64
86
  walkAstNodes(program, (node) => {
65
- collectEcoPageOptionStripEdit(node, source, edits);
87
+ if (!isEcoPageOptionsCall(node))
88
+ return;
89
+ collectPageOptionEdits(node, code);
66
90
  });
67
- if (edits.length === 0) {
68
- return { transformed: source, modified: false };
69
- }
70
- return { transformed: applySourceEdits(source, edits), modified: true };
91
+ return code;
71
92
  }
@@ -7,7 +7,15 @@ export type SourceEdit = {
7
7
  replacement: string;
8
8
  };
9
9
  /**
10
- * Applies range replacements from last-to-first so earlier offsets stay valid.
10
+ * Applies range replacements; an edit inside the range of another edit is dropped.
11
+ *
12
+ * @remarks
13
+ * Edits come from independent passes, so an import pruning edit can sit inside a declaration
14
+ * another pass removes. Ranges that overlap without one containing the other are a bug.
11
15
  */
12
- export declare function applySourceEdits(source: string, edits: SourceEdit[]): string;
16
+ export declare function applySourceEdits(source: string, edits: readonly SourceEdit[]): string;
17
+ /**
18
+ * Returns whether {@link buildImportDeclarationRewrite} keeps an import specifier under `rules`.
19
+ */
20
+ export declare function isImportSpecifierKept(spec: any, rules: Set<string>): boolean;
13
21
  export declare function buildImportDeclarationRewrite(node: any, specifier: string, rules: Set<string>): SourceEdit | undefined;
@@ -2,13 +2,28 @@
2
2
  * Builds source edits for import declaration specifier pruning.
3
3
  */
4
4
  /**
5
- * Applies range replacements from last-to-first so earlier offsets stay valid.
5
+ * Applies range replacements; an edit inside the range of another edit is dropped.
6
+ *
7
+ * @remarks
8
+ * Edits come from independent passes, so an import pruning edit can sit inside a declaration
9
+ * another pass removes. Ranges that overlap without one containing the other are a bug.
6
10
  */
7
11
  export function applySourceEdits(source, edits) {
8
- edits.sort((a, b) => b.start - a.start);
12
+ const sorted = [...edits].sort((a, b) => a.start - b.start || b.end - a.end);
13
+ const outermost = [];
14
+ for (const edit of sorted) {
15
+ const last = outermost.at(-1);
16
+ if (last && edit.start < last.end) {
17
+ if (edit.end > last.end) {
18
+ throw new Error(`Overlapping source edits at ${last.start}-${last.end} and ${edit.start}-${edit.end}`);
19
+ }
20
+ continue;
21
+ }
22
+ outermost.push(edit);
23
+ }
9
24
  let transformed = source;
10
- for (const edit of edits) {
11
- transformed = transformed.slice(0, edit.start) + edit.replacement + transformed.slice(edit.end);
25
+ for (const edit of outermost.reverse()) {
26
+ transformed = `${transformed.slice(0, edit.start)}${edit.replacement}${transformed.slice(edit.end)}`;
12
27
  }
13
28
  return transformed;
14
29
  }
@@ -27,10 +42,25 @@ function collectKeptImportSpecifiers(node, rules) {
27
42
  }
28
43
  return kept;
29
44
  }
45
+ function getImportedName(spec) {
46
+ return spec.imported.type === 'Identifier' ? spec.imported.name : spec.imported.value;
47
+ }
48
+ /**
49
+ * Returns whether {@link buildImportDeclarationRewrite} keeps an import specifier under `rules`.
50
+ */
51
+ export function isImportSpecifierKept(spec, rules) {
52
+ if (spec.type === 'ImportSpecifier')
53
+ return rules.has(getImportedName(spec));
54
+ if (spec.type === 'ImportDefaultSpecifier')
55
+ return rules.has('default');
56
+ if (spec.type === 'ImportNamespaceSpecifier')
57
+ return rules.has('*');
58
+ return false;
59
+ }
30
60
  function appendKeptNamedSpecifier(spec, rules, kept) {
31
- const importedName = spec.imported.type === 'Identifier' ? spec.imported.name : spec.imported.value;
32
- if (!rules.has(importedName))
61
+ if (!isImportSpecifierKept(spec, rules))
33
62
  return;
63
+ const importedName = getImportedName(spec);
34
64
  kept.keptSpecifierCount += 1;
35
65
  const localName = spec.local?.name;
36
66
  kept.namedImportNodes.push(localName && localName !== importedName ? `${importedName} as ${localName}` : importedName);
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Removes the top-level code the browser module does not need once server-only code is gone,
3
+ * and rejects a module whose browser code would still use a binding whose import is stripped.
4
+ */
5
+ import type { SourceEdit } from './ast-transform-import-edits.js';
6
+ import type { ExplicitlyRequestedExports } from './reachability-export-names.js';
7
+ export type StrippedImportCleanupInput = {
8
+ program: any;
9
+ source: string;
10
+ filename: string;
11
+ /** Subtrees the boundary removes; references inside them do not reach the browser. */
12
+ strippedNodes: ReadonlySet<unknown>;
13
+ /** Local names of the imported bindings the boundary removes, mapped to their import specifier. */
14
+ strippedBindings: ReadonlyMap<string, string>;
15
+ /** Import declarations the boundary already edits. */
16
+ editedImports: ReadonlySet<unknown>;
17
+ /** Exports that browser importers of this module are known to use. */
18
+ requestedExports?: ExplicitlyRequestedExports;
19
+ };
20
+ /**
21
+ * Plans the removal of the top-level code the browser module does not need once server-only code is gone.
22
+ *
23
+ * @remarks
24
+ * The browser module needs its top-level statements other than declarations (the default export
25
+ * included), the declarations that create a client root, and the named exports browser importers
26
+ * are known to request. A named export nothing requests is not needed: rolldown would tree-shake
27
+ * it, and the requests are unknown for imports through a path alias. Declarations those roots reach are needed too.
28
+ *
29
+ * A declaration that is not needed is removed when only removed code used it, or when it uses a
30
+ * stripped binding or another removed declaration; the check repeats until nothing else changes.
31
+ * Removal ignores side effects of the declaration's initializer, so code that must run in the
32
+ * browser belongs in a statement of its own. An exported name keeps its binding, set to
33
+ * `undefined`. An import only removed code used is removed too, so its module stays out of the
34
+ * browser graph. A needed statement, or an `export { ... }`, that still uses a stripped binding
35
+ * throws, naming the binding, its import specifier and the `line:column` of the use.
36
+ */
37
+ export declare function planStrippedImportCleanup(input: StrippedImportCleanupInput): SourceEdit[];
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Removes the top-level code the browser module does not need once server-only code is gone,
3
+ * and rejects a module whose browser code would still use a binding whose import is stripped.
4
+ */
5
+ import { checkPotentialClientRoot } from './reachability-client-roots.js';
6
+ import { getExportedName, isExplicitlyRequestedExport } from './reachability-export-names.js';
7
+ import { collectLexicalDeclarations, walkScopedReferences } from './scope-walk.js';
8
+ const DECLARATION_TYPES = new Set(['VariableDeclaration', 'FunctionDeclaration', 'ClassDeclaration']);
9
+ function isBrowserExport(name, input) {
10
+ return isExplicitlyRequestedExport(name, input.requestedExports);
11
+ }
12
+ function containsClientRoot(declaration) {
13
+ if (declaration.type !== 'VariableDeclaration')
14
+ return false;
15
+ const roots = [];
16
+ for (const declarator of declaration.declarations)
17
+ checkPotentialClientRoot(declarator.init, roots);
18
+ return roots.length > 0;
19
+ }
20
+ function classifyStatement(statement, names, input) {
21
+ if (statement.type === 'ExportNamedDeclaration' && !statement.source) {
22
+ const declaration = statement.declaration;
23
+ if (!declaration) {
24
+ const rootReferences = (statement.specifiers ?? [])
25
+ .filter((specifier) => isBrowserExport(getExportedName(specifier) ?? '', input))
26
+ .map((specifier) => specifier.local?.name);
27
+ return { kind: 'export-specifiers', isRoot: false, rootReferences };
28
+ }
29
+ if (DECLARATION_TYPES.has(declaration.type) && !declaration.declare) {
30
+ const isRoot = containsClientRoot(declaration) || [...names].some((name) => isBrowserExport(name, input));
31
+ return { kind: 'exported-declaration', isRoot, rootReferences: [] };
32
+ }
33
+ }
34
+ if (DECLARATION_TYPES.has(statement.type) && !statement.declare) {
35
+ return { kind: 'declaration', isRoot: false, rootReferences: [] };
36
+ }
37
+ return { kind: 'statement', isRoot: true, rootReferences: [] };
38
+ }
39
+ function createUnit(statement, input) {
40
+ const names = new Set();
41
+ collectLexicalDeclarations(statement, names);
42
+ const keptReferences = new Map();
43
+ const allReferences = new Set();
44
+ walkScopedReferences(statement, { onReference: (name) => allReferences.add(name) });
45
+ walkScopedReferences(statement, {
46
+ onReference: (name, node) => {
47
+ if (!keptReferences.has(name))
48
+ keptReferences.set(name, node);
49
+ },
50
+ onNode: (node) => input.strippedNodes.has(node),
51
+ });
52
+ return { statement, names, keptReferences, allReferences, ...classifyStatement(statement, names, input) };
53
+ }
54
+ /**
55
+ * Marks the units the browser module needs: the roots and every unit they reference, transitively.
56
+ */
57
+ function collectNeededUnits(units, referencesOf) {
58
+ const unitByName = new Map();
59
+ for (const unit of units)
60
+ for (const name of unit.names)
61
+ unitByName.set(name, unit);
62
+ const needed = new Set();
63
+ const queue = [];
64
+ const need = (unit) => {
65
+ if (unit && !needed.has(unit)) {
66
+ needed.add(unit);
67
+ queue.push(unit);
68
+ }
69
+ };
70
+ for (const unit of units) {
71
+ if (unit.isRoot)
72
+ need(unit);
73
+ for (const name of unit.rootReferences)
74
+ need(unitByName.get(name));
75
+ }
76
+ while (queue.length > 0) {
77
+ for (const name of referencesOf(queue.pop()))
78
+ need(unitByName.get(name));
79
+ }
80
+ return needed;
81
+ }
82
+ /**
83
+ * Collects the declarations to remove: those only removed code needed, and every declaration the
84
+ * browser module does not need that uses a stripped binding or a removed declaration.
85
+ */
86
+ function collectRemovedUnits(units, input) {
87
+ const neededBefore = collectNeededUnits(units, (unit) => unit.allReferences);
88
+ const neededAfter = collectNeededUnits(units, (unit) => unit.keptReferences.keys());
89
+ const candidates = units.filter((unit) => (unit.kind === 'declaration' || unit.kind === 'exported-declaration') && !neededAfter.has(unit));
90
+ const removed = new Set(candidates.filter((unit) => unit.kind === 'declaration' && neededBefore.has(unit)));
91
+ const removedNames = new Set([...removed].flatMap((unit) => [...unit.names]));
92
+ let changed = true;
93
+ while (changed) {
94
+ changed = false;
95
+ for (const unit of candidates) {
96
+ if (removed.has(unit))
97
+ continue;
98
+ const references = [...unit.keptReferences.keys()];
99
+ if (references.some((name) => input.strippedBindings.has(name) || removedNames.has(name))) {
100
+ removed.add(unit);
101
+ for (const name of unit.names)
102
+ removedNames.add(name);
103
+ changed = true;
104
+ }
105
+ }
106
+ }
107
+ return removed;
108
+ }
109
+ /**
110
+ * Removes a declaration, or replaces it with `undefined` bindings when the module still exports its names.
111
+ */
112
+ function createRemovalEdit(unit, exportedLocals) {
113
+ const statement = unit.statement;
114
+ const keepsNames = unit.kind === 'exported-declaration' || [...unit.names].some((name) => exportedLocals.has(name));
115
+ if (!keepsNames)
116
+ return { start: statement.start, end: statement.end, replacement: '' };
117
+ const target = unit.kind === 'exported-declaration' ? statement.declaration : statement;
118
+ const bindings = [...unit.names].map((name) => `${name} = undefined`).join(', ');
119
+ return { start: target.start, end: target.end, replacement: `const ${bindings};` };
120
+ }
121
+ function getValueImportNames(statement) {
122
+ if (statement.importKind === 'type')
123
+ return [];
124
+ return (statement.specifiers ?? [])
125
+ .filter((specifier) => specifier.importKind !== 'type')
126
+ .map((specifier) => specifier.local.name);
127
+ }
128
+ function toLineColumn(source, offset) {
129
+ const lines = source.slice(0, offset).split('\n');
130
+ return `${lines.length}:${lines.at(-1).length + 1}`;
131
+ }
132
+ function assertNoStrippedBindingReferences(browserUnits, input) {
133
+ let first;
134
+ for (const unit of browserUnits) {
135
+ for (const [name, node] of unit.keptReferences) {
136
+ if (input.strippedBindings.has(name) && (!first || node.start < first.node.start))
137
+ first = { name, node };
138
+ }
139
+ }
140
+ if (!first)
141
+ return;
142
+ const specifier = input.strippedBindings.get(first.name);
143
+ throw new Error(`[Ecopages Client Graph] '${first.name}' (imported from '${specifier}') is used at ${input.filename}:${toLineColumn(input.source, first.node.start)}, but that import is server-only and the browser build removes it. Use it only in server-only Page options such as middleware or staticProps, or in code the browser module does not reach.`);
144
+ }
145
+ /**
146
+ * Plans the removal of the top-level code the browser module does not need once server-only code is gone.
147
+ *
148
+ * @remarks
149
+ * The browser module needs its top-level statements other than declarations (the default export
150
+ * included), the declarations that create a client root, and the named exports browser importers
151
+ * are known to request. A named export nothing requests is not needed: rolldown would tree-shake
152
+ * it, and the requests are unknown for imports through a path alias. Declarations those roots reach are needed too.
153
+ *
154
+ * A declaration that is not needed is removed when only removed code used it, or when it uses a
155
+ * stripped binding or another removed declaration; the check repeats until nothing else changes.
156
+ * Removal ignores side effects of the declaration's initializer, so code that must run in the
157
+ * browser belongs in a statement of its own. An exported name keeps its binding, set to
158
+ * `undefined`. An import only removed code used is removed too, so its module stays out of the
159
+ * browser graph. A needed statement, or an `export { ... }`, that still uses a stripped binding
160
+ * throws, naming the binding, its import specifier and the `line:column` of the use.
161
+ */
162
+ export function planStrippedImportCleanup(input) {
163
+ const imports = [];
164
+ const units = [];
165
+ for (const statement of input.program.body) {
166
+ if (statement.type === 'ImportDeclaration') {
167
+ imports.push(statement);
168
+ }
169
+ else {
170
+ units.push(createUnit(statement, input));
171
+ }
172
+ }
173
+ const removed = collectRemovedUnits(units, input);
174
+ const surviving = units.filter((unit) => !removed.has(unit));
175
+ const exportSpecifiers = surviving.filter((unit) => unit.kind === 'export-specifiers');
176
+ const browserUnits = collectNeededUnits(surviving, (unit) => unit.keptReferences.keys());
177
+ assertNoStrippedBindingReferences([...browserUnits, ...exportSpecifiers], input);
178
+ const exportedLocals = new Set(exportSpecifiers.flatMap((unit) => [...unit.allReferences]));
179
+ const edits = [...removed].map((unit) => createRemovalEdit(unit, exportedLocals));
180
+ const usedBefore = new Set(units.flatMap((unit) => [...unit.allReferences]));
181
+ const usedAfter = new Set(surviving.flatMap((unit) => [...unit.keptReferences.keys()]));
182
+ for (const statement of imports) {
183
+ if (input.editedImports.has(statement))
184
+ continue;
185
+ const names = getValueImportNames(statement);
186
+ if (names.some((name) => usedBefore.has(name)) && !names.some((name) => usedAfter.has(name))) {
187
+ edits.push({ start: statement.start, end: statement.end, replacement: '' });
188
+ }
189
+ }
190
+ return edits;
191
+ }
@@ -13,6 +13,10 @@ export type WalkImportsContext = {
13
13
  edits: SourceEdit[];
14
14
  allowedMap: Map<string, Set<string> | '*'>;
15
15
  preserveUnreachableSideEffectImports: boolean;
16
+ /** Receives the local name of each removed value binding, mapped to its import specifier. */
17
+ strippedBindings: Map<string, string>;
18
+ /** Receives each import declaration that gets an edit. */
19
+ editedImports: Set<unknown>;
16
20
  };
17
21
  /**
18
22
  * Walks a parsed program and collects import-pruning edits.
@@ -3,7 +3,7 @@
3
3
  */
4
4
  import { isServerOnlySpecifier, toModuleBaseSpecifier } from './specifier-classification.js';
5
5
  import { walkAstNodes } from './ast-walk.js';
6
- import { buildImportDeclarationRewrite } from './ast-transform-import-edits.js';
6
+ import { buildImportDeclarationRewrite, isImportSpecifierKept } from './ast-transform-import-edits.js';
7
7
  function processSpecifier(specifier, allowedMap) {
8
8
  const explicitRules = allowedMap.get(toModuleBaseSpecifier(specifier));
9
9
  if (isServerOnlySpecifier(specifier) && !explicitRules) {
@@ -18,18 +18,31 @@ function pruneForbiddenSpecifier(node, ctx, specifier, message, replacement) {
18
18
  }
19
19
  ctx.edits.push({ start: node.start, end: node.end, replacement });
20
20
  }
21
+ function recordStrippedBindings(node, specifier, ctx, isKept = () => false) {
22
+ if (node.importKind === 'type')
23
+ return;
24
+ for (const specifierNode of node.specifiers ?? []) {
25
+ if (specifierNode.importKind !== 'type' && !isKept(specifierNode)) {
26
+ ctx.strippedBindings.set(specifierNode.local.name, specifier);
27
+ }
28
+ }
29
+ }
21
30
  function handleImportDeclaration(node, ctx) {
22
31
  const specifier = node.source.value;
23
32
  const reachableRules = ctx.reachability.reachableImports.get(specifier);
24
33
  const { allowed, rules } = processSpecifier(specifier, ctx.allowedMap);
25
34
  if (!allowed) {
26
35
  pruneForbiddenSpecifier(node, ctx, specifier, `Forbidden client import '${specifier}'`, '');
36
+ recordStrippedBindings(node, specifier, ctx);
37
+ ctx.editedImports.add(node);
27
38
  return true;
28
39
  }
29
40
  if (rules instanceof Set && node.specifiers && node.specifiers.length > 0) {
30
41
  const rewrite = buildImportDeclarationRewrite(node, specifier, rules);
31
42
  if (rewrite) {
32
43
  ctx.edits.push(rewrite);
44
+ recordStrippedBindings(node, specifier, ctx, (specifierNode) => isImportSpecifierKept(specifierNode, rules));
45
+ ctx.editedImports.add(node);
33
46
  }
34
47
  return true;
35
48
  }
@@ -37,6 +50,7 @@ function handleImportDeclaration(node, ctx) {
37
50
  !reachableRules &&
38
51
  (!node.specifiers || node.specifiers.length === 0)) {
39
52
  ctx.edits.push({ start: node.start, end: node.end, replacement: '' });
53
+ ctx.editedImports.add(node);
40
54
  }
41
55
  return true;
42
56
  }