@eserstack/laroux-server 0.0.0-bootstrap.0 → 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 +411 -0
  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 +84 -1
package/LICENSE ADDED
@@ -0,0 +1,13 @@
1
+ Copyright 2023-present Eser Ozvataf and other contributors.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,411 @@
1
+ # 🛰️ [@eserstack/laroux-server](./)
2
+
3
+ > **Note:** JSR is frozen at 4.5.x. From 5.0.0, `@eserstack/laroux-server` is
4
+ > published on npm under the same name, and the `laroux` command as the npm
5
+ > package `laroux`, which an app lists as a dev dependency
6
+ > (`npm install --save-dev laroux`); the JSR versions stay available but get no
7
+ > updates.
8
+
9
+ > **eserstack Product-Candidate** — SSR runtime for laroux ·
10
+ > [eser/stack](https://github.com/eser/stack) **Install:**
11
+ > `pnpm add @eserstack/laroux-server`
12
+
13
+ Core runtime and utilities for [laroux.js](https://github.com/eser/stack) - A
14
+ React Server Components framework for Node.js. The server renders pages and RSC
15
+ payloads, serves static assets, runs API routes, proxies and server actions, and
16
+ ships the `laroux` CLI that creates, develops, builds and serves an app.
17
+
18
+ ## Overview
19
+
20
+ This package contains the core runtime logic and utilities for laroux.js,
21
+ including:
22
+
23
+ - **HTTP Server** - Request handling, routing, and static file serving
24
+ - **RSC Handler** - React Server Components rendering and streaming
25
+ - **SSR Renderer** - HTML rendering with the RSC payload embedded for hydration
26
+ - **Server Actions** - Server-side function invocation from client components
27
+ - **API Routes and Proxies** - File-based `route.ts` handlers and `proxy.ts`
28
+ middleware
29
+ - **HTML Shell** - Initial HTML document generation
30
+ - **Configuration System** - Type-safe config loading that merges the defaults,
31
+ `laroux.config.ts` and the options passed to `startServer`
32
+ - **CLI** - `laroux init`, `dev`, `build` and `serve`, standalone or mounted as
33
+ `eser laroux`
34
+
35
+ ## 🚀 Quick Start
36
+
37
+ The `laroux` bin comes from the npm package `laroux`, whose one dependency is
38
+ this package at the same version. The CLI creates a project, and the project's
39
+ own scripts start the development server once its dependencies are installed:
40
+
41
+ ```bash
42
+ npx laroux init my-app
43
+ cd my-app
44
+ npm install
45
+ npm run dev
46
+ ```
47
+
48
+ An app imports the `@eserstack` packages and lists `laroux` as a dev
49
+ dependency, so the bin runs the app's own copy of this package and of React:
50
+
51
+ ```bash
52
+ npm install @eserstack/laroux @eserstack/laroux-react react react-dom
53
+ npm install --save-dev laroux
54
+ ```
55
+
56
+ Its scripts call the bin, and the app needs no `laroux.config.ts` to run them:
57
+
58
+ ```json
59
+ {
60
+ "scripts": {
61
+ "dev": "laroux dev",
62
+ "build": "laroux build",
63
+ "serve": "laroux serve"
64
+ }
65
+ }
66
+ ```
67
+
68
+ The same commands run as `eser laroux <command>` through `@eserstack/cli`.
69
+
70
+ To start the server from code, pass the renderer and HTML shell of a framework
71
+ adapter. Without a bundler plugin, `startServer` serves the build already in
72
+ `dist/`:
73
+
74
+ ```typescript
75
+ import * as larouxServer from "@eserstack/laroux-server";
76
+ import * as reactAdapter from "@eserstack/laroux-server/adapters/react";
77
+
78
+ await larouxServer.startServer({
79
+ mode: "serve",
80
+ port: 8000,
81
+ renderer: reactAdapter.reactRenderer,
82
+ htmlShell: reactAdapter.reactHtmlShellBuilder,
83
+ });
84
+ ```
85
+
86
+ ## 🛠 API Reference
87
+
88
+ ### Starting the Server
89
+
90
+ `startServer(options)` loads the configuration, builds the app when a bundler
91
+ plugin is given, and starts the HTTP server. The build uses only the bundler
92
+ adapters you pass. This is what `laroux dev` runs:
93
+
94
+ ```typescript
95
+ import * as larouxServer from "@eserstack/laroux-server";
96
+ import * as reactAdapter from "@eserstack/laroux-server/adapters/react";
97
+ import * as fonts from "@eserstack/laroux-bundler/adapters/fonts";
98
+ import * as lightningcss from "@eserstack/laroux-bundler/adapters/lightningcss";
99
+ import * as reactBundler from "@eserstack/laroux-bundler/adapters/react";
100
+ import * as sharp from "@eserstack/laroux-bundler/adapters/sharp";
101
+ import * as tailwind from "@eserstack/laroux-bundler/adapters/tailwindcss";
102
+
103
+ await larouxServer.startServer({
104
+ mode: "dev",
105
+ port: 8000,
106
+ renderer: reactAdapter.reactRenderer,
107
+ htmlShell: reactAdapter.reactHtmlShellBuilder,
108
+ frameworkPlugin: reactBundler.reactPlugin,
109
+ cssPlugin: tailwind.createTailwindPlugin({
110
+ globalCssPath: "src/app/styles/global.css",
111
+ }),
112
+ cssProcessor: lightningcss.lightningCssProcessor,
113
+ fontOptimizer: fonts.googleFontOptimizer,
114
+ imageOptimizer: sharp.sharpImageOptimizer,
115
+ });
116
+ ```
117
+
118
+ | Option | Type | Description |
119
+ | ----------------- | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
120
+ | `mode` | `"dev"` \| `"serve"` | `dev` builds on each start, watches and enables HMR; `serve` builds only a missing or stale build |
121
+ | `port` | `number` | Overrides `server.port` from the configuration (default `8000`) |
122
+ | `hmr` | `boolean` | Hot module replacement in dev mode (default `true` in dev) |
123
+ | `open` | `boolean` | Opens the browser after the server starts |
124
+ | `projectRoot` | `string` | Directory holding `laroux.config.ts` (default: the working directory) |
125
+ | `logLevel` | `LogLevel` | `trace`, `debug`, `info`, `warn`, `error` or `fatal` (default `info`) |
126
+ | `renderer` | `Renderer` | Framework renderer adapter; without one, pages render empty |
127
+ | `htmlShell` | `HtmlShellBuilder` | HTML shell adapter; without one, the shell is empty |
128
+ | `frameworkPlugin` | `FrameworkPlugin` | Bundler plugin from `@eserstack/laroux-bundler`; without it nothing is built |
129
+ | `cssPlugin` | `CssPlugin` | CSS plugin from `@eserstack/laroux-bundler`, such as `createTailwindPlugin(...)` |
130
+ | `cssProcessor` | `CssProcessor` | Stylesheet processor, such as `lightningCssProcessor`, for a stylesheet the CSS plugin does not compile; without it that stylesheet is written unchanged |
131
+ | `fontOptimizer` | `FontOptimizer` | Font optimizer, such as `googleFontOptimizer`; without it no fonts are self-hosted |
132
+ | `imageOptimizer` | `ImageOptimizer` | Image optimizer, such as `sharpImageOptimizer`; without it images are served as they are |
133
+
134
+ In `serve` mode, the build is stale when `dist/client/manifest.json` is missing
135
+ or a file under the source directory or `public/`, or the project's
136
+ `laroux.config.ts` or `package.json`, changed after
137
+ the last build.
138
+
139
+ When the build that `startServer` runs fails, it throws `BuildFailedError` and
140
+ does not start the server, so the app never runs on a stale or empty `dist/`.
141
+ The bundler has already logged the failing step and its error. `laroux dev`,
142
+ `laroux serve` and `laroux build` report the failure and exit with code 1.
143
+
144
+ In `dev` mode, a change under the source directory rebuilds the app. After a
145
+ rebuild that succeeds, the server loads the rebuilt pages, layout, `route.ts`
146
+ handlers, `proxy.ts` modules and server actions, then sends the HMR clients an
147
+ update, so the change is served without a restart. The runtime keeps an
148
+ imported module under its URL until the process exits, so the server imports
149
+ these modules by URLs that end in `?v=` and the build id: each rebuild loads
150
+ fresh, and within one build each module loads once. Serve mode imports them the
151
+ same way, with a build id that never changes. Pages and layouts are bundled with
152
+ the modules they import, but `route.ts` and `proxy.ts` load from `src/`, and the
153
+ modules they import keep the code they had when first loaded; restart the dev
154
+ server after changing one of those. A change to CSS files alone rebuilds the
155
+ stylesheets, CSS module styles included, and keeps the build id, so the loaded
156
+ modules stay as they are.
157
+
158
+ After a rebuild that fails, the server logs the failure and sends the clients an
159
+ error message without detail instead of an update; the error itself is in the
160
+ server log. When a rebuild succeeds but its pages or layout fail to load, such
161
+ as a page that throws on import, the server logs that error, keeps the pages of
162
+ the build it loaded before, and sends the clients the same kind of error
163
+ message.
164
+
165
+ The root entry point also exports the port types these options take (`Renderer`,
166
+ `HtmlShellBuilder`, `FrameworkPlugin`, `CssPlugin`, `CssProcessor`,
167
+ `FontOptimizer`, `ImageOptimizer` and the types they use), so you can type an
168
+ adapter of your own without importing the bundler.
169
+
170
+ ### React Adapter
171
+
172
+ `@eserstack/laroux-server/adapters/react` implements the renderer and HTML shell
173
+ ports for React.
174
+
175
+ | Export | Description |
176
+ | ---------------------------------------------------------- | --------------------------------------------------- |
177
+ | `reactRenderer`, `createReactRenderer()` | Renderer port for React pages and RSC payloads |
178
+ | `reactHtmlShellBuilder`, `createReactHtmlShellBuilder()` | HTML shell port for React apps |
179
+ | `renderToReadableStream()` | Low-level RSC Flight renderer |
180
+ | `renderValueToReadableStream()` | RSC encoding of a value, such as an action result |
181
+ | `renderRSC()`, `renderRSCResponse()`, `streamToResponse()` | RSC handler for the HTTP layer |
182
+ | `renderSSR()`, `generateRSCPayloadScript()` | Server-side rendering with the RSC payload embedded |
183
+ | `createInlineRSCStream()`, `chunkToInlineScript()` | Inline RSC chunks for streaming responses |
184
+ | `renderApp()` | Composes the layout and page with the request data |
185
+
186
+ When a page fails to render as a whole, `renderSSR()` returns a fallback with a
187
+ fixed message and a correlation id instead of the error's message, which can
188
+ carry request data and internal detail. The error is logged on the server with
189
+ the same `correlationId`, so a visitor's report leads to the log entry.
190
+
191
+ ### Request Data in Pages
192
+
193
+ The server passes each page `params`, `pathname` and `request`, and the layout
194
+ `children` and `request`. `request` is a `PageRequest` from `@eserstack/laroux`
195
+ with the decoded `cookies` (a `ReadonlyMap`), `host` (the Host header) and
196
+ `locale` (the page URL's `locale` parameter), each of the last two `null` when
197
+ the request has none. It is built for each render and never kept in module
198
+ scope, so concurrent requests cannot read each other's cookies:
199
+
200
+ ```tsx
201
+ // src/app/routes/account/page.tsx
202
+ import type * as laroux from "@eserstack/laroux";
203
+
204
+ export function AccountPage(props: laroux.PageProps) {
205
+ const name = props.request.cookies.get("display_name");
206
+
207
+ return (
208
+ <p>
209
+ {name === undefined ? "Welcome" : `Welcome back, ${name}`} on{" "}
210
+ {props.request.host ?? "this site"}
211
+ </p>
212
+ );
213
+ }
214
+ ```
215
+
216
+ `request` reaches server components only; a page or layout that is a client
217
+ component does not get it. Pass a client component the values it renders, never
218
+ `request` or a cookie, since its props are sent to the browser.
219
+
220
+ `params` holds the route's parameters percent-decoded, in pages and in
221
+ `route.ts` handlers alike: `/stories/hello%20world` gives a
222
+ `stories/[slug]/page.tsx` page `{ slug: "hello world" }`. A catch-all such as
223
+ `docs/[...path]` also matches its bare prefix, `/docs` or `/docs/`, with
224
+ `path: []`. A decoded parameter can hold `/` or `..`, so validate it before it
225
+ goes into a file path or a query.
226
+
227
+ ### Server Actions
228
+
229
+ Client components call server actions through stubs that `POST` to `/_rsc` with
230
+ an `RSC-Action` header. The arguments arrive as a JSON array or as one
231
+ `FormData`; any other body gets a 400. The server encodes the result with
232
+ `renderValueToReadableStream()`, so Dates, Maps, Sets, BigInts, `undefined`,
233
+ React elements and server action references reach the client as themselves. A
234
+ symbol, a promise, a plain function or an object that contains itself cannot be
235
+ sent: the call rejects with an error that names where it sits, such as
236
+ `value.user.onSave`. An action that throws answers 500 with
237
+ `{ "error": "Server action failed" }`, and the error is logged with the action
238
+ id.
239
+
240
+ The endpoint calls only real server actions:
241
+
242
+ - The module of the action id must be listed in
243
+ `dist/server/actions-manifest.json`, which the build writes for every file
244
+ with a `"use server"` directive. Any other module is never imported.
245
+ - The export must carry the React server reference marker that the build adds to
246
+ each export of those files. Other exports, such as helpers, get a 404 and do
247
+ not run.
248
+ - A body over 1 MiB (`ACTION_MAX_BODY_BYTES`) gets a 413 before it is parsed,
249
+ whether the size comes from `Content-Length` or from the bytes read.
250
+ - A request with `Sec-Fetch-Site` other than `same-origin` or `none`, or with an
251
+ `Origin` other than the request's own, gets a 403. A request with neither
252
+ header comes from a client that is not a browser and passes.
253
+
254
+ Route-scoped proxies do not cover `POST /_rsc` yet: an action request carries no
255
+ page path, so only the root `proxy.ts` chain runs for it. Check authorization
256
+ inside each action until laroux R1 binds actions to routes (backlog doc-3,
257
+ section 7.4). `GET /rsc?pathname=<path>` runs the full proxy chain of `<path>`,
258
+ as the document request for that page does.
259
+
260
+ ### Configuration System
261
+
262
+ Type-safe configuration loading with 3-layer merging (defaults → user config →
263
+ `startServer` options). `loadConfig(projectRoot?)` reads `laroux.config.ts` from
264
+ the project root (the working directory by default) and deep-merges it over the
265
+ defaults from `@eserstack/laroux`:
266
+
267
+ ```typescript
268
+ import * as larouxConfig from "@eserstack/laroux-server/config";
269
+
270
+ const config = await larouxConfig.loadConfig("./my-app");
271
+
272
+ console.log(config.server.port); // 8000 unless laroux.config.ts sets it
273
+ ```
274
+
275
+ **Example `laroux.config.ts`:**
276
+
277
+ ```typescript
278
+ import type { UserConfig } from "@eserstack/laroux";
279
+
280
+ export default {
281
+ srcDir: "src",
282
+ distDir: "dist",
283
+ publicDir: "public",
284
+ logLevel: "info",
285
+ server: {
286
+ port: 3000,
287
+ hmr: true,
288
+ },
289
+ } satisfies UserConfig;
290
+ ```
291
+
292
+ See `UserConfig` in `@eserstack/laroux` for the full schema.
293
+
294
+ ### CLI
295
+
296
+ | Command | Flags |
297
+ | ---------------------- | --------------------------------------------------------------------------- |
298
+ | `laroux init [folder]` | `--template` (minimal), `--registry`, `--force`, `--no-git`, `--no-install` |
299
+ | `laroux dev` | `--port`, `--no-hmr`, `--log-level`, `--open` |
300
+ | `laroux build` | `--out-dir`, `--clean`, `--no-minify`, `--analyze`, `--log-level` |
301
+ | `laroux serve` | `--port`, `--log-level` |
302
+
303
+ Every command prints its usage and flags with `--help` (or `-h`) and does
304
+ nothing else.
305
+
306
+ `init` creates the project in `my-laroux-app` when no folder is given. It
307
+ scaffolds a kit recipe, the same one `eser kit new laroux-app` creates: the
308
+ `minimal` template is the `laroux-app` recipe of eser/stack's
309
+ `.eser/recipes.json` on GitHub, which kit reads by default. `--registry` takes
310
+ another `recipes.json` by path or URL, such as a fork's or a local checkout's.
311
+ `init` does not install dependencies; `--no-git` and `--no-install` skip the
312
+ recipe's post-install commands, and `laroux-app` has none. It stops at a folder
313
+ that is not empty unless you pass `--force`, and when scaffolding fails it
314
+ removes the folder it created. The `./module` export holds the same command
315
+ tree for the `eser` CLI to mount.
316
+
317
+ ### Server Action Registry (deprecated)
318
+
319
+ `@eserstack/laroux-server/action-registry` keeps the old manual registry
320
+ (`registerAction`, `invokeAction`, `getRegisteredActions`, `clearActions`). New
321
+ code marks its action modules with `"use server"` instead, and the bundler wires
322
+ them up. `invokeAction` does not log failures; it rejects with a
323
+ `ServerActionError` whose `actionId` names the action and whose `cause` is the
324
+ error the action threw, so the caller logs it once.
325
+
326
+ ## Upgrading from 4.x
327
+
328
+ These changes since 4.5.2 need a change in code, commands or files that use this
329
+ package. The [changelog](https://github.com/eser/stack/blob/main/CHANGELOG.md)
330
+ lists the changes in every package.
331
+
332
+ - `startServer` throws `BuildFailedError` when its pre-serve build fails, and
333
+ `laroux build`, `dev` and `serve` exit with code 1; they used to serve a stale
334
+ or empty `dist/`. Fix the build, or catch the error where you must keep
335
+ running:
336
+
337
+ ```typescript
338
+ import * as larouxServer from "@eserstack/laroux-server";
339
+
340
+ try {
341
+ await larouxServer.startServer(options);
342
+ } catch (error) {
343
+ if (!(error instanceof larouxServer.BuildFailedError)) throw error;
344
+ // After: decide here what a failed build means for your process
345
+ }
346
+ ```
347
+
348
+ - `startServer` loads the generated routes file, the root layout, the API route
349
+ and proxy registries and the actions manifest before it serves. A module among
350
+ them that fails to load, or a missing root layout, stops startup with that
351
+ error; requests used to fail later. In dev, the same failure after a rebuild
352
+ keeps the previous pages and sends HMR clients an error. Fix the reported
353
+ module, or add `src/app/layout.tsx`.
354
+ - `ServerOptions` takes `cssProcessor`, `fontOptimizer` and `imageOptimizer`,
355
+ and the build no longer runs Lightning CSS, Google Fonts self-hosting or sharp
356
+ unless you pass them. The `laroux` CLI passes them; a programmatic caller adds
357
+ them as in the `startServer` example:
358
+ `cssProcessor: lightningcss.lightningCssProcessor`,
359
+ `fontOptimizer: fonts.googleFontOptimizer`,
360
+ `imageOptimizer: sharp.sharpImageOptimizer`.
361
+ - Page and `route.ts` params arrive percent-decoded, and API routes use the page
362
+ matcher, so a catch-all also matches its prefix (`/docs` and `/api/docs/`).
363
+ Remove `decodeURIComponent` on params, and validate a param before it reaches
364
+ a file path or a query:
365
+
366
+ ```typescript
367
+ // Before
368
+ const slug = decodeURIComponent(ctx.params.slug as string);
369
+ // After
370
+ const slug = ctx.params.slug as string;
371
+ ```
372
+
373
+ - `renderApp` is typed as
374
+ `renderApp(Layout: ComponentType<LayoutProps<ReactNode>>, Page: ComponentType<PageProps>, props?)`,
375
+ and server-component pages and layouts receive `request`. Type them with
376
+ `laroux.PageProps` and `laroux.LayoutProps<React.ReactNode>`.
377
+ - Server action calls answer with an RSC stream (`text/x-component`) instead of
378
+ JSON (see the laroux-react README), and the RSC-Action 404 body is
379
+ `{"error":"Action not found"}` without the id.
380
+ - `streamToResponse()` and `renderRSCResponse()` no longer send
381
+ `Access-Control-Allow-Origin: *` or the other CORS headers. Same-origin
382
+ clients need nothing. A deployment that serves the RSC payload to another
383
+ origin adds CORS for that origin, for example with
384
+ `http.middlewares.cors.cors({ origin: ["https://app.example.com"] })`.
385
+ - `invokeAction()` (`./action-registry`, deprecated) rejects with
386
+ `ServerActionError` for an unknown id and for a throwing action, and no longer
387
+ logs. Match `instanceof ServerActionError`, read `error.cause` for the
388
+ action's own error and `error.actionId` for the action, and log in the caller.
389
+ - `laroux init` scaffolds the `laroux-app` kit recipe instead of cloning
390
+ `gh:eser/laroux-template-{minimal,blog,dashboard,docs}`, and none of those
391
+ repositories exists. `--template` accepts `minimal` only; `blog`, `dashboard`
392
+ and `docs` had no source and fail with the list of available templates. Use
393
+ `minimal`, or drop `--template`. `init` stops at a folder that is not empty;
394
+ pass `--force` to write over it.
395
+
396
+ ## License
397
+
398
+ Apache-2.0 © [Eser Ozvataf](https://github.com/eser)
399
+
400
+ ## 🔗 Links
401
+
402
+ - [@eserstack/cli](https://www.npmjs.com/package/@eserstack/cli) -
403
+ Main CLI tool (`eser laroux` commands)
404
+ - [@eserstack/laroux-bundler](https://www.npmjs.com/package/@eserstack/laroux-bundler) -
405
+ Build system and HMR
406
+ - [@eserstack/laroux](https://www.npmjs.com/package/@eserstack/laroux) -
407
+ Framework-agnostic core: router, configuration types and defaults
408
+ - [@eserstack/laroux-react](https://www.npmjs.com/package/@eserstack/laroux-react) -
409
+ React integration for laroux
410
+ - [npm package](https://www.npmjs.com/package/@eserstack/laroux-server)
411
+ - [eserstack repository](https://github.com/eser/stack)
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Builds the value of an RSC "E" (error) chunk.
3
+ *
4
+ * E chunks are streamed to the browser on the public /rsc and page routes, so
5
+ * they carry only the error message. The stack names server file paths and
6
+ * dependency internals; it stays in the server log, where the caller writes
7
+ * the full error.
8
+ */
9
+ export declare const toClientErrorValue: (error: unknown) => {
10
+ message: string;
11
+ };
@@ -0,0 +1,12 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Builds the value of an RSC "E" (error) chunk.
4
+ *
5
+ * E chunks are streamed to the browser on the public /rsc and page routes, so
6
+ * they carry only the error message. The stack names server file paths and
7
+ * dependency internals; it stays in the server log, where the caller writes
8
+ * the full error.
9
+ */
10
+ export const toClientErrorValue = (error) => ({
11
+ message: error instanceof Error ? error.message : String(error),
12
+ });
@@ -0,0 +1,15 @@
1
+ /**
2
+ * React HTML Shell Builder
3
+ * Implements the HtmlShellBuilder port interface for React applications
4
+ */
5
+ import type { HtmlShellBuilder } from "../../domain/html-shell.ts";
6
+ /**
7
+ * Create a React HTML shell builder
8
+ *
9
+ * @returns HtmlShellBuilder implementation for React
10
+ */
11
+ export declare function createReactHtmlShellBuilder(): HtmlShellBuilder;
12
+ /**
13
+ * Default React HTML shell builder instance
14
+ */
15
+ export declare const reactHtmlShellBuilder: HtmlShellBuilder;
@@ -0,0 +1,109 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * React HTML Shell Builder
4
+ * Implements the HtmlShellBuilder port interface for React applications
5
+ */
6
+ import * as scriptJson from "./script-json.js";
7
+ /**
8
+ * Generate script tags from URLs
9
+ */
10
+ function generateScriptTags(scripts) {
11
+ return scripts
12
+ .map((src) => `<script type="module" src="${escapeHtml(src)}"></script>`)
13
+ .join("\n ");
14
+ }
15
+ /**
16
+ * Generate link tags for stylesheets
17
+ */
18
+ function generateStyleTags(styles) {
19
+ return styles
20
+ .map((href) => `<link rel="stylesheet" href="${escapeHtml(href)}">`)
21
+ .join("\n ");
22
+ }
23
+ /**
24
+ * Escape HTML special characters
25
+ */
26
+ function escapeHtml(str) {
27
+ return str
28
+ .replace(/&/g, "&amp;")
29
+ .replace(/</g, "&lt;")
30
+ .replace(/>/g, "&gt;")
31
+ .replace(/"/g, "&quot;")
32
+ .replace(/'/g, "&#039;");
33
+ }
34
+ /**
35
+ * Create a React HTML shell builder
36
+ *
37
+ * @returns HtmlShellBuilder implementation for React
38
+ */
39
+ export function createReactHtmlShellBuilder() {
40
+ return {
41
+ name: "react",
42
+ createShell(options) {
43
+ const { head = "", body = "", scripts = [], styles = [], criticalCss, rscPayload, manifest, title = "", lang = "en", } = options;
44
+ const stylesTags = generateStyleTags(styles);
45
+ const scriptsTags = generateScriptTags(scripts);
46
+ const criticalCssTag = criticalCss
47
+ ? `<style id="__critical_css__">${criticalCss}</style>`
48
+ : "";
49
+ // Serialize manifest for client-side chunk loading
50
+ const manifestScript = manifest
51
+ ? `<script id="__CHUNK_MANIFEST__" type="application/json">${scriptJson.escapeJsonForScript(JSON.stringify(manifest))}</script>`
52
+ : "";
53
+ return `<!DOCTYPE html>
54
+ <html lang="${lang}">
55
+ <head>
56
+ <meta charset="utf-8">
57
+ <meta name="viewport" content="width=device-width, initial-scale=1">
58
+ <title>${escapeHtml(title)}</title>
59
+ ${stylesTags}
60
+ ${criticalCssTag}
61
+ ${head}
62
+ </head>
63
+ <body>
64
+ <div id="root">${body}</div>
65
+ ${rscPayload ?? ""}
66
+ ${manifestScript}
67
+ ${scriptsTags}
68
+ </body>
69
+ </html>`;
70
+ },
71
+ createStreamingStart(options) {
72
+ const { head = "", styles = [], criticalCss, title = "", lang = "en", } = options;
73
+ const stylesTags = generateStyleTags(styles);
74
+ const criticalCssTag = criticalCss
75
+ ? `<style id="__critical_css__">${criticalCss}</style>`
76
+ : "";
77
+ return `<!DOCTYPE html>
78
+ <html lang="${lang}">
79
+ <head>
80
+ <meta charset="utf-8">
81
+ <meta name="viewport" content="width=device-width, initial-scale=1">
82
+ <title>${escapeHtml(title)}</title>
83
+ ${stylesTags}
84
+ ${criticalCssTag}
85
+ ${head}
86
+ </head>
87
+ <body>
88
+ <div id="root">`;
89
+ },
90
+ createStreamingEnd(options) {
91
+ const { scripts = [], rscPayload, manifest } = options;
92
+ const scriptsTags = generateScriptTags(scripts);
93
+ // Serialize manifest for client-side chunk loading
94
+ const manifestScript = manifest
95
+ ? `<script id="__CHUNK_MANIFEST__" type="application/json">${scriptJson.escapeJsonForScript(JSON.stringify(manifest))}</script>`
96
+ : "";
97
+ return `</div>
98
+ ${rscPayload ?? ""}
99
+ ${manifestScript}
100
+ ${scriptsTags}
101
+ </body>
102
+ </html>`;
103
+ },
104
+ };
105
+ }
106
+ /**
107
+ * Default React HTML shell builder instance
108
+ */
109
+ export const reactHtmlShellBuilder = createReactHtmlShellBuilder();
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Inline RSC Emitter
3
+ *
4
+ * Transforms RSC wire format into inline <script> tags that can be
5
+ * embedded directly in the HTML stream. This allows true progressive
6
+ * RSC streaming without a separate /rsc fetch.
7
+ *
8
+ * @see https://github.com/facebook/react/tree/main/packages/react-server-dom-webpack
9
+ */
10
+ import type { ReactElement } from "react";
11
+ import type { RSCChunk } from "@eserstack/laroux-react/protocol";
12
+ import type { BundlerConfig } from "./rsc-flight-renderer.ts";
13
+ /**
14
+ * Chunk callback function type for inline chunk emission
15
+ */
16
+ export type InlineChunkCallback = (chunk: RSCChunk) => void;
17
+ /**
18
+ * Transform RSC wire format to inline script format
19
+ *
20
+ * Input (wire format): J0:{"value":"test"}\n
21
+ * Output (inline): <script>self.__RSC_CHUNK__({type:"J",id:0,value:{"value":"test"}})</script>\n
22
+ */
23
+ export declare function chunkToInlineScript(line: string): string;
24
+ /**
25
+ * Create a TransformStream that converts RSC wire format to inline scripts
26
+ *
27
+ * This transforms the raw RSC stream into HTML-embeddable script tags.
28
+ * Each chunk becomes a <script> that calls self.__RSC_CHUNK__()
29
+ */
30
+ export declare function createInlineTransformStream(): TransformStream<Uint8Array, Uint8Array>;
31
+ /**
32
+ * Create an inline RSC stream from a React element
33
+ *
34
+ * This function:
35
+ * 1. Renders the React element using the existing RSC Flight renderer
36
+ * 2. Transforms the wire format output to inline <script> tags
37
+ * 3. Returns a stream that can be piped into HTML response
38
+ *
39
+ * @param element - The root React element to render
40
+ * @param bundlerConfig - Module map for client component resolution
41
+ * @returns ReadableStream of inline script tags
42
+ */
43
+ export declare function createInlineRSCStream(element: ReactElement, bundlerConfig: BundlerConfig): ReadableStream<Uint8Array>;
44
+ /**
45
+ * Generate the bootstrap script that buffers inline RSC chunks
46
+ *
47
+ * This script must be placed BEFORE any RSC chunk scripts in the HTML.
48
+ * It sets up:
49
+ * 1. A buffer array for chunks that arrive before JS loads
50
+ * 2. A handler function that stores chunks in the buffer
51
+ *
52
+ * The client entry.ts will later process buffered chunks and
53
+ * replace the handler with a direct processor.
54
+ */
55
+ export declare function generateInlineBootstrapScript(): string;
56
+ /**
57
+ * Generate the completion marker script
58
+ *
59
+ * This script is placed AFTER all RSC chunks to signal completion.
60
+ * The client uses this to know when all chunks have been received.
61
+ */
62
+ export declare function generateInlineCompletionScript(): string;