@pithyjs/ssr 0.0.0-stage → 0.1.2-beta.11

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 (156) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -2
  3. package/bin/pithy-ssg.mjs +23 -0
  4. package/dist/browser.d.ts +38 -0
  5. package/dist/browser.d.ts.map +1 -0
  6. package/dist/browser.js +40 -0
  7. package/dist/browser.js.map +1 -0
  8. package/dist/build/cli-args.d.ts +104 -0
  9. package/dist/build/cli-args.d.ts.map +1 -0
  10. package/dist/build/cli-args.js +88 -0
  11. package/dist/build/cli-args.js.map +1 -0
  12. package/dist/build/cli-exit.d.ts +95 -0
  13. package/dist/build/cli-exit.d.ts.map +1 -0
  14. package/dist/build/cli-exit.js +237 -0
  15. package/dist/build/cli-exit.js.map +1 -0
  16. package/dist/build/cli.d.ts +11 -0
  17. package/dist/build/cli.d.ts.map +1 -0
  18. package/dist/build/cli.js +93 -0
  19. package/dist/build/cli.js.map +1 -0
  20. package/dist/build/collect-css.d.ts +168 -0
  21. package/dist/build/collect-css.d.ts.map +1 -0
  22. package/dist/build/collect-css.js +479 -0
  23. package/dist/build/collect-css.js.map +1 -0
  24. package/dist/build/css-live-props.d.ts +89 -0
  25. package/dist/build/css-live-props.d.ts.map +1 -0
  26. package/dist/build/css-live-props.js +704 -0
  27. package/dist/build/css-live-props.js.map +1 -0
  28. package/dist/build/css-purge.d.ts +153 -0
  29. package/dist/build/css-purge.d.ts.map +1 -0
  30. package/dist/build/css-purge.js +463 -0
  31. package/dist/build/css-purge.js.map +1 -0
  32. package/dist/build/index.d.ts +24 -0
  33. package/dist/build/index.d.ts.map +1 -0
  34. package/dist/build/index.js +31 -0
  35. package/dist/build/index.js.map +1 -0
  36. package/dist/build/not-found.d.ts +94 -0
  37. package/dist/build/not-found.d.ts.map +1 -0
  38. package/dist/build/not-found.js +99 -0
  39. package/dist/build/not-found.js.map +1 -0
  40. package/dist/build/relative-links.d.ts +31 -0
  41. package/dist/build/relative-links.d.ts.map +1 -0
  42. package/dist/build/relative-links.js +79 -0
  43. package/dist/build/relative-links.js.map +1 -0
  44. package/dist/build/shell-head.d.ts +68 -0
  45. package/dist/build/shell-head.d.ts.map +1 -0
  46. package/dist/build/shell-head.js +236 -0
  47. package/dist/build/shell-head.js.map +1 -0
  48. package/dist/build/sprite-ssg.d.ts +61 -0
  49. package/dist/build/sprite-ssg.d.ts.map +1 -0
  50. package/dist/build/sprite-ssg.js +114 -0
  51. package/dist/build/sprite-ssg.js.map +1 -0
  52. package/dist/build/ssg.d.ts +117 -0
  53. package/dist/build/ssg.d.ts.map +1 -0
  54. package/dist/build/ssg.js +404 -0
  55. package/dist/build/ssg.js.map +1 -0
  56. package/dist/build/vite-ssg.d.ts +396 -0
  57. package/dist/build/vite-ssg.d.ts.map +1 -0
  58. package/dist/build/vite-ssg.js +1130 -0
  59. package/dist/build/vite-ssg.js.map +1 -0
  60. package/dist/client/bootstrap.d.ts +51 -0
  61. package/dist/client/bootstrap.d.ts.map +1 -0
  62. package/dist/client/bootstrap.js +121 -0
  63. package/dist/client/bootstrap.js.map +1 -0
  64. package/dist/client/hydrate.d.ts +60 -0
  65. package/dist/client/hydrate.d.ts.map +1 -0
  66. package/dist/client/hydrate.js +168 -0
  67. package/dist/client/hydrate.js.map +1 -0
  68. package/dist/client/index.d.ts +21 -0
  69. package/dist/client/index.d.ts.map +1 -0
  70. package/dist/client/index.js +16 -0
  71. package/dist/client/index.js.map +1 -0
  72. package/dist/index.d.ts +32 -0
  73. package/dist/index.d.ts.map +1 -0
  74. package/dist/index.js +31 -0
  75. package/dist/index.js.map +1 -0
  76. package/dist/server/app.d.ts +166 -0
  77. package/dist/server/app.d.ts.map +1 -0
  78. package/dist/server/app.js +200 -0
  79. package/dist/server/app.js.map +1 -0
  80. package/dist/server/context.d.ts +238 -0
  81. package/dist/server/context.d.ts.map +1 -0
  82. package/dist/server/context.js +371 -0
  83. package/dist/server/context.js.map +1 -0
  84. package/dist/server/environment.d.ts +88 -0
  85. package/dist/server/environment.d.ts.map +1 -0
  86. package/dist/server/environment.js +261 -0
  87. package/dist/server/environment.js.map +1 -0
  88. package/dist/server/html-shell.d.ts +41 -0
  89. package/dist/server/html-shell.d.ts.map +1 -0
  90. package/dist/server/html-shell.js +208 -0
  91. package/dist/server/html-shell.js.map +1 -0
  92. package/dist/server/index.d.ts +26 -0
  93. package/dist/server/index.d.ts.map +1 -0
  94. package/dist/server/index.js +37 -0
  95. package/dist/server/index.js.map +1 -0
  96. package/dist/server/layout-taint.d.ts +62 -0
  97. package/dist/server/layout-taint.d.ts.map +1 -0
  98. package/dist/server/layout-taint.js +313 -0
  99. package/dist/server/layout-taint.js.map +1 -0
  100. package/dist/server/loaders.d.ts +194 -0
  101. package/dist/server/loaders.d.ts.map +1 -0
  102. package/dist/server/loaders.js +479 -0
  103. package/dist/server/loaders.js.map +1 -0
  104. package/dist/server/render-route.d.ts +102 -0
  105. package/dist/server/render-route.d.ts.map +1 -0
  106. package/dist/server/render-route.js +182 -0
  107. package/dist/server/render-route.js.map +1 -0
  108. package/dist/server/render.d.ts +80 -0
  109. package/dist/server/render.d.ts.map +1 -0
  110. package/dist/server/render.js +256 -0
  111. package/dist/server/render.js.map +1 -0
  112. package/dist/server/router-adapter.d.ts +134 -0
  113. package/dist/server/router-adapter.d.ts.map +1 -0
  114. package/dist/server/router-adapter.js +225 -0
  115. package/dist/server/router-adapter.js.map +1 -0
  116. package/dist/server/serialization.d.ts +54 -0
  117. package/dist/server/serialization.d.ts.map +1 -0
  118. package/dist/server/serialization.js +287 -0
  119. package/dist/server/serialization.js.map +1 -0
  120. package/dist/server/ssr-worker.d.ts +18 -0
  121. package/dist/server/ssr-worker.d.ts.map +1 -0
  122. package/dist/server/ssr-worker.js +118 -0
  123. package/dist/server/ssr-worker.js.map +1 -0
  124. package/dist/server/utils.d.ts +11 -0
  125. package/dist/server/utils.d.ts.map +1 -0
  126. package/dist/server/utils.js +14 -0
  127. package/dist/server/utils.js.map +1 -0
  128. package/dist/server/worker-pool.d.ts +153 -0
  129. package/dist/server/worker-pool.d.ts.map +1 -0
  130. package/dist/server/worker-pool.js +451 -0
  131. package/dist/server/worker-pool.js.map +1 -0
  132. package/dist/server/worker-protocol.d.ts +61 -0
  133. package/dist/server/worker-protocol.d.ts.map +1 -0
  134. package/dist/server/worker-protocol.js +9 -0
  135. package/dist/server/worker-protocol.js.map +1 -0
  136. package/dist/shared/css-purge.d.ts +71 -0
  137. package/dist/shared/css-purge.d.ts.map +1 -0
  138. package/dist/shared/css-purge.js +177 -0
  139. package/dist/shared/css-purge.js.map +1 -0
  140. package/dist/shared/entry-path.d.ts +41 -0
  141. package/dist/shared/entry-path.d.ts.map +1 -0
  142. package/dist/shared/entry-path.js +87 -0
  143. package/dist/shared/entry-path.js.map +1 -0
  144. package/dist/shared/head.d.ts +87 -0
  145. package/dist/shared/head.d.ts.map +1 -0
  146. package/dist/shared/head.js +412 -0
  147. package/dist/shared/head.js.map +1 -0
  148. package/dist/shared/shell-helpers.d.ts +69 -0
  149. package/dist/shared/shell-helpers.d.ts.map +1 -0
  150. package/dist/shared/shell-helpers.js +160 -0
  151. package/dist/shared/shell-helpers.js.map +1 -0
  152. package/dist/shared/types.d.ts +332 -0
  153. package/dist/shared/types.d.ts.map +1 -0
  154. package/dist/shared/types.js +27 -0
  155. package/dist/shared/types.js.map +1 -0
  156. package/package.json +84 -3
@@ -0,0 +1,182 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.ssr.server.render-route",
4
+ "title": "SSR Route Rendering Pipeline",
5
+ "category": "runtime"
6
+ }
7
+ */
8
+ import { flattenRouteTree, findMatchingEntry, matchRoute, } from '@pithyjs/router';
9
+ import { renderToString } from './render.js';
10
+ import { executeSSRLoaders, extractLoadersFromRouteTree, generateCacheControlHeader, } from './loaders.js';
11
+ // =============================================================================
12
+ // Implementation
13
+ // =============================================================================
14
+ /** @codexApi {"parent":"pithy.ssr.server.render-route","name":"renderRoute","stability":"experimental","signature":"(options: RenderRouteOptions) => Promise<RenderRouteResult>"} */
15
+ /**
16
+ * Render a route to HTML with automatic route matching and loader execution.
17
+ *
18
+ * This is the high-level SSR entry point that handles the complete pipeline:
19
+ * 1. Parse URL into path and query
20
+ * 2. Match URL against route tree
21
+ * 3. Extract route parameters
22
+ * 4. Execute route loaders
23
+ * 5. Render the component with all data
24
+ * 6. Return HTML with cache hints
25
+ *
26
+ * For manual control over each step, use `renderToString()` directly.
27
+ *
28
+ * @param options - Route render options
29
+ * @returns Rendered HTML with route-specific metadata
30
+ *
31
+ * @example Basic usage
32
+ * ```ts
33
+ * const result = await renderRoute({
34
+ * url: '/dashboard',
35
+ * App,
36
+ * routes,
37
+ * });
38
+ *
39
+ * if (result.redirectTo) {
40
+ * res.redirect(result.status, result.redirectTo);
41
+ * } else {
42
+ * res.status(result.status).send(htmlShell({
43
+ * html: result.html,
44
+ * head: result.head,
45
+ * state: result.state,
46
+ * scripts: ['/entry-client.js'],
47
+ * }));
48
+ * }
49
+ * ```
50
+ *
51
+ * @example With cache headers
52
+ * ```ts
53
+ * const result = await renderRoute({ url: '/blog/123', App, routes });
54
+ * if (result.cacheControl) {
55
+ * res.setHeader('Cache-Control', result.cacheControl);
56
+ * }
57
+ * ```
58
+ */
59
+ export async function renderRoute(options) {
60
+ const { url, App, routes, context, appId, head, status, loaderTimeout, continueOnError = false, signal, } = options;
61
+ // 1. Parse URL into path and query
62
+ const routeMatchStart = performance.now();
63
+ const urlObj = new URL(url, 'http://localhost');
64
+ const urlPath = urlObj.pathname;
65
+ const query = {};
66
+ urlObj.searchParams.forEach((value, key) => {
67
+ query[key] = value;
68
+ });
69
+ // 2. Match URL against route tree
70
+ const flatRoutes = flattenRouteTree(routes);
71
+ const entry = findMatchingEntry(urlPath, flatRoutes);
72
+ if (!entry) {
73
+ // No matching route — render with 404 status
74
+ const routeMatchTime = performance.now() - routeMatchStart;
75
+ const result = await renderToString({
76
+ url,
77
+ App,
78
+ context,
79
+ appId,
80
+ head,
81
+ query,
82
+ status: status ?? 404,
83
+ });
84
+ if (result.timing) {
85
+ result.timing.routeMatch = routeMatchTime;
86
+ result.timing.total += routeMatchTime;
87
+ }
88
+ return {
89
+ ...result,
90
+ routeMatch: undefined,
91
+ loaderResult: undefined,
92
+ cacheControl: undefined,
93
+ };
94
+ }
95
+ // 3. Extract params from matched route
96
+ const routeMatchResult = matchRoute(urlPath, entry.node.pattern);
97
+ const routeMatchTime = performance.now() - routeMatchStart;
98
+ // Defensive: matchRoute returned null despite findMatchingEntry succeeding.
99
+ // This shouldn't happen in practice, but guard against edge cases.
100
+ if (!routeMatchResult) {
101
+ const result = await renderToString({
102
+ url,
103
+ App,
104
+ context,
105
+ appId,
106
+ head,
107
+ query,
108
+ status: status ?? 404,
109
+ });
110
+ if (result.timing) {
111
+ result.timing.routeMatch = routeMatchTime;
112
+ result.timing.total += routeMatchTime;
113
+ }
114
+ return {
115
+ ...result,
116
+ routeMatch: undefined,
117
+ loaderResult: undefined,
118
+ cacheControl: undefined,
119
+ };
120
+ }
121
+ const params = {};
122
+ if (routeMatchResult.params) {
123
+ // Flatten params (RouteParams may have string | string[] values)
124
+ for (const [key, value] of Object.entries(routeMatchResult.params)) {
125
+ params[key] = Array.isArray(value) ? value.join('/') : String(value);
126
+ }
127
+ }
128
+ // 4. Extract loaders from ancestor chain + matched route
129
+ const matchedSegments = routeMatchResult.segments ?? [];
130
+ const segments = await extractLoadersFromRouteTree(routes, matchedSegments);
131
+ // 5. Execute loaders (outside SSR environment — loaders are pure data fetching)
132
+ let loaderResult;
133
+ let loaderData = {};
134
+ if (segments.length > 0) {
135
+ loaderResult = await executeSSRLoaders({
136
+ segments,
137
+ params,
138
+ query,
139
+ timeout: loaderTimeout,
140
+ signal,
141
+ continueOnError,
142
+ });
143
+ loaderData = loaderResult.loaderData;
144
+ }
145
+ // 6. Determine status code
146
+ let resolvedStatus = status ?? 200;
147
+ if (loaderResult && !loaderResult.success && resolvedStatus === 200) {
148
+ resolvedStatus = 500;
149
+ }
150
+ // 7. Render the component with all collected data
151
+ const result = await renderToString({
152
+ url,
153
+ App,
154
+ context,
155
+ appId,
156
+ params,
157
+ query,
158
+ loaderData,
159
+ head,
160
+ status: resolvedStatus,
161
+ });
162
+ // 8. Overlay route matching and loader timing onto the render timing.
163
+ // renderToString reports routeMatch=0 and loaders=0 since it doesn't
164
+ // orchestrate those phases — renderRoute does.
165
+ const loaderTime = loaderResult?.totalTiming ?? 0;
166
+ if (result.timing) {
167
+ result.timing.routeMatch = routeMatchTime;
168
+ result.timing.loaders = loaderTime;
169
+ result.timing.total += routeMatchTime + loaderTime;
170
+ }
171
+ // 9. Generate cache control header
172
+ const cacheControl = loaderResult
173
+ ? generateCacheControlHeader(loaderResult.cacheHints)
174
+ : undefined;
175
+ return {
176
+ ...result,
177
+ routeMatch: routeMatchResult,
178
+ loaderResult,
179
+ cacheControl,
180
+ };
181
+ }
182
+ //# sourceMappingURL=render-route.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render-route.js","sourceRoot":"","sources":["../../src/server/render-route.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAYF,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,UAAU,GAGX,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EACL,iBAAiB,EACjB,2BAA2B,EAC3B,0BAA0B,GAE3B,MAAM,cAAc,CAAC;AA4CtB,gFAAgF;AAChF,iBAAiB;AACjB,gFAAgF;AAEhF,qLAAqL;AACrL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,OAA2B;IAE3B,MAAM,EACJ,GAAG,EACH,GAAG,EACH,MAAM,EACN,OAAO,EACP,KAAK,EACL,IAAI,EACJ,MAAM,EACN,aAAa,EACb,eAAe,GAAG,KAAK,EACvB,M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\"SSR Route Rendering Pipeline\",\n \"category\": \"runtime\"\n}\n*/\n\n/**\n * @pithyjs/ssr - Full SSR Route Pipeline\n *\n * High-level `renderRoute()` function that orchestrates the complete SSR pipeline:\n * URL → route match → loader execution → component render → HTML output.\n *\n * For manual orchestration, use `renderToString()` directly.\n */\n\nimport type { Component } from '@pithyjs/core';\nimport {\n flattenRouteTree,\n findMatchingEntry,\n matchRoute,\n type RouteNode,\n type RouteMatch,\n} from '@pithyjs/router';\nimport type { RenderResult, HeadState } from '../shared/types.js';\nimport { renderToString } from './render.js';\nimport {\n executeSSRLoaders,\n extractLoadersFromRouteTree,\n generateCacheControlHeader,\n type ExecuteLoadersResult,\n} from './loaders.js';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Options for renderRoute()\n */\nexport interface RenderRouteOptions {\n /** URL to render (e.g., '/dashboard?tab=settings') */\n url: string;\n /** The root component to render */\n App: Component;\n /** Route tree from the router manifest */\n routes: RouteNode[];\n /** Additional context to pass to components */\n context?: Record<string, unknown>;\n /** App container ID (default: 'app') */\n appId?: string;\n /** Initial head state */\n head?: Partial<HeadState>;\n /** Initial HTTP status code (default: 200; preserved when set, otherwise falls back to 404 if no route matches or 500 on loader error) */\n status?: number;\n /** Loader execution timeout in milliseconds (default: 30000) */\n loaderTimeout?: number;\n /** Whether to continue rendering after a loader error (default: false) */\n continueOnError?: boolean;\n /** Abort signal for cancellation */\n signal?: AbortSignal;\n}\n\n/**\n * Result from renderRoute(), extends RenderResult with route-specific data\n */\nexport interface RenderRouteResult extends RenderResult {\n /** The route match result with params and pattern (undefined if no route matched) */\n routeMatch?: RouteMatch;\n /** Loader execution result (undefined if no loaders ran) */\n loaderResult?: ExecuteLoadersResult;\n /** Generated Cache-Control header value from loader cache hints */\n cacheControl?: string;\n}\n\n// =============================================================================\n// Implementation\n// =============================================================================\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.render-route\",\"name\":\"renderRoute\",\"stability\":\"experimental\",\"signature\":\"(options: RenderRouteOptions) => Promise<RenderRouteResult>\"} */\n/**\n * Render a route to HTML with automatic route matching and loader execution.\n *\n * This is the high-level SSR entry point that handles the complete pipeline:\n * 1. Parse URL into path and query\n * 2. Match URL against route tree\n * 3. Extract route parameters\n * 4. Execute route loaders\n * 5. Render the component with all data\n * 6. Return HTML with cache hints\n *\n * For manual control over each step, use `renderToString()` directly.\n *\n * @param options - Route render options\n * @returns Rendered HTML with route-specific metadata\n *\n * @example Basic usage\n * ```ts\n * const result = await renderRoute({\n * url: '/dashboard',\n * App,\n * routes,\n * });\n *\n * if (result.redirectTo) {\n * res.redirect(result.status, result.redirectTo);\n * } else {\n * res.status(result.status).send(htmlShell({\n * html: result.html,\n * head: result.head,\n * state: result.state,\n * scripts: ['/entry-client.js'],\n * }));\n * }\n * ```\n *\n * @example With cache headers\n * ```ts\n * const result = await renderRoute({ url: '/blog/123', App, routes });\n * if (result.cacheControl) {\n * res.setHeader('Cache-Control', result.cacheControl);\n * }\n * ```\n */\nexport async function renderRoute(\n options: RenderRouteOptions\n): Promise<RenderRouteResult> {\n const {\n url,\n App,\n routes,\n context,\n appId,\n head,\n status,\n loaderTimeout,\n continueOnError = false,\n signal,\n } = options;\n\n // 1. Parse URL into path and query\n const routeMatchStart = performance.now();\n const urlObj = new URL(url, 'http://localhost');\n const urlPath = urlObj.pathname;\n const query: Record<string, string> = {};\n urlObj.searchParams.forEach((value, key) => {\n query[key] = value;\n });\n\n // 2. Match URL against route tree\n const flatRoutes = flattenRouteTree(routes);\n const entry = findMatchingEntry(urlPath, flatRoutes);\n\n if (!entry) {\n // No matching route — render with 404 status\n const routeMatchTime = performance.now() - routeMatchStart;\n const result = await renderToString({\n url,\n App,\n context,\n appId,\n head,\n query,\n status: status ?? 404,\n });\n\n if (result.timing) {\n result.timing.routeMatch = routeMatchTime;\n result.timing.total += routeMatchTime;\n }\n\n return {\n ...result,\n routeMatch: undefined,\n loaderResult: undefined,\n cacheControl: undefined,\n };\n }\n\n // 3. Extract params from matched route\n const routeMatchResult = matchRoute(urlPath, entry.node.pattern);\n const routeMatchTime = performance.now() - routeMatchStart;\n\n // Defensive: matchRoute returned null despite findMatchingEntry succeeding.\n // This shouldn't happen in practice, but guard against edge cases.\n if (!routeMatchResult) {\n const result = await renderToString({\n url,\n App,\n context,\n appId,\n head,\n query,\n status: status ?? 404,\n });\n\n if (result.timing) {\n result.timing.routeMatch = routeMatchTime;\n result.timing.total += routeMatchTime;\n }\n\n return {\n ...result,\n routeMatch: undefined,\n loaderResult: undefined,\n cacheControl: undefined,\n };\n }\n\n const params: Record<string, string> = {};\n if (routeMatchResult.params) {\n // Flatten params (RouteParams may have string | string[] values)\n for (const [key, value] of Object.entries(routeMatchResult.params)) {\n params[key] = Array.isArray(value) ? value.join('/') : String(value);\n }\n }\n\n // 4. Extract loaders from ancestor chain + matched route\n const matchedSegments = routeMatchResult.segments ?? [];\n const segments = await extractLoadersFromRouteTree(routes, matchedSegments);\n\n // 5. Execute loaders (outside SSR environment — loaders are pure data fetching)\n let loaderResult: ExecuteLoadersResult | undefined;\n let loaderData: Record<string, unknown> = {};\n\n if (segments.length > 0) {\n loaderResult = await executeSSRLoaders({\n segments,\n params,\n query,\n timeout: loaderTimeout,\n signal,\n continueOnError,\n });\n loaderData = loaderResult.loaderData;\n }\n\n // 6. Determine status code\n let resolvedStatus = status ?? 200;\n if (loaderResult && !loaderResult.success && resolvedStatus === 200) {\n resolvedStatus = 500;\n }\n\n // 7. Render the component with all collected data\n const result = await renderToString({\n url,\n App,\n context,\n appId,\n params,\n query,\n loaderData,\n head,\n status: resolvedStatus,\n });\n\n // 8. Overlay route matching and loader timing onto the render timing.\n // renderToString reports routeMatch=0 and loaders=0 since it doesn't\n // orchestrate those phases — renderRoute does.\n const loaderTime = loaderResult?.totalTiming ?? 0;\n if (result.timing) {\n result.timing.routeMatch = routeMatchTime;\n result.timing.loaders = loaderTime;\n result.timing.total += routeMatchTime + loaderTime;\n }\n\n // 9. Generate cache control header\n const cacheControl = loaderResult\n ? generateCacheControlHeader(loaderResult.cacheHints)\n : undefined;\n\n return {\n ...result,\n routeMatch: routeMatchResult,\n loaderResult,\n cacheControl,\n };\n}\n"]}
@@ -0,0 +1,80 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.ssr.server.render",
4
+ "title": "SSR Render to String",
5
+ "category": "runtime"
6
+ }
7
+ */
8
+ /**
9
+ * @pithyjs/ssr - Server-Side Rendering
10
+ *
11
+ * Core renderToString function that renders PithyJS components to HTML strings
12
+ * on the server for SSR/SSG.
13
+ */
14
+ import { type Component } from '@pithyjs/core';
15
+ import { type RenderResult, type HeadState } from '../shared/types.js';
16
+ /**
17
+ * Extended render options that include the App component
18
+ */
19
+ export interface RenderToStringOptions {
20
+ /** URL to render */
21
+ url: string;
22
+ /** The root component to render */
23
+ App: Component;
24
+ /** Additional context to pass to components */
25
+ context?: Record<string, unknown>;
26
+ /** App container ID (default: 'app') */
27
+ appId?: string;
28
+ /** Route parameters (from your router or explicitly provided; renderToString does not parse these from the URL) */
29
+ params?: Record<string, string>;
30
+ /** Query parameters (explicitly provided; if omitted or empty, they are parsed from the `url` search string by createSSRContext) */
31
+ query?: Record<string, string>;
32
+ /** Pre-populated loader data (from executeSSRLoaders) */
33
+ loaderData?: Record<string, unknown>;
34
+ /** Initial head state */
35
+ head?: Partial<HeadState>;
36
+ /** Initial HTTP status code (default: 200) */
37
+ status?: number;
38
+ }
39
+ /** @codexApi {"parent":"pithy.ssr.server.render","name":"renderToString","stability":"experimental","signature":"(options: RenderToStringOptions) => Promise<RenderResult>"} */
40
+ /**
41
+ * Render a PithyJS component to an HTML string
42
+ *
43
+ * Sets up the SSR environment, renders the component tree, collects head state,
44
+ * and returns the result for hydration.
45
+ *
46
+ * @param options - Render options
47
+ * @param options.url - The URL to render (required)
48
+ * @param options.App - The root component to render (required)
49
+ * @param options.context - Additional context passed to components
50
+ * @param options.appId - Container element ID (default: 'app')
51
+ * @param options.params - Pre-parsed route parameters (e.g., `{ id: '123' }`)
52
+ * @param options.query - Pre-parsed query parameters (e.g., `{ tab: 'settings' }`)
53
+ * @param options.loaderData - Pre-fetched loader data keyed by route segment ID
54
+ * @param options.head - Initial head state (title, meta tags, etc.)
55
+ * @param options.status - Initial HTTP status code (default: 200)
56
+ * @returns Rendered HTML, head state, serialized state, and timing info
57
+ *
58
+ * @example Basic usage
59
+ * ```ts
60
+ * const result = await renderToString({
61
+ * url: '/dashboard',
62
+ * App,
63
+ * });
64
+ * ```
65
+ *
66
+ * @example With pre-parsed route data
67
+ * ```ts
68
+ * const result = await renderToString({
69
+ * url: '/users/123?tab=settings',
70
+ * App,
71
+ * params: { id: '123' },
72
+ * query: { tab: 'settings' },
73
+ * loaderData: { 'users.$id': userData },
74
+ * head: { title: 'User Profile' },
75
+ * status: 200,
76
+ * });
77
+ * ```
78
+ */
79
+ export declare function renderToString(options: RenderToStringOptions): Promise<RenderResult>;
80
+ //# sourceMappingURL=render.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render.d.ts","sourceRoot":"","sources":["../../src/server/render.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;GAKG;AAEH,OAAO,EAGL,KAAK,SAAS,EACf,MAAM,eAAe,CAAC;AAEvB,OAAO,EAEL,KAAK,YAAY,EAGjB,KAAK,SAAS,EAEf,MAAM,oBAAoB,CAAC;AA6E5B;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC,oBAAoB;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,mCAAmC;IACnC,GAAG,EAAE,SAAS,CAAC;IACf,+CAA+C;IAC/C,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClC,wCAAwC;IACxC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,mHAAmH;IACnH,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,oIAAoI;IACpI,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B,yDAAyD;IACzD,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,yBAAyB;IACzB,IAAI,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;IAC1B,8CAA8C;IAC9C,MAAM,CAAC,EAAE,MAAM,CAAC;CAIjB;AAMD,gLAAgL;AAChL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,wBAAsB,cAAc,CAClC,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,YAAY,CAAC,CA0KvB"}
@@ -0,0 +1,256 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.ssr.server.render",
4
+ "title": "SSR Render to String",
5
+ "category": "runtime"
6
+ }
7
+ */
8
+ /**
9
+ * @pithyjs/ssr - Server-Side Rendering
10
+ *
11
+ * Core renderToString function that renders PithyJS components to HTML strings
12
+ * on the server for SSR/SSG.
13
+ */
14
+ import { collectUnhandledSSRRenderCrashes, resetSSRRenderCrashes, } from '@pithyjs/core';
15
+ import { createRoot } from '@pithyjs/signals';
16
+ import { SSR_VERSION, } from '../shared/types.js';
17
+ import { createSSRContext, getSSRContext, runWithSSRContextAsync, runWithComponentContext, runWithDestroyCallbacks, } from './context.js';
18
+ import { setupEnvironment } from './environment.js';
19
+ import { setContextGetter } from '../shared/head.js';
20
+ import { findSuspiciousGeometry, stripTaintedStyles } from './layout-taint.js';
21
+ /**
22
+ * Collect layout-taint findings for a render, deduplicated.
23
+ *
24
+ * Returned to the caller rather than logged — see `RenderResult.layoutDiagnostics`.
25
+ */
26
+ function buildLayoutDiagnostics(html, droppedStyles) {
27
+ const suspiciousGeometry = [...new Set(findSuspiciousGeometry(html))];
28
+ const dropped = [...new Set(droppedStyles)];
29
+ if (dropped.length === 0 && suspiciousGeometry.length === 0)
30
+ return undefined;
31
+ return { droppedStyles: dropped, suspiciousGeometry };
32
+ }
33
+ /**
34
+ * Fail the render if a component crashed and no `@error-boundary` claimed it.
35
+ *
36
+ * The binders degrade at the crash site and record what they could not hand to
37
+ * an `@error-boundary`. Whatever is still recorded once the render finishes is a
38
+ * genuine failure, and throwing hands it to the per-route catch in `vite-ssg.ts`
39
+ * so the route lands in `failed[]` and the CLI exits non-zero (BUG-018).
40
+ *
41
+ * @throws the first unhandled crash, wrapped so the tag is legible in the
42
+ * `Failed routes:` summary; the original error is kept as `cause`.
43
+ */
44
+ function assertNoUnhandledComponentCrash() {
45
+ const unhandled = collectUnhandledSSRRenderCrashes();
46
+ if (unhandled.length === 0)
47
+ return;
48
+ const [first, ...rest] = unhandled;
49
+ for (const crash of rest) {
50
+ console.error(`[SSR] Component <${crash.tag}> also crashed during render:`, crash.error);
51
+ }
52
+ const suffix = rest.length > 0 ? ` (and ${rest.length} more component crash(es))` : '';
53
+ const failure = new Error(`Component <${first.tag}> crashed during render: ${first.error.message}${suffix}`);
54
+ // Assigned through a cast rather than passed to the constructor: the repo
55
+ // targets ES2020, where neither `new Error(msg, { cause })` nor `.cause` is in
56
+ // the lib's signature — though every runtime we ship to supports both. Worth
57
+ // keeping: it is what preserves the component's own stack for the failure
58
+ // report, which the message alone flattens away.
59
+ failure.cause = first.error;
60
+ throw failure;
61
+ }
62
+ // Wire up the head() function to access SSR context
63
+ // This bridges the shared head module to the server's AsyncLocalStorage-based context
64
+ setContextGetter(getSSRContext);
65
+ // =============================================================================
66
+ // Implementation
67
+ // =============================================================================
68
+ /** @codexApi {"parent":"pithy.ssr.server.render","name":"renderToString","stability":"experimental","signature":"(options: RenderToStringOptions) => Promise<RenderResult>"} */
69
+ /**
70
+ * Render a PithyJS component to an HTML string
71
+ *
72
+ * Sets up the SSR environment, renders the component tree, collects head state,
73
+ * and returns the result for hydration.
74
+ *
75
+ * @param options - Render options
76
+ * @param options.url - The URL to render (required)
77
+ * @param options.App - The root component to render (required)
78
+ * @param options.context - Additional context passed to components
79
+ * @param options.appId - Container element ID (default: 'app')
80
+ * @param options.params - Pre-parsed route parameters (e.g., `{ id: '123' }`)
81
+ * @param options.query - Pre-parsed query parameters (e.g., `{ tab: 'settings' }`)
82
+ * @param options.loaderData - Pre-fetched loader data keyed by route segment ID
83
+ * @param options.head - Initial head state (title, meta tags, etc.)
84
+ * @param options.status - Initial HTTP status code (default: 200)
85
+ * @returns Rendered HTML, head state, serialized state, and timing info
86
+ *
87
+ * @example Basic usage
88
+ * ```ts
89
+ * const result = await renderToString({
90
+ * url: '/dashboard',
91
+ * App,
92
+ * });
93
+ * ```
94
+ *
95
+ * @example With pre-parsed route data
96
+ * ```ts
97
+ * const result = await renderToString({
98
+ * url: '/users/123?tab=settings',
99
+ * App,
100
+ * params: { id: '123' },
101
+ * query: { tab: 'settings' },
102
+ * loaderData: { 'users.$id': userData },
103
+ * head: { title: 'User Profile' },
104
+ * status: 200,
105
+ * });
106
+ * ```
107
+ */
108
+ export async function renderToString(options) {
109
+ const { url, App, context = {}, appId = 'app', params, query, loaderData, head, status, } = options;
110
+ const timing = {
111
+ total: 0,
112
+ routeMatch: 0,
113
+ loaders: 0,
114
+ render: 0,
115
+ serialize: 0,
116
+ };
117
+ const totalStart = performance.now();
118
+ let env;
119
+ try {
120
+ // 1. Set up DOM environment (happy-dom)
121
+ // Pass URL so window.location reflects the request path during SSR
122
+ // Use URL constructor for proper URL normalization (handles relative paths, edge cases)
123
+ const envUrl = new URL(url, 'http://localhost').toString();
124
+ env = setupEnvironment({ url: envUrl, appId });
125
+ // Only now, having taken ownership of the environment, is the crash
126
+ // collector ours to clear. Routes render sequentially in one process, so a
127
+ // leftover record would otherwise fail the *next* route.
128
+ //
129
+ // Deliberately AFTER `setupEnvironment`, which throws if an environment is
130
+ // already active. Resetting first meant a nested or overlapping call wiped
131
+ // the in-flight render's records on its way to that error, and the outer
132
+ // render then passed its own crash assertion and reported success.
133
+ resetSSRRenderCrashes();
134
+ // 2. Create SSR context with any pre-populated data
135
+ const ssrContextOptions = {
136
+ url,
137
+ params,
138
+ query,
139
+ loaderData,
140
+ head,
141
+ status,
142
+ };
143
+ const ssrContext = createSSRContext(ssrContextOptions);
144
+ // 3. Run rendering within SSR context
145
+ const result = await runWithSSRContextAsync(ssrContext, async () => {
146
+ const renderStart = performance.now();
147
+ // Use AsyncLocalStorage for component context and onDestroy isolation
148
+ // This ensures concurrent renders don't interfere with each other
149
+ // See Task 14 in docs/ssr/progress-tracker.md
150
+ return runWithDestroyCallbacks(() => runWithComponentContext(context, () => {
151
+ let html = '';
152
+ let destroy;
153
+ let disposeSetup;
154
+ let diagnostics;
155
+ try {
156
+ // 4. Invoke the App component
157
+ const componentResult = createRoot(disposeRoot => {
158
+ disposeSetup = disposeRoot;
159
+ return App();
160
+ });
161
+ destroy = componentResult.destroy;
162
+ // 5. Get the app container and append the rendered content
163
+ const appContainer = document.getElementById(appId);
164
+ if (appContainer) {
165
+ appContainer.appendChild(componentResult.el);
166
+ html = appContainer.innerHTML;
167
+ }
168
+ else {
169
+ // Fallback: serialize the node directly. Wrapping covers every
170
+ // node kind uniformly — a component's `el` is a `Node`, so it may
171
+ // be a fragment or a text node, neither of which has `outerHTML`.
172
+ const wrapper = document.createElement('div');
173
+ wrapper.appendChild(componentResult.el.cloneNode(true));
174
+ html = wrapper.innerHTML;
175
+ }
176
+ // Drop any inline style derived from an unmeasurable layout. See
177
+ // `layout-taint.ts`: measurements answer NaN on the server, so the
178
+ // declarations they produce identify themselves.
179
+ //
180
+ // Cleaned on the DOM, before serialization — a regex over the
181
+ // finished HTML cannot tell a style attribute from the same
182
+ // characters inside app-authored content.
183
+ const droppedStyles = [];
184
+ if (appContainer) {
185
+ stripTaintedStyles(appContainer, d => droppedStyles.push(d));
186
+ html = appContainer.innerHTML;
187
+ }
188
+ diagnostics = buildLayoutDiagnostics(html, droppedStyles);
189
+ // Checked once the tree is complete, so a crash a boundary went
190
+ // on to handle is not reported — but before the `finally` below
191
+ // tears the tree down, since the records reference its elements.
192
+ assertNoUnhandledComponentCrash();
193
+ timing.render = performance.now() - renderStart;
194
+ // 6. Serialize state
195
+ const serializeStart = performance.now();
196
+ const state = {
197
+ url: ssrContext.url,
198
+ params: ssrContext.params,
199
+ query: ssrContext.query,
200
+ loaderData: ssrContext.loaderData,
201
+ timestamp: Date.now(),
202
+ version: SSR_VERSION,
203
+ };
204
+ timing.serialize = performance.now() - serializeStart;
205
+ // 7. Collect head state
206
+ const headState = { ...ssrContext.head };
207
+ return {
208
+ html,
209
+ head: headState,
210
+ state,
211
+ status: ssrContext.status,
212
+ redirectTo: ssrContext.redirectTo,
213
+ layoutDiagnostics: diagnostics,
214
+ };
215
+ }
216
+ finally {
217
+ // Call destroy if available
218
+ try {
219
+ if (typeof destroy === 'function') {
220
+ try {
221
+ destroy();
222
+ }
223
+ catch {
224
+ // Ignore cleanup errors during SSR
225
+ }
226
+ }
227
+ }
228
+ finally {
229
+ try {
230
+ disposeSetup?.();
231
+ }
232
+ catch {
233
+ // Ignore cleanup errors during SSR
234
+ }
235
+ }
236
+ }
237
+ }));
238
+ });
239
+ timing.total = performance.now() - totalStart;
240
+ return {
241
+ ...result,
242
+ timing,
243
+ };
244
+ }
245
+ finally {
246
+ // Guarded for the same reason as the reset above: a call that never owned
247
+ // the environment must not clear the records of the render that does.
248
+ if (env) {
249
+ // Never let a record outlive its render — a leaked entry would fail an
250
+ // unrelated route later in the same process.
251
+ resetSSRRenderCrashes();
252
+ env.cleanup();
253
+ }
254
+ }
255
+ }
256
+ //# sourceMappingURL=render.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render.js","sourceRoot":"","sources":["../../src/server/render.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;GAKG;AAEH,OAAO,EACL,gCAAgC,EAChC,qBAAqB,GAEtB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EACL,WAAW,GAMZ,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,gBAAgB,EAChB,aAAa,EACb,s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AAU,EAAE,UAAU,CAAC,UAAU;wBACjC,iBAAiB,EAAE,WAAW;qBAC/B,CAAC;gBACJ,CAAC;wBAAS,CAAC;oBACT,4BAA4B;oBAC5B,IAAI,CAAC;wBACH,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE,CAAC;4BAClC,IAAI,CAAC;gCACH,OAAO,EAAE,CAAC;4BACZ,CAAC;4BAAC,MAAM,CAAC;gCACP,mCAAmC;4BACrC,CAAC;wBACH,CAAC;oBACH,CAAC;4BAAS,CAAC;wBACT,IAAI,CAAC;4BACH,YAAY,EAAE,EAAE,CAAC;wBACnB,CAAC;wBAAC,MAAM,CAAC;4BACP,mCAAmC;wBACrC,CAAC;oBACH,CAAC;gBACH,CAAC;YACH,CAAC,CAAC,CACH,CAAC;QACJ,CAAC,CAAC,CAAC;QAEH,MAAM,CAAC,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE,GAAG,UAAU,CAAC;QAE9C,OAAO;YACL,GAAG,MAAM;YACT,MAAM;SACP,CAAC;IACJ,CAAC;YAAS,CAAC;QACT,0EAA0E;QAC1E,sEAAsE;QACtE,IAAI,GAAG,EAAE,CAAC;YACR,uEAAuE;YACvE,6CAA6C;YAC7C,qBAAqB,EAAE,CAAC;YACxB,GAAG,CAAC,OAAO,EAAE,CAAC;QAChB,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.ssr.server.render\",\n \"title\": \"SSR Render to String\",\n \"category\": \"runtime\"\n}\n*/\n\n/**\n * @pithyjs/ssr - Server-Side Rendering\n *\n * Core renderToString function that renders PithyJS components to HTML strings\n * on the server for SSR/SSG.\n */\n\nimport {\n collectUnhandledSSRRenderCrashes,\n resetSSRRenderCrashes,\n type Component,\n} from '@pithyjs/core';\nimport { createRoot } from '@pithyjs/signals';\nimport {\n SSR_VERSION,\n type RenderResult,\n type RenderTiming,\n type SerializedState,\n type HeadState,\n type LayoutDiagnostics,\n} from '../shared/types.js';\nimport {\n createSSRContext,\n getSSRContext,\n runWithSSRContextAsync,\n runWithComponentContext,\n runWithDestroyCallbacks,\n type CreateSSRContextOptions,\n} from './context.js';\nimport { setupEnvironment } from './environment.js';\nimport { setContextGetter } from '../shared/head.js';\nimport { findSuspiciousGeometry, stripTaintedStyles } from './layout-taint.js';\n\n/**\n * Collect layout-taint findings for a render, deduplicated.\n *\n * Returned to the caller rather than logged — see `RenderResult.layoutDiagnostics`.\n */\nfunction buildLayoutDiagnostics(\n html: string,\n droppedStyles: string[]\n): LayoutDiagnostics | undefined {\n const suspiciousGeometry = [...new Set(findSuspiciousGeometry(html))];\n const dropped = [...new Set(droppedStyles)];\n\n if (dropped.length === 0 && suspiciousGeometry.length === 0) return undefined;\n return { droppedStyles: dropped, suspiciousGeometry };\n}\n\n/**\n * Fail the render if a component crashed and no `@error-boundary` claimed it.\n *\n * The binders degrade at the crash site and record what they could not hand to\n * an `@error-boundary`. Whatever is still recorded once the render finishes is a\n * genuine failure, and throwing hands it to the per-route catch in `vite-ssg.ts`\n * so the route lands in `failed[]` and the CLI exits non-zero (BUG-018).\n *\n * @throws the first unhandled crash, wrapped so the tag is legible in the\n * `Failed routes:` summary; the original error is kept as `cause`.\n */\nfunction assertNoUnhandledComponentCrash(): void {\n const unhandled = collectUnhandledSSRRenderCrashes();\n if (unhandled.length === 0) return;\n\n const [first, ...rest] = unhandled;\n for (const crash of rest) {\n console.error(\n `[SSR] Component <${crash.tag}> also crashed during render:`,\n crash.error\n );\n }\n\n const suffix =\n rest.length > 0 ? ` (and ${rest.length} more component crash(es))` : '';\n const failure = new Error(\n `Component <${first.tag}> crashed during render: ${first.error.message}${suffix}`\n );\n // Assigned through a cast rather than passed to the constructor: the repo\n // targets ES2020, where neither `new Error(msg, { cause })` nor `.cause` is in\n // the lib's signature — though every runtime we ship to supports both. Worth\n // keeping: it is what preserves the component's own stack for the failure\n // report, which the message alone flattens away.\n (failure as Error & { cause?: unknown }).cause = first.error;\n throw failure;\n}\n\n// Wire up the head() function to access SSR context\n// This bridges the shared head module to the server's AsyncLocalStorage-based context\nsetContextGetter(getSSRContext);\n\n// Note: The global __getComponentContext getter is installed automatically when\n// context.ts is loaded. This happens as a side effect of importing from './context.js'.\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Extended render options that include the App component\n */\nexport interface RenderToStringOptions {\n /** URL to render */\n url: string;\n /** The root component to render */\n App: Component;\n /** Additional context to pass to components */\n context?: Record<string, unknown>;\n /** App container ID (default: 'app') */\n appId?: string;\n /** Route parameters (from your router or explicitly provided; renderToString does not parse these from the URL) */\n params?: Record<string, string>;\n /** Query parameters (explicitly provided; if omitted or empty, they are parsed from the `url` search string by createSSRContext) */\n query?: Record<string, string>;\n /** Pre-populated loader data (from executeSSRLoaders) */\n loaderData?: Record<string, unknown>;\n /** Initial head state */\n head?: Partial<HeadState>;\n /** Initial HTTP status code (default: 200) */\n status?: number;\n // Note: timeout option was removed as it was not implemented.\n // If render timeout is needed in the future, it should be implemented\n // using AbortController pattern similar to loader timeout handling.\n}\n\n// =============================================================================\n// Implementation\n// =============================================================================\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.render\",\"name\":\"renderToString\",\"stability\":\"experimental\",\"signature\":\"(options: RenderToStringOptions) => Promise<RenderResult>\"} */\n/**\n * Render a PithyJS component to an HTML string\n *\n * Sets up the SSR environment, renders the component tree, collects head state,\n * and returns the result for hydration.\n *\n * @param options - Render options\n * @param options.url - The URL to render (required)\n * @param options.App - The root component to render (required)\n * @param options.context - Additional context passed to components\n * @param options.appId - Container element ID (default: 'app')\n * @param options.params - Pre-parsed route parameters (e.g., `{ id: '123' }`)\n * @param options.query - Pre-parsed query parameters (e.g., `{ tab: 'settings' }`)\n * @param options.loaderData - Pre-fetched loader data keyed by route segment ID\n * @param options.head - Initial head state (title, meta tags, etc.)\n * @param options.status - Initial HTTP status code (default: 200)\n * @returns Rendered HTML, head state, serialized state, and timing info\n *\n * @example Basic usage\n * ```ts\n * const result = await renderToString({\n * url: '/dashboard',\n * App,\n * });\n * ```\n *\n * @example With pre-parsed route data\n * ```ts\n * const result = await renderToString({\n * url: '/users/123?tab=settings',\n * App,\n * params: { id: '123' },\n * query: { tab: 'settings' },\n * loaderData: { 'users.$id': userData },\n * head: { title: 'User Profile' },\n * status: 200,\n * });\n * ```\n */\nexport async function renderToString(\n options: RenderToStringOptions\n): Promise<RenderResult> {\n const {\n url,\n App,\n context = {},\n appId = 'app',\n params,\n query,\n loaderData,\n head,\n status,\n } = options;\n const timing: RenderTiming = {\n total: 0,\n routeMatch: 0,\n loaders: 0,\n render: 0,\n serialize: 0,\n };\n\n const totalStart = performance.now();\n let env: ReturnType<typeof setupEnvironment> | undefined;\n\n try {\n // 1. Set up DOM environment (happy-dom)\n // Pass URL so window.location reflects the request path during SSR\n // Use URL constructor for proper URL normalization (handles relative paths, edge cases)\n const envUrl = new URL(url, 'http://localhost').toString();\n env = setupEnvironment({ url: envUrl, appId });\n\n // Only now, having taken ownership of the environment, is the crash\n // collector ours to clear. Routes render sequentially in one process, so a\n // leftover record would otherwise fail the *next* route.\n //\n // Deliberately AFTER `setupEnvironment`, which throws if an environment is\n // already active. Resetting first meant a nested or overlapping call wiped\n // the in-flight render's records on its way to that error, and the outer\n // render then passed its own crash assertion and reported success.\n resetSSRRenderCrashes();\n\n // 2. Create SSR context with any pre-populated data\n const ssrContextOptions: CreateSSRContextOptions = {\n url,\n params,\n query,\n loaderData,\n head,\n status,\n };\n const ssrContext = createSSRContext(ssrContextOptions);\n\n // 3. Run rendering within SSR context\n const result = await runWithSSRContextAsync(ssrContext, async () => {\n const renderStart = performance.now();\n\n // Use AsyncLocalStorage for component context and onDestroy isolation\n // This ensures concurrent renders don't interfere with each other\n // See Task 14 in docs/ssr/progress-tracker.md\n return runWithDestroyCallbacks(() =>\n runWithComponentContext(context, () => {\n let html = '';\n let destroy: (() => void) | undefined;\n let disposeSetup: (() => void) | undefined;\n let diagnostics: LayoutDiagnostics | undefined;\n\n try {\n // 4. Invoke the App component\n const componentResult = createRoot(disposeRoot => {\n disposeSetup = disposeRoot;\n return App();\n });\n destroy = componentResult.destroy;\n\n // 5. Get the app container and append the rendered content\n const appContainer = document.getElementById(appId);\n if (appContainer) {\n appContainer.appendChild(componentResult.el);\n html = appContainer.innerHTML;\n } else {\n // Fallback: serialize the node directly. Wrapping covers every\n // node kind uniformly — a component's `el` is a `Node`, so it may\n // be a fragment or a text node, neither of which has `outerHTML`.\n const wrapper = document.createElement('div');\n wrapper.appendChild(componentResult.el.cloneNode(true));\n html = wrapper.innerHTML;\n }\n\n // Drop any inline style derived from an unmeasurable layout. See\n // `layout-taint.ts`: measurements answer NaN on the server, so the\n // declarations they produce identify themselves.\n //\n // Cleaned on the DOM, before serialization — a regex over the\n // finished HTML cannot tell a style attribute from the same\n // characters inside app-authored content.\n const droppedStyles: string[] = [];\n if (appContainer) {\n stripTaintedStyles(appContainer, d => droppedStyles.push(d));\n html = appContainer.innerHTML;\n }\n\n diagnostics = buildLayoutDiagnostics(html, droppedStyles);\n\n // Checked once the tree is complete, so a crash a boundary went\n // on to handle is not reported — but before the `finally` below\n // tears the tree down, since the records reference its elements.\n assertNoUnhandledComponentCrash();\n\n timing.render = performance.now() - renderStart;\n\n // 6. Serialize state\n const serializeStart = performance.now();\n const state: SerializedState = {\n url: ssrContext.url,\n params: ssrContext.params,\n query: ssrContext.query,\n loaderData: ssrContext.loaderData,\n timestamp: Date.now(),\n version: SSR_VERSION,\n };\n timing.serialize = performance.now() - serializeStart;\n\n // 7. Collect head state\n const headState: HeadState = { ...ssrContext.head };\n\n return {\n html,\n head: headState,\n state,\n status: ssrContext.status,\n redirectTo: ssrContext.redirectTo,\n layoutDiagnostics: diagnostics,\n };\n } finally {\n // Call destroy if available\n try {\n if (typeof destroy === 'function') {\n try {\n destroy();\n } catch {\n // Ignore cleanup errors during SSR\n }\n }\n } finally {\n try {\n disposeSetup?.();\n } catch {\n // Ignore cleanup errors during SSR\n }\n }\n }\n })\n );\n });\n\n timing.total = performance.now() - totalStart;\n\n return {\n ...result,\n timing,\n };\n } finally {\n // Guarded for the same reason as the reset above: a call that never owned\n // the environment must not clear the records of the render that does.\n if (env) {\n // Never let a record outlive its render — a leaked entry would fail an\n // unrelated route later in the same process.\n resetSSRRenderCrashes();\n env.cleanup();\n }\n }\n}\n"]}