jskelet 0.1.1 → 0.1.2

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 (64) hide show
  1. package/AGENTS.md +5 -0
  2. package/CHANGELOG.md +63 -0
  3. package/README.md +21 -7
  4. package/bin/jskelet.mjs +6 -6
  5. package/docs/03-routing.md +48 -9
  6. package/docs/04-render-ve-sablonlar.md +2 -2
  7. package/docs/05-islands.md +59 -6
  8. package/docs/06-cache.md +39 -7
  9. package/docs/07-yapilandirma.md +51 -1
  10. package/docs/08-build.md +4 -4
  11. package/docs/09-dev-araclari.md +5 -0
  12. package/docs/12-panel-ve-oturum.md +384 -0
  13. package/docs/README.md +25 -2
  14. package/docs/en/01-getting-started.md +292 -0
  15. package/docs/en/02-architecture.md +305 -0
  16. package/docs/en/03-routing.md +493 -0
  17. package/docs/en/04-rendering.md +504 -0
  18. package/docs/en/05-islands.md +492 -0
  19. package/docs/en/06-caching.md +454 -0
  20. package/docs/en/07-configuration.md +736 -0
  21. package/docs/en/08-build.md +383 -0
  22. package/docs/en/09-dev-tools.md +314 -0
  23. package/docs/en/10-deployment.md +332 -0
  24. package/docs/en/11-migration.md +360 -0
  25. package/docs/en/12-dashboards-and-sessions.md +392 -0
  26. package/docs/en/README.md +112 -0
  27. package/package.json +4 -2
  28. package/src/build/build.mjs +1 -1
  29. package/src/build/tasks/client.mjs +2 -2
  30. package/src/build/tasks/fonts.mjs +3 -3
  31. package/src/build/tasks/icons.mjs +1 -1
  32. package/src/build/tasks/images.mjs +2 -2
  33. package/src/client/devtools/overlay.js +196 -164
  34. package/src/client/devtools/report.js +96 -96
  35. package/src/client/form.js +192 -0
  36. package/src/client/index.js +10 -1
  37. package/src/client/registry.js +78 -4
  38. package/src/client/swap.js +188 -0
  39. package/src/config/defaults.js +34 -0
  40. package/src/config/index.js +68 -13
  41. package/src/config/pattern.js +1 -1
  42. package/src/dev-server.mjs +1 -1
  43. package/src/http/control-flow.js +16 -1
  44. package/src/http/cookies.js +257 -0
  45. package/src/http/request-context.js +162 -0
  46. package/src/index.js +19 -2
  47. package/src/init.mjs +32 -31
  48. package/src/log.mjs +8 -2
  49. package/src/logo.png +0 -0
  50. package/src/runtime/alias-hooks.mjs +1 -1
  51. package/src/server/assets.js +1 -1
  52. package/src/server/create-app.js +12 -4
  53. package/src/server/dev/devtools.js +6 -2
  54. package/src/server/dev/version-check.mjs +139 -0
  55. package/src/server/head-hints.js +1 -1
  56. package/src/server/html-cache.js +10 -4
  57. package/src/server/middleware/csrf.js +134 -0
  58. package/src/server/prewarm.js +6 -6
  59. package/src/server/render.js +199 -16
  60. package/src/server/router.js +14 -7
  61. package/src/server/status-page.js +1 -1
  62. package/src/version.mjs +9 -4
  63. package/src/views/components/loader.js +1 -1
  64. package/src/views/helpers/tags.js +53 -1
@@ -0,0 +1,292 @@
1
+ # 01 — Getting started
2
+
3
+ This document explains how to get JSkelet running from scratch: installing the
4
+ package, scaffolding the skeleton with `jskelet init`, writing your first route
5
+ and your first island, what the resulting directory layout means, and the CLI's
6
+ four commands. By the end you will have a page in the browser that is rendered
7
+ on the server, cached, and whose island hydrates on visibility. For the
8
+ *reasons* behind the decisions see
9
+ [02-architecture.md](./02-architecture.md), and for the full reference of every
10
+ config field mentioned here see
11
+ [07-configuration.md](./07-configuration.md).
12
+
13
+ ## Requirements
14
+
15
+ - **Node.js 22 or newer.** `package.json` → `engines` enforces this. The
16
+ framework uses new Node surfaces such as `node:async_hooks`,
17
+ `fs.readdirSync(..., { recursive: true })`, `--env-file-if-exists` and
18
+ `module.register()` directly.
19
+ - If you are going to use Tailwind CSS, the `postcss`, `@tailwindcss/postcss`
20
+ and `tailwindcss` packages. These are **optional peer dependencies** of the
21
+ framework; if they are not installed the CSS step is skipped and the site
22
+ stays unstyled but working (details: [08-build.md](./08-build.md)).
23
+
24
+ ## Installation
25
+
26
+ ```bash
27
+ mkdir my-site && cd my-site
28
+ npm init -y
29
+ npm pkg set type=module
30
+ npm install jskelet
31
+ npm install -D postcss @tailwindcss/postcss tailwindcss lightningcss
32
+ ```
33
+
34
+ `type: "module"` is required: route modules, components and the config file are
35
+ loaded as ESM.
36
+
37
+ Then add the scripts to `package.json`:
38
+
39
+ ```json
40
+ {
41
+ "scripts": {
42
+ "dev": "jskelet dev",
43
+ "build": "jskelet build",
44
+ "start": "jskelet start"
45
+ }
46
+ }
47
+ ```
48
+
49
+ ## `jskelet init`
50
+
51
+ ```bash
52
+ npx jskelet init
53
+ ```
54
+
55
+ This command installs a working minimal skeleton into the directory you are in.
56
+ It **does not overwrite existing files**: running it a second time only fills in
57
+ what is missing and prints the number of skipped files as a warning. The goal is
58
+ to skip the "I installed it but nothing works" stage entirely — `jskelet dev`
59
+ runs right afterwards.
60
+
61
+ The files it creates:
62
+
63
+ ```
64
+ jskelet.config.mjs config: brand, preconnect, cache(), hooks
65
+ routes/10-pages.mjs the "/" route
66
+ views/pages/home.ejs home page template
67
+ views/pages/not-found.ejs 404 template
68
+ views/components/button.js example component (a function returning an HTML string)
69
+ client/entries/main.js island bootstrap
70
+ client/islands/counter.js example island
71
+ styles/globals.css Tailwind entry + @source directives
72
+ jsconfig.json checkJs + the "@/*" alias
73
+ .gitignore node_modules/, .jskelet/, public/assets/, .env
74
+ ```
75
+
76
+ Then:
77
+
78
+ ```bash
79
+ npm run dev
80
+ ```
81
+
82
+ In the terminal you will see a banner, aligned build lines and a `Ready`
83
+ summary; `http://localhost:3000` serves the page. A dev overlay bubble sits in
84
+ the bottom right corner, opened with `Alt+D`
85
+ ([09-dev-tools.md](./09-dev-tools.md)).
86
+
87
+ ## Directory layout
88
+
89
+ None of the directory names are fixed; all of them can be overridden via
90
+ `jskelet.config.mjs` → `paths`. The values below are the defaults
91
+ (`src/config/defaults.js`).
92
+
93
+ | Directory | Default | Contents |
94
+ | --- | --- | --- |
95
+ | `views` | `views` | EJS layout, pages and components |
96
+ | `public` | `public` | Static files; build output is written here too |
97
+ | `client` | `client` | Island runtime sources and entries |
98
+ | `routes` | `routes` | Route modules |
99
+ | `styles` | `styles/globals.css` | Tailwind/PostCSS entry **file** |
100
+ | `generated` | `.jskelet` | Intermediate build output: `manifest.json`, `metafile.json`, `images.json` |
101
+
102
+ In addition to these the framework always derives two paths and accepts no
103
+ separate setting for them: `public/assets` (hashed build output) and
104
+ `public/fonts` (self-hosted fonts).
105
+
106
+ A typical project:
107
+
108
+ ```
109
+ my-site/
110
+ ├── jskelet.config.mjs
111
+ ├── jsconfig.json
112
+ ├── routes/
113
+ │ ├── 10-pages.mjs
114
+ │ └── 90-catch-all.mjs
115
+ ├── views/
116
+ │ ├── layout.ejs
117
+ │ ├── pages/
118
+ │ │ ├── home.ejs
119
+ │ │ └── not-found.ejs
120
+ │ └── components/
121
+ │ └── card.js
122
+ ├── client/
123
+ │ ├── entries/
124
+ │ │ └── main.js
125
+ │ └── islands/
126
+ │ └── counter.js
127
+ ├── styles/
128
+ │ └── globals.css
129
+ ├── public/
130
+ │ └── (static files; build → public/assets)
131
+ └── .jskelet/
132
+ └── manifest.json
133
+ ```
134
+
135
+ ## Your first route
136
+
137
+ Route modules **do not derive URLs automatically from the file system**; every
138
+ module writes its own paths explicitly with `app.get(...)`. The module contract:
139
+ a default export or a named export called `register`, with the signature
140
+ `(app, api)`.
141
+
142
+ ```js
143
+ // routes/10-pages.mjs
144
+ export default function register(app, { route }) {
145
+ app.get(
146
+ "/",
147
+ route(
148
+ async () => ({
149
+ view: "pages/home",
150
+ metadata: { title: "Home" },
151
+ data: { heading: "JSkelet is running", items: ["One", "Two"] },
152
+ }),
153
+ { revalidate: 60 },
154
+ ),
155
+ );
156
+ }
157
+ ```
158
+
159
+ The `api` object comes with `route`, `renderView`, `renderPage`, `notFound`,
160
+ `redirect` and `permanentRedirect` ready to use, so route files don't have to
161
+ import them one by one from the framework. `route()` wraps the controller: the
162
+ HTML cache, the notFound/redirect control flow, compression and the
163
+ `X-JSkelet-Cache` header all come from it. The controller's only job is to
164
+ return a page definition.
165
+
166
+ The `10-` prefix in the file name determines the load order. Because `routes/`
167
+ is scanned alphabetically, you should put catch-all routes such as `/:slug` in a
168
+ file with a higher number; otherwise `/about` will be mistaken for a slug.
169
+ Details: [03-routing.md](./03-routing.md).
170
+
171
+ The template side is plain EJS:
172
+
173
+ ```ejs
174
+ <%# views/pages/home.ejs %>
175
+ <section class="wrapper">
176
+ <h1 class="text-3xl font-bold"><%= heading %></h1>
177
+ <%- list({ items }) %>
178
+ <div data-island="counter" data-island-props='{"start":5}'></div>
179
+ </section>
180
+ ```
181
+
182
+ Here `list` is a function defined in `views/components/list.js` and it has not
183
+ been imported: every named export under `views/components/**` automatically
184
+ becomes a template local ([04-rendering.md](./04-rendering.md)).
185
+
186
+ ## Your first island
187
+
188
+ An island is a small module that adds behaviour to the HTML the server
189
+ produced. The contract has two parts.
190
+
191
+ **1. A marker in the template:** give an element `data-island="ad"`. Props are
192
+ carried as JSON inside `data-island-props`.
193
+
194
+ ```ejs
195
+ <div data-island="counter" data-island-props='{"start":5}'></div>
196
+ ```
197
+
198
+ **2. A `mount` in the module:** the island provides a named export called
199
+ `mount(element, props)`.
200
+
201
+ ```js
202
+ // client/islands/counter.js
203
+ /**
204
+ * @param {HTMLElement} element
205
+ * @param {{ start?: number }} props
206
+ */
207
+ export function mount(element, props) {
208
+ let value = props.start ?? 0;
209
+
210
+ const button = document.createElement("button");
211
+ button.type = "button";
212
+
213
+ const paint = () => {
214
+ button.textContent = `Clicks: ${value}`;
215
+ };
216
+
217
+ button.addEventListener("click", () => {
218
+ value += 1;
219
+ paint();
220
+ });
221
+
222
+ paint();
223
+ element.append(button);
224
+ }
225
+ ```
226
+
227
+ **3. Registration:** `client/entries/main.js` maps the island name to a dynamic
228
+ import and starts the runtime.
229
+
230
+ ```js
231
+ import { registerAll, start } from "jskelet/client";
232
+
233
+ registerAll({
234
+ counter: () => import("../islands/counter.js"),
235
+ });
236
+
237
+ start();
238
+ ```
239
+
240
+ It is critical that the values are dynamic imports: the module is downloaded
241
+ only if that island actually exists on the page **and** when the element becomes
242
+ visible. In other words, growing this map does not grow the initial payload.
243
+ Hydration strategies (`data-island-eager`, `data-island-idle`) and the complete
244
+ runtime API are in [05-islands.md](./05-islands.md).
245
+
246
+ ## CLI commands
247
+
248
+ `bin/jskelet.mjs` offers four subcommands. Each runs in a separate Node process;
249
+ the reason is that `dev` manages two long-lived processes and the server needs
250
+ ESM resolve hooks (`--import`) at process start.
251
+
252
+ | Command | What it does |
253
+ | --- | --- |
254
+ | `jskelet dev` | Build watch + server, in a single terminal. Live reload, CSS hot-swap, dev overlay. `NODE_ENV=development`. |
255
+ | `jskelet build` | One-shot prod build: fonts → icon sprite → CSS → client JS → images → manifest → precompress. `production` if `NODE_ENV` is not given. |
256
+ | `jskelet start` | Prod server. If there is no build output it produces it first. `production` if `NODE_ENV` is not given. |
257
+ | `jskelet init` | Installs a minimal skeleton into the current directory; leaves existing files alone. |
258
+
259
+ An unknown command, or a call with no arguments, prints the usage text.
260
+
261
+ Every command runs with two Node flags:
262
+
263
+ - `--env-file=.env` — passed only if the file really exists; otherwise no flag
264
+ is added and no warning is printed.
265
+ - `--import <register.mjs>` — installs the ESM hooks that resolve the
266
+ `compilerOptions.paths` aliases (`@/lib/x`) from `jsconfig.json` /
267
+ `tsconfig.json` and extensionless relative imports (`./cache` →
268
+ `./cache.js`). (`jskelet dev` installs these hooks in its own child
269
+ processes, not in the outer process.)
270
+
271
+ ## Import paths
272
+
273
+ The `package.json` → `exports` map defines the stable surface. In examples, use
274
+ only these specifiers:
275
+
276
+ | Specifier | Contents |
277
+ | --- | --- |
278
+ | `jskelet` | Server API: `route`, `renderPage`, `renderView`, `renderNotFound`, `createApp`, `startServer`, `notFound`, `redirect`, `permanentRedirect`, `cache`, `withRequestCache`, `reportUpstreamFailure`, `asset`, `hasAsset`, `optimizedImage`, `getSpriteIds`, `headHints`, `renderHeadMeta`, HTML cache functions, `prewarm`, `createProxy`, `getConfig`, `loadConfig` and the html/tag helpers |
279
+ | `jskelet/server` | The same module as `jskelet` (an alias for readability) |
280
+ | `jskelet/client` | Browser runtime: `register`, `registerAll`, `hydrate`, `observeDocument`, `start`, `createStore`, DOM helpers, `startSafeImages` |
281
+ | `jskelet/html` | `esc`, `attrs`, `cx`, `cn`, `jsonScript` |
282
+ | `jskelet/tags` | `link`, `image`, `icon`, `preloadImage`, `toKebab` |
283
+ | `jskelet/log` | Console output helpers (`banner`, `event`, `task`, `size`, `ms`, …) |
284
+ | `jskelet/register` | Alias + extension hooks via `node --import jskelet/register` |
285
+ | `jskelet/layout` | The path to the framework's default `layout.ejs` file |
286
+
287
+ ## What's next
288
+
289
+ - Why it works this way: [02-architecture.md](./02-architecture.md)
290
+ - More routes and catch-all patterns: [03-routing.md](./03-routing.md)
291
+ - Taking over the layout, and metadata: [04-rendering.md](./04-rendering.md)
292
+ - Tuning the cache: [06-caching.md](./06-caching.md)
@@ -0,0 +1,305 @@
1
+ # 02 — Architecture and the reasoning behind the decisions
2
+
3
+ This document does not explain how JSkelet works, but **why it works this way**.
4
+ The path a request takes from the server to the browser, why the island model is
5
+ tied to visibility, why the HTML is produced in full, why the cache lives in
6
+ process memory and why the middleware order must not be shuffled — that is all
7
+ here. Most of the reasoning comes from the measurement notes in the headers of
8
+ the source files; for the APIs themselves see documents
9
+ [03](./03-routing.md), [04](./04-rendering.md), [05](./05-islands.md) and
10
+ [06](./06-caching.md).
11
+
12
+ ## The basic premise
13
+
14
+ On a news or content site, almost everything the visitor sees is already ready
15
+ on the server. Interaction, on the other hand, is scattered point by point: a
16
+ search box, a drawer, a chart, a comment form. With that profile, rebuilding the
17
+ whole page on the client (hydration) is the biggest cost you pay, and in return
18
+ the visitor gains nothing.
19
+
20
+ JSkelet puts this observation at the centre of the architecture:
21
+
22
+ 1. **The server HTML is complete.** Even if JS never runs, the page can be read,
23
+ navigated and indexed.
24
+ 2. **JS only adds behaviour.** Every interactive piece is attached as an
25
+ independent "island", with its own module, at its own time.
26
+ 3. **Page production is cached.** There is no point in producing the same HTML
27
+ again on every request; a memory cache with a TTL takes the place of ISR.
28
+
29
+ ## The path of a request
30
+
31
+ ```
32
+ Request
33
+ ├─ rewrites(beforeFiles) config → proxy or a change to req.url
34
+ ├─ compression brotli/gzip negotiation (quality 5)
35
+ ├─ headers static cache + config headers()
36
+ ├─ devGate if DEV_TOKEN is set, 404 without a token
37
+ ├─ redirects config redirects(), first match wins
38
+ ├─ staticPrecompressed .br/.gz copies produced at build (quality 11)
39
+ ├─ express.static files under public/
40
+ ├─ (dev) devtools only when NODE_ENV=development
41
+ ├─ body parsers urlencoded 64kb + json 256kb
42
+ ├─ rewrites(afterFiles) after static has been tried
43
+ ├─ routes
44
+ │ └─ route(controller)
45
+ │ └─ withHtmlCache TTL + stale-while-revalidate
46
+ │ └─ withUpstreamTracking
47
+ │ └─ withRequestCache
48
+ │ └─ controller → renderPage → EJS
49
+ ├─ 404 → hooks.notFound()
50
+ └─ error handling redirect/notFound + 500 fallback
51
+ ```
52
+
53
+ ## Why the middleware order is this order
54
+
55
+ The real value of the `src/server/create-app.js` file is the order; every
56
+ position has a reason, and moving things around leads to silent breakage.
57
+
58
+ - **`rewrites(beforeFiles)` comes even before static files.** Otherwise a rule
59
+ that moves the `/assets/x.js` path somewhere else would never take effect,
60
+ because `express.static` answers the request first.
61
+ - **`compression` before static.** If it came after, static files would never be
62
+ compressed.
63
+ - **`headers` → `devGate` → `redirects`.** The gate's 404 must come before the
64
+ redirects: an environment that has not gone live should not leak even its
65
+ redirect rules to the outside.
66
+ - **`staticPrecompressed` before `express.static`.** If there are `.br`/`.gz`
67
+ copies produced at build time, those are served (brotli quality 11);
68
+ otherwise the request falls through to the `static` below it and the
69
+ middleware compresses on the fly (quality 5). Recompressing a hashed,
70
+ `immutable` file on every request is wasted CPU.
71
+ - **Body parsers after static.** Image requests should not pay the cost of body
72
+ parsing.
73
+ - **`rewrites(afterFiles)` after static has been tried and before pages.** The
74
+ equivalent of Next.js's two-phase rewrite semantics.
75
+ - **404 and error handling last.** The error handler also catches the
76
+ `notFound`/`redirect` control flow, because those can be thrown outside a
77
+ controller as well (e.g. inside a middleware).
78
+
79
+ The framework turns off `x-powered-by` and writes a brandable header in its
80
+ place, sets `etag` to `strong` and enables `trust proxy`. `trust proxy` is
81
+ required for the correct protocol and client IP behind a reverse proxy
82
+ ([10-deployment.md](./10-deployment.md)).
83
+
84
+ ## The island model: why visibility-based hydration
85
+
86
+ `src/client/registry.js` hands every `[data-island]` element to an
87
+ `IntersectionObserver` (`rootMargin: "200px 0px"`). Elements on screen are
88
+ triggered on the very first observation; those off screen are **never
89
+ downloaded** until they are scrolled to. Heavy modules like the chart library on
90
+ the home page thus drop out of the initial load entirely.
91
+
92
+ There are three behaviours, all controlled from the HTML:
93
+
94
+ - **Default:** tied to visibility.
95
+ - **`data-island-eager`:** independent of visibility, attaches immediately. For
96
+ global behaviours like the header or the cookie banner.
97
+ - **`data-island-idle`:** even if it is visible, it waits until `load` has
98
+ completed and the main thread is free. So that heavy modules that are visible
99
+ in the first viewport but not critical (e.g. a mini chart that pulls in a
100
+ chart library) do not compete with LCP.
101
+
102
+ Two further details came out of measurement:
103
+
104
+ - **The attaching work is deferred to idle time** (`requestIdleCallback`,
105
+ `timeout: 500`). If many islands that become visible at once turn into a
106
+ single long task, TBT and INP suffer.
107
+ - **Elements with no layout box are attached directly.** A `hidden`
108
+ drawer/dialog has no layout box and `IntersectionObserver` will never report
109
+ it; that is why `hydrate()` reads the measurements in one pass
110
+ (`getClientRects().length`) and, instead of handing boxless elements to the
111
+ observer, attaches them immediately.
112
+
113
+ One consequence of this: **image error handling is not an island.** An
114
+ image-heavy page can have 80+ `<img>` elements, and attaching a separate island
115
+ to each one (observer + dynamic import + mount) is a serious hydration cost just
116
+ for the possibility of an error. `startSafeImages()` instead installs a single
117
+ capture-phase listener on the document ([05-islands.md](./05-islands.md)).
118
+
119
+ ## Why the server HTML is complete
120
+
121
+ The layout and the page template produce the entirety of the content the visitor
122
+ will see. There is no "show a skeleton, then fill it in" pattern on the client
123
+ side. This buys three things:
124
+
125
+ 1. **SEO:** the crawler does not have to wait for JS.
126
+ 2. **LCP:** the largest contentful element arrives in the first HTML response;
127
+ downloading, parsing and executing JS is not on the LCP path.
128
+ 3. **CLS:** because content is not injected later, the layout does not shift.
129
+
130
+ The same principle is applied on the `<head>` side too. The layout prints
131
+ resource hints (`preconnect`, LCP `preload`) at the **very beginning** of the
132
+ `<head>`; delaying those writes straight to LCP.
133
+
134
+ ### Why a single, render-blocking stylesheet
135
+
136
+ No separate "critical CSS" is produced. In measurement, because the inline
137
+ critical CSS did not fully cover the first viewport, the page reflowed once the
138
+ sheet arrived (CLS 0.307 on a list page) and the same ~27 KB was repeated in
139
+ every HTML response. Leaving a single compressed sheet render-blocking is both
140
+ faster and free of CLS; on the second visit it already comes from the
141
+ `immutable` cache.
142
+
143
+ The same logic applies to icons: instead of a separate request per icon, an SVG
144
+ sprite is produced at build time from only the symbols actually used in the
145
+ source. Shipping the whole Phosphor set is 1500+ icons, that is several
146
+ megabytes; the scan typically keeps the sprite at 10-30 symbols
147
+ ([08-build.md](./08-build.md)).
148
+
149
+ ## Cache strategy: in-memory TTL instead of ISR
150
+
151
+ `src/server/html-cache.js` keeps an LRU HTML cache with a TTL, keyed by route +
152
+ query (at most 500 entries). When the TTL expires the entry is not thrown away
153
+ immediately: within the `stale` window the old HTML returns instantly and the
154
+ refresh runs in the background (stale-while-revalidate, `STALE_FACTOR = 1`, i.e.
155
+ the stale window is as long as the TTL).
156
+
157
+ The gain: after the first warm-up no request ever waits for a render. The price:
158
+ the data in the HTML can be at most `revalidate + one refresh round` behind.
159
+ That price is acceptable, because live fields such as prices are updated on the
160
+ client from a WebSocket and the lag is not visible on screen.
161
+
162
+ The decision not to write to disk is deliberate. The equivalent of Next's
163
+ build-time prerender is prewarm, but the output is not written to disk: because
164
+ the cache lives in process memory, the warm-up is done when the process comes
165
+ up. The gain is the same — the first visitor does not wait for a cold render —
166
+ but the data is not frozen; every entry ages with the route's `revalidate`
167
+ duration ([06-caching.md](./06-caching.md)).
168
+
169
+ ### Keeping the compressed body in the cache
170
+
171
+ Every cached entry stores the brotli/gzip output alongside the HTML (the
172
+ `encoded` map shares its lifetime with the HTML). The same page is not
173
+ re-brotli'd on every request. Because `Content-Encoding` is set inside `route()`
174
+ on this path, the compression middleware does not kick in.
175
+
176
+ ### Why transient and permanent upstream errors are handled differently
177
+
178
+ If an upstream went down during the render, the output contains incomplete data,
179
+ and such HTML is **not** written to the cache: the next request tries again.
180
+
181
+ But this only applies to *transient* errors (network errors, 408, 425, 429 and
182
+ all 5xx). Deterministic answers like 400/403/404 do not get better by retrying;
183
+ turning off the cache because of them would mean rendering the page from scratch
184
+ on every visit — the content comes back in the same incomplete state anyway, the
185
+ visitor merely pays the render time. That is why permanent errors are only
186
+ logged and do not block the cache.
187
+
188
+ The direction in which this information reaches the framework is also
189
+ deliberately inverted: the framework does not know the data layer, the data
190
+ layer notifies the framework (`reportUpstreamFailure()`). If nobody ever calls
191
+ it, the cost is an empty array.
192
+
193
+ ### The nesting order of the three scopes
194
+
195
+ `route()` sets up this order:
196
+
197
+ ```
198
+ withHtmlCache( withUpstreamTracking( withRequestCache( controller ) ) )
199
+ ```
200
+
201
+ The order matters: **the per-request cache must be innermost** so that two calls
202
+ within the same render collapse into a single upstream request; **upstream
203
+ tracking must be inside the HTML cache** so that output produced with incomplete
204
+ data is not written to the cache.
205
+
206
+ ## Fault tolerance: no single gap takes the site down
207
+
208
+ There is a principle repeated throughout the framework: missing configuration or
209
+ missing build output produces a degraded but working page instead of an error.
210
+
211
+ - **If the config file is missing or unreadable**, a warning is printed and the
212
+ server comes up with the defaults. A broken edit must not make the site
213
+ impossible to open. In the same way, if one of the
214
+ `headers()`/`redirects()`/`rewrites()`/`cache()` sections throws, only that
215
+ section is ignored.
216
+ - **If hooks throw**, the framework falls back to its own default and warns.
217
+ - **If the build did not run**, `asset()` returns `/assets/<name>`, `hasAsset()`
218
+ is false and the layout does not print the stylesheet/script tags at all. When
219
+ `jskelet build` is forgotten you see an unstyled but working page instead of
220
+ an error.
221
+ - **A broken route module in dev** prints a warning and is skipped; **in
222
+ production it throws.** Going live with a half-built route table means pages
223
+ that silently return 404.
224
+ - **If the 404 render blows up too**, a minimal, template-free HTML is returned;
225
+ the visitor should not see an empty response.
226
+ - **A single request error does not take the process down:**
227
+ `unhandledRejection` and `uncaughtException` are logged and the process stays
228
+ up. On a news site, an error on a single page must not take the whole site
229
+ down.
230
+
231
+ ## Why there is no file-system-based routing
232
+
233
+ Order matters. If a single-segment catch-all such as `/:slug` is registered
234
+ before the `/about` route, "about" is mistaken for a slug. Making the order
235
+ visible instead of hiding it in file names makes diagnosis easier: either you
236
+ give an explicit list via `jskelet.config.mjs` → `routes`, or you have the
237
+ `routes/` directory scanned alphabetically and put a numeric prefix on the file
238
+ names (`10-pages.js`, `50-blog.js`, `99-catch-all.js`). Details:
239
+ [03-routing.md](./03-routing.md).
240
+
241
+ ## Why a single source of truth for config
242
+
243
+ `src/config/index.js` normalizes the project root, the directory paths, the
244
+ branding, the hooks and the rules. Other modules do not compute paths, they call
245
+ `getConfig()`. The reason is concrete: once the framework lives inside
246
+ `node_modules/`, every file that tries to find the root by counting `../..`
247
+ breaks. For the same reason there is a single mutation point on the build side
248
+ too (`initBuildPaths()`).
249
+
250
+ If `getConfig()` is used without `loadConfig()` having been called, it throws
251
+ instead of assuming an empty project root: a silently wrong path turns into
252
+ hard-to-diagnose problems like "why is there no stylesheet".
253
+
254
+ ## Why this dependency list
255
+
256
+ There are four runtime dependencies: `express`, `ejs`, `esbuild`,
257
+ `tailwind-merge`. Everything else (Tailwind, PostCSS, lightningcss, sharp, the
258
+ Phosphor icons) is an **optional peer dependency**, and if it is absent the
259
+ corresponding build step is skipped.
260
+
261
+ Two decisions deserve a separate explanation:
262
+
263
+ - **`node:zlib` instead of the `compression` package.** The package does not
264
+ support brotli and brings a seven-deep dependency tree; doing the brotli +
265
+ gzip negotiation by hand is enough. Brotli is preferred: on the home page HTML
266
+ it is ~35% smaller than gzip.
267
+ - **`tailwind-merge` stays at runtime.** Class computation is done only on the
268
+ server, it never enters the client bundle, so it has no effect on page weight.
269
+ A hand-written group table, on the other hand, produced visual regressions
270
+ because it mixed up width/colour pairs like `border-2` +
271
+ `border-transparent` and dropped classes.
272
+
273
+ Optional packages are resolved from the **application's** `node_modules`, not
274
+ from the framework's own. If the framework is installed via a `file:` or
275
+ workspace link, a plain `import "postcss"` looks in the framework's tree — not
276
+ in the application's.
277
+
278
+ ## Why alias and extension hooks
279
+
280
+ `node --import jskelet/register` does two things:
281
+
282
+ 1. It resolves the `compilerOptions.paths` aliases in `jsconfig.json` /
283
+ `tsconfig.json` (`@/lib/x` → `<root>/lib/x`). Because the editor and the
284
+ runtime are fed from the same file, the two do not drift apart.
285
+ 2. It adds extensions to extensionless relative imports (`./cache` →
286
+ `./cache.js`). Node ESM does not do this, and it is the most common breaking
287
+ point in code migrated from a bundler.
288
+
289
+ The `@/` resolution on the esbuild side mimics the same behaviour, so that
290
+ modules under `lib/` can use the same import style both on the server and in the
291
+ browser.
292
+
293
+ `--import` expects a module **specifier**, not a file path. On Windows an
294
+ absolute path like `H:\...` is mistaken for a URL with the `h:` scheme and
295
+ rejected; that is why the framework uses `pathToFileURL(...).href` everywhere.
296
+ For the same reason the config, the route modules and the components are
297
+ imported with a `file://` URL too.
298
+
299
+ ## What's next
300
+
301
+ - The route and controller contract: [03-routing.md](./03-routing.md)
302
+ - The template layer and metadata: [04-rendering.md](./04-rendering.md)
303
+ - The island runtime API: [05-islands.md](./05-islands.md)
304
+ - Cache settings and prewarm: [06-caching.md](./06-caching.md)
305
+ - The inner workings of the dev flow: [09-dev-tools.md](./09-dev-tools.md)