@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.
- package/LICENSE +16 -0
- package/README.md +1468 -2
- package/crate/Cargo.lock +1347 -0
- package/crate/Cargo.toml +72 -0
- package/crate/README.md +322 -0
- package/crate/rust-toolchain.toml +3 -0
- package/crate/src/build/emit.rs +103 -0
- package/crate/src/build.rs +367 -0
- package/crate/src/ctx.rs +186 -0
- package/crate/src/envelope.rs +163 -0
- package/crate/src/functions.rs +173 -0
- package/crate/src/lib.rs +118 -0
- package/crate/src/native.rs +212 -0
- package/crate/src/otel.rs +62 -0
- package/crate/src/server.rs +203 -0
- package/package.json +123 -3
- package/src/app.mjs +136 -0
- package/src/asset-receipt.d.mts +13 -0
- package/src/asset-receipt.mjs +61 -0
- package/src/auth/better-auth.ts +280 -0
- package/src/auth/drizzle.ts +17 -0
- package/src/auth/emails.ts +44 -0
- package/src/auth.ts +62 -0
- package/src/boot.ts +57 -0
- package/src/builtin.tsx +19 -0
- package/src/bus/postgres.ts +104 -0
- package/src/bus.ts +51 -0
- package/src/cache.ts +4 -0
- package/src/capture.ts +50 -0
- package/src/changes-sql.d.mts +20 -0
- package/src/changes-sql.mjs +115 -0
- package/src/changes.ts +352 -0
- package/src/channel/connections.ts +216 -0
- package/src/channel/socket.ts +396 -0
- package/src/channel-fake.ts +70 -0
- package/src/channel.ts +250 -0
- package/src/client.tsx +27 -0
- package/src/contract/describe.mjs +237 -0
- package/src/contract.mjs +299 -0
- package/src/cron.ts +74 -0
- package/src/data/after.ts +57 -0
- package/src/data/cache.ts +354 -0
- package/src/data/definitions.ts +94 -0
- package/src/data/draft.ts +104 -0
- package/src/data/foundation.ts +95 -0
- package/src/data/live-api.ts +22 -0
- package/src/data/mutation.ts +138 -0
- package/src/data/primitives.ts +135 -0
- package/src/data/query.ts +106 -0
- package/src/data/transport.ts +123 -0
- package/src/data/types.ts +333 -0
- package/src/data.ts +125 -0
- package/src/db/bun-sqlite.d.ts +13 -0
- package/src/db/changes-mysql.ts +126 -0
- package/src/db/changes-postgres.ts +238 -0
- package/src/db/changes-sqlite.ts +183 -0
- package/src/db/core.ts +95 -0
- package/src/db/index.ts +43 -0
- package/src/db/mysql.ts +84 -0
- package/src/db/postgres.ts +102 -0
- package/src/db/sqlite.ts +166 -0
- package/src/derive.d.mts +19 -0
- package/src/derive.mjs +237 -0
- package/src/dev-runtime.mjs +46 -0
- package/src/email.ts +146 -0
- package/src/exec/errors.ts +87 -0
- package/src/exec/impl.ts +21 -0
- package/src/exec/landing.ts +66 -0
- package/src/exec/limit.ts +25 -0
- package/src/exec/once.ts +24 -0
- package/src/exec/scope.ts +328 -0
- package/src/exec/touch.ts +80 -0
- package/src/exec/validation.ts +176 -0
- package/src/exec/warm.ts +50 -0
- package/src/exec.ts +400 -0
- package/src/extension.ts +48 -0
- package/src/first-paint.ts +74 -0
- package/src/form/value.ts +15 -0
- package/src/form.tsx +223 -0
- package/src/gate.css +6 -0
- package/src/hub/channels.ts +102 -0
- package/src/hub/connections.ts +147 -0
- package/src/hub/delivery.ts +62 -0
- package/src/hub/feed.ts +168 -0
- package/src/hub/presence.ts +64 -0
- package/src/hub/route.ts +159 -0
- package/src/hub/subscriptions.ts +213 -0
- package/src/hub/topic.ts +98 -0
- package/src/hub/tracked.ts +12 -0
- package/src/hub/types.ts +190 -0
- package/src/hub/view.ts +147 -0
- package/src/hub.ts +196 -0
- package/src/index.ts +184 -0
- package/src/inline.mjs +359 -0
- package/src/inspect/compare.mjs +162 -0
- package/src/inspect/routes.mjs +154 -0
- package/src/inspect/samples.mjs +59 -0
- package/src/inspect/url.mjs +2 -0
- package/src/inspect.mjs +239 -0
- package/src/jobs.ts +223 -0
- package/src/link/election.ts +178 -0
- package/src/link/lines.ts +27 -0
- package/src/link.ts +385 -0
- package/src/list-drizzle.ts +136 -0
- package/src/list.ts +315 -0
- package/src/listen.ts +54 -0
- package/src/live/api.ts +18 -0
- package/src/live/backoff.ts +6 -0
- package/src/live/frames.ts +42 -0
- package/src/live/read.ts +77 -0
- package/src/live/sub-types.ts +24 -0
- package/src/live/transport.ts +86 -0
- package/src/live/types.ts +52 -0
- package/src/live-fake.ts +57 -0
- package/src/live-target.mjs +231 -0
- package/src/live.ts +390 -0
- package/src/media.ts +50 -0
- package/src/migrations.mjs +27 -0
- package/src/mux-session.ts +6 -0
- package/src/mux.ts +232 -0
- package/src/og/DefaultCard.tsx +91 -0
- package/src/og/fonts.mjs +72 -0
- package/src/og/images.mjs +124 -0
- package/src/og/index.mjs +222 -0
- package/src/og/native.mjs +36 -0
- package/src/range.mjs +31 -0
- package/src/router.ts +199 -0
- package/src/routes.mjs +193 -0
- package/src/run/admission.ts +67 -0
- package/src/run/boot.tsx +115 -0
- package/src/run/cache-presentation.ts +67 -0
- package/src/run/cache.ts +254 -0
- package/src/run/helpers.ts +197 -0
- package/src/run/listeners.ts +166 -0
- package/src/run/navigation.ts +385 -0
- package/src/run/page-skeleton.tsx +35 -0
- package/src/run/prefetch.ts +129 -0
- package/src/run/retain-view.ts +18 -0
- package/src/run/shape-preparation.ts +97 -0
- package/src/run/shape-styles.ts +72 -0
- package/src/run/source-context/pin.ts +124 -0
- package/src/run/source-context.ts +311 -0
- package/src/run.tsx +74 -0
- package/src/rust/common.ts +163 -0
- package/src/rust/native.ts +282 -0
- package/src/rust.ts +207 -0
- package/src/server/background.ts +34 -0
- package/src/server/card.tsx +65 -0
- package/src/server/compression.ts +115 -0
- package/src/server/core.ts +70 -0
- package/src/server/cron.ts +49 -0
- package/src/server/dispatch.ts +73 -0
- package/src/server/form.ts +92 -0
- package/src/server/functions.ts +133 -0
- package/src/server/handler.ts +57 -0
- package/src/server/head.ts +96 -0
- package/src/server/health.ts +36 -0
- package/src/server/jobs.ts +112 -0
- package/src/server/lifecycle.ts +48 -0
- package/src/server/log.ts +42 -0
- package/src/server/media.ts +61 -0
- package/src/server/navigation-cache.ts +75 -0
- package/src/server/navigation.tsx +86 -0
- package/src/server/page-cold.ts +96 -0
- package/src/server/page-stream.tsx +181 -0
- package/src/server/page-types.ts +51 -0
- package/src/server/page-warm.ts +131 -0
- package/src/server/page.ts +69 -0
- package/src/server/payload.ts +89 -0
- package/src/server/prerender.ts +64 -0
- package/src/server/preview.tsx +67 -0
- package/src/server/render.ts +197 -0
- package/src/server/request.ts +192 -0
- package/src/server/resolver.ts +228 -0
- package/src/server/routes.ts +150 -0
- package/src/server/security.ts +50 -0
- package/src/server/services.ts +69 -0
- package/src/server/shutdown.ts +23 -0
- package/src/server/text.ts +29 -0
- package/src/server/types.ts +170 -0
- package/src/server.tsx +138 -0
- package/src/shape.d.mts +3 -0
- package/src/shape.mjs +97 -0
- package/src/share/display.ts +50 -0
- package/src/share/network.ts +119 -0
- package/src/share/receive.ts +70 -0
- package/src/share/state.ts +30 -0
- package/src/share/tab-queue.ts +28 -0
- package/src/share-server.ts +293 -0
- package/src/share.ts +397 -0
- package/src/sheets.mjs +87 -0
- package/src/sidecar/build.mjs +170 -0
- package/src/sidecar/cargo.mjs +164 -0
- package/src/sidecar/common.mjs +17 -0
- package/src/sidecar/dev-build.mjs +91 -0
- package/src/sidecar/dev-watch.mjs +88 -0
- package/src/sidecar/manifest.mjs +19 -0
- package/src/sidecar/process.mjs +58 -0
- package/src/sidecar/refresh.mjs +19 -0
- package/src/sidecar.mjs +162 -0
- package/src/socket/check.ts +50 -0
- package/src/socket/deliver.ts +16 -0
- package/src/socket/publish.ts +56 -0
- package/src/socket/rooms.ts +41 -0
- package/src/socket/route.ts +79 -0
- package/src/socket/shared.ts +26 -0
- package/src/socket/types.ts +48 -0
- package/src/socket.ts +400 -0
- package/src/stream.ts +22 -0
- package/src/verify/app.ts +39 -0
- package/src/verify/cleanup.ts +27 -0
- package/src/verify/database.ts +11 -0
- package/src/verify/live.ts +63 -0
- package/src/verify/notify.ts +35 -0
- package/src/verify/skip.ts +19 -0
- package/src/verify/support.ts +149 -0
- package/src/verify/timing.ts +15 -0
- package/src/verify/trigger.ts +14 -0
- package/src/verify.ts +152 -0
- package/src/view.tsx +132 -0
- package/src/vite/asset-bytes.mjs +95 -0
- package/src/vite/assets.mjs +117 -0
- package/src/vite/config-hooks.mjs +166 -0
- package/src/vite/dev-hooks.mjs +103 -0
- package/src/vite/dev.mjs +102 -0
- package/src/vite/entries.mjs +149 -0
- package/src/vite/module-hooks.mjs +290 -0
- package/src/vite/route-modules.mjs +289 -0
- package/src/vite/server-functions.mjs +222 -0
- package/src/vite/shape-entry-css.mjs +187 -0
- package/src/vite/shape-override.mjs +226 -0
- package/src/vite/shared.mjs +55 -0
- package/src/vite/sheets.mjs +92 -0
- package/src/vite/state.mjs +89 -0
- package/src/vite/syntax.mjs +139 -0
- package/src/vite.mjs +202 -0
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import type { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
import { BaseRootRoute, BaseRoute, isNotFound, type AnyRoute } from '@tanstack/router-core'
|
|
3
|
+
import { isRedirect, type Redirect } from '../data'
|
|
4
|
+
import * as exec from '../exec'
|
|
5
|
+
import type { Scope } from '../exec'
|
|
6
|
+
import type { Manifest, RouteModule } from './types'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* What each router-core loader gets as `context`: the request scope, where it leaves tags and redirects (router-core
|
|
10
|
+
* copies the context object, so those go in shared containers), and the matched page's catch-all name.
|
|
11
|
+
*/
|
|
12
|
+
export interface LoadContext {
|
|
13
|
+
request: Request
|
|
14
|
+
scope: Scope
|
|
15
|
+
tags: Map<string, Set<string>>
|
|
16
|
+
out: { redirect?: Redirect; chain?: Promise<unknown> }
|
|
17
|
+
splat?: string | undefined
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface TreeNode {
|
|
21
|
+
route: AnyRoute
|
|
22
|
+
children: AnyRoute[]
|
|
23
|
+
dir: string
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const makeLoader =
|
|
27
|
+
(modules: Record<string, RouteModule>, als: AsyncLocalStorage<Scope>) =>
|
|
28
|
+
(file: string, splat?: string) =>
|
|
29
|
+
async ({
|
|
30
|
+
params,
|
|
31
|
+
context,
|
|
32
|
+
abortController,
|
|
33
|
+
}: {
|
|
34
|
+
params: Record<string, unknown>
|
|
35
|
+
context: LoadContext
|
|
36
|
+
abortController: AbortController
|
|
37
|
+
}) => {
|
|
38
|
+
const load = modules[file]?.load
|
|
39
|
+
if (!load) return undefined
|
|
40
|
+
// Parent first (router-core starts them together): a layout's `load` is a guard, so a child never runs for a
|
|
41
|
+
// visitor its parent redirects (research 28 §3).
|
|
42
|
+
const out = context.out
|
|
43
|
+
const before = out.chain
|
|
44
|
+
let done!: () => void
|
|
45
|
+
out.chain = new Promise<void>((ok) => {
|
|
46
|
+
done = ok
|
|
47
|
+
})
|
|
48
|
+
await before
|
|
49
|
+
if (out.redirect) return (done(), undefined)
|
|
50
|
+
// Each loader runs in its own frame of the request scope, which records the tags of the queries it read.
|
|
51
|
+
const f = exec.frame(context.scope)
|
|
52
|
+
context.tags.set(file, f.tags!)
|
|
53
|
+
try {
|
|
54
|
+
const ctx = await f.ctx()
|
|
55
|
+
const v = await als.run(f, () =>
|
|
56
|
+
load({
|
|
57
|
+
params: cleanParams(params, splat ?? context.splat),
|
|
58
|
+
request: context.request,
|
|
59
|
+
signal: abortController.signal,
|
|
60
|
+
ctx,
|
|
61
|
+
}),
|
|
62
|
+
)
|
|
63
|
+
// oxlint-disable-next-line typescript/only-throw-error -- router-core's own not-found signal, passed on as it came
|
|
64
|
+
if (isNotFound(v)) throw v
|
|
65
|
+
return v
|
|
66
|
+
} catch (e) {
|
|
67
|
+
if (!isRedirect(e)) throw e
|
|
68
|
+
out.redirect ??= e
|
|
69
|
+
return undefined
|
|
70
|
+
} finally {
|
|
71
|
+
done()
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The router-core tree for the manifest: layouts are path prefixes, routes hang under their innermost layout. */
|
|
76
|
+
export function routeTree(
|
|
77
|
+
manifest: Manifest,
|
|
78
|
+
modules: Record<string, RouteModule>,
|
|
79
|
+
als: AsyncLocalStorage<Scope>,
|
|
80
|
+
) {
|
|
81
|
+
const loader = makeLoader(modules, als)
|
|
82
|
+
const rootLayout = manifest.layouts.find((l) => l.dir === '')
|
|
83
|
+
const root = new BaseRootRoute({
|
|
84
|
+
...(rootLayout && { loader: loader(rootLayout.file), kerf: rootLayout }),
|
|
85
|
+
} as never)
|
|
86
|
+
const top: TreeNode = { route: root, children: [], dir: '' }
|
|
87
|
+
const nodes = new Map<string, TreeNode>()
|
|
88
|
+
const at = (id: string | undefined) => (id ? (nodes.get(id) ?? top) : top)
|
|
89
|
+
for (const l of manifest.layouts) {
|
|
90
|
+
if (l.dir === '') {
|
|
91
|
+
nodes.set(l.id, top)
|
|
92
|
+
continue
|
|
93
|
+
}
|
|
94
|
+
const parent = at(l.parent)
|
|
95
|
+
const route = new BaseRoute({
|
|
96
|
+
getParentRoute: () => parent.route,
|
|
97
|
+
path: toPath(l.dir, parent.dir),
|
|
98
|
+
loader: loader(l.file),
|
|
99
|
+
kerf: l,
|
|
100
|
+
} as never)
|
|
101
|
+
parent.children.push(route)
|
|
102
|
+
nodes.set(l.id, { route, children: [], dir: l.dir })
|
|
103
|
+
}
|
|
104
|
+
const splats = new Set(manifest.routes.filter((r) => r.splat).map((r) => r.pattern))
|
|
105
|
+
for (const r of manifest.routes) {
|
|
106
|
+
if (r.kind !== 'page') continue
|
|
107
|
+
const parent = at(r.layouts.at(-1))
|
|
108
|
+
const rel = r.pattern
|
|
109
|
+
.slice(1)
|
|
110
|
+
.split('/')
|
|
111
|
+
.slice(parent.dir ? parent.dir.split('/').length : 0)
|
|
112
|
+
.join('/')
|
|
113
|
+
// A splat beside it (`docs/[...slug]` next to `docs/index`) also matches `/docs`, and router-core ranks the
|
|
114
|
+
// splat first unless the page is its index route, written with the slash.
|
|
115
|
+
const index = rel && splats.has(`${r.pattern}/$`) ? `${rel}/` : rel
|
|
116
|
+
parent.children.push(
|
|
117
|
+
new BaseRoute({
|
|
118
|
+
getParentRoute: () => parent.route,
|
|
119
|
+
path: index || '/',
|
|
120
|
+
loader: loader(r.file, r.splat),
|
|
121
|
+
kerf: r,
|
|
122
|
+
} as never),
|
|
123
|
+
)
|
|
124
|
+
}
|
|
125
|
+
// Innermost layouts first, so each route's children are attached before its parent takes it.
|
|
126
|
+
for (const n of [...new Set(nodes.values())]
|
|
127
|
+
.filter((x) => x !== top)
|
|
128
|
+
.sort((a, b) => b.dir.length - a.dir.length))
|
|
129
|
+
if (n.children.length) n.route.addChildren(n.children)
|
|
130
|
+
return root.addChildren(top.children)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** A layout dir relative to its parent layout's, as a router-core path: `users/[id]` → `users/$id`. */
|
|
134
|
+
function toPath(dir: string, parentDir: string) {
|
|
135
|
+
const rel = dir.split('/').slice(parentDir ? parentDir.split('/').length : 0)
|
|
136
|
+
return rel
|
|
137
|
+
.map((s) => s.replace(/^\[\.\.\.(\w+)\]$/, '$').replace(/^\[(\w+)\]$/, '$$$1'))
|
|
138
|
+
.join('/')
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** router-core's params without its splat aliases; a splat is under its file name (`[...rest]` → `rest`). */
|
|
142
|
+
export function cleanParams(
|
|
143
|
+
p: Record<string, unknown> = {},
|
|
144
|
+
splat?: string,
|
|
145
|
+
): Record<string, string> {
|
|
146
|
+
const out: Record<string, string> = {}
|
|
147
|
+
for (const k in p) if (k !== '*' && k !== '_splat') out[k] = String(p[k])
|
|
148
|
+
if (splat && p._splat !== undefined) out[splat] = p._splat as string
|
|
149
|
+
return out
|
|
150
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { HandlerOptions } from './types'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* What every response gets unless it set its own (`site.security` changes or drops them). Nothing here can break a
|
|
5
|
+
* page: no CSP (that needs the app's own sources), and popups keep their opener, so OAuth popups still work.
|
|
6
|
+
*/
|
|
7
|
+
export const SECURITY: Record<string, string> = {
|
|
8
|
+
'x-content-type-options': 'nosniff',
|
|
9
|
+
'referrer-policy': 'strict-origin-when-cross-origin',
|
|
10
|
+
'x-frame-options': 'SAMEORIGIN',
|
|
11
|
+
'cross-origin-opener-policy': 'same-origin-allow-popups',
|
|
12
|
+
}
|
|
13
|
+
const HSTS = 'max-age=31536000'
|
|
14
|
+
|
|
15
|
+
/** Whether the page was reached over https: the URL, a proxy's `X-Forwarded-Proto`, or an https `site.url`. */
|
|
16
|
+
function secure(request: Request, options: HandlerOptions) {
|
|
17
|
+
return (
|
|
18
|
+
request.url.startsWith('https:') ||
|
|
19
|
+
request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim() === 'https' ||
|
|
20
|
+
!!options.site?.url?.startsWith('https:')
|
|
21
|
+
)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The headers `secured` adds for this request: the defaults, HSTS on https outside dev, then `site.security`. */
|
|
25
|
+
export function securityHeaders(request: Request, options: HandlerOptions): [string, string][] {
|
|
26
|
+
const own = options.site?.security
|
|
27
|
+
if (own === false) return []
|
|
28
|
+
const all: Record<string, string | false> = { ...SECURITY }
|
|
29
|
+
if (!options.dev && secure(request, options)) all['strict-transport-security'] = HSTS
|
|
30
|
+
for (const [name, value] of Object.entries(own ?? {})) all[name.toLowerCase()] = value
|
|
31
|
+
return Object.entries(all).filter((e): e is [string, string] => e[1] !== false)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The response with the security headers it doesn't already carry. A response with fixed headers is copied. */
|
|
35
|
+
export function secured(response: Response, request: Request, options: HandlerOptions): Response {
|
|
36
|
+
const add = securityHeaders(request, options).filter(([name]) => !response.headers.has(name))
|
|
37
|
+
if (!add.length) return response
|
|
38
|
+
try {
|
|
39
|
+
for (const [name, value] of add) response.headers.set(name, value)
|
|
40
|
+
return response
|
|
41
|
+
} catch {
|
|
42
|
+
const headers = new Headers(response.headers)
|
|
43
|
+
for (const [name, value] of add) headers.set(name, value)
|
|
44
|
+
return new Response(response.body, {
|
|
45
|
+
status: response.status,
|
|
46
|
+
statusText: response.statusText,
|
|
47
|
+
headers,
|
|
48
|
+
})
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { runtime } from '../data'
|
|
2
|
+
import * as exec from '../exec'
|
|
3
|
+
import type { MediaServer } from '../exec'
|
|
4
|
+
import { configure } from '../hub'
|
|
5
|
+
import type { ServerExtension } from '../extension'
|
|
6
|
+
import type { HandlerOptions } from './types'
|
|
7
|
+
|
|
8
|
+
/** Handler-local extensions, media provider, and boot state. */
|
|
9
|
+
export function makeServices(options: HandlerOptions) {
|
|
10
|
+
let provider: Promise<MediaServer> | undefined
|
|
11
|
+
const mediaServer = () => (provider ??= options.media?.())
|
|
12
|
+
const scopeOptions = {
|
|
13
|
+
context: options.context,
|
|
14
|
+
store: options.store,
|
|
15
|
+
dev: options.dev,
|
|
16
|
+
onDiagnostic: options.onDiagnostic,
|
|
17
|
+
media: mediaServer,
|
|
18
|
+
extensions: undefined as ServerExtension[] | undefined,
|
|
19
|
+
}
|
|
20
|
+
let checked = !options.dev
|
|
21
|
+
const authBase = (options.auth?.basePath ?? '/api/auth').replace(/\/$/, '')
|
|
22
|
+
const extensions = new Map<string, ServerExtension>()
|
|
23
|
+
let loading: Promise<void> | undefined
|
|
24
|
+
const loadExtensions = () =>
|
|
25
|
+
(loading ??= (async () => {
|
|
26
|
+
for (const e of options.extensions ?? []) extensions.set(e.key, await e.load())
|
|
27
|
+
scopeOptions.extensions = [...extensions.values()]
|
|
28
|
+
})())
|
|
29
|
+
let applied = -1
|
|
30
|
+
configure({
|
|
31
|
+
...options.realtime,
|
|
32
|
+
build: options.build,
|
|
33
|
+
dev: options.dev,
|
|
34
|
+
store: options.store,
|
|
35
|
+
required: options.liveRequired,
|
|
36
|
+
onDiagnostic: options.onDiagnostic,
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Before the first request (and in dev, when `drizzle/` grows): the auth secret, and the list each database applies
|
|
41
|
+
* before its first statement (db/core.ts), so a page with no queries doesn't need one. A client whose statements can't
|
|
42
|
+
* be held is migrated here; if that fails the request goes on, and Q016 is what using the database then gives.
|
|
43
|
+
*/
|
|
44
|
+
async function boot() {
|
|
45
|
+
const list = options.migrations?.() ?? []
|
|
46
|
+
if (applied !== list.length) {
|
|
47
|
+
options.auth?.$kerf?.check()
|
|
48
|
+
for (const e of extensions.values()) e.check?.(options.dev)
|
|
49
|
+
applied = list.length
|
|
50
|
+
const report = (e: unknown) =>
|
|
51
|
+
options.onDiagnostic?.({
|
|
52
|
+
code: 'Q016',
|
|
53
|
+
severity: 'error',
|
|
54
|
+
message: `Q016: ${String((e as Error | null)?.message ?? e)}`,
|
|
55
|
+
})
|
|
56
|
+
runtime.migrations = { list, report }
|
|
57
|
+
}
|
|
58
|
+
if (runtime.dbs?.size)
|
|
59
|
+
await Promise.all([...runtime.dbs].map((ready) => Promise.resolve(ready()).catch(() => {})))
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const check = () => {
|
|
63
|
+
if (!checked) {
|
|
64
|
+
checked = true
|
|
65
|
+
exec.checkTags((d) => options.onDiagnostic?.(d))
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return { mediaServer, scopeOptions, authBase, extensions, loadExtensions, boot, check }
|
|
69
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
let last: (() => unknown) | undefined
|
|
2
|
+
let listening = false
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* On SIGTERM or SIGINT (a deploy or scale-down), stop the schedule and close realtime connections with "going away",
|
|
6
|
+
* so open pages reconnect to an instance that's staying, while the server finishes the requests it has (Nitro's
|
|
7
|
+
* server stops taking new ones and waits for them). The newest handler's is the one that runs.
|
|
8
|
+
*/
|
|
9
|
+
export function onShutdown(stop: () => unknown) {
|
|
10
|
+
last = stop
|
|
11
|
+
if (listening || typeof process === 'undefined' || !process.once) return
|
|
12
|
+
listening = true
|
|
13
|
+
for (const signal of ['SIGTERM', 'SIGINT'] as const)
|
|
14
|
+
process.once(signal, () => {
|
|
15
|
+
// A listener stops Node's own exit: with no other (Nitro's server has one), exit as the signal would have.
|
|
16
|
+
const alone = process.listenerCount(signal) === 0
|
|
17
|
+
void Promise.resolve(last?.())
|
|
18
|
+
.catch(() => {})
|
|
19
|
+
.finally(() => {
|
|
20
|
+
if (alone) process.kill(process.pid, signal)
|
|
21
|
+
})
|
|
22
|
+
})
|
|
23
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { esc } from '@kerf-js/core/markup'
|
|
2
|
+
export { esc } from '@kerf-js/core/markup'
|
|
3
|
+
|
|
4
|
+
export const json = (v: unknown) => JSON.stringify(v ?? null).replace(/</g, '\\u003c')
|
|
5
|
+
/**
|
|
6
|
+
* A redirect's body. A server's 3xx is followed by its `location`; a prerendered one is a file on a static host, and this
|
|
7
|
+
* is what that file says: go now, and the address to index. No stylesheet, so no view transition starts on a page
|
|
8
|
+
* that never paints (Chrome aborts it, and logs an InvalidStateError).
|
|
9
|
+
*/
|
|
10
|
+
export const moved = (href: string) =>
|
|
11
|
+
`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Moved</title><meta name="robots" content="noindex"><link rel="canonical" href="${esc(href)}"><meta http-equiv="refresh" content="0; url=${esc(href)}"><a href="${esc(href)}">Moved here</a>`
|
|
12
|
+
export const thenable = (v: unknown): v is PromiseLike<unknown> =>
|
|
13
|
+
typeof (v as Partial<PromiseLike<unknown>> | null | undefined)?.then === 'function'
|
|
14
|
+
|
|
15
|
+
/** `/` → `index`, `/users/42` → `users/42`: the card path under `/_kerf/og/`. */
|
|
16
|
+
export const cardPath = (path: string) =>
|
|
17
|
+
path.replace(/[?#].*/, '').replace(/^\/+|\/+$/g, '') || 'index'
|
|
18
|
+
|
|
19
|
+
/** FNV-1a, twice (different seeds), in base 36: a stable, sync content hash for `?v=`. */
|
|
20
|
+
export function hash(s: string): string {
|
|
21
|
+
let a = 0x811c9dc5,
|
|
22
|
+
b = 0x01000193 ^ 0x5bd1e995
|
|
23
|
+
for (let i = 0; i < s.length; i++) {
|
|
24
|
+
const c = s.charCodeAt(i)
|
|
25
|
+
a = Math.imul(a ^ c, 0x01000193)
|
|
26
|
+
b = Math.imul(b ^ c, 0x5bd1e995)
|
|
27
|
+
}
|
|
28
|
+
return ((a >>> 0).toString(36) + (b >>> 0).toString(36)).slice(0, 10)
|
|
29
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import type { Site, Merged, Meta as MetaObject } from '@kerf-js/core/ssr'
|
|
2
|
+
import type { AssetReceipt, Component, Match } from '../router'
|
|
3
|
+
import type { AuthProvider } from '../auth'
|
|
4
|
+
import type { ExtensionEntry } from '../extension'
|
|
5
|
+
import type { Context, Redirect } from '../data'
|
|
6
|
+
import type { MediaServer, Store } from '../exec'
|
|
7
|
+
import type { RealtimeOptions } from '../hub'
|
|
8
|
+
import type { Pieces } from '../first-paint'
|
|
9
|
+
import type { Diagnostic } from './log'
|
|
10
|
+
import type { CronJobs } from '../cron'
|
|
11
|
+
import type { Mailer } from '../email'
|
|
12
|
+
import type { Jobs } from '../jobs'
|
|
13
|
+
|
|
14
|
+
/** A page route from the file tree. */
|
|
15
|
+
export interface RouteEntry {
|
|
16
|
+
id: string
|
|
17
|
+
file: string
|
|
18
|
+
layouts: string[]
|
|
19
|
+
pattern: string
|
|
20
|
+
params: string[]
|
|
21
|
+
splat?: string
|
|
22
|
+
card?: string
|
|
23
|
+
kind: 'page' | '404' | 'error'
|
|
24
|
+
}
|
|
25
|
+
/** A layout from the file tree. */
|
|
26
|
+
export interface LayoutEntry {
|
|
27
|
+
id: string
|
|
28
|
+
file: string
|
|
29
|
+
dir: string
|
|
30
|
+
parent?: string
|
|
31
|
+
}
|
|
32
|
+
/** The routes and layouts `kerf build` found. */
|
|
33
|
+
export interface Manifest {
|
|
34
|
+
dir: string
|
|
35
|
+
routes: RouteEntry[]
|
|
36
|
+
layouts: LayoutEntry[]
|
|
37
|
+
defaultCard?: string
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** What a route file exports. */
|
|
41
|
+
export interface RouteModule {
|
|
42
|
+
default?: Component
|
|
43
|
+
load?: (args: {
|
|
44
|
+
params: Record<string, string>
|
|
45
|
+
request: Request
|
|
46
|
+
signal: AbortSignal
|
|
47
|
+
ctx: Context
|
|
48
|
+
}) => unknown
|
|
49
|
+
meta?:
|
|
50
|
+
| MetaObject
|
|
51
|
+
| ((args: {
|
|
52
|
+
params: Record<string, string>
|
|
53
|
+
data: unknown
|
|
54
|
+
}) => MetaObject | Promise<MetaObject>)
|
|
55
|
+
prerender?:
|
|
56
|
+
| true
|
|
57
|
+
| Record<string, string>[]
|
|
58
|
+
| (() => Record<string, string>[] | Promise<Record<string, string>[]>)
|
|
59
|
+
size?: { width: number; height: number }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** A font for generated cards. */
|
|
63
|
+
export interface Font {
|
|
64
|
+
name: string
|
|
65
|
+
data: Uint8Array
|
|
66
|
+
weight?: number
|
|
67
|
+
style?: 'normal' | 'italic'
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** `createHandler`: the app as the build describes it, and how to serve it. */
|
|
71
|
+
export interface HandlerOptions {
|
|
72
|
+
manifest: Manifest
|
|
73
|
+
/** Route, layout and card modules by manifest file. */
|
|
74
|
+
modules: Record<string, RouteModule>
|
|
75
|
+
site?: Site
|
|
76
|
+
/**
|
|
77
|
+
* The client entry and what to preload (Nitro's `?assets=client`), plus the font build's preloads (`kerf:fonts/preloads`).
|
|
78
|
+
* `pieces`: the build's first-paint table. Without it, `inline` and Kerf's purge (`critical`) are what `pageStyles` uses.
|
|
79
|
+
*/
|
|
80
|
+
assets?: {
|
|
81
|
+
entry?: string
|
|
82
|
+
js?: { href: string }[]
|
|
83
|
+
css?: { href: string }[]
|
|
84
|
+
fonts?: { href: string; type: string }[]
|
|
85
|
+
pieces?: Pieces & {
|
|
86
|
+
shared?: { href: string; has: string[] }
|
|
87
|
+
routes: { href: string; has: string[] }[]
|
|
88
|
+
}
|
|
89
|
+
inline?: Record<string, string>
|
|
90
|
+
critical?: {
|
|
91
|
+
parse: (css: string) => unknown[]
|
|
92
|
+
purge: (sheets: string[], found: { has: (word: string) => boolean }) => string[]
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/** Changes with every build: part of each card's `?v=` hash. */
|
|
96
|
+
build?: string
|
|
97
|
+
/** Build-matched emitted asset receipt; null until the client bundle is available. */
|
|
98
|
+
routeAssetBytes?: AssetReceipt | null
|
|
99
|
+
dev?: boolean
|
|
100
|
+
fonts?: Font[]
|
|
101
|
+
/** Route and layout ids with no client code (PLAN §11): the server sends their HTML. */
|
|
102
|
+
statics?: string[]
|
|
103
|
+
/** Client chunks by level or island id: the page's own are preloaded, so they don't wait for the entry to ask. */
|
|
104
|
+
chunks?: Record<string, { js?: { href: string }[]; css?: { href: string }[] }>
|
|
105
|
+
/** Some island can wait, so every page carries the capture script: a navigation can arrive at one that does. */
|
|
106
|
+
lazy?: boolean
|
|
107
|
+
/** Stream timeout for Boundaries (ms). */
|
|
108
|
+
timeout?: number
|
|
109
|
+
/** How long (ms) a page waits for its Boundaries' data before streaming it: what lands sooner goes in the page. 0 streams at once. */
|
|
110
|
+
hold?: number
|
|
111
|
+
/** The app's context for `load` and server functions (`src/context.server.ts`'s default export). */
|
|
112
|
+
context?: (args: { request: Request }) => object | Promise<object>
|
|
113
|
+
/** The shared cache for `cache: { life }` queries (memory by default). */
|
|
114
|
+
store?: Store
|
|
115
|
+
/** `src/auth.server.ts`'s default export, any provider: mounted at its base path, checked on the first request. */
|
|
116
|
+
auth?: Pick<AuthProvider, 'handler' | 'basePath' | '$kerf'>
|
|
117
|
+
/** `server.extension` providers with an app file (`virtual:kerf/extensions`), loaded on the first request. */
|
|
118
|
+
extensions?: ExtensionEntry[]
|
|
119
|
+
/** The app's migrations (`drizzle/`); dev reads them each request, so `kerf db generate` needs no restart. */
|
|
120
|
+
migrations?: () => { tag: string; sql: string }[]
|
|
121
|
+
/** The `media.server` provider (`virtual:kerf/media`), loaded on first use. */
|
|
122
|
+
media?: () => Promise<MediaServer>
|
|
123
|
+
/** `src/cron.server.ts`'s default export: jobs on a schedule, run by a server preset (not in a build). */
|
|
124
|
+
cron?: CronJobs
|
|
125
|
+
/** `src/email.server.ts`'s default export: the mailer `sendEmail` and auth's emails use. */
|
|
126
|
+
email?: Mailer
|
|
127
|
+
/** `src/jobs.server.ts`'s default export: queued jobs, worked by a server preset. */
|
|
128
|
+
jobs?: Jobs
|
|
129
|
+
/** `src/realtime.server.ts`'s default export: the bus, origins and limits. */
|
|
130
|
+
realtime?: RealtimeOptions
|
|
131
|
+
/** `false`: never build URLs on the request's origin (`kerf routes --meta`, whose requests aren't real). */
|
|
132
|
+
requestOrigin?: false
|
|
133
|
+
/** Queries marked `live: { required: true }` (`scanRequired`, at build). */
|
|
134
|
+
liveRequired?: string[]
|
|
135
|
+
/** Dev and tests: diagnostics found while serving (H005–H008, Q002–Q010). */
|
|
136
|
+
onDiagnostic?: (d: Diagnostic) => void
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** One matched route level, with its module and the data before serialising. */
|
|
140
|
+
export interface Level extends Match {
|
|
141
|
+
mod?: RouteModule | undefined
|
|
142
|
+
raw: unknown
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Where the words on a page came from, and its image: what `kerf routes --meta` and `kerf check` report. */
|
|
146
|
+
export interface MetaSource {
|
|
147
|
+
title: 'route' | 'layout' | 'auto' | 'config' | 'none'
|
|
148
|
+
description: 'route' | 'layout' | 'auto' | 'config' | 'none'
|
|
149
|
+
image: 'explicit' | 'card' | 'auto' | 'none'
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** What a path comes to: the status, the route and its levels. */
|
|
153
|
+
export interface Resolved {
|
|
154
|
+
status: number
|
|
155
|
+
path: string
|
|
156
|
+
levels: Level[]
|
|
157
|
+
head: Merged
|
|
158
|
+
/** The page route, when one matched. */
|
|
159
|
+
route?: RouteEntry | undefined
|
|
160
|
+
error?: unknown
|
|
161
|
+
/** A loader called `redirect()`: nothing renders. */
|
|
162
|
+
redirect?: Redirect
|
|
163
|
+
/** Headers supplied by a router-core redirect. */
|
|
164
|
+
redirectHeaders?: Headers
|
|
165
|
+
/** The metas the head is merged from, until `complete` has finished it. */
|
|
166
|
+
metas?: MetaObject[] | undefined
|
|
167
|
+
source?: MetaSource
|
|
168
|
+
/** The origin URLs are built on, when one is known. */
|
|
169
|
+
origin?: string | undefined
|
|
170
|
+
}
|
package/src/server.tsx
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// The request handler (research 25 §3–§5): match the path and run the loaders on @tanstack/router-core, merge the
|
|
2
|
+
// metadata (research 20 §1: awaited before the first byte, plain data), then stream the page: the head with every
|
|
3
|
+
// tag and the shell first, each Boundary's content as it resolves, the page data last. The same resolve step answers
|
|
4
|
+
// client navigations (`/_kerf/data/<path>`) and renders share cards (`/_kerf/og/<path>.png`).
|
|
5
|
+
//
|
|
6
|
+
// Status codes are decided before the first byte: 404 when nothing matches or a loader returns `notFound()`, 500 when
|
|
7
|
+
// a loader or `meta` throws, 307 (or the given status) when a loader calls `redirect()`. 404 and 500 render inside
|
|
8
|
+
// the root layout when it loaded.
|
|
9
|
+
//
|
|
10
|
+
// A build's stylesheets go in the page, a round trip saved before the first paint. Each `<style>` keeps a disabled link
|
|
11
|
+
// beside it: a disabled link is never fetched, and it is how Vite's preload helper, on importing a route's chunk, sees
|
|
12
|
+
// the sheet is there and doesn't apply it twice.
|
|
13
|
+
//
|
|
14
|
+
// Server functions (research 27): each request gets a scope (AsyncLocalStorage), so `q.fetch()` in loaders and `q()`
|
|
15
|
+
// in the render share one request cache; `/_kerf/fn/<id>` answers the client's calls; the page ends with the
|
|
16
|
+
// scope's resolved entries (`#kerf-cache`) so the client cache starts seeded and hydration fetches nothing.
|
|
17
|
+
//
|
|
18
|
+
// Forms and media (research 29): a form POST to a page URL runs its mutation, then answers 303 or the page with the
|
|
19
|
+
// errors in it, so `<Form>` works without JS. `/_kerf/m/<hash>/<width>.<fmt>` serves media through the `media.server`
|
|
20
|
+
// provider. The request's cookies reach `persist: 'cookie'` boxes, and the `rt.isolated` below makes a scope reached
|
|
21
|
+
// outside a render S002: this process serves many users, so it has no "the tab's app".
|
|
22
|
+
|
|
23
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
24
|
+
import { rt } from '@kerf-js/core/internal'
|
|
25
|
+
import { runtime } from './data'
|
|
26
|
+
import * as exec from './exec'
|
|
27
|
+
import type { Scope } from './exec'
|
|
28
|
+
import { hub } from './hub'
|
|
29
|
+
import { makeMedia } from './server/media'
|
|
30
|
+
import { makeForm } from './server/form'
|
|
31
|
+
import { makeNavigation } from './server/navigation'
|
|
32
|
+
import { makeCard } from './server/card'
|
|
33
|
+
import { makePrerender } from './server/prerender'
|
|
34
|
+
import { makePage } from './server/page'
|
|
35
|
+
import { makeCore } from './server/core'
|
|
36
|
+
import { makeServices } from './server/services'
|
|
37
|
+
import { makeDispatch } from './server/dispatch'
|
|
38
|
+
import { makeHandler } from './server/handler'
|
|
39
|
+
import { lifecycle, withRequestIds } from './server/lifecycle'
|
|
40
|
+
import { useMailer } from './email'
|
|
41
|
+
import { makeComplete } from './server/head'
|
|
42
|
+
import { makePreview } from './server/preview'
|
|
43
|
+
import { resolveRoute } from './server/resolver'
|
|
44
|
+
import type { HandlerOptions } from './server/types'
|
|
45
|
+
export { cardPath, hash } from './server/text'
|
|
46
|
+
export { serverLog, type Diagnostic } from './server/log'
|
|
47
|
+
export type {
|
|
48
|
+
RouteEntry,
|
|
49
|
+
LayoutEntry,
|
|
50
|
+
Manifest,
|
|
51
|
+
RouteModule,
|
|
52
|
+
Font,
|
|
53
|
+
HandlerOptions,
|
|
54
|
+
Level,
|
|
55
|
+
MetaSource,
|
|
56
|
+
Resolved,
|
|
57
|
+
} from './server/types'
|
|
58
|
+
|
|
59
|
+
const als = new AsyncLocalStorage<Scope>()
|
|
60
|
+
runtime.scope = () => als.getStore()
|
|
61
|
+
runtime.enter = (scope, fn) => als.run(scope as Scope, fn)
|
|
62
|
+
runtime.exec = exec
|
|
63
|
+
rt.isolated = true
|
|
64
|
+
runtime.poke = (tags, origin) => hub().poke(tags, origin)
|
|
65
|
+
|
|
66
|
+
const CARD = { width: 1200, height: 630 }
|
|
67
|
+
/** Render passes a page may take. Only a backstop: a render stops when its passes stop reading anything new, and `timeout` ends a stream. */
|
|
68
|
+
const PASSES = 1024
|
|
69
|
+
|
|
70
|
+
/** The app as a `(Request) => Response`: pages, data, functions and cards. */
|
|
71
|
+
export function createHandler(options: HandlerOptions) {
|
|
72
|
+
options = withRequestIds(options, () => als.getStore()?.requestId)
|
|
73
|
+
useMailer(options.email, !!options.dev)
|
|
74
|
+
const { manifest, site, byId, mod, comps, statics, heads, remember, originOf, stateOf, tree } =
|
|
75
|
+
makeCore(options, als)
|
|
76
|
+
const services = makeServices(options)
|
|
77
|
+
const { scopeOptions, mediaServer, authBase, extensions } = services
|
|
78
|
+
|
|
79
|
+
const resolve = (path: string, request: Request) =>
|
|
80
|
+
resolveRoute(
|
|
81
|
+
{ als, scopeOptions, tree, site, manifest, byId, mod, comps, options, originOf },
|
|
82
|
+
path,
|
|
83
|
+
request,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
const timing = options.timeout === undefined ? {} : { timeout: options.timeout }
|
|
87
|
+
const complete = makeComplete(options, manifest, site, mod, CARD)
|
|
88
|
+
|
|
89
|
+
const { finished, inspect } = makePreview({
|
|
90
|
+
als,
|
|
91
|
+
scopeOptions,
|
|
92
|
+
resolve,
|
|
93
|
+
stateOf,
|
|
94
|
+
timing,
|
|
95
|
+
complete,
|
|
96
|
+
PASSES,
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
const page = makePage({
|
|
100
|
+
options,
|
|
101
|
+
site,
|
|
102
|
+
statics,
|
|
103
|
+
timing,
|
|
104
|
+
passes: PASSES,
|
|
105
|
+
resolve,
|
|
106
|
+
stateOf,
|
|
107
|
+
complete,
|
|
108
|
+
heads,
|
|
109
|
+
remember,
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
const form = makeForm(options, page)
|
|
113
|
+
|
|
114
|
+
const media = makeMedia(options, mediaServer)
|
|
115
|
+
|
|
116
|
+
const data = makeNavigation({ resolve, finished, statics, stateOf, PASSES, options })
|
|
117
|
+
|
|
118
|
+
const og = makeCard({ resolve, finished, mod, manifest, options, site, CARD })
|
|
119
|
+
|
|
120
|
+
const prerenderList = makePrerender(manifest, mod, resolve, finished)
|
|
121
|
+
|
|
122
|
+
const route = makeDispatch({
|
|
123
|
+
options,
|
|
124
|
+
authBase,
|
|
125
|
+
extensions,
|
|
126
|
+
form,
|
|
127
|
+
media,
|
|
128
|
+
og,
|
|
129
|
+
data,
|
|
130
|
+
prerenderList,
|
|
131
|
+
page,
|
|
132
|
+
})
|
|
133
|
+
const handler = makeHandler(options, als, services, route)
|
|
134
|
+
lifecycle(options, services, (scope, run) => als.run(scope, run))
|
|
135
|
+
return Object.assign(handler, { resolve, inspect })
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export { headTags } from '@kerf-js/core/ssr'
|
package/src/shape.d.mts
ADDED