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

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,444 +0,0 @@
1
- /**
2
- * React HMR Strategy
3
- *
4
- * Handles hot module replacement for React components.
5
- * Triggers module invalidation on changes to ensure fresh component re-renders.
6
- *
7
- * @module
8
- */
9
-
10
- import path from 'node:path';
11
- import { pathToFileURL } from 'node:url';
12
-
13
- import { HmrStrategy, HmrStrategyType, type HmrAction } from '@ecopages/core/hmr/hmr-strategy';
14
- import { defaultBuildAdapter } from '@ecopages/core/build/build-adapter';
15
- import type { EcoBuildPlugin } from '@ecopages/core/build/build-types';
16
- import { FileNotFoundError, fileSystem } from '@ecopages/file-system';
17
- import { Logger } from '@ecopages/logger';
18
- import type { DefaultHmrContext, EcoComponentConfig } from '@ecopages/core';
19
- import type { CompileOptions } from '@mdx-js/mdx';
20
- import { injectHmrHandler } from './utils/hmr-scripts.ts';
21
- import { createClientGraphBoundaryPlugin } from './utils/client-graph-boundary-plugin.ts';
22
- import { collectPageDeclaredModules, collectPageDeclaredModulesFromModule } from './utils/declared-modules.ts';
23
- import type { ReactHmrPageMetadataCache } from './services/react-hmr-page-metadata-cache.ts';
24
-
25
- const appLogger = new Logger('[ReactHmrStrategy]');
26
-
27
- /**
28
- * Strategy for handling React component HMR updates.
29
- *
30
- * This strategy provides React-specific HMR handling by rebuilding entrypoints
31
- * and injecting HMR acceptance handlers that trigger module invalidation.
32
- *
33
- * The processing steps are:
34
- * 1. Check if any React entrypoints are registered
35
- * 2. Rebuild all React entrypoints (the changed file could be a dependency)
36
- * 3. Replace bare specifiers with runtime URLs
37
- * 4. Inject HMR acceptance handler
38
- * 5. Broadcast update events for each rebuilt entrypoint
39
- *
40
- * @remarks
41
- * This strategy has higher priority than generic JsHmrStrategy, allowing it
42
- * to handle React files specially while falling back to generic handling for
43
- * non-React files.
44
- *
45
- * Future enhancement: Track dependencies using Bun's transpiler API to only
46
- * rebuild affected entrypoints instead of all of them.
47
- *
48
- * @see https://bun.sh/docs/runtime/transpiler
49
- *
50
- * @example
51
- * ```typescript
52
- * const context = {
53
- * getWatchedFiles: () => watchedFilesMap,
54
- * getSpecifierMap: () => specifierMap,
55
- * getDistDir: () => '/path/to/dist/_hmr',
56
- * getPlugins: () => [],
57
- * getSrcDir: () => '/path/to/src',
58
- * getLayoutsDir: () => '/path/to/src/layouts'
59
- * };
60
- * const strategy = new ReactHmrStrategy(context);
61
- * ```
62
- */
63
- export class ReactHmrStrategy extends HmrStrategy {
64
- readonly type = HmrStrategyType.INTEGRATION;
65
- private mdxCompilerOptions?: CompileOptions;
66
- private readonly knownEntrypoints = new Set<string>();
67
-
68
- private async importNodePageModule(entrypointPath: string): Promise<{
69
- default?: { config?: EcoComponentConfig };
70
- config?: EcoComponentConfig;
71
- }> {
72
- const srcDir = this.context.getSrcDir();
73
- const rootDir = path.dirname(srcDir);
74
- const outdir = path.join(path.resolve(this.context.getDistDir(), '..', '..'), '.server-modules');
75
- const fileBaseName = path.basename(entrypointPath, path.extname(entrypointPath));
76
- const fileHash = fileSystem.hash(entrypointPath);
77
- const outputFileName = `${fileBaseName}-${fileHash}.js`;
78
-
79
- const buildResult = await defaultBuildAdapter.build({
80
- entrypoints: [entrypointPath],
81
- root: rootDir,
82
- outdir,
83
- target: 'node',
84
- format: 'esm',
85
- sourcemap: 'none',
86
- splitting: false,
87
- minify: false,
88
- naming: outputFileName,
89
- });
90
-
91
- if (!buildResult.success) {
92
- const details = buildResult.logs.map((log) => log.message).join(' | ');
93
- throw new Error(`Error transpiling React HMR page module: ${details}`);
94
- }
95
-
96
- const preferredOutputPath = path.join(outdir, outputFileName);
97
- const compiledOutput =
98
- buildResult.outputs.find((output) => output.path === preferredOutputPath)?.path ??
99
- buildResult.outputs.find((output) => output.path.endsWith('.js'))?.path;
100
-
101
- if (!compiledOutput) {
102
- throw new Error(`No transpiled output generated for React HMR page module: ${entrypointPath}`);
103
- }
104
-
105
- return (await import(pathToFileURL(compiledOutput).href)) as {
106
- default?: { config?: EcoComponentConfig };
107
- config?: EcoComponentConfig;
108
- };
109
- }
110
-
111
- private createUseSyncExternalStoreShimPlugin(): EcoBuildPlugin {
112
- return {
113
- name: 'react-hmr-use-sync-external-store-shim',
114
- setup(build) {
115
- build.onResolve({ filter: /^use-sync-external-store\/shim(?:\/index\.js)?$/ }, () => ({
116
- path: 'use-sync-external-store/shim',
117
- namespace: 'ecopages-react-hmr-shim',
118
- }));
119
-
120
- build.onLoad(
121
- { filter: /^use-sync-external-store\/shim$/, namespace: 'ecopages-react-hmr-shim' },
122
- () => ({
123
- contents: "export { useSyncExternalStore } from 'react';",
124
- loader: 'js',
125
- }),
126
- );
127
-
128
- build.onLoad({ filter: /[\\/]use-sync-external-store[\\/]shim[\\/]index\.js$/ }, () => ({
129
- contents: "export { useSyncExternalStore } from 'react';",
130
- loader: 'js',
131
- }));
132
-
133
- build.onLoad(
134
- {
135
- filter: /[\\/]use-sync-external-store[\\/]cjs[\\/]use-sync-external-store-shim\.development\.js$/,
136
- },
137
- () => ({
138
- contents: "export { useSyncExternalStore } from 'react';",
139
- loader: 'js',
140
- }),
141
- );
142
- },
143
- };
144
- }
145
-
146
- /**
147
- * Creates a new React HMR strategy instance.
148
- *
149
- * @param context - The HMR context providing access to watched files, plugins, build directories,
150
- * and the layouts directory for detecting layout file changes that require full
151
- * page reloads instead of module-level HMR updates.
152
- * @param pageMetadataCache - React-only cache of declared browser modules discovered during
153
- * server rendering. This avoids re-importing unchanged page modules
154
- * during save-time Fast Refresh rebuilds.
155
- * @param mdxCompilerOptions - Optional MDX compiler options for processing .mdx files
156
- * @param explicitGraphEnabled - Enables explicit graph mode for React HMR bundling.
157
- * In explicit mode, HMR builds omit AST server-only stripping plugins in React paths.
158
- */
159
- constructor(
160
- private context: DefaultHmrContext,
161
- private pageMetadataCache: ReactHmrPageMetadataCache,
162
- mdxCompilerOptions?: CompileOptions,
163
- private explicitGraphEnabled = false,
164
- ) {
165
- super();
166
- this.mdxCompilerOptions = mdxCompilerOptions;
167
- }
168
-
169
- /**
170
- * Returns build plugins for React HMR bundling.
171
- *
172
- * Includes the client graph boundary plugin to prevent undeclared imports
173
- * (including `node:*`) from breaking the browser bundle.
174
- */
175
- private getBuildPlugins(declaredModules?: string[]): EcoBuildPlugin[] {
176
- const allowSpecifiers = [
177
- '@ecopages/core',
178
- 'react',
179
- 'react-dom',
180
- 'react/jsx-runtime',
181
- 'react/jsx-dev-runtime',
182
- 'react-dom/client',
183
- ...Array.from(this.context.getSpecifierMap().keys()),
184
- ];
185
-
186
- return [
187
- createClientGraphBoundaryPlugin({
188
- absWorkingDir: path.dirname(this.context.getSrcDir()),
189
- alwaysAllowSpecifiers: allowSpecifiers,
190
- declaredModules,
191
- }),
192
- ...this.context.getPlugins(),
193
- this.createUseSyncExternalStoreShimPlugin(),
194
- ];
195
- }
196
-
197
- private isReactEntrypoint(filePath: string): boolean {
198
- if (filePath.endsWith('.tsx')) {
199
- return true;
200
- }
201
-
202
- return filePath.endsWith('.mdx') && this.mdxCompilerOptions !== undefined;
203
- }
204
-
205
- /**
206
- * Determines if the file is a React/MDX entrypoint that's registered for HMR.
207
- *
208
- * @param filePath - Absolute path to the changed file
209
- * @returns True if this is a registered React or MDX entrypoint
210
- */
211
- matches(filePath: string): boolean {
212
- const watchedFiles = this.context.getWatchedFiles();
213
- appLogger.debug(`Checking ${filePath}. Watched: ${watchedFiles.size}`);
214
- if (watchedFiles.size === 0) {
215
- return false;
216
- }
217
-
218
- return this.isReactEntrypoint(filePath);
219
- }
220
-
221
- /**
222
- * Checks if a file is a layout file.
223
- *
224
- * Layout files require special HMR handling because they wrap multiple pages and affect
225
- * the entire page structure. When a layout changes, we trigger a 'layout-update' event
226
- * instead of a regular 'update' event, which instructs the browser to perform a full
227
- * page reload (or clear cache and re-render) rather than attempting module-level HMR.
228
- *
229
- * @param filePath - Absolute path to the file
230
- * @returns True if the file is in the layouts directory
231
- */
232
- private isLayoutFile(filePath: string): boolean {
233
- return filePath.startsWith(this.context.getLayoutsDir());
234
- }
235
-
236
- /**
237
- * Processes a React file change by rebuilding all React entrypoints.
238
- *
239
- * For layout files, broadcasts a 'layout-update' event to trigger full page reload.
240
- * For regular components/pages, broadcasts 'update' events for module-level HMR.
241
- * When a page entrypoint is first registered, only that entrypoint is built.
242
- * Subsequent file updates rebuild all watched React entrypoints as usual.
243
- *
244
- * @param _filePath - Absolute path to the changed file
245
- * @returns Action to broadcast update events (layout-update for layouts, update for components)
246
- */
247
- async process(_filePath: string): Promise<HmrAction> {
248
- appLogger.debug(`Processing ${_filePath}`);
249
- const watchedFiles = this.context.getWatchedFiles();
250
-
251
- if (watchedFiles.size === 0) {
252
- appLogger.debug(`No watched files`);
253
- return { type: 'none' };
254
- }
255
-
256
- const isLayout = this.isLayoutFile(_filePath);
257
- if (isLayout) {
258
- appLogger.debug(`Detected layout file change: ${_filePath}`);
259
- }
260
-
261
- const entrypointsToBuild =
262
- !this.knownEntrypoints.has(_filePath) && watchedFiles.has(_filePath)
263
- ? [[_filePath, watchedFiles.get(_filePath)!]]
264
- : watchedFiles.entries();
265
- this.knownEntrypoints.add(_filePath);
266
-
267
- const updates: string[] = [];
268
- for (const [entrypoint, outputUrl] of entrypointsToBuild) {
269
- if (!this.isReactEntrypoint(entrypoint)) {
270
- continue;
271
- }
272
-
273
- appLogger.debug(`Bundling ${entrypoint}`);
274
- const success = await this.bundleReactEntrypoint(entrypoint, outputUrl);
275
- if (success) {
276
- updates.push(outputUrl);
277
- }
278
- }
279
-
280
- if (updates.length > 0) {
281
- if (isLayout) {
282
- appLogger.debug(`Layout update detected, sending layout-update event`);
283
- return {
284
- type: 'broadcast',
285
- events: [
286
- {
287
- type: 'layout-update',
288
- },
289
- ],
290
- };
291
- }
292
-
293
- appLogger.debug(`Broadcasting ${updates.length} updates`);
294
- return {
295
- type: 'broadcast',
296
- events: updates.map((path) => ({
297
- type: 'update',
298
- path,
299
- timestamp: Date.now(),
300
- })),
301
- };
302
- }
303
-
304
- appLogger.debug(`No updates generated`);
305
- return { type: 'none' };
306
- }
307
-
308
- /**
309
- * Bundles a single React/MDX entrypoint with HMR support.
310
- *
311
- * @param entrypointPath - Absolute path to the source file
312
- * @param outputUrl - URL path for the bundled file
313
- * @returns True if bundling was successful
314
- */
315
- private async bundleReactEntrypoint(entrypointPath: string, outputUrl: string): Promise<boolean> {
316
- try {
317
- const isMdx = entrypointPath.endsWith('.mdx');
318
- const srcDir = this.context.getSrcDir();
319
- const relativePath = path.relative(srcDir, entrypointPath);
320
- const relativePathJs = relativePath.replace(/\.(tsx?|jsx?|mdx)$/, '.js');
321
- const encodedPathJs = this.encodeDynamicSegments(relativePathJs);
322
- const outputPath = path.join(this.context.getDistDir(), encodedPathJs);
323
- const tempDir = path.dirname(outputPath);
324
-
325
- const declaredModules = this.pageMetadataCache.getDeclaredModules(entrypointPath)
326
- ? this.pageMetadataCache.getDeclaredModules(entrypointPath)!
327
- : isMdx
328
- ? await collectPageDeclaredModules(entrypointPath)
329
- : collectPageDeclaredModulesFromModule(await this.importNodePageModule(entrypointPath));
330
- const plugins = this.getBuildPlugins(declaredModules);
331
-
332
- if (isMdx && this.mdxCompilerOptions) {
333
- const { createReactMdxLoaderPlugin } = await import('./utils/react-mdx-loader-plugin.ts');
334
- const mdxPlugin = createReactMdxLoaderPlugin(this.mdxCompilerOptions);
335
- plugins.unshift(mdxPlugin);
336
- }
337
-
338
- const result = await defaultBuildAdapter.build({
339
- entrypoints: [entrypointPath],
340
- outdir: tempDir,
341
- naming: `[name].[hash].tmp`,
342
- target: 'browser',
343
- format: 'esm',
344
- sourcemap: 'none',
345
- plugins,
346
- minify: false,
347
- external: ['react', 'react-dom', 'react/jsx-runtime', 'react/jsx-dev-runtime', 'react-dom/client'],
348
- });
349
-
350
- if (!result.success) {
351
- appLogger.error(`Failed to build ${entrypointPath}:`, result.logs);
352
- return false;
353
- }
354
-
355
- const tempFile = result.outputs[0]?.path;
356
- if (!tempFile) {
357
- appLogger.error(`No output file generated for ${entrypointPath}`);
358
- return false;
359
- }
360
-
361
- const processed = await this.processOutput(tempFile, outputPath, outputUrl);
362
- return processed;
363
- } catch (error) {
364
- appLogger.error(`Error bundling ${entrypointPath}:`, error as Error);
365
- return false;
366
- }
367
- }
368
-
369
- /**
370
- * Encodes dynamic route segments (brackets) in file paths.
371
- * Converts `[slug]` to `_slug_` to avoid filesystem issues.
372
- */
373
- private encodeDynamicSegments(filepath: string): string {
374
- return filepath.replace(/\[([^\]]+)\]/g, '_$1_');
375
- }
376
-
377
- /**
378
- * Processes bundled output by replacing specifiers and injecting HMR handler.
379
- * Writes to temp file first, then renames atomically to avoid conflicts.
380
- *
381
- * @param tempPath - Path to the temporary bundled file
382
- * @param finalPath - Final destination path
383
- * @param url - URL path for logging
384
- * @returns True if processing was successful
385
- */
386
- private async processOutput(tempPath: string, finalPath: string, url: string): Promise<boolean> {
387
- if (!fileSystem.exists(tempPath)) {
388
- appLogger.debug(`Skipping stale temp output for ${url}: ${tempPath}`);
389
- return false;
390
- }
391
-
392
- try {
393
- let code = await fileSystem.readFile(tempPath);
394
-
395
- code = this.replaceBareSpecifiers(code);
396
- code = injectHmrHandler(code);
397
-
398
- await fileSystem.writeAsync(finalPath, code);
399
- await fileSystem.removeAsync(tempPath).catch(() => {});
400
-
401
- appLogger.debug(`Processed ${url} with HMR handler`);
402
- return true;
403
- } catch (error) {
404
- if (
405
- error instanceof FileNotFoundError ||
406
- (error instanceof Error && error.message.includes('not found')) ||
407
- (error instanceof Error && 'code' in error && error.code === 'ENOENT')
408
- ) {
409
- appLogger.debug(`Skipping stale temp output for ${url}: ${tempPath}`);
410
- await fileSystem.removeAsync(tempPath).catch(() => {});
411
- return false;
412
- }
413
-
414
- appLogger.error(`Error processing output for ${url}:`, error as Error);
415
- await fileSystem.removeAsync(tempPath).catch(() => {});
416
- return false;
417
- }
418
- }
419
-
420
- /**
421
- * Replaces bare specifiers with runtime URLs.
422
- *
423
- * Handles both static imports and dynamic imports.
424
- *
425
- * @param code - The bundled code to transform
426
- * @returns The transformed code with runtime URLs
427
- */
428
- private replaceBareSpecifiers(code: string): string {
429
- const specifierMap = this.context.getSpecifierMap();
430
-
431
- if (specifierMap.size === 0) {
432
- return code;
433
- }
434
-
435
- let result = code;
436
- for (const [bareSpec, runtimeUrl] of specifierMap.entries()) {
437
- const escaped = bareSpec.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
438
- result = result.replace(new RegExp(`from\\s*["']${escaped}["']`, 'g'), `from "${runtimeUrl}"`);
439
- result = result.replace(new RegExp(`import\\(["']${escaped}["']\\)`, 'g'), `import("${runtimeUrl}")`);
440
- }
441
-
442
- return result;
443
- }
444
- }