@ecopages/core 0.3.0 → 0.3.2

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 (201) hide show
  1. package/README.md +2 -2
  2. package/package.json +3 -3
  3. package/src/adapters/node/create-app.d.ts +40 -11
  4. package/src/adapters/node/create-app.js +95 -69
  5. package/src/adapters/node/dev-session.js +0 -1
  6. package/src/adapters/node/http-request-bridge.d.ts +4 -0
  7. package/src/adapters/node/http-request-bridge.js +9 -1
  8. package/src/adapters/node/runtime-host.d.ts +28 -6
  9. package/src/adapters/node/runtime-host.js +35 -9
  10. package/src/adapters/node/server-adapter.d.ts +10 -35
  11. package/src/adapters/node/server-adapter.js +21 -58
  12. package/src/adapters/shared/hmr/hmr-manager.d.ts +21 -7
  13. package/src/adapters/shared/hmr/hmr-manager.js +58 -70
  14. package/src/adapters/shared/http/api-request-pipeline.d.ts +3 -12
  15. package/src/adapters/shared/http/api-request-pipeline.js +7 -7
  16. package/src/adapters/shared/http/dist-file-handler.d.ts +16 -0
  17. package/src/adapters/shared/http/dist-file-handler.js +172 -0
  18. package/src/adapters/shared/http/explicit-static-route-matcher.js +2 -1
  19. package/src/adapters/shared/http/fs-server-response-matcher.js +3 -2
  20. package/src/adapters/shared/runtime/bind-runtime-server.d.ts +5 -7
  21. package/src/adapters/shared/runtime/bind-runtime-server.js +8 -12
  22. package/src/adapters/shared/runtime/copy-runtime-public-dir.js +10 -9
  23. package/src/adapters/shared/runtime/port-manager.d.ts +8 -11
  24. package/src/adapters/shared/runtime/port-manager.js +19 -30
  25. package/src/adapters/shared/runtime/runtime-server-lifecycle.d.ts +6 -9
  26. package/src/adapters/shared/runtime/runtime-server-lifecycle.js +2 -5
  27. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +1 -3
  28. package/src/adapters/shared/runtime/server-request-pipeline.js +1 -5
  29. package/src/adapters/shared/runtime/server-static-builder.d.ts +3 -3
  30. package/src/adapters/shared/runtime/server-static-builder.js +3 -3
  31. package/src/adapters/shared/ws/node-http-websocket-upgrades.js +2 -1
  32. package/src/adapters/shared/ws/websocket-lifecycle.d.ts +5 -6
  33. package/src/adapters/shared/ws/websocket-lifecycle.js +1 -2
  34. package/src/assets/app-browser-client-build.js +1 -2
  35. package/src/assets/asset-processing-service/browser-runtime-entry-resolution.js +8 -8
  36. package/src/assets/asset-processing-service/browser-runtime-entry.factory.js +4 -4
  37. package/src/assets/asset-processing-service/processors/script/file-script.processor.d.ts +12 -8
  38. package/src/assets/asset-processing-service/processors/script/file-script.processor.js +36 -16
  39. package/src/assets/asset-processing-service/processors/stylesheet/file-stylesheet.processor.js +11 -6
  40. package/src/assets/browser-asset-output.d.ts +19 -0
  41. package/src/assets/browser-asset-output.js +30 -0
  42. package/src/assets/hashed-browser-asset.d.ts +8 -6
  43. package/src/assets/hashed-browser-asset.js +8 -6
  44. package/src/build/build-adapter.d.ts +2 -19
  45. package/src/build/build-adapter.js +0 -21
  46. package/src/build/build-graph.js +2 -2
  47. package/src/build/cache/cache-keys.d.ts +0 -3
  48. package/src/build/cache/cache-keys.js +0 -14
  49. package/src/build/cache/pages-unified-graph-build.js +2 -17
  50. package/src/build/contracts/build-contracts.d.ts +0 -3
  51. package/src/build/preserve-import-meta-transform.js +2 -2
  52. package/src/build/rolldown/app-package-declarations.js +3 -3
  53. package/src/build/rolldown/rolldown-adapter-helpers.js +3 -3
  54. package/src/build/rolldown/rolldown-build-adapter.d.ts +0 -1
  55. package/src/build/rolldown/rolldown-build-adapter.js +1 -2
  56. package/src/build/rolldown/rolldown-build-invocation-metrics.d.ts +1 -2
  57. package/src/build/rolldown/rolldown-build-invocation-metrics.js +5 -12
  58. package/src/build/rolldown/server-side-css-shim-plugin.js +3 -3
  59. package/src/build/runtime/build-queue.d.ts +8 -13
  60. package/src/build/runtime/build-queue.js +6 -17
  61. package/src/build/server/app-module-loader.service.d.ts +1 -1
  62. package/src/build/server/app-module-loader.service.js +0 -2
  63. package/src/build/server/page-module-import.service.d.ts +2 -3
  64. package/src/build/server/page-module-import.service.js +3 -4
  65. package/src/build/server-bundle-deploy-manifest.d.ts +5 -0
  66. package/src/build/server-bundle-deploy-manifest.js +15 -1
  67. package/src/build/server-bundle-publication.js +4 -5
  68. package/src/build.d.ts +2 -2
  69. package/src/build.js +2 -2
  70. package/src/config/assembly/app-runtime.d.ts +2 -2
  71. package/src/config/assembly/app-runtime.js +2 -2
  72. package/src/config/assembly/finalize-config.d.ts +4 -4
  73. package/src/config/assembly/finalize-config.js +4 -5
  74. package/src/config/config-module-files.js +2 -3
  75. package/src/config/internal-types.d.ts +0 -7
  76. package/src/config/user-config-types.d.ts +0 -4
  77. package/src/diagnostics/request-pipeline-metrics.d.ts +3 -3
  78. package/src/diagnostics/request-pipeline-metrics.js +4 -4
  79. package/src/diagnostics/startup-trace.js +2 -5
  80. package/src/errors/http-error.d.ts +2 -2
  81. package/src/errors/http-error.js +4 -4
  82. package/src/hmr/client/hmr-runtime.js +16 -7
  83. package/src/hmr/client/module-update.d.ts +7 -0
  84. package/src/hmr/client/module-update.js +21 -4
  85. package/src/hmr/hmr-strategy.d.ts +0 -3
  86. package/src/hmr/hmr-strategy.js +0 -3
  87. package/src/hmr/strategies/js-hmr-strategy.d.ts +2 -3
  88. package/src/hmr/strategies/js-hmr-strategy.js +3 -6
  89. package/src/html-pages/html-page-module-scripts.js +4 -3
  90. package/src/html-pages/html-page-renderer.js +2 -3
  91. package/src/plugins/alias-resolver-cache.d.ts +4 -3
  92. package/src/plugins/alias-resolver-cache.js +4 -3
  93. package/src/plugins/component-import-discovery.js +4 -4
  94. package/src/plugins/eco-component-meta-plugin.d.ts +10 -1
  95. package/src/plugins/eco-component-meta-plugin.js +66 -10
  96. package/src/plugins/foreign-jsx-override-plugin.js +4 -3
  97. package/src/plugins/tsconfig-import-resolver.js +12 -12
  98. package/src/route-renderer/error-pages/default-error-pages.js +2 -1
  99. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.js +1 -1
  100. package/src/route-renderer/orchestration/foreign-child/render-session.d.ts +0 -1
  101. package/src/route-renderer/orchestration/integration-renderer.d.ts +10 -5
  102. package/src/route-renderer/orchestration/integration-renderer.js +13 -14
  103. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.d.ts +1 -23
  104. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.js +0 -29
  105. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph.service.js +10 -32
  106. package/src/route-renderer/page-loading/ecopages-virtual-imports.js +2 -2
  107. package/src/route-renderer/page-loading/page-dependency-bundling.js +5 -5
  108. package/src/route-renderer/page-loading/page-module-loader.js +1 -1
  109. package/src/route-renderer/route-renderer.d.ts +2 -5
  110. package/src/route-renderer/route-renderer.js +2 -4
  111. package/src/router/client/link-navigation-policy.d.ts +4 -1
  112. package/src/router/client/link-navigation-policy.js +20 -6
  113. package/src/router/server/route-registry.d.ts +0 -1
  114. package/src/router/server/route-registry.js +3 -13
  115. package/src/router/server/segment-path-matcher.d.ts +12 -0
  116. package/src/router/server/segment-path-matcher.js +30 -0
  117. package/src/static-site-generator/static-site-generator.d.ts +0 -5
  118. package/src/static-site-generator/static-site-generator.js +2 -15
  119. package/src/types/contracts.d.ts +17 -27
  120. package/src/types/public-types.d.ts +1 -1
  121. package/src/utils/format-error-chain.d.ts +9 -0
  122. package/src/utils/format-error-chain.js +20 -0
  123. package/src/utils/invariant.d.ts +6 -1
  124. package/src/utils/invariant.js +7 -2
  125. package/src/watchers/project-watcher.d.ts +20 -1
  126. package/src/watchers/project-watcher.js +40 -9
  127. package/src/watchers/workspace-package-watch-roots.js +5 -5
  128. package/src/adapters/README.md +0 -58
  129. package/src/adapters/shared/hmr/hmr-manager.test-helpers.d.ts +0 -28
  130. package/src/adapters/shared/hmr/hmr-manager.test-helpers.js +0 -53
  131. package/src/adapters/shared/runtime/runtime-host.d.ts +0 -15
  132. package/src/adapters/shared/runtime/runtime-host.js +0 -1
  133. package/src/assets/README.md +0 -35
  134. package/src/build/README.md +0 -298
  135. package/src/build/server/README.md +0 -50
  136. package/src/cache/README.md +0 -5
  137. package/src/client/README.md +0 -5
  138. package/src/client/navigation-scripts/navigation-scripts.test.browser.d.ts +0 -1
  139. package/src/client/navigation-scripts/navigation-scripts.test.browser.js +0 -111
  140. package/src/client/scroll.test.browser.d.ts +0 -1
  141. package/src/client/scroll.test.browser.js +0 -31
  142. package/src/client/view-transitions.test.browser.d.ts +0 -1
  143. package/src/client/view-transitions.test.browser.js +0 -53
  144. package/src/config/README.md +0 -58
  145. package/src/config/constants.d.ts +0 -1
  146. package/src/config/constants.js +0 -1
  147. package/src/dev/README.md +0 -61
  148. package/src/dev/invalidation/README.md +0 -11
  149. package/src/dev-toolbar/README.md +0 -66
  150. package/src/diagnostics/README.md +0 -11
  151. package/src/eco/README.md +0 -776
  152. package/src/errors/README.md +0 -5
  153. package/src/global/README.md +0 -5
  154. package/src/hmr/README.md +0 -64
  155. package/src/hmr/client/build-error-overlay.test.browser.d.ts +0 -1
  156. package/src/hmr/client/build-error-overlay.test.browser.js +0 -48
  157. package/src/hmr/client/hmr-runtime.test.browser.d.ts +0 -1
  158. package/src/hmr/client/hmr-runtime.test.browser.js +0 -32
  159. package/src/hmr/entrypoint-dependency-graph.d.ts +0 -12
  160. package/src/hmr/entrypoint-dependency-graph.js +0 -27
  161. package/src/hmr/hmr-file-change-prep.d.ts +0 -9
  162. package/src/hmr/hmr-file-change-prep.js +0 -11
  163. package/src/html/README.md +0 -15
  164. package/src/html-pages/README.md +0 -104
  165. package/src/islands/README.md +0 -44
  166. package/src/page-cache/README.md +0 -17
  167. package/src/plugins/README.md +0 -53
  168. package/src/route-renderer/GRAPH.md +0 -142
  169. package/src/route-renderer/README.md +0 -160
  170. package/src/route-renderer/error-pages/README.md +0 -11
  171. package/src/route-renderer/orchestration/custom-element-scripts/README.md +0 -15
  172. package/src/route-renderer/orchestration/integration-renderer.test-fixtures.d.ts +0 -39
  173. package/src/route-renderer/orchestration/integration-renderer.test-fixtures.js +0 -94
  174. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.test-fixtures.d.ts +0 -35
  175. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.test-fixtures.js +0 -69
  176. package/src/router/README.md +0 -160
  177. package/src/router/client/link-intent.test.browser.d.ts +0 -1
  178. package/src/router/client/link-intent.test.browser.js +0 -33
  179. package/src/router/client/link-navigation-policy.test.browser.d.ts +0 -1
  180. package/src/router/client/link-navigation-policy.test.browser.js +0 -142
  181. package/src/router/client/navigation-commit.test.browser.d.ts +0 -1
  182. package/src/router/client/navigation-commit.test.browser.js +0 -116
  183. package/src/router/client/navigation-document.test.browser.d.ts +0 -1
  184. package/src/router/client/navigation-document.test.browser.js +0 -77
  185. package/src/router/client/navigation-head.test.browser.d.ts +0 -1
  186. package/src/router/client/navigation-head.test.browser.js +0 -101
  187. package/src/router/client/navigation-lifecycle.test.browser.d.ts +0 -1
  188. package/src/router/client/navigation-lifecycle.test.browser.js +0 -97
  189. package/src/router/client/navigation-view-transition.test.browser.d.ts +0 -1
  190. package/src/router/client/navigation-view-transition.test.browser.js +0 -189
  191. package/src/router/client/staged-stylesheets.test-fixtures.d.ts +0 -18
  192. package/src/router/client/staged-stylesheets.test-fixtures.js +0 -31
  193. package/src/static-site-generator/README.md +0 -67
  194. package/src/static-site-generator/static-site-generator.test-utils.d.ts +0 -2
  195. package/src/static-site-generator/static-site-generator.test-utils.js +0 -41
  196. package/src/types/README.md +0 -5
  197. package/src/utils/README.md +0 -7
  198. package/src/validation/README.md +0 -9
  199. package/src/watchers/README.md +0 -15
  200. package/src/watchers/project-watcher.test-helpers.d.ts +0 -60
  201. package/src/watchers/project-watcher.test-helpers.js +0 -108
package/src/eco/README.md DELETED
@@ -1,776 +0,0 @@
1
- # `eco` Namespace
2
-
3
- **Layer:** Contracts.
4
-
5
- A unified API for defining components, pages, and page data in EcoPages.
6
-
7
- ## Overview
8
-
9
- The `eco` namespace provides a consistent, type-safe interface for:
10
-
11
- 1. **`eco.component()`** - Factory for defining reusable components with dependencies and optional lazy-loading
12
- 2. **`eco.html()`** - Semantic alias for the document shell component (the outermost HTML wrapper)
13
- 3. **`eco.layout()`** - Semantic alias for route layout components (page-level wrappers)
14
- 4. **`eco.page()`** - Factory for defining page components with optional inline `staticPaths`, `staticProps`, and `metadata`
15
- 5. **`eco.metadata()`** - Type-safe wrapper for page metadata (legacy pattern)
16
- 6. **`eco.staticPaths()`** - Type-safe wrapper for dynamic route generation (legacy pattern)
17
- 7. **`eco.staticProps()`** - Type-safe wrapper for static data fetching (legacy pattern)
18
-
19
- ## Layout assignment
20
-
21
- Layouts are assigned explicitly on each `eco.page({ layout })` call — either one layout component or an outer→inner array. EcoPages normalizes the stack at factory time to `config.layouts` and `config.layoutEntries`.
22
-
23
- EcoPages does **not** infer layouts from `src/layouts/` file paths or route segment directories. A file under `src/layouts/` is only used when a page imports it and passes it to `layout`.
24
-
25
- ## Dependency discovery
26
-
27
- Discovery is enabled by default for modules declaring `eco.component()`, `eco.layout()`, `eco.html()`, or `eco.page()`, as well as MDX documents compiled through `@ecopages/mdx/core`.
28
-
29
- ```tsx
30
- import { eco } from '@ecopages/core';
31
- import { Counter } from './counter';
32
- import './page.css';
33
-
34
- export default eco.page({
35
- render: () => <Counter />,
36
- });
37
- ```
38
-
39
- Direct static named/default imports of local Eco Components contribute their Dependencies transitively. Configured TypeScript path aliases and relative imports are supported for both Components and CSS stylesheets (e.g., `import '@/components/button'` or `import '@/styles/main.css'`). Side-effect CSS imports become stylesheet Dependencies; the shared transform removes the imports so the existing asset pipeline owns delivery in server and browser builds. In MDX documents, top-level component and CSS imports are discovered while markdown code blocks and dynamic imports within functions are safely ignored.
40
-
41
- Discovery is conservative and module-scoped: every Eco declaration in a file shares its imported Components and styles, even when a render condition omits a Component. It does not infer which Components actually render. **Best practice:** author **one `eco.component()` per file**. Co-locating multiple components in a single file will cause all declared components in that file to share discovered dependencies.
42
-
43
- Imported Layouts contribute assets; only the explicit `layout` option controls Layout composition.
44
-
45
- Explicit `dependencies` remain supported. Explicit Components come first, followed by discovered Components in import order, with duplicate Components removed. Explicit stylesheet declarations take precedence over discovered references to the same resolved file, preserving their attributes and order. Discovered stylesheets are **not** written into `config.dependencies.stylesheets`; they stay on Component identity until collection. Inferred styles follow explicit styles and are emitted once per collection. Circular dependency traversal is guarded by Component config identity, so two Components in one file remain distinct.
46
-
47
- When a Page combines its own relative assets with a content entry, use `mergePageDependencies()`. Do not object-spread the two bags: spread copies `ownerFile` onto the other side's relative paths.
48
-
49
- ```ts
50
- import { eco, mergePageDependencies } from '@ecopages/core';
51
- import { getEntryDependencies } from 'ecopages:content/posts/server';
52
-
53
- export default eco.page({
54
- dependencies: async ({ props }) =>
55
- mergePageDependencies({ stylesheets: ['./post.css'] }, await getEntryDependencies(props.slug)),
56
- render: () => <article />,
57
- });
58
- ```
59
-
60
- Browser scripts remain explicit:
61
-
62
- ```ts
63
- scripts: [
64
- {
65
- src: './counter.script.ts',
66
- ssr: true,
67
- lazy: { 'on:visible': true },
68
- },
69
- ];
70
- ```
71
-
72
- For Lit and Ecopages JSX (Radiant hosts), `ssr: true` imports the script on the server before rendering so `customElements.define` runs without a separate value import in the component file. `lazy` controls browser delivery only; it does not suppress server import. To load eagerly in the browser, omit `lazy`. String-form `scripts: ['./file.ts']` stays browser-only unless you opt in with `{ src, ssr: true }`.
73
-
74
- Scripts listening to client navigation events (`eco:after-swap`, `eco:page-load`) should be registered as client scripts (e.g., using `scripts: ['./component.script.ts']`) or guarded by `isServer` from `@ecopages/radiant/is-server` when used in Radiant projects where `document` is defined during SSR.
75
-
76
- Named barrel re-exports (`export { Counter } from './counter'`) are followed for the imported binding only. The imported module, the factory file, and successful named re-export hops are watch paths, so editing a child Component or retargeting a barrel updates page assets without editing the importing Page. Discovery does not follow `export * from './components'`, dynamic imports, namespace imports (`import * as`), package Components/CSS, CSS Modules, or custom import attributes. `export *` would pull an entire kit into the page asset graph; keep that explicit with `dependencies.components`. Plain-function modules retain their existing behavior. Ordinary utility imports do not become browser script entries. Missing supported imports report the owner file and import specifier.
77
-
78
- ## Component ownership
79
-
80
- The effective Integration owner follows one precedence rule everywhere: `config.integration`, then the build-time `config.identity.integration`, then the containing component's owner. A component-level override therefore controls both server rendering and its Page Client Plan even when the file belongs to another Integration. Components without either declaration inherit their parent's owner.
81
-
82
- Component factories read their active render context from `eco/`. The route renderer opens that context for each render and supplies the foreign-child runtime used to hand off components owned by another Integration. Nested and overlapping renders keep their own context across asynchronous work.
83
-
84
- ## Component Patterns
85
-
86
- EcoPages supports two approaches for creating components, each suited for different use cases:
87
-
88
- ### Simple JSX Functions (Static Components)
89
-
90
- For purely presentational components without client-side interactivity, use plain JSX functions. This pattern works best with utility-first CSS frameworks like Tailwind, where styles are applied via class names:
91
-
92
- ```tsx
93
- import type { PropsWithChildren } from '@kitajs/html';
94
- import { cn } from 'your-library';
95
-
96
- type CardProps = PropsWithChildren<{
97
- class?: string;
98
- }>;
99
-
100
- export function Card({ children, class: className }: CardProps) {
101
- return <div class={cn('p-6 rounded-2xl border border-white/10 bg-zinc-900/30', className)}>{children}</div>;
102
- }
103
- ```
104
-
105
- **When to use:**
106
-
107
- - Static/presentational UI (cards, alerts, badges, layout primitives)
108
- - Projects using utility-first CSS (Tailwind, UnoCSS, etc.)
109
- - Components that only render HTML without scripts or dedicated stylesheets
110
- - Zero runtime cost - just functions returning markup
111
-
112
- > **Note:** If your component requires a dedicated CSS file, use `eco.component()` instead to manage the stylesheet dependency.
113
-
114
- ### Plain React Components
115
-
116
- React components with hooks and Tailwind CSS work out of the box without `eco.component()`. Standard React components can be used directly:
117
-
118
- ```tsx
119
- import { useEffect, useState } from 'react';
120
-
121
- export function ThemeToggle() {
122
- const [mounted, setMounted] = useState(false);
123
- const [isDark, setIsDark] = useState(false);
124
-
125
- useEffect(() => {
126
- setMounted(true);
127
- const theme = localStorage.getItem('theme');
128
- const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
129
-
130
- if (theme === 'dark' || (!theme && prefersDark)) {
131
- setIsDark(true);
132
- document.documentElement.classList.add('dark');
133
- } else {
134
- setIsDark(false);
135
- document.documentElement.classList.remove('dark');
136
- }
137
- }, []);
138
-
139
- const toggleTheme = () => {
140
- const newTheme = !isDark;
141
- setIsDark(newTheme);
142
-
143
- if (newTheme) {
144
- document.documentElement.classList.add('dark');
145
- localStorage.setItem('theme', 'dark');
146
- } else {
147
- document.documentElement.classList.remove('dark');
148
- localStorage.setItem('theme', 'light');
149
- }
150
- };
151
-
152
- if (!mounted) return null;
153
-
154
- return (
155
- <button
156
- onClick={toggleTheme}
157
- className="p-2 rounded-md hover:bg-surface-200 dark:hover:bg-surface-800 transition-colors"
158
- aria-label="Toggle theme"
159
- >
160
- {isDark ? <SunIcon /> : <MoonIcon />}
161
- </button>
162
- );
163
- }
164
- ```
165
-
166
- **When to use:**
167
-
168
- - React components with hooks (`useState`, `useEffect`, etc.)
169
- - Components styled with Tailwind CSS classes
170
- - Interactive UI that doesn't require external scripts or dedicated stylesheets
171
-
172
- > **Note:** Use `eco.component()` only when you need to manage external stylesheets, scripts, or lazy loading. For React components relying solely on hooks and Tailwind, plain functions are simpler and sufficient.
173
-
174
- ### `eco.component()` (Interactive Components)
175
-
176
- For components that need dependencies, scripts, or lazy loading:
177
-
178
- ```tsx
179
- import { eco } from '@ecopages/core';
180
-
181
- export const Counter = eco.component({
182
- dependencies: {
183
- stylesheets: ['./counter.css'],
184
- scripts: [{ src: './counter.script.ts', lazy: { 'on:interaction': 'mouseenter,focusin' } }],
185
- },
186
- render: ({ count }) => <my-counter count={count} />,
187
- });
188
- ```
189
-
190
- **When to use:**
191
-
192
- - Components with client-side interactivity
193
- - Components requiring scripts or stylesheets
194
- - Lazy-loaded components with hydration strategies
195
- - Web components or custom elements
196
-
197
- ### Comparison
198
-
199
- | Aspect | Simple JSX | Plain React | `eco.component()` |
200
- | -------------------- | ---------- | -------------- | ----------------- |
201
- | React hooks | No | Yes | Yes |
202
- | Scripts/Stylesheets | No | No | Yes |
203
- | Lazy loading | No | No | Yes |
204
- | Hydration strategies | No | No | Yes |
205
- | Runtime cost | Zero | Minimal | Minimal |
206
- | Use case | Static UI | Interactive UI | Advanced UI |
207
-
208
- All patterns can coexist in the same project. Use the right tool for the job.
209
-
210
- ## React Support
211
-
212
- EcoPages fully supports React components. You can use `eco.component()` with React to managing dependencies and hydration while maintaining type safety.
213
-
214
- Since React components return `ReactNode` or `JSX.Element` (not `EcoPagesElement`), you need to specify the return type generic:
215
-
216
- ```tsx
217
- import { eco } from '@ecopages/core';
218
- import type { ReactNode } from 'react';
219
-
220
- type ButtonProps = {
221
- label: string;
222
- onClick?: () => void;
223
- };
224
-
225
- // Specify ReactNode as the second generic argument
226
- export const Button = eco.component<ButtonProps, ReactNode>({
227
- dependencies: {
228
- stylesheets: ['./button.css'],
229
- },
230
- render: ({ label, onClick }) => (
231
- <button className="eco-button" onClick={onClick}>
232
- {label}
233
- </button>
234
- ),
235
- });
236
- ```
237
-
238
- You can also use it for pages:
239
-
240
- ```tsx
241
- import { eco } from '@ecopages/core';
242
- import type { JSX } from 'react';
243
-
244
- export default eco.page<Props, JSX.Element>({
245
- layout: BaseLayout,
246
- render: () => <h1>Hello React</h1>,
247
- });
248
- ```
249
-
250
- ## Two Patterns for Pages
251
-
252
- ### Consolidated API (Recommended)
253
-
254
- Define everything in one place:
255
-
256
- ```tsx
257
- import { eco } from '@ecopages/core';
258
-
259
- export default eco.page<BlogPostProps>({
260
- layout: BaseLayout,
261
- staticPaths: async () => ({ paths: getAllSlugs() }),
262
- staticProps: async ({ pathname }) => ({
263
- props: { post: await getPost(pathname.params.slug) },
264
- }),
265
- metadata: ({ props: { post } }) => ({
266
- title: post.title,
267
- description: post.excerpt,
268
- }),
269
- render: ({ post }) => <article>{post.content}</article>,
270
- });
271
- ```
272
-
273
- ### Separate Exports (Legacy)
274
-
275
- The traditional pattern with named exports:
276
-
277
- ```tsx
278
- import { eco } from '@ecopages/core';
279
-
280
- export const getStaticPaths = eco.staticPaths(async () => ({
281
- paths: getAllSlugs(),
282
- }));
283
-
284
- export const getStaticProps = eco.staticProps(async ({ pathname }) => ({
285
- props: { post: await getPost(pathname.params.slug) },
286
- }));
287
-
288
- export const getMetadata = eco.metadata<typeof getStaticProps>(({ props: { post } }) => ({
289
- title: post.title,
290
- description: post.excerpt,
291
- }));
292
-
293
- export default eco.page<typeof getStaticProps>({
294
- render: ({ post }) => <article>{post.content}</article>,
295
- });
296
- ```
297
-
298
- Both patterns work and can be mixed - the renderer checks for attached properties first, then falls back to named exports.
299
-
300
- ## API Reference
301
-
302
- ### `eco.html()`
303
-
304
- Creates the document shell component — the outermost HTML wrapper rendered once per page. Semantically equivalent to `eco.component()` but signals intent to tooling and readers that this component owns the full document structure (`<html>`, `<head>`, `<body>`).
305
-
306
- ```tsx
307
- import { eco } from '@ecopages/core';
308
-
309
- export const Document = eco.html({
310
- dependencies: {
311
- stylesheets: ['./document.css'],
312
- },
313
- render: ({ children, metadata }) => (
314
- <html lang="en">
315
- <head>
316
- <title>{metadata?.title ?? 'EcoPages'}</title>
317
- </head>
318
- <body>{children}</body>
319
- </html>
320
- ),
321
- });
322
- ```
323
-
324
- ### `eco.layout()`
325
-
326
- Creates a route layout component — a wrapper rendered around page content. Semantically equivalent to `eco.component()` but clearly communicates that the component is intended to be used as a `layout` in `eco.page()`.
327
-
328
- ```tsx
329
- import { eco } from '@ecopages/core';
330
-
331
- export const BaseLayout = eco.layout({
332
- dependencies: {
333
- stylesheets: ['./base-layout.css'],
334
- scripts: ['./base-layout.script.ts'],
335
- },
336
- render: ({ children }) => <main>{children}</main>,
337
- });
338
- ```
339
-
340
- Use `eco.layout()` components as the `layout` option in `eco.page()`:
341
-
342
- ```tsx
343
- export default eco.page({
344
- layout: BaseLayout,
345
- render: () => <h1>Hello</h1>,
346
- });
347
- ```
348
-
349
- **Nested layouts (outer → inner):**
350
-
351
- ```tsx
352
- export default eco.page({
353
- layout: [MarketingShell, DocsShell],
354
- render: () => <h1>Hello</h1>,
355
- });
356
- ```
357
-
358
- A single layout remains equivalent to a one-element array. Normalization stores the stack on `config.layouts` and `config.layoutEntries` at factory time.
359
-
360
- ### `eco.component()`
361
-
362
- Define a reusable component with dependencies.
363
-
364
- ```tsx
365
- import { eco } from '@ecopages/core';
366
-
367
- export const BaseLayout = eco.component({
368
- dependencies: {
369
- stylesheets: ['./base-layout.css'],
370
- scripts: ['./base-layout.script.ts'],
371
- },
372
- render: ({ children, class: className }) => (
373
- <html>
374
- <body class={className}>{children}</body>
375
- </html>
376
- ),
377
- });
378
- ```
379
-
380
- **With lazy-loaded scripts:**
381
-
382
- ```tsx
383
- export const Counter = eco.component({
384
- dependencies: {
385
- stylesheets: ['./counter.css'], // loaded immediately
386
- scripts: [
387
- { src: './counter.script.ts', lazy: { 'on:interaction': 'mouseenter,focusin' } }, // loaded on trigger
388
- ],
389
- },
390
- render: ({ count }) => <my-counter count={count}></my-counter>,
391
- });
392
- ```
393
-
394
- #### Lazy Loading Options
395
-
396
- Lazy loading is configured per dependency entry in `dependencies.scripts`:
397
-
398
- ```tsx
399
- // Load on idle
400
- scripts: [{ src: './component.script.ts', lazy: { 'on:idle': true } }];
401
-
402
- // Load on interaction
403
- scripts: [{ src: './component.script.ts', lazy: { 'on:interaction': 'mouseenter,focusin' } }];
404
-
405
- // Load on visibility
406
- scripts: [{ src: './component.script.ts', lazy: { 'on:visible': true } }]; // or viewport margin like '100px'
407
- ```
408
-
409
- Each entry can define its own trigger, so mixed strategies in one component are supported.
410
-
411
- At render time, the component's root element receives a `data-eco-trigger` attribute, and the page carries one
412
- global injector map that tells the [`scripts-injector`](https://github.com/ecopages/scripts-injector) runtime which
413
- scripts to load for each trigger.
414
-
415
- ### `eco.page()`
416
-
417
- Define a page component with optional inline static functions.
418
-
419
- **Consolidated API (everything in one place):**
420
-
421
- ```tsx
422
- type BlogPostProps = { slug: string; title: string; text: string };
423
-
424
- export default eco.page<BlogPostProps>({
425
- layout: BaseLayout,
426
-
427
- // Generate paths for dynamic routes
428
- staticPaths: async () => ({
429
- paths: posts.map((p) => ({ params: { slug: p.slug } })),
430
- }),
431
-
432
- // Fetch data at build time
433
- staticProps: async ({ pathname }) => ({
434
- props: {
435
- slug: pathname.params.slug as string,
436
- title: post.title,
437
- text: post.text,
438
- },
439
- }),
440
-
441
- // Generate page metadata
442
- metadata: ({ props: { title, slug } }) => ({
443
- title: `${title} | My Blog`,
444
- description: `Read about ${slug}`,
445
- }),
446
-
447
- // Render the page
448
- render: ({ title, text }) => (
449
- <article>
450
- <h1>{title}</h1>
451
- <p>{text}</p>
452
- </article>
453
- ),
454
- });
455
- ```
456
-
457
- **Simple page without data fetching:**
458
-
459
- ```tsx
460
- export default eco.page({
461
- layout: BaseLayout,
462
- metadata: () => ({
463
- title: 'Home',
464
- description: 'Welcome to EcoPages',
465
- }),
466
- render: () => <h1>Welcome</h1>,
467
- });
468
- ```
469
-
470
- **With layout:**
471
-
472
- ```tsx
473
- export default eco.page({
474
- layout: BaseLayout, // Wraps render output automatically
475
- render: () => <h1>Content</h1>,
476
- });
477
- ```
478
-
479
- ### `eco.metadata()`
480
-
481
- Type-safe wrapper for page metadata (for separate exports pattern).
482
-
483
- ```tsx
484
- export const getMetadata = eco.metadata<typeof getStaticProps>(({ props: { post } }) => ({
485
- title: post.title,
486
- description: post.excerpt,
487
- }));
488
- ```
489
-
490
- ### `eco.staticPaths()`
491
-
492
- Type-safe wrapper for dynamic route generation (for separate exports pattern).
493
-
494
- ```tsx
495
- export const getStaticPaths = eco.staticPaths(async () => ({
496
- paths: posts.map((p) => ({ params: { slug: p.slug } })),
497
- }));
498
- ```
499
-
500
- ### `eco.staticProps()`
501
-
502
- Type-safe wrapper for static data fetching (for separate exports pattern).
503
-
504
- ```tsx
505
- export const getStaticProps = eco.staticProps(async ({ pathname }) => ({
506
- props: { post: await getPost(pathname.params.slug) },
507
- }));
508
- ```
509
-
510
- ## Complete Examples
511
-
512
- ### Dynamic Blog Post (Consolidated API)
513
-
514
- ```tsx
515
- // pages/blog/[slug].tsx
516
- import { eco } from '@ecopages/core';
517
- import { BaseLayout } from '@/layouts/base-layout';
518
- import { getBlogPost, getAllBlogPostSlugs, getAuthor } from '@/mocks/data';
519
-
520
- type BlogPostProps = {
521
- slug: string;
522
- title: string;
523
- text: string;
524
- authorId: string;
525
- authorName: string;
526
- };
527
-
528
- export default eco.page<BlogPostProps>({
529
- layout: BaseLayout,
530
-
531
- staticPaths: async () => {
532
- return { paths: getAllBlogPostSlugs() };
533
- },
534
-
535
- staticProps: async ({ pathname }) => {
536
- const slug = pathname.params.slug as string;
537
- const post = getBlogPost(slug);
538
- if (!post) throw new Error(`Post not found: ${slug}`);
539
- const author = getAuthor(post.authorId);
540
- return {
541
- props: {
542
- slug,
543
- title: post.title,
544
- text: post.text,
545
- authorId: post.authorId,
546
- authorName: author?.name ?? 'Unknown',
547
- },
548
- };
549
- },
550
-
551
- metadata: ({ props: { title, slug } }) => ({
552
- title: `${title} | My Blog`,
553
- description: `Read the blog post: ${slug}`,
554
- }),
555
-
556
- render: ({ title, text, authorId, authorName }) => (
557
- <article>
558
- <h1>{title}</h1>
559
- <p>
560
- By <a href={`/blog/author/${authorId}`}>{authorName}</a>
561
- </p>
562
- <div>{text}</div>
563
- </article>
564
- ),
565
- });
566
- ```
567
-
568
- ### Lazy-Loaded Component
569
-
570
- ```tsx
571
- // components/counter/counter.tsx
572
- import { eco } from '@ecopages/core';
573
-
574
- export const Counter = eco.component({
575
- dependencies: {
576
- stylesheets: ['./counter.css'],
577
- scripts: [{ src: './counter.script.ts', lazy: { 'on:interaction': 'mouseenter,focusin' } }],
578
- },
579
- render: ({ count }) => <my-counter count={count} />,
580
- });
581
- ```
582
-
583
- **HTML Output:**
584
-
585
- ```html
586
- <my-counter count="5" data-eco-trigger="eco-trigger-1a2b3c">
587
- <!-- SSR content -->
588
- </my-counter>
589
- ```
590
-
591
- The page also carries one `<script type="ecopages/global-injector-map">` that maps each `data-eco-trigger` id to its trigger and script URLs.
592
-
593
- ### Page with Lazy Component
594
-
595
- ```tsx
596
- // pages/index.tsx
597
- import { eco } from '@ecopages/core';
598
- import { BaseLayout } from '@/layouts/base-layout';
599
- import { Counter } from '@/components/counter';
600
-
601
- export default eco.page({
602
- layout: BaseLayout,
603
- metadata: () => ({
604
- title: 'Home',
605
- description: 'Welcome to EcoPages',
606
- }),
607
- render: () => (
608
- <>
609
- <h1>Welcome</h1>
610
- <Counter count={5} />
611
- </>
612
- ),
613
- });
614
- ```
615
-
616
- The static `Counter` import is discovered automatically. You do not list it again in `dependencies.components`. Lazy scripts stay on the Component.
617
-
618
- ## Type Definitions
619
-
620
- ```typescript
621
- type LazyTrigger = { 'on:idle': true } | { 'on:interaction': string } | { 'on:visible': true | string };
622
-
623
- type DependencyEntry = {
624
- src?: string;
625
- content?: string;
626
- lazy?: LazyTrigger;
627
- ssr?: boolean;
628
- attributes?: Record<string, string>;
629
- };
630
-
631
- interface EcoComponentDependencies {
632
- scripts?: Array<string | DependencyEntry>;
633
- stylesheets?: Array<string | DependencyEntry>;
634
- modules?: string[];
635
- /** Declared eco components only — see `EcoComponent`. */
636
- components?: EcoComponent[];
637
- }
638
-
639
- type FileOwnedDependencyContribution = EcoComponentDependencies & {
640
- ownerFile?: string;
641
- };
642
-
643
- type PageDependenciesResult = FileOwnedDependencyContribution & {
644
- contributions?: FileOwnedDependencyContribution[];
645
- };
646
-
647
- type GetPageDependencies<T> = (context: {
648
- props: PagePropsFor<T>;
649
- params?: PageParams;
650
- query?: PageQuery;
651
- }) => PageDependenciesResult | undefined | Promise<PageDependenciesResult | undefined>;
652
-
653
- // Shared base option shape used by component(), html(), and layout()
654
- interface ComponentOptions<P, E = EcoPagesElement> {
655
- componentDir?: string;
656
- dependencies?: EcoComponentDependencies;
657
- render: (props: P) => E;
658
- }
659
-
660
- // html() and layout() accept the same options as component() but return
661
- // narrower types to signal intent (EcoHtmlComponent / EcoLayoutComponent).
662
- type HtmlOptions<E = EcoPagesElement> = ComponentOptions<Record<string, unknown>, E>;
663
- type LayoutOptions<E = EcoPagesElement> = ComponentOptions<LayoutProps<E>, E>;
664
-
665
- interface PageOptions<T, E = EcoPagesElement> {
666
- componentDir?: string;
667
- dependencies?: EcoComponentDependencies | GetPageDependencies<T>;
668
- layout?: EcoComponent<{ children: E }>;
669
- staticPaths?: GetStaticPaths;
670
- staticProps?: GetStaticProps<T>;
671
- metadata?: GetMetadata<T>;
672
- render: (props: PagePropsFor<T>) => E;
673
- }
674
-
675
- type EcoPageComponent<T> = EcoComponent<PagePropsFor<T>> & {
676
- staticPaths?: GetStaticPaths;
677
- staticProps?: GetStaticProps<T>;
678
- metadata?: GetMetadata<T>;
679
- };
680
-
681
- type PagePropsFor<T> =
682
- T extends GetStaticProps<infer P>
683
- ? P & { params?: PageParams; query?: PageQuery }
684
- : T & { params?: PageParams; query?: PageQuery };
685
- ```
686
-
687
- ## Benefits
688
-
689
- ### 1. Discoverability
690
-
691
- ```tsx
692
- import { eco } from '@ecopages/core';
693
-
694
- eco. // IDE shows: component, html, layout, page, metadata, staticPaths, staticProps
695
- ```
696
-
697
- ### 2. Type Safety
698
-
699
- Props flow through the system automatically:
700
-
701
- ```tsx
702
- export default eco.page<{ title: string }>({
703
- staticProps: async () => ({ props: { title: 'Hello' } }),
704
- render: ({ title }) => <h1>{title}</h1>, // ✓ TypeScript knows `title` is a string
705
- });
706
- ```
707
-
708
- ### 3. Single Source of Truth (Consolidated API)
709
-
710
- All page configuration in one place - no hunting for separate exports:
711
-
712
- ```tsx
713
- export default eco.page<Props>({
714
- layout: BaseLayout,
715
- staticPaths: async () => ...,
716
- staticProps: async () => ...,
717
- metadata: () => ...,
718
- render: () => ...,
719
- });
720
- ```
721
-
722
- ### 4. Backwards Compatible
723
-
724
- Both patterns work side by side - choose what works best for your use case.
725
-
726
- ## Design Decisions
727
-
728
- ### Why consolidated API?
729
-
730
- | Aspect | Separate Exports | Consolidated API |
731
- | ------------------ | ---------------------- | ---------------- |
732
- | Discoverability | Scan file for exports | All in one place |
733
- | Type inference | Manual with `typeof` | Automatic flow |
734
- | Colocated concerns | Spread across file | Single object |
735
- | Flexibility | Mix with other exports | Self-contained |
736
-
737
- ### Why both patterns?
738
-
739
- - **Consolidated** is cleaner for new pages
740
- - **Separate exports** provides flexibility and follows Next.js conventions
741
- - Backwards compatibility with existing code
742
-
743
- ## Implementation Notes
744
-
745
- The renderer checks for attached properties first:
746
-
747
- ```typescript
748
- // Check for attached static functions (consolidated API) or named exports (legacy)
749
- const getStaticProps = Page.staticProps ?? module.getStaticProps;
750
- const getMetadata = Page.metadata ?? module.getMetadata;
751
- ```
752
-
753
- This ensures both patterns work seamlessly.
754
-
755
- ## Migration
756
-
757
- Pages can be migrated incrementally:
758
-
759
- ```tsx
760
- // Before (separate exports)
761
- export const getStaticProps = ...
762
- export const getMetadata = ...
763
- export default Page;
764
-
765
- // After (consolidated)
766
- export default eco.page({
767
- staticProps: ...,
768
- metadata: ...,
769
- render: ...,
770
- });
771
- ```
772
-
773
- ## References
774
-
775
- - [scripts-injector](https://github.com/ecopages/scripts-injector) - Custom element for lazy script loading
776
- - [Islands Architecture](https://www.patterns.dev/posts/islands-architecture) - Pattern inspiration