@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
@@ -126,7 +126,7 @@ export class DevTransformServer {
126
126
  }
127
127
  async tryHandleRequest(request) {
128
128
  const url = new URL(request.url);
129
- const vendorResponse = this.vendorRegistry.tryHandleVendorRequest(url.pathname, request.headers.get('If-None-Match'));
129
+ const vendorResponse = await this.vendorRegistry.tryHandleVendorRequest(url.pathname, request.headers.get('If-None-Match'));
130
130
  if (vendorResponse) {
131
131
  return vendorResponse;
132
132
  }
@@ -6,23 +6,46 @@ export type DevTransformVendorRegistryOptions = {
6
6
  };
7
7
  /**
8
8
  * Lazily prebundles bare npm imports into process-local `/assets/vendors/*` chunks.
9
+ *
10
+ * @remarks
11
+ * A vendor bundle keeps the ESM imports of other packages external and points them at those packages' own
12
+ * vendor URLs, so a package shared by several vendors, such as a framework core, loads once in the browser
13
+ * and keeps one module identity. `require()` calls stay bundled, since a vendor URL is an ES module that
14
+ * `require()` cannot load.
9
15
  */
10
16
  export declare class DevTransformVendorRegistry {
11
17
  private readonly appConfig;
12
18
  private readonly browserBundleService;
13
19
  private readonly resolveVendorBundlePlugins?;
14
- private readonly cache;
15
- private readonly inFlight;
20
+ private records;
21
+ private recordsByUrl;
16
22
  constructor(options: DevTransformVendorRegistryOptions);
17
23
  resolveVendorUrl(specifier: string): Promise<string>;
18
24
  /**
19
25
  * @remarks
20
- * Responses carry `no-cache` and a content `ETag`, so browsers revalidate each
21
- * load and get `304` while `ifNoneMatch` still matches the in-memory bundle.
26
+ * A vendor that another vendor references may still be building when the browser asks for it, so the
27
+ * request waits for that build. Responses carry `no-cache` and a content `ETag`, so browsers revalidate
28
+ * each load and get `304` while `ifNoneMatch` still matches the in-memory bundle.
22
29
  */
23
- tryHandleVendorRequest(pathname: string, ifNoneMatch?: string | null): Response | null;
30
+ tryHandleVendorRequest(pathname: string, ifNoneMatch?: string | null): Promise<Response | null>;
24
31
  invalidateAll(): void;
32
+ /**
33
+ * Returns the record for a package entry, starting its build when no build exists yet.
34
+ *
35
+ * @remarks
36
+ * The build is not awaited here: two vendors that import each other would otherwise wait on each other.
37
+ * Failures are kept on the record and reported to whoever awaits the build or requests the URL.
38
+ */
39
+ private ensureVendor;
25
40
  private createVendorResponse;
26
- private prebundleSpecifier;
41
+ private prebundle;
42
+ /**
43
+ * Points the ESM imports of other packages inside one vendor bundle at those packages' vendor URLs.
44
+ *
45
+ * @remarks
46
+ * It runs after the vendor plugins, so a specifier the browser runtime manifest owns keeps the manifest's
47
+ * URL. Each dependency resolves from its importer, where a strict install places it.
48
+ */
49
+ private createSharedPackagePlugin;
27
50
  private resolvePackageEntry;
28
51
  }
@@ -2,7 +2,7 @@ import { contentHash } from '../../utils/content-hash.js';
2
2
  import path from 'node:path';
3
3
  import { RESOLVED_ASSETS_VENDORS_DIR } from '../../constants.js';
4
4
  import { resolveAppBuildPlugins } from '../../build/runtime/build-request-policy.js';
5
- import { resolveBarePackageBrowserEntry } from '../../plugins/tsconfig-import-resolver.js';
5
+ import { isBarePackageImportSpecifier, resolveBarePackageBrowserEntry, } from '../../plugins/tsconfig-import-resolver.js';
6
6
  import { toPackageRootSpecifier } from '../../plugins/package-specifier.js';
7
7
  import { BrowserBundleService } from '../../assets/browser-bundle.service.js';
8
8
  import { assertBuildSucceeded } from '../../build/build-log.js';
@@ -16,62 +16,89 @@ function getVendorBundleConditions(specifier) {
16
16
  }
17
17
  /**
18
18
  * Lazily prebundles bare npm imports into process-local `/assets/vendors/*` chunks.
19
+ *
20
+ * @remarks
21
+ * A vendor bundle keeps the ESM imports of other packages external and points them at those packages' own
22
+ * vendor URLs, so a package shared by several vendors, such as a framework core, loads once in the browser
23
+ * and keeps one module identity. `require()` calls stay bundled, since a vendor URL is an ES module that
24
+ * `require()` cannot load.
19
25
  */
20
26
  export class DevTransformVendorRegistry {
21
27
  appConfig;
22
28
  browserBundleService;
23
29
  resolveVendorBundlePlugins;
24
- cache = new Map();
25
- inFlight = new Map();
30
+ records = new Map();
31
+ recordsByUrl = new Map();
26
32
  constructor(options) {
27
33
  this.appConfig = options.appConfig;
28
34
  this.browserBundleService = new BrowserBundleService(options.appConfig);
29
35
  this.resolveVendorBundlePlugins = options.resolveVendorBundlePlugins;
30
36
  }
31
37
  async resolveVendorUrl(specifier) {
32
- const cached = this.cache.get(specifier);
33
- if (cached) {
34
- return cached.url;
35
- }
36
- const pending = this.inFlight.get(specifier);
37
- if (pending) {
38
- return (await pending).url;
39
- }
40
- const promise = this.prebundleSpecifier(specifier)
41
- .then((entry) => {
42
- if (this.inFlight.get(specifier) === promise) {
43
- this.cache.set(specifier, entry);
44
- }
45
- return entry;
46
- })
47
- .finally(() => {
48
- if (this.inFlight.get(specifier) === promise) {
49
- this.inFlight.delete(specifier);
50
- }
51
- });
52
- this.inFlight.set(specifier, promise);
53
- return (await promise).url;
38
+ const entryPath = this.resolvePackageEntry(specifier, this.appConfig.rootDir);
39
+ const record = this.ensureVendor(specifier, entryPath);
40
+ await record.build;
41
+ return record.url;
54
42
  }
55
43
  /**
56
44
  * @remarks
57
- * Responses carry `no-cache` and a content `ETag`, so browsers revalidate each
58
- * load and get `304` while `ifNoneMatch` still matches the in-memory bundle.
45
+ * A vendor that another vendor references may still be building when the browser asks for it, so the
46
+ * request waits for that build. Responses carry `no-cache` and a content `ETag`, so browsers revalidate
47
+ * each load and get `304` while `ifNoneMatch` still matches the in-memory bundle.
59
48
  */
60
- tryHandleVendorRequest(pathname, ifNoneMatch) {
61
- const prefix = `/${RESOLVED_ASSETS_VENDORS_DIR}/`;
62
- if (!pathname.startsWith(prefix)) {
49
+ async tryHandleVendorRequest(pathname, ifNoneMatch) {
50
+ if (!pathname.startsWith(`/${RESOLVED_ASSETS_VENDORS_DIR}/`)) {
63
51
  return null;
64
52
  }
65
- const fileName = pathname.slice(prefix.length);
66
- if (!fileName || fileName.includes('..')) {
53
+ const record = this.recordsByUrl.get(pathname);
54
+ if (!record) {
67
55
  return null;
68
56
  }
69
- const entry = [...this.cache.values()].find((cachedEntry) => cachedEntry.url === pathname);
70
- return entry ? this.createVendorResponse(entry, ifNoneMatch) : null;
57
+ try {
58
+ return this.createVendorResponse(await record.build, ifNoneMatch);
59
+ }
60
+ catch (error) {
61
+ return new Response(error instanceof Error ? error.message : String(error), {
62
+ status: 500,
63
+ headers: { 'Content-Type': 'text/plain', 'Cache-Control': 'no-store' },
64
+ });
65
+ }
71
66
  }
72
67
  invalidateAll() {
73
- this.cache.clear();
74
- this.inFlight.clear();
68
+ this.records = new Map();
69
+ this.recordsByUrl = new Map();
70
+ }
71
+ /**
72
+ * Returns the record for a package entry, starting its build when no build exists yet.
73
+ *
74
+ * @remarks
75
+ * The build is not awaited here: two vendors that import each other would otherwise wait on each other.
76
+ * Failures are kept on the record and reported to whoever awaits the build or requests the URL.
77
+ */
78
+ ensureVendor(specifier, entryPath) {
79
+ const existing = this.records.get(entryPath);
80
+ if (existing) {
81
+ return existing;
82
+ }
83
+ const records = this.records;
84
+ const record = {
85
+ specifier,
86
+ entryPath,
87
+ url: `/${RESOLVED_ASSETS_VENDORS_DIR}/${sanitizeSpecifierForFileName(specifier)}.${contentHash(entryPath, 8)}.js`,
88
+ build: Promise.resolve(undefined),
89
+ };
90
+ record.build = this.prebundle(record).then((entry) => {
91
+ if (this.records === records)
92
+ record.entry = entry;
93
+ return entry;
94
+ }, (error) => {
95
+ record.error = error;
96
+ throw error;
97
+ });
98
+ record.build.catch(() => { });
99
+ this.records.set(entryPath, record);
100
+ this.recordsByUrl.set(record.url, record);
101
+ return record;
75
102
  }
76
103
  createVendorResponse(entry, ifNoneMatch) {
77
104
  const etag = `"${contentHash(entry.content, 16)}"`;
@@ -83,38 +110,62 @@ export class DevTransformVendorRegistry {
83
110
  headers: { ...headers, 'Content-Type': 'application/javascript' },
84
111
  });
85
112
  }
86
- async prebundleSpecifier(specifier) {
87
- const resolvedEntry = this.resolvePackageEntry(specifier);
88
- const fileName = `${sanitizeSpecifierForFileName(specifier)}.${hashVendorSpecifier(specifier)}.js`;
89
- const url = `/${RESOLVED_ASSETS_VENDORS_DIR}/${fileName}`;
113
+ async prebundle(record) {
90
114
  const vendorPlugins = this.resolveVendorBundlePlugins ? await this.resolveVendorBundlePlugins() : [];
91
115
  const result = await this.browserBundleService.bundle({
92
116
  lane: 'build',
93
- entrypoints: [resolvedEntry.path],
117
+ entrypoints: [record.entryPath],
94
118
  outdir: path.join(this.appConfig.absolutePaths.workDir, 'vendor-memory'),
95
- naming: fileName,
119
+ naming: path.basename(record.url),
96
120
  writeToDisk: false,
97
121
  minify: false,
98
122
  externalPackages: false,
99
123
  treeshaking: true,
100
124
  splitting: false,
101
- conditions: [...getVendorBundleConditions(specifier)],
125
+ conditions: [...getVendorBundleConditions(record.specifier)],
102
126
  excludeAppBuildPlugins: resolveAppBuildPlugins(this.appConfig, 'browser').map((plugin) => plugin.name),
103
- plugins: [...vendorPlugins],
127
+ plugins: [...vendorPlugins, this.createSharedPackagePlugin(record)],
104
128
  });
105
- assertBuildSucceeded(result, (details) => formatVendorPrebundleError(specifier, details));
129
+ assertBuildSucceeded(result, (details) => formatVendorPrebundleError(record.specifier, details));
106
130
  const output = result.outputs.find((candidate) => typeof candidate.content === 'string');
107
131
  if (!output || typeof output.content !== 'string') {
108
- throw new Error(`[dev-transform] Vendor prebundle produced no in-memory JavaScript for ${specifier}`);
132
+ throw new Error(`[dev-transform] Vendor prebundle produced no in-memory JavaScript for ${record.specifier}`);
109
133
  }
110
- return { url, content: output.content };
134
+ return { url: record.url, content: output.content };
111
135
  }
112
- resolvePackageEntry(specifier) {
113
- const resolved = resolveBarePackageBrowserEntry(this.appConfig.rootDir, specifier);
136
+ /**
137
+ * Points the ESM imports of other packages inside one vendor bundle at those packages' vendor URLs.
138
+ *
139
+ * @remarks
140
+ * It runs after the vendor plugins, so a specifier the browser runtime manifest owns keeps the manifest's
141
+ * URL. Each dependency resolves from its importer, where a strict install places it.
142
+ */
143
+ createSharedPackagePlugin(record) {
144
+ return {
145
+ name: 'ecopages-dev-vendor-shared-packages',
146
+ environments: ['browser'],
147
+ setup: (build) => {
148
+ build.onResolve({ filter: /.*/u }, (args) => {
149
+ if (!args.importer || args.namespace)
150
+ return undefined;
151
+ if (args.kind !== 'import-statement' && args.kind !== 'dynamic-import')
152
+ return undefined;
153
+ if (!isBarePackageImportSpecifier(args.path))
154
+ return undefined;
155
+ const dependency = resolveBarePackageBrowserEntry(this.appConfig.rootDir, args.path, path.dirname(args.importer));
156
+ if (!dependency || dependency.path === record.entryPath)
157
+ return undefined;
158
+ return { path: this.ensureVendor(args.path, dependency.path).url, external: true };
159
+ });
160
+ },
161
+ };
162
+ }
163
+ resolvePackageEntry(specifier, fromDirectory) {
164
+ const resolved = resolveBarePackageBrowserEntry(this.appConfig.rootDir, specifier, fromDirectory);
114
165
  if (!resolved) {
115
166
  throw new Error(`[dev-transform] Unable to resolve bare import "${specifier}" for vendor prebundle`);
116
167
  }
117
- return { path: resolved.path };
168
+ return resolved.path;
118
169
  }
119
170
  }
120
171
  function formatVendorPrebundleError(specifier, details) {
@@ -130,9 +181,6 @@ function formatVendorPrebundleError(specifier, details) {
130
181
  function sanitizeSpecifierForFileName(specifier) {
131
182
  return specifier.replaceAll(/^@/gu, '').replaceAll(/[/:@]/gu, '-');
132
183
  }
133
- function hashVendorSpecifier(specifier) {
134
- return contentHash(specifier, 8);
135
- }
136
184
  /**
137
185
  * Whether an `If-None-Match` header matches `etag` under the weak comparison of
138
186
  * RFC 9110: any listed tag equal to it once `W/` is stripped, or `*`.
@@ -22,6 +22,15 @@ export declare class HttpError extends Error {
22
22
  * Prefer this over `instanceof` when catching errors from app page bundles.
23
23
  */
24
24
  static isHttpError(error: unknown): error is HttpError;
25
+ /**
26
+ * Answers with an error's status and JSON body, whichever `HttpError` class threw it.
27
+ *
28
+ * @remarks
29
+ * An error that passed {@link HttpError.isHttpError} may come from an app bundle's own copy of
30
+ * this class, or be a duck-typed object without `toResponse()`, so the response is rebuilt from
31
+ * its fields.
32
+ */
33
+ static responseFor(error: HttpError): Response;
25
34
  /**
26
35
  * Serialize error to JSON for API responses.
27
36
  */
@@ -27,6 +27,17 @@ export class HttpError extends Error {
27
27
  error.name === 'HttpError' &&
28
28
  typeof error.status === 'number');
29
29
  }
30
+ /**
31
+ * Answers with an error's status and JSON body, whichever `HttpError` class threw it.
32
+ *
33
+ * @remarks
34
+ * An error that passed {@link HttpError.isHttpError} may come from an app bundle's own copy of
35
+ * this class, or be a duck-typed object without `toResponse()`, so the response is rebuilt from
36
+ * its fields.
37
+ */
38
+ static responseFor(error) {
39
+ return new HttpError(error.status, error.message, error.details).toResponse();
40
+ }
30
41
  /**
31
42
  * Serialize error to JSON for API responses.
32
43
  */
@@ -1,4 +1,3 @@
1
- import type { ProcessedAsset } from '../assets/asset-processing-service/assets.types.js';
2
1
  import type { PagePackageResult } from '../types/contracts.js';
3
2
  export type HtmlDocumentContributionPlacement = 'head-prepend' | 'head-append' | 'body-prepend' | 'body-append';
4
3
  export type HtmlDocumentContribution = {
@@ -26,30 +25,10 @@ export declare class HtmlTransformerService {
26
25
  * Sets attributes on the first `<html>` start tag.
27
26
  */
28
27
  applyAttributesToHtmlElement(html: string, attributes: Record<string, string>): string;
29
- /**
30
- * Sets attributes on the element that directly follows the `<body>` start tag.
31
- *
32
- * @remarks
33
- * Nothing is stamped when text or a comment comes first (whitespace aside).
34
- */
35
- applyAttributesToFirstBodyElement(html: string, attributes: Record<string, string>): string;
36
- /**
37
- * Removes duplicate processed assets while preserving first-seen order.
38
- *
39
- * @remarks
40
- * Dedupe keys include structural asset fields and HTML attributes so repeated
41
- * orchestration passes can merge assets safely without collapsing distinct tag
42
- * variants.
43
- */
44
- dedupeProcessedAssets(assets: ProcessedAsset[]): ProcessedAsset[];
45
28
  /**
46
29
  * Injects page assets and document contributions into a streaming HTML response.
47
30
  */
48
31
  transform(res: Response, input?: PageAssetInjection): Response;
49
- /**
50
- * Injects page assets and document contributions into a complete HTML string.
51
- */
52
- injectPageAssets(html: string, input?: PageAssetInjection): string;
53
32
  /**
54
33
  * @remarks
55
34
  * Each slot is inserted as one joined string, so contributions and assets keep
@@ -43,44 +43,12 @@ export class HtmlTransformerService {
43
43
  applyAttributesToHtmlElement(html, attributes) {
44
44
  return stampAttributes(html, attributes, (element) => element.tagName === 'html');
45
45
  }
46
- /**
47
- * Sets attributes on the element that directly follows the `<body>` start tag.
48
- *
49
- * @remarks
50
- * Nothing is stamped when text or a comment comes first (whitespace aside).
51
- */
52
- applyAttributesToFirstBodyElement(html, attributes) {
53
- let insideBody = false;
54
- return stampAttributes(html, attributes, (element) => {
55
- if (insideBody)
56
- return true;
57
- insideBody = element.tagName === 'body';
58
- return false;
59
- }, { leadingOnly: true });
60
- }
61
- /**
62
- * Removes duplicate processed assets while preserving first-seen order.
63
- *
64
- * @remarks
65
- * Dedupe keys include structural asset fields and HTML attributes so repeated
66
- * orchestration passes can merge assets safely without collapsing distinct tag
67
- * variants.
68
- */
69
- dedupeProcessedAssets(assets) {
70
- return dedupeProcessedAssets(assets);
71
- }
72
46
  /**
73
47
  * Injects page assets and document contributions into a streaming HTML response.
74
48
  */
75
49
  transform(res, input = {}) {
76
50
  return this.createRewriter(input.contributions ?? [], input.pagePackage).transform(res);
77
51
  }
78
- /**
79
- * Injects page assets and document contributions into a complete HTML string.
80
- */
81
- injectPageAssets(html, input = {}) {
82
- return this.createRewriter(input.contributions ?? [], input.pagePackage).transform(html);
83
- }
84
52
  /**
85
53
  * @remarks
86
54
  * Each slot is inserted as one joined string, so contributions and assets keep
@@ -1,3 +1,4 @@
1
+ import type { ComponentIdentity } from '../eco/component-identity.js';
1
2
  import type { EcoPagesAppConfig } from '../config/internal-types.js';
2
3
  import type { EcoComponent, EcoPageFile } from '../types/contracts.js';
3
4
  import { type HtmlTemplate } from './html-page-template.js';
@@ -15,6 +16,10 @@ export declare function warnHtmlTemplateRender(appConfig: EcoPagesAppConfig, fil
15
16
  * Returns the compiled template behind an HTML Page or Html shell component.
16
17
  */
17
18
  export declare function getCompiledHtmlTemplate(component: unknown): HtmlTemplate | undefined;
19
+ export type SerializedHtmlPageModule = {
20
+ template: HtmlTemplate;
21
+ identity?: ComponentIdentity;
22
+ };
18
23
  /**
19
24
  * Builds the module for one HTML Page or the `html.html` shell.
20
25
  *
@@ -26,6 +31,20 @@ export declare function getCompiledHtmlTemplate(component: unknown): HtmlTemplat
26
31
  * one invalidates the cached HTML of every route the template renders into.
27
32
  */
28
33
  export declare function loadHtmlPageModule(appConfig: EcoPagesAppConfig, filePath: string): EcoPageFile;
34
+ /**
35
+ * Records a compiled HTML Page or Html shell so production can import it without compiling.
36
+ *
37
+ * @remarks
38
+ * File paths are stored relative to `rootDir` so the emitted module has no
39
+ * absolute paths of the build machine.
40
+ */
41
+ export declare function serializeHtmlPageModule(module: EcoPageFile, rootDir: string): SerializedHtmlPageModule;
42
+ /**
43
+ * Restores a compiled HTML Page or Html shell from {@link serializeHtmlPageModule}.
44
+ *
45
+ * @param rootDir - App root used to resolve stored relative file paths.
46
+ */
47
+ export declare function reviveHtmlPageModule(data: SerializedHtmlPageModule, rootDir?: string): EcoPageFile;
29
48
  /**
30
49
  * Returns the Html shell HTML Pages use when the app has no `src/includes/html.*`.
31
50
  */
@@ -4,6 +4,7 @@ import { registerDiscoveredDependencies } from '../eco/discovered-dependencies.j
4
4
  import { appLogger } from '../global/app-logger.js';
5
5
  import { requireAppRuntime } from '../utils/app-runtime.js';
6
6
  import { contentHash } from '../utils/content-hash.js';
7
+ import { toRootRelativePath } from '../utils/root-relative-path.js';
7
8
  import { isDevelopmentRuntime } from '../utils/runtime.js';
8
9
  import { compileHtmlPage, compileHtmlShell, getHtmlTemplateWatchFiles, } from './html-page-template.js';
9
10
  export const HTML_PAGES_INTEGRATION_NAME = 'html-pages';
@@ -60,6 +61,24 @@ function createTemplateComponent(template, identity) {
60
61
  [HTML_TEMPLATE]: template,
61
62
  });
62
63
  }
64
+ function assembleHtmlPageFile(template, identity) {
65
+ const component = createTemplateComponent(template, identity);
66
+ if (identity) {
67
+ registerDiscoveredDependencies(identity, {
68
+ components: () => [],
69
+ stylesheets: [],
70
+ watchFiles: getHtmlTemplateWatchFiles(template),
71
+ });
72
+ }
73
+ if (template.kind === 'page') {
74
+ const metadata = ({ appConfig: { defaultMetadata } }) => ({
75
+ ...defaultMetadata,
76
+ ...template.metadata,
77
+ });
78
+ component.metadata = metadata;
79
+ }
80
+ return { default: component };
81
+ }
63
82
  /**
64
83
  * Builds the module for one HTML Page or the `html.html` shell.
65
84
  *
@@ -89,20 +108,54 @@ export function loadHtmlPageModule(appConfig, filePath) {
89
108
  file,
90
109
  integration: HTML_PAGES_INTEGRATION_NAME,
91
110
  };
92
- const component = createTemplateComponent(template, identity);
93
- registerDiscoveredDependencies(identity, {
94
- components: () => [],
95
- stylesheets: [],
96
- watchFiles: getHtmlTemplateWatchFiles(template),
97
- });
98
- if (template.kind === 'page') {
99
- const metadata = ({ appConfig: { defaultMetadata } }) => ({
100
- ...defaultMetadata,
101
- ...template.metadata,
102
- });
103
- component.metadata = metadata;
111
+ return assembleHtmlPageFile(template, identity);
112
+ }
113
+ function relativizeHtmlFilePath(rootDir, filePath) {
114
+ return path.isAbsolute(filePath) ? toRootRelativePath(rootDir, filePath) : filePath;
115
+ }
116
+ function relativizeHtmlTemplate(rootDir, template) {
117
+ const relativize = (filePath) => relativizeHtmlFilePath(rootDir, filePath);
118
+ const assets = template.assets.map((asset) => 'filepath' in asset ? { ...asset, filepath: relativize(asset.filepath) } : asset);
119
+ return { ...template, file: relativize(template.file), assets };
120
+ }
121
+ /**
122
+ * Records a compiled HTML Page or Html shell so production can import it without compiling.
123
+ *
124
+ * @remarks
125
+ * File paths are stored relative to `rootDir` so the emitted module has no
126
+ * absolute paths of the build machine.
127
+ */
128
+ export function serializeHtmlPageModule(module, rootDir) {
129
+ const component = module.default;
130
+ const template = component[HTML_TEMPLATE];
131
+ if (!template) {
132
+ throw new Error('[ecopages] Cannot serialize an HTML Page module that has no compiled template.');
104
133
  }
105
- return { default: component };
134
+ const identity = component.config?.identity;
135
+ return {
136
+ template: relativizeHtmlTemplate(rootDir, template),
137
+ identity: identity?.file ? { ...identity, file: relativizeHtmlFilePath(rootDir, identity.file) } : identity,
138
+ };
139
+ }
140
+ function resolveHtmlFilePath(rootDir, filePath) {
141
+ return path.isAbsolute(filePath) ? filePath : path.join(rootDir, filePath);
142
+ }
143
+ function resolveHtmlTemplate(rootDir, template) {
144
+ const resolve = (filePath) => resolveHtmlFilePath(rootDir, filePath);
145
+ const assets = template.assets.map((asset) => 'filepath' in asset ? { ...asset, filepath: resolve(asset.filepath) } : asset);
146
+ return { ...template, file: resolve(template.file), assets };
147
+ }
148
+ /**
149
+ * Restores a compiled HTML Page or Html shell from {@link serializeHtmlPageModule}.
150
+ *
151
+ * @param rootDir - App root used to resolve stored relative file paths.
152
+ */
153
+ export function reviveHtmlPageModule(data, rootDir) {
154
+ const template = rootDir ? resolveHtmlTemplate(rootDir, data.template) : data.template;
155
+ const identity = rootDir && data.identity?.file
156
+ ? { ...data.identity, file: resolveHtmlFilePath(rootDir, data.identity.file) }
157
+ : data.identity;
158
+ return assembleHtmlPageFile(template, identity);
106
159
  }
107
160
  /**
108
161
  * Returns the Html shell HTML Pages use when the app has no `src/includes/html.*`.
@@ -19,6 +19,10 @@ export declare class HtmlPageRenderer extends StringMarkupRenderer {
19
19
  name: string;
20
20
  private readonly renderedHeads;
21
21
  constructor(options: IntegrationRendererOptions);
22
+ /**
23
+ * Loads the Html shell from disk, or from the production server-modules map
24
+ * when the source file is not in the deploy.
25
+ */
22
26
  protected getHtmlTemplate(): Promise<EcoComponent<HtmlTemplateProps>>;
23
27
  /**
24
28
  * Renders the `html.html` shell, including when a Page owned by another
@@ -31,10 +35,11 @@ export declare class HtmlPageRenderer extends StringMarkupRenderer {
31
35
  * A direct call reconciles here, so the Page head is never dropped.
32
36
  */
33
37
  render(options: IntegrationRendererRenderOptions): Promise<RouteRendererBody>;
38
+ renderRouteBody(options: InternalIntegrationRendererRenderOptions): Promise<RouteRendererBody>;
34
39
  /**
35
40
  * Renders the Page body and retains its head until core document contributions have been applied.
36
41
  */
37
- renderRouteBody(options: InternalIntegrationRendererRenderOptions): Promise<RouteRendererBody>;
42
+ protected renderRouteDocument(options: IntegrationRendererRenderOptions): Promise<RouteRendererBody>;
38
43
  private finalizeHtmlPageDocument;
39
44
  private renderHtmlPage;
40
45
  /**
@@ -1,6 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import { fileSystem } from '@ecopages/file-system';
3
3
  import { AssetFactory } from '../assets/asset-processing-service/asset.factory.js';
4
+ import { hasProductionServerModule } from '../build/server/server-modules-manifest.js';
4
5
  import { StringMarkupRenderer } from '../route-renderer/orchestration/string-markup-renderer.js';
5
6
  import { findElements, parseHtml } from '../html/html-source-parser.js';
6
7
  import { escapeHtmlAttribute } from '../utils/html-escaping.js';
@@ -62,12 +63,17 @@ export class HtmlPageRenderer extends StringMarkupRenderer {
62
63
  finalizeDocument: (body, renderOptions) => this.finalizeHtmlPageDocument(body, renderOptions),
63
64
  };
64
65
  }
66
+ /**
67
+ * Loads the Html shell from disk, or from the production server-modules map
68
+ * when the source file is not in the deploy.
69
+ */
65
70
  async getHtmlTemplate() {
66
71
  const htmlTemplatePath = this.appConfig.absolutePaths.htmlTemplatePath;
67
- if (!htmlTemplatePath || !fileSystem.exists(htmlTemplatePath)) {
68
- return getBuiltInHtmlShell();
72
+ if (htmlTemplatePath &&
73
+ (fileSystem.exists(htmlTemplatePath) || hasProductionServerModule(this.appConfig, htmlTemplatePath))) {
74
+ return super.getHtmlTemplate();
69
75
  }
70
- return super.getHtmlTemplate();
76
+ return getBuiltInHtmlShell();
71
77
  }
72
78
  /**
73
79
  * Renders the `html.html` shell, including when a Page owned by another
@@ -86,13 +92,15 @@ export class HtmlPageRenderer extends StringMarkupRenderer {
86
92
  * A direct call reconciles here, so the Page head is never dropped.
87
93
  */
88
94
  async render(options) {
89
- const { html, head } = await this.renderHtmlPage(options);
90
- return reconcileHtmlPageDocument(html, head);
95
+ return this.finalizeHtmlPageDocument(await super.render(options), options);
96
+ }
97
+ async renderRouteBody(options) {
98
+ return super.render(options);
91
99
  }
92
100
  /**
93
101
  * Renders the Page body and retains its head until core document contributions have been applied.
94
102
  */
95
- async renderRouteBody(options) {
103
+ async renderRouteDocument(options) {
96
104
  const rendered = await this.renderHtmlPage(options);
97
105
  this.renderedHeads.set(options, rendered.head);
98
106
  return rendered.html;
@@ -20,4 +20,14 @@ export declare class HtmlPagesPlugin extends IntegrationPlugin {
20
20
  * @throws For any other `.html` file, which is neither a Page nor the HTML template.
21
21
  */
22
22
  compilePageModule(filePath: string, appConfig: EcoPagesAppConfig): EcoPageFile;
23
+ serializeCompiledPageModule(module: EcoPageFile, context: {
24
+ rootDir: string;
25
+ filePath: string;
26
+ }): {
27
+ contents: string;
28
+ };
29
+ reviveCompiledPageModule(contents: string, context: {
30
+ rootDir: string;
31
+ filePath: string;
32
+ }): EcoPageFile;
23
33
  }
@@ -1,6 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import { IntegrationPlugin } from '../plugins/integration-plugin.js';
3
- import { HTML_PAGES_INTEGRATION_NAME, loadHtmlPageModule } from './html-page-module.js';
3
+ import { HTML_PAGES_INTEGRATION_NAME, loadHtmlPageModule, reviveHtmlPageModule, serializeHtmlPageModule, } from './html-page-module.js';
4
4
  import { HtmlPageRenderer } from './html-page-renderer.js';
5
5
  /**
6
6
  * Core-owned Integration for `.html` Filesystem Routes.
@@ -29,4 +29,10 @@ export class HtmlPagesPlugin extends IntegrationPlugin {
29
29
  }
30
30
  return loadHtmlPageModule(appConfig, file);
31
31
  }
32
+ serializeCompiledPageModule(module, context) {
33
+ return { contents: `${JSON.stringify(serializeHtmlPageModule(module, context.rootDir))}\n` };
34
+ }
35
+ reviveCompiledPageModule(contents, context) {
36
+ return reviveHtmlPageModule(JSON.parse(contents), context.rootDir);
37
+ }
32
38
  }
package/src/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  export type * from './types/public-types.js';
2
2
  export { eco } from './eco/eco.js';
3
3
  export { defineApiHandler, defineGroupHandler, defineGet, definePost, definePut, defineDelete, definePatch, defineOptions, defineHead, defineQuery, json, html, redirect, type GroupHandler, } from './adapters/shared/http/define-api-handler.js';
4
+ export { createViewReference } from './build/server/view-reference.js';
5
+ export { VIEW_REFERENCE, isViewReference } from './types/view-reference.js';
4
6
  export { attributeMdxComponentIdentity } from './plugins/eco-component-meta-plugin.js';
5
7
  export { bindComponentIdentity, getComponentIdentity, getComponentOwner, type ComponentIdentity, } from './eco/component-identity.js';
6
8
  export { attachDiscoveredDependencies } from './eco/discovered-dependencies.js';