@ecopages/react 0.2.0-alpha.4 → 0.2.0-alpha.40

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 (70) hide show
  1. package/README.md +161 -18
  2. package/package.json +16 -12
  3. package/src/eco-embed.d.ts +11 -0
  4. package/src/eco-embed.js +11 -0
  5. package/src/react-hmr-strategy.d.ts +42 -32
  6. package/src/react-hmr-strategy.js +103 -124
  7. package/src/react-renderer.d.ts +169 -42
  8. package/src/react-renderer.js +484 -164
  9. package/src/react.constants.d.ts +1 -0
  10. package/src/react.constants.js +4 -0
  11. package/src/react.plugin.d.ts +38 -111
  12. package/src/react.plugin.js +132 -61
  13. package/src/react.types.d.ts +88 -0
  14. package/src/react.types.js +0 -0
  15. package/src/router-adapter.d.ts +7 -14
  16. package/src/services/react-bundle.service.d.ts +15 -26
  17. package/src/services/react-bundle.service.js +45 -93
  18. package/src/services/react-hmr-page-metadata-cache.d.ts +9 -0
  19. package/src/services/react-hmr-page-metadata-cache.js +18 -2
  20. package/src/services/react-hydration-asset.service.d.ts +26 -19
  21. package/src/services/react-hydration-asset.service.js +72 -66
  22. package/src/services/react-mdx-config-dependency.service.d.ts +36 -0
  23. package/src/services/react-mdx-config-dependency.service.js +122 -0
  24. package/src/services/react-page-module.service.d.ts +10 -2
  25. package/src/services/react-page-module.service.js +47 -39
  26. package/src/services/react-page-payload.service.d.ts +46 -0
  27. package/src/services/react-page-payload.service.js +67 -0
  28. package/src/services/react-runtime-bundle.service.d.ts +15 -13
  29. package/src/services/react-runtime-bundle.service.js +103 -180
  30. package/src/utils/client-graph-boundary-plugin.d.ts +1 -1
  31. package/src/utils/client-graph-boundary-plugin.js +149 -11
  32. package/src/utils/component-config-traversal.d.ts +36 -0
  33. package/src/utils/component-config-traversal.js +54 -0
  34. package/src/utils/declared-modules.d.ts +1 -1
  35. package/src/utils/declared-modules.js +7 -16
  36. package/src/utils/dynamic.test.browser.d.ts +1 -0
  37. package/src/utils/dynamic.test.browser.js +33 -0
  38. package/src/utils/hydration-scripts.d.ts +25 -6
  39. package/src/utils/hydration-scripts.js +150 -44
  40. package/src/utils/hydration-scripts.test.browser.d.ts +1 -0
  41. package/src/utils/hydration-scripts.test.browser.js +198 -0
  42. package/src/utils/reachability-analyzer.d.ts +12 -1
  43. package/src/utils/reachability-analyzer.js +101 -5
  44. package/src/utils/react-dom-runtime-interop-plugin.d.ts +5 -0
  45. package/src/utils/react-dom-runtime-interop-plugin.js +29 -0
  46. package/src/utils/react-mdx-loader-plugin.d.ts +1 -1
  47. package/src/utils/react-mdx-loader-plugin.js +13 -5
  48. package/src/utils/react-runtime-alias-map.d.ts +6 -0
  49. package/src/utils/react-runtime-alias-map.js +33 -0
  50. package/src/utils/use-sync-external-store-shim-plugin.d.ts +5 -0
  51. package/src/utils/use-sync-external-store-shim-plugin.js +41 -0
  52. package/CHANGELOG.md +0 -62
  53. package/src/react-hmr-strategy.ts +0 -444
  54. package/src/react-renderer.ts +0 -403
  55. package/src/react.plugin.ts +0 -241
  56. package/src/router-adapter.ts +0 -95
  57. package/src/services/react-bundle.service.ts +0 -212
  58. package/src/services/react-hmr-page-metadata-cache.ts +0 -24
  59. package/src/services/react-hydration-asset.service.ts +0 -260
  60. package/src/services/react-page-module.service.ts +0 -214
  61. package/src/services/react-runtime-bundle.service.ts +0 -271
  62. package/src/utils/client-graph-boundary-plugin.ts +0 -590
  63. package/src/utils/client-only.ts +0 -27
  64. package/src/utils/declared-modules.ts +0 -99
  65. package/src/utils/dynamic.ts +0 -27
  66. package/src/utils/hmr-scripts.ts +0 -47
  67. package/src/utils/html-boundary.ts +0 -66
  68. package/src/utils/hydration-scripts.ts +0 -338
  69. package/src/utils/reachability-analyzer.ts +0 -440
  70. package/src/utils/react-mdx-loader-plugin.ts +0 -40
@@ -1,440 +0,0 @@
1
- /**
2
- * @module ReachabilityAnalyzer
3
- *
4
- * This module is responsible for performing static analysis on Ecopages client components
5
- * using the Oxc AST parser. It computes a strict "reachability graph" of all JavaScript/TypeScript
6
- * dependencies (imports, variables, functions, and classes) that begin from explicit client roots.
7
- *
8
- * In Ecopages, "client roots" are defined as the `render`, `errorBoundary`, or `loadingFallback`
9
- * properties passed into `eco.page()` or `eco.component()`. By tracing the execution path from
10
- * these roots, the analyzer determines exactly which modules and bindings are actually needed
11
- * by the browser to hydrate the page, and which imports are unused on the client (and thus can be pruned).
12
- */
13
-
14
- import { parseSync } from 'oxc-parser';
15
- import { extname } from 'node:path';
16
-
17
- type ParserLanguage = 'js' | 'jsx' | 'ts' | 'tsx';
18
-
19
- /**
20
- * Determines the appropriate parser language configuration for a given file name.
21
- *
22
- * @param filename - The absolute or relative path to the file.
23
- * @returns The Oxc parser language dialect to use ('js', 'jsx', 'ts', or 'tsx').
24
- */
25
- export function parserLanguageForFile(filename: string): ParserLanguage {
26
- const extension = extname(filename).toLowerCase();
27
- if (extension === '.tsx') return 'tsx';
28
- if (extension === '.ts') return 'ts';
29
- if (extension === '.jsx') return 'jsx';
30
- return 'js';
31
- }
32
-
33
- /**
34
- * Represents the computed results of a reachability analysis pass.
35
- */
36
- export type ReachabilityResult = {
37
- /**
38
- * Map from import specifier (e.g. 'node:fs', '@/components/Button')
39
- * to a Set of imported bindings, or '*' for namespace imports.
40
- */
41
- reachableImports: Map<string, Set<string> | '*'>;
42
-
43
- /**
44
- * AST nodes of top-level declarations that are reachable.
45
- */
46
- reachableDeclarations: Set<unknown>;
47
-
48
- unreachableSideEffectImports: unknown[];
49
-
50
- /**
51
- * Indicates whether the file had explicit eco client roots, or fell back to treating all exports as roots.
52
- */
53
- isFallbackRoots: boolean;
54
-
55
- /**
56
- * Whether the file was successfully parsed and analyzed.
57
- */
58
- analyzed: boolean;
59
- };
60
-
61
- /**
62
- * Analyzes a module using Oxc AST and extracts a strict reachability graph
63
- * starting from client roots (`render`, `errorBoundary`, `loadingFallback` of `eco.page` or `eco.component`).
64
- *
65
- * @param source - Raw source string of the module.
66
- * @param filename - Absolute or relative path to the module file.
67
- * @param program - Optional pre-parsed Oxc program AST. When supplied, the
68
- * internal `parseSync` call is skipped entirely (avoids double-parsing).
69
- */
70
- export function analyzeReachability(
71
- source: string,
72
- filename: string,
73
- program?: ReturnType<typeof parseSync>['program'],
74
- ): ReachabilityResult {
75
- /**
76
- * AST Resolution
77
- *
78
- * If the caller already has a parsed AST (e.g. from a prior `parseSync` call in the same
79
- * pipeline), we reuse it directly to avoid double-parsing the same source text.
80
- * Otherwise we parse here and return early with an empty "unanalyzed" result on failure.
81
- */
82
- let resolvedProgram: ReturnType<typeof parseSync>['program'];
83
-
84
- if (program) {
85
- resolvedProgram = program;
86
- } else {
87
- let result;
88
- try {
89
- result = parseSync(filename, source, {
90
- sourceType: 'module',
91
- lang: parserLanguageForFile(filename),
92
- });
93
- } catch {
94
- return {
95
- reachableImports: new Map(),
96
- reachableDeclarations: new Set(),
97
- unreachableSideEffectImports: [],
98
- isFallbackRoots: true,
99
- analyzed: false,
100
- };
101
- }
102
- resolvedProgram = result.program;
103
- }
104
-
105
- /**
106
- * Top-level statement scan
107
- *
108
- * Make a single pass over the top-level AST body to build two indexes:
109
- *
110
- * - `topLevelImports`: every `import` declaration found in this module, keyed by specifier.
111
- * Each entry carries a `bindings` map from local alias → imported name so that later
112
- * identifier lookups can resolve `import { readFile as rf } from 'node:fs'` correctly.
113
- *
114
- * - `topLevelDeclarations`: every locally declared variable, function, or class so that
115
- * the BFS traversal can follow identifier references into their definition nodes.
116
- *
117
- * As declarations are catalogued, `checkPotentialClientRoot()` is called to detect whether
118
- * any of them are `eco.page(…)` or `eco.component(…)` calls — the seed nodes for the graph.
119
- */
120
- const topLevelImports: {
121
- node: unknown;
122
- specifier: string;
123
- bindings: Map<string, string>;
124
- isSideEffect: boolean;
125
- }[] = [];
126
- const topLevelDeclarations: Map<string, unknown> = new Map();
127
- const potentialClientRoots: unknown[] = [];
128
-
129
- for (const statement of resolvedProgram.body) {
130
- if (statement.type === 'ImportDeclaration') {
131
- const specifier = statement.source.value as string;
132
- const bindings = new Map<string, string>();
133
-
134
- if (!statement.specifiers || statement.specifiers.length === 0) {
135
- topLevelImports.push({ node: statement, specifier, bindings, isSideEffect: true });
136
- } else {
137
- for (const spec of statement.specifiers) {
138
- if (spec.type === 'ImportDefaultSpecifier') {
139
- bindings.set(spec.local.name, 'default');
140
- } else if (spec.type === 'ImportNamespaceSpecifier') {
141
- bindings.set(spec.local.name, '*');
142
- } else if (spec.type === 'ImportSpecifier') {
143
- const importedName =
144
- spec.imported.type === 'Identifier' ? spec.imported.name : (spec.imported as any).value;
145
- bindings.set(spec.local.name, importedName);
146
- }
147
- }
148
- topLevelImports.push({ node: statement, specifier, bindings, isSideEffect: false });
149
- }
150
- } else if (statement.type === 'VariableDeclaration') {
151
- for (const decl of statement.declarations) {
152
- if (decl.id.type === 'Identifier') {
153
- topLevelDeclarations.set(decl.id.name, statement);
154
- checkPotentialClientRoot(decl.init);
155
- }
156
- }
157
- } else if (statement.type === 'FunctionDeclaration' || statement.type === 'ClassDeclaration') {
158
- if (statement.id && statement.id.type === 'Identifier') {
159
- topLevelDeclarations.set(statement.id.name, statement);
160
- }
161
- } else if (statement.type === 'ExportNamedDeclaration') {
162
- if (statement.declaration) {
163
- const decl = statement.declaration;
164
- if (decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration') {
165
- if (decl.id && decl.id.type === 'Identifier') {
166
- topLevelDeclarations.set(decl.id.name, statement);
167
- }
168
- } else if (decl.type === 'VariableDeclaration') {
169
- for (const v of decl.declarations) {
170
- if (v.id.type === 'Identifier') {
171
- topLevelDeclarations.set(v.id.name, statement);
172
- checkPotentialClientRoot(v.init);
173
- }
174
- }
175
- }
176
- }
177
- } else if (statement.type === 'ExportDefaultDeclaration') {
178
- checkPotentialClientRoot(statement.declaration);
179
- } else if (statement.type === 'ExpressionStatement') {
180
- checkPotentialClientRoot(statement.expression);
181
- } else if (statement.type === 'ExportAllDeclaration' && (statement as { source?: { value: string } }).source) {
182
- /**
183
- * `export * from '...'` unconditionally re-exports every binding from the
184
- * source module. Because the re-exported bindings do not create local
185
- * identifiers in this file, the BFS traverser would never encounter them
186
- * naturally. We therefore always seed these nodes into `potentialClientRoots`
187
- * so that `traverse` can mark the source specifier as fully reachable ('*').
188
- */
189
- potentialClientRoots.push(statement);
190
- }
191
- }
192
-
193
- /**
194
- * Inspects a node to determine if it represents an Ecopages client root declaration.
195
- *
196
- * @param node - The AST node to inspect.
197
- */
198
- function checkPotentialClientRoot(node: unknown) {
199
- if (!node || typeof node !== 'object') return;
200
- if (
201
- (node as { type: string }).type === 'CallExpression' &&
202
- (node as { callee: { type: string } }).callee.type === 'MemberExpression'
203
- ) {
204
- const obj = (node as { callee: { object: unknown } }).callee.object;
205
- const prop = (node as { callee: { property: unknown } }).callee.property;
206
- if (
207
- (obj as { type: string }).type === 'Identifier' &&
208
- (obj as { name: string }).name === 'eco' &&
209
- (prop as { type: string }).type === 'Identifier' &&
210
- ((prop as { name: string }).name === 'page' || (prop as { name: string }).name === 'component')
211
- ) {
212
- potentialClientRoots.push((node as { callee: unknown }).callee);
213
-
214
- const arg = (node as { arguments: unknown[] }).arguments[0];
215
- if (arg && (arg as { type: string }).type === 'ObjectExpression') {
216
- for (const prop of (arg as { properties: unknown[] }).properties) {
217
- if (
218
- (prop as { type: string }).type === 'Property' &&
219
- (prop as { key: { type: string } }).key.type === 'Identifier'
220
- ) {
221
- if (
222
- [
223
- 'render',
224
- 'errorBoundary',
225
- 'loadingFallback',
226
- 'clientScripts',
227
- 'dependencies',
228
- ].includes((prop as { key: { name: string } }).key.name)
229
- ) {
230
- potentialClientRoots.push((prop as { value: unknown }).value);
231
- }
232
- }
233
- }
234
- }
235
- }
236
- } else if (
237
- (node as { type: string }).type === 'CallExpression' &&
238
- (node as { callee: { type: string } }).callee.type === 'Identifier' &&
239
- (node as { callee: { name: string } }).callee.name === 'dynamic'
240
- ) {
241
- potentialClientRoots.push(node);
242
- }
243
- }
244
-
245
- /**
246
- * Client root resolution (fallback mode)
247
- *
248
- * If *no* `eco.page`/`eco.component` call was found in the file, we fall back to treating
249
- * every exported declaration as a potential client root. This covers utility modules that
250
- * don't use Ecopages conventions (plain React components, shared helpers, etc.)
251
- *
252
- * In fallback mode the analysis is intentionally permissive — the `isFallbackRoots` flag
253
- * propagates to callers so they know not to hard-fail on reachable forbidden imports
254
- * (since we cannot be 100% certain about the execution boundary).
255
- */
256
- let isFallbackRoots = false;
257
- if (potentialClientRoots.length === 0) {
258
- isFallbackRoots = true;
259
- for (const node of resolvedProgram.body) {
260
- if (
261
- (node as { type: string }).type === 'ExportNamedDeclaration' ||
262
- (node as { type: string }).type === 'ExportDefaultDeclaration' ||
263
- (node as { type: string }).type === 'ExportAllDeclaration'
264
- ) {
265
- potentialClientRoots.push(node);
266
- }
267
- }
268
- }
269
-
270
- /**
271
- * BFS reachability traversal
272
- *
273
- * Starting from the seed nodes collected above, we perform a breadth-first walk of the AST.
274
- * Every identifier encountered is checked against `topLevelDeclarations` (to enqueue further
275
- * nodes) and `topLevelImports` (to mark the referenced binding as reachable).
276
- *
277
- * `visitedNodes` guards against infinite cycles in recursive or mutually-recursive declarations.
278
- */
279
- const reachableImports = new Map<string, Set<string> | '*'>();
280
- const reachableDeclarations = new Set<unknown>();
281
- const queue: unknown[] = [...potentialClientRoots];
282
- const visitedNodes = new Set<unknown>();
283
-
284
- /**
285
- * Registers an imported binding as reachable in the client graph.
286
- *
287
- * @param specifier - The module specifier from which the binding is imported.
288
- * @param importedName - The specific named export being imported, or '*' for namespace imports.
289
- */
290
- function markImportReachable(specifier: string, importedName: string) {
291
- let current = reachableImports.get(specifier);
292
- if (current === '*') return;
293
-
294
- if (importedName === '*') {
295
- reachableImports.set(specifier, '*');
296
- } else {
297
- if (!current) {
298
- current = new Set<string>();
299
- reachableImports.set(specifier, current);
300
- }
301
- current.add(importedName);
302
- }
303
- }
304
-
305
- /**
306
- * Traces an identifier to its origin declaration, enqueuing it for deep traversal if it resolves
307
- * to a local module-level declaration, or marking it as a reachable import if it originates from another module.
308
- *
309
- * @param name - The identifier name to check.
310
- */
311
- function checkIdentifier(name: string) {
312
- if (topLevelDeclarations.has(name)) {
313
- const declNode = topLevelDeclarations.get(name);
314
- if (!reachableDeclarations.has(declNode)) {
315
- reachableDeclarations.add(declNode);
316
- queue.push(declNode);
317
- }
318
- }
319
-
320
- for (const imp of topLevelImports) {
321
- if (imp.bindings.has(name)) {
322
- markImportReachable(imp.specifier, imp.bindings.get(name)!);
323
- }
324
- }
325
- }
326
-
327
- /**
328
- * Recursively walks down an AST node to discover referenced variables and function calls,
329
- * building out the reachability graph.
330
- *
331
- * @param node - The Oxc AST node to traverse. Typed as `any` because Oxc lacks a unified iterable node type.
332
- * @param localScope - A set of identifiers that shadow module-level declarations within the current lexical scope.
333
- */
334
- function traverse(node: any, localScope: Set<string>) {
335
- if (!node || typeof node !== 'object') return;
336
- if (visitedNodes.has(node)) return;
337
- visitedNodes.add(node);
338
-
339
- if (Array.isArray(node)) {
340
- for (const child of node) traverse(child, localScope);
341
- return;
342
- }
343
-
344
- const currentScope = localScope;
345
-
346
- /**
347
- * `export * from '...'` nodes are seeded into the BFS queue by the top-level scan.
348
- * When the traverser reaches one here we immediately mark the entire source module
349
- * as reachable ('*'), then stop — there are no local identifiers to follow.
350
- */
351
- if (node.type === 'ExportAllDeclaration' && typeof node.source?.value === 'string') {
352
- markImportReachable(node.source.value as string, '*');
353
- return;
354
- }
355
-
356
- if (node.type === 'Identifier' || (node.type === 'JSXIdentifier' && /^[A-Z]/.test(node.name))) {
357
- if (!currentScope.has(node.name)) {
358
- checkIdentifier(node.name);
359
- }
360
- } else if (node.type === 'MemberExpression') {
361
- traverse(node.object, currentScope);
362
- if (node.computed) {
363
- traverse(node.property, currentScope);
364
- }
365
- return;
366
- } else if (node.type === 'Property') {
367
- if (node.computed) traverse(node.key, currentScope);
368
- traverse(node.value, currentScope);
369
- return;
370
- } else if (node.type === 'JSXOpeningElement' || node.type === 'JSXClosingElement') {
371
- traverse(node.name, currentScope);
372
- if (node.attributes) {
373
- for (const attr of node.attributes) traverse(attr, currentScope);
374
- }
375
- return;
376
- } else if (node.type === 'JSXIdentifier') {
377
- if (/^[A-Z]/.test(node.name) && !currentScope.has(node.name)) {
378
- checkIdentifier(node.name);
379
- }
380
- } else if (node.type === 'JSXMemberExpression') {
381
- traverse(node.object, currentScope);
382
- return;
383
- } else if (
384
- node.type === 'CallExpression' &&
385
- node.callee.type === 'Identifier' &&
386
- node.callee.name === 'dynamic'
387
- ) {
388
- const arg = node.arguments[0];
389
- if (arg && (arg.type === 'ArrowFunctionExpression' || arg.type === 'FunctionExpression')) {
390
- const body = arg.body;
391
- if (body.type === 'ImportExpression' && body.source.type === 'Literal') {
392
- markImportReachable(body.source.value as string, '*');
393
- }
394
- }
395
- } else if (node.type === 'ImportExpression' && node.source.type === 'Literal') {
396
- markImportReachable(node.source.value as string, '*');
397
- }
398
-
399
- if (
400
- node.type === 'ArrowFunctionExpression' ||
401
- node.type === 'FunctionExpression' ||
402
- node.type === 'FunctionDeclaration'
403
- ) {
404
- const newScope = new Set(currentScope);
405
- if (node.id && node.id.type === 'Identifier') newScope.add(node.id.name);
406
- if (node.params && node.params.items) {
407
- for (const p of node.params.items) {
408
- if (p.pattern && p.pattern.type === 'Identifier') {
409
- newScope.add(p.pattern.name);
410
- }
411
- }
412
- }
413
- traverse(node.body, newScope);
414
- return;
415
- }
416
-
417
- for (const key in node) {
418
- if (key !== 'type' && key !== 'start' && key !== 'end') {
419
- traverse(node[key], currentScope);
420
- }
421
- }
422
- }
423
-
424
- while (queue.length > 0) {
425
- const root = queue.shift();
426
- traverse(root, new Set());
427
- }
428
-
429
- const unreachableSideEffectImports = topLevelImports
430
- .filter((imp) => imp.isSideEffect && !reachableImports.has(imp.specifier))
431
- .map((imp) => imp.node);
432
-
433
- return {
434
- reachableImports,
435
- reachableDeclarations,
436
- unreachableSideEffectImports,
437
- isFallbackRoots,
438
- analyzed: true,
439
- };
440
- }
@@ -1,40 +0,0 @@
1
- import { readFileSync } from 'node:fs';
2
- import path from 'node:path';
3
- import type { EcoBuildPlugin } from '@ecopages/core/build/build-types';
4
- import { type CompileOptions, compile } from '@mdx-js/mdx';
5
- import { SourceMapGenerator } from 'source-map';
6
- import { VFile } from 'vfile';
7
-
8
- export function createReactMdxLoaderPlugin(compilerOptions?: CompileOptions): EcoBuildPlugin {
9
- const mdxExtensions = compilerOptions?.mdxExtensions ?? ['.mdx'];
10
- const mdExtensions = compilerOptions?.mdExtensions ?? ['.md'];
11
- const allExtensions = [...mdxExtensions, ...mdExtensions];
12
- const escapedExts = allExtensions.map((ext) => ext.replace('.', '\\.'));
13
- const filter = new RegExp(`(${escapedExts.join('|')})(\\?.*)?$`);
14
-
15
- return {
16
- name: 'react-mdx-loader',
17
- setup(build) {
18
- build.onLoad({ filter }, async (args) => {
19
- const filePath = args.path.includes('?') ? args.path.split('?')[0] : args.path;
20
- const source = readFileSync(filePath, 'utf-8');
21
- const file = new VFile({ path: filePath, value: source });
22
-
23
- const compiled = await compile(file, {
24
- ...compilerOptions,
25
- SourceMapGenerator,
26
- });
27
-
28
- const sourceMap = compiled.map
29
- ? `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(JSON.stringify(compiled.map)).toString('base64')}\n`
30
- : '';
31
-
32
- return {
33
- contents: `${String(compiled.value)}${sourceMap}`,
34
- loader: compilerOptions?.jsx ? 'jsx' : 'js',
35
- resolveDir: path.dirname(args.path),
36
- };
37
- });
38
- },
39
- };
40
- }