@ecopages/core 0.8.0 → 0.9.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 (145) hide show
  1. package/README.md +2 -2
  2. package/package.json +14 -4
  3. package/src/adapters/node/create-app.d.ts +1 -1
  4. package/src/adapters/node/create-app.js +1 -1
  5. package/src/adapters/node/server-adapter.d.ts +1 -0
  6. package/src/adapters/node/server-adapter.js +4 -1
  7. package/src/adapters/shared/hmr/hmr-manager.d.ts +2 -0
  8. package/src/adapters/shared/hmr/hmr-manager.js +8 -4
  9. package/src/adapters/shared/http/api-request-pipeline.d.ts +16 -3
  10. package/src/adapters/shared/http/api-request-pipeline.js +16 -11
  11. package/src/adapters/shared/http/explicit-static-route-matcher.js +8 -4
  12. package/src/adapters/shared/runtime/render-context.d.ts +2 -0
  13. package/src/adapters/shared/runtime/render-context.js +4 -0
  14. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +2 -2
  15. package/src/adapters/shared/runtime/server-request-pipeline.js +4 -3
  16. package/src/adapters/shared/runtime/server-static-builder.js +4 -1
  17. package/src/adapters/shared/runtime/unattached-scripts.d.ts +17 -0
  18. package/src/adapters/shared/runtime/unattached-scripts.js +57 -0
  19. package/src/adapters/shared/ws/node-http-websocket-upgrades.js +3 -2
  20. package/src/adapters/shared/ws/ws-pattern-matcher.d.ts +14 -1
  21. package/src/adapters/shared/ws/ws-pattern-matcher.js +14 -13
  22. package/src/assets/app-browser-client-build.js +3 -0
  23. package/src/assets/asset-processing-service/asset-processing.service.d.ts +9 -0
  24. package/src/assets/asset-processing-service/asset-processing.service.js +19 -0
  25. package/src/assets/asset-processing-service/processed-asset-ledger.d.ts +16 -2
  26. package/src/assets/asset-processing-service/processed-asset-ledger.js +31 -3
  27. package/src/build/build-graph.d.ts +19 -2
  28. package/src/build/build-graph.js +19 -18
  29. package/src/build/cache/pages-unified-graph-build.d.ts +4 -6
  30. package/src/build/cache/pages-unified-graph-build.js +14 -51
  31. package/src/build/cache/server-module-entries.d.ts +5 -9
  32. package/src/build/cache/server-module-entries.js +5 -58
  33. package/src/build/contracts/build-contracts.d.ts +15 -0
  34. package/src/build/contracts.d.ts +1 -1
  35. package/src/build/contracts.js +1 -1
  36. package/src/build/production-asset-ledger.d.ts +1 -1
  37. package/src/build/production-asset-ledger.js +4 -2
  38. package/src/build/rolldown/file-role-grammar-plugin.d.ts +11 -0
  39. package/src/build/rolldown/file-role-grammar-plugin.js +32 -0
  40. package/src/build/rolldown/rolldown-adapter-helpers.d.ts +11 -0
  41. package/src/build/rolldown/rolldown-adapter-helpers.js +79 -10
  42. package/src/build/rolldown/ssr-script-entries-plugin.d.ts +31 -0
  43. package/src/build/rolldown/ssr-script-entries-plugin.js +104 -0
  44. package/src/build/server/server-modules-manifest.d.ts +6 -1
  45. package/src/build/server/server-modules-manifest.js +10 -1
  46. package/src/build/server/view-reference.d.ts +9 -0
  47. package/src/build/server/view-reference.js +11 -0
  48. package/src/build.d.ts +2 -1
  49. package/src/build.js +2 -1
  50. package/src/cli.d.ts +14 -0
  51. package/src/cli.js +14 -0
  52. package/src/config/assembly/app-runtime.d.ts +13 -0
  53. package/src/config/assembly/app-runtime.js +2 -0
  54. package/src/config/assembly/finalize-config.js +13 -8
  55. package/src/config/internal-types.d.ts +0 -12
  56. package/src/config/resolve-eco-config-path.d.ts +2 -0
  57. package/src/config/resolve-eco-config-path.js +2 -1
  58. package/src/config/server-config-bundle.d.ts +0 -1
  59. package/src/config/server-config-bundle.js +1 -1
  60. package/src/config/user-config-types.d.ts +0 -12
  61. package/src/dev/invalidation/development-invalidation.service.d.ts +0 -2
  62. package/src/dev/invalidation/development-invalidation.service.js +1 -11
  63. package/src/dev/transform-server/dev-transform-vendor-registry.js +33 -19
  64. package/src/eco/discovered-dependencies.d.ts +5 -0
  65. package/src/eco/discovered-dependencies.js +9 -0
  66. package/src/eco/eco.browser.js +5 -5
  67. package/src/eco/eco.js +24 -5
  68. package/src/eco/migration-docs.d.ts +7 -0
  69. package/src/eco/migration-docs.js +7 -0
  70. package/src/hmr/client/hmr-runtime.js +1 -1
  71. package/src/hmr/strategies/js-hmr-strategy.d.ts +0 -2
  72. package/src/hmr/strategies/server-rendered-template-hmr-strategy.d.ts +2 -1
  73. package/src/hmr/strategies/server-rendered-template-hmr-strategy.js +4 -3
  74. package/src/html/html-rewriter.d.ts +9 -7
  75. package/src/html/html-rewriter.js +26 -41
  76. package/src/html/html-transformer.service.d.ts +2 -2
  77. package/src/html/html-transformer.service.js +21 -15
  78. package/src/html-pages/html-page-module-scripts.js +2 -1
  79. package/src/html-pages/html-pages.plugin.d.ts +1 -1
  80. package/src/html-pages/html-pages.plugin.js +1 -1
  81. package/src/integration.d.ts +1 -1
  82. package/src/integration.js +1 -1
  83. package/src/islands/island-host.d.ts +16 -5
  84. package/src/islands/island-host.js +8 -1
  85. package/src/plugins/component-import-discovery.d.ts +14 -1
  86. package/src/plugins/component-import-discovery.js +36 -16
  87. package/src/plugins/eco-component-meta-plugin.d.ts +5 -0
  88. package/src/plugins/eco-component-meta-plugin.js +39 -22
  89. package/src/plugins/ecopages-virtual-imports.d.ts +15 -0
  90. package/src/plugins/ecopages-virtual-imports.js +25 -0
  91. package/src/plugins/integration-plugin.d.ts +1 -1
  92. package/src/plugins/integration-plugin.js +1 -1
  93. package/src/plugins/tsconfig-import-resolver.d.ts +2 -0
  94. package/src/plugins/tsconfig-import-resolver.js +7 -5
  95. package/src/route-renderer/error-pages/error-page-renderer.js +3 -2
  96. package/src/route-renderer/explicit-view-render-preparation.d.ts +10 -3
  97. package/src/route-renderer/explicit-view-render-preparation.js +14 -8
  98. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.d.ts +24 -9
  99. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.js +73 -50
  100. package/src/route-renderer/orchestration/integration-renderer.d.ts +39 -10
  101. package/src/route-renderer/orchestration/integration-renderer.js +74 -38
  102. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.d.ts +32 -11
  103. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.js +68 -61
  104. package/src/route-renderer/page-declaration.d.ts +25 -0
  105. package/src/route-renderer/page-declaration.js +39 -0
  106. package/src/route-renderer/page-loading/component-declarations.d.ts +65 -0
  107. package/src/route-renderer/page-loading/component-declarations.js +77 -0
  108. package/src/route-renderer/page-loading/component-dependency-collection.d.ts +4 -16
  109. package/src/route-renderer/page-loading/component-dependency-collection.js +36 -105
  110. package/src/route-renderer/page-loading/declared-asset-collection.d.ts +19 -14
  111. package/src/route-renderer/page-loading/declared-asset-collection.js +66 -67
  112. package/src/route-renderer/page-loading/dependency-resolver.d.ts +18 -10
  113. package/src/route-renderer/page-loading/dependency-resolver.js +58 -99
  114. package/src/route-renderer/page-loading/lazy-entry-collection.d.ts +19 -26
  115. package/src/route-renderer/page-loading/lazy-entry-collection.js +53 -64
  116. package/src/route-renderer/page-loading/module-declaration-aggregation.d.ts +17 -3
  117. package/src/route-renderer/page-loading/module-declaration-aggregation.js +14 -13
  118. package/src/route-renderer/page-loading/page-module-loader.d.ts +10 -11
  119. package/src/route-renderer/page-loading/page-module-loader.js +30 -30
  120. package/src/router/server/pages-dir.d.ts +7 -0
  121. package/src/router/server/pages-dir.js +7 -0
  122. package/src/router/server/route-registry.d.ts +22 -10
  123. package/src/router/server/route-registry.js +54 -23
  124. package/src/router/server/segment-path-matcher.d.ts +29 -5
  125. package/src/router/server/segment-path-matcher.js +22 -19
  126. package/src/static-site-generator/production-page-browser-graph-prebuild.d.ts +2 -2
  127. package/src/static-site-generator/production-page-browser-graph-prebuild.js +5 -5
  128. package/src/static-site-generator/static-site-generator.d.ts +17 -1
  129. package/src/static-site-generator/static-site-generator.js +46 -12
  130. package/src/types/contracts.d.ts +28 -28
  131. package/src/types/eco-api-types.d.ts +17 -12
  132. package/src/types/public-types.d.ts +1 -1
  133. package/src/utils/file-roles.d.ts +48 -0
  134. package/src/utils/file-roles.js +85 -0
  135. package/src/utils/node-builtin.d.ts +10 -0
  136. package/src/utils/node-builtin.js +13 -0
  137. package/src/watchers/project-watcher.js +2 -2
  138. package/src/build/contracts/server-only-specifier.d.ts +0 -8
  139. package/src/build/contracts/server-only-specifier.js +0 -11
  140. package/src/route-renderer/orchestration/route-pipeline/marker-artifact.utils.d.ts +0 -5
  141. package/src/route-renderer/orchestration/route-pipeline/marker-artifact.utils.js +0 -11
  142. package/src/route-renderer/page-loading/ecopages-virtual-imports.d.ts +0 -12
  143. package/src/route-renderer/page-loading/ecopages-virtual-imports.js +0 -100
  144. package/src/utils/endpoint-file-extensions.d.ts +0 -11
  145. package/src/utils/endpoint-file-extensions.js +0 -13
@@ -14,6 +14,8 @@ export type SerializedProcessedAssetLedger = {
14
14
  entries: LedgerEntry[];
15
15
  /** Every file the app-wide browser build emitted, chunks included; absent when no browser build ran. */
16
16
  browserOutputs?: string[];
17
+ /** The processed shell Dependencies of each route shell, by {@link ProcessedAssetLedger.recordShell} key. */
18
+ shells?: Record<string, LedgerProcessedAsset[]>;
17
19
  };
18
20
  /**
19
21
  * The emitted form of every dependency one production build processed or bundled, by dependency key.
@@ -27,6 +29,7 @@ export type SerializedProcessedAssetLedger = {
27
29
  */
28
30
  export declare class ProcessedAssetLedger {
29
31
  private readonly entries;
32
+ private readonly shells;
30
33
  private browserOutputs;
31
34
  private sealed;
32
35
  private readonly rootDir;
@@ -45,12 +48,23 @@ export declare class ProcessedAssetLedger {
45
48
  /** Records the files one app-wide browser build emitted, which marks the ledger as holding that build. */
46
49
  recordBrowserOutputs(filepaths: readonly string[]): void;
47
50
  /**
48
- * Forgets the app-wide browser build, so a retried production build records only its own outputs.
51
+ * Records the processed Dependencies of one route shell: its Html template, Layouts and Page.
52
+ *
53
+ * @remarks
54
+ * `key` names the Page and Html template, which fix the shell. The build records each shell the first time it
55
+ * prepares a route of that Page, and every later preparation, in the build or in `ecopages start`, reads it.
56
+ */
57
+ recordShell(key: string, assets: ProcessedAsset[]): void;
58
+ /** Returns the processed Dependencies recorded for one route shell. */
59
+ lookupShell(key: string): ProcessedAsset[] | undefined;
60
+ /**
61
+ * Forgets the app-wide browser build and the recorded shells, so a retried production build records only its
62
+ * own outputs.
49
63
  *
50
64
  * @remarks
51
65
  * Recorded dependencies stay: the next build records the ones it bundles again under the same keys.
52
66
  */
53
- clearBrowserOutputs(): void;
67
+ clearBuildOutputs(): void;
54
68
  /** Returns the recorded asset with paths resolved against the current app root. */
55
69
  lookup(dep: AssetDefinition): ProcessedAsset | undefined;
56
70
  /** Names `dep` in error messages: its app-root relative file, import path or content name. */
@@ -12,6 +12,7 @@ import { getAssetDependencyKey } from './asset-dependency-keys.js';
12
12
  */
13
13
  export class ProcessedAssetLedger {
14
14
  entries = new Map();
15
+ shells = new Map();
15
16
  browserOutputs;
16
17
  sealed = false;
17
18
  rootDir;
@@ -45,13 +46,29 @@ export class ProcessedAssetLedger {
45
46
  this.browserOutputs.add(this.relative(filepath));
46
47
  }
47
48
  /**
48
- * Forgets the app-wide browser build, so a retried production build records only its own outputs.
49
+ * Records the processed Dependencies of one route shell: its Html template, Layouts and Page.
50
+ *
51
+ * @remarks
52
+ * `key` names the Page and Html template, which fix the shell. The build records each shell the first time it
53
+ * prepares a route of that Page, and every later preparation, in the build or in `ecopages start`, reads it.
54
+ */
55
+ recordShell(key, assets) {
56
+ this.shells.set(key, assets);
57
+ }
58
+ /** Returns the processed Dependencies recorded for one route shell. */
59
+ lookupShell(key) {
60
+ return this.shells.get(key);
61
+ }
62
+ /**
63
+ * Forgets the app-wide browser build and the recorded shells, so a retried production build records only its
64
+ * own outputs.
49
65
  *
50
66
  * @remarks
51
67
  * Recorded dependencies stay: the next build records the ones it bundles again under the same keys.
52
68
  */
53
- clearBrowserOutputs() {
69
+ clearBuildOutputs() {
54
70
  this.browserOutputs = undefined;
71
+ this.shells.clear();
55
72
  }
56
73
  /** Returns the recorded asset with paths resolved against the current app root. */
57
74
  lookup(dep) {
@@ -70,13 +87,24 @@ export class ProcessedAssetLedger {
70
87
  const entries = [...this.entries]
71
88
  .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
72
89
  .map(([key, asset]) => ({ key, asset }));
73
- return this.browserOutputs ? { entries, browserOutputs: [...this.browserOutputs].sort() } : { entries };
90
+ const shells = Object.fromEntries([...this.shells]
91
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
92
+ .map(([key, assets]) => [key, assets.map((asset) => this.toPortable(asset))]));
93
+ return {
94
+ entries,
95
+ ...(this.browserOutputs ? { browserOutputs: [...this.browserOutputs].sort() } : {}),
96
+ ...(this.shells.size > 0 ? { shells } : {}),
97
+ };
74
98
  }
75
99
  restore(ledger) {
76
100
  this.entries.clear();
77
101
  for (const { key, asset } of ledger.entries)
78
102
  this.entries.set(key, asset);
79
103
  this.browserOutputs = ledger.browserOutputs ? new Set(ledger.browserOutputs) : undefined;
104
+ this.shells.clear();
105
+ for (const [key, assets] of Object.entries(ledger.shells ?? {})) {
106
+ this.shells.set(key, assets.map((asset) => this.toAbsolute(asset)));
107
+ }
80
108
  }
81
109
  relative(filepath) {
82
110
  return path.relative(this.rootDir, path.resolve(this.rootDir, filepath));
@@ -3,6 +3,24 @@ import type { BuildOptions, BuildSuccess } from './build-adapter.js';
3
3
  * Absolute path for an entry as the caller passed it, without resolving symlinks.
4
4
  */
5
5
  export declare function resolveBuildEntryPath(entry: string, root: string): string;
6
+ /**
7
+ * One requested build entry with its symlink-resolved paths.
8
+ */
9
+ export type RequestedBuildEntry = {
10
+ name: string;
11
+ entry: string;
12
+ resolved: string;
13
+ entryReal: string | undefined;
14
+ resolvedReal: string | undefined;
15
+ };
16
+ /**
17
+ * Resolves every requested entry and its real paths once, for repeated {@link recordBuildEntryOutput} calls.
18
+ *
19
+ * @remarks
20
+ * Real-path lookups touch the filesystem, so recording one build's chunks against freshly resolved entries
21
+ * would repeat them for every chunk and entry.
22
+ */
23
+ export declare function resolveRequestedBuildEntries(entrypoints: BuildOptions['entrypoints'], root: string): RequestedBuildEntry[];
6
24
  /**
7
25
  * Records every spelling a caller may use to look up one entry's output.
8
26
  *
@@ -14,8 +32,7 @@ export declare function resolveBuildEntryPath(entry: string, root: string): stri
14
32
  export declare function recordBuildEntryOutput(entryOutputs: Record<string, string>, outputPath: string, options: {
15
33
  facadeModuleId: string;
16
34
  chunkName?: string;
17
- entrypoints: BuildOptions['entrypoints'];
18
- root: string;
35
+ requestedEntries: RequestedBuildEntry[];
19
36
  }): void;
20
37
  /**
21
38
  * Finds the emitted file for an entry using the path or name the caller passed.
@@ -14,23 +14,24 @@ function tryRealpath(filePath) {
14
14
  export function resolveBuildEntryPath(entry, root) {
15
15
  return path.resolve(root, entry);
16
16
  }
17
- function requestedBuildEntries(entrypoints, root) {
17
+ /**
18
+ * Resolves every requested entry and its real paths once, for repeated {@link recordBuildEntryOutput} calls.
19
+ *
20
+ * @remarks
21
+ * Real-path lookups touch the filesystem, so recording one build's chunks against freshly resolved entries
22
+ * would repeat them for every chunk and entry.
23
+ */
24
+ export function resolveRequestedBuildEntries(entrypoints, root) {
18
25
  const pairs = Array.isArray(entrypoints)
19
26
  ? entrypoints.map((entry) => [entry, entry])
20
27
  : Object.entries(entrypoints);
21
- return pairs.map(([name, entry]) => ({
22
- name,
23
- entry,
24
- resolved: resolveBuildEntryPath(entry, root),
25
- }));
28
+ return pairs.map(([name, entry]) => {
29
+ const resolved = resolveBuildEntryPath(entry, root);
30
+ return { name, entry, resolved, entryReal: tryRealpath(entry), resolvedReal: tryRealpath(resolved) };
31
+ });
26
32
  }
27
- function isSameBuildEntry(left, right) {
28
- if (left === right) {
29
- return true;
30
- }
31
- const leftReal = tryRealpath(left);
32
- const rightReal = tryRealpath(right);
33
- return Boolean(leftReal && rightReal && leftReal === rightReal);
33
+ function isSameBuildEntry(left, leftReal, right, rightReal) {
34
+ return left === right || Boolean(leftReal && rightReal && leftReal === rightReal);
34
35
  }
35
36
  /**
36
37
  * Records every spelling a caller may use to look up one entry's output.
@@ -47,8 +48,9 @@ export function recordBuildEntryOutput(entryOutputs, outputPath, options) {
47
48
  if (facadeReal) {
48
49
  keys.add(facadeReal);
49
50
  }
50
- for (const requested of requestedBuildEntries(options.entrypoints, options.root)) {
51
- const matchesFacade = isSameBuildEntry(facadeModuleId, requested.resolved) || isSameBuildEntry(facadeModuleId, requested.entry);
51
+ for (const requested of options.requestedEntries) {
52
+ const matchesFacade = isSameBuildEntry(facadeModuleId, facadeReal, requested.resolved, requested.resolvedReal) ||
53
+ isSameBuildEntry(facadeModuleId, facadeReal, requested.entry, requested.entryReal);
52
54
  const matchesName = options.chunkName !== undefined && options.chunkName === requested.name;
53
55
  if (!matchesFacade && !matchesName) {
54
56
  continue;
@@ -56,9 +58,8 @@ export function recordBuildEntryOutput(entryOutputs, outputPath, options) {
56
58
  keys.add(requested.entry);
57
59
  keys.add(requested.resolved);
58
60
  keys.add(requested.name);
59
- const requestedReal = tryRealpath(requested.resolved);
60
- if (requestedReal) {
61
- keys.add(requestedReal);
61
+ if (requested.resolvedReal) {
62
+ keys.add(requested.resolvedReal);
62
63
  }
63
64
  }
64
65
  for (const key of keys) {
@@ -28,12 +28,8 @@ export declare function importEmittedServerModule<T>(appConfig: EcoPagesAppConfi
28
28
  * Emits every production server entry into `outdir` and writes `server-modules.json`.
29
29
  *
30
30
  * @remarks
31
- * Imports the emitted Rolldown modules to discover extra `ssr: true` scripts, so
32
- * Integrations are activated first; Core installs the configured server DOM
33
- * before their `setup()`. A discovered script already bundled into the first
34
- * emit maps to that output. Otherwise a second emit adds the scripts; preserved
35
- * modules keep their output path across both emits, so a module imported after
36
- * the first emit is not evaluated again from a second copy.
31
+ * The `ssr: true` scripts that declarations list are entries of the same build (see
32
+ * `createSsrScriptEntriesPlugin`), so every module is bundled once and none is evaluated from two copies.
37
33
  */
38
34
  export declare function emitProductionServerModules(options: {
39
35
  appConfig: EcoPagesAppConfig;
@@ -41,6 +37,8 @@ export declare function emitProductionServerModules(options: {
41
37
  staticRoutes?: readonly StaticRoute[];
42
38
  errorPageLoaders?: ErrorPageLoaders;
43
39
  outdir?: string;
40
+ /** Receives the project and package source files the server build bundled, after it succeeds. */
41
+ onServerSources?: (sources: readonly string[]) => void | Promise<void>;
44
42
  }): Promise<ProductionServerModulesManifest>;
45
43
  /**
46
44
  * Imports the emitted module for `filePath` from the production server-modules map.
@@ -20,7 +20,7 @@ import { toRootRelativePath } from '../../utils/root-relative-path.js';
20
20
  import { loadProductionServerModules, writeProductionServerModulesManifest, } from '../server/server-modules-manifest.js';
21
21
  import { getServerBundleOutputPaths } from '../server-bundle-deploy-manifest.js';
22
22
  import { ensureProductionBuildId } from '../production-build-id.js';
23
- import { collectServerModuleEntries, collectSsrScriptPaths, isRolldownServerModuleEntry, } from './server-module-entries.js';
23
+ import { collectServerModuleEntries, isRolldownServerModuleEntry, } from './server-module-entries.js';
24
24
  /**
25
25
  * True when a production build should emit the server-modules map.
26
26
  *
@@ -93,7 +93,7 @@ export async function importEmittedServerModule(appConfig, filePath, outputPath)
93
93
  }
94
94
  async function emitRolldownServerModules(appConfig, entryPaths, outdir) {
95
95
  if (entryPaths.length === 0) {
96
- return { modules: {}, outputGraph: {} };
96
+ return { modules: {}, sources: [] };
97
97
  }
98
98
  const entryRecord = {};
99
99
  for (const entryPath of entryPaths) {
@@ -107,6 +107,7 @@ async function emitRolldownServerModules(appConfig, entryPaths, outdir) {
107
107
  preserveModules: true,
108
108
  preserveModulesRoot: appConfig.rootDir,
109
109
  naming: '[name]-[hash].[ext]',
110
+ ssrScriptEntries: true,
110
111
  });
111
112
  const buildResult = await buildOrThrow(appConfig, buildOptions, 'Pages unified graph build failed').finally(() => appLogger.debugTimeEnd('pagesUnifiedGraphBuild'));
112
113
  const modules = {};
@@ -117,27 +118,13 @@ async function emitRolldownServerModules(appConfig, entryPaths, outdir) {
117
118
  }
118
119
  modules[toRootRelativePath(appConfig.rootDir, entryPath)] = toRootRelativePath(outdir, compiledOutput);
119
120
  }
120
- return { modules, outputGraph: buildResult.outputGraph };
121
- }
122
- function findEmittedModulePath(outputGraph, sourcePath) {
123
- const resolvedSource = path.resolve(sourcePath);
124
- for (const [outputPath, chunk] of Object.entries(outputGraph)) {
125
- if (chunk.modules.includes(resolvedSource)) {
126
- return outputPath;
127
- }
128
- }
129
- return undefined;
130
- }
131
- async function importEmittedModules(manifest, sourceKeys) {
132
- const modules = [];
133
- for (const sourceKey of sourceKeys) {
134
- const relativePath = manifest.modules[sourceKey];
135
- if (!relativePath) {
136
- continue;
121
+ for (const [outputPath, chunk] of Object.entries(buildResult.outputGraph)) {
122
+ if (chunk.isEntry && chunk.facadeModuleId) {
123
+ modules[toRootRelativePath(appConfig.rootDir, chunk.facadeModuleId)] ??= toRootRelativePath(outdir, outputPath);
137
124
  }
138
- modules.push(await import(/* @vite-ignore */ path.toFileUrl(path.join(manifest.outdir, relativePath)).href));
139
125
  }
140
- return modules;
126
+ const sources = [...new Set(Object.values(buildResult.dependencyGraph.entrypoints).flat())];
127
+ return { modules, sources };
141
128
  }
142
129
  function assignProductionServerModules(appConfig, manifest) {
143
130
  const runtime = requireAppRuntime(appConfig);
@@ -147,12 +134,8 @@ function assignProductionServerModules(appConfig, manifest) {
147
134
  * Emits every production server entry into `outdir` and writes `server-modules.json`.
148
135
  *
149
136
  * @remarks
150
- * Imports the emitted Rolldown modules to discover extra `ssr: true` scripts, so
151
- * Integrations are activated first; Core installs the configured server DOM
152
- * before their `setup()`. A discovered script already bundled into the first
153
- * emit maps to that output. Otherwise a second emit adds the scripts; preserved
154
- * modules keep their output path across both emits, so a module imported after
155
- * the first emit is not evaluated again from a second copy.
137
+ * The `ssr: true` scripts that declarations list are entries of the same build (see
138
+ * `createSsrScriptEntriesPlugin`), so every module is bundled once and none is evaluated from two copies.
156
139
  */
157
140
  export async function emitProductionServerModules(options) {
158
141
  const appConfig = options.appConfig;
@@ -160,7 +143,7 @@ export async function emitProductionServerModules(options) {
160
143
  await setupAppRuntimeIntegrations({ appConfig });
161
144
  const outdir = path.resolve(options.outdir ?? getServerBundleOutputPaths(appConfig).serverOutdir);
162
145
  fileSystem.ensureDir(outdir);
163
- const collected = await collectServerModuleEntries({
146
+ const collected = collectServerModuleEntries({
164
147
  appConfig,
165
148
  router: options.router,
166
149
  staticRoutes: options.staticRoutes,
@@ -168,38 +151,18 @@ export async function emitProductionServerModules(options) {
168
151
  });
169
152
  const rolldownEntries = collected.filter((entryPath) => isRolldownServerModuleEntry(entryPath, appConfig));
170
153
  const htmlEntries = collected.filter((entryPath) => !isRolldownServerModuleEntry(entryPath, appConfig));
171
- const modules = {};
172
- const initialEmit = await emitRolldownServerModules(appConfig, uniqueEntryPaths(rolldownEntries), outdir);
173
- Object.assign(modules, initialEmit.modules);
154
+ const { modules, sources } = await emitRolldownServerModules(appConfig, uniqueEntryPaths(rolldownEntries), outdir);
155
+ await options.onServerSources?.(sources);
174
156
  for (const htmlEntry of uniqueEntryPaths(htmlEntries)) {
175
157
  const emitted = await emitCompiledPageModule(appConfig, htmlEntry, outdir);
176
158
  modules[emitted.sourceKey] = emitted.relativePath;
177
159
  }
178
- let manifest = {
160
+ const manifest = {
179
161
  outdir,
180
162
  buildId: ensureProductionBuildId(appConfig),
181
163
  modules,
182
164
  };
183
165
  assignProductionServerModules(appConfig, manifest);
184
- const discoveredScripts = collectSsrScriptPaths(await importEmittedModules(manifest, rolldownEntries.map((entryPath) => toRootRelativePath(appConfig.rootDir, entryPath))), appConfig.rootDir).filter((scriptPath) => fileSystem.exists(scriptPath) && !(toRootRelativePath(appConfig.rootDir, scriptPath) in modules));
185
- if (discoveredScripts.length > 0) {
186
- const scriptsToEmit = [];
187
- for (const scriptPath of discoveredScripts) {
188
- const existingOutput = findEmittedModulePath(initialEmit.outputGraph, scriptPath);
189
- if (existingOutput) {
190
- modules[toRootRelativePath(appConfig.rootDir, scriptPath)] = toRootRelativePath(outdir, existingOutput);
191
- }
192
- else {
193
- scriptsToEmit.push(scriptPath);
194
- }
195
- }
196
- if (scriptsToEmit.length > 0) {
197
- const emittedModules = await emitRolldownServerModules(appConfig, uniqueEntryPaths([...rolldownEntries, ...scriptsToEmit]), outdir);
198
- Object.assign(modules, emittedModules.modules);
199
- }
200
- manifest = { outdir, buildId: ensureProductionBuildId(appConfig), modules };
201
- assignProductionServerModules(appConfig, manifest);
202
- }
203
166
  writeProductionServerModulesManifest(manifest);
204
167
  appLogger.debug(`Emitted ${Object.keys(modules).length} production server modules`);
205
168
  return manifest;
@@ -14,22 +14,18 @@ export type ServerModuleEntryRouteSource = {
14
14
  */
15
15
  export declare function isRolldownServerModuleEntry(filePath: string, appConfig: EcoPagesAppConfig): boolean;
16
16
  /**
17
- * Collects every production server entry except `ssr: true` scripts, which are
18
- * discovered from compiled modules after the first graph emit.
17
+ * Collects every production server entry except `ssr: true` scripts, which the server build
18
+ * adds from each declaration (`createSsrScriptEntriesPlugin`).
19
19
  *
20
20
  * @remarks
21
21
  * Processor `listProductionServerModuleEntries()` files, such as generated content
22
22
  * collection modules, join the same map so production start can import them without
23
- * calling Processor `setup()`. Views imported into the server entry (`ctx.render`,
24
- * `ctx.renderPartial`) are recorded by the imported-view plugin during that bundle.
23
+ * calling Processor `setup()`. A Layout is not an entry: the Page that passes it as `eco.page({ layout })` uses
24
+ * it, so it is bundled once with that Page and keeps its exports. Views imported into the server entry (`ctx.render`, `ctx.renderPartial`) are recorded by the imported-view plugin during that bundle.
25
25
  */
26
26
  export declare function collectServerModuleEntries(options: {
27
27
  appConfig: EcoPagesAppConfig;
28
28
  router: ServerModuleEntryRouteSource;
29
29
  staticRoutes?: readonly StaticRoute[];
30
30
  errorPageLoaders?: ErrorPageLoaders;
31
- }): Promise<string[]>;
32
- /**
33
- * Walks compiled Page, Layout, and view modules for `ssr: true` script paths.
34
- */
35
- export declare function collectSsrScriptPaths(modules: readonly unknown[], rootDir: string): string[];
31
+ }): string[];
@@ -1,7 +1,5 @@
1
1
  import { path } from '@ecopages/file-system/path';
2
2
  import { fileSystem } from '@ecopages/file-system';
3
- import { getComponentIdentity } from '../../eco/component-identity.js';
4
- import { isEcoDeclaredComponent } from '../../eco/eco-declared-component.js';
5
3
  import { findIntegrationForFile } from '../../plugins/find-integration-for-file.js';
6
4
  import { getImportedViewPaths } from '../server/imported-view-plugin.js';
7
5
  /**
@@ -23,34 +21,23 @@ function addExistingPath(entries, filePath) {
23
21
  function addViewLoader(entries, loader) {
24
22
  addExistingPath(entries, loader?.filePath);
25
23
  }
26
- async function collectLayoutFiles(appConfig, entries) {
27
- const layoutsDir = appConfig.absolutePaths.layoutsDir;
28
- if (!layoutsDir || !fileSystem.exists(layoutsDir)) {
29
- return;
30
- }
31
- const files = await fileSystem.glob(appConfig.templatesExt.map((extension) => `**/*${extension}`), { cwd: layoutsDir });
32
- for (const file of files) {
33
- entries.add(path.resolve(layoutsDir, file));
34
- }
35
- }
36
24
  /**
37
- * Collects every production server entry except `ssr: true` scripts, which are
38
- * discovered from compiled modules after the first graph emit.
25
+ * Collects every production server entry except `ssr: true` scripts, which the server build
26
+ * adds from each declaration (`createSsrScriptEntriesPlugin`).
39
27
  *
40
28
  * @remarks
41
29
  * Processor `listProductionServerModuleEntries()` files, such as generated content
42
30
  * collection modules, join the same map so production start can import them without
43
- * calling Processor `setup()`. Views imported into the server entry (`ctx.render`,
44
- * `ctx.renderPartial`) are recorded by the imported-view plugin during that bundle.
31
+ * calling Processor `setup()`. A Layout is not an entry: the Page that passes it as `eco.page({ layout })` uses
32
+ * it, so it is bundled once with that Page and keeps its exports. Views imported into the server entry (`ctx.render`, `ctx.renderPartial`) are recorded by the imported-view plugin during that bundle.
45
33
  */
46
- export async function collectServerModuleEntries(options) {
34
+ export function collectServerModuleEntries(options) {
47
35
  const entries = new Set();
48
36
  const { appConfig } = options;
49
37
  for (const route of options.router.templateRoutes) {
50
38
  addExistingPath(entries, route.filePath);
51
39
  }
52
40
  addExistingPath(entries, appConfig.absolutePaths.htmlTemplatePath);
53
- await collectLayoutFiles(appConfig, entries);
54
41
  for (const route of options.staticRoutes ?? []) {
55
42
  addViewLoader(entries, route.loader);
56
43
  }
@@ -67,43 +54,3 @@ export async function collectServerModuleEntries(options) {
67
54
  }
68
55
  return [...entries];
69
56
  }
70
- function addSsrScripts(component, rootDir, scripts) {
71
- const identity = getComponentIdentity(component);
72
- const ownerDir = identity?.file ? path.dirname(path.resolve(rootDir, identity.file)) : undefined;
73
- if (!ownerDir) {
74
- return;
75
- }
76
- for (const script of component.config?.dependencies?.scripts ?? []) {
77
- if (typeof script === 'object' && script.ssr && script.src) {
78
- scripts.add(path.resolve(ownerDir, script.src));
79
- }
80
- }
81
- }
82
- function collectSsrScriptsFromComponent(component, rootDir, seen, scripts) {
83
- if (!component || seen.has(component) || !isEcoDeclaredComponent(component)) {
84
- return;
85
- }
86
- seen.add(component);
87
- const ecoComponent = component;
88
- addSsrScripts(ecoComponent, rootDir, scripts);
89
- for (const related of ecoComponent.config?.layouts ?? []) {
90
- collectSsrScriptsFromComponent(related, rootDir, seen, scripts);
91
- }
92
- for (const related of ecoComponent.config?.dependencies?.components ?? []) {
93
- collectSsrScriptsFromComponent(related, rootDir, seen, scripts);
94
- }
95
- }
96
- /**
97
- * Walks compiled Page, Layout, and view modules for `ssr: true` script paths.
98
- */
99
- export function collectSsrScriptPaths(modules, rootDir) {
100
- const scripts = new Set();
101
- const seen = new Set();
102
- for (const module of modules) {
103
- if (!module || typeof module !== 'object') {
104
- continue;
105
- }
106
- collectSsrScriptsFromComponent(module.default, rootDir, seen, scripts);
107
- }
108
- return [...scripts];
109
- }
@@ -153,6 +153,21 @@ export interface BuildOptions {
153
153
  * The dev transform server sets `false`: it compiles one module at a time and points the URL at its own module URL.
154
154
  */
155
155
  workerEntries?: boolean;
156
+ /**
157
+ * Builds each `ssr: true` script a declaration lists as an entry of the same build. Server builds only; defaults to `false`.
158
+ */
159
+ ssrScriptEntries?: boolean;
160
+ /**
161
+ * Gives each installed package with at least `minSize` bytes of source in the build a chunk of its own, named
162
+ * `vendor-<package>-[hash]`. Browser builds with code splitting only; off when unset.
163
+ *
164
+ * @remarks
165
+ * A package's chunk holds that package's modules and their own dependencies, so its name and bytes do not change when app code does. A
166
+ * smaller package stays with whatever shares it, as the bundler would place it.
167
+ */
168
+ packageChunks?: {
169
+ minSize: number;
170
+ };
156
171
  }
157
172
  /**
158
173
  * The stylesheets of one build request and the compiler of the module a binding import of one receives.
@@ -1,4 +1,4 @@
1
1
  export type * from './contracts/build-contracts.js';
2
2
  export type * from './contracts/build-types.js';
3
3
  export { CONTENT_COMPONENT_VIRTUAL_MODULE_PATTERN, CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, isContentServerVirtualModule, parseCollectionSpecifier, type ParsedCollectionSpecifier, } from './contracts/content-virtual-modules.js';
4
- export { isServerOnlyModuleSpecifier } from './contracts/server-only-specifier.js';
4
+ export { isServerOnlyModuleSpecifier } from '../utils/file-roles.js';
@@ -1,2 +1,2 @@
1
1
  export { CONTENT_COMPONENT_VIRTUAL_MODULE_PATTERN, CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, isContentServerVirtualModule, parseCollectionSpecifier, } from './contracts/content-virtual-modules.js';
2
- export { isServerOnlyModuleSpecifier } from './contracts/server-only-specifier.js';
2
+ export { isServerOnlyModuleSpecifier } from '../utils/file-roles.js';
@@ -9,7 +9,7 @@ export declare const PRODUCTION_ASSET_LEDGER_FILENAME = "processed-assets.json";
9
9
  * root-relative source, so the file serves a build moved to another folder or platform.
10
10
  */
11
11
  export type ProductionAssetLedgerFile = SerializedProcessedAssetLedger & {
12
- version: 4;
12
+ version: 5;
13
13
  buildId: string;
14
14
  htmlPageModuleScriptUrls: Record<string, string>;
15
15
  };
@@ -22,7 +22,7 @@ function getLedgerPath(appConfig) {
22
22
  export function writeProductionAssetLedger(appConfig, htmlPageModuleScriptUrls) {
23
23
  const runtime = requireAppRuntime(appConfig);
24
24
  const payload = {
25
- version: 4,
25
+ version: 5,
26
26
  buildId: ensureProductionBuildId(appConfig),
27
27
  ...runtime.processedAssets.serialize(),
28
28
  htmlPageModuleScriptUrls: Object.fromEntries([...htmlPageModuleScriptUrls]
@@ -45,11 +45,13 @@ function isStringArray(value) {
45
45
  }
46
46
  function isLedgerFile(value) {
47
47
  return (isRecord(value) &&
48
- value.version === 4 &&
48
+ value.version === 5 &&
49
49
  typeof value.buildId === 'string' &&
50
50
  Array.isArray(value.entries) &&
51
51
  value.entries.every((entry) => isRecord(entry) && typeof entry.key === 'string' && isRecord(entry.asset)) &&
52
52
  (value.browserOutputs === undefined || isStringArray(value.browserOutputs)) &&
53
+ (value.shells === undefined ||
54
+ (isRecord(value.shells) && Object.values(value.shells).every((assets) => Array.isArray(assets)))) &&
53
55
  isRecord(value.htmlPageModuleScriptUrls) &&
54
56
  Object.values(value.htmlPageModuleScriptUrls).every((url) => typeof url === 'string'));
55
57
  }
@@ -0,0 +1,11 @@
1
+ import type { RolldownPlugin } from 'rolldown';
2
+ /**
3
+ * Fails a build that compiles an app module whose name puts a role segment anywhere but directly before a script
4
+ * extension, such as `card.server.kita.tsx`.
5
+ *
6
+ * @remarks
7
+ * Role suffixes follow `<name>.<role>.<ts|tsx|js|jsx>`. The router enforces that for route files; this plugin
8
+ * covers every other module the build compiles, wherever it lives, so a misplaced segment never reads two ways.
9
+ * Modules under `node_modules` are installed packages and are not checked.
10
+ */
11
+ export declare function createFileRoleGrammarPlugin(): RolldownPlugin;
@@ -0,0 +1,32 @@
1
+ import { describeRoleForms, findMisplacedRole } from '../../utils/file-roles.js';
2
+ import { fromRolldownModuleId } from './rolldown-module-id.js';
3
+ const ROLE_FILE_PATTERN = /\.(?:api|server|script)\.[^/\\]*\.(?:[cm]?[jt]sx?)$/u;
4
+ /**
5
+ * Fails a build that compiles an app module whose name puts a role segment anywhere but directly before a script
6
+ * extension, such as `card.server.kita.tsx`.
7
+ *
8
+ * @remarks
9
+ * Role suffixes follow `<name>.<role>.<ts|tsx|js|jsx>`. The router enforces that for route files; this plugin
10
+ * covers every other module the build compiles, wherever it lives, so a misplaced segment never reads two ways.
11
+ * Modules under `node_modules` are installed packages and are not checked.
12
+ */
13
+ export function createFileRoleGrammarPlugin() {
14
+ return {
15
+ name: 'ecopages:file-role-grammar',
16
+ transform: {
17
+ filter: { id: ROLE_FILE_PATTERN },
18
+ handler(_code, id) {
19
+ if (id.startsWith('\0'))
20
+ return null;
21
+ const file = fromRolldownModuleId(id);
22
+ if (file.split('/').includes('node_modules'))
23
+ return null;
24
+ const misplaced = findMisplacedRole(file);
25
+ if (misplaced) {
26
+ this.error(`${file}: the "${misplaced}" role segment must come directly before a script extension, as in ${describeRoleForms()}. Rename the file.`);
27
+ }
28
+ return null;
29
+ },
30
+ },
31
+ };
32
+ }
@@ -69,6 +69,9 @@ export declare function createInstalledPackageExternalPlugin(contextRoot: string
69
69
  * bare specifiers. This plugin fails the build instead so server-only graphs
70
70
  * cannot reach the browser as silent CORS errors.
71
71
  *
72
+ * A built-in is recorded where it resolves and reported at `buildEnd`, because the importer chain through
73
+ * `node_modules` to the app module is only known once every module is parsed.
74
+ *
72
75
  * The `.server` check reads the resolved ids a module imports once it is parsed,
73
76
  * not the specifiers as written, so an alias such as a `package.json` `imports`
74
77
  * entry or a tsconfig path is rejected like a relative import. Rolldown has no
@@ -97,6 +100,14 @@ export interface ResolvedRolldownOptions {
97
100
  inputOptions: InputOptions;
98
101
  outputOptions: OutputOptions;
99
102
  }
103
+ /**
104
+ * Names the chunk of the installed package a module belongs to, or nothing for app code.
105
+ *
106
+ * @remarks
107
+ * The package is the one at the last `node_modules` segment, so a pnpm store path and a nested install both resolve to
108
+ * the package that owns the module.
109
+ */
110
+ export declare function getInstalledPackageChunkName(moduleId: string): string | null;
100
111
  /**
101
112
  * Translates a {@link BuildOptions} into Rolldown's `InputOptions` and
102
113
  * `OutputOptions`. Always sets `experimental.nativeMagicString: true`