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

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,479 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.ssr.server.loaders",
4
+ "title": "SSR Loader Execution",
5
+ "category": "runtime"
6
+ }
7
+ */
8
+ /**
9
+ * @pithyjs/ssr - SSR Loader Execution
10
+ *
11
+ * Executes route loaders during server-side rendering and serializes
12
+ * loader data for client hydration.
13
+ */
14
+ import { combineAbortSignals, findBestMatch, } from '@pithyjs/router';
15
+ import { getSSRContext, setLoaderData, setStatus } from './context.js';
16
+ import { isDev } from './utils.js';
17
+ // Create a fresh signal when no AbortSignal is provided.
18
+ // Avoid sharing a singleton to prevent accumulating abort listeners across requests.
19
+ const createNeverAbortSignal = () => new AbortController().signal;
20
+ // Re-export serialization utilities
21
+ export { serializeLoaderData, deserializeLoaderData, } from './serialization.js';
22
+ // =============================================================================
23
+ // Loader Execution
24
+ // =============================================================================
25
+ /** @codexApi {"parent":"pithy.ssr.server.loaders","name":"executeSSRLoaders","stability":"stable","signature":"(options: ExecuteLoadersOptions) => Promise<ExecuteLoadersResult>"} */
26
+ /**
27
+ * Execute loaders for route segments during SSR
28
+ *
29
+ * Loaders are executed in sequence (parent to child) to allow parent
30
+ * loader data to potentially inform child loaders.
31
+ *
32
+ * @param options - Loader execution options
33
+ * @returns Result containing loader data and status
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * const result = await executeSSRLoaders({
38
+ * segments: [
39
+ * { id: 'root', loader: rootLoader },
40
+ * { id: 'dashboard', loader: dashboardLoader }
41
+ * ],
42
+ * params: { id: '123' },
43
+ * query: { tab: 'settings' }
44
+ * });
45
+ *
46
+ * if (result.success) {
47
+ * console.log('All loaders succeeded:', result.loaderData);
48
+ * }
49
+ * ```
50
+ */
51
+ export async function executeSSRLoaders(options) {
52
+ const { segments, params, query, timeout = 30000, signal: externalSignal, continueOnError = false, } = options;
53
+ const startTime = performance.now();
54
+ const results = [];
55
+ const loaderData = {};
56
+ let firstError;
57
+ // Track timeout state externally (since combineAbortSignals doesn't preserve reason)
58
+ let didTimeout = false;
59
+ // Create timeout abort controller
60
+ const timeoutController = new AbortController();
61
+ const timeoutId = setTimeout(() => {
62
+ didTimeout = true;
63
+ timeoutController.abort();
64
+ }, timeout);
65
+ // Combine external signal with timeout (only if external signal exists)
66
+ const signal = externalSignal
67
+ ? combineAbortSignals([externalSignal, timeoutController.signal])
68
+ : timeoutController.signal;
69
+ // Helper to check if abort was timeout
70
+ const isTimeoutAbort = () => didTimeout && signal.aborted;
71
+ try {
72
+ // Execute loaders sequentially (parent to child)
73
+ for (const segment of segments) {
74
+ // Skip segments without loaders
75
+ if (!segment.loader) {
76
+ continue;
77
+ }
78
+ // Check if already aborted
79
+ if (signal.aborted) {
80
+ const abortResult = createAbortedResult(segment.id, isTimeoutAbort());
81
+ results.push(abortResult);
82
+ if (!firstError)
83
+ firstError = abortResult.error;
84
+ break;
85
+ }
86
+ // Execute single loader
87
+ const result = await executeSingleLoader(segment, {
88
+ params,
89
+ query,
90
+ signal,
91
+ isTimeoutAbort,
92
+ });
93
+ results.push(result);
94
+ if (result.success && result.data !== undefined) {
95
+ loaderData[segment.id] = result.data;
96
+ // Store in SSR context if available
97
+ const ctx = getSSRContext();
98
+ if (ctx) {
99
+ setLoaderData(segment.id, result.data);
100
+ }
101
+ else if (isDev()) {
102
+ console.warn(`[SSR] Loader data for "${segment.id}" was not stored because no SSR context is active. ` +
103
+ 'Ensure executeSSRLoaders() is called within runWithSSRContext() or runWithSSRContextAsync() or as part of renderToString for proper hydration.');
104
+ }
105
+ }
106
+ else if (result.error) {
107
+ if (!firstError)
108
+ firstError = result.error;
109
+ // Stop execution unless continueOnError is true
110
+ if (!continueOnError) {
111
+ break;
112
+ }
113
+ }
114
+ }
115
+ }
116
+ finally {
117
+ clearTimeout(timeoutId);
118
+ }
119
+ const totalTiming = performance.now() - startTime;
120
+ const success = !firstError;
121
+ // Set error status in SSR context if any loader failed
122
+ if (!success) {
123
+ const ctx = getSSRContext();
124
+ if (ctx) {
125
+ setStatus(500);
126
+ }
127
+ else if (isDev()) {
128
+ console.warn('[SSR] Loader error status (500) was not set because executeSSRLoaders() ran without an active SSR context. ' +
129
+ 'Ensure executeSSRLoaders() is called within runWithSSRContext() or runWithSSRContextAsync() or as part of renderToString for proper error handling.');
130
+ }
131
+ }
132
+ // Calculate aggregated cache hints
133
+ const cacheHints = aggregateCacheHints(results);
134
+ return {
135
+ results,
136
+ loaderData,
137
+ success,
138
+ firstError,
139
+ totalTiming,
140
+ cacheHints,
141
+ };
142
+ }
143
+ /** @codexApi {"parent":"pithy.ssr.server.loaders","name":"createSSRLoaderContext","stability":"stable","signature":"(options: { params: Record<string, string>; query: Record<string, string>; signal?: AbortSignal }) => LoaderContext"} */
144
+ /**
145
+ * Create a LoaderContext for SSR execution
146
+ *
147
+ * @param options - Context options
148
+ * @returns LoaderContext compatible with router loaders
149
+ *
150
+ * @example
151
+ * ```ts
152
+ * const context = createSSRLoaderContext({
153
+ * params: { id: '123' },
154
+ * query: { filter: 'active' }
155
+ * });
156
+ * const data = await myLoader(context);
157
+ * ```
158
+ */
159
+ export function createSSRLoaderContext(options) {
160
+ const { params, query, signal } = options;
161
+ return {
162
+ params,
163
+ query,
164
+ signal: signal ?? createNeverAbortSignal(),
165
+ // Use 0 as navId for SSR (single request, no navigation tracking)
166
+ navId: 0,
167
+ };
168
+ }
169
+ // =============================================================================
170
+ // Single Loader Execution
171
+ // =============================================================================
172
+ /**
173
+ * Execute a single loader with error handling
174
+ */
175
+ async function executeSingleLoader(segment, contextOptions) {
176
+ const startTime = performance.now();
177
+ // Create loader context
178
+ const context = createSSRLoaderContext(contextOptions);
179
+ try {
180
+ // Execute loader (may be sync or async)
181
+ const data = await Promise.resolve(segment.loader(context));
182
+ const timing = performance.now() - startTime;
183
+ return {
184
+ id: segment.id,
185
+ success: true,
186
+ data,
187
+ timing,
188
+ cacheHints: deriveCacheHints(segment.cacheOptions),
189
+ };
190
+ }
191
+ catch (error) {
192
+ const timing = performance.now() - startTime;
193
+ return {
194
+ id: segment.id,
195
+ success: false,
196
+ error: normalizeLoaderError(error, contextOptions.signal, contextOptions.isTimeoutAbort),
197
+ timing,
198
+ cacheHints: { public: false, maxAge: 0, noStore: true },
199
+ };
200
+ }
201
+ }
202
+ /**
203
+ * Create a result for an aborted loader
204
+ */
205
+ function createAbortedResult(id, isTimeout) {
206
+ return {
207
+ id,
208
+ success: false,
209
+ error: {
210
+ message: isTimeout
211
+ ? 'Loader execution timeout'
212
+ : 'Loader execution aborted',
213
+ name: isTimeout ? 'TimeoutError' : 'AbortError',
214
+ isTimeout,
215
+ isAborted: true,
216
+ },
217
+ timing: 0,
218
+ cacheHints: { public: false, maxAge: 0, noStore: true },
219
+ };
220
+ }
221
+ // =============================================================================
222
+ // Cache Hints
223
+ // =============================================================================
224
+ /**
225
+ * Derive cache hints from loader cache options
226
+ */
227
+ function deriveCacheHints(options) {
228
+ if (!options) {
229
+ // Default: private, cache for 5 minutes
230
+ return {
231
+ public: false,
232
+ maxAge: 300,
233
+ noStore: false,
234
+ };
235
+ }
236
+ if (options.strategy === 'no-store') {
237
+ return {
238
+ public: false,
239
+ maxAge: 0,
240
+ noStore: true,
241
+ };
242
+ }
243
+ return {
244
+ public: options.public ?? false,
245
+ maxAge: options.ttl ? Math.floor(options.ttl / 1000) : 300,
246
+ swr: options.swr,
247
+ noStore: false,
248
+ };
249
+ }
250
+ /**
251
+ * Aggregate cache hints from multiple loaders (most restrictive wins)
252
+ *
253
+ * Rules:
254
+ * - public/private: Only public if ALL loaders explicitly allow public
255
+ * - maxAge: Shortest wins
256
+ * - swr: Shortest wins
257
+ * - noStore: Any noStore makes result noStore
258
+ */
259
+ function aggregateCacheHints(results) {
260
+ // Track if ALL loaders allow public caching (most restrictive wins)
261
+ // Starts true, becomes false permanently if ANY loader is private
262
+ let allAllowPublic = true;
263
+ let maxAge = Infinity;
264
+ let swr;
265
+ let noStore = false;
266
+ let hasAnyHints = false;
267
+ for (const result of results) {
268
+ const hints = result.cacheHints;
269
+ if (!hints)
270
+ continue;
271
+ hasAnyHints = true;
272
+ // no-store is most restrictive - short circuit
273
+ if (hints.noStore) {
274
+ noStore = true;
275
+ continue;
276
+ }
277
+ // If ANY loader requires private, result must be private
278
+ // (public only if ALL loaders allow it)
279
+ if (!hints.public) {
280
+ allAllowPublic = false;
281
+ }
282
+ // Shortest max-age wins
283
+ if (hints.maxAge < maxAge) {
284
+ maxAge = hints.maxAge;
285
+ }
286
+ // Shortest swr wins
287
+ if (hints.swr !== undefined) {
288
+ swr = swr === undefined ? hints.swr : Math.min(swr, hints.swr);
289
+ }
290
+ }
291
+ // If no loaders had cache hints, use restrictive defaults
292
+ if (!hasAnyHints || maxAge === Infinity) {
293
+ maxAge = 300;
294
+ }
295
+ // Final public status: must have hints, all must allow public, and no noStore
296
+ const isPublic = hasAnyHints && allAllowPublic && !noStore;
297
+ return {
298
+ public: isPublic,
299
+ maxAge: noStore ? 0 : maxAge,
300
+ swr: noStore ? undefined : swr,
301
+ noStore,
302
+ };
303
+ }
304
+ /** @codexApi {"parent":"pithy.ssr.server.loaders","name":"generateCacheControlHeader","stability":"stable","signature":"(hints: SSRCacheHints) => string"} */
305
+ /**
306
+ * Generate Cache-Control header value from cache hints
307
+ *
308
+ * @param hints - Aggregated cache hints
309
+ * @returns Cache-Control header value
310
+ *
311
+ * @example
312
+ * ```ts
313
+ * const cacheControl = generateCacheControlHeader(result.cacheHints);
314
+ * res.setHeader('Cache-Control', cacheControl);
315
+ * ```
316
+ */
317
+ export function generateCacheControlHeader(hints) {
318
+ if (hints.noStore) {
319
+ return 'no-store, no-cache, must-revalidate';
320
+ }
321
+ const directives = [];
322
+ directives.push(hints.public ? 'public' : 'private');
323
+ directives.push(`max-age=${hints.maxAge}`);
324
+ if (hints.swr !== undefined) {
325
+ directives.push(`stale-while-revalidate=${hints.swr}`);
326
+ }
327
+ return directives.join(', ');
328
+ }
329
+ // =============================================================================
330
+ // Route Segment Extraction
331
+ // =============================================================================
332
+ /** @codexApi {"parent":"pithy.ssr.server.loaders","name":"extractLoadersFromRouteTree","stability":"stable","signature":"(nodes: RouteNode[], matchedPath: string[]) => Promise<SSRRouteSegment[]>"} */
333
+ /**
334
+ * Extract loader segments from matched route nodes
335
+ *
336
+ * Handles both nested route trees AND flat manifests (where all routes are
337
+ * at the top level with full path patterns like `/dashboard/settings`).
338
+ *
339
+ * @param nodes - Route nodes (may be flat or nested)
340
+ * @param matchedPath - Matched path segments (e.g., ['dashboard', 'settings'])
341
+ * @returns Array of route segments with loaders (parent to child order)
342
+ *
343
+ * @example
344
+ * ```ts
345
+ * const segments = await extractLoadersFromRouteTree(routes, ['dashboard', 'settings']);
346
+ * ```
347
+ */
348
+ export async function extractLoadersFromRouteTree(nodes, matchedPath) {
349
+ const segments = [];
350
+ // Build all URL prefixes from matched path segments
351
+ // e.g., ['dashboard', 'settings'] → ['/', '/dashboard', '/dashboard/settings']
352
+ const prefixes = buildUrlPrefixes(matchedPath);
353
+ // Track which route IDs we've already processed to avoid duplicates
354
+ const processedIds = new Set();
355
+ // Collect all route nodes (flatten if nested)
356
+ const allNodes = collectAllNodes(nodes);
357
+ // For each URL prefix, find matching routes and collect their loaders
358
+ for (const prefix of prefixes) {
359
+ const node = findMatchingNodeByPattern(allNodes, prefix);
360
+ if (!node || processedIds.has(node.id))
361
+ continue;
362
+ processedIds.add(node.id);
363
+ // Load loader if present
364
+ if (node.imports.loader) {
365
+ try {
366
+ const loaderModule = await node.imports.loader();
367
+ const loaderExport = loaderModule.default ?? loaderModule.loader;
368
+ const loader = typeof loaderExport === 'function'
369
+ ? loaderExport
370
+ : undefined;
371
+ // Load config for cache options
372
+ let cacheOptions;
373
+ if (node.imports.config) {
374
+ const configModule = await node.imports.config();
375
+ const cache = configModule.cache;
376
+ if (cache && typeof cache === 'object') {
377
+ const { strategy, ttl } = cache;
378
+ cacheOptions = { strategy, ttl };
379
+ }
380
+ }
381
+ segments.push({
382
+ id: node.id,
383
+ loader,
384
+ cacheOptions,
385
+ });
386
+ }
387
+ catch (error) {
388
+ // Warn in development about failed loader imports
389
+ if (isDev()) {
390
+ console.warn(`[SSR] Failed to import loader for route "${node.id}":`, error instanceof Error ? error.message : error);
391
+ }
392
+ }
393
+ }
394
+ }
395
+ return segments;
396
+ }
397
+ /**
398
+ * Build URL prefixes from path segments
399
+ * e.g., ['dashboard', 'settings'] → ['/', '/dashboard', '/dashboard/settings']
400
+ */
401
+ function buildUrlPrefixes(pathSegments) {
402
+ const prefixes = ['/'];
403
+ let currentPath = '';
404
+ for (const segment of pathSegments) {
405
+ currentPath += '/' + segment;
406
+ prefixes.push(currentPath);
407
+ }
408
+ return prefixes;
409
+ }
410
+ /**
411
+ * Collect all route nodes (flattens nested tree structure)
412
+ * This ensures we can match routes regardless of whether manifest is flat or nested
413
+ */
414
+ function collectAllNodes(nodes) {
415
+ const result = [];
416
+ for (const node of nodes) {
417
+ result.push(node);
418
+ if (node.children.length > 0) {
419
+ result.push(...collectAllNodes(node.children));
420
+ }
421
+ }
422
+ return result;
423
+ }
424
+ /**
425
+ * Find a matching node using pattern matching
426
+ *
427
+ * For SSR loader extraction, we prioritize exact pattern matches over catch-all
428
+ * patterns. This ensures parent routes' loaders run even when a child catch-all
429
+ * also matches the URL.
430
+ *
431
+ * Example: For URL prefix '/docs', we want to match pattern '/docs' exactly,
432
+ * not '/docs/*' which would also match but is a child route.
433
+ */
434
+ function findMatchingNodeByPattern(nodes, urlPath) {
435
+ // Build pattern-to-node map
436
+ const nodeByPattern = new Map();
437
+ const patterns = [];
438
+ for (const node of nodes) {
439
+ patterns.push(node.pattern);
440
+ nodeByPattern.set(node.pattern, node);
441
+ }
442
+ // First, check for an exact pattern match (highest priority for SSR loaders)
443
+ // This ensures parent routes like '/docs' are matched before catch-all '/docs/*'
444
+ if (nodeByPattern.has(urlPath)) {
445
+ return nodeByPattern.get(urlPath);
446
+ }
447
+ // Fall back to findBestMatch for dynamic/catch-all patterns
448
+ const match = findBestMatch(urlPath, patterns);
449
+ if (!match) {
450
+ return undefined;
451
+ }
452
+ return nodeByPattern.get(match.pattern);
453
+ }
454
+ // =============================================================================
455
+ // Utilities
456
+ // =============================================================================
457
+ /**
458
+ * Normalize an error into SSRLoaderError format
459
+ */
460
+ function normalizeLoaderError(error, signal, isTimeoutAbort) {
461
+ const isAborted = signal.aborted;
462
+ const isTimeout = isTimeoutAbort();
463
+ if (error instanceof Error) {
464
+ return {
465
+ message: error.message,
466
+ name: error.name,
467
+ stack: isDev() ? error.stack : undefined,
468
+ isTimeout,
469
+ isAborted,
470
+ };
471
+ }
472
+ return {
473
+ message: String(error),
474
+ name: 'Error',
475
+ isTimeout,
476
+ isAborted,
477
+ };
478
+ }
479
+ //# sourceMappingURL=loaders.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loaders.js","sourceRoot":"","sources":["../../src/server/loaders.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;GAKG;AAEH,OAAO,EACL,mBAAmB,EACnB,aAAa,GAKd,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACvE,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAEnC,yDAAyD;AACzD,qFAAqF;AACrF,MAAM,sBAAsB,GAAG,GAAgB,EAAE,CAAC,IAAI,eAAe,EAAE,CAAC,MAAM,CAAC;AAE/E,oCAAoC;AACpC,OAAO,EACL,mBAAmB,EACnB,qBAAqB,GAEtB,MAAM,oBAAoB,CAAC;AAgH5B,gFAAgF;AAChF,mBAAmB;AACnB,gFAAgF;AAEhF,sLAAsL;AACtL;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,OAA8B;IAE9B,MAAM,EACJ,QAAQ,EACR,MAAM,EACN,KAAK,EACL,OAAO,GAAG,KAAK,EACf,MAAM,EAAE,cAAc,EACtB,eAAe,GAAG,KAAK,GACxB,GAAG,OAAO,CAAC;IAEZ,MAAM,SAAS,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IACpC,MAAM,OAAO,GAAsB,EAAE,CAAC;IACtC,MAAM,UAAU,GAA4B,EAAE,CAAC;IAC/C,IAAI,UAAsC,CAAC;IAE3C,qFAAqF;IACrF,IAAI,UAAU,GAAG,KAAK,CAAC;IAEvB,kCAAkC;IAClC,MAAM,iBAAiB,GAAG,IAAI,eAAe,EAAE,CAAC;IAChD,MAAM,SAAS,GAAG,UAAU,CAAC,GAAG,EAAE;QAChC,UAAU,GAAG,IAAI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C,EAAE,CAAC;QAC/B,OAAO,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IACpC,CAAC;IAED,4DAA4D;IAC5D,MAAM,KAAK,GAAG,aAAa,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;IAC/C,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,OAAO,aAAa,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;AAC1C,CAAC;AAED,gFAAgF;AAChF,YAAY;AACZ,gFAAgF;AAEhF;;GAEG;AACH,SAAS,oBAAoB,CAC3B,KAAc,EACd,MAAmB,EACnB,cAA6B;IAE7B,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC;IACjC,MAAM,SAAS,GAAG,cAAc,EAAE,CAAC;IAEnC,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;QAC3B,OAAO;YACL,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS;YACxC,SAAS;YACT,SAAS;SACV,CAAC;IACJ,CAAC;IAED,OAAO;QACL,OAAO,EAAE,MAAM,CAAC,KAAK,CAAC;QACtB,IAAI,EAAE,OAAO;QACb,SAAS;QACT,SAAS;KACV,CAAC;AACJ,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.ssr.server.loaders\",\n \"title\": \"SSR Loader Execution\",\n \"category\": \"runtime\"\n}\n*/\n\n/**\n * @pithyjs/ssr - SSR Loader Execution\n *\n * Executes route loaders during server-side rendering and serializes\n * loader data for client hydration.\n */\n\nimport {\n combineAbortSignals,\n findBestMatch,\n type LoaderFunction,\n type LoaderContext,\n type RouteNode,\n type CacheOptions,\n} from '@pithyjs/router';\nimport { getSSRContext, setLoaderData, setStatus } from './context.js';\nimport { isDev } from './utils.js';\n\n// Create a fresh signal when no AbortSignal is provided.\n// Avoid sharing a singleton to prevent accumulating abort listeners across requests.\nconst createNeverAbortSignal = (): AbortSignal => new AbortController().signal;\n\n// Re-export serialization utilities\nexport {\n serializeLoaderData,\n deserializeLoaderData,\n type SerializedLoaderData,\n} from './serialization.js';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Route segment with loader information for SSR execution\n */\nexport interface SSRRouteSegment {\n /** Unique route segment ID */\n id: string;\n /** Loader function (if present) */\n loader?: LoaderFunction;\n /** Cache options for this loader */\n cacheOptions?: SSRLoaderCacheOptions;\n}\n\n/**\n * Cache options for SSR loaders (extends router CacheOptions with HTTP-specific fields)\n */\nexport interface SSRLoaderCacheOptions extends CacheOptions {\n /** Whether response can be cached by CDN (public vs private) */\n public?: boolean;\n /** Stale-while-revalidate window in seconds (for HTTP header) */\n swr?: number;\n}\n\n/**\n * Options for SSR loader execution\n */\nexport interface ExecuteLoadersOptions {\n /** Route segments to execute loaders for */\n segments: SSRRouteSegment[];\n /** Route parameters */\n params: Record<string, string>;\n /** Query parameters */\n query: Record<string, string>;\n /** Timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Abort signal for cancellation */\n signal?: AbortSignal;\n /** Whether to continue on loader error (default: false) */\n continueOnError?: boolean;\n}\n\n/**\n * Result from executing a single loader\n */\nexport interface SSRLoaderResult<T = unknown> {\n /** Route segment ID */\n id: string;\n /** Whether loader succeeded */\n success: boolean;\n /** Loader data (if successful) */\n data?: T;\n /** Error (if failed) */\n error?: SSRLoaderError;\n /** Execution time in milliseconds */\n timing: number;\n /** Cache hints from loader config */\n cacheHints?: SSRCacheHints;\n}\n\n/**\n * Loader error details\n */\nexport interface SSRLoaderError {\n /** Error message */\n message: string;\n /** Error name/type */\n name: string;\n /** Stack trace (in development) */\n stack?: string;\n /** Whether this was a timeout */\n isTimeout: boolean;\n /** Whether this was an abort */\n isAborted: boolean;\n}\n\n/**\n * Cache hints for HTTP headers\n */\nexport interface SSRCacheHints {\n /** Cache-Control: public or private */\n public: boolean;\n /** Max-age in seconds */\n maxAge: number;\n /** Stale-while-revalidate in seconds */\n swr?: number;\n /** Whether to skip cache entirely */\n noStore: boolean;\n}\n\n/**\n * Result from executeSSRLoaders\n */\nexport interface ExecuteLoadersResult {\n /** All loader results */\n results: SSRLoaderResult[];\n /** Combined loader data (keyed by segment ID) */\n loaderData: Record<string, unknown>;\n /** Whether all loaders succeeded */\n success: boolean;\n /** First error encountered (if any) */\n firstError?: SSRLoaderError;\n /** Total execution time in milliseconds */\n totalTiming: number;\n /** Aggregated cache hints (most restrictive wins) */\n cacheHints: SSRCacheHints;\n}\n\n// =============================================================================\n// Loader Execution\n// =============================================================================\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.loaders\",\"name\":\"executeSSRLoaders\",\"stability\":\"stable\",\"signature\":\"(options: ExecuteLoadersOptions) => Promise<ExecuteLoadersResult>\"} */\n/**\n * Execute loaders for route segments during SSR\n *\n * Loaders are executed in sequence (parent to child) to allow parent\n * loader data to potentially inform child loaders.\n *\n * @param options - Loader execution options\n * @returns Result containing loader data and status\n *\n * @example\n * ```ts\n * const result = await executeSSRLoaders({\n * segments: [\n * { id: 'root', loader: rootLoader },\n * { id: 'dashboard', loader: dashboardLoader }\n * ],\n * params: { id: '123' },\n * query: { tab: 'settings' }\n * });\n *\n * if (result.success) {\n * console.log('All loaders succeeded:', result.loaderData);\n * }\n * ```\n */\nexport async function executeSSRLoaders(\n options: ExecuteLoadersOptions\n): Promise<ExecuteLoadersResult> {\n const {\n segments,\n params,\n query,\n timeout = 30000,\n signal: externalSignal,\n continueOnError = false,\n } = options;\n\n const startTime = performance.now();\n const results: SSRLoaderResult[] = [];\n const loaderData: Record<string, unknown> = {};\n let firstError: SSRLoaderError | undefined;\n\n // Track timeout state externally (since combineAbortSignals doesn't preserve reason)\n let didTimeout = false;\n\n // Create timeout abort controller\n const timeoutController = new AbortController();\n const timeoutId = setTimeout(() => {\n didTimeout = true;\n timeoutController.abort();\n }, timeout);\n\n // Combine external signal with timeout (only if external signal exists)\n const signal = externalSignal\n ? combineAbortSignals([externalSignal, timeoutController.signal])\n : timeoutController.signal;\n\n // Helper to check if abort was timeout\n const isTimeoutAbort = () => didTimeout && signal.aborted;\n\n try {\n // Execute loaders sequentially (parent to child)\n for (const segment of segments) {\n // Skip segments without loaders\n if (!segment.loader) {\n continue;\n }\n\n // Check if already aborted\n if (signal.aborted) {\n const abortResult = createAbortedResult(segment.id, isTimeoutAbort());\n results.push(abortResult);\n if (!firstError) firstError = abortResult.error;\n break;\n }\n\n // Execute single loader\n const result = await executeSingleLoader(segment, {\n params,\n query,\n signal,\n isTimeoutAbort,\n });\n\n results.push(result);\n\n if (result.success && result.data !== undefined) {\n loaderData[segment.id] = result.data;\n\n // Store in SSR context if available\n const ctx = getSSRContext();\n if (ctx) {\n setLoaderData(segment.id, result.data);\n } else if (isDev()) {\n console.warn(\n `[SSR] Loader data for \"${segment.id}\" was not stored because no SSR context is active. ` +\n 'Ensure executeSSRLoaders() is called within runWithSSRContext() or runWithSSRContextAsync() or as part of renderToString for proper hydration.'\n );\n }\n } else if (result.error) {\n if (!firstError) firstError = result.error;\n\n // Stop execution unless continueOnError is true\n if (!continueOnError) {\n break;\n }\n }\n }\n } finally {\n clearTimeout(timeoutId);\n }\n\n const totalTiming = performance.now() - startTime;\n const success = !firstError;\n\n // Set error status in SSR context if any loader failed\n if (!success) {\n const ctx = getSSRContext();\n if (ctx) {\n setStatus(500);\n } else if (isDev()) {\n console.warn(\n '[SSR] Loader error status (500) was not set because executeSSRLoaders() ran without an active SSR context. ' +\n 'Ensure executeSSRLoaders() is called within runWithSSRContext() or runWithSSRContextAsync() or as part of renderToString for proper error handling.'\n );\n }\n }\n\n // Calculate aggregated cache hints\n const cacheHints = aggregateCacheHints(results);\n\n return {\n results,\n loaderData,\n success,\n firstError,\n totalTiming,\n cacheHints,\n };\n}\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.loaders\",\"name\":\"createSSRLoaderContext\",\"stability\":\"stable\",\"signature\":\"(options: { params: Record<string, string>; query: Record<string, string>; signal?: AbortSignal }) => LoaderContext\"} */\n/**\n * Create a LoaderContext for SSR execution\n *\n * @param options - Context options\n * @returns LoaderContext compatible with router loaders\n *\n * @example\n * ```ts\n * const context = createSSRLoaderContext({\n * params: { id: '123' },\n * query: { filter: 'active' }\n * });\n * const data = await myLoader(context);\n * ```\n */\nexport function createSSRLoaderContext(options: {\n params: Record<string, string>;\n query: Record<string, string>;\n signal?: AbortSignal;\n}): LoaderContext {\n const { params, query, signal } = options;\n\n return {\n params,\n query,\n signal: signal ?? createNeverAbortSignal(),\n // Use 0 as navId for SSR (single request, no navigation tracking)\n navId: 0,\n };\n}\n\n// =============================================================================\n// Single Loader Execution\n// =============================================================================\n\n/**\n * Execute a single loader with error handling\n */\nasync function executeSingleLoader(\n segment: SSRRouteSegment,\n contextOptions: {\n params: Record<string, string>;\n query: Record<string, string>;\n signal: AbortSignal;\n isTimeoutAbort: () => boolean;\n }\n): Promise<SSRLoaderResult> {\n const startTime = performance.now();\n\n // Create loader context\n const context = createSSRLoaderContext(contextOptions);\n\n try {\n // Execute loader (may be sync or async)\n const data = await Promise.resolve(segment.loader!(context));\n\n const timing = performance.now() - startTime;\n\n return {\n id: segment.id,\n success: true,\n data,\n timing,\n cacheHints: deriveCacheHints(segment.cacheOptions),\n };\n } catch (error) {\n const timing = performance.now() - startTime;\n\n return {\n id: segment.id,\n success: false,\n error: normalizeLoaderError(\n error,\n contextOptions.signal,\n contextOptions.isTimeoutAbort\n ),\n timing,\n cacheHints: { public: false, maxAge: 0, noStore: true },\n };\n }\n}\n\n/**\n * Create a result for an aborted loader\n */\nfunction createAbortedResult(id: string, isTimeout: boolean): SSRLoaderResult {\n return {\n id,\n success: false,\n error: {\n message: isTimeout\n ? 'Loader execution timeout'\n : 'Loader execution aborted',\n name: isTimeout ? 'TimeoutError' : 'AbortError',\n isTimeout,\n isAborted: true,\n },\n timing: 0,\n cacheHints: { public: false, maxAge: 0, noStore: true },\n };\n}\n\n// =============================================================================\n// Cache Hints\n// =============================================================================\n\n/**\n * Derive cache hints from loader cache options\n */\nfunction deriveCacheHints(options?: SSRLoaderCacheOptions): SSRCacheHints {\n if (!options) {\n // Default: private, cache for 5 minutes\n return {\n public: false,\n maxAge: 300,\n noStore: false,\n };\n }\n\n if (options.strategy === 'no-store') {\n return {\n public: false,\n maxAge: 0,\n noStore: true,\n };\n }\n\n return {\n public: options.public ?? false,\n maxAge: options.ttl ? Math.floor(options.ttl / 1000) : 300,\n swr: options.swr,\n noStore: false,\n };\n}\n\n/**\n * Aggregate cache hints from multiple loaders (most restrictive wins)\n *\n * Rules:\n * - public/private: Only public if ALL loaders explicitly allow public\n * - maxAge: Shortest wins\n * - swr: Shortest wins\n * - noStore: Any noStore makes result noStore\n */\nfunction aggregateCacheHints(results: SSRLoaderResult[]): SSRCacheHints {\n // Track if ALL loaders allow public caching (most restrictive wins)\n // Starts true, becomes false permanently if ANY loader is private\n let allAllowPublic = true;\n let maxAge = Infinity;\n let swr: number | undefined;\n let noStore = false;\n let hasAnyHints = false;\n\n for (const result of results) {\n const hints = result.cacheHints;\n if (!hints) continue;\n\n hasAnyHints = true;\n\n // no-store is most restrictive - short circuit\n if (hints.noStore) {\n noStore = true;\n continue;\n }\n\n // If ANY loader requires private, result must be private\n // (public only if ALL loaders allow it)\n if (!hints.public) {\n allAllowPublic = false;\n }\n\n // Shortest max-age wins\n if (hints.maxAge < maxAge) {\n maxAge = hints.maxAge;\n }\n\n // Shortest swr wins\n if (hints.swr !== undefined) {\n swr = swr === undefined ? hints.swr : Math.min(swr, hints.swr);\n }\n }\n\n // If no loaders had cache hints, use restrictive defaults\n if (!hasAnyHints || maxAge === Infinity) {\n maxAge = 300;\n }\n\n // Final public status: must have hints, all must allow public, and no noStore\n const isPublic = hasAnyHints && allAllowPublic && !noStore;\n\n return {\n public: isPublic,\n maxAge: noStore ? 0 : maxAge,\n swr: noStore ? undefined : swr,\n noStore,\n };\n}\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.loaders\",\"name\":\"generateCacheControlHeader\",\"stability\":\"stable\",\"signature\":\"(hints: SSRCacheHints) => string\"} */\n/**\n * Generate Cache-Control header value from cache hints\n *\n * @param hints - Aggregated cache hints\n * @returns Cache-Control header value\n *\n * @example\n * ```ts\n * const cacheControl = generateCacheControlHeader(result.cacheHints);\n * res.setHeader('Cache-Control', cacheControl);\n * ```\n */\nexport function generateCacheControlHeader(hints: SSRCacheHints): string {\n if (hints.noStore) {\n return 'no-store, no-cache, must-revalidate';\n }\n\n const directives: string[] = [];\n\n directives.push(hints.public ? 'public' : 'private');\n directives.push(`max-age=${hints.maxAge}`);\n\n if (hints.swr !== undefined) {\n directives.push(`stale-while-revalidate=${hints.swr}`);\n }\n\n return directives.join(', ');\n}\n\n// =============================================================================\n// Route Segment Extraction\n// =============================================================================\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.loaders\",\"name\":\"extractLoadersFromRouteTree\",\"stability\":\"stable\",\"signature\":\"(nodes: RouteNode[], matchedPath: string[]) => Promise<SSRRouteSegment[]>\"} */\n/**\n * Extract loader segments from matched route nodes\n *\n * Handles both nested route trees AND flat manifests (where all routes are\n * at the top level with full path patterns like `/dashboard/settings`).\n *\n * @param nodes - Route nodes (may be flat or nested)\n * @param matchedPath - Matched path segments (e.g., ['dashboard', 'settings'])\n * @returns Array of route segments with loaders (parent to child order)\n *\n * @example\n * ```ts\n * const segments = await extractLoadersFromRouteTree(routes, ['dashboard', 'settings']);\n * ```\n */\nexport async function extractLoadersFromRouteTree(\n nodes: RouteNode[],\n matchedPath: string[]\n): Promise<SSRRouteSegment[]> {\n const segments: SSRRouteSegment[] = [];\n\n // Build all URL prefixes from matched path segments\n // e.g., ['dashboard', 'settings'] → ['/', '/dashboard', '/dashboard/settings']\n const prefixes = buildUrlPrefixes(matchedPath);\n\n // Track which route IDs we've already processed to avoid duplicates\n const processedIds = new Set<string>();\n\n // Collect all route nodes (flatten if nested)\n const allNodes = collectAllNodes(nodes);\n\n // For each URL prefix, find matching routes and collect their loaders\n for (const prefix of prefixes) {\n const node = findMatchingNodeByPattern(allNodes, prefix);\n if (!node || processedIds.has(node.id)) continue;\n\n processedIds.add(node.id);\n\n // Load loader if present\n if (node.imports.loader) {\n try {\n const loaderModule = await node.imports.loader();\n const loaderExport = loaderModule.default ?? loaderModule.loader;\n const loader =\n typeof loaderExport === 'function'\n ? (loaderExport as LoaderFunction)\n : undefined;\n\n // Load config for cache options\n let cacheOptions: SSRLoaderCacheOptions | undefined;\n if (node.imports.config) {\n const configModule = await node.imports.config();\n const cache = configModule.cache;\n if (cache && typeof cache === 'object') {\n const { strategy, ttl } = cache as CacheOptions;\n cacheOptions = { strategy, ttl };\n }\n }\n\n segments.push({\n id: node.id,\n loader,\n cacheOptions,\n });\n } catch (error) {\n // Warn in development about failed loader imports\n if (isDev()) {\n console.warn(\n `[SSR] Failed to import loader for route \"${node.id}\":`,\n error instanceof Error ? error.message : error\n );\n }\n }\n }\n }\n\n return segments;\n}\n\n/**\n * Build URL prefixes from path segments\n * e.g., ['dashboard', 'settings'] → ['/', '/dashboard', '/dashboard/settings']\n */\nfunction buildUrlPrefixes(pathSegments: string[]): string[] {\n const prefixes: string[] = ['/'];\n\n let currentPath = '';\n for (const segment of pathSegments) {\n currentPath += '/' + segment;\n prefixes.push(currentPath);\n }\n\n return prefixes;\n}\n\n/**\n * Collect all route nodes (flattens nested tree structure)\n * This ensures we can match routes regardless of whether manifest is flat or nested\n */\nfunction collectAllNodes(nodes: RouteNode[]): RouteNode[] {\n const result: RouteNode[] = [];\n\n for (const node of nodes) {\n result.push(node);\n if (node.children.length > 0) {\n result.push(...collectAllNodes(node.children));\n }\n }\n\n return result;\n}\n\n/**\n * Find a matching node using pattern matching\n *\n * For SSR loader extraction, we prioritize exact pattern matches over catch-all\n * patterns. This ensures parent routes' loaders run even when a child catch-all\n * also matches the URL.\n *\n * Example: For URL prefix '/docs', we want to match pattern '/docs' exactly,\n * not '/docs/*' which would also match but is a child route.\n */\nfunction findMatchingNodeByPattern(\n nodes: RouteNode[],\n urlPath: string\n): RouteNode | undefined {\n // Build pattern-to-node map\n const nodeByPattern = new Map<string, RouteNode>();\n const patterns: string[] = [];\n\n for (const node of nodes) {\n patterns.push(node.pattern);\n nodeByPattern.set(node.pattern, node);\n }\n\n // First, check for an exact pattern match (highest priority for SSR loaders)\n // This ensures parent routes like '/docs' are matched before catch-all '/docs/*'\n if (nodeByPattern.has(urlPath)) {\n return nodeByPattern.get(urlPath);\n }\n\n // Fall back to findBestMatch for dynamic/catch-all patterns\n const match = findBestMatch(urlPath, patterns);\n if (!match) {\n return undefined;\n }\n\n return nodeByPattern.get(match.pattern);\n}\n\n// =============================================================================\n// Utilities\n// =============================================================================\n\n/**\n * Normalize an error into SSRLoaderError format\n */\nfunction normalizeLoaderError(\n error: unknown,\n signal: AbortSignal,\n isTimeoutAbort: () => boolean\n): SSRLoaderError {\n const isAborted = signal.aborted;\n const isTimeout = isTimeoutAbort();\n\n if (error instanceof Error) {\n return {\n message: error.message,\n name: error.name,\n stack: isDev() ? error.stack : undefined,\n isTimeout,\n isAborted,\n };\n }\n\n return {\n message: String(error),\n name: 'Error',\n isTimeout,\n isAborted,\n };\n}\n"]}
@@ -0,0 +1,102 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.ssr.server.render-route",
4
+ "title": "SSR Route Rendering Pipeline",
5
+ "category": "runtime"
6
+ }
7
+ */
8
+ /**
9
+ * @pithyjs/ssr - Full SSR Route Pipeline
10
+ *
11
+ * High-level `renderRoute()` function that orchestrates the complete SSR pipeline:
12
+ * URL → route match → loader execution → component render → HTML output.
13
+ *
14
+ * For manual orchestration, use `renderToString()` directly.
15
+ */
16
+ import type { Component } from '@pithyjs/core';
17
+ import { type RouteNode, type RouteMatch } from '@pithyjs/router';
18
+ import type { RenderResult, HeadState } from '../shared/types.js';
19
+ import { type ExecuteLoadersResult } from './loaders.js';
20
+ /**
21
+ * Options for renderRoute()
22
+ */
23
+ export interface RenderRouteOptions {
24
+ /** URL to render (e.g., '/dashboard?tab=settings') */
25
+ url: string;
26
+ /** The root component to render */
27
+ App: Component;
28
+ /** Route tree from the router manifest */
29
+ routes: RouteNode[];
30
+ /** Additional context to pass to components */
31
+ context?: Record<string, unknown>;
32
+ /** App container ID (default: 'app') */
33
+ appId?: string;
34
+ /** Initial head state */
35
+ head?: Partial<HeadState>;
36
+ /** Initial HTTP status code (default: 200; preserved when set, otherwise falls back to 404 if no route matches or 500 on loader error) */
37
+ status?: number;
38
+ /** Loader execution timeout in milliseconds (default: 30000) */
39
+ loaderTimeout?: number;
40
+ /** Whether to continue rendering after a loader error (default: false) */
41
+ continueOnError?: boolean;
42
+ /** Abort signal for cancellation */
43
+ signal?: AbortSignal;
44
+ }
45
+ /**
46
+ * Result from renderRoute(), extends RenderResult with route-specific data
47
+ */
48
+ export interface RenderRouteResult extends RenderResult {
49
+ /** The route match result with params and pattern (undefined if no route matched) */
50
+ routeMatch?: RouteMatch;
51
+ /** Loader execution result (undefined if no loaders ran) */
52
+ loaderResult?: ExecuteLoadersResult;
53
+ /** Generated Cache-Control header value from loader cache hints */
54
+ cacheControl?: string;
55
+ }
56
+ /** @codexApi {"parent":"pithy.ssr.server.render-route","name":"renderRoute","stability":"experimental","signature":"(options: RenderRouteOptions) => Promise<RenderRouteResult>"} */
57
+ /**
58
+ * Render a route to HTML with automatic route matching and loader execution.
59
+ *
60
+ * This is the high-level SSR entry point that handles the complete pipeline:
61
+ * 1. Parse URL into path and query
62
+ * 2. Match URL against route tree
63
+ * 3. Extract route parameters
64
+ * 4. Execute route loaders
65
+ * 5. Render the component with all data
66
+ * 6. Return HTML with cache hints
67
+ *
68
+ * For manual control over each step, use `renderToString()` directly.
69
+ *
70
+ * @param options - Route render options
71
+ * @returns Rendered HTML with route-specific metadata
72
+ *
73
+ * @example Basic usage
74
+ * ```ts
75
+ * const result = await renderRoute({
76
+ * url: '/dashboard',
77
+ * App,
78
+ * routes,
79
+ * });
80
+ *
81
+ * if (result.redirectTo) {
82
+ * res.redirect(result.status, result.redirectTo);
83
+ * } else {
84
+ * res.status(result.status).send(htmlShell({
85
+ * html: result.html,
86
+ * head: result.head,
87
+ * state: result.state,
88
+ * scripts: ['/entry-client.js'],
89
+ * }));
90
+ * }
91
+ * ```
92
+ *
93
+ * @example With cache headers
94
+ * ```ts
95
+ * const result = await renderRoute({ url: '/blog/123', App, routes });
96
+ * if (result.cacheControl) {
97
+ * res.setHeader('Cache-Control', result.cacheControl);
98
+ * }
99
+ * ```
100
+ */
101
+ export declare function renderRoute(options: RenderRouteOptions): Promise<RenderRouteResult>;
102
+ //# sourceMappingURL=render-route.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render-route.d.ts","sourceRoot":"","sources":["../../src/server/render-route.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAIL,KAAK,SAAS,EACd,KAAK,UAAU,EAChB,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAElE,OAAO,EAIL,KAAK,oBAAoB,EAC1B,MAAM,cAAc,CAAC;AAMtB;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,sDAAsD;IACtD,GAAG,EAAE,MAAM,CAAC;IACZ,mCAAmC;IACnC,GAAG,EAAE,SAAS,CAAC;IACf,0CAA0C;IAC1C,MAAM,EAAE,SAAS,EAAE,CAAC;IACpB,+CAA+C;IAC/C,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClC,wCAAwC;IACxC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,yBAAyB;IACzB,IAAI,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;IAC1B,0IAA0I;IAC1I,MAAM,CAAC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