@kerf-js/start 0.0.0-stage → 0.1.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 (236) hide show
  1. package/LICENSE +16 -0
  2. package/README.md +1468 -2
  3. package/crate/Cargo.lock +1347 -0
  4. package/crate/Cargo.toml +72 -0
  5. package/crate/README.md +322 -0
  6. package/crate/rust-toolchain.toml +3 -0
  7. package/crate/src/build/emit.rs +103 -0
  8. package/crate/src/build.rs +367 -0
  9. package/crate/src/ctx.rs +186 -0
  10. package/crate/src/envelope.rs +163 -0
  11. package/crate/src/functions.rs +173 -0
  12. package/crate/src/lib.rs +118 -0
  13. package/crate/src/native.rs +212 -0
  14. package/crate/src/otel.rs +62 -0
  15. package/crate/src/server.rs +203 -0
  16. package/package.json +123 -3
  17. package/src/app.mjs +136 -0
  18. package/src/asset-receipt.d.mts +13 -0
  19. package/src/asset-receipt.mjs +61 -0
  20. package/src/auth/better-auth.ts +280 -0
  21. package/src/auth/drizzle.ts +17 -0
  22. package/src/auth/emails.ts +44 -0
  23. package/src/auth.ts +62 -0
  24. package/src/boot.ts +57 -0
  25. package/src/builtin.tsx +19 -0
  26. package/src/bus/postgres.ts +104 -0
  27. package/src/bus.ts +51 -0
  28. package/src/cache.ts +4 -0
  29. package/src/capture.ts +50 -0
  30. package/src/changes-sql.d.mts +20 -0
  31. package/src/changes-sql.mjs +115 -0
  32. package/src/changes.ts +352 -0
  33. package/src/channel/connections.ts +216 -0
  34. package/src/channel/socket.ts +396 -0
  35. package/src/channel-fake.ts +70 -0
  36. package/src/channel.ts +250 -0
  37. package/src/client.tsx +27 -0
  38. package/src/contract/describe.mjs +237 -0
  39. package/src/contract.mjs +299 -0
  40. package/src/cron.ts +74 -0
  41. package/src/data/after.ts +57 -0
  42. package/src/data/cache.ts +354 -0
  43. package/src/data/definitions.ts +94 -0
  44. package/src/data/draft.ts +104 -0
  45. package/src/data/foundation.ts +95 -0
  46. package/src/data/live-api.ts +22 -0
  47. package/src/data/mutation.ts +138 -0
  48. package/src/data/primitives.ts +135 -0
  49. package/src/data/query.ts +106 -0
  50. package/src/data/transport.ts +123 -0
  51. package/src/data/types.ts +333 -0
  52. package/src/data.ts +125 -0
  53. package/src/db/bun-sqlite.d.ts +13 -0
  54. package/src/db/changes-mysql.ts +126 -0
  55. package/src/db/changes-postgres.ts +238 -0
  56. package/src/db/changes-sqlite.ts +183 -0
  57. package/src/db/core.ts +95 -0
  58. package/src/db/index.ts +43 -0
  59. package/src/db/mysql.ts +84 -0
  60. package/src/db/postgres.ts +102 -0
  61. package/src/db/sqlite.ts +166 -0
  62. package/src/derive.d.mts +19 -0
  63. package/src/derive.mjs +237 -0
  64. package/src/dev-runtime.mjs +46 -0
  65. package/src/email.ts +146 -0
  66. package/src/exec/errors.ts +87 -0
  67. package/src/exec/impl.ts +21 -0
  68. package/src/exec/landing.ts +66 -0
  69. package/src/exec/limit.ts +25 -0
  70. package/src/exec/once.ts +24 -0
  71. package/src/exec/scope.ts +328 -0
  72. package/src/exec/touch.ts +80 -0
  73. package/src/exec/validation.ts +176 -0
  74. package/src/exec/warm.ts +50 -0
  75. package/src/exec.ts +400 -0
  76. package/src/extension.ts +48 -0
  77. package/src/first-paint.ts +74 -0
  78. package/src/form/value.ts +15 -0
  79. package/src/form.tsx +223 -0
  80. package/src/gate.css +6 -0
  81. package/src/hub/channels.ts +102 -0
  82. package/src/hub/connections.ts +147 -0
  83. package/src/hub/delivery.ts +62 -0
  84. package/src/hub/feed.ts +168 -0
  85. package/src/hub/presence.ts +64 -0
  86. package/src/hub/route.ts +159 -0
  87. package/src/hub/subscriptions.ts +213 -0
  88. package/src/hub/topic.ts +98 -0
  89. package/src/hub/tracked.ts +12 -0
  90. package/src/hub/types.ts +190 -0
  91. package/src/hub/view.ts +147 -0
  92. package/src/hub.ts +196 -0
  93. package/src/index.ts +184 -0
  94. package/src/inline.mjs +359 -0
  95. package/src/inspect/compare.mjs +162 -0
  96. package/src/inspect/routes.mjs +154 -0
  97. package/src/inspect/samples.mjs +59 -0
  98. package/src/inspect/url.mjs +2 -0
  99. package/src/inspect.mjs +239 -0
  100. package/src/jobs.ts +223 -0
  101. package/src/link/election.ts +178 -0
  102. package/src/link/lines.ts +27 -0
  103. package/src/link.ts +385 -0
  104. package/src/list-drizzle.ts +136 -0
  105. package/src/list.ts +315 -0
  106. package/src/listen.ts +54 -0
  107. package/src/live/api.ts +18 -0
  108. package/src/live/backoff.ts +6 -0
  109. package/src/live/frames.ts +42 -0
  110. package/src/live/read.ts +77 -0
  111. package/src/live/sub-types.ts +24 -0
  112. package/src/live/transport.ts +86 -0
  113. package/src/live/types.ts +52 -0
  114. package/src/live-fake.ts +57 -0
  115. package/src/live-target.mjs +231 -0
  116. package/src/live.ts +390 -0
  117. package/src/media.ts +50 -0
  118. package/src/migrations.mjs +27 -0
  119. package/src/mux-session.ts +6 -0
  120. package/src/mux.ts +232 -0
  121. package/src/og/DefaultCard.tsx +91 -0
  122. package/src/og/fonts.mjs +72 -0
  123. package/src/og/images.mjs +124 -0
  124. package/src/og/index.mjs +222 -0
  125. package/src/og/native.mjs +36 -0
  126. package/src/range.mjs +31 -0
  127. package/src/router.ts +199 -0
  128. package/src/routes.mjs +193 -0
  129. package/src/run/admission.ts +67 -0
  130. package/src/run/boot.tsx +115 -0
  131. package/src/run/cache-presentation.ts +67 -0
  132. package/src/run/cache.ts +254 -0
  133. package/src/run/helpers.ts +197 -0
  134. package/src/run/listeners.ts +166 -0
  135. package/src/run/navigation.ts +385 -0
  136. package/src/run/page-skeleton.tsx +35 -0
  137. package/src/run/prefetch.ts +129 -0
  138. package/src/run/retain-view.ts +18 -0
  139. package/src/run/shape-preparation.ts +97 -0
  140. package/src/run/shape-styles.ts +72 -0
  141. package/src/run/source-context/pin.ts +124 -0
  142. package/src/run/source-context.ts +311 -0
  143. package/src/run.tsx +74 -0
  144. package/src/rust/common.ts +163 -0
  145. package/src/rust/native.ts +282 -0
  146. package/src/rust.ts +207 -0
  147. package/src/server/background.ts +34 -0
  148. package/src/server/card.tsx +65 -0
  149. package/src/server/compression.ts +115 -0
  150. package/src/server/core.ts +70 -0
  151. package/src/server/cron.ts +49 -0
  152. package/src/server/dispatch.ts +73 -0
  153. package/src/server/form.ts +92 -0
  154. package/src/server/functions.ts +133 -0
  155. package/src/server/handler.ts +57 -0
  156. package/src/server/head.ts +96 -0
  157. package/src/server/health.ts +36 -0
  158. package/src/server/jobs.ts +112 -0
  159. package/src/server/lifecycle.ts +48 -0
  160. package/src/server/log.ts +42 -0
  161. package/src/server/media.ts +61 -0
  162. package/src/server/navigation-cache.ts +75 -0
  163. package/src/server/navigation.tsx +86 -0
  164. package/src/server/page-cold.ts +96 -0
  165. package/src/server/page-stream.tsx +181 -0
  166. package/src/server/page-types.ts +51 -0
  167. package/src/server/page-warm.ts +131 -0
  168. package/src/server/page.ts +69 -0
  169. package/src/server/payload.ts +89 -0
  170. package/src/server/prerender.ts +64 -0
  171. package/src/server/preview.tsx +67 -0
  172. package/src/server/render.ts +197 -0
  173. package/src/server/request.ts +192 -0
  174. package/src/server/resolver.ts +228 -0
  175. package/src/server/routes.ts +150 -0
  176. package/src/server/security.ts +50 -0
  177. package/src/server/services.ts +69 -0
  178. package/src/server/shutdown.ts +23 -0
  179. package/src/server/text.ts +29 -0
  180. package/src/server/types.ts +170 -0
  181. package/src/server.tsx +138 -0
  182. package/src/shape.d.mts +3 -0
  183. package/src/shape.mjs +97 -0
  184. package/src/share/display.ts +50 -0
  185. package/src/share/network.ts +119 -0
  186. package/src/share/receive.ts +70 -0
  187. package/src/share/state.ts +30 -0
  188. package/src/share/tab-queue.ts +28 -0
  189. package/src/share-server.ts +293 -0
  190. package/src/share.ts +397 -0
  191. package/src/sheets.mjs +87 -0
  192. package/src/sidecar/build.mjs +170 -0
  193. package/src/sidecar/cargo.mjs +164 -0
  194. package/src/sidecar/common.mjs +17 -0
  195. package/src/sidecar/dev-build.mjs +91 -0
  196. package/src/sidecar/dev-watch.mjs +88 -0
  197. package/src/sidecar/manifest.mjs +19 -0
  198. package/src/sidecar/process.mjs +58 -0
  199. package/src/sidecar/refresh.mjs +19 -0
  200. package/src/sidecar.mjs +162 -0
  201. package/src/socket/check.ts +50 -0
  202. package/src/socket/deliver.ts +16 -0
  203. package/src/socket/publish.ts +56 -0
  204. package/src/socket/rooms.ts +41 -0
  205. package/src/socket/route.ts +79 -0
  206. package/src/socket/shared.ts +26 -0
  207. package/src/socket/types.ts +48 -0
  208. package/src/socket.ts +400 -0
  209. package/src/stream.ts +22 -0
  210. package/src/verify/app.ts +39 -0
  211. package/src/verify/cleanup.ts +27 -0
  212. package/src/verify/database.ts +11 -0
  213. package/src/verify/live.ts +63 -0
  214. package/src/verify/notify.ts +35 -0
  215. package/src/verify/skip.ts +19 -0
  216. package/src/verify/support.ts +149 -0
  217. package/src/verify/timing.ts +15 -0
  218. package/src/verify/trigger.ts +14 -0
  219. package/src/verify.ts +152 -0
  220. package/src/view.tsx +132 -0
  221. package/src/vite/asset-bytes.mjs +95 -0
  222. package/src/vite/assets.mjs +117 -0
  223. package/src/vite/config-hooks.mjs +166 -0
  224. package/src/vite/dev-hooks.mjs +103 -0
  225. package/src/vite/dev.mjs +102 -0
  226. package/src/vite/entries.mjs +149 -0
  227. package/src/vite/module-hooks.mjs +290 -0
  228. package/src/vite/route-modules.mjs +289 -0
  229. package/src/vite/server-functions.mjs +222 -0
  230. package/src/vite/shape-entry-css.mjs +187 -0
  231. package/src/vite/shape-override.mjs +226 -0
  232. package/src/vite/shared.mjs +55 -0
  233. package/src/vite/sheets.mjs +92 -0
  234. package/src/vite/state.mjs +89 -0
  235. package/src/vite/syntax.mjs +139 -0
  236. package/src/vite.mjs +202 -0
@@ -0,0 +1,197 @@
1
+ import type { RoutePayload } from '../router'
2
+ import { firstPaint } from '../first-paint'
3
+ import { pick } from '../sheets.mjs'
4
+ import type { HandlerOptions } from './types'
5
+ import { esc, hash } from './text'
6
+
7
+ /**
8
+ * A page's styles from the build's first-paint table (`firstPaint`): the rules its HTML reaches, inline, and its sheets as
9
+ * links past the shell, where they hold nothing above it. `late` gives a streamed chunk the rules it adds, and a link for
10
+ * a sheet none of the page's has: an island in a Boundary the shell didn't show.
11
+ */
12
+ export function tableStyles(
13
+ pieces: NonNullable<NonNullable<HandlerOptions['assets']>['pieces']>,
14
+ css: { href: string }[],
15
+ siteHead: string | undefined,
16
+ lang: string,
17
+ ) {
18
+ const hrefs = css.map((c) => c.href)
19
+ const late = pick(pieces, hrefs)
20
+ const paint = firstPaint(pieces, hrefs, siteHead)
21
+ const held: string[] = late.sheets.flatMap((c: { has: string[] }) => c.has)
22
+ const carried = new Set([...hrefs, ...held])
23
+ const link = (href: string) => `<link rel="stylesheet" href="${esc(href)}">\n`
24
+ return {
25
+ rules: (shell: string) => paint(`<html${lang}><body><div id="app">${shell}`),
26
+ // A combined sheet's parts as disabled links: Vite's preload helper finds them there and doesn't fetch them again.
27
+ links:
28
+ [...late.sheets.map((c: { href: string }) => c.href), ...late.rest].map(link).join('') +
29
+ held.map((href) => `<link rel="stylesheet" href="${esc(href)}" disabled>\n`).join(''),
30
+ late(sheets: { href: string }[] = [], chunk = '') {
31
+ const more = sheets.map((c) => c.href).filter((h) => !carried.has(h))
32
+ for (const h of more) carried.add(h)
33
+ const rules = paint(chunk)
34
+ return more.map(link).join('') + (rules ? `<style>${rules}</style>\n` : '')
35
+ },
36
+ }
37
+ }
38
+
39
+ /**
40
+ * The payload with its static levels marked: their hash, without their data (the HTML holds it), and with `html` their
41
+ * HTML, each level's next one cut down to its markers. The `aria-current` a navigation moves doesn't count as a change.
42
+ */
43
+ /**
44
+ * The chunks `payload`'s page will want: its non-static levels and the islands that load with it, and `fold`, the lazy
45
+ * ones in the first view. Those stay preloaded, fetched but not run, so a first click on them doesn't wait; the rest
46
+ * load when they're needed. `$client`: the router and runtime, whenever any of that will run.
47
+ */
48
+ export const pageChunks = (
49
+ payload: RoutePayload,
50
+ chunks: HandlerOptions['chunks'] = {},
51
+ fold: string[] = [],
52
+ now = true,
53
+ ) => {
54
+ const ids = [...payload.m.filter((m) => !m.s).map((m) => m.id), ...(payload.i ?? []), ...fold]
55
+ return [...(now || ids.length ? ['$client'] : []), ...ids].flatMap((id) => chunks[id]?.js ?? [])
56
+ }
57
+
58
+ /**
59
+ * The route's stylesheets and those of every island on the page. An island is a dynamic import, so its CSS is not in the
60
+ * route's chunk graph; without this the server's HTML paints bare and the sheets arrive with the script.
61
+ */
62
+ export const pageSheets = (
63
+ css: { href: string }[] = [],
64
+ parts: { now: string[]; lazy: string[]; fold: string[] },
65
+ chunks: HandlerOptions['chunks'] = {},
66
+ ) => {
67
+ const found = [...parts.now, ...parts.lazy, ...parts.fold].flatMap((id) => chunks[id]?.css ?? [])
68
+ return [...new Map([...css, ...found].map((c) => [c.href, c])).values()]
69
+ }
70
+
71
+ export const saveData = (request: Request) =>
72
+ request.headers.get('save-data') === 'on' ||
73
+ request.headers.get('sec-ch-prefers-reduced-data') === 'reduce'
74
+
75
+ /** Where the first view ends, in px: past most laptops' and phones' first screen. */
76
+ const FOLD = 900
77
+
78
+ /**
79
+ * About how far down the page `html` runs out, in px. The server has no layout, so this counts what makes a page tall:
80
+ * blocks, and lines of their text. A wrong guess costs one chunk's fetch, either way: it's a preload, not a decision.
81
+ */
82
+ function depth(html: string) {
83
+ const plain = html.replace(/<(svg|style|template)\b[\s\S]*?<\/\1>|<!--[\s\S]*?-->/g, '')
84
+ const blocks =
85
+ plain.match(
86
+ /<(?:section|article|header|footer|h[1-6]|p|li|tr|img|form|pre|blockquote|video|figure)\b/g,
87
+ )?.length ?? 0
88
+ return blocks * 32 + (plain.replace(/<[^>]*>/g, '').length / 60) * 24
89
+ }
90
+
91
+ /** What a page's HTML says about its islands: those that load with it, those that wait, and the waiting ones in view. */
92
+ export function islandsOf(html: string) {
93
+ const known = renderedOf(html)
94
+ if (known.p) return known.p
95
+ const parts = { now: [] as string[], lazy: [] as string[], fold: [] as string[] }
96
+ let past = false
97
+ for (const m of html.matchAll(/<!--wi:(\[.*?\])-->/g)) {
98
+ const [id, , , when] = JSON.parse(m[1]!) as [string, string, unknown[], string?]
99
+ const list = when ? parts.lazy : parts.now
100
+ if (!list.includes(id)) list.push(id)
101
+ past ||= depth(html.slice(0, m.index)) >= FOLD
102
+ if (when && !past && !parts.fold.includes(id)) parts.fold.push(id)
103
+ }
104
+ return (known.p = parts)
105
+ }
106
+
107
+ export function modulepreloads(
108
+ chunks: { href: string }[],
109
+ assets: NonNullable<HandlerOptions['assets']>,
110
+ ) {
111
+ const hrefs = new Set(chunks.map((c) => c.href))
112
+ hrefs.delete(assets.entry!)
113
+ return [...hrefs].map((href) => `<link rel="modulepreload" href="${esc(href)}">`).join('')
114
+ }
115
+
116
+ /** What a render's HTML says about its levels, worked out as asked and kept by the exact text. */
117
+ interface Rendered {
118
+ h: Record<number, string>
119
+ x: Record<number, string>
120
+ p?: { now: string[]; lazy: string[]; fold: string[] }
121
+ }
122
+ const RENDERED_MAX = 64
123
+ const rendered = new Map<string, Rendered>()
124
+
125
+ function renderedOf(html: string) {
126
+ let r = rendered.get(html)
127
+ if (!r) {
128
+ if (rendered.size >= RENDERED_MAX) rendered.clear()
129
+ rendered.set(html, (r = { h: {}, x: {} }))
130
+ }
131
+ return r
132
+ }
133
+
134
+ /** A static level's HTML minus what its islands render: they refresh their own data, so a change there isn't the level's. */
135
+ export function outsideIslands(h: string) {
136
+ let out = '',
137
+ at = 0
138
+ for (;;) {
139
+ const i = h.indexOf('<!--wi:', at)
140
+ if (i < 0) return out + h.slice(at)
141
+ const open = h.indexOf('-->', i) + 3
142
+ out += h.slice(at, open)
143
+ at = open
144
+ if (!h.startsWith('<!--[-->', open)) continue
145
+ let nest = 0,
146
+ j = open
147
+ for (;;) {
148
+ const a = h.indexOf('<!--[-->', j),
149
+ b = h.indexOf('<!--]-->', j)
150
+ if (b < 0) return out + h.slice(at)
151
+ if (a >= 0 && a < b) {
152
+ nest++
153
+ j = a + 8
154
+ } else {
155
+ nest--
156
+ j = b + 8
157
+ if (!nest) break
158
+ }
159
+ }
160
+ at = j
161
+ }
162
+ }
163
+
164
+ export function withLevels(
165
+ payload: RoutePayload,
166
+ html: string,
167
+ statics: Set<string>,
168
+ sendHtml: boolean,
169
+ ): RoutePayload {
170
+ if (!payload.m.some((m) => statics.has(m.id))) return payload
171
+ const known = renderedOf(html)
172
+ const slice = (d: number) => {
173
+ const open = html.indexOf(`<!--wl:${d}:`)
174
+ const end = `<!--/wl:${d}-->`
175
+ const close = html.indexOf(end)
176
+ if (open < 0 || close < 0) return ''
177
+ const body = html.slice(html.indexOf('-->', open) + 3, close)
178
+ const kid = body.indexOf(`<!--wl:${d + 1}:`)
179
+ const tail = body.indexOf(`<!--/wl:${d + 1}-->`)
180
+ return kid < 0 || tail < 0
181
+ ? body
182
+ : body.slice(0, body.indexOf('-->', kid) + 3) + body.slice(tail)
183
+ }
184
+ const m = payload.m.map((lv, d) => {
185
+ if (!statics.has(lv.id)) return lv
186
+ const { data: _, ...rest } = lv
187
+ const h = (known.h[d] ??= slice(d))
188
+ return {
189
+ ...rest,
190
+ s: 1 as const,
191
+ x: (known.x[d] ??= hash(outsideIslands(h).replaceAll(' aria-current="page"', ''))),
192
+ ...(sendHtml && { h }),
193
+ }
194
+ })
195
+ const i = islandsOf(html).now
196
+ return { ...payload, m, ...(i.length && { i }) }
197
+ }
@@ -0,0 +1,192 @@
1
+ import { CLIENT_IP, decodeForm, StartError } from '../data'
2
+ import type { Scope } from '../exec'
3
+
4
+ /**
5
+ * Who sent the request. Without `trustProxy` it's the socket's address (Nitro's server sets `.ip`). Behind `n` proxies
6
+ * it's the `n`th address from the right of `X-Forwarded-For`: each proxy appends who it heard from, so the entries left
7
+ * of that are whatever the client wrote, and the socket is the nearest proxy itself.
8
+ */
9
+ export function clientIp(request: Request, trustProxy?: boolean | number): string | undefined {
10
+ const { ip } = request as Request & { ip?: string }
11
+ const hops = trustProxy === true ? 1 : trustProxy || 0
12
+ if (!hops) return ip
13
+ const chain = (request.headers.get('x-forwarded-for') ?? '')
14
+ .split(',')
15
+ .map((a) => a.trim())
16
+ .filter(Boolean)
17
+ return chain[chain.length - hops] ?? chain[0] ?? ip
18
+ }
19
+
20
+ /** The request with the client's address (`clientIp`) in CLIENT_IP, replacing any the client sent. */
21
+ export function stamped(request: Request, trustProxy?: boolean | number): Request {
22
+ const headers = new Headers(request.headers)
23
+ const ip = clientIp(request, trustProxy)
24
+ headers.delete(CLIENT_IP)
25
+ if (ip) headers.set(CLIENT_IP, ip)
26
+ // `new Request(request, …)` refuses the server's request wrapper; the parts are enough.
27
+ return new Request(request.url, {
28
+ method: request.method,
29
+ headers,
30
+ ...(request.body && { body: request.body, duplex: 'half' }),
31
+ })
32
+ }
33
+
34
+ /** The request's cookies for `persist: 'cookie'`, parsed on first read: a page with none pays nothing. */
35
+ export function cookieJar(request: Request) {
36
+ let jar: Map<string, string> | undefined
37
+ return {
38
+ get(name: string) {
39
+ jar ??= new Map(
40
+ (request.headers.get('cookie') ?? '')
41
+ .split(/;\s*/)
42
+ .map((c) => [c.slice(0, c.indexOf('=')), c.slice(c.indexOf('=') + 1)]),
43
+ )
44
+ return jar.get(name)
45
+ },
46
+ }
47
+ }
48
+
49
+ const refresh = (v: FormDataEntryValue | null) => (typeof v === 'string' ? v : '[]')
50
+
51
+ /** The multipart body `<Form>` sends when a form holds a file: the fields, and the refresh list in `$r`. */
52
+ export async function multipartBody(request: Request) {
53
+ const data = await request.formData()
54
+ return {
55
+ i: decodeForm(data),
56
+ f: JSON.parse(refresh(data.get('$r'))) as [string, unknown][],
57
+ c: 1 as const,
58
+ }
59
+ }
60
+
61
+ /** What a failed form's page gives back: no secrets (the HTML outlives the request) and no files. */
62
+ export function echoed(input: Record<string, unknown>): Record<string, unknown> {
63
+ const keep = (v: unknown): unknown =>
64
+ typeof v === 'string'
65
+ ? v
66
+ : Array.isArray(v)
67
+ ? v.filter((x) => typeof x === 'string')
68
+ : v && typeof v === 'object' && !(v instanceof Blob)
69
+ ? echoed(v as Record<string, unknown>)
70
+ : undefined
71
+ return Object.fromEntries(
72
+ Object.entries(input)
73
+ .filter(([k]) => !/pass|secret|token|card|cvv|cvc/i.test(k))
74
+ .map(([k, v]) => [k, keep(v)]),
75
+ )
76
+ }
77
+
78
+ /**
79
+ * The cookies and headers server functions set (`ctx.response.headers`), on the response. Cookies add up and `Vary`
80
+ * merges; any other header the app set replaces Kerf's default (a route's `cache-control` over `private, no-cache`).
81
+ */
82
+ export function withHeaders(res: Response, scope: Scope): Response {
83
+ for (const cookie of scope.headers.getSetCookie()) res.headers.append('set-cookie', cookie)
84
+ for (const [k, v] of scope.headers) {
85
+ if (k === 'set-cookie') continue
86
+ if (k !== 'vary') res.headers.set(k, v)
87
+ else {
88
+ const names = (res.headers.get('vary') ?? '')
89
+ .split(',')
90
+ .map((n) => n.trim())
91
+ .filter(Boolean)
92
+ for (const name of v.split(',').map((n) => n.trim()))
93
+ if (name && !names.some((n) => n.toLowerCase() === name.toLowerCase())) names.push(name)
94
+ res.headers.set('vary', names.join(', '))
95
+ }
96
+ }
97
+ return res
98
+ }
99
+
100
+ /** Merge scope headers, then replace metadata for the redirect's new response body. */
101
+ export function redirectBody(
102
+ res: Response,
103
+ scope: Scope,
104
+ type: string,
105
+ location?: string,
106
+ ): Response {
107
+ withHeaders(res, scope)
108
+ for (const name of [
109
+ 'content-length',
110
+ 'content-encoding',
111
+ 'content-range',
112
+ 'content-location',
113
+ 'content-language',
114
+ 'content-disposition',
115
+ 'transfer-encoding',
116
+ 'trailer',
117
+ 'accept-ranges',
118
+ 'etag',
119
+ 'last-modified',
120
+ 'digest',
121
+ 'content-digest',
122
+ 'repr-digest',
123
+ 'content-md5',
124
+ ])
125
+ res.headers.delete(name)
126
+ res.headers.set('content-type', type)
127
+ if (location === undefined) res.headers.delete('location')
128
+ else res.headers.set('location', location)
129
+ return res
130
+ }
131
+
132
+ /** Whether `If-None-Match` names `etag` (a list, weak `W/` forms and `*` included). No ETag never matches. */
133
+ export function etagMatches(request: Request, etag: string | null): boolean {
134
+ if (!etag) return false
135
+ const header = request.headers.get('if-none-match')
136
+ if (!header) return false
137
+ return header.split(',').some((candidate) => {
138
+ const tag = candidate.trim()
139
+ return tag === '*' || tag.replace(/^W\//, '') === etag.replace(/^W\//, '')
140
+ })
141
+ }
142
+
143
+ /** The default request body limits: JSON 1 MB, multipart (a form with files) 25 MB. `site.limits` changes them. */
144
+ export const LIMITS = { body: 1 << 20, upload: 25 << 20 }
145
+
146
+ /** The limit for this request's body under `site.limits`: multipart bodies get `upload`, others `body`. */
147
+ export function bodyLimit(
148
+ limits: { body?: number | undefined; upload?: number | undefined } | undefined,
149
+ request: Request,
150
+ ) {
151
+ const multipart = (request.headers.get('content-type') ?? '').startsWith('multipart/form-data')
152
+ return multipart ? (limits?.upload ?? LIMITS.upload) : (limits?.body ?? LIMITS.body)
153
+ }
154
+
155
+ const tooLarge = (max: number) =>
156
+ new StartError(
157
+ 'Q018',
158
+ `the request body is over ${max} bytes`,
159
+ 'send less, or raise `site.limits`',
160
+ {
161
+ status: 413,
162
+ },
163
+ )
164
+
165
+ /**
166
+ * The request with its body read up to `max` bytes: a declared `Content-Length` over it is refused before any is
167
+ * read, and a stream that runs past it is cancelled there (Q018, 413), so a huge body never sits in memory.
168
+ */
169
+ export async function limited(request: Request, max: number): Promise<Request> {
170
+ if (Number(request.headers.get('content-length')) > max) throw tooLarge(max)
171
+ if (!request.body) return request
172
+ const reader = request.body.getReader()
173
+ const chunks: Uint8Array[] = []
174
+ let total = 0
175
+ for (;;) {
176
+ const { done, value } = await reader.read()
177
+ if (done) break
178
+ total += value.byteLength
179
+ if (total > max) {
180
+ void reader.cancel()
181
+ throw tooLarge(max)
182
+ }
183
+ chunks.push(value)
184
+ }
185
+ const body = new Uint8Array(total)
186
+ let at = 0
187
+ for (const chunk of chunks) {
188
+ body.set(chunk, at)
189
+ at += chunk.byteLength
190
+ }
191
+ return new Request(request.url, { method: request.method, headers: request.headers, body })
192
+ }
@@ -0,0 +1,228 @@
1
+ import type { AsyncLocalStorage } from 'node:async_hooks'
2
+ import {
3
+ RouterCore,
4
+ createNonReactiveMutableStore,
5
+ createNonReactiveReadonlyStore,
6
+ isNotFound,
7
+ } from '@tanstack/router-core'
8
+ import { createMemoryHistory } from '@tanstack/history'
9
+ import { mergeMeta, type Merged, type Meta as MetaObject } from '@kerf-js/core/ssr'
10
+ import type { Component } from '../router'
11
+ import { StartError } from '../data'
12
+ import * as exec from '../exec'
13
+ import type { Scope } from '../exec'
14
+ import { cleanParams, type routeTree, type LoadContext } from './routes'
15
+ import { split, settledView } from './payload'
16
+ import type {
17
+ HandlerOptions,
18
+ LayoutEntry,
19
+ Level,
20
+ MetaSource,
21
+ Resolved,
22
+ RouteEntry,
23
+ RouteModule,
24
+ } from './types'
25
+
26
+ type RouterOptions = ConstructorParameters<typeof RouterCore>[0]
27
+ export interface ResolverDeps {
28
+ als: AsyncLocalStorage<Scope>
29
+ scopeOptions: Parameters<typeof exec.createScope>[1]
30
+ tree: ReturnType<typeof routeTree>
31
+ site: NonNullable<HandlerOptions['site']>
32
+ manifest: HandlerOptions['manifest']
33
+ byId: Map<string, RouteEntry>
34
+ mod: (file?: string) => RouteModule | undefined
35
+ comps: Record<string, Component>
36
+ options: HandlerOptions
37
+ originOf: (request: Request) => string | undefined
38
+ }
39
+ const stores = () => ({
40
+ createMutableStore: createNonReactiveMutableStore,
41
+ createReadonlyStore: createNonReactiveReadonlyStore,
42
+ batch: (f: () => void) => f(),
43
+ })
44
+ /** The origin a head's URLs are built on, or none. */
45
+ export function pointAt(head: Merged, origin: string | undefined) {
46
+ if (origin) head.url = origin
47
+ else delete head.url
48
+ }
49
+
50
+ export async function resolveRoute(
51
+ deps: ResolverDeps,
52
+ path: string,
53
+ request: Request,
54
+ ): Promise<Resolved> {
55
+ const { als, scopeOptions, tree } = deps
56
+ const scope = als.getStore() ?? exec.createScope(request, scopeOptions)
57
+ const hold: LoadContext = { request, scope, tags: new Map(), out: {} }
58
+ const router = new RouterCore(
59
+ {
60
+ routeTree: tree,
61
+ history: createMemoryHistory({ initialEntries: [path] }),
62
+ isServer: true,
63
+ context: hold,
64
+ } as RouterOptions,
65
+ stores,
66
+ )
67
+ // The page's `[...name]`, so its layouts see the catch-all under that name too (the loaders copy `hold` as they start).
68
+ hold.splat = (
69
+ router.getMatchedRoutes(router.latestLocation.pathname)[2] as
70
+ | { options: { kerf?: RouteEntry } }
71
+ | undefined
72
+ )?.options.kerf?.splat
73
+ await router.load()
74
+ return resolvedMatches(deps, router, hold, path, request)
75
+ }
76
+
77
+ function redirectOf(
78
+ deps: ResolverDeps,
79
+ router: InstanceType<typeof RouterCore>,
80
+ hold: LoadContext,
81
+ path: string,
82
+ ): Resolved | undefined {
83
+ const native =
84
+ router._serverResult?.type === 'redirect' ? router._serverResult.redirect : undefined
85
+ const href = native?.headers.get('location')
86
+ const goes =
87
+ hold.out.redirect ??
88
+ (native && href ? { isRedirect: true as const, href, status: native.status } : undefined)
89
+ if (!goes) return undefined
90
+ return {
91
+ status: goes.status,
92
+ path,
93
+ levels: [],
94
+ head: mergeMeta(deps.site),
95
+ redirect: goes,
96
+ ...(!hold.out.redirect && native ? { redirectHeaders: native.headers } : {}),
97
+ }
98
+ }
99
+
100
+ async function resolvedMatches(
101
+ deps: ResolverDeps,
102
+ router: InstanceType<typeof RouterCore>,
103
+ hold: LoadContext,
104
+ path: string,
105
+ request: Request,
106
+ ): Promise<Resolved> {
107
+ const { manifest, byId, mod, comps, options } = deps
108
+ const redirected = redirectOf(deps, router, hold, path)
109
+ if (redirected) return redirected
110
+ const matches = router.state.matches.map((m) => ({
111
+ m,
112
+ kerf: (router.routesById as Record<string, { options: { kerf?: RouteEntry | LayoutEntry } }>)[
113
+ m.routeId
114
+ ]?.options.kerf,
115
+ }))
116
+ const params = (m: { params: Record<string, unknown> }, splat?: string) =>
117
+ cleanParams(m.params, splat)
118
+ const leaf = matches.at(-1)?.kerf
119
+ const route = leaf && 'kind' in leaf ? leaf : undefined
120
+ const failed = matches.find((x) => x.m.status === 'error')
121
+ const missing = !route || matches.some((x) => x.m.status === 'notFound' || isNotFound(x.m.error))
122
+ const rootLayout = manifest.layouts.find((l) => l.dir === '')
123
+ const rootOk =
124
+ rootLayout && matches[0]?.kerf === rootLayout && matches[0].m.status === 'success'
125
+ ? matches[0]
126
+ : undefined
127
+ const levelOf = (x: (typeof matches)[number]): Level => {
128
+ const raw = x.m.loaderData
129
+ const t = hold.tags.get(x.kerf!.file)
130
+ return {
131
+ id: x.kerf!.id,
132
+ params: params(x.m, hold.splat),
133
+ mod: mod(x.kerf!.file),
134
+ raw,
135
+ ...split(raw),
136
+ ...(t?.size && { t: [...t] }),
137
+ }
138
+ }
139
+ const special = (id: '404' | 'error', status: number, error?: unknown): Promise<Resolved> => {
140
+ const entry = byId.get(id)
141
+ if (error instanceof StartError && error.code)
142
+ options.onDiagnostic?.({ code: error.code, severity: 'error', message: error.message })
143
+ const shown =
144
+ id === 'error'
145
+ ? {
146
+ status,
147
+ message:
148
+ options.dev && error instanceof Error ? error.message : 'Something went wrong.',
149
+ }
150
+ : { path }
151
+ const levels: Level[] = [
152
+ ...(rootOk && !(failed && failed === rootOk) ? [levelOf(rootOk)] : []),
153
+ { id, params: {}, data: shown, raw: shown, mod: mod(entry?.file) },
154
+ ]
155
+ if (entry && mod(entry.file)?.default) comps[id] = mod(entry.file)!.default!
156
+ return finish(levels, status, undefined, error)
157
+ }
158
+ const finish = (shown: Level[], status: number, matched?: RouteEntry, error?: unknown) =>
159
+ finishResolution(deps, { path, request }, { shown, status, matched, error })
160
+
161
+ if (failed) {
162
+ const e = exec.dbError(failed.m.error)
163
+ return special('error', (e as { code?: string } | null)?.code === 'Q016' ? 503 : 500, e)
164
+ }
165
+ if (missing) return special('404', 404)
166
+ const levels = matches.filter((x) => x.kerf).map(levelOf)
167
+ try {
168
+ return await finish(levels, 200, route)
169
+ } catch (e) {
170
+ if (isNotFound(e)) return special('404', 404)
171
+ return special('error', 500, e)
172
+ }
173
+ }
174
+
175
+ export async function finishResolution(
176
+ deps: ResolverDeps,
177
+ { path, request }: { path: string; request: Request },
178
+ {
179
+ shown,
180
+ status,
181
+ matched,
182
+ error,
183
+ }: {
184
+ shown: Level[]
185
+ status: number
186
+ matched?: RouteEntry | undefined
187
+ error?: unknown
188
+ },
189
+ ): Promise<Resolved> {
190
+ const { site, options, originOf } = deps
191
+ const metas: MetaObject[] = []
192
+ const source: MetaSource = {
193
+ title: site.name ? 'config' : 'none',
194
+ description: site.description ? 'config' : 'none',
195
+ image: 'none',
196
+ }
197
+ for (const lv of shown) {
198
+ const m =
199
+ lv.mod?.meta ??
200
+ (lv.id === '404'
201
+ ? { title: 'Not found' }
202
+ : lv.id === 'error'
203
+ ? { title: 'Error' }
204
+ : undefined)
205
+ if (!m) continue
206
+ const value =
207
+ typeof m === 'function'
208
+ ? await m({ params: lv.params, data: settledView(lv.raw, lv.d, lv.id, options) })
209
+ : m
210
+ metas.push(value)
211
+ const who = lv === shown.at(-1) ? 'route' : 'layout'
212
+ if (value?.title != null) source.title = who
213
+ if (value?.description != null) source.description = who
214
+ }
215
+ const resolved: Resolved = {
216
+ status,
217
+ path,
218
+ levels: shown,
219
+ head: mergeMeta(site, ...metas),
220
+ route: matched,
221
+ error,
222
+ metas,
223
+ source,
224
+ origin: originOf(request),
225
+ }
226
+ pointAt(resolved.head, resolved.origin)
227
+ return resolved
228
+ }