@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,96 @@
1
+ import { mergeMeta, type Merged } from '@kerf-js/core/ssr'
2
+ import { pageText } from '../derive.mjs'
3
+ import { pointAt } from './resolver'
4
+ import { cardPath, hash } from './text'
5
+ import type {
6
+ HandlerOptions,
7
+ Level,
8
+ Manifest,
9
+ MetaSource,
10
+ Resolved,
11
+ RouteEntry,
12
+ RouteModule,
13
+ } from './types'
14
+
15
+ /** Whether a title or description can come from the page itself. */
16
+ export const leftToPage = (s: MetaSource['title']) => s === 'config' || s === 'none'
17
+
18
+ /** Complete a head from the metadata and the rendered page. */
19
+ export function makeComplete(
20
+ options: HandlerOptions,
21
+ manifest: Manifest,
22
+ site: NonNullable<HandlerOptions['site']>,
23
+ mod: (file?: string) => RouteModule | undefined,
24
+ CARD: { width: number; height: number },
25
+ ) {
26
+ /**
27
+ * The content hash of a generated card: what it draws. The built-in card reads the head and the site's look and
28
+ * nothing else, so a loader's timestamp can't change its URL; an `.og.tsx` also gets the page's data.
29
+ */
30
+ function cardUrl(route: RouteEntry, levels: Level[], head: Merged, path: string) {
31
+ const card = route.card ?? manifest.defaultCard
32
+ const size = mod(card)?.size ?? CARD
33
+ const { image: _, ...graph } = head.og
34
+ const leaf = levels.at(-1)!
35
+ const v = hash(
36
+ [
37
+ options.build ?? '',
38
+ card ?? 'builtin',
39
+ JSON.stringify(size),
40
+ JSON.stringify({ ...head, og: graph }),
41
+ JSON.stringify(site.card ?? null),
42
+ card ? JSON.stringify(leaf.data ?? null) : '',
43
+ ].join('\0'),
44
+ )
45
+ return `/_kerf/og/${cardPath(path)}.png?v=${v}`
46
+ }
47
+
48
+ /**
49
+ * The rest of the head, once the page's HTML can speak for it (research 20 §10): a level that set no title or
50
+ * description gets the page's own, under anything a layout or the route wrote, and `image: 'auto'` becomes the
51
+ * card, whose URL hashes the text it shows. Called once per request, before anything is written.
52
+ */
53
+ return function complete(r: Resolved, html?: string) {
54
+ if (!r.metas || !r.source) return r.head
55
+ const { metas, source } = r
56
+ r.metas = undefined
57
+ const left = leftToPage(source.title) || leftToPage(source.description)
58
+ const words = left && r.status === 200 && html ? pageText(html) : {}
59
+ const title = leftToPage(source.title) ? words.title : undefined
60
+ const description = leftToPage(source.description) ? words.description : undefined
61
+ if (title) source.title = 'auto'
62
+ if (description) source.description = 'auto'
63
+ const head = (r.head = mergeMeta(
64
+ site,
65
+ { ...(title !== undefined && { title }), ...(description !== undefined && { description }) },
66
+ ...metas,
67
+ ))
68
+ pointAt(head, r.origin)
69
+ if (
70
+ head.jsonLd === undefined &&
71
+ r.route?.pattern === '/' &&
72
+ r.status === 200 &&
73
+ r.origin &&
74
+ site.name
75
+ )
76
+ head.jsonLd = {
77
+ '@context': 'https://schema.org',
78
+ '@type': 'WebSite',
79
+ name: site.name,
80
+ url: r.origin,
81
+ ...(site.description && { description: site.description }),
82
+ }
83
+ if (head.og.image === 'auto') {
84
+ const showing = r.status === 200 && r.route
85
+ if (showing)
86
+ head.og.image = {
87
+ url: cardUrl(r.route!, r.levels, head, r.path),
88
+ ...CARD,
89
+ alt: head.og.title ?? head.title,
90
+ }
91
+ else delete head.og.image
92
+ if (showing) source.image = r.route!.card || manifest.defaultCard ? 'card' : 'auto'
93
+ } else if (head.og.image) source.image = 'explicit'
94
+ return head
95
+ }
96
+ }
@@ -0,0 +1,36 @@
1
+ import { handles } from '../db/core'
2
+ import { liveHealth } from '../hub'
3
+
4
+ const LIMIT_MS = 2000
5
+
6
+ /** One database's answer: up, with how long `select 1` took, or down with why. */
7
+ async function probe(handle: { dialect: string; ping?: () => Promise<unknown> }) {
8
+ if (!handle.ping) return { dialect: handle.dialect, ok: true }
9
+ const started = performance.now()
10
+ try {
11
+ let timer: ReturnType<typeof setTimeout> | undefined
12
+ const late = new Promise((_, no) => {
13
+ timer = setTimeout(() => no(new Error(`no answer in ${LIMIT_MS} ms`)), LIMIT_MS)
14
+ })
15
+ await Promise.race([handle.ping(), late]).finally(() => clearTimeout(timer))
16
+ return { dialect: handle.dialect, ok: true, ms: Math.round(performance.now() - started) }
17
+ } catch (e) {
18
+ return { dialect: handle.dialect, ok: false, error: e instanceof Error ? e.message : String(e) }
19
+ }
20
+ }
21
+
22
+ /**
23
+ * `/_kerf/health`, for a load balancer or uptime check: 200 when every database answers and live data is delivered
24
+ * as required, 503 otherwise, with what each part said. It runs before migrations, so a failed one still reports.
25
+ */
26
+ export async function health(dev: boolean | undefined): Promise<Response> {
27
+ const db = await Promise.all([...handles].map(probe))
28
+ const live = liveHealth()
29
+ const ok = db.every((d) => d.ok) && live.ok
30
+ // A database's error can name its host: production says only that it's down.
31
+ const shown = dev ? db : db.map(({ error: _error, ...d }) => d)
32
+ return Response.json(
33
+ { ok, db: shown, live: { ok: live.ok, mode: live.mode } },
34
+ { status: ok ? 200 : 503, headers: { 'cache-control': 'no-store' } },
35
+ )
36
+ }
@@ -0,0 +1,112 @@
1
+ import {
2
+ backoff as defaultBackoff,
3
+ jobsState,
4
+ type JobDefs,
5
+ type Jobs,
6
+ type Queue,
7
+ type QueuedJob,
8
+ } from '../jobs'
9
+ import { errorText, inScope, type BackgroundDeps } from './background'
10
+
11
+ type Report = BackgroundDeps['scopeOptions']['onDiagnostic']
12
+
13
+ /** Runs one claimed job, then marks it done, due again after its backoff (J003), or dead (J004). */
14
+ function settler(defs: JobDefs, queue: Queue, deps: BackgroundDeps) {
15
+ const report: Report = deps.scopeOptions.onDiagnostic
16
+ const dead = async (job: QueuedJob, why: string) => {
17
+ await queue.fail(job, why)
18
+ report?.({
19
+ code: 'J004',
20
+ severity: 'error',
21
+ message: `J004: job \`${job.name}\` (${job.id}) is dead: ${why}`,
22
+ })
23
+ }
24
+ return async (job: QueuedJob) => {
25
+ const def = defs[job.name]
26
+ const retries = def?.retries ?? 5
27
+ // A job no definition names (renamed, removed), or one whose leases ran out as often as its retries: a process
28
+ // died running it every time.
29
+ if (!def) return dead(job, 'no job by that name is defined')
30
+ if (job.attempt > retries + 1) return dead(job, 'its process stopped on every attempt')
31
+ try {
32
+ await inScope(deps, `/_kerf/jobs/${encodeURIComponent(job.name)}`, (ctx) =>
33
+ def.run({ ctx, input: job.input, id: job.id, name: job.name, attempt: job.attempt }),
34
+ )
35
+ await queue.done(job)
36
+ } catch (e) {
37
+ const error = errorText(e)
38
+ if (job.attempt > retries)
39
+ return dead(job, `out of retries after ${job.attempt} attempts: ${error}`)
40
+ const wait = (def.backoff ?? defaultBackoff)(job.attempt)
41
+ await queue.retry(job, Date.now() + wait)
42
+ report?.({
43
+ code: 'J003',
44
+ severity: 'warning',
45
+ message: `J003: job \`${job.name}\` (${job.id}) failed attempt ${job.attempt}, retrying in ${Math.round(wait / 1000)}s: ${error}`,
46
+ })
47
+ }
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Works the app's job queue: claims what's due (up to `concurrency` at once) and runs each with the app's `ctx`. A
53
+ * shared queue is polled; the memory queue also wakes the runner when a job is added. The returned function stops
54
+ * claiming and resolves when the jobs running have finished.
55
+ */
56
+ export function startJobs(jobs: Jobs, deps: BackgroundDeps): () => Promise<void> {
57
+ const state = jobsState(jobs)
58
+ if (!state) return () => Promise.resolve()
59
+ const { defs, queue, runner } = state
60
+ const concurrency = runner.concurrency ?? 4
61
+ const lease = runner.lease ?? 5 * 60_000
62
+ const poll = runner.poll ?? 1000
63
+ const settle = settler(defs, queue, deps)
64
+ const running = new Set<Promise<void>>()
65
+ const failed = (e: unknown) =>
66
+ deps.scopeOptions.onDiagnostic?.({
67
+ code: 'J004',
68
+ severity: 'error',
69
+ message: `J004: the job queue failed: ${errorText(e)}`,
70
+ })
71
+ const live = { stopped: false, claiming: false }
72
+ let timer: ReturnType<typeof setTimeout> | undefined
73
+
74
+ const start = (job: QueuedJob) => {
75
+ const p: Promise<void> = settle(job)
76
+ .catch(failed)
77
+ .finally(() => {
78
+ running.delete(p)
79
+ void tick()
80
+ })
81
+ running.add(p)
82
+ }
83
+ const tick = async () => {
84
+ if (live.stopped || live.claiming) return
85
+ live.claiming = true
86
+ clearTimeout(timer)
87
+ try {
88
+ for (;;) {
89
+ const room = concurrency - running.size
90
+ if (live.stopped || room <= 0) break
91
+ const claimed = await queue.claim(Date.now(), lease, room)
92
+ if (!claimed.length) break
93
+ claimed.forEach(start)
94
+ }
95
+ } catch (e) {
96
+ failed(e)
97
+ } finally {
98
+ live.claiming = false
99
+ if (!live.stopped) {
100
+ timer = setTimeout(() => void tick(), poll)
101
+ ;(timer as { unref?: () => void }).unref?.() // the queue never keeps a process alive by itself
102
+ }
103
+ }
104
+ }
105
+ queue.onPush?.(() => void tick())
106
+ void tick()
107
+ return async () => {
108
+ live.stopped = true
109
+ clearTimeout(timer)
110
+ await Promise.allSettled([...running])
111
+ }
112
+ }
@@ -0,0 +1,48 @@
1
+ import * as exec from '../exec'
2
+ import type { Scope } from '../exec'
3
+ import { hub } from '../hub'
4
+ import { startCron } from './cron'
5
+ import { startJobs } from './jobs'
6
+ import type { makeServices } from './services'
7
+ import { onShutdown } from './shutdown'
8
+ import type { HandlerOptions } from './types'
9
+
10
+ /** The options with an `onDiagnostic` that names the request each diagnostic came from. */
11
+ export function withRequestIds(
12
+ options: HandlerOptions,
13
+ current: () => string | undefined,
14
+ ): HandlerOptions {
15
+ const report = options.onDiagnostic
16
+ if (!report) return options
17
+ return { ...options, onDiagnostic: (d) => report({ ...d, requestId: d.requestId ?? current() }) }
18
+ }
19
+
20
+ /**
21
+ * What a serving process starts besides answering requests: the cron schedule and the job queue, and on shutdown,
22
+ * stopping both (letting running jobs finish) and closing realtime connections. A build, and `kerf routes --meta`, load the server to read it, not to run it.
23
+ */
24
+ export function lifecycle(
25
+ options: HandlerOptions,
26
+ services: ReturnType<typeof makeServices>,
27
+ enter: (scope: Scope, run: () => Promise<void>) => Promise<void>,
28
+ ) {
29
+ if (process.env.KERF_BUILD || options.requestOrigin === false) return
30
+ const deps = {
31
+ scopeOptions: services.scopeOptions,
32
+ store: options.store ?? exec.defaultStore,
33
+ boot: async () => {
34
+ await services.loadExtensions()
35
+ await services.boot()
36
+ },
37
+ origin: (options.site?.url ?? 'http://localhost').replace(/\/$/, ''),
38
+ enter,
39
+ }
40
+ const stopCron = options.cron && startCron(options.cron, deps)
41
+ const stopJobs = options.jobs && startJobs(options.jobs, deps)
42
+ if (!options.dev)
43
+ onShutdown(async () => {
44
+ stopCron?.()
45
+ // Realtime goes first: open pages move to another instance while the jobs running here finish.
46
+ await Promise.all([hub().shutdown(), stopJobs?.()])
47
+ })
48
+ }
@@ -0,0 +1,42 @@
1
+ import type { Site } from '@kerf-js/core/ssr'
2
+
3
+ /** One diagnostic as the server reports it: what `onDiagnostic` receives. */
4
+ export interface Diagnostic {
5
+ code: string
6
+ severity: string
7
+ message: string
8
+ route?: string
9
+ /** The request it came from (`x-request-id` on that response), when it came from one. */
10
+ requestId?: string | undefined
11
+ }
12
+
13
+ /**
14
+ * The server log: one line per diagnostic on stderr. `site.log: 'json'` writes JSON objects (time, level, code, message,
15
+ * route, requestId) for a log collector; the default is a line a person reads.
16
+ */
17
+ export function serverLog(site: Site | undefined): (d: Diagnostic) => void {
18
+ if (site?.log === 'json')
19
+ return (d) =>
20
+ console.warn(
21
+ JSON.stringify({
22
+ time: new Date().toISOString(),
23
+ level: d.severity,
24
+ code: d.code,
25
+ message: d.message.replace(/^[A-Z]{1,3}\d{3}:? /, ''),
26
+ ...(d.route && { route: d.route }),
27
+ ...(d.requestId && { requestId: d.requestId }),
28
+ }),
29
+ )
30
+ return (d) =>
31
+ console.warn(
32
+ `[kerf] ${d.code} ${d.severity}${d.route ? ` (${d.route})` : ''}${d.requestId ? ` [${d.requestId}]` : ''}: ${d.message.replace(/^[A-Z]{1,3}\d{3}:? /, '')}`,
33
+ )
34
+ }
35
+
36
+ const GIVEN = /^[\w.:-]{1,128}$/
37
+
38
+ /** The request's id: a proxy's `x-request-id` when `site.trustProxy` says one is in front, else a fresh one. */
39
+ export function requestIdOf(request: Request, site: Site | undefined): string {
40
+ const given = request.headers.get('x-request-id')
41
+ return site?.trustProxy && given && GIVEN.test(given) ? given : crypto.randomUUID()
42
+ }
@@ -0,0 +1,61 @@
1
+ import type { HandlerOptions } from './types'
2
+ import type { MediaServer } from '../exec'
3
+ import { etagMatches } from './request'
4
+ export function makeMedia(
5
+ options: HandlerOptions,
6
+ mediaServer: () => Promise<MediaServer> | undefined,
7
+ ) {
8
+ /** `/_kerf/m/<hash>/<width>.<fmt>` (research 29 §6): content-addressed, so cached for good; `auto` varies on `Accept`. */
9
+ return async function media(url: URL, request: Request): Promise<Response> {
10
+ const m = /^\/_kerf\/m\/([0-9a-f]{32})\/(\d+)\.([a-z0-9]+)$/.exec(url.pathname)
11
+ const server = await mediaServer()
12
+ if (!server)
13
+ options.onDiagnostic?.({
14
+ code: 'M017',
15
+ severity: 'error',
16
+ message:
17
+ 'M017: a media URL was requested, but nothing provides `media.server`. Add `media()` from `@kerf-js/media` to `plugins`',
18
+ })
19
+ const out =
20
+ m &&
21
+ (await server?.serve({
22
+ hash: m[1]!,
23
+ width: Number(m[2]),
24
+ format: m[3]!,
25
+ accept: request.headers.get('accept') ?? '',
26
+ }))
27
+ if (!out) return new Response('Not found', { status: 404 })
28
+ const headers = new Headers({
29
+ 'content-type': out.type,
30
+ 'cache-control': 'public, max-age=31536000, immutable',
31
+ etag: `"${m[1]}-${out.width}-${out.format}"`,
32
+ 'x-content-type-options': 'nosniff',
33
+ })
34
+ if (out.negotiated) headers.set('vary', 'Accept')
35
+ if (out.type === 'image/svg+xml')
36
+ headers.set(
37
+ 'content-security-policy',
38
+ "default-src 'none'; style-src 'unsafe-inline'; sandbox",
39
+ )
40
+ if (out.temporary) {
41
+ // The original, standing in for a rung still encoding.
42
+ headers.set('cache-control', 'no-store')
43
+ headers.delete('etag')
44
+ }
45
+ if (etagMatches(request, headers.get('etag')))
46
+ return new Response(null, { status: 304, headers })
47
+ const range =
48
+ /^(video|audio)\//.test(out.type) &&
49
+ /^bytes=(\d+)-(\d*)$/.exec(request.headers.get('range') ?? '')
50
+ if (!range) return new Response(out.bytes as BodyInit, { headers })
51
+ const start = Number(range[1])
52
+ const end = Math.min(range[2] ? Number(range[2]) : Infinity, out.bytes.length - 1)
53
+ if (start > end)
54
+ return new Response(null, {
55
+ status: 416,
56
+ headers: { 'content-range': `bytes */${out.bytes.length}` },
57
+ })
58
+ headers.set('content-range', `bytes ${start}-${end}/${out.bytes.length}`)
59
+ return new Response(out.bytes.subarray(start, end + 1) as BodyInit, { status: 206, headers })
60
+ }
61
+ }
@@ -0,0 +1,75 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { etagMatches } from './request'
3
+
4
+ /** Prevent retention of a route response. */
5
+ export function noRetention(response: Response): Response {
6
+ response.headers.set('cache-control', 'no-store')
7
+ response.headers.delete('etag')
8
+ return response
9
+ }
10
+
11
+ function cacheDirectives(policy: string): string[] | undefined {
12
+ const parts: string[] = []
13
+ let start = 0
14
+ let quoted = false
15
+ let escaped = false
16
+ for (let i = 0; i < policy.length; i++) {
17
+ const char = policy[i]
18
+ if (escaped) escaped = false
19
+ else if (quoted && char === '\\') escaped = true
20
+ else if (char === '"') quoted = !quoted
21
+ else if (char === ',' && !quoted) {
22
+ parts.push(policy.slice(start, i).trim())
23
+ start = i + 1
24
+ }
25
+ }
26
+ if (quoted || escaped) return undefined
27
+ parts.push(policy.slice(start).trim())
28
+ return parts.filter(Boolean)
29
+ }
30
+
31
+ /** Validate only the final, authorized route representation. */
32
+ export function validateNavigation(
33
+ response: Response,
34
+ request: Request,
35
+ body: string,
36
+ build: string | undefined,
37
+ status: number,
38
+ ): Response {
39
+ const headers = response.headers
40
+ const policy = headers.get('cache-control') ?? ''
41
+ const directives = cacheDirectives(policy)
42
+ if (!directives) return noRetention(response)
43
+ const noStore = directives.some((part) => /^no-store(?:\s*=|$)/i.test(part))
44
+ if (status < 200 || status >= 300 || headers.has('set-cookie') || noStore) {
45
+ if (noStore) {
46
+ headers.delete('etag')
47
+ return response
48
+ }
49
+ return noRetention(response)
50
+ }
51
+
52
+ const kept = directives.filter((part) => !/^(public|max-age)(?:\s*=|$)/i.test(part))
53
+ // A bare private directive protects the entire response, including unlisted fields.
54
+ const barePrivate = kept.some((part) => /^private$/i.test(part))
55
+ if (!barePrivate) kept.unshift('private')
56
+ kept.splice(1, 0, 'max-age=0')
57
+ if (!policy) kept.push('stale-while-revalidate=30')
58
+ headers.set('cache-control', kept.join(', '))
59
+ const vary = headers.get('vary')
60
+ if (vary !== '*') {
61
+ const names = (vary ?? '')
62
+ .split(',')
63
+ .map((name) => name.trim())
64
+ .filter(Boolean)
65
+ for (const name of ['Accept', 'Cookie', 'Authorization'])
66
+ if (!names.some((existing) => existing.toLowerCase() === name.toLowerCase())) names.push(name)
67
+ headers.set('vary', names.join(', '))
68
+ }
69
+ const tag = `"${createHash('sha256')
70
+ .update(JSON.stringify([build ?? '', body]))
71
+ .digest('hex')}"`
72
+ headers.set('etag', tag)
73
+ if (etagMatches(request, tag)) return new Response(null, { status: 304, headers })
74
+ return response
75
+ }
@@ -0,0 +1,86 @@
1
+ import { renderToStringAsync } from '@kerf-js/core/ssr'
2
+ import type { Merged } from '@kerf-js/core/ssr'
3
+ import type { RoutePayload, createRouteState } from '../router'
4
+ import * as exec from '../exec'
5
+ import type { Scope } from '../exec'
6
+ import { App } from '../view'
7
+ import { withLevels } from './render'
8
+ import { payloadOf, wire } from './payload'
9
+ import { noRetention, validateNavigation } from './navigation-cache'
10
+ import { cookieJar, redirectBody, withHeaders } from './request'
11
+ import type { HandlerOptions, Resolved } from './types'
12
+ export function makeNavigation({
13
+ resolve,
14
+ finished,
15
+ statics,
16
+ stateOf,
17
+ PASSES,
18
+ options,
19
+ }: {
20
+ resolve: (path: string, request: Request) => Promise<Resolved>
21
+ finished: (r: Resolved, request: Request) => Promise<Merged>
22
+ statics: Set<string>
23
+ stateOf: (r: Resolved, payload: RoutePayload) => ReturnType<typeof createRouteState>
24
+ PASSES: number
25
+ options: HandlerOptions
26
+ }) {
27
+ /** The route as JSON for client navigation, with deferred fields awaited. */
28
+ return async function data(path: string, request: Request, scope: Scope): Promise<Response> {
29
+ // Loads see the page's own URL, as on a full load, not `/_kerf/data/<path>`: method, headers and signal carry over.
30
+ const r = await resolve(path, new Request(new URL(path, request.url), request))
31
+ if (r.redirect) {
32
+ const headers = new Headers(r.redirectHeaders)
33
+ headers.delete('location')
34
+ headers.set('cache-control', 'no-store')
35
+ return noRetention(
36
+ redirectBody(
37
+ Response.json(
38
+ { m: [], p: path, s: r.redirect.status, r: r.redirect.href } satisfies RoutePayload,
39
+ { headers },
40
+ ),
41
+ scope,
42
+ 'application/json',
43
+ ),
44
+ )
45
+ }
46
+ for (const lv of r.levels)
47
+ if (lv.d?.length)
48
+ lv.data = {
49
+ ...(lv.data as object),
50
+ ...Object.fromEntries(
51
+ await Promise.all(
52
+ lv.d.map(async (k) => [k, await (lv.raw as Record<string, unknown>)[k]]),
53
+ ),
54
+ ),
55
+ }
56
+ await finished(r, request)
57
+ const c = wire(scope)
58
+ let payload = payloadOf(r, true, options)
59
+ if (r.levels.some((lv) => statics.has(lv.id))) {
60
+ const route = stateOf(r, payload)
61
+ const out = await renderToStringAsync(() => <App route={route} />, {
62
+ passes: PASSES,
63
+ shown: (e) => exec.shown(e, scope),
64
+ app: { cookies: cookieJar(request) },
65
+ })
66
+ const at = out.lastIndexOf('<script type="application/json" data-kerf>')
67
+ payload = {
68
+ ...withLevels(payload, at < 0 ? out : out.slice(0, at), statics, true),
69
+ ...(at >= 0 && {
70
+ b: JSON.parse(
71
+ out
72
+ .slice(at)
73
+ .replace(/^<[^>]*>/, '')
74
+ .replace(/<\/script>$/, ''),
75
+ ),
76
+ }),
77
+ }
78
+ }
79
+ const body = JSON.stringify({ ...payload, ...(c.length && { c }) })
80
+ const response = withHeaders(
81
+ new Response(body, { headers: { 'content-type': 'application/json' } }),
82
+ scope,
83
+ )
84
+ return validateNavigation(response, request, body, options.build, r.error ? 500 : r.status)
85
+ }
86
+ }
@@ -0,0 +1,96 @@
1
+ // Render first when no remembered head can be sent yet.
2
+ import { LAYER_ORDER, pageStyles, type keptSheets } from '../inline.mjs'
3
+ import { capture, speculate } from '../capture'
4
+ import { whole } from './compression'
5
+ import { withHeaders } from './request'
6
+ import { esc } from './text'
7
+ import { finish, pageShell, render, rest, shaped, table, top } from './page-stream'
8
+ import { HOLD, type Head, type PageState } from './page-types'
9
+
10
+ type Styles = ReturnType<typeof pageStyles>
11
+ type Shape = ReturnType<typeof shaped>
12
+ type Table = ReturnType<typeof table>
13
+
14
+ function coldHead(
15
+ p: PageState,
16
+ shape: Shape,
17
+ t: Table,
18
+ styles: Styles | undefined,
19
+ capturing: boolean,
20
+ ) {
21
+ return (
22
+ top(p) +
23
+ shape.preloads +
24
+ // A streamed page's entry is at the end of what the shell sends, so its script tag is found late.
25
+ (p.assets.entry && shape.streaming
26
+ ? `<link rel="modulepreload" href="${esc(p.assets.entry)}">\n`
27
+ : '') +
28
+ (t
29
+ ? `<style>${LAYER_ORDER}${p.assets.pieces!.layers}${t.rules(p.stream.shell)}</style>\n`
30
+ : styles!.head) +
31
+ (capturing ? `<script>${capture(shape.now)}</script>\n` + speculate(shape) : '') +
32
+ p.dev +
33
+ (p.assets.entry && !shape.streaming
34
+ ? `<script type="module" src="${esc(p.assets.entry)}"></script>\n`
35
+ : '') +
36
+ '</head>\n<body>\n' +
37
+ pageShell(p, shape, t ? t.links : '')
38
+ )
39
+ }
40
+
41
+ /** Render first and send the head and shell together. */
42
+ export async function coldPage(
43
+ p: PageState,
44
+ known: Head | null | undefined,
45
+ cold: string,
46
+ kept: ReturnType<typeof keptSheets>,
47
+ ) {
48
+ const t0 = performance.now()
49
+ p.stream = render(p)
50
+ await p.stream.settle() // queries read outside a Boundary have nowhere to stream to
51
+ await p.stream.hold(p.options.hold ?? HOLD)
52
+ const ms = performance.now() - t0
53
+ p.complete(p.r, p.stream.shell)
54
+ const shape = shaped(p)
55
+ const t = table(p, shape)
56
+ const styles = t
57
+ ? undefined
58
+ : pageStyles(p.assets, shape.sheets, p.stream.shell, {
59
+ head: p.site.head,
60
+ have: kept,
61
+ keep: p.request.headers.has('cookie'),
62
+ })
63
+ const capturing = !!p.options.lazy || shape.streaming
64
+ if (known !== null && !p.options.dev)
65
+ p.remember(styles?.links ? cold + ' w' : cold, {
66
+ ...shape,
67
+ ms,
68
+ split: styles?.split ?? false,
69
+ found: styles?.found() ?? new Set(),
70
+ capture: capturing,
71
+ fold: !!shape.parts.fold.length,
72
+ })
73
+ const head = coldHead(p, shape, t, styles, capturing)
74
+ const init = {
75
+ status: p.status,
76
+ headers: {
77
+ 'content-type': 'text/html; charset=utf-8',
78
+ // Never stored by a shared cache: the page can carry the signed-in user. A route's own header replaces it.
79
+ 'cache-control': 'private, no-cache',
80
+ ...(shape.parts.fold.length && { vary: 'Save-Data, Sec-CH-Prefers-Reduced-Data' }),
81
+ },
82
+ }
83
+ // No Boundary is waiting, so there's nothing to stream: the page goes out in one piece.
84
+ if (!shape.streaming) {
85
+ const res = new Response(null, init)
86
+ whole.set(res, head + (await finish(p, false)))
87
+ return withHeaders(res, p.scope)
88
+ }
89
+ const body = new ReadableStream<Uint8Array>({
90
+ async start(controller) {
91
+ controller.enqueue(p.enc.encode(head))
92
+ await rest(p, { controller, styles: t || styles!, streaming: true })
93
+ },
94
+ })
95
+ return withHeaders(new Response(body, init), p.scope)
96
+ }