@eserstack/laroux-server 0.0.0-stage → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/LICENSE +13 -0
  2. package/README.md +410 -2
  3. package/dist/adapters/react/error-chunk.d.ts +11 -0
  4. package/dist/adapters/react/error-chunk.js +12 -0
  5. package/dist/adapters/react/html-shell.d.ts +15 -0
  6. package/dist/adapters/react/html-shell.js +109 -0
  7. package/dist/adapters/react/inline-rsc-emitter.d.ts +62 -0
  8. package/dist/adapters/react/inline-rsc-emitter.js +120 -0
  9. package/dist/adapters/react/mod.d.ts +30 -0
  10. package/dist/adapters/react/mod.js +36 -0
  11. package/dist/adapters/react/render-app.d.ts +46 -0
  12. package/dist/adapters/react/render-app.js +44 -0
  13. package/dist/adapters/react/renderer.d.ts +15 -0
  14. package/dist/adapters/react/renderer.js +86 -0
  15. package/dist/adapters/react/rsc-flight-renderer.d.ts +64 -0
  16. package/dist/adapters/react/rsc-flight-renderer.js +623 -0
  17. package/dist/adapters/react/rsc-handler.d.ts +47 -0
  18. package/dist/adapters/react/rsc-handler.js +114 -0
  19. package/dist/adapters/react/script-json.d.ts +12 -0
  20. package/dist/adapters/react/script-json.js +18 -0
  21. package/dist/adapters/react/ssr-renderer.d.ts +63 -0
  22. package/dist/adapters/react/ssr-renderer.js +625 -0
  23. package/dist/bin-main.d.ts +1 -0
  24. package/dist/bin-main.js +18 -0
  25. package/dist/cli.d.ts +26 -0
  26. package/dist/cli.js +48 -0
  27. package/dist/commands/build.d.ts +78 -0
  28. package/dist/commands/build.js +221 -0
  29. package/dist/commands/dev.d.ts +50 -0
  30. package/dist/commands/dev.js +133 -0
  31. package/dist/commands/init.d.ts +29 -0
  32. package/dist/commands/init.js +228 -0
  33. package/dist/commands/serve.d.ts +47 -0
  34. package/dist/commands/serve.js +124 -0
  35. package/dist/config/load-config.d.ts +14 -0
  36. package/dist/config/load-config.js +67 -0
  37. package/dist/domain/action-registry.d.ts +83 -0
  38. package/dist/domain/action-registry.js +124 -0
  39. package/dist/domain/build-module.d.ts +30 -0
  40. package/dist/domain/build-module.js +50 -0
  41. package/dist/domain/hmr-manager.d.ts +51 -0
  42. package/dist/domain/hmr-manager.js +90 -0
  43. package/dist/domain/html-shell.d.ts +56 -0
  44. package/dist/domain/html-shell.js +15 -0
  45. package/dist/domain/middleware-dispatcher.d.ts +42 -0
  46. package/dist/domain/middleware-dispatcher.js +150 -0
  47. package/dist/domain/rebuild-handler.d.ts +52 -0
  48. package/dist/domain/rebuild-handler.js +52 -0
  49. package/dist/domain/renderer.d.ts +62 -0
  50. package/dist/domain/renderer.js +15 -0
  51. package/dist/domain/route-dispatcher.d.ts +40 -0
  52. package/dist/domain/route-dispatcher.js +134 -0
  53. package/dist/domain/server-modules.d.ts +65 -0
  54. package/dist/domain/server-modules.js +208 -0
  55. package/dist/main.d.ts +40 -0
  56. package/dist/main.js +256 -0
  57. package/dist/module.d.ts +24 -0
  58. package/dist/module.js +140 -0
  59. package/dist/options.d.ts +53 -0
  60. package/dist/options.js +14 -0
  61. package/dist/package.json +98 -0
  62. package/dist/proxy/types.d.ts +19 -0
  63. package/dist/proxy/types.js +3 -0
  64. package/dist/runtime/action-guard.d.ts +49 -0
  65. package/dist/runtime/action-guard.js +115 -0
  66. package/dist/runtime/html-shell.d.ts +66 -0
  67. package/dist/runtime/html-shell.js +246 -0
  68. package/dist/runtime/media-types.d.ts +13 -0
  69. package/dist/runtime/media-types.js +83 -0
  70. package/dist/runtime/path-containment.d.ts +11 -0
  71. package/dist/runtime/path-containment.js +27 -0
  72. package/dist/runtime/seo/generate-meta.d.ts +16 -0
  73. package/dist/runtime/seo/generate-meta.js +121 -0
  74. package/dist/runtime/seo/index.d.ts +5 -0
  75. package/dist/runtime/seo/index.js +5 -0
  76. package/dist/runtime/seo/types.d.ts +25 -0
  77. package/dist/runtime/seo/types.js +5 -0
  78. package/dist/runtime/server.d.ts +58 -0
  79. package/dist/runtime/server.js +699 -0
  80. package/package.json +81 -3
@@ -0,0 +1,623 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * React Flight Server - RSC Renderer
4
+ *
5
+ * This module implements the server-side RSC renderer that converts
6
+ * React component trees into the RSC wire format for streaming to clients.
7
+ *
8
+ * The RSC wire format is a newline-delimited sequence of chunks:
9
+ * - J chunks: JSON data (elements, props, primitives)
10
+ * - M chunks: Module references (client components)
11
+ * - E chunks: Errors from server rendering
12
+ *
13
+ * Each chunk is assigned an ID, and chunks can reference each other using
14
+ * the $ syntax (e.g., "$42" references chunk ID 42).
15
+ *
16
+ * @see https://github.com/facebook/react/tree/main/packages/react-server-dom-webpack
17
+ */
18
+ import * as errorChunk from "./error-chunk.js";
19
+ import * as protocol from "@eserstack/laroux-react/protocol";
20
+ import * as logging from "@eserstack/logging";
21
+ const flightLogger = logging.logger.getLogger([
22
+ "laroux-server",
23
+ "react",
24
+ "flight",
25
+ ]);
26
+ /**
27
+ * Add a chunk to the context and emit it to the stream
28
+ *
29
+ * Chunks are emitted as they're created for true streaming behavior.
30
+ * The emission is fire-and-forget (not awaited) since chunk creation
31
+ * is synchronous and doesn't need to wait for network I/O.
32
+ */
33
+ function addChunk(context, chunk) {
34
+ context.chunks.push(chunk);
35
+ context.emitChunk?.(chunk);
36
+ }
37
+ /**
38
+ * Encode a number for a J chunk: the values JSON turns into null or 0
39
+ * (NaN, the infinities and -0) get their tag.
40
+ */
41
+ function encodeNumber(value) {
42
+ const tags = protocol.RSC_VALUE_TAGS;
43
+ if (Number.isNaN(value))
44
+ return tags.nan;
45
+ if (value === Infinity)
46
+ return tags.infinity;
47
+ if (value === -Infinity)
48
+ return tags.negativeInfinity;
49
+ if (Object.is(value, -0))
50
+ return tags.negativeZero;
51
+ return value;
52
+ }
53
+ /**
54
+ * Encode a primitive child of a tree for a J chunk. Strings that start with
55
+ * "$" are escaped, and functions and symbols, which React does not render,
56
+ * become null.
57
+ */
58
+ function encodeChildPrimitive(value) {
59
+ switch (typeof value) {
60
+ case "string":
61
+ return protocol.escapeString(value);
62
+ case "number":
63
+ return encodeNumber(value);
64
+ case "bigint":
65
+ return `${protocol.RSC_VALUE_TAGS.bigint}${value}`;
66
+ case "function":
67
+ case "symbol":
68
+ return null;
69
+ default:
70
+ return value;
71
+ }
72
+ }
73
+ /**
74
+ * Emit the S chunk of a server action and return the reference to it.
75
+ */
76
+ function encodeServerReference(value, context) {
77
+ const actionChunkId = context.nextId++;
78
+ addChunk(context, {
79
+ type: "S",
80
+ id: actionChunkId,
81
+ value: { id: value.$$id, bound: value.$$bound },
82
+ });
83
+ return `$F${actionChunkId}`;
84
+ }
85
+ /**
86
+ * Encode a value for a J chunk the way laroux-react's
87
+ * createValueFromReadableStream decodes it.
88
+ *
89
+ * JSON values arrive the same and strings that start with "$" are escaped.
90
+ * Dates, BigInts, undefined and non-finite numbers get a tag, and Maps and
91
+ * Sets a chunk of their entries (protocol.RSC_VALUE_TAGS). React elements are
92
+ * rendered like a page tree and server actions become references. Other
93
+ * objects are encoded the way JSON.stringify encodes them: through their
94
+ * toJSON method when they have one, else their own enumerable properties.
95
+ *
96
+ * @param path Where the value sits, for the message of an unsupported value
97
+ * @param ancestors The objects that contain the value, to find a cycle
98
+ * @throws {TypeError} For a symbol, a promise, a function that is not a
99
+ * server action, or an object that contains itself, which the client cannot
100
+ * receive
101
+ */
102
+ async function encodeValue(value, context, path, ancestors) {
103
+ const tags = protocol.RSC_VALUE_TAGS;
104
+ switch (typeof value) {
105
+ case "undefined":
106
+ return tags.undefined;
107
+ case "boolean":
108
+ return value;
109
+ case "string":
110
+ return protocol.escapeString(value);
111
+ case "number":
112
+ return encodeNumber(value);
113
+ case "bigint":
114
+ return `${tags.bigint}${value}`;
115
+ case "symbol":
116
+ throw new TypeError(`encode RSC value: ${path} is a symbol, which cannot be sent to the client; send a string instead`);
117
+ case "function":
118
+ if (protocol.isServerReference(value)) {
119
+ return encodeServerReference(value, context);
120
+ }
121
+ throw new TypeError(`encode RSC value: ${path} is a function, which cannot be sent to the client; send data, or a server action from a "use server" file`);
122
+ }
123
+ if (value === null) {
124
+ return null;
125
+ }
126
+ // Every other type returned or threw above, so the value is an object.
127
+ const container = value;
128
+ if (ancestors.has(container)) {
129
+ throw new TypeError(`encode RSC value: ${path} contains itself, which cannot be sent to the client; send a copy without the cycle`);
130
+ }
131
+ const innerAncestors = new Set(ancestors).add(container);
132
+ if (Array.isArray(value)) {
133
+ return await Promise.all(value.map((item, index) => encodeValue(item, context, `${path}[${index}]`, innerAncestors)));
134
+ }
135
+ if (protocol.isReactElement(value) || protocol.isClientReference(value)) {
136
+ const elementId = await renderElement(value, context);
137
+ return `$${elementId}`;
138
+ }
139
+ if (value instanceof Date) {
140
+ const time = value.getTime();
141
+ return `${tags.date}${Number.isNaN(time) ? "Invalid Date" : value.toISOString()}`;
142
+ }
143
+ if (value instanceof Map) {
144
+ const id = context.nextId++;
145
+ const entries = await Promise.all([...value].map(([key, item], index) => Promise.all([
146
+ encodeValue(key, context, `${path}[map key ${index}]`, innerAncestors),
147
+ encodeValue(item, context, `${path}[map value ${index}]`, innerAncestors),
148
+ ])));
149
+ addChunk(context, { type: "J", id, value: entries });
150
+ return `${tags.map}${id}`;
151
+ }
152
+ if (value instanceof Set) {
153
+ const id = context.nextId++;
154
+ const items = await Promise.all([...value].map((item, index) => encodeValue(item, context, `${path}[set value ${index}]`, innerAncestors)));
155
+ addChunk(context, { type: "J", id, value: items });
156
+ return `${tags.set}${id}`;
157
+ }
158
+ const object = value;
159
+ if (typeof object.then === "function") {
160
+ throw new TypeError(`encode RSC value: ${path} is a promise, which cannot be sent to the client; await it before returning the value`);
161
+ }
162
+ if (typeof object.toJSON === "function") {
163
+ return await encodeValue(object.toJSON(), context, path, ancestors);
164
+ }
165
+ const entries = await Promise.all(Object.entries(object).map(async ([key, item]) => [
166
+ key,
167
+ await encodeValue(item, context, `${path}.${key}`, innerAncestors),
168
+ ]));
169
+ return Object.fromEntries(entries);
170
+ }
171
+ /**
172
+ * Render a React element tree to RSC chunks
173
+ *
174
+ * This is the core rendering function that recursively traverses the React tree
175
+ * and emits chunks for each node. It handles:
176
+ * - Primitives (null, strings, numbers, booleans)
177
+ * - Arrays
178
+ * - Client component references
179
+ * - Server components (function components)
180
+ * - Built-in elements (div, span, etc.)
181
+ * - React symbols (Suspense, Fragment, etc.)
182
+ * - Async components (Promises)
183
+ *
184
+ * @param element The React element or value to render
185
+ * @param context The render context with chunk buffer and config
186
+ * @returns Promise resolving to the chunk ID for this element
187
+ */
188
+ async function renderElement(element, context) {
189
+ // Null/undefined → JSON chunk with null
190
+ if (element === null || element === undefined) {
191
+ const id = context.nextId++;
192
+ addChunk(context, { type: "J", id, value: null });
193
+ return id;
194
+ }
195
+ // Primitives → JSON chunk with value
196
+ if (typeof element !== "object") {
197
+ const id = context.nextId++;
198
+ addChunk(context, { type: "J", id, value: encodeChildPrimitive(element) });
199
+ return id;
200
+ }
201
+ // Arrays → render each item, return array of references to their chunks
202
+ if (Array.isArray(element)) {
203
+ const id = context.nextId++;
204
+ const arrayPromises = element.map((item) => renderElement(item, context));
205
+ const arrayIds = await Promise.all(arrayPromises);
206
+ addChunk(context, {
207
+ type: "J",
208
+ id,
209
+ value: arrayIds.map((itemId) => `$${itemId}`),
210
+ });
211
+ return id;
212
+ }
213
+ // Client component references → module chunk
214
+ if (protocol.isClientReference(element)) {
215
+ const id = context.nextId++;
216
+ const moduleId = element.$$id;
217
+ const moduleRef = context.bundlerConfig[moduleId];
218
+ if (moduleRef) {
219
+ addChunk(context, { type: "M", id, value: moduleRef });
220
+ }
221
+ else {
222
+ // Fallback for missing bundler config entry
223
+ addChunk(context, {
224
+ type: "M",
225
+ id,
226
+ value: { id: moduleId, chunks: ["client"], name: "default" },
227
+ });
228
+ }
229
+ return id;
230
+ }
231
+ // React elements - the main case we're handling
232
+ // Check for both transitional (React 19 RSC) and standard element symbols
233
+ const isReactElement = element.$$typeof === Symbol.for("react.transitional.element") ||
234
+ element.$$typeof === Symbol.for("react.element");
235
+ if (isReactElement) {
236
+ const { type, props } = element;
237
+ // Client component (type is a client reference object)
238
+ if (type !== null &&
239
+ typeof type === "object" &&
240
+ protocol.isClientReference(type)) {
241
+ const moduleId = type.$$id;
242
+ const moduleRef = context.bundlerConfig[moduleId];
243
+ flightLogger.debug(`Client reference detected: ${moduleId}`);
244
+ flightLogger.debug(`Module ref found: ${!!moduleRef}`);
245
+ if (!moduleRef) {
246
+ flightLogger.debug(`Available keys: ${Object.keys(context.bundlerConfig).join(", ")}`);
247
+ }
248
+ if (moduleRef) {
249
+ const id = context.nextId++;
250
+ const moduleChunkId = context.nextId++;
251
+ const propsId = await renderProps(props, context);
252
+ // Emit module reference chunk
253
+ // Use the export name from the client reference, not from bundler config
254
+ const exportName = moduleRef.name ?? "default";
255
+ addChunk(context, {
256
+ type: "M",
257
+ id: moduleChunkId,
258
+ value: { ...moduleRef, name: exportName },
259
+ });
260
+ // Emit element chunk that references the module and props
261
+ addChunk(context, {
262
+ type: "J",
263
+ id,
264
+ value: {
265
+ $$typeof: "react.element",
266
+ type: `$M${moduleChunkId}`,
267
+ props: `$${propsId}`,
268
+ },
269
+ });
270
+ return id;
271
+ }
272
+ }
273
+ // ForwardRef component - unwrap and call render function
274
+ if (type !== null &&
275
+ typeof type === "object" &&
276
+ type.$$typeof === Symbol.for("react.forward_ref") &&
277
+ typeof type.render === "function") {
278
+ try {
279
+ const result = type.render(props, null);
280
+ return await renderElement(result, context);
281
+ }
282
+ catch (error) {
283
+ // Handled here: logged once, and the client receives the error chunk
284
+ // in place of the component.
285
+ const id = context.nextId++;
286
+ flightLogger
287
+ .with({ error })
288
+ .error("render RSC: a forwardRef component threw; sent an error chunk in its place");
289
+ addChunk(context, {
290
+ type: "E",
291
+ id,
292
+ value: errorChunk.toClientErrorValue(error),
293
+ });
294
+ return id;
295
+ }
296
+ }
297
+ // Memo component - unwrap and render inner type
298
+ if (type !== null &&
299
+ typeof type === "object" &&
300
+ type.$$typeof === Symbol.for("react.memo")) {
301
+ const innerType = type.type;
302
+ const innerElement = { ...element, type: innerType };
303
+ return await renderElement(innerElement, context);
304
+ }
305
+ // Server component (type is a function) - execute and render result
306
+ if (typeof type === "function") {
307
+ try {
308
+ const result = type(props);
309
+ // Async server component - handle Promise
310
+ if (result instanceof Promise) {
311
+ const id = context.nextId++;
312
+ // DON'T emit the chunk yet - just return the ID as a placeholder
313
+ // The chunk will be emitted when the Promise resolves
314
+ // This allows the parent tree to reference this ID before it's ready
315
+ // Track completion promise to ensure stream doesn't close early
316
+ const completionPromise = result
317
+ .then(async (resolved) => {
318
+ const resolvedId = await renderElement(resolved, context);
319
+ // NOW emit the chunk that resolves the forward reference
320
+ addChunk(context, { type: "J", id, value: `$${resolvedId}` });
321
+ // Remove from pending chunks after completion
322
+ context.pendingChunks.delete(id);
323
+ })
324
+ .catch((error) => {
325
+ flightLogger
326
+ .with({ error })
327
+ .error("render RSC: an async server component rejected; sent an error chunk in its place");
328
+ addChunk(context, {
329
+ type: "E",
330
+ id,
331
+ value: errorChunk.toClientErrorValue(error),
332
+ });
333
+ // Remove from pending chunks after error
334
+ context.pendingChunks.delete(id);
335
+ });
336
+ context.pendingChunks.set(id, completionPromise);
337
+ return id;
338
+ }
339
+ // Sync server component - render result directly
340
+ return await renderElement(result, context);
341
+ }
342
+ catch (error) {
343
+ // Handled here: logged once, and the client receives the error chunk
344
+ // in place of the component.
345
+ const id = context.nextId++;
346
+ flightLogger
347
+ .with({ error })
348
+ .error("render RSC: a server component threw; sent an error chunk in its place");
349
+ addChunk(context, {
350
+ type: "E",
351
+ id,
352
+ value: errorChunk.toClientErrorValue(error),
353
+ });
354
+ return id;
355
+ }
356
+ }
357
+ // Built-in HTML elements (div, span, etc.)
358
+ if (typeof type === "string") {
359
+ const id = context.nextId++;
360
+ const propsId = await renderProps(props, context);
361
+ addChunk(context, {
362
+ type: "J",
363
+ id,
364
+ value: {
365
+ $$typeof: "react.element",
366
+ type,
367
+ props: `$${propsId}`,
368
+ },
369
+ });
370
+ return id;
371
+ }
372
+ // React built-in symbols (Suspense, Fragment, etc.)
373
+ if (typeof type === "symbol") {
374
+ const id = context.nextId++;
375
+ const propsId = await renderProps(props, context);
376
+ // Serialize symbol as string - client will reconstruct it
377
+ const typeStr = type.toString(); // e.g., "Symbol(react.suspense)"
378
+ addChunk(context, {
379
+ type: "J",
380
+ id,
381
+ value: {
382
+ $$typeof: "react.element",
383
+ type: typeStr,
384
+ props: `$${propsId}`,
385
+ },
386
+ });
387
+ return id;
388
+ }
389
+ }
390
+ // Other objects keep JSON semantics, as client component props do
391
+ const id = context.nextId++;
392
+ let value;
393
+ try {
394
+ value = protocol.encodeJsonValue(element) ?? null;
395
+ }
396
+ catch (error) {
397
+ // Handled here: React cannot render the object either, so the child
398
+ // renders as nothing and the render goes on.
399
+ flightLogger
400
+ .with({ error })
401
+ .warn("render RSC: a child object cannot be encoded as JSON; rendering null in its place");
402
+ value = null;
403
+ }
404
+ addChunk(context, { type: "J", id, value });
405
+ return id;
406
+ }
407
+ /**
408
+ * Render props object
409
+ *
410
+ * Props are rendered as a separate chunk to allow sharing props between elements.
411
+ * Special handling for:
412
+ * - children: Rendered as separate chunks and referenced with $ syntax
413
+ * - functions: Skipped (can't be serialized, e.g., event handlers)
414
+ * - other values: Inlined directly (strings, numbers, objects, etc.)
415
+ *
416
+ * @param props The props object to render
417
+ * @param context The render context
418
+ * @returns Promise resolving to the chunk ID for the props
419
+ */
420
+ async function renderProps(props, context) {
421
+ if (!props || typeof props !== "object") {
422
+ const id = context.nextId++;
423
+ addChunk(context, { type: "J", id, value: props });
424
+ return id;
425
+ }
426
+ const id = context.nextId++;
427
+ const renderedProps = {};
428
+ // Props render one at a time: renderElement takes ids from the shared
429
+ // context counter, so prop order fixes the chunk ids and their emit order.
430
+ for (const [key, value] of Object.entries(props)) {
431
+ if (key === "children" || key === "fallback") {
432
+ // Children and fallback are React elements - render as chunks and reference them
433
+ if (Array.isArray(value)) {
434
+ // Sequential across props to keep chunk ids in prop order.
435
+ // oxlint-disable-next-line no-await-in-loop
436
+ const childIds = await Promise.all(value.map((child) => renderElement(child, context)));
437
+ renderedProps[key] = childIds.map((childId) => `$${childId}`);
438
+ }
439
+ else if (value !== null &&
440
+ typeof value === "object" &&
441
+ "$$typeof" in value) {
442
+ // It's a React element - render it, in prop order like above
443
+ // oxlint-disable-next-line no-await-in-loop
444
+ const childId = await renderElement(value, context);
445
+ renderedProps[key] = `$${childId}`;
446
+ }
447
+ else {
448
+ // Not a React element - inline it
449
+ renderedProps[key] = protocol.encodeJsonValue(value);
450
+ }
451
+ }
452
+ else if (protocol.isServerReference(value)) {
453
+ // Server action reference - emit S chunk with action ID
454
+ renderedProps[key] = encodeServerReference(value, context);
455
+ }
456
+ else if (typeof value === "function") {
457
+ // Skip regular functions - they can't be serialized
458
+ continue;
459
+ }
460
+ else {
461
+ // Inline other values with JSON semantics
462
+ renderedProps[key] = protocol.encodeJsonValue(value);
463
+ }
464
+ }
465
+ addChunk(context, { type: "J", id, value: renderedProps });
466
+ return id;
467
+ }
468
+ /**
469
+ * Create the RSC stream of one render: renderRoot adds chunk 0 and the chunks
470
+ * it references, and the stream closes once every async server component
471
+ * has resolved.
472
+ *
473
+ * Chunks are emitted as they're created for true streaming behavior, and
474
+ * rendering starts when the stream is first pulled.
475
+ */
476
+ function createRenderStream(bundlerConfig, renderRoot) {
477
+ const context = {
478
+ bundlerConfig,
479
+ nextId: 0,
480
+ chunks: [],
481
+ pendingChunks: new Map(),
482
+ };
483
+ let controller = null;
484
+ let streamClosed = false;
485
+ // Setup chunk emission before rendering starts
486
+ context.emitChunk = (chunk) => {
487
+ if (streamClosed || !controller)
488
+ return;
489
+ const line = protocol.serializeChunk(chunk);
490
+ try {
491
+ const bytes = new TextEncoder().encode(line);
492
+ controller.enqueue(bytes);
493
+ }
494
+ catch (error) {
495
+ if (!streamClosed) {
496
+ flightLogger
497
+ .with({ error })
498
+ .error(`emit RSC chunk ${chunk.id}; closing the stream`);
499
+ streamClosed = true;
500
+ }
501
+ }
502
+ };
503
+ // Rendering logic - starts when stream is first pulled
504
+ let renderingStarted = false;
505
+ const startRendering = () => {
506
+ if (renderingStarted)
507
+ return;
508
+ renderingStarted = true;
509
+ flightLogger.debug("Starting RSC render...");
510
+ // Every failure is handled inside, so this promise never rejects.
511
+ (async () => {
512
+ try {
513
+ await renderRoot(context);
514
+ flightLogger.debug(`Root rendered, pending async: ${context.pendingChunks.size}`);
515
+ // Wait for all async components (Suspense boundaries)
516
+ // Use a loop to handle nested async components - when one resolves,
517
+ // it might create more pending chunks that also need to be awaited
518
+ while (context.pendingChunks.size > 0) {
519
+ flightLogger.debug(`Waiting for ${context.pendingChunks.size} async component(s)...`);
520
+ // Each round waits for every pending chunk at once; the loop only
521
+ // repeats for chunks registered while the previous round resolved.
522
+ // oxlint-disable-next-line no-await-in-loop
523
+ await Promise.all(context.pendingChunks.values());
524
+ }
525
+ flightLogger.debug("All async components resolved");
526
+ flightLogger.debug(`All done. Closing stream. Total: ${context.chunks.length} chunks`);
527
+ // Close stream when all chunks are emitted
528
+ if (!streamClosed && controller) {
529
+ streamClosed = true;
530
+ controller.close();
531
+ }
532
+ }
533
+ catch (error) {
534
+ flightLogger
535
+ .with({ error })
536
+ .error("render RSC stream; erroring the stream");
537
+ if (!streamClosed && controller) {
538
+ streamClosed = true;
539
+ controller.error(error);
540
+ }
541
+ }
542
+ })();
543
+ };
544
+ // Create ReadableStream that starts rendering on first pull
545
+ return new ReadableStream({
546
+ start(ctrl) {
547
+ controller = ctrl;
548
+ },
549
+ pull() {
550
+ // Lazy rendering - starts when client begins reading
551
+ startRendering();
552
+ },
553
+ cancel() {
554
+ streamClosed = true;
555
+ },
556
+ });
557
+ }
558
+ /**
559
+ * Render a React tree to RSC wire format stream
560
+ *
561
+ * This is the main server-side entry point. It:
562
+ * 1. Creates a ReadableStream for the RSC wire format
563
+ * 2. Starts rendering the React tree (which emits chunks)
564
+ * 3. Waits for all async components to complete
565
+ * 4. Closes the stream when everything is done
566
+ *
567
+ * Chunks are emitted as they're created for true streaming behavior.
568
+ * The stream stays open until all async components (Suspense boundaries) resolve.
569
+ *
570
+ * @param element The root React element (or primitive value, array, etc.) to render
571
+ * @param bundlerConfig Mapping of client component IDs to module references
572
+ * @returns ReadableStream of RSC wire format (newline-delimited chunks)
573
+ */
574
+ export function renderToReadableStream(
575
+ // Any value a server component tree can hold; the walk narrows it per node.
576
+ // oxlint-disable-next-line typescript/no-explicit-any
577
+ element, bundlerConfig) {
578
+ return createRenderStream(bundlerConfig, async (context) => {
579
+ // The root takes the first id, so it is chunk 0
580
+ const rootId = await renderElement(element, context);
581
+ flightLogger.debug(`Root chunk ID: ${rootId}`);
582
+ });
583
+ }
584
+ /**
585
+ * Render a value to the RSC wire format, as laroux-server sends a server
586
+ * action's result.
587
+ *
588
+ * Chunk 0 holds the value. Unlike client component props, which keep JSON
589
+ * semantics, it is encoded so that Dates, Maps, Sets, BigInts, `undefined`
590
+ * and non-finite numbers arrive as themselves; the React elements in it
591
+ * render like a page tree, and server actions arrive callable.
592
+ * createValueFromReadableStream in `@eserstack/laroux-react/client` decodes
593
+ * it.
594
+ *
595
+ * A value the client cannot receive (a symbol, a promise, a function that is
596
+ * not a server action, or an object that contains itself) is logged, and
597
+ * chunk 0 becomes an error chunk whose message names where it sits.
598
+ *
599
+ * @param value The value to send
600
+ * @param bundlerConfig Mapping of client component IDs to module references
601
+ * @returns ReadableStream of RSC wire format (newline-delimited chunks)
602
+ */
603
+ export function renderValueToReadableStream(value, bundlerConfig) {
604
+ return createRenderStream(bundlerConfig, async (context) => {
605
+ const rootId = context.nextId++;
606
+ try {
607
+ const model = await encodeValue(value, context, "value", new Set());
608
+ addChunk(context, { type: "J", id: rootId, value: model });
609
+ }
610
+ catch (error) {
611
+ // Handled here: logged once, and the client receives the message as
612
+ // the error of chunk 0.
613
+ await flightLogger
614
+ .with({ error })
615
+ .error("encode RSC value: the value cannot be sent to the client; sent an error chunk");
616
+ addChunk(context, {
617
+ type: "E",
618
+ id: rootId,
619
+ value: errorChunk.toClientErrorValue(error),
620
+ });
621
+ }
622
+ });
623
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * RSC Renderer with Streaming
3
+ * Renders React Server Components to the RSC wire protocol format
4
+ */
5
+ import type { BundlerConfig } from "./rsc-flight-renderer.ts";
6
+ import type { AppConfig } from "@eserstack/laroux/config";
7
+ export type { BundlerConfig };
8
+ /**
9
+ * Load the module map generated during build
10
+ * @param config - Application configuration
11
+ * @returns Bundler configuration with component mappings
12
+ */
13
+ export declare function loadModuleMap(config: AppConfig): Promise<BundlerConfig>;
14
+ /**
15
+ * Render a React Server Component tree to RSC wire format stream
16
+ *
17
+ * This implements the React Server Components protocol:
18
+ * - Server components render on the server and stream as JSON
19
+ * - Client components are sent as references (not code)
20
+ * - Uses RSC wire format: J0: (JSON), M1: (Module reference), etc.
21
+ * - Supports progressive rendering with Suspense
22
+ *
23
+ * @param config - Application configuration
24
+ * @param component - Root React element to render
25
+ * @param moduleMap - Optional pre-loaded module map (for current mode)
26
+ * @returns ReadableStream of RSC wire format chunks
27
+ */
28
+ export declare function renderRSC(config: AppConfig, component: React.ReactElement, moduleMap?: BundlerConfig): Promise<ReadableStream>;
29
+ /**
30
+ * Convert RSC stream to HTTP Response with proper headers
31
+ *
32
+ * The response carries no CORS headers: the laroux client fetches `/rsc` from
33
+ * its own origin. A deployment that serves the payload to another origin adds
34
+ * an allowlist for that origin itself.
35
+ *
36
+ * @param stream - RSC wire format stream
37
+ * @returns HTTP Response ready to send to client
38
+ */
39
+ export declare function streamToResponse(stream: ReadableStream): Response;
40
+ /**
41
+ * Render RSC and return as HTTP Response (convenience method)
42
+ * @param config - Application configuration
43
+ * @param component - Root React element to render
44
+ * @param moduleMap - Optional pre-loaded module map (for current mode)
45
+ * @returns HTTP Response with RSC stream
46
+ */
47
+ export declare function renderRSCResponse(config: AppConfig, component: React.ReactElement, moduleMap?: BundlerConfig): Promise<Response>;