@ecopages/core 0.2.0-rc.10 → 0.2.0-rc.13

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 (161) hide show
  1. package/README.md +0 -9
  2. package/package.json +3 -152
  3. package/src/adapters/README.md +8 -2
  4. package/src/adapters/abstract/application-adapter.d.ts +6 -32
  5. package/src/adapters/abstract/application-adapter.js +6 -45
  6. package/src/adapters/abstract/ws-pattern-matcher.d.ts +0 -5
  7. package/src/adapters/abstract/ws-pattern-matcher.js +0 -9
  8. package/src/adapters/bun/create-app.d.ts +8 -12
  9. package/src/adapters/bun/create-app.js +13 -55
  10. package/src/adapters/bun/hmr-manager.d.ts +0 -1
  11. package/src/adapters/bun/hmr-manager.js +2 -4
  12. package/src/adapters/bun/server-adapter.d.ts +9 -19
  13. package/src/adapters/bun/server-adapter.js +19 -66
  14. package/src/adapters/bun/static-preview-host.d.ts +1 -0
  15. package/src/adapters/bun/static-preview-host.js +1 -1
  16. package/src/adapters/create-app.d.ts +1 -1
  17. package/src/adapters/create-app.js +2 -1
  18. package/src/adapters/node/create-app.d.ts +4 -8
  19. package/src/adapters/node/create-app.js +7 -12
  20. package/src/adapters/node/runtime-host.d.ts +10 -10
  21. package/src/adapters/node/runtime-host.js +4 -4
  22. package/src/adapters/node/server-adapter-dependencies.d.ts +2 -10
  23. package/src/adapters/node/server-adapter-dependencies.js +8 -13
  24. package/src/adapters/node/server-adapter.d.ts +25 -31
  25. package/src/adapters/node/server-adapter.js +43 -64
  26. package/src/adapters/shared/hmr/shared-hmr-manager.d.ts +0 -4
  27. package/src/adapters/shared/hmr/shared-hmr-manager.js +0 -12
  28. package/src/adapters/shared/http/api-request-pipeline.d.ts +27 -1
  29. package/src/adapters/shared/http/api-request-pipeline.js +31 -16
  30. package/src/adapters/shared/http/fs-server-response-factory.d.ts +0 -1
  31. package/src/adapters/shared/http/fs-server-response-factory.js +0 -3
  32. package/src/adapters/shared/runtime/collect-dev-prewarm-plan.d.ts +1 -3
  33. package/src/adapters/shared/runtime/collect-dev-prewarm-plan.js +1 -4
  34. package/src/adapters/shared/runtime/runtime-app-bootstrap.d.ts +0 -10
  35. package/src/adapters/shared/runtime/runtime-app-bootstrap.js +0 -7
  36. package/src/adapters/shared/runtime/runtime-host.d.ts +5 -2
  37. package/src/adapters/shared/runtime/runtime-server-lifecycle.d.ts +1 -1
  38. package/src/adapters/shared/runtime/runtime-server-lifecycle.js +1 -1
  39. package/src/adapters/shared/runtime/server-adapter.d.ts +13 -0
  40. package/src/adapters/shared/runtime/server-adapter.js +22 -0
  41. package/src/adapters/shared/ws/node-http-websocket-upgrades.d.ts +9 -1
  42. package/src/adapters/shared/ws/node-http-websocket-upgrades.js +8 -2
  43. package/src/build/README.md +5 -6
  44. package/src/build/cache/cache-constants.d.ts +0 -2
  45. package/src/build/cache/cache-constants.js +0 -2
  46. package/src/build/cache/cache-keys.d.ts +0 -2
  47. package/src/build/cache/cache-keys.js +0 -2
  48. package/src/build/cache/output-imports.d.ts +35 -0
  49. package/src/build/cache/output-imports.js +87 -0
  50. package/src/build/cache/pages-unified-graph-build.d.ts +6 -1
  51. package/src/build/cache/pages-unified-graph-build.js +49 -18
  52. package/src/build/cache/production-build-cache.d.ts +2 -2
  53. package/src/build/cache/production-build-cache.js +2 -2
  54. package/src/build/cache/server-entry-build-cache.d.ts +1 -2
  55. package/src/build/cache/server-entry-build-cache.js +4 -5
  56. package/src/build/contracts/build-contracts.d.ts +1 -13
  57. package/src/build/rolldown/runtime-build-output-normalizer.js +3 -6
  58. package/src/build/runtime/build-request-identity.d.ts +2 -6
  59. package/src/build/runtime/build-request-identity.js +2 -8
  60. package/src/build/runtime/deduping-build-executor.d.ts +0 -1
  61. package/src/build/runtime/deduping-build-executor.js +0 -1
  62. package/src/cache/index.d.ts +1 -1
  63. package/src/cache/index.js +1 -1
  64. package/src/cache/module-parse-cache.d.ts +2 -29
  65. package/src/cache/module-parse-cache.js +6 -39
  66. package/src/config/README.md +3 -3
  67. package/src/config/apply-user-config.d.ts +3 -1
  68. package/src/config/apply-user-config.js +3 -2
  69. package/src/config/config-builder.d.ts +1 -0
  70. package/src/config/config-builder.js +2 -2
  71. package/src/config/constants.d.ts +0 -4
  72. package/src/config/constants.js +0 -4
  73. package/src/config/index.d.ts +1 -1
  74. package/src/config/index.js +1 -1
  75. package/src/config/load-eco-config.d.ts +1 -1
  76. package/src/config/load-eco-config.js +18 -11
  77. package/src/config/resolve-eco-config-path.d.ts +9 -0
  78. package/src/config/resolve-eco-config-path.js +11 -0
  79. package/src/config/server-config-bundle.js +2 -2
  80. package/src/config/user-config-types.d.ts +9 -3
  81. package/src/dev/host-runtime.d.ts +0 -1
  82. package/src/dev/host-runtime.js +0 -3
  83. package/src/dev/sc-server.d.ts +4 -1
  84. package/src/dev/sc-server.js +11 -20
  85. package/src/dev/transform-server/dev-transform-import-rewriter.js +2 -2
  86. package/src/hmr/hmr-file-change-prep.d.ts +0 -1
  87. package/src/hmr/hmr-file-change-prep.js +2 -5
  88. package/src/hmr/hmr-strategy.d.ts +3 -8
  89. package/src/hmr/hmr-strategy.js +3 -8
  90. package/src/index.browser.d.ts +1 -2
  91. package/src/index.browser.js +1 -2
  92. package/src/index.d.ts +5 -6
  93. package/src/index.js +5 -6
  94. package/src/islands/island-host.d.ts +0 -9
  95. package/src/islands/island-host.js +1 -13
  96. package/src/plugins/component-import-discovery.js +2 -2
  97. package/src/plugins/eco-component-meta-plugin.js +5 -5
  98. package/src/plugins/integration-plugin.d.ts +0 -1
  99. package/src/plugins/integration-plugin.js +0 -4
  100. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.js +1 -4
  101. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.d.ts +25 -24
  102. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.js +18 -20
  103. package/src/route-renderer/orchestration/integration-renderer.d.ts +24 -7
  104. package/src/route-renderer/orchestration/integration-renderer.js +44 -33
  105. package/src/route-renderer/orchestration/integration-renderer.test-fixtures.js +1 -1
  106. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.d.ts +1 -1
  107. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.js +1 -1
  108. package/src/services/README.md +1 -1
  109. package/src/services/assets/browser-bundle.service.d.ts +1 -6
  110. package/src/services/error-pages/default-error-pages.d.ts +1 -6
  111. package/src/services/error-pages/default-error-pages.js +0 -8
  112. package/src/services/html/html-rewriter.d.ts +77 -0
  113. package/src/services/html/html-rewriter.js +751 -0
  114. package/src/services/html/html-rewriter.parity.test.bun.d.ts +1 -0
  115. package/src/services/html/html-rewriter.parity.test.bun.js +74 -0
  116. package/src/services/html/html-transformer.service.d.ts +29 -42
  117. package/src/services/html/html-transformer.service.js +85 -157
  118. package/src/services/invalidation/development-invalidation.service.d.ts +2 -19
  119. package/src/services/invalidation/development-invalidation.service.js +1 -39
  120. package/src/services/module-loading/README.md +1 -1
  121. package/src/services/module-loading/app-module-loader.service.d.ts +0 -2
  122. package/src/services/module-loading/app-server-module-transpiler.service.d.ts +1 -1
  123. package/src/services/module-loading/app-server-module-transpiler.service.js +0 -10
  124. package/src/services/module-loading/collection-server-module-build.service.d.ts +0 -1
  125. package/src/services/module-loading/collection-server-module-build.service.js +0 -3
  126. package/src/services/module-loading/host-module-loader-registry.d.ts +0 -1
  127. package/src/services/module-loading/host-module-loader-registry.js +0 -3
  128. package/src/services/module-loading/route-module-build-cache-registry.d.ts +0 -4
  129. package/src/services/module-loading/route-module-build-cache-registry.js +0 -4
  130. package/src/services/module-loading/route-module-build-cache.store.d.ts +3 -0
  131. package/src/services/module-loading/route-module-build-cache.store.js +20 -5
  132. package/src/services/module-loading/route-module-build-manifest.d.ts +12 -1
  133. package/src/services/module-loading/route-module-build-manifest.js +7 -3
  134. package/src/services/module-loading/route-module-dependency-hasher.d.ts +3 -2
  135. package/src/services/module-loading/server-module-transpiler.service.d.ts +1 -15
  136. package/src/services/module-loading/server-module-transpiler.service.js +0 -24
  137. package/src/services/runtime-state/entrypoint-dependency-graph.service.js +0 -12
  138. package/src/services/runtime-state/server-invalidation-state.service.d.ts +4 -2
  139. package/src/services/runtime-state/server-invalidation-state.service.js +7 -14
  140. package/src/types/internal-types.d.ts +0 -38
  141. package/src/types/public-types.d.ts +0 -112
  142. package/src/watchers/project-watcher.d.ts +0 -15
  143. package/src/watchers/project-watcher.js +1 -27
  144. package/src/watchers/project-watcher.test-helpers.d.ts +10 -1
  145. package/src/watchers/project-watcher.test-helpers.js +12 -0
  146. package/src/adapters/abstract/router-adapter.d.ts +0 -26
  147. package/src/adapters/abstract/router-adapter.js +0 -13
  148. package/src/adapters/bun/index.d.ts +0 -2
  149. package/src/adapters/bun/index.js +0 -2
  150. package/src/adapters/index.d.ts +0 -2
  151. package/src/adapters/index.js +0 -2
  152. package/src/eco/eco.utils.d.ts +0 -1
  153. package/src/eco/eco.utils.js +0 -1
  154. package/src/services/cache/index.d.ts +0 -9
  155. package/src/services/cache/index.js +0 -8
  156. package/src/services/html/html-rewriter-provider.service.d.ts +0 -40
  157. package/src/services/html/html-rewriter-provider.service.js +0 -68
  158. package/src/services/module-loading/route-module-build-cache.d.ts +0 -4
  159. package/src/services/module-loading/route-module-build-cache.js +0 -3
  160. package/src/services/runtime-state/dev-graph.service.d.ts +0 -118
  161. package/src/services/runtime-state/dev-graph.service.js +0 -170
@@ -0,0 +1,74 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { HtmlRewriter } from './html-rewriter.js';
3
+ /**
4
+ * Differential check against Bun's native `HTMLRewriter` (lol-html). Runs only in
5
+ * the `bun-adapter` Vitest project, i.e. when Vitest itself runs on Bun.
6
+ */
7
+ const CORPUS = [
8
+ '<html><head><title>T</title></head><body><main>M</main></body></html>',
9
+ '<html><head><title>T</title><body><main>M</main>',
10
+ '<html><head><script>const s = "</head><body>";</script></head><body><!-- <body> --><textarea></body></textarea><main>M</main></body></html>',
11
+ '<head><title></head>fake</title><noscript></head></noscript></head>',
12
+ '<body><style>a{content:"</body>"}</style><iframe></body></iframe><xmp></body></xmp></body>',
13
+ '<body><script><!--<script>x</script>--></script></body>',
14
+ '<head><SCRIPT>x="</head>"</SCRIPT ></head >',
15
+ '<body><!--><head><!---></body>',
16
+ '<div id="a"><div id="b">x</div></div><body><body>inner</body></body>',
17
+ '<head><meta charset="x"><link rel="x"></head><svg><path d="m0"/></svg><br/><div/><p>x</p></div>',
18
+ `<html LANG=en data-x='1' hidden><body class="a b" data-y="a>b"></body></html>`,
19
+ '<!DOCTYPE html><?xml x?><HTML><HEAD></HEAD><BODY></BODY></HTML>',
20
+ '<template><body></body></template>',
21
+ '<body\n class="x"\n>y</body\n>',
22
+ '<body><svg><![CDATA[ a > </body> ]]></svg><![CDATA[ b > </body> ]]></body>',
23
+ '<body><svg><foreignObject><style>a</body>b</style></foreignObject><p><style>c</body>d</style></p></svg></body>',
24
+ '<body><svg><font color="r"><style>a</body>b</style></font></svg><math><mi><style>c</body></style></mi></math></body>',
25
+ '<body><!--a--!></body foo="</body>"><div a=/><div a="x"/ b="y"><br/></body>',
26
+ ];
27
+ const TAGS = ['html', 'head', 'body', 'main', 'div', 'meta', 'link', 'path', 'br', 'script'];
28
+ function handlers(tag) {
29
+ return {
30
+ element(element) {
31
+ element.before(`[B:${tag}]`, { html: true });
32
+ element.prepend(`[P:${tag}]`, { html: true });
33
+ element.append(`[A:${tag}]`, { html: true });
34
+ element.after(`<F:${tag}>`);
35
+ if (tag === 'html')
36
+ element.setAttribute('data-eco', 'x"y');
37
+ },
38
+ };
39
+ }
40
+ const SERIALIZE_CORPUS = [
41
+ '<div a="1"/>',
42
+ '<div\n a="1"\n b=\'2\'\n c\n>',
43
+ '<DIV A="1" b = 2/>',
44
+ '<div a=/>',
45
+ '<div a="x"/ b="y">',
46
+ '<br a="1"/>',
47
+ '<svg><path d="1" /></svg>',
48
+ ];
49
+ const MUTATIONS = [
50
+ (element) => element.setAttribute('z', 'v"w'),
51
+ (element) => element.setAttribute('a', '2').prepend('[P]', { html: true }),
52
+ (element) => element.removeAttribute('a'),
53
+ ];
54
+ describe('HtmlRewriter parity with Bun HTMLRewriter', () => {
55
+ it.each(CORPUS)('matches native output for %s', (html) => {
56
+ let native = new HTMLRewriter();
57
+ const ours = new HtmlRewriter();
58
+ for (const tag of TAGS) {
59
+ native = native.on(tag, handlers(tag));
60
+ ours.on(tag, handlers(tag));
61
+ }
62
+ expect(ours.transform(html)).toBe(native.transform(html));
63
+ });
64
+ it.each(SERIALIZE_CORPUS)('re-serialises changed tags like native for %s', (html) => {
65
+ for (const mutate of MUTATIONS) {
66
+ const tag = html.includes('<path') ? 'path' : html.toLowerCase().includes('<br') ? 'br' : 'div';
67
+ const native = new HTMLRewriter().on(tag, {
68
+ element: mutate,
69
+ });
70
+ const ours = new HtmlRewriter().on(tag, { element: mutate });
71
+ expect(ours.transform(html)).toBe(native.transform(html));
72
+ }
73
+ });
74
+ });
@@ -1,42 +1,18 @@
1
1
  import type { ProcessedAsset } from '../assets/asset-processing-service/assets.types.js';
2
2
  import type { PagePackageResult } from '../../types/public-types.js';
3
- import { type HtmlRewriterMode, type HtmlRewriterProvider } from './html-rewriter-provider.service.js';
4
3
  export type HtmlDocumentContributionPlacement = 'head-prepend' | 'head-append' | 'body-prepend' | 'body-append';
5
4
  export type HtmlDocumentContribution = {
6
5
  placement: HtmlDocumentContributionPlacement;
7
6
  html: string;
8
7
  };
9
- export interface HtmlTransformerServiceOptions {
10
- htmlRewriterMode?: HtmlRewriterMode;
11
- htmlRewriterProvider?: HtmlRewriterProvider;
12
- }
13
8
  export declare class HtmlTransformerService {
14
9
  private processedDependencies;
15
10
  private pagePackage?;
16
- private htmlRewriterProvider;
17
- constructor(options?: HtmlTransformerServiceOptions);
18
- /**
19
- * Overrides the HTML rewriter runtime selection.
20
- *
21
- * This is intended for internal/runtime tests that need deterministic
22
- * selection between native, worker-tools, and string fallback behavior.
23
- *
24
- * @param mode Requested runtime selection strategy.
25
- */
26
- setHtmlRewriterMode(mode: HtmlRewriterMode): void;
27
11
  private formatAttributes;
28
12
  private generateScriptTag;
29
13
  private generateStylesheetTag;
30
- private appendDependencies;
31
14
  private buildDependencyTags;
32
- private applyContributions;
33
- /**
34
- * Injects generated markup immediately before the closing HTML tag when it is
35
- * present, or appends/prepends a fallback insertion otherwise.
36
- */
37
- private injectBeforeClosingTag;
38
- private injectAfterOpeningTag;
39
- private groupContributionsByPlacement;
15
+ private joinContributions;
40
16
  /**
41
17
  * Replaces the current processed dependency set used during HTML finalization.
42
18
  */
@@ -54,18 +30,16 @@ export declare class HtmlTransformerService {
54
30
  */
55
31
  getPagePackage(): PagePackageResult | undefined;
56
32
  /**
57
- * Applies attributes to the opening `<html>` tag when present.
33
+ * Sets attributes on the first `<html>` start tag.
58
34
  */
59
35
  applyAttributesToHtmlElement(html: string, attributes: Record<string, string>): string;
60
36
  /**
61
- * Applies attributes to the first element nested directly under `<body>`.
37
+ * Sets attributes on the element that directly follows the `<body>` start tag.
38
+ *
39
+ * @remarks
40
+ * Nothing is stamped when text or a comment comes first (whitespace aside).
62
41
  */
63
42
  applyAttributesToFirstBodyElement(html: string, attributes: Record<string, string>): string;
64
- /**
65
- * Applies attributes to the first element in a fragment or full-document HTML
66
- * string.
67
- */
68
- applyAttributesToFirstElement(html: string, attributes: Record<string, string>): string;
69
43
  /**
70
44
  * Removes duplicate processed assets while preserving first-seen order.
71
45
  *
@@ -76,21 +50,34 @@ export declare class HtmlTransformerService {
76
50
  */
77
51
  dedupeProcessedAssets(assets: ProcessedAsset[]): ProcessedAsset[];
78
52
  /**
79
- * Injects the currently processed dependencies into an HTML response.
80
- *
53
+ * Injects the queued dependencies and document contributions into a streaming
54
+ * HTML response.
55
+ */
56
+ transform(res: Response, contributions?: HtmlDocumentContribution[], pagePackage?: PagePackageResult): Response;
57
+ /**
58
+ * Injects the queued dependencies and document contributions into a complete
59
+ * HTML string.
60
+ */
61
+ transformHtml(html: string, contributions?: HtmlDocumentContribution[], pagePackage?: PagePackageResult): string;
62
+ /**
81
63
  * @remarks
82
- * Native or worker-tools HTML rewriter support is preferred when available. A
83
- * string-based fallback remains in place for runtimes that cannot provide one
84
- * of those rewriter implementations.
64
+ * Each slot is inserted as one joined string, so contributions and assets keep
65
+ * their array order even though repeated `prepend` calls insert in reverse.
66
+ * Documents without a `<head>` or `<body>` element, or whose element never
67
+ * closes, skip the matching head or body injections (lol-html semantics).
85
68
  */
86
- transform(res: Response, contributions?: HtmlDocumentContribution[], pagePackage?: PagePackageResult): Promise<Response>;
69
+ private createRewriter;
87
70
  /**
88
71
  * Splits processed assets into head and body injection groups.
89
72
  */
90
73
  private groupDependenciesByPosition;
91
74
  private resolvePagePackageHtmlDependencies;
92
- /**
93
- * Builds a serialized HTML attribute string from an attribute object.
94
- */
95
- private buildAttributeString;
96
75
  }
76
+ /**
77
+ * Sets attributes on the element a fragment or document starts with.
78
+ *
79
+ * @remarks
80
+ * Nothing is stamped when text or a comment comes first (whitespace aside),
81
+ * so a Lit render that opens with `<!--lit-part-->` keeps its markup.
82
+ */
83
+ export declare function applyAttributesToFirstElement(html: string, attributes: Record<string, string>): string;
@@ -1,26 +1,8 @@
1
- import { DefaultHtmlRewriterProvider, } from './html-rewriter-provider.service.js';
1
+ import { HtmlRewriter, rewriteFirstElement } from './html-rewriter.js';
2
2
  import { buildProcessedAssetDedupeKey, dedupeProcessedAssets, } from '../../route-renderer/orchestration/page-browser-graph/processed-asset-dedupe.js';
3
3
  export class HtmlTransformerService {
4
4
  processedDependencies = [];
5
5
  pagePackage;
6
- htmlRewriterProvider;
7
- constructor(options = {}) {
8
- this.htmlRewriterProvider = options.htmlRewriterProvider ?? new DefaultHtmlRewriterProvider();
9
- if (options.htmlRewriterMode) {
10
- this.htmlRewriterProvider.setMode(options.htmlRewriterMode);
11
- }
12
- }
13
- /**
14
- * Overrides the HTML rewriter runtime selection.
15
- *
16
- * This is intended for internal/runtime tests that need deterministic
17
- * selection between native, worker-tools, and string fallback behavior.
18
- *
19
- * @param mode Requested runtime selection strategy.
20
- */
21
- setHtmlRewriterMode(mode) {
22
- this.htmlRewriterProvider.setMode(mode);
23
- }
24
6
  formatAttributes(attrs) {
25
7
  if (!attrs)
26
8
  return '';
@@ -38,62 +20,16 @@ export class HtmlTransformerService {
38
20
  ? `<style${this.formatAttributes(dep.attributes)}>${dep.content}</style>`
39
21
  : `<link rel="stylesheet" href="${dep.srcUrl}"${this.formatAttributes(dep.attributes)}>`;
40
22
  }
41
- appendDependencies(element, dependencies) {
42
- for (const dep of dependencies) {
43
- const tag = dep.kind === 'script' ? this.generateScriptTag(dep) : this.generateStylesheetTag(dep);
44
- element.append(tag, { html: true });
45
- }
46
- }
47
23
  buildDependencyTags(dependencies) {
48
24
  return dependencies
49
25
  .map((dep) => dep.kind === 'script' ? this.generateScriptTag(dep) : this.generateStylesheetTag(dep))
50
26
  .join('');
51
27
  }
52
- applyContributions(element, contributions, placement) {
53
- for (const contribution of contributions) {
54
- element[placement](contribution.html, { html: true });
55
- }
56
- }
57
- /**
58
- * Injects generated markup immediately before the closing HTML tag when it is
59
- * present, or appends/prepends a fallback insertion otherwise.
60
- */
61
- injectBeforeClosingTag(html, tag, content) {
62
- if (!content) {
63
- return html;
64
- }
65
- const closingTag = `</${tag}>`;
66
- const lowerHtml = html.toLowerCase();
67
- const closingTagIndex = lowerHtml.lastIndexOf(closingTag);
68
- if (closingTagIndex !== -1) {
69
- return `${html.slice(0, closingTagIndex)}${content}${html.slice(closingTagIndex)}`;
70
- }
71
- if (tag === 'head') {
72
- return `${content}${html}`;
73
- }
74
- return `${html}${content}`;
75
- }
76
- injectAfterOpeningTag(html, tag, content) {
77
- if (!content) {
78
- return html;
79
- }
80
- const openingTag = new RegExp(`<${tag}\\b[^>]*>`, 'i');
81
- const match = html.match(openingTag);
82
- if (!match || match.index === undefined) {
83
- return tag === 'head'
84
- ? `${content}${html}`
85
- : html.replace(/<body\b[^>]*>/i, (value) => `${value}${content}`);
86
- }
87
- const insertAt = match.index + match[0].length;
88
- return `${html.slice(0, insertAt)}${content}${html.slice(insertAt)}`;
89
- }
90
- groupContributionsByPlacement(contributions) {
91
- return {
92
- headPrepend: contributions.filter((item) => item.placement === 'head-prepend'),
93
- headAppend: contributions.filter((item) => item.placement === 'head-append'),
94
- bodyPrepend: contributions.filter((item) => item.placement === 'body-prepend'),
95
- bodyAppend: contributions.filter((item) => item.placement === 'body-append'),
96
- };
28
+ joinContributions(contributions, placement) {
29
+ return contributions
30
+ .filter((item) => item.placement === placement)
31
+ .map((item) => item.html)
32
+ .join('');
97
33
  }
98
34
  /**
99
35
  * Replaces the current processed dependency set used during HTML finalization.
@@ -122,56 +58,25 @@ export class HtmlTransformerService {
122
58
  return this.pagePackage;
123
59
  }
124
60
  /**
125
- * Applies attributes to the opening `<html>` tag when present.
61
+ * Sets attributes on the first `<html>` start tag.
126
62
  */
127
63
  applyAttributesToHtmlElement(html, attributes) {
128
- const htmlTagMatch = html.match(/<html\b[^>]*>/i);
129
- if (!htmlTagMatch || htmlTagMatch.index === undefined) {
130
- return html;
131
- }
132
- const attrs = this.buildAttributeString(attributes);
133
- if (attrs.length === 0) {
134
- return html;
135
- }
136
- const injectionOffset = htmlTagMatch.index + htmlTagMatch[0].length - 1;
137
- return `${html.slice(0, injectionOffset)}${attrs}${html.slice(injectionOffset)}`;
64
+ return stampAttributes(html, attributes, (element) => element.tagName === 'html');
138
65
  }
139
66
  /**
140
- * Applies attributes to the first element nested directly under `<body>`.
67
+ * Sets attributes on the element that directly follows the `<body>` start tag.
68
+ *
69
+ * @remarks
70
+ * Nothing is stamped when text or a comment comes first (whitespace aside).
141
71
  */
142
72
  applyAttributesToFirstBodyElement(html, attributes) {
143
- const bodyMatch = html.match(/<body\b[^>]*>/i);
144
- if (!bodyMatch || bodyMatch.index === undefined) {
145
- return html;
146
- }
147
- const bodyOpenEnd = bodyMatch.index + bodyMatch[0].length;
148
- const afterBody = html.slice(bodyOpenEnd);
149
- const firstTagMatch = afterBody.match(/^(\s*<)([a-zA-Z][a-zA-Z0-9:-]*)(\b[^>]*>)/);
150
- if (!firstTagMatch || firstTagMatch.index === undefined) {
151
- return html;
152
- }
153
- const attrs = this.buildAttributeString(attributes);
154
- if (attrs.length === 0) {
155
- return html;
156
- }
157
- const injectionOffset = bodyOpenEnd + firstTagMatch[1].length + firstTagMatch[2].length;
158
- return `${html.slice(0, injectionOffset)}${attrs}${html.slice(injectionOffset)}`;
159
- }
160
- /**
161
- * Applies attributes to the first element in a fragment or full-document HTML
162
- * string.
163
- */
164
- applyAttributesToFirstElement(html, attributes) {
165
- const firstTagMatch = html.match(/^(\s*<)([a-zA-Z][a-zA-Z0-9:-]*)(\b[^>]*>)/);
166
- if (!firstTagMatch || firstTagMatch.index === undefined) {
167
- return html;
168
- }
169
- const attrs = this.buildAttributeString(attributes);
170
- if (attrs.length === 0) {
171
- return html;
172
- }
173
- const injectionOffset = firstTagMatch[1].length + firstTagMatch[2].length;
174
- return `${html.slice(0, injectionOffset)}${attrs}${html.slice(injectionOffset)}`;
73
+ let insideBody = false;
74
+ return stampAttributes(html, attributes, (element) => {
75
+ if (insideBody)
76
+ return true;
77
+ insideBody = element.tagName === 'body';
78
+ return false;
79
+ }, { leadingOnly: true });
175
80
  }
176
81
  /**
177
82
  * Removes duplicate processed assets while preserving first-seen order.
@@ -185,46 +90,52 @@ export class HtmlTransformerService {
185
90
  return dedupeProcessedAssets(assets);
186
91
  }
187
92
  /**
188
- * Injects the currently processed dependencies into an HTML response.
189
- *
93
+ * Injects the queued dependencies and document contributions into a streaming
94
+ * HTML response.
95
+ */
96
+ transform(res, contributions = [], pagePackage) {
97
+ return this.createRewriter(contributions, pagePackage).transform(res);
98
+ }
99
+ /**
100
+ * Injects the queued dependencies and document contributions into a complete
101
+ * HTML string.
102
+ */
103
+ transformHtml(html, contributions = [], pagePackage) {
104
+ return this.createRewriter(contributions, pagePackage).transform(html);
105
+ }
106
+ /**
190
107
  * @remarks
191
- * Native or worker-tools HTML rewriter support is preferred when available. A
192
- * string-based fallback remains in place for runtimes that cannot provide one
193
- * of those rewriter implementations.
108
+ * Each slot is inserted as one joined string, so contributions and assets keep
109
+ * their array order even though repeated `prepend` calls insert in reverse.
110
+ * Documents without a `<head>` or `<body>` element, or whose element never
111
+ * closes, skip the matching head or body injections (lol-html semantics).
194
112
  */
195
- async transform(res, contributions = [], pagePackage) {
113
+ createRewriter(contributions, pagePackage) {
196
114
  const { head, body } = this.groupDependenciesByPosition(pagePackage);
197
- const { headPrepend, headAppend, bodyPrepend, bodyAppend } = this.groupContributionsByPlacement(contributions);
198
- const htmlRewriter = await this.htmlRewriterProvider.createHtmlRewriter();
199
- if (htmlRewriter) {
200
- htmlRewriter
201
- .on('head', {
202
- element: (element) => {
203
- this.applyContributions(element, headPrepend, 'prepend');
204
- this.appendDependencies(element, head);
205
- this.applyContributions(element, headAppend, 'append');
206
- },
207
- })
208
- .on('body', {
209
- element: (element) => {
210
- this.applyContributions(element, bodyPrepend, 'prepend');
211
- this.appendDependencies(element, body);
212
- this.applyContributions(element, bodyAppend, 'append');
115
+ const slots = {
116
+ head: {
117
+ prepend: this.joinContributions(contributions, 'head-prepend'),
118
+ append: `${this.buildDependencyTags(head)}${this.joinContributions(contributions, 'head-append')}`,
119
+ },
120
+ body: {
121
+ prepend: this.joinContributions(contributions, 'body-prepend'),
122
+ append: `${this.buildDependencyTags(body)}${this.joinContributions(contributions, 'body-append')}`,
123
+ },
124
+ };
125
+ const rewriter = new HtmlRewriter();
126
+ for (const [tagName, slot] of Object.entries(slots)) {
127
+ if (!slot.prepend && !slot.append)
128
+ continue;
129
+ rewriter.on(tagName, {
130
+ element(element) {
131
+ if (slot.prepend)
132
+ element.prepend(slot.prepend, { html: true });
133
+ if (slot.append)
134
+ element.append(slot.append, { html: true });
213
135
  },
214
136
  });
215
- return htmlRewriter.transform(res);
216
137
  }
217
- const html = await res.text();
218
- const headers = new Headers(res.headers);
219
- const withHeadPrependedContent = this.injectAfterOpeningTag(html, 'head', headPrepend.map((item) => item.html).join(''));
220
- const withHeadDependencies = this.injectBeforeClosingTag(withHeadPrependedContent, 'head', `${this.buildDependencyTags(head)}${headAppend.map((item) => item.html).join('')}`);
221
- const withBodyPrependedContent = this.injectAfterOpeningTag(withHeadDependencies, 'body', bodyPrepend.map((item) => item.html).join(''));
222
- const transformedHtml = this.injectBeforeClosingTag(withBodyPrependedContent, 'body', `${this.buildDependencyTags(body)}${bodyAppend.map((item) => item.html).join('')}`);
223
- return new Response(transformedHtml, {
224
- headers,
225
- status: res.status,
226
- statusText: res.statusText,
227
- });
138
+ return rewriter;
228
139
  }
229
140
  /**
230
141
  * Splits processed assets into head and body injection groups.
@@ -258,13 +169,30 @@ export class HtmlTransformerService {
258
169
  const entryHtmlAssets = pagePackage.pageBrowserGraph.entryAssets.filter((asset) => !chunkKeys.has(buildProcessedAssetDedupeKey(asset)));
259
170
  return dedupeProcessedAssets([...nonGraphHtmlAssets, ...entryHtmlAssets]);
260
171
  }
261
- /**
262
- * Builds a serialized HTML attribute string from an attribute object.
263
- */
264
- buildAttributeString(attributes) {
265
- return Object.entries(attributes)
266
- .filter(([key, value]) => key.length > 0 && value.length > 0)
267
- .map(([key, value]) => ` ${key}="${value}"`)
268
- .join('');
269
- }
172
+ }
173
+ /**
174
+ * Sets attributes on the element a fragment or document starts with.
175
+ *
176
+ * @remarks
177
+ * Nothing is stamped when text or a comment comes first (whitespace aside),
178
+ * so a Lit render that opens with `<!--lit-part-->` keeps its markup.
179
+ */
180
+ export function applyAttributesToFirstElement(html, attributes) {
181
+ return stampAttributes(html, attributes, () => true, { leadingOnly: true });
182
+ }
183
+ /**
184
+ * Sets `attributes` on the first element that `isTarget` accepts.
185
+ *
186
+ * @remarks
187
+ * Entries with an empty name or value are skipped, and an attribute the element
188
+ * already has is replaced rather than duplicated.
189
+ */
190
+ function stampAttributes(html, attributes, isTarget, options) {
191
+ const entries = Object.entries(attributes).filter(([name, value]) => name.length > 0 && value.length > 0);
192
+ if (entries.length === 0)
193
+ return html;
194
+ return rewriteFirstElement(html, isTarget, (element) => {
195
+ for (const [name, value] of entries)
196
+ element.setAttribute(name, value);
197
+ }, options);
270
198
  }
@@ -1,5 +1,4 @@
1
- import type { EcoPagesAppConfig, RegisteredScriptEntrypointChangeHandler } from '../../types/internal-types.js';
2
- export type { RegisteredScriptEntrypointChangeHandler };
1
+ import type { EcoPagesAppConfig } from '../../types/internal-types.js';
3
2
  export type DevelopmentInvalidationCategory = 'public-asset' | 'additional-watch' | 'include-source' | 'explicit-server-view' | 'route-source' | 'processor-owned-asset' | 'server-source' | 'runtime-restart' | 'other';
4
3
  /**
5
4
  * Framework-owned invalidation plan for one changed file.
@@ -23,7 +22,7 @@ export interface DevelopmentInvalidationPlan {
23
22
  * @remarks
24
23
  * This service centralizes two responsibilities:
25
24
  * - file-change classification for watcher behavior
26
- * - app-owned server-module invalidation versioning backed by the dev graph
25
+ * - app-owned server-module invalidation
27
26
  *
28
27
  * Hosts and watchers should ask this service what a file change means instead
29
28
  * of deciding invalidation semantics inline.
@@ -31,26 +30,10 @@ export interface DevelopmentInvalidationPlan {
31
30
  export declare class DevelopmentInvalidationService {
32
31
  private readonly appConfig;
33
32
  constructor(appConfig: EcoPagesAppConfig);
34
- /**
35
- * Returns the current app-owned server-module invalidation version.
36
- */
37
- getServerModuleInvalidationVersion(): number;
38
33
  /**
39
34
  * Invalidates the app-owned server-module graph.
40
35
  */
41
36
  invalidateServerModules(changedFiles?: string[]): void;
42
- /**
43
- * Registers an integration-owned handler for registered script entrypoint edits.
44
- */
45
- registerRegisteredScriptEntrypointChangeHandler(handler: RegisteredScriptEntrypointChangeHandler): void;
46
- /**
47
- * Notifies integration handlers that a registered script entrypoint changed.
48
- */
49
- notifyRegisteredScriptEntrypointChange(filePath: string): Promise<void>;
50
- /**
51
- * Resets runtime-owned graph state and invalidates server modules.
52
- */
53
- resetRuntimeState(changedFiles?: string[]): void;
54
37
  /**
55
38
  * Classifies one changed file into an explicit framework invalidation plan.
56
39
  */
@@ -1,7 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import { isDevEnvFilePath } from '../../dev/development-restart-watch-paths.js';
3
3
  import { getAppServerInvalidationState } from '../runtime-state/server-invalidation-state.service.js';
4
- import { appLogger } from '../../global/app-logger.js';
5
4
  import { clearAppDevelopmentRouteModuleBuildCaches } from '../module-loading/route-module-build-cache-registry.js';
6
5
  import { clearCollectionServerBuildArtifacts } from '../module-loading/collection-server-module-build.service.js';
7
6
  /**
@@ -10,7 +9,7 @@ import { clearCollectionServerBuildArtifacts } from '../module-loading/collectio
10
9
  * @remarks
11
10
  * This service centralizes two responsibilities:
12
11
  * - file-change classification for watcher behavior
13
- * - app-owned server-module invalidation versioning backed by the dev graph
12
+ * - app-owned server-module invalidation
14
13
  *
15
14
  * Hosts and watchers should ask this service what a file change means instead
16
15
  * of deciding invalidation semantics inline.
@@ -20,12 +19,6 @@ export class DevelopmentInvalidationService {
20
19
  constructor(appConfig) {
21
20
  this.appConfig = appConfig;
22
21
  }
23
- /**
24
- * Returns the current app-owned server-module invalidation version.
25
- */
26
- getServerModuleInvalidationVersion() {
27
- return getAppServerInvalidationState(this.appConfig).getServerInvalidationVersion();
28
- }
29
22
  /**
30
23
  * Invalidates the app-owned server-module graph.
31
24
  */
@@ -38,37 +31,6 @@ export class DevelopmentInvalidationService {
38
31
  processor.invalidateServerArtifacts?.();
39
32
  }
40
33
  }
41
- /**
42
- * Registers an integration-owned handler for registered script entrypoint edits.
43
- */
44
- registerRegisteredScriptEntrypointChangeHandler(handler) {
45
- const runtime = this.appConfig.runtime ?? {};
46
- this.appConfig.runtime = runtime;
47
- runtime.registeredScriptEntrypointChangeHandlers ??= [];
48
- runtime.registeredScriptEntrypointChangeHandlers.push(handler);
49
- }
50
- /**
51
- * Notifies integration handlers that a registered script entrypoint changed.
52
- */
53
- async notifyRegisteredScriptEntrypointChange(filePath) {
54
- const handlers = this.appConfig.runtime?.registeredScriptEntrypointChangeHandlers ?? [];
55
- for (const handler of handlers) {
56
- try {
57
- await handler(filePath);
58
- }
59
- catch (error) {
60
- appLogger.error(`Failed to handle registered script entrypoint change for ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
61
- }
62
- }
63
- }
64
- /**
65
- * Resets runtime-owned graph state and invalidates server modules.
66
- */
67
- resetRuntimeState(changedFiles) {
68
- this.invalidateServerModules(changedFiles);
69
- const serverInvalidationState = getAppServerInvalidationState(this.appConfig);
70
- serverInvalidationState.reset();
71
- }
72
34
  /**
73
35
  * Classifies one changed file into an explicit framework invalidation plan.
74
36
  */
@@ -30,7 +30,7 @@ Call site (route scan, renderer, SSG, API)
30
30
  ## Caching layers
31
31
 
32
32
  1. **In-memory promise cache** (`PageModuleImportService.importCache`) — keyed by runtime, file path, content-derived reuse identity (`createRouteModuleReuseIdentity`), and source hash. Cleared by `invalidateDevelopmentGraph()`.
33
- 2. **Disk transpile cache** (`.eco/.server-modules/.build-cache.json`) — production and stable development graphs when dependency hashes match. Manifest field `corePackageVersion` invalidates entries when the framework package changes.
33
+ 2. **Disk transpile cache** (`.eco/.server-modules/.build-cache.json`) — production and stable development graphs when dependency hashes match. Manifest field `corePackageVersion` invalidates entries when the framework package changes. An entry is also reused only while every local file its compiled output imports still exists.
34
34
  3. **Unified graph manifest** — production static export fast path only; see build layer docs.
35
35
 
36
36
  Development import URLs use `sourceHash` plus a per-service import generation counter. Node uses that value in its `?update=` query. Bun also receives a generation-specific compiled output filename because it retains a previously imported file when only its query changes. Both paths advance after `invalidateDevelopmentGraph()` without a process-wide invalidation version in reuse keys.
@@ -1,7 +1,5 @@
1
1
  import type { PageModuleBuildImportOptions } from './page-module-import.service.js';
2
- export type AppModuleLoaderOwner = 'app' | 'host';
3
2
  export interface AppModuleLoader {
4
- readonly owner: AppModuleLoaderOwner;
5
3
  importModule<T = unknown>(options: PageModuleBuildImportOptions): Promise<T>;
6
4
  invalidateDevelopmentGraph(): void;
7
5
  }
@@ -1,5 +1,5 @@
1
1
  import type { EcoPagesAppConfig } from '../../types/internal-types.js';
2
- import { type AppModuleLoader } from './app-module-loader.service.js';
2
+ import type { AppModuleLoader } from './app-module-loader.service.js';
3
3
  import type { SourceModuleLoader } from './module-loading-types.js';
4
4
  import { ServerModuleTranspiler } from './server-module-transpiler.service.js';
5
5
  export declare function shouldAppUseHostModuleLoader(appConfig: EcoPagesAppConfig, filePath: string): boolean;