@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,333 @@
|
|
|
1
|
+
import type { Derived, Resource } from '@kerf-js/core'
|
|
2
|
+
import type { Context, FnOptions, Skip } from '../data'
|
|
3
|
+
import type { ServerExtension } from '../extension'
|
|
4
|
+
|
|
5
|
+
/** Here and not in verify.ts: that file needs `postgres`, and an app without it still reads this type. */
|
|
6
|
+
export interface VerifyOptions {
|
|
7
|
+
/** `true` or a target's name, as `verify: true` and `verify: 'staging'` mean, for when the rest of this is needed too. */
|
|
8
|
+
target?: true | string
|
|
9
|
+
/** A running staging app. Fine in code. */
|
|
10
|
+
url?: string
|
|
11
|
+
/** A database, from the environment: `process.env.STAGING_DATABASE_URL`. */
|
|
12
|
+
db?: string
|
|
13
|
+
/** The query's input. */
|
|
14
|
+
input?: unknown
|
|
15
|
+
/** Columns of the test row: whose it is, so the signed-in test user can see it. The rest are made up. */
|
|
16
|
+
row?: Record<string, unknown>
|
|
17
|
+
/** Name of the env var with a cookie for a user who can see the row. Default `KERF_STAGING_COOKIE`. */
|
|
18
|
+
cookie?: string
|
|
19
|
+
/** Name of the env var with a cookie for a user who can't. Default `KERF_STAGING_OTHER_COOKIE`; without it, a signed-out client. */
|
|
20
|
+
otherCookie?: string
|
|
21
|
+
/** Ms each link may take. Default 5000. */
|
|
22
|
+
timeout?: number
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The Standard Schema interface (standardschema.dev): Zod, Valibot, ArkType and Drizzle's derived schemas. */
|
|
26
|
+
export interface StandardSchemaV1<I = unknown, O = I> {
|
|
27
|
+
readonly '~standard': {
|
|
28
|
+
readonly version: 1
|
|
29
|
+
readonly vendor: string
|
|
30
|
+
readonly validate: (value: unknown) => SchemaResult<O> | Promise<SchemaResult<O>>
|
|
31
|
+
readonly types?: { readonly input: I; readonly output: O } | undefined
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** What a Standard Schema validator answers. */
|
|
35
|
+
export type SchemaResult<O> =
|
|
36
|
+
| { readonly value: O; readonly issues?: undefined }
|
|
37
|
+
| { readonly issues: readonly SchemaIssue[] }
|
|
38
|
+
/** One failure from a schema, with the path to the field when there is one. */
|
|
39
|
+
export interface SchemaIssue {
|
|
40
|
+
readonly message: string
|
|
41
|
+
readonly path?: readonly (PropertyKey | { readonly key: PropertyKey })[] | undefined
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* At most `max` calls per `window` seconds, counted per signed-in user (`by: 'user'`, the default when someone is
|
|
46
|
+
* signed in) or per client address (`by: 'ip'`). The next call is refused with 429 (Q019) and `Retry-After`. The count
|
|
47
|
+
* lives in the cache store, so with `redisStore()` it holds across every instance.
|
|
48
|
+
*/
|
|
49
|
+
export interface Limit {
|
|
50
|
+
max: number
|
|
51
|
+
window: number
|
|
52
|
+
by?: 'user' | 'ip'
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** `'minutes'` etc. or seconds: how long the shared server cache keeps a value (research 27 §4). */
|
|
56
|
+
export type Life = 'seconds' | 'minutes' | 'hours' | 'days' | 'max' | number
|
|
57
|
+
|
|
58
|
+
/** What `ctx.user` carries for a role check: Better Auth's `admin` plugin writes `role` as `'admin'` or `'admin,user'`. */
|
|
59
|
+
type Signed = Context extends { user: infer U } ? NonNullable<U> : { id: string; role?: unknown }
|
|
60
|
+
/**
|
|
61
|
+
* Who may call a function. `'user'`: anyone signed in (A002 otherwise). `'public'`: anyone, said out loud (a mutation
|
|
62
|
+
* in an app with auth needs it, since there the default is `'user'`). `{ role }`: a signed-in user with one of these
|
|
63
|
+
* roles. `{ can }`: a signed-in user your check passes. Both answer 403 (A006) to anyone else.
|
|
64
|
+
*/
|
|
65
|
+
export type AuthScope =
|
|
66
|
+
| 'user'
|
|
67
|
+
| 'public'
|
|
68
|
+
| { role: string | readonly string[] }
|
|
69
|
+
| { can: (ctx: Omit<Context, 'user'> & { user: Signed }) => boolean | Promise<boolean> }
|
|
70
|
+
type Ctx<A> = A extends 'user' | { role: unknown } | { can: unknown }
|
|
71
|
+
? Context extends { user: infer U }
|
|
72
|
+
? Omit<Context, 'user'> & { user: NonNullable<U> }
|
|
73
|
+
: Context
|
|
74
|
+
: Context
|
|
75
|
+
|
|
76
|
+
export type In<S> = S extends StandardSchemaV1<infer I, unknown> ? I : void
|
|
77
|
+
export type Out<S> = S extends StandardSchemaV1<unknown, infer O> ? O : undefined
|
|
78
|
+
type DeepPartial<T> = T extends object ? { [K in keyof T]?: DeepPartial<T[K]> } : T
|
|
79
|
+
type Tags<A extends unknown[]> = readonly string[] | ((...args: A) => readonly string[])
|
|
80
|
+
/** Read before `run`, for one user's tag: `tags: (_, ctx) => [`entitlements:${ctx.user.id}`]`. */
|
|
81
|
+
type QueryTags<I, A> = Tags<[input: I, ctx: Ctx<A>]>
|
|
82
|
+
|
|
83
|
+
/** What an `Impl` is called with. */
|
|
84
|
+
export interface ImplCall {
|
|
85
|
+
fn: Fn
|
|
86
|
+
input: unknown
|
|
87
|
+
ctx: Context
|
|
88
|
+
request: Request
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** A server function's body in Rust: `remote('rust://search')` or `native('media')`, from `@kerf-js/start/rust` (research 36, 37). */
|
|
92
|
+
export interface Impl {
|
|
93
|
+
readonly kind: string
|
|
94
|
+
readonly target: string
|
|
95
|
+
readonly service: string
|
|
96
|
+
call(c: ImplCall): Promise<{ value: unknown; tags: string[]; touched: string[] }>
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Errors a function raises by name, with the data each carries: a Rust function's become an enum. */
|
|
100
|
+
export type Errors = Record<string, StandardSchemaV1>
|
|
101
|
+
|
|
102
|
+
/** `query()` with a `run` on this server. */
|
|
103
|
+
export interface QueryDef<S, O, A = undefined> extends FnOptions {
|
|
104
|
+
input?: S
|
|
105
|
+
/** The result's shape: checked in dev and tests (C002), and the contract's `output`. */
|
|
106
|
+
output?: StandardSchemaV1
|
|
107
|
+
/** Who may call it (`AuthScope`): `'user'`, `'public'`, `{ role }` or `{ can }`. The contract's auth scope. */
|
|
108
|
+
auth?: A
|
|
109
|
+
/** How often one caller may call it (`Limit`): `{ max: 30, window: 60 }`. */
|
|
110
|
+
limit?: Limit
|
|
111
|
+
/** An example result, for what `output` can't say: sizes a pending view (research 31 §2). */
|
|
112
|
+
shape?: O extends (infer R)[] ? DeepPartial<R>[] : DeepPartial<O>
|
|
113
|
+
/** What invalidates it: the client cache, the request cache and the shared cache all go by these. */
|
|
114
|
+
tags?: QueryTags<Out<S>, A>
|
|
115
|
+
/** `required: true`: `kerf check` and `kerf build` fail on a target with no real change feed, and the server won't start without one (R013, R015). */
|
|
116
|
+
live?: {
|
|
117
|
+
required?: boolean
|
|
118
|
+
/** A real round trip against a target that isn't production, in `kerf check` and `kerf build`. `true` finds `KERF_STAGING_URL` or `STAGING_DATABASE_URL`; a string names a target in `live.targets`. */
|
|
119
|
+
verify?: true | string | VerifyOptions
|
|
120
|
+
}
|
|
121
|
+
/** Turn on the shared server cache (across requests). Omit it and the query runs once per request. */
|
|
122
|
+
cache?: {
|
|
123
|
+
life?: Life
|
|
124
|
+
/** One cached value per signed-in user: `ctx.user` is readable. */ scope?: 'user'
|
|
125
|
+
/** When a change invalidates it, run it again at once in the background, so the next visitor finds it ready
|
|
126
|
+
* instead of paying for the miss. For what every visitor reads: a menu, settings, a search index. */
|
|
127
|
+
warm?: boolean
|
|
128
|
+
}
|
|
129
|
+
/** Named failures, for the client as `FnError.code` and `.data`. */
|
|
130
|
+
errors?: Errors
|
|
131
|
+
run: (args: { input: Out<S>; ctx: Ctx<A> }) => O | Promise<O>
|
|
132
|
+
impl?: undefined
|
|
133
|
+
/** Set by the `kerf:start` plugin: `<export>.<file hash>`. */
|
|
134
|
+
$id?: string
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** The same declaration with its body elsewhere: `output` is required, because it's the whole contract for what comes back. */
|
|
138
|
+
export type ImplQueryDef<S, OS extends StandardSchemaV1, A = undefined> = Omit<
|
|
139
|
+
QueryDef<S, Out<OS>, A>,
|
|
140
|
+
'run' | 'impl' | 'output'
|
|
141
|
+
> & { output: OS; impl: Impl; run?: undefined }
|
|
142
|
+
/** `mutation()` with `impl` and an `output` schema: no `run` here. */
|
|
143
|
+
export type ImplMutationDef<S, OS extends StandardSchemaV1, A = undefined> = Omit<
|
|
144
|
+
MutationDef<S, Out<OS>, A>,
|
|
145
|
+
'run' | 'impl' | 'output'
|
|
146
|
+
> & { output: OS; impl: Impl; run?: undefined }
|
|
147
|
+
|
|
148
|
+
/** `mutation()` with a `run` on this server. */
|
|
149
|
+
export interface MutationDef<S, O, A = undefined> extends FnOptions {
|
|
150
|
+
input?: S
|
|
151
|
+
output?: StandardSchemaV1
|
|
152
|
+
/** Who may call it. In an app with auth (`ctx.user` exists) a mutation needs a signed-in user unless it says `'public'`. */
|
|
153
|
+
auth?: A
|
|
154
|
+
/** How often one caller may call it (`Limit`): `{ max: 5, window: 60 }`. */
|
|
155
|
+
limit?: Limit
|
|
156
|
+
/** Tags whose queries the response refreshes (single-flight) and whose cached values it drops. */
|
|
157
|
+
invalidates?: Tags<[input: Out<S>, result: Awaited<O>]>
|
|
158
|
+
/** Client only: predict the result. Each call's layers are re-applied on new values until it settles. */
|
|
159
|
+
optimistic?: (args: { input: In<S> }, cache: OptimisticCache) => void
|
|
160
|
+
errors?: Errors
|
|
161
|
+
run: (args: { input: Out<S>; ctx: Ctx<A> }) => O | Promise<O>
|
|
162
|
+
impl?: undefined
|
|
163
|
+
$id?: string
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
type Arg<I> = I | (() => I | Skip)
|
|
167
|
+
|
|
168
|
+
/** What `query()` returns: call it for a resource, or `.live()` for one that stays current. */
|
|
169
|
+
export interface Query<I, O> {
|
|
170
|
+
/** The live value, read in a component or a defineState setup (Q001 elsewhere: use `fetch`). */
|
|
171
|
+
(
|
|
172
|
+
...args: [I] extends [void] ? [input?: undefined | (() => undefined | Skip)] : [input: Arg<I>]
|
|
173
|
+
): Resource<O>
|
|
174
|
+
/** The value as a promise: in `load`, handlers, server code and tests. Through the request or client cache. */
|
|
175
|
+
fetch(...args: [I] extends [void] ? [] : [input: I]): Promise<O>
|
|
176
|
+
/** A placeholder result to size a pending view by (last seen, else declared), or undefined when nothing is known. */
|
|
177
|
+
shape(...args: [I] extends [void] ? [] : [input: I]): O | undefined
|
|
178
|
+
/**
|
|
179
|
+
* The same value, refetched whenever a mutation anywhere invalidates one of its tags. `.live` is the connection's
|
|
180
|
+
* status. `keep`: how long the subscription outlives its last reader (`'30s'`, `'session'`).
|
|
181
|
+
*/
|
|
182
|
+
live(
|
|
183
|
+
...args: [I] extends [void]
|
|
184
|
+
? [input?: undefined | (() => undefined | Skip), options?: LiveOptions]
|
|
185
|
+
: [input: Arg<I>, options?: LiveOptions]
|
|
186
|
+
): LiveQuery<O>
|
|
187
|
+
readonly kind: 'query'
|
|
188
|
+
readonly $id: string
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** What `mutation()` returns: call it, or read its `pending` and `error`. */
|
|
192
|
+
export interface Mutation<I, O> {
|
|
193
|
+
(...args: [I] extends [void] ? [] : [input: I]): Promise<O>
|
|
194
|
+
/** A call is in flight. */
|
|
195
|
+
readonly pending: Derived<boolean>
|
|
196
|
+
/** The last call's failure, until the next call succeeds. */
|
|
197
|
+
readonly error: Derived<unknown>
|
|
198
|
+
readonly kind: 'mutation'
|
|
199
|
+
readonly $id: string
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** `degraded`: connected, and writes from outside the app arrive late or not at all. `.liveMode` says which. */
|
|
203
|
+
export type LiveStatus = 'connecting' | 'live' | 'degraded' | 'reconnecting' | 'offline'
|
|
204
|
+
/**
|
|
205
|
+
* How writes reach this page. `app`: mutations only, no `changes` configured. `feed`: the database reports every change.
|
|
206
|
+
* `external`: a separate listener does, through the bus. `poll`: an estimate, every few seconds. `off`: mutations only, though `changes` asks for more.
|
|
207
|
+
*/
|
|
208
|
+
export type LiveMode = 'app' | 'feed' | 'external' | 'poll' | 'off'
|
|
209
|
+
/** `.live()`: how long it's kept, and whether it refuses to run without a real feed. */
|
|
210
|
+
export interface LiveOptions {
|
|
211
|
+
keep?: string | number
|
|
212
|
+
/** Fail `kerf check`, `kerf build` and server startup rather than run without a real change feed (R013, R015). */
|
|
213
|
+
required?: boolean
|
|
214
|
+
}
|
|
215
|
+
/** A resource that also says how live it is. */
|
|
216
|
+
export type LiveQuery<O> = Resource<O> & {
|
|
217
|
+
readonly live: Derived<LiveStatus>
|
|
218
|
+
readonly liveMode: Derived<LiveMode>
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Any definition, as the executor and transports see it. */
|
|
222
|
+
export interface Fn {
|
|
223
|
+
kind: 'query' | 'mutation' | 'stream' | 'channel' | 'shared'
|
|
224
|
+
$id: string
|
|
225
|
+
def: {
|
|
226
|
+
input?: StandardSchemaV1
|
|
227
|
+
output?: StandardSchemaV1
|
|
228
|
+
message?: StandardSchemaV1
|
|
229
|
+
shape?: unknown
|
|
230
|
+
auth?: AuthScope
|
|
231
|
+
limit?: Limit
|
|
232
|
+
run?: (args: {
|
|
233
|
+
input: unknown
|
|
234
|
+
ctx: Context
|
|
235
|
+
signal?: AbortSignal
|
|
236
|
+
lastEventId?: unknown
|
|
237
|
+
}) => unknown
|
|
238
|
+
impl?: Impl
|
|
239
|
+
errors?: Errors
|
|
240
|
+
tags?: Tags<[input: unknown, ctx?: Context]>
|
|
241
|
+
cache?: { life?: Life; scope?: 'user'; warm?: boolean }
|
|
242
|
+
invalidates?: Tags<[unknown, unknown]>
|
|
243
|
+
optimistic?: (args: { input: unknown }, cache: OptimisticCache) => void
|
|
244
|
+
/** `channel` and `sharedState` (research 32). */
|
|
245
|
+
params?: StandardSchemaV1
|
|
246
|
+
authorize?: unknown
|
|
247
|
+
left?: (args: { id: string; ctx: Context; params: unknown; room: unknown }) => unknown
|
|
248
|
+
recheck?: (args: { id: string; ctx: Context; reply: unknown }) => unknown
|
|
249
|
+
client?: Record<string, StandardSchemaV1>
|
|
250
|
+
server?: Record<string, StandardSchemaV1>
|
|
251
|
+
on?: Record<string, (args: never) => unknown>
|
|
252
|
+
limits?: { perSecond?: number }
|
|
253
|
+
key?: StandardSchemaV1
|
|
254
|
+
value?: StandardSchemaV1
|
|
255
|
+
initial?: unknown
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** One cached entry as the server sends it: `[id, input, value, tags]` (page payload, navigation, refreshes). */
|
|
260
|
+
export type Wire = [id: string, input: unknown, value: unknown, tags: string[]]
|
|
261
|
+
|
|
262
|
+
/** What the transports answer (research 27 §3). */
|
|
263
|
+
export interface Answer {
|
|
264
|
+
v?: unknown
|
|
265
|
+
t?: string[]
|
|
266
|
+
c?: Wire[]
|
|
267
|
+
r?: string
|
|
268
|
+
/** `r` is a full load: the session changed, so nothing cached may survive. */ x?: 1
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** How a client call reaches the server: `fetch` by default, a fake under test. */
|
|
272
|
+
export interface Transport {
|
|
273
|
+
query(id: string, input: unknown): Promise<Answer>
|
|
274
|
+
/** `form`: the input came from a form, so strings may be coerced; a FormData is sent as is (it holds files). */
|
|
275
|
+
mutate(
|
|
276
|
+
id: string,
|
|
277
|
+
input: unknown,
|
|
278
|
+
refresh: [string, unknown][],
|
|
279
|
+
form?: true | FormData,
|
|
280
|
+
): Promise<Answer>
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** @kerf-js/core/test's fake-transport controls (research 27 §7). */
|
|
284
|
+
export interface NetControl {
|
|
285
|
+
latency: number
|
|
286
|
+
ctx?: object
|
|
287
|
+
/** Server extensions for this test (`net.extension`). */
|
|
288
|
+
extensions: ServerExtension[]
|
|
289
|
+
online(): boolean
|
|
290
|
+
fails: Map<string, unknown[]>
|
|
291
|
+
handlers: Map<string, (input: unknown, ctx: Context) => unknown>
|
|
292
|
+
log: { id: string; kind: string; input: unknown }[]
|
|
293
|
+
inflight: Set<Promise<unknown>>
|
|
294
|
+
als: { run<T>(store: unknown, fn: () => T): T; getStore(): unknown }
|
|
295
|
+
resets: (() => unknown)[]
|
|
296
|
+
/** Subscriptions an owner holds: open at the end of a test, they're T012. */
|
|
297
|
+
open: Map<object, [what: string, close: () => void]>
|
|
298
|
+
/** The realtime fake, while one is connected: `net.push`, `net.poke`, `net.drop`. */
|
|
299
|
+
rt?:
|
|
300
|
+
| {
|
|
301
|
+
push(id: string, msg: unknown): number
|
|
302
|
+
poke(tags: string[]): Promise<void>
|
|
303
|
+
drop(): void
|
|
304
|
+
subscriptions(): { kind: string; id: string; input: unknown }[]
|
|
305
|
+
}
|
|
306
|
+
| undefined
|
|
307
|
+
/** The channel fake, while a socket is open. */
|
|
308
|
+
ws?:
|
|
309
|
+
| {
|
|
310
|
+
publish(id: string, params: unknown, name: string, msg: unknown): Promise<void>
|
|
311
|
+
drop(): void
|
|
312
|
+
recheck(): Promise<void>
|
|
313
|
+
}
|
|
314
|
+
| undefined
|
|
315
|
+
/** What this client's sockets sent, across reconnects. */
|
|
316
|
+
sent: { id: string; name: string; msg: unknown }[]
|
|
317
|
+
reconnects: number
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** A query handle, whatever its input: what the cache needs of one. */
|
|
321
|
+
export type QueryRef<O> = Pick<Query<void, O>, 'kind' | '$id'> & {
|
|
322
|
+
fetch(...args: never[]): Promise<O>
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** The cache as an `optimistic` sees it. */
|
|
326
|
+
export interface OptimisticCache {
|
|
327
|
+
/** Change a query's cached value with a draft (copy-on-write: untouched rows keep their identity). */
|
|
328
|
+
update<O>(q: QueryRef<O>, input: unknown, recipe: (draft: O) => O | void): void
|
|
329
|
+
set<O>(q: QueryRef<O>, input: unknown, value: O): void
|
|
330
|
+
get<O>(q: QueryRef<O>, input?: unknown): O | undefined
|
|
331
|
+
/** The value (a row) was made by a pending optimistic layer. */
|
|
332
|
+
isOptimistic(value: unknown): boolean
|
|
333
|
+
}
|
package/src/data.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// Server functions and the client data cache (research 27). `query`/`mutation` definitions live in server modules
|
|
2
|
+
// (`src/server/**`, `*.server.ts`); the `kerf:start` plugin gives each an id and, for the client, strips everything
|
|
3
|
+
// but `optimistic`. One definition is then:
|
|
4
|
+
//
|
|
5
|
+
// - on the server: `q.fetch(input)` runs `run` through the request cache (exec.ts), at most once per request;
|
|
6
|
+
// - in a component or scope: `q(input)` is a `Query` (a Resource) reading the client cache. Its fetcher reads the
|
|
7
|
+
// entry's value, so a new server value or an optimistic layer updates every reader in place;
|
|
8
|
+
// - a mutation `m(input)` POSTs, applies `optimistic` layers at once, and settles with the refreshed queries the
|
|
9
|
+
// server sends back in the same response (single-flight).
|
|
10
|
+
//
|
|
11
|
+
// The cache entry's value is `base` with each pending layer applied. New bases are structurally shared with the old
|
|
12
|
+
// one, so unchanged rows keep their identity and `For` keeps them. This module ships to the client; the executor
|
|
13
|
+
// (exec.ts) is the server's, and the in-process fake transport @kerf-js/core/test turns on loads it on demand. Realtime
|
|
14
|
+
// (research 30) costs a query app one method here: `q.live()` imports live.ts on its first call.
|
|
15
|
+
|
|
16
|
+
import type { MediaAsset } from '@kerf-js/core/media'
|
|
17
|
+
import { cache, resetRetry } from './data/cache'
|
|
18
|
+
import { configureReset, currentScope, runtime } from './data/foundation'
|
|
19
|
+
import { StartError } from './data/primitives'
|
|
20
|
+
import { resetMutation } from './data/mutation'
|
|
21
|
+
|
|
22
|
+
export type {
|
|
23
|
+
VerifyOptions,
|
|
24
|
+
StandardSchemaV1,
|
|
25
|
+
SchemaResult,
|
|
26
|
+
SchemaIssue,
|
|
27
|
+
Life,
|
|
28
|
+
Limit,
|
|
29
|
+
AuthScope,
|
|
30
|
+
ImplCall,
|
|
31
|
+
Impl,
|
|
32
|
+
Errors,
|
|
33
|
+
QueryDef,
|
|
34
|
+
ImplQueryDef,
|
|
35
|
+
ImplMutationDef,
|
|
36
|
+
MutationDef,
|
|
37
|
+
Query,
|
|
38
|
+
Mutation,
|
|
39
|
+
LiveStatus,
|
|
40
|
+
LiveMode,
|
|
41
|
+
LiveOptions,
|
|
42
|
+
LiveQuery,
|
|
43
|
+
Fn,
|
|
44
|
+
Wire,
|
|
45
|
+
Answer,
|
|
46
|
+
Transport,
|
|
47
|
+
NetControl,
|
|
48
|
+
QueryRef,
|
|
49
|
+
OptimisticCache,
|
|
50
|
+
} from './data/types'
|
|
51
|
+
export {
|
|
52
|
+
StartError,
|
|
53
|
+
FnError,
|
|
54
|
+
redirect,
|
|
55
|
+
isRedirect,
|
|
56
|
+
raise,
|
|
57
|
+
invalid,
|
|
58
|
+
fieldsOf,
|
|
59
|
+
decodeForm,
|
|
60
|
+
stable,
|
|
61
|
+
keyOf,
|
|
62
|
+
} from './data/primitives'
|
|
63
|
+
export type { Redirect } from './data/primitives'
|
|
64
|
+
export {
|
|
65
|
+
skip,
|
|
66
|
+
fns,
|
|
67
|
+
runtime,
|
|
68
|
+
rt,
|
|
69
|
+
stale,
|
|
70
|
+
net,
|
|
71
|
+
SUBMIT,
|
|
72
|
+
fnOf,
|
|
73
|
+
currentScope,
|
|
74
|
+
enter,
|
|
75
|
+
} from './data/foundation'
|
|
76
|
+
export type { Skip } from './data/foundation'
|
|
77
|
+
export { http, fakeScope, track } from './data/transport'
|
|
78
|
+
export { share, produce } from './data/draft'
|
|
79
|
+
export { seed, cache, invalidate } from './data/cache'
|
|
80
|
+
export { after, preview } from './data/after'
|
|
81
|
+
export { liveApi } from './data/live-api'
|
|
82
|
+
export type { LiveApi } from './data/live-api'
|
|
83
|
+
export { query, mutation } from './data/definitions'
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Run a query or mutation by `$id` as the caller of the request in progress: its schema, `auth`, every extension's
|
|
87
|
+
* `guard` and its invalidations, as a browser call would. Server code only: `@kerf-js/agent` runs tools this way.
|
|
88
|
+
*/
|
|
89
|
+
export function serverCall(id: string, input?: unknown): Promise<unknown> {
|
|
90
|
+
const scope = currentScope()
|
|
91
|
+
if (!scope || !runtime.exec)
|
|
92
|
+
return Promise.reject(
|
|
93
|
+
new StartError(
|
|
94
|
+
'Q020',
|
|
95
|
+
`\`serverCall('${id}')\` outside a request`,
|
|
96
|
+
'call it from a query, mutation, `load` or extension route',
|
|
97
|
+
{ status: 500 },
|
|
98
|
+
),
|
|
99
|
+
)
|
|
100
|
+
return runtime.exec.callById(scope, id, input)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* What `run` and `load` get. Augment it with what `src/context.server.ts` returns:
|
|
105
|
+
* `declare module '@kerf-js/start' { interface Context { db: Db; user: User | null } }`.
|
|
106
|
+
*/
|
|
107
|
+
export interface Context {
|
|
108
|
+
request: Request
|
|
109
|
+
/** Headers merged into the response (cookies a sign-in sets). */
|
|
110
|
+
response: { headers: Headers }
|
|
111
|
+
/** Uploads and CMS images (research 29 §6): `ingest` stores the original and returns the record `z.media()` validates. */
|
|
112
|
+
media: { ingest(file: Blob | Uint8Array, options?: { name?: string }): Promise<MediaAsset> }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The address the server saw (never one a client sent): Better Auth's rate limits key on it. */
|
|
116
|
+
export const CLIENT_IP = 'x-kerf-client-ip'
|
|
117
|
+
|
|
118
|
+
/** Options a plugin adds to `query` and `mutation`, by augmenting this; its extension's `guard` reads them. Empty here. */
|
|
119
|
+
export interface FnOptions {}
|
|
120
|
+
|
|
121
|
+
configureReset(() => {
|
|
122
|
+
cache.clear()
|
|
123
|
+
resetRetry()
|
|
124
|
+
resetMutation()
|
|
125
|
+
})
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// Bun's built-in driver has no types on Node, where this package is checked: only what `open` calls.
|
|
2
|
+
declare module 'bun:sqlite' {
|
|
3
|
+
/** One open database file. */
|
|
4
|
+
export class Database {
|
|
5
|
+
constructor(path: string, options: { create: boolean })
|
|
6
|
+
prepare(text: string): {
|
|
7
|
+
run(...params: unknown[]): unknown
|
|
8
|
+
values(...params: unknown[]): unknown[][]
|
|
9
|
+
}
|
|
10
|
+
run(text: string): unknown
|
|
11
|
+
close(): void
|
|
12
|
+
}
|
|
13
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// The change feed on MySQL. A trigger can't reach a client and the binlog needs replication rights, so triggers write a
|
|
2
|
+
// log and this reads it on a timer: polling, and it says so. An AUTO_INCREMENT id is taken before commit, so a long
|
|
3
|
+
// transaction can land behind the mark: each look re-reads a window behind it.
|
|
4
|
+
|
|
5
|
+
import type { Pool } from 'mysql2/promise'
|
|
6
|
+
import { LOG, MAX_IDS } from '../changes-sql.mjs'
|
|
7
|
+
import type { Change, Probe, Sink } from '../changes'
|
|
8
|
+
|
|
9
|
+
const BEHIND = 512
|
|
10
|
+
const KEEP_HOURS = 1
|
|
11
|
+
const PRUNE = 60_000
|
|
12
|
+
|
|
13
|
+
interface Options {
|
|
14
|
+
pool: Pool
|
|
15
|
+
tables: string[]
|
|
16
|
+
interval?: number
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** A bigint column: the driver's number, or its string once past 2^53. */
|
|
20
|
+
type Seq = number | string
|
|
21
|
+
const said = (e: unknown) => (e as Error | null)?.message ?? String(e)
|
|
22
|
+
|
|
23
|
+
async function probeMysql(pool: Pool, tables: string[], interval: number): Promise<Probe> {
|
|
24
|
+
try {
|
|
25
|
+
const [rows] = await pool.query(
|
|
26
|
+
`select event_object_table as t from information_schema.triggers where trigger_schema = database() and trigger_name like 'kerf\\_changes\\_%\\_upd'`,
|
|
27
|
+
)
|
|
28
|
+
const have = (rows as { t: string }[]).map((r) => r.t)
|
|
29
|
+
const missing = tables.filter((t) => !have.includes(t))
|
|
30
|
+
if (!missing.length)
|
|
31
|
+
return {
|
|
32
|
+
mode: 'feed',
|
|
33
|
+
via: 'mysql-log',
|
|
34
|
+
why: `read every ${interval} ms: MySQL can't push`,
|
|
35
|
+
}
|
|
36
|
+
const [grants] = await pool.query('show grants').catch(() => [[]])
|
|
37
|
+
const may = (grants as Record<string, string>[]).some((g) =>
|
|
38
|
+
/ALL PRIVILEGES|\bTRIGGER\b/.test(Object.values(g)[0] ?? ''),
|
|
39
|
+
)
|
|
40
|
+
return {
|
|
41
|
+
mode: 'off',
|
|
42
|
+
via: 'none',
|
|
43
|
+
why: `no trigger on ${missing.map((t) => `\`${t}\``).join(', ')}, and MySQL has no counter to fall back on`,
|
|
44
|
+
fix: may
|
|
45
|
+
? 'run `kerf db live`, then apply the migration'
|
|
46
|
+
: 'run `kerf db live`, and apply the migration as a user with the TRIGGER privilege',
|
|
47
|
+
}
|
|
48
|
+
} catch (e) {
|
|
49
|
+
return {
|
|
50
|
+
mode: 'off',
|
|
51
|
+
via: 'none',
|
|
52
|
+
why: `the database didn't answer: ${said(e)}`,
|
|
53
|
+
fix: 'check `DATABASE_URL`',
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function mysqlChanges({ pool, tables, interval = 500 }: Options) {
|
|
59
|
+
const probe = () => probeMysql(pool, tables, interval)
|
|
60
|
+
|
|
61
|
+
async function start(sink: Sink, how: Probe) {
|
|
62
|
+
if (how.mode === 'off') return () => {}
|
|
63
|
+
let stopped = false,
|
|
64
|
+
timer: ReturnType<typeof setTimeout> | undefined,
|
|
65
|
+
failed = false,
|
|
66
|
+
pruned = Date.now()
|
|
67
|
+
const [[{ top }]] = (await pool.query(
|
|
68
|
+
`select coalesce(max(seq), 0) as top from ${LOG}`,
|
|
69
|
+
)) as unknown as [[{ top: number | string }]]
|
|
70
|
+
let mark = Number(top)
|
|
71
|
+
// What's already there is old news, and needs no poke.
|
|
72
|
+
const [old] = (await pool.query(`select seq from ${LOG} where seq > ?`, [
|
|
73
|
+
Math.max(0, mark - BEHIND),
|
|
74
|
+
])) as unknown as [{ seq: Seq }[]]
|
|
75
|
+
const seen = new Set<number>(old.map((r) => Number(r.seq)))
|
|
76
|
+
const look = async () => {
|
|
77
|
+
if (stopped) return
|
|
78
|
+
try {
|
|
79
|
+
const [rows] = (await pool.query(
|
|
80
|
+
`select seq, tbl, pk from ${LOG} where seq > ? order by seq limit 5000`,
|
|
81
|
+
[Math.max(0, mark - BEHIND)],
|
|
82
|
+
)) as unknown as [{ seq: Seq; tbl: string; pk: string | null }[]]
|
|
83
|
+
if (failed) {
|
|
84
|
+
failed = false
|
|
85
|
+
sink.lost()
|
|
86
|
+
sink.up()
|
|
87
|
+
}
|
|
88
|
+
const fresh = rows.filter((r) => !seen.has(Number(r.seq)))
|
|
89
|
+
const byTable = new Map<string, Set<string> | null>()
|
|
90
|
+
for (const r of fresh) {
|
|
91
|
+
seen.add(Number(r.seq))
|
|
92
|
+
if (r.pk === null) byTable.set(r.tbl, null)
|
|
93
|
+
else if (byTable.get(r.tbl) !== null) {
|
|
94
|
+
const ids = byTable.get(r.tbl) ?? new Set()
|
|
95
|
+
ids.add(r.pk)
|
|
96
|
+
byTable.set(r.tbl, ids.size > MAX_IDS ? null : ids)
|
|
97
|
+
}
|
|
98
|
+
mark = Math.max(mark, Number(r.seq))
|
|
99
|
+
}
|
|
100
|
+
for (const s of seen) if (s <= mark - BEHIND) seen.delete(s)
|
|
101
|
+
const list: Change[] = []
|
|
102
|
+
for (const [table, ids] of byTable)
|
|
103
|
+
ids ? list.push(...[...ids].map((id) => ({ table, id }))) : list.push({ table })
|
|
104
|
+
if (list.length) sink.changes(list)
|
|
105
|
+
if (Date.now() - pruned > PRUNE) {
|
|
106
|
+
pruned = Date.now()
|
|
107
|
+
await pool.query(
|
|
108
|
+
`delete from ${LOG} where at < now() - interval ${KEEP_HOURS} hour limit 10000`,
|
|
109
|
+
)
|
|
110
|
+
}
|
|
111
|
+
} catch (e) {
|
|
112
|
+
failed = true
|
|
113
|
+
sink.down(`MySQL watcher: ${said(e)}`)
|
|
114
|
+
}
|
|
115
|
+
timer = setTimeout(() => void look(), interval)
|
|
116
|
+
;(timer as { unref?(): void }).unref?.()
|
|
117
|
+
}
|
|
118
|
+
await look()
|
|
119
|
+
return () => {
|
|
120
|
+
stopped = true
|
|
121
|
+
clearTimeout(timer)
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
return { probe, start }
|
|
126
|
+
}
|