@ecopages/core 0.4.0 → 0.6.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 (163) hide show
  1. package/README.md +19 -15
  2. package/package.json +13 -4
  3. package/src/adapters/create-app.js +9 -5
  4. package/src/adapters/node/create-app.d.ts +18 -16
  5. package/src/adapters/node/create-app.js +26 -30
  6. package/src/adapters/node/server-adapter.d.ts +26 -9
  7. package/src/adapters/node/server-adapter.js +38 -8
  8. package/src/adapters/shared/hmr/hmr-manager.js +3 -2
  9. package/src/adapters/shared/http/api-request-pipeline.js +2 -2
  10. package/src/adapters/shared/http/dist-file-handler.js +25 -7
  11. package/src/adapters/shared/runtime/render-context.d.ts +2 -1
  12. package/src/adapters/shared/runtime/render-context.js +18 -21
  13. package/src/adapters/shared/runtime/runtime-server-lifecycle.d.ts +4 -3
  14. package/src/adapters/shared/runtime/runtime-server-lifecycle.js +6 -4
  15. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +6 -1
  16. package/src/adapters/shared/runtime/server-request-pipeline.js +11 -10
  17. package/src/adapters/shared/runtime/server-route-handler.js +4 -4
  18. package/src/adapters/shared/runtime/server-static-builder.d.ts +11 -11
  19. package/src/adapters/shared/runtime/server-static-builder.js +37 -18
  20. package/src/assets/app-browser-client-build.js +8 -21
  21. package/src/assets/app-browser-client-manifest.d.ts +1 -4
  22. package/src/assets/app-browser-client-manifest.js +6 -78
  23. package/src/assets/asset-processing-service/processors/script/file-script.processor.d.ts +2 -2
  24. package/src/assets/asset-processing-service/processors/script/file-script.processor.js +2 -2
  25. package/src/assets/browser-asset-output.d.ts +1 -1
  26. package/src/assets/browser-asset-output.js +1 -1
  27. package/src/build/app-build-manifest-runtime.d.ts +11 -1
  28. package/src/build/app-build-manifest-runtime.js +17 -3
  29. package/src/build/cache/pages-unified-graph-build.d.ts +32 -35
  30. package/src/build/cache/pages-unified-graph-build.js +206 -124
  31. package/src/build/cache/server-module-entries.d.ts +35 -0
  32. package/src/build/cache/server-module-entries.js +109 -0
  33. package/src/build/contracts/build-contracts.d.ts +5 -0
  34. package/src/build/contracts/content-virtual-modules.d.ts +9 -3
  35. package/src/build/contracts/content-virtual-modules.js +11 -5
  36. package/src/build/contracts.d.ts +1 -1
  37. package/src/build/contracts.js +1 -1
  38. package/src/build/copy-server-files.d.ts +10 -0
  39. package/src/build/copy-server-files.js +37 -0
  40. package/src/build/preserve-import-meta-transform.d.ts +1 -1
  41. package/src/build/preserve-import-meta-transform.js +1 -1
  42. package/src/build/production-build-id.d.ts +9 -0
  43. package/src/build/production-build-id.js +19 -0
  44. package/src/build/production-dist-complete.d.ts +5 -0
  45. package/src/build/production-dist-complete.js +101 -0
  46. package/src/build/production-route-list.d.ts +26 -0
  47. package/src/build/production-route-list.js +78 -0
  48. package/src/build/rolldown/rolldown-adapter-helpers.d.ts +2 -2
  49. package/src/build/rolldown/rolldown-adapter-helpers.js +56 -4
  50. package/src/build/rolldown/rolldown-build-adapter.js +1 -1
  51. package/src/build/rolldown/rolldown-plugin-bridge.js +2 -2
  52. package/src/build/runtime/build-request-identity.js +2 -1
  53. package/src/build/runtime/build-request-policy.d.ts +3 -2
  54. package/src/build/runtime/build-request-policy.js +5 -3
  55. package/src/build/server/import-view-module.d.ts +11 -0
  56. package/src/build/server/import-view-module.js +21 -0
  57. package/src/build/server/imported-view-plugin.d.ts +16 -0
  58. package/src/build/server/imported-view-plugin.js +59 -0
  59. package/src/build/server/page-module-import.service.d.ts +19 -20
  60. package/src/build/server/page-module-import.service.js +65 -36
  61. package/src/build/server/resolve-static-view.d.ts +9 -0
  62. package/src/build/server/resolve-static-view.js +28 -0
  63. package/src/build/server/route-module-build-cache-registry.d.ts +5 -3
  64. package/src/build/server/route-module-build-cache-registry.js +5 -3
  65. package/src/build/server/server-modules-manifest.d.ts +51 -0
  66. package/src/build/server/server-modules-manifest.js +129 -0
  67. package/src/build/server/view-reference.d.ts +38 -0
  68. package/src/build/server/view-reference.js +112 -0
  69. package/src/build/server-bundle-deploy-manifest.d.ts +9 -9
  70. package/src/build/server-bundle-deploy-manifest.js +24 -28
  71. package/src/build.d.ts +4 -2
  72. package/src/build.js +4 -2
  73. package/src/config/assembly/app-runtime.d.ts +15 -2
  74. package/src/config/assembly/app-runtime.js +3 -1
  75. package/src/config/assembly/finalize-config.js +64 -13
  76. package/src/config/index.d.ts +1 -0
  77. package/src/config/index.js +1 -0
  78. package/src/config/internal-types.d.ts +6 -0
  79. package/src/config/load-eco-config.d.ts +1 -0
  80. package/src/config/load-eco-config.js +11 -2
  81. package/src/config/resolve-eco-config-path.d.ts +2 -1
  82. package/src/config/resolve-eco-config-path.js +21 -15
  83. package/src/config/user-config-types.d.ts +9 -2
  84. package/src/dev/transform-server/dev-transform-server.js +1 -1
  85. package/src/dev/transform-server/dev-transform-vendor-registry.d.ts +29 -6
  86. package/src/dev/transform-server/dev-transform-vendor-registry.js +101 -53
  87. package/src/errors/http-error.d.ts +9 -0
  88. package/src/errors/http-error.js +11 -0
  89. package/src/html/html-transformer.service.d.ts +0 -21
  90. package/src/html/html-transformer.service.js +0 -32
  91. package/src/html-pages/html-page-module.d.ts +19 -0
  92. package/src/html-pages/html-page-module.js +66 -13
  93. package/src/html-pages/html-page-renderer.d.ts +6 -1
  94. package/src/html-pages/html-page-renderer.js +14 -6
  95. package/src/html-pages/html-pages.plugin.d.ts +10 -0
  96. package/src/html-pages/html-pages.plugin.js +7 -1
  97. package/src/index.d.ts +2 -0
  98. package/src/index.js +2 -0
  99. package/src/integration.d.ts +2 -2
  100. package/src/integration.js +1 -1
  101. package/src/islands/island-host.d.ts +1 -2
  102. package/src/islands/island-host.js +1 -2
  103. package/src/page-cache/page-cache-service.d.ts +8 -0
  104. package/src/page-cache/page-cache-service.js +12 -0
  105. package/src/plugins/integration-plugin.d.ts +34 -7
  106. package/src/plugins/integration-plugin.js +14 -2
  107. package/src/plugins/processor.d.ts +18 -1
  108. package/src/plugins/processor.js +20 -1
  109. package/src/plugins/server-dom.d.ts +29 -0
  110. package/src/plugins/server-dom.js +36 -0
  111. package/src/plugins/tsconfig-import-resolver.d.ts +3 -1
  112. package/src/plugins/tsconfig-import-resolver.js +4 -2
  113. package/src/processor.d.ts +1 -1
  114. package/src/route-renderer/error-pages/error-page-renderer.d.ts +6 -4
  115. package/src/route-renderer/error-pages/error-page-renderer.js +9 -5
  116. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.d.ts +2 -44
  117. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.js +14 -89
  118. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.d.ts +4 -16
  119. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.js +2 -10
  120. package/src/route-renderer/orchestration/foreign-child/render-session.d.ts +3 -5
  121. package/src/route-renderer/orchestration/integration-renderer.d.ts +21 -44
  122. package/src/route-renderer/orchestration/integration-renderer.js +69 -117
  123. package/src/route-renderer/orchestration/ownership-graph/page-client-browser-assets.d.ts +3 -4
  124. package/src/route-renderer/orchestration/ownership-graph/page-client-browser-assets.js +4 -15
  125. package/src/route-renderer/orchestration/ownership-graph/prepared-graph-membership.d.ts +22 -0
  126. package/src/route-renderer/orchestration/ownership-graph/prepared-graph-membership.js +45 -0
  127. package/src/route-renderer/orchestration/page-browser-graph/grouped-graph-build-plan.d.ts +0 -1
  128. package/src/route-renderer/orchestration/page-browser-graph/missing-production-browser-graph.d.ts +21 -0
  129. package/src/route-renderer/orchestration/page-browser-graph/missing-production-browser-graph.js +31 -0
  130. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph.service.js +58 -24
  131. package/src/route-renderer/orchestration/page-browser-graph/route-instance-key.d.ts +12 -0
  132. package/src/route-renderer/orchestration/page-browser-graph/route-instance-key.js +55 -0
  133. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.js +4 -3
  134. package/src/router/server/route-registry.d.ts +23 -1
  135. package/src/router/server/route-registry.js +41 -14
  136. package/src/static-site-generator/production-page-browser-graph-prebuild.d.ts +8 -2
  137. package/src/static-site-generator/production-page-browser-graph-prebuild.js +14 -13
  138. package/src/static-site-generator/static-site-generator.d.ts +19 -3
  139. package/src/static-site-generator/static-site-generator.js +78 -40
  140. package/src/types/build-types.d.ts +6 -0
  141. package/src/types/contracts.d.ts +26 -35
  142. package/src/types/eco-api-types.d.ts +1 -1
  143. package/src/types/public-types.d.ts +1 -0
  144. package/src/types/view-reference.d.ts +31 -0
  145. package/src/types/view-reference.js +15 -0
  146. package/src/utils/additional-watch-paths.d.ts +3 -3
  147. package/src/utils/additional-watch-paths.js +3 -1
  148. package/src/utils/resolve-entry-file.d.ts +4 -2
  149. package/src/utils/resolve-entry-file.js +4 -2
  150. package/src/utils/root-relative-path.d.ts +4 -0
  151. package/src/utils/root-relative-path.js +8 -0
  152. package/src/utils/server-bundle-context.d.ts +14 -0
  153. package/src/utils/server-bundle-context.js +45 -0
  154. package/src/watchers/project-watcher-ignore.d.ts +2 -5
  155. package/src/watchers/project-watcher-ignore.js +2 -5
  156. package/src/watchers/project-watcher.d.ts +9 -7
  157. package/src/watchers/project-watcher.js +100 -52
  158. package/src/watchers/workspace-package-watch-roots.d.ts +4 -4
  159. package/src/watchers/workspace-package-watch-roots.js +41 -25
  160. package/src/build/server/view-module-loader.d.ts +0 -10
  161. package/src/build/server/view-module-loader.js +0 -46
  162. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-merge.utils.d.ts +0 -12
  163. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-merge.utils.js +0 -32
@@ -0,0 +1,37 @@
1
+ import path from 'node:path';
2
+ import { fileSystem } from '@ecopages/file-system';
3
+ import { getServerBundleOutputPaths } from './server-bundle-deploy-manifest.js';
4
+ /**
5
+ * Copies `serverFiles` globs into `dist/server/` under each file's basename.
6
+ *
7
+ * @remarks
8
+ * Production `import.meta.dirname` is the emitted module directory, so declared
9
+ * files land next to those modules. Two matches that share a basename fail the
10
+ * build.
11
+ */
12
+ export async function copyDeclaredServerFiles(appConfig) {
13
+ const patterns = appConfig.serverFiles;
14
+ if (!patterns || patterns.length === 0) {
15
+ return;
16
+ }
17
+ const { serverOutdir } = getServerBundleOutputPaths(appConfig);
18
+ const matches = await fileSystem.glob(patterns, { cwd: appConfig.rootDir });
19
+ const copiedNames = new Map();
20
+ for (const relative of matches) {
21
+ const source = path.resolve(appConfig.rootDir, relative);
22
+ if (!fileSystem.exists(source) || fileSystem.isDirectory(source)) {
23
+ continue;
24
+ }
25
+ const name = path.basename(relative);
26
+ const existing = copiedNames.get(name);
27
+ if (existing) {
28
+ throw new Error(`serverFiles copy collision: "${existing}" and "${relative}" both copy to ${name} in dist/server/. Use unique names, or move the files to public/.`);
29
+ }
30
+ const destination = path.join(serverOutdir, name);
31
+ if (fileSystem.exists(destination)) {
32
+ throw new Error(`serverFiles copy would overwrite ${name} in dist/server/. Use a unique basename, or move the file to public/.`);
33
+ }
34
+ copiedNames.set(name, relative);
35
+ fileSystem.copyFile(source, destination);
36
+ }
37
+ }
@@ -18,7 +18,7 @@ export declare function realpathOfDirectory(dir: string): string;
18
18
  * @remarks
19
19
  * A bundled module would otherwise see the location of its output chunk, so a
20
20
  * lookup such as Core reading `../../../package.json` or a page globbing
21
- * `import.meta.dirname` would search `dist/.server/` or `.eco/.server-modules/`.
21
+ * `import.meta.dirname` would search `dist/server/` or `.eco/.server-modules/`.
22
22
  * The rewrite is a path relative to the output chunk's own `import.meta`, so
23
23
  * the output keeps working after it moves together with the sources. It
24
24
  * assumes flat output file names in `runtimeDir`, which the external package
@@ -102,7 +102,7 @@ function collectImportMetaEdits(code, id, runtimeDir) {
102
102
  * @remarks
103
103
  * A bundled module would otherwise see the location of its output chunk, so a
104
104
  * lookup such as Core reading `../../../package.json` or a page globbing
105
- * `import.meta.dirname` would search `dist/.server/` or `.eco/.server-modules/`.
105
+ * `import.meta.dirname` would search `dist/server/` or `.eco/.server-modules/`.
106
106
  * The rewrite is a path relative to the output chunk's own `import.meta`, so
107
107
  * the output keeps working after it moves together with the sources. It
108
108
  * assumes flat output file names in `runtimeDir`, which the external package
@@ -0,0 +1,9 @@
1
+ import type { EcoPagesAppConfig } from '../config/internal-types.js';
2
+ /**
3
+ * Returns the build id for this production export, creating one if needed.
4
+ *
5
+ * @remarks
6
+ * Every production manifest written during one `ecopages build` shares this
7
+ * id so `ecopages start` can refuse a mixed `dist/`.
8
+ */
9
+ export declare function ensureProductionBuildId(appConfig: EcoPagesAppConfig): string;
@@ -0,0 +1,19 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ /**
3
+ * Returns the build id for this production export, creating one if needed.
4
+ *
5
+ * @remarks
6
+ * Every production manifest written during one `ecopages build` shares this
7
+ * id so `ecopages start` can refuse a mixed `dist/`.
8
+ */
9
+ export function ensureProductionBuildId(appConfig) {
10
+ const runtime = appConfig.appRuntime;
11
+ if (runtime?.productionBuildId) {
12
+ return runtime.productionBuildId;
13
+ }
14
+ const buildId = randomUUID();
15
+ if (runtime) {
16
+ runtime.productionBuildId = buildId;
17
+ }
18
+ return buildId;
19
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Checks that `dist/` is a complete production export: one build id across its
3
+ * manifests, and every listed output exists. It does not read sources.
4
+ */
5
+ export declare function assertProductionDistComplete(rootDir: string, distDir: string): void;
@@ -0,0 +1,101 @@
1
+ import path from 'node:path';
2
+ import { fileSystem } from '@ecopages/file-system';
3
+ import { SERVER_BUNDLE_DIR } from '../utils/resolve-entry-file.js';
4
+ import { PRODUCTION_ROUTES_FILENAME } from './production-route-list.js';
5
+ import { SERVER_MODULES_MANIFEST_FILENAME } from './server/server-modules-manifest.js';
6
+ const BROWSER_CLIENT_MANIFEST_FILENAME = 'browser-client-manifest.json';
7
+ function describe(rootDir, filePath) {
8
+ return path.relative(rootDir, filePath) || '.';
9
+ }
10
+ function readJsonObject(filePath) {
11
+ if (!fileSystem.exists(filePath)) {
12
+ return { kind: 'missing' };
13
+ }
14
+ try {
15
+ const parsed = JSON.parse(fileSystem.readFileSync(filePath));
16
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
17
+ return { kind: 'invalid', error: new TypeError('Expected a JSON object.') };
18
+ }
19
+ return { kind: 'valid', value: parsed };
20
+ }
21
+ catch (error) {
22
+ return { kind: 'invalid', error };
23
+ }
24
+ }
25
+ function requireJsonObject(rootDir, filePath, label) {
26
+ const result = readJsonObject(filePath);
27
+ if (result.kind === 'valid')
28
+ return result.value;
29
+ if (result.kind === 'missing') {
30
+ throw new Error(`The production ${label} ${describe(rootDir, filePath)} is missing. Run \`ecopages build\` again.`);
31
+ }
32
+ throw new Error(`The production ${label} ${describe(rootDir, filePath)} is invalid or unreadable. Run \`ecopages build\` again.`, { cause: result.error });
33
+ }
34
+ function requireBuildId(rootDir, filePath, payload) {
35
+ if (typeof payload.buildId !== 'string' || payload.buildId.length === 0) {
36
+ throw new Error(`${describe(rootDir, filePath)} is missing a build id. Run \`ecopages build\` again.`);
37
+ }
38
+ return payload.buildId;
39
+ }
40
+ function requireExisting(rootDir, filePath, label) {
41
+ if (!fileSystem.exists(filePath)) {
42
+ throw new Error(`The production ${label} ${describe(rootDir, filePath)} is missing. Run \`ecopages build\` again.`);
43
+ }
44
+ }
45
+ function requireMatchingBuildId(rootDir, buildId, deployManifestPath, filePath, payload) {
46
+ if (requireBuildId(rootDir, filePath, payload) !== buildId) {
47
+ throw new Error(`Production manifests disagree on the build id (${describe(rootDir, deployManifestPath)} vs ${describe(rootDir, filePath)}). Run \`ecopages build\` again.`);
48
+ }
49
+ }
50
+ function requireListedFiles(rootDir, values, resolvePath, label) {
51
+ for (const relativePath of values) {
52
+ if (typeof relativePath !== 'string')
53
+ continue;
54
+ requireExisting(rootDir, resolvePath(relativePath), label);
55
+ }
56
+ }
57
+ function requireServerModules(rootDir, serverDir, buildId, deployManifestPath) {
58
+ const serverModulesPath = path.join(serverDir, SERVER_MODULES_MANIFEST_FILENAME);
59
+ const serverModules = requireJsonObject(rootDir, serverModulesPath, 'server-modules map');
60
+ requireMatchingBuildId(rootDir, buildId, deployManifestPath, serverModulesPath, serverModules);
61
+ const modules = serverModules.modules;
62
+ if (!modules || typeof modules !== 'object' || Array.isArray(modules)) {
63
+ throw new Error(`${describe(rootDir, serverModulesPath)} is missing a modules map. Run \`ecopages build\` again.`);
64
+ }
65
+ requireListedFiles(rootDir, Object.values(modules), (relativePath) => path.join(serverDir, relativePath), 'server module');
66
+ }
67
+ function requireOptionalBrowserManifest(rootDir, serverDir, buildId, deployManifestPath) {
68
+ const browserManifestPath = path.join(serverDir, BROWSER_CLIENT_MANIFEST_FILENAME);
69
+ if (!fileSystem.exists(browserManifestPath))
70
+ return;
71
+ const browserManifest = requireJsonObject(rootDir, browserManifestPath, 'browser client manifest');
72
+ requireMatchingBuildId(rootDir, buildId, deployManifestPath, browserManifestPath, browserManifest);
73
+ const browserOutputPaths = browserManifest.browserOutputPaths;
74
+ if (Array.isArray(browserOutputPaths)) {
75
+ requireListedFiles(rootDir, browserOutputPaths, (relativePath) => path.resolve(rootDir, relativePath), 'browser output');
76
+ }
77
+ }
78
+ /**
79
+ * Checks that `dist/` is a complete production export: one build id across its
80
+ * manifests, and every listed output exists. It does not read sources.
81
+ */
82
+ export function assertProductionDistComplete(rootDir, distDir) {
83
+ const resolvedRoot = path.resolve(rootDir);
84
+ const resolvedDist = path.resolve(resolvedRoot, distDir);
85
+ const serverDir = path.join(resolvedDist, SERVER_BUNDLE_DIR);
86
+ const deployManifestPath = path.join(serverDir, 'manifest.json');
87
+ const deployManifest = requireJsonObject(resolvedRoot, deployManifestPath, 'bundle manifest');
88
+ const buildId = requireBuildId(resolvedRoot, deployManifestPath, deployManifest);
89
+ if (typeof deployManifest.serverEntry !== 'string' || deployManifest.serverEntry.length === 0) {
90
+ throw new Error(`${describe(resolvedRoot, deployManifestPath)} is missing a server entry. Run \`ecopages build\` again.`);
91
+ }
92
+ requireExisting(resolvedRoot, path.join(serverDir, deployManifest.serverEntry), 'server entry');
93
+ if (typeof deployManifest.emittedConfigModule === 'string' && deployManifest.emittedConfigModule.length > 0) {
94
+ requireExisting(resolvedRoot, path.join(serverDir, deployManifest.emittedConfigModule), 'emitted config');
95
+ }
96
+ const routeListPath = path.join(serverDir, PRODUCTION_ROUTES_FILENAME);
97
+ const routeList = requireJsonObject(resolvedRoot, routeListPath, 'route list');
98
+ requireMatchingBuildId(resolvedRoot, buildId, deployManifestPath, routeListPath, routeList);
99
+ requireServerModules(resolvedRoot, serverDir, buildId, deployManifestPath);
100
+ requireOptionalBrowserManifest(resolvedRoot, serverDir, buildId, deployManifestPath);
101
+ }
@@ -0,0 +1,26 @@
1
+ import type { EcoPagesAppConfig } from '../config/internal-types.js';
2
+ import type { RouteKind, RouteRole, TemplateRoute } from '../router/server/route-registry.js';
3
+ export declare const PRODUCTION_ROUTES_FILENAME = "routes.json";
4
+ type SerializedTemplateRoute = {
5
+ pathname: string;
6
+ kind: RouteKind;
7
+ role: RouteRole;
8
+ filePath: string;
9
+ paramNames: string[];
10
+ };
11
+ export type ProductionRouteList = {
12
+ buildId: string;
13
+ routes: SerializedTemplateRoute[];
14
+ };
15
+ export declare function getProductionRouteListPath(appConfig: EcoPagesAppConfig): string;
16
+ /**
17
+ * Writes the filesystem route list `ecopages start` loads instead of scanning sources.
18
+ */
19
+ export declare function writeProductionRouteList(appConfig: EcoPagesAppConfig, routes: readonly TemplateRoute[]): void;
20
+ export declare function readProductionRouteList(appConfig: EcoPagesAppConfig): ProductionRouteList | undefined;
21
+ export declare function readProductionRouteListFromDist(rootDir: string, distDir: string): ProductionRouteList | undefined;
22
+ /**
23
+ * Restores template routes from `dist/server/routes.json`, resolving file paths against `rootDir`.
24
+ */
25
+ export declare function loadProductionTemplateRoutes(appConfig: EcoPagesAppConfig): TemplateRoute[] | undefined;
26
+ export {};
@@ -0,0 +1,78 @@
1
+ import path from 'node:path';
2
+ import { fileSystem } from '@ecopages/file-system';
3
+ import { toRootRelativePath } from '../utils/root-relative-path.js';
4
+ import { ensureProductionBuildId } from './production-build-id.js';
5
+ import { SERVER_BUNDLE_DIR } from '../utils/resolve-entry-file.js';
6
+ import { getServerBundleOutputPaths } from './server-bundle-deploy-manifest.js';
7
+ export const PRODUCTION_ROUTES_FILENAME = 'routes.json';
8
+ export function getProductionRouteListPath(appConfig) {
9
+ return path.join(getServerBundleOutputPaths(appConfig).serverOutdir, PRODUCTION_ROUTES_FILENAME);
10
+ }
11
+ function getProductionRouteListPathFromDist(rootDir, distDir) {
12
+ return path.join(path.resolve(rootDir, distDir), SERVER_BUNDLE_DIR, PRODUCTION_ROUTES_FILENAME);
13
+ }
14
+ /**
15
+ * Writes the filesystem route list `ecopages start` loads instead of scanning sources.
16
+ */
17
+ export function writeProductionRouteList(appConfig, routes) {
18
+ const payload = {
19
+ buildId: ensureProductionBuildId(appConfig),
20
+ routes: routes.map((route) => ({
21
+ pathname: route.pathname,
22
+ kind: route.kind,
23
+ role: route.role,
24
+ filePath: toRootRelativePath(appConfig.rootDir, route.filePath),
25
+ paramNames: [...(route.paramNames ?? [])],
26
+ })),
27
+ };
28
+ const listPath = getProductionRouteListPath(appConfig);
29
+ fileSystem.ensureDir(path.dirname(listPath));
30
+ fileSystem.write(listPath, `${JSON.stringify(payload, null, '\t')}\n`);
31
+ }
32
+ function parseProductionRouteList(raw) {
33
+ try {
34
+ const parsed = JSON.parse(raw);
35
+ if (typeof parsed !== 'object' ||
36
+ parsed === null ||
37
+ !('buildId' in parsed) ||
38
+ !('routes' in parsed) ||
39
+ typeof parsed.buildId !== 'string' ||
40
+ !Array.isArray(parsed.routes)) {
41
+ return undefined;
42
+ }
43
+ return parsed;
44
+ }
45
+ catch {
46
+ return undefined;
47
+ }
48
+ }
49
+ export function readProductionRouteList(appConfig) {
50
+ const listPath = getProductionRouteListPath(appConfig);
51
+ if (!fileSystem.exists(listPath)) {
52
+ return undefined;
53
+ }
54
+ return parseProductionRouteList(fileSystem.readFileSync(listPath));
55
+ }
56
+ export function readProductionRouteListFromDist(rootDir, distDir) {
57
+ const listPath = getProductionRouteListPathFromDist(rootDir, distDir);
58
+ if (!fileSystem.exists(listPath)) {
59
+ return undefined;
60
+ }
61
+ return parseProductionRouteList(fileSystem.readFileSync(listPath));
62
+ }
63
+ /**
64
+ * Restores template routes from `dist/server/routes.json`, resolving file paths against `rootDir`.
65
+ */
66
+ export function loadProductionTemplateRoutes(appConfig) {
67
+ const list = readProductionRouteList(appConfig);
68
+ if (!list) {
69
+ return undefined;
70
+ }
71
+ return list.routes.map((route) => ({
72
+ pathname: route.pathname,
73
+ kind: route.kind,
74
+ role: route.role,
75
+ filePath: path.resolve(appConfig.rootDir, route.filePath),
76
+ paramNames: route.paramNames,
77
+ }));
78
+ }
@@ -20,7 +20,7 @@ import type { BuildDependencyGraph, BuildOptions, BuildLog, BuildSuccess } from
20
20
  * A compiled package can depend on its location on disk: it loads a native
21
21
  * binding (`sharp`, `oxc-parser`), a platform package, or a sibling file
22
22
  * through `createRequire(import.meta.url)` or `__dirname`. Bundled into
23
- * `dist/.server/`, that lookup starts from the wrong folder and fails at
23
+ * `dist/server/`, that lookup starts from the wrong folder and fails at
24
24
  * runtime, and the bundle cannot tell which packages do it. So server builds
25
25
  * bundle source code only (the app, workspace packages, TypeScript or JSX
26
26
  * packages) and keep every compiled package installed in `node_modules`
@@ -28,7 +28,7 @@ import type { BuildDependencyGraph, BuildOptions, BuildLog, BuildSuccess } from
28
28
  * Core itself.
29
29
  *
30
30
  * Under isolated installs (pnpm, Bun's isolated linker) a package the app does
31
- * not declare is not reachable as a bare specifier from `dist/.server`, so the
31
+ * not declare is not reachable as a bare specifier from `dist/server`, so the
32
32
  * hook resolves it through Rolldown, from the importer (or, for Core's own
33
33
  * dependencies, from Core), so the `node` and `import` conditions apply and
34
34
  * the result is a real path, and returns a `./` or `../` path that Rolldown
@@ -9,6 +9,7 @@
9
9
  *
10
10
  * @module
11
11
  */
12
+ import { createHash } from 'node:crypto';
12
13
  import { builtinModules, createRequire } from 'node:module';
13
14
  import path from 'node:path';
14
15
  import { fileSystem } from '@ecopages/file-system';
@@ -29,6 +30,8 @@ import { createRolldownPluginBridge, getEcoBuildPluginName } from './rolldown-pl
29
30
  import { isDeclaredAppPackageImport, isWorkspacePackageImport } from './app-package-declarations.js';
30
31
  const coreSourceFile = fileURLToPath(import.meta.url);
31
32
  const nodeBuiltinSpecifiers = new Set(builtinModules);
33
+ const MAX_FLATTENED_PRESERVED_MODULE_NAME_BYTES = 120;
34
+ const PRESERVED_MODULE_NAME_HASH_LENGTH = 16;
32
35
  let corePackageNames;
33
36
  const CORE_RUNTIME_BUNDLED_PACKAGES = new Set(['ws']);
34
37
  /**
@@ -92,7 +95,7 @@ function getAppRootRequire(cache, contextRoot) {
92
95
  * packages and source (TypeScript or JSX) packages are bundled. Undeclared
93
96
  * compiled packages are handled by {@link createInstalledPackageExternalPlugin},
94
97
  * because isolated installs (pnpm, Bun's isolated linker) do not expose them
95
- * as bare specifiers to output directories like `.eco/` or `dist/.server/`.
98
+ * as bare specifiers to output directories like `.eco/` or `dist/server/`.
96
99
  */
97
100
  function isAppPackageExternal(id, contextRoot, appRootRequireCache) {
98
101
  if (isWorkspacePackageImport(id, contextRoot) || !isDeclaredAppPackageImport(id, contextRoot)) {
@@ -164,7 +167,7 @@ function isInstalledCompiledModule(filePath) {
164
167
  * A compiled package can depend on its location on disk: it loads a native
165
168
  * binding (`sharp`, `oxc-parser`), a platform package, or a sibling file
166
169
  * through `createRequire(import.meta.url)` or `__dirname`. Bundled into
167
- * `dist/.server/`, that lookup starts from the wrong folder and fails at
170
+ * `dist/server/`, that lookup starts from the wrong folder and fails at
168
171
  * runtime, and the bundle cannot tell which packages do it. So server builds
169
172
  * bundle source code only (the app, workspace packages, TypeScript or JSX
170
173
  * packages) and keep every compiled package installed in `node_modules`
@@ -172,7 +175,7 @@ function isInstalledCompiledModule(filePath) {
172
175
  * Core itself.
173
176
  *
174
177
  * Under isolated installs (pnpm, Bun's isolated linker) a package the app does
175
- * not declare is not reachable as a bare specifier from `dist/.server`, so the
178
+ * not declare is not reachable as a bare specifier from `dist/server`, so the
176
179
  * hook resolves it through Rolldown, from the importer (or, for Core's own
177
180
  * dependencies, from Core), so the `node` and `import` conditions apply and
178
181
  * the result is a real path, and returns a `./` or `../` path that Rolldown
@@ -470,14 +473,53 @@ function shouldDisableRolldownCodeSplitting(options) {
470
473
  : Object.keys(options.entrypoints).length;
471
474
  return entrypointCount === 1;
472
475
  }
476
+ function truncateUtf8(value, maximumBytes) {
477
+ let prefix = '';
478
+ let prefixBytes = 0;
479
+ for (const character of value) {
480
+ const characterBytes = Buffer.byteLength(character);
481
+ if (prefixBytes + characterBytes > maximumBytes)
482
+ break;
483
+ prefix += character;
484
+ prefixBytes += characterBytes;
485
+ }
486
+ return prefix;
487
+ }
488
+ function flattenPreservedModuleName(sourceName) {
489
+ const flattened = sourceName.replaceAll(/[\\/]/g, '-');
490
+ if (Buffer.byteLength(flattened) <= MAX_FLATTENED_PRESERVED_MODULE_NAME_BYTES)
491
+ return flattened;
492
+ const digest = createHash('sha256').update(sourceName).digest('hex').slice(0, PRESERVED_MODULE_NAME_HASH_LENGTH);
493
+ const prefixBytes = MAX_FLATTENED_PRESERVED_MODULE_NAME_BYTES - digest.length - 1;
494
+ return `${truncateUtf8(flattened, prefixBytes)}-${digest}`;
495
+ }
496
+ /**
497
+ * Names preserved modules after their source paths while keeping each flat filename below the filesystem component limit.
498
+ *
499
+ * @remarks
500
+ * `preserveModules` otherwise mirrors the source tree below the output directory. Flat names keep every emitted module
501
+ * next to the others, so a module's `import.meta` points at the folder that holds its `serverFiles`, and installed-package
502
+ * externals relative to the output directory resolve from every module. Deep package-manager store paths are shortened
503
+ * with a stable digest to stay within common filesystem filename limits without colliding on a shared prefix.
504
+ */
505
+ function flattenPreservedModuleFileNames(pattern) {
506
+ return (chunk) => pattern.replaceAll('[name]', () => flattenPreservedModuleName(chunk.name));
507
+ }
473
508
  function buildRolldownOutputOptions(options, outdir) {
509
+ const entryFileNames = resolveRolldownEntryFileNames(options);
474
510
  return {
475
511
  dir: outdir,
476
512
  format: mapRolldownFormat(options.format),
477
513
  minify: !!options.minify,
478
- entryFileNames: resolveRolldownEntryFileNames(options),
514
+ entryFileNames: options.preserveModules ? flattenPreservedModuleFileNames(entryFileNames) : entryFileNames,
479
515
  chunkFileNames: '[name]-[hash].js',
480
516
  assetFileNames: '[name]-[hash][extname]',
517
+ ...(options.preserveModules
518
+ ? {
519
+ preserveModules: true,
520
+ ...(options.preserveModulesRoot ? { preserveModulesRoot: options.preserveModulesRoot } : {}),
521
+ }
522
+ : {}),
481
523
  sourcemap: mapRolldownSourcemap(options.sourcemap),
482
524
  ...(shouldDisableRolldownCodeSplitting(options) ? { codeSplitting: false } : {}),
483
525
  };
@@ -521,6 +563,15 @@ function isContentHashedOutput(entry, entryNamingHashed) {
521
563
  function isHashedSourceMap(fileName, hashedFileNames) {
522
564
  return fileName.endsWith('.map') && hashedFileNames.has(fileName.slice(0, -'.map'.length));
523
565
  }
566
+ /**
567
+ * Returns the source file path of a bundled module, or nothing for a virtual module.
568
+ */
569
+ function sourceModulePath(moduleId, root) {
570
+ if (moduleId.startsWith('\0'))
571
+ return [];
572
+ const filePath = moduleId.startsWith('file:') ? fileURLToPath(moduleId) : moduleId;
573
+ return path.isAbsolute(filePath) ? [resolveBuildEntryPath(filePath, root)] : [];
574
+ }
524
575
  /** Maps a Rolldown `output` to the output fields of a {@link BuildSuccess}. */
525
576
  export function buildResultFromRolldownOutput(output, outdir, contextRoot, dependencyGraph, entrypoints, naming, includeContent = false) {
526
577
  const entryNamingHashed = Boolean(naming?.includes('[hash]'));
@@ -546,6 +597,7 @@ export function buildResultFromRolldownOutput(output, outdir, contextRoot, depen
546
597
  dynamicImports: chunk.dynamicImports.map(outputImport),
547
598
  isEntry: chunk.isEntry,
548
599
  facadeModuleId: chunk.facadeModuleId ? resolveBuildEntryPath(chunk.facadeModuleId, contextRoot) : null,
600
+ modules: Object.keys(chunk.modules).flatMap((moduleId) => sourceModulePath(moduleId, contextRoot)),
549
601
  },
550
602
  ]));
551
603
  const entryOutputs = {};
@@ -32,7 +32,7 @@ export class RolldownBuildAdapter {
32
32
  }
33
33
  recordRolldownBuildInvocation();
34
34
  const contextRoot = options.root ? path.resolve(options.root) : process.cwd();
35
- const outdir = path.resolve(options.outdir ?? 'dist/assets');
35
+ const outdir = path.resolve(options.outdir ?? 'dist/client/assets');
36
36
  const recordingContext = getBuildInputRecordingContext();
37
37
  const loadedInputs = new Set();
38
38
  const loadedInputsByModule = new Map();
@@ -338,7 +338,7 @@ export async function createRolldownPluginBridge(plugins, contextRoot, recordBui
338
338
  }
339
339
  }
340
340
  registrationClosed = true;
341
- const resolveIdHandler = async (source, importer) => {
341
+ const resolveIdHandler = async (source, importer, extraOptions) => {
342
342
  for (const { matches, callback, pluginName } of resolveRegistrations) {
343
343
  if (!matches(source)) {
344
344
  continue;
@@ -346,7 +346,7 @@ export async function createRolldownPluginBridge(plugins, contextRoot, recordBui
346
346
  const { namespace, path: sourcePath } = splitNamespace(source);
347
347
  let result;
348
348
  try {
349
- result = await callback({ path: sourcePath, importer, namespace });
349
+ result = await callback({ path: sourcePath, importer, namespace, kind: extraOptions?.kind });
350
350
  }
351
351
  catch (error) {
352
352
  throw new EcoBuildPluginError(error, pluginName, importer);
@@ -37,7 +37,7 @@ function canonicalize(value) {
37
37
  * since Rolldown hook precedence depends on position.
38
38
  */
39
39
  export function createBuildRequestIdentity(options) {
40
- const { plugins, entrypoints, root, outdir, runtimeOutdir, external, ...rest } = options;
40
+ const { plugins, entrypoints, root, outdir, runtimeOutdir, preserveModulesRoot, external, ...rest } = options;
41
41
  return JSON.stringify([
42
42
  canonicalize({
43
43
  ...rest,
@@ -45,6 +45,7 @@ export function createBuildRequestIdentity(options) {
45
45
  root: root ? path.resolve(root) : undefined,
46
46
  outdir: outdir ? path.resolve(outdir) : undefined,
47
47
  runtimeOutdir: runtimeOutdir ? path.resolve(runtimeOutdir) : undefined,
48
+ preserveModulesRoot: preserveModulesRoot ? path.resolve(preserveModulesRoot) : undefined,
48
49
  external: external ? [...external].sort() : undefined,
49
50
  }),
50
51
  createPluginCacheKey(plugins),
@@ -59,8 +59,9 @@ export type BrowserBuildRequestInput = Partial<BuildOptions> & {
59
59
  * themselves. Plugins follow {@link resolveBuildPluginOrder}, so server module loading shares browser
60
60
  * attribution. Every server request
61
61
  * also gets {@link createPreserveImportMetaPlugin} for `runtimeOutdir` (or
62
- * `outdir`), so bundled modules, Core included, keep reading files relative to
63
- * their sources from `dist/.server/` and `.eco/.server-modules/`.
62
+ * `outdir`) in development, so compiled modules in `.eco/.server-modules/`
63
+ * keep reading files next to their sources. Production emit leaves
64
+ * `import.meta` pointing at the files in `dist/server/`.
64
65
  */
65
66
  export declare function createServerBuildRequest(appConfig: EcoPagesAppConfig, input: ServerBuildRequestInput): BuildOptions;
66
67
  /**
@@ -4,6 +4,7 @@ import { createAliasResolverPlugin } from '../../plugins/alias-resolver-plugin.j
4
4
  import { resolveBuildEnvironmentOptions } from './build-environment-options.js';
5
5
  import { getJsxOwnershipPlugins } from '../browser/jsx-ownership-plugins.js';
6
6
  import { createEcoComponentMetaPlugin } from '../../plugins/eco-component-meta-plugin.js';
7
+ import { isProductionRuntime } from '../../env.js';
7
8
  import { createPreserveImportMetaPlugin } from '../preserve-import-meta-transform.js';
8
9
  /**
9
10
  * App-owned plugins of one environment, in the order their hooks run.
@@ -78,14 +79,15 @@ export function resolveBuildPluginOrder(appConfig, environment, options) {
78
79
  * themselves. Plugins follow {@link resolveBuildPluginOrder}, so server module loading shares browser
79
80
  * attribution. Every server request
80
81
  * also gets {@link createPreserveImportMetaPlugin} for `runtimeOutdir` (or
81
- * `outdir`), so bundled modules, Core included, keep reading files relative to
82
- * their sources from `dist/.server/` and `.eco/.server-modules/`.
82
+ * `outdir`) in development, so compiled modules in `.eco/.server-modules/`
83
+ * keep reading files next to their sources. Production emit leaves
84
+ * `import.meta` pointing at the files in `dist/server/`.
83
85
  */
84
86
  export function createServerBuildRequest(appConfig, input) {
85
87
  const importMetaDir = input.runtimeOutdir ?? input.outdir;
86
88
  const plugins = resolveBuildPluginOrder(appConfig, 'server', {
87
89
  callerPlugins: input.plugins,
88
- coreTransforms: importMetaDir ? [createPreserveImportMetaPlugin(importMetaDir)] : [],
90
+ coreTransforms: importMetaDir && !isProductionRuntime() ? [createPreserveImportMetaPlugin(importMetaDir)] : [],
89
91
  });
90
92
  const { plugins: _callerPlugins, ...overrides } = input;
91
93
  return {
@@ -0,0 +1,11 @@
1
+ import type { EcoPagesAppConfig } from '../../config/internal-types.js';
2
+ import type { ViewLoader } from '../../types/contracts.js';
3
+ /**
4
+ * Loads a view through the app module loader.
5
+ *
6
+ * @remarks
7
+ * Development compiles from source with watcher invalidation. Production imports
8
+ * the module `ecopages build` wrote to the server-modules map.
9
+ */
10
+ export declare function importViewModule<T = unknown>(appConfig: EcoPagesAppConfig, filePath: string): Promise<T>;
11
+ export declare function createViewLoaderFromFilePath<P = Record<string, unknown>>(appConfig: EcoPagesAppConfig, filePath: string): ViewLoader<P>;
@@ -0,0 +1,21 @@
1
+ import { getServerModuleBuildCacheOutdir } from './route-module-build-cache-registry.js';
2
+ import { requireAppRuntime } from '../../utils/app-runtime.js';
3
+ /**
4
+ * Loads a view through the app module loader.
5
+ *
6
+ * @remarks
7
+ * Development compiles from source with watcher invalidation. Production imports
8
+ * the module `ecopages build` wrote to the server-modules map.
9
+ */
10
+ export async function importViewModule(appConfig, filePath) {
11
+ return await requireAppRuntime(appConfig).moduleLoader.importModule({
12
+ filePath,
13
+ outdir: getServerModuleBuildCacheOutdir(appConfig),
14
+ externalPackages: true,
15
+ });
16
+ }
17
+ export function createViewLoaderFromFilePath(appConfig, filePath) {
18
+ const loader = async () => await importViewModule(appConfig, filePath);
19
+ loader.filePath = filePath;
20
+ return loader;
21
+ }
@@ -0,0 +1,16 @@
1
+ import type { EcoBuildPlugin } from '../contracts/build-types.js';
2
+ import type { EcoPagesAppConfig } from '../../config/internal-types.js';
3
+ export declare const IMPORTED_VIEW_PLUGIN_NAME = "ecopages-imported-views";
4
+ /** Paths the server-entry plugin turned into view references for this app. */
5
+ export declare function getImportedViewPaths(appConfig: EcoPagesAppConfig): readonly string[];
6
+ /**
7
+ * Turns Integration-owned imports in the server-entry graph into view references.
8
+ *
9
+ * @remarks
10
+ * Register only on the server-entry bundle. Page and route-module builds must
11
+ * still compile those files. Recorded paths join the production server-modules
12
+ * map so `ctx.render` views are not compiled at request time.
13
+ */
14
+ export declare function createImportedViewPlugin(appConfig: EcoPagesAppConfig, options?: {
15
+ entryPath?: string;
16
+ }): EcoBuildPlugin;
@@ -0,0 +1,59 @@
1
+ import path from 'node:path';
2
+ import { collectViewIntegrations, findViewOwner, isExemptFromViewReference, viewExtensionFilter, viewReferenceModuleSource, } from './view-reference.js';
3
+ export const IMPORTED_VIEW_PLUGIN_NAME = 'ecopages-imported-views';
4
+ const importedViewPaths = new WeakMap();
5
+ /** Paths the server-entry plugin turned into view references for this app. */
6
+ export function getImportedViewPaths(appConfig) {
7
+ return [...(importedViewPaths.get(appConfig) ?? [])];
8
+ }
9
+ function recordImportedViewPath(appConfig, filePath) {
10
+ const resolvedPath = path.resolve(filePath);
11
+ const paths = importedViewPaths.get(appConfig);
12
+ if (paths) {
13
+ paths.add(resolvedPath);
14
+ return;
15
+ }
16
+ importedViewPaths.set(appConfig, new Set([resolvedPath]));
17
+ }
18
+ /**
19
+ * Turns Integration-owned imports in the server-entry graph into view references.
20
+ *
21
+ * @remarks
22
+ * Register only on the server-entry bundle. Page and route-module builds must
23
+ * still compile those files. Recorded paths join the production server-modules
24
+ * map so `ctx.render` views are not compiled at request time.
25
+ */
26
+ export function createImportedViewPlugin(appConfig, options = {}) {
27
+ const integrations = collectViewIntegrations(appConfig.integrations);
28
+ const extensions = [...new Set(integrations.flatMap((integration) => [...integration.extensions]))];
29
+ const entryPath = options.entryPath ? path.resolve(options.entryPath) : undefined;
30
+ if (extensions.length === 0) {
31
+ return {
32
+ name: IMPORTED_VIEW_PLUGIN_NAME,
33
+ environments: ['server'],
34
+ setup() { },
35
+ };
36
+ }
37
+ const filter = viewExtensionFilter(extensions);
38
+ return {
39
+ name: IMPORTED_VIEW_PLUGIN_NAME,
40
+ environments: ['server'],
41
+ cacheKey: JSON.stringify(extensions),
42
+ setup(build) {
43
+ build.onLoad({ filter }, (args) => {
44
+ if (isExemptFromViewReference(args.path, { entryPath, appRoot: appConfig.rootDir })) {
45
+ return undefined;
46
+ }
47
+ const owner = findViewOwner(integrations, args.path);
48
+ if (!owner) {
49
+ return undefined;
50
+ }
51
+ recordImportedViewPath(appConfig, args.path);
52
+ return {
53
+ contents: viewReferenceModuleSource(args.path, owner.name),
54
+ loader: 'js',
55
+ };
56
+ });
57
+ },
58
+ };
59
+ }