@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,56 @@
1
+ import type { PublishOptions } from '../channel'
2
+ import { stable, StartError, type Fn } from '../data'
3
+ import { hub } from '../hub'
4
+ import { check } from './check'
5
+
6
+ const roomName = (id: string, params: unknown) => `kerf:c:${id}:${stable(params)}`
7
+
8
+ /** `room.publish` and `room.in(params).publish`. */
9
+ export async function publish(
10
+ fn: Fn,
11
+ params: unknown,
12
+ name: string,
13
+ message: unknown,
14
+ o: PublishOptions & { from?: string } = {},
15
+ ) {
16
+ const h = hub()
17
+ const valid = await check(
18
+ fn.kind === 'shared' ? fn.def.key : fn.def.params,
19
+ params,
20
+ `\`${fn.$id}\`'s params`,
21
+ )
22
+ if (h.dev) {
23
+ const schema = Object.hasOwn(fn.def.server ?? {}, name) ? fn.def.server![name] : undefined
24
+ if (!schema)
25
+ throw new StartError(
26
+ 'C002',
27
+ `\`${fn.$id}\` has no server message \`${name}\``,
28
+ 'add it to `server`',
29
+ { status: 500 },
30
+ )
31
+ const r = await schema['~standard'].validate(message)
32
+ if (r.issues)
33
+ throw new StartError(
34
+ 'C002',
35
+ `\`${fn.$id}.${name}\` was published with a message its schema rejects: ${r.issues.map((i) => i.message).join('; ')}`,
36
+ 'fix the message, or the schema',
37
+ { status: 500 },
38
+ )
39
+ }
40
+ // `v` first: the hub reads it off the front of the string, to leave the ring alone.
41
+ const raw = JSON.stringify({
42
+ ...(o.volatile && { v: 1 }),
43
+ ...(o.from && { f: o.from }),
44
+ ...(o.exceptSelf && { x: 1 }),
45
+ ...(o.to && { t: o.to }),
46
+ n: name,
47
+ m: message,
48
+ })
49
+ if (raw.length > h.limits.message)
50
+ throw new StartError(
51
+ 'R008',
52
+ `a \`${fn.$id}\` message is ${raw.length} bytes; a message may be ${h.limits.message}`,
53
+ 'publish less, or an id subscribers fetch',
54
+ )
55
+ await h.bus.publish(roomName(fn.$id, valid), raw)
56
+ }
@@ -0,0 +1,41 @@
1
+ import type { Hub, Ev } from '../hub'
2
+ import type { Hubbed, Room, Value } from './types'
3
+
4
+ export const VALUE = '$v',
5
+ ASK = '$?'
6
+ const VALUES = 10_000
7
+
8
+ export function room(h: Hub, st: Hubbed, name: string, shared: boolean): Room {
9
+ let r = st.rooms.get(name)
10
+ if (r) return (r.refs++, r)
11
+ const ch = h.channel(name)
12
+ const on = (ev: Ev | null) => {
13
+ if (!ev || !shared) return
14
+ const m = (ev.p ??= JSON.parse(ev.raw)) as { n: string; m: never }
15
+ if (m.n === VALUE) store(st, name, m.m)
16
+ else if (m.n === ASK) {
17
+ const v = st.values.get(name)
18
+ if (v) void h.bus.publish(name, JSON.stringify({ n: VALUE, m: v }))
19
+ }
20
+ }
21
+ ch.listeners.add(on)
22
+ r = { name, ch, refs: 1, shared, on }
23
+ st.rooms.set(name, r)
24
+ if (shared && !st.values.has(name))
25
+ void ch.ready.then(() => h.bus.publish(name, JSON.stringify({ n: ASK })))
26
+ return r
27
+ }
28
+
29
+ export function leaveRoom(h: Hub, st: Hubbed, r: Room) {
30
+ if (--r.refs) return
31
+ st.rooms.delete(r.name)
32
+ h.unlisten(r.ch, r.on)
33
+ }
34
+
35
+ export function store(st: Hubbed, name: string, v: Value) {
36
+ const had = st.values.get(name)
37
+ if (had && (had.at > v.at || (had.at === v.at && had.o >= v.o))) return
38
+ st.values.delete(name) // last in the map: the oldest key goes first
39
+ st.values.set(name, v)
40
+ if (st.values.size > VALUES) st.values.delete(st.values.keys().next().value!)
41
+ }
@@ -0,0 +1,79 @@
1
+ import { checkOrigins } from '../hub'
2
+ import type { Scope } from '../exec'
3
+ import type { Peer, Attached } from '../socket'
4
+
5
+ interface WsPeer {
6
+ id: string
7
+ send(text: string): unknown
8
+ close(code?: number, reason?: string): unknown
9
+ websocket?: { bufferedAmount?: number }
10
+ }
11
+
12
+ /** Nitro reads `crossws` off the response (research 32 §1). A refusal is a hook that throws, so no socket opens. */
13
+ export function socketRouteWith(
14
+ request: Request,
15
+ scope: Scope,
16
+ origins: string[],
17
+ attach: (peer: Peer, request: Request, scope: Scope) => Promise<Attached>,
18
+ ): Promise<Response> {
19
+ const hooks = (crossws: object) =>
20
+ Promise.resolve(Object.assign(new Response('Upgrade required', { status: 426 }), { crossws }))
21
+ const turnAway = (code: string, message: string, status: number) => {
22
+ scope.options.onDiagnostic?.({ code, severity: 'error', message })
23
+ // oxlint-disable only-throw-error -- crossws answers an upgrade with the Response its hook throws
24
+ return hooks({
25
+ upgrade() {
26
+ throw new Response(message, { status }) /* oxlint-enable only-throw-error */
27
+ },
28
+ })
29
+ }
30
+ if (request.headers.get('upgrade')?.toLowerCase() !== 'websocket')
31
+ return Promise.resolve(
32
+ new Response('Upgrade required', { status: 426, headers: { 'cache-control': 'no-store' } }),
33
+ )
34
+ try {
35
+ checkOrigins(origins)
36
+ } catch (e) {
37
+ return turnAway('R004', (e as Error).message, 500)
38
+ }
39
+ const origin = request.headers.get('origin')
40
+ if (!origin || (origin !== new URL(request.url).origin && !origins.includes(origin)))
41
+ return turnAway(
42
+ 'R010',
43
+ `R010: origin \`${origin ?? 'none'}\` may not open a socket: list it in \`realtime({ origins })\``,
44
+ 403,
45
+ )
46
+ const peers = new Map<string, Promise<Pick<Attached, 'message' | 'close'>>>()
47
+ const mux = new URL(request.url).searchParams.has('mux')
48
+ return hooks({
49
+ open(peer: WsPeer) {
50
+ const p: Peer = {
51
+ send: (t) => void peer.send(t),
52
+ close: (code, reason) => peer.close(code, reason),
53
+ backlog: () => peer.websocket?.bufferedAmount ?? 0,
54
+ }
55
+ peers.set(
56
+ peer.id,
57
+ (mux
58
+ ? import('../mux').then((m) => m.muxed(p, request, scope))
59
+ : attach(p, request, scope)
60
+ ).catch((e) => {
61
+ scope.options.onDiagnostic?.({
62
+ code: 'E_RT',
63
+ severity: 'error',
64
+ message: `/_kerf/ws: ${e instanceof Error ? (e.stack ?? e.message) : String(e)}`,
65
+ })
66
+ peer.close(1011, 'context failed')
67
+ return { message() {}, close() {} }
68
+ }),
69
+ )
70
+ },
71
+ message(peer: WsPeer, m: { text(): string }) {
72
+ void peers.get(peer.id)?.then((a) => a.message(m.text()))
73
+ },
74
+ close(peer: WsPeer) {
75
+ void peers.get(peer.id)?.then((a) => a.close())
76
+ peers.delete(peer.id)
77
+ },
78
+ })
79
+ }
@@ -0,0 +1,26 @@
1
+ import type { Fn } from '../data'
2
+ import { stable } from '../data'
3
+ import { hub, type Hub } from '../hub'
4
+ import { check } from './check'
5
+ import { store, VALUE } from './rooms'
6
+ import type { Hubbed, Value } from './types'
7
+
8
+ const roomName = (id: string, params: unknown) => `kerf:c:${id}:${stable(params)}`
9
+
10
+ export function sharedWriter(stateOf: (h: Hub) => Hubbed) {
11
+ /** A shared value written by the server: `deckSlide.in(key).set(3)`. */
12
+ return async function setShared(fn: Fn, key: unknown, value: unknown) {
13
+ const h = hub()
14
+ const valid = await check(fn.def.key, key, `\`${fn.$id}\`'s key`)
15
+ const v = await check(fn.def.value, value, `\`${fn.$id}\`'s value`)
16
+ const st = stateOf(h),
17
+ name = roomName(fn.$id, valid)
18
+ const stamp: Value = {
19
+ v,
20
+ at: Math.max(Date.now(), (st.values.get(name)?.at ?? 0) + 1),
21
+ o: h.epoch,
22
+ }
23
+ store(st, name, stamp)
24
+ await h.bus.publish(name, JSON.stringify({ n: VALUE, m: stamp }))
25
+ }
26
+ }
@@ -0,0 +1,48 @@
1
+ import type { Context, Fn } from '../data'
2
+ import type { ScopeOptions } from '../exec'
3
+ import type { Channel, Ev } from '../hub'
4
+ import type { Peer } from '../socket'
5
+
6
+ export interface Join {
7
+ n: number
8
+ fn: Fn
9
+ params: unknown
10
+ room?: Room
11
+ on?: (ev: Ev | null) => void
12
+ bucket: Bucket
13
+ gone?: boolean
14
+ chain: Promise<unknown>
15
+ }
16
+ export interface Bucket {
17
+ tokens: number
18
+ at: number
19
+ }
20
+ export interface Sock {
21
+ k: string
22
+ peer: Peer
23
+ request: Request
24
+ options: ScopeOptions
25
+ ctx: Context
26
+ user?: string | undefined
27
+ joins: Map<number, Join>
28
+ bucket: Bucket
29
+ last: number
30
+ timers: ReturnType<typeof setTimeout>[]
31
+ }
32
+ export interface Room {
33
+ name: string
34
+ ch: Channel
35
+ refs: number
36
+ shared: boolean
37
+ on: (ev: Ev | null) => void
38
+ }
39
+ export interface Value {
40
+ v: unknown
41
+ at: number
42
+ o: string
43
+ }
44
+ export interface Hubbed {
45
+ socks: Set<Sock>
46
+ rooms: Map<string, Room>
47
+ values: Map<string, Value>
48
+ }
package/src/socket.ts ADDED
@@ -0,0 +1,400 @@
1
+ // The server's half of `channel` and `sharedState` (research 32 §4): one socket per tab, many joins. `attach` knows
2
+ // nothing about crossws, so the same code runs behind `/_kerf/ws` and behind @kerf-js/core/test's fake. A room is a hub channel
3
+ // (`kerf:c:<id>:<params>`), so rings, cursors, gaps and fan-out are the hub's, and a join listens before it replays.
4
+ //
5
+ // checks the upgrade: exact Origin (a missing one is refused), a wildcard in `origins` (R004).
6
+ // authorize every join, and again every `limits.session` and on a poke of `session:<user>`. A gone user is 4401.
7
+ // limits frame size (1009), a token bucket per socket and per channel (1008), joins, sockets, send queue (1013).
8
+ // shared state last writer wins by `(at, instance)`. Instances hold the value; a new listener asks on the bus.
9
+
10
+ import type { PublishOptions } from './channel'
11
+ import { enter, fns, FnError, isRedirect, runtime, stable, StartError, type Context } from './data'
12
+ import { createScope, type Scope } from './exec'
13
+ import { hub, type Ev, type Hub } from './hub'
14
+ import type { Join, Sock, Hubbed, Value } from './socket/types'
15
+ import { room, leaveRoom, store, VALUE } from './socket/rooms'
16
+ import { take, check, allowed, denied } from './socket/check'
17
+ import { deliver } from './socket/deliver'
18
+ import { sharedWriter } from './socket/shared'
19
+ import { publish } from './socket/publish'
20
+ import { socketRouteWith } from './socket/route'
21
+ import { SHARE, shareChannel } from './share-server'
22
+
23
+ /** A socket as this file needs it. `send` takes a whole frame. */
24
+ export interface Peer {
25
+ send(text: string): void
26
+ close(code: number, reason?: string): void
27
+ backlog(): number
28
+ }
29
+
30
+ export interface Attached {
31
+ message(text: string): void
32
+ close(): void
33
+ /** The session re-check, now. */
34
+ recheck(): Promise<void>
35
+ }
36
+
37
+ /** A hub's sockets: a new hub (a dev reload, a test) starts empty. */
38
+ const states = new WeakMap<Hub, Hubbed>()
39
+
40
+ function stateOf(h: Hub): Hubbed {
41
+ const s = states.get(h)
42
+ if (s) return s
43
+ const made: Hubbed = { socks: new Set(), rooms: new Map(), values: new Map() }
44
+ states.set(h, made)
45
+ h.closing.add(() => {
46
+ for (const c of Array.from(made.socks)) gone(h, c, 1001)
47
+ })
48
+ h.watch((tags) => {
49
+ for (const t of tags) {
50
+ if (!t.startsWith('session:')) continue
51
+ for (const c of made.socks) if (c.user === t.slice(8)) void recheck(h, c)
52
+ }
53
+ })
54
+ return made
55
+ }
56
+
57
+ const unref = <T>(t: T) => ((t as { unref?(): void } | null | undefined)?.unref?.(), t)
58
+ const roomName = (id: string, params: unknown) => `kerf:c:${id}:${stable(params)}`
59
+ const SET = '$set'
60
+
61
+ const send = (c: Sock, out: unknown[]) => {
62
+ c.peer.send(JSON.stringify(out))
63
+ if (c.peer.backlog() > hub().limits.queue) gone(hub(), c, 1013)
64
+ }
65
+
66
+ const refuse = (c: Sock, n: number, e: { code?: string | undefined; message: string }) =>
67
+ send(c, ['e', n, { code: e.code, message: e.message }])
68
+
69
+ async function join(
70
+ h: Hub,
71
+ c: Sock,
72
+ want: { n: number; id: string; params: unknown; cursor?: string | undefined },
73
+ ) {
74
+ const { n, id, params, cursor } = want
75
+ const st = stateOf(h)
76
+ if (c.joins.has(n) || typeof n !== 'number') return
77
+ const fn = id === SHARE ? shareChannel(h) : fns.get(id)
78
+ if (fn?.kind !== 'channel' && fn?.kind !== 'shared')
79
+ return refuse(
80
+ c,
81
+ n,
82
+ new StartError('Q009', `no channel \`${id}\` (the page is older than the server): reload`),
83
+ )
84
+ if (c.joins.size >= h.limits.subscriptions)
85
+ return refuse(
86
+ c,
87
+ n,
88
+ new StartError(
89
+ 'R009',
90
+ `this socket already has ${h.limits.subscriptions} joins`,
91
+ 'join fewer rooms, or raise `limits.subscriptions`',
92
+ ),
93
+ )
94
+ const j: Join = {
95
+ n,
96
+ fn,
97
+ params,
98
+ bucket: { tokens: h.limits.burst, at: Date.now() },
99
+ chain: Promise.resolve(),
100
+ }
101
+ c.joins.set(n, j)
102
+ try {
103
+ j.params = await check(
104
+ fn.kind === 'shared' ? fn.def.key : fn.def.params,
105
+ params,
106
+ `\`${id}\`'s params`,
107
+ )
108
+ if (!(await allowed(fn, c.ctx, j.params))) throw denied(fn)
109
+ } catch (e) {
110
+ c.joins.delete(n)
111
+ return refuse(c, n, known(c, id, e))
112
+ }
113
+ if (j.gone) return
114
+ const name = roomName(id, j.params)
115
+ const r = (j.room = room(h, st, name, fn.kind === 'shared'))
116
+ const pending: Ev[] = []
117
+ let live = false,
118
+ lost = false
119
+ // Listen, then replay: a message published in between can't be lost (R006's rule).
120
+ j.on = (ev) => {
121
+ if (!ev) return live ? send(c, ['r', n, h.position()]) : void (lost = true)
122
+ if (live) deliver(c, j, h, ev, send)
123
+ else pending.push(ev)
124
+ }
125
+ r.ch.listeners.add(j.on)
126
+ try {
127
+ await r.ch.ready
128
+ } catch (e) {
129
+ leave(h, c, j)
130
+ return refuse(c, n, new StartError('R011', `\`${id}\`: the bus is down`, undefined))
131
+ }
132
+ if (j.gone) return
133
+ const back = cursor ? h.replay(r.ch, cursor) : []
134
+ send(c, ['j', n, h.position()])
135
+ if (!back || lost) {
136
+ send(c, ['r', n, h.position()])
137
+ pending.length = 0
138
+ } else {
139
+ const seen = new Set(back.map((e) => e.seq))
140
+ for (const ev of [...back, ...pending.filter((e) => !seen.has(e.seq))].sort(
141
+ (a, b) => a.seq - b.seq,
142
+ ))
143
+ deliver(c, j, h, ev, send)
144
+ }
145
+ live = true
146
+ const v = st.values.get(name)
147
+ if (fn.kind === 'shared' && v) send(c, ['m', n, h.position(), VALUE, v])
148
+ }
149
+
150
+ function leave(h: Hub, c: Sock, j: Join) {
151
+ j.gone = true
152
+ c.joins.delete(j.n)
153
+ if (j.room && j.on) {
154
+ j.room.ch.listeners.delete(j.on)
155
+ leaveRoom(h, stateOf(h), j.room)
156
+ if (j.fn.def.left) void left(c, j)
157
+ }
158
+ }
159
+
160
+ const bound = (c: Sock, j: Join) => ({
161
+ params: j.params,
162
+ publish: (n: string, m: unknown, o?: PublishOptions) =>
163
+ publish(j.fn, j.params, n, m, { ...o, from: c.k }),
164
+ })
165
+
166
+ /** To this connection, past the bus: only `share` uses it, and it has already picked who hears what. */
167
+ const reply = (h: Hub, c: Sock, j: Join) => (name: string, msg: unknown) => {
168
+ if (!j.gone) send(c, ['m', j.n, h.position(), name, msg])
169
+ }
170
+
171
+ /** `def.left`, once per join that got in, however it ended. Nothing is listening for a failure, so it's reported. */
172
+ async function left(c: Sock, j: Join) {
173
+ const scope: Scope = { ...createScope(c.request, c.options), ctx: () => Promise.resolve(c.ctx) }
174
+ try {
175
+ await enter(scope, () =>
176
+ j.fn.def.left!({ id: c.k, ctx: c.ctx, params: j.params, room: bound(c, j) }),
177
+ )
178
+ } catch (e) {
179
+ known(c, j.fn.$id, e)
180
+ }
181
+ }
182
+
183
+ const known = (
184
+ c: Sock,
185
+ id: string,
186
+ e: unknown,
187
+ ): { code?: string | undefined; message: string; issues?: unknown } => {
188
+ if (e instanceof StartError || e instanceof FnError)
189
+ return { code: e.code, message: e.message, ...(e.issues && { issues: e.issues }) }
190
+ c.options.onDiagnostic?.({
191
+ code: 'E_RT',
192
+ severity: 'error',
193
+ message: `${id}: ${e instanceof Error ? (e.stack ?? e.message) : String(e)}`,
194
+ })
195
+ return { message: c.options.dev && e instanceof Error ? e.message : 'Message failed.' }
196
+ }
197
+
198
+ /** A message from the client: validated, its handler run in a fresh scope, the ack sent. In order within a join. */
199
+ async function run(h: Hub, c: Sock, j: Join, call: { ack: number; name: string; msg: unknown }) {
200
+ const { ack, name, msg } = call
201
+ const fn = j.fn
202
+ try {
203
+ if (fn.kind === 'shared') {
204
+ if (name !== SET) throw new StartError('Q002', `\`${fn.$id}\` takes no message \`${name}\``)
205
+ const v = await check(fn.def.value, msg, `\`${fn.$id}\`'s value`)
206
+ if (!(await allowed(fn, c.ctx, j.params, true))) throw denied(fn)
207
+ const st = stateOf(h),
208
+ key = j.room!.name
209
+ const stamp: Value = {
210
+ v,
211
+ at: Math.max(Date.now(), (st.values.get(key)?.at ?? 0) + 1),
212
+ o: h.epoch,
213
+ }
214
+ store(st, key, stamp)
215
+ await h.bus.publish(key, JSON.stringify({ f: c.k, n: VALUE, m: stamp }))
216
+ } else {
217
+ const schema = Object.hasOwn(fn.def.client ?? {}, name) ? fn.def.client![name] : undefined
218
+ const handler = Object.hasOwn(fn.def.on ?? {}, name) ? fn.def.on![name] : undefined
219
+ if (!schema || !handler)
220
+ throw new StartError(
221
+ 'Q002',
222
+ `\`${fn.$id}\` takes no message \`${name}\``,
223
+ 'name one of `client`, with a handler in `on`',
224
+ )
225
+ const valid = await check(schema, msg, `\`${fn.$id}.${name}\``)
226
+ const scope: Scope = {
227
+ ...createScope(c.request, c.options),
228
+ ctx: () => Promise.resolve(c.ctx),
229
+ }
230
+ await enter(scope, () =>
231
+ handler({
232
+ msg: valid,
233
+ id: c.k,
234
+ ctx: c.ctx,
235
+ params: j.params,
236
+ room: bound(c, j),
237
+ reply: reply(h, c, j),
238
+ } as never),
239
+ )
240
+ }
241
+ if (!j.gone) send(c, ['a', j.n, ack])
242
+ } catch (e) {
243
+ if (isRedirect(e)) return void (!j.gone && send(c, ['a', j.n, ack]))
244
+ if (!j.gone) send(c, ['a', j.n, ack, known(c, fn.$id, e)])
245
+ }
246
+ }
247
+
248
+ function slow(h: Hub, c: Sock, what: string) {
249
+ c.options.onDiagnostic?.({
250
+ code: 'R008',
251
+ severity: 'error',
252
+ message: `R008: a client sent over ${what}`,
253
+ })
254
+ return gone(h, c, 1008, 'rate limit')
255
+ }
256
+
257
+ function frame(h: Hub, c: Sock, text: string) {
258
+ if (!stateOf(h).socks.has(c)) return // closing: what was already on the wire
259
+ c.last = Date.now()
260
+ if (text.length > h.limits.body) {
261
+ c.options.onDiagnostic?.({
262
+ code: 'R008',
263
+ severity: 'error',
264
+ message: `R008: a channel frame of ${text.length} bytes; the limit is ${h.limits.body}`,
265
+ })
266
+ return gone(h, c, 1009, 'too big')
267
+ }
268
+ let f: unknown
269
+ try {
270
+ f = JSON.parse(text)
271
+ } catch {
272
+ return gone(h, c, 1007, 'not JSON')
273
+ }
274
+ if (!Array.isArray(f)) return gone(h, c, 1007, 'not a frame')
275
+ if (f[0] === 'p') return send(c, ['p'])
276
+ if (!take(c.bucket, h.limits.perSecond, h.limits.burst)) {
277
+ return slow(h, c, `${h.limits.perSecond} messages a second`)
278
+ }
279
+ if (f[0] === 'j' && typeof f[2] === 'string')
280
+ return void join(h, c, {
281
+ n: f[1],
282
+ id: f[2],
283
+ params: f[3],
284
+ cursor: typeof f[4] === 'string' ? f[4] : undefined,
285
+ })
286
+ const j = c.joins.get(f[1])
287
+ if (f[0] === 'l') return j && leave(h, c, j)
288
+ if (f[0] !== 'm' || typeof f[2] !== 'number' || typeof f[3] !== 'string') return
289
+ if (!j) return send(c, ['a', f[1], f[2], { code: 'Q009', message: 'not joined' }])
290
+ const per = j.fn.def.limits?.perSecond
291
+ if (per && !take(j.bucket, per, per * 2)) {
292
+ return slow(h, c, `${per} messages a second to \`${j.fn.$id}\``)
293
+ }
294
+ j.chain = j.chain.then(() => run(h, c, j, { ack: f[2], name: f[3], msg: f[4] }))
295
+ }
296
+
297
+ function gone(h: Hub, c: Sock, code: number, reason?: string) {
298
+ const st = stateOf(h)
299
+ if (!st.socks.delete(c)) return
300
+ for (const t of c.timers) clearTimeout(t)
301
+ for (const j of Array.from(c.joins.values())) leave(h, c, j)
302
+ c.peer.close(code, reason)
303
+ }
304
+
305
+ /** The session again: `ctx`, then `authorize` for every join. A user who's gone closes the socket; 4401 tells the client. */
306
+ async function recheck(h: Hub, c: Sock) {
307
+ const ctx = await createScope(c.request, c.options)
308
+ .ctx()
309
+ .catch(() => ({}) as Context)
310
+ if (!stateOf(h).socks.has(c)) return
311
+ if (c.user !== undefined && (ctx as { user?: { id?: string } }).user?.id !== c.user)
312
+ return gone(h, c, 4401, 'session')
313
+ c.ctx = ctx
314
+ for (const j of Array.from(c.joins.values())) {
315
+ if (await allowed(j.fn, ctx, j.params).catch(() => false)) {
316
+ await j.fn.def.recheck?.({ id: c.k, ctx, reply: reply(h, c, j) })
317
+ continue
318
+ }
319
+ leave(h, c, j)
320
+ refuse(c, j.n, denied(j.fn))
321
+ }
322
+ }
323
+
324
+ /** Open: the hello, the heartbeat watch and the session timer. */
325
+ /** `line`: one tab on a shared socket (mux.ts), which `limits.connections` counted already. */
326
+ export async function attach(
327
+ peer: Peer,
328
+ request: Request,
329
+ scope: Scope,
330
+ h = hub(),
331
+ line = false,
332
+ ): Promise<Attached> {
333
+ const st = stateOf(h)
334
+ const ctx = await scope.ctx()
335
+ const user = (ctx as { user?: { id?: string } }).user?.id
336
+ const c: Sock = {
337
+ k: crypto.randomUUID(),
338
+ peer,
339
+ request,
340
+ options: scope.options,
341
+ ctx,
342
+ user,
343
+ joins: new Map(),
344
+ bucket: { tokens: h.limits.burst, at: Date.now() },
345
+ last: Date.now(),
346
+ timers: [],
347
+ }
348
+ if (
349
+ !line &&
350
+ user !== undefined &&
351
+ [...st.socks].filter((s) => s.user === user).length >= h.limits.connections
352
+ ) {
353
+ peer.close(1008, 'too many sockets')
354
+ scope.options.onDiagnostic?.({
355
+ code: 'R009',
356
+ severity: 'error',
357
+ message: `R009: user \`${user}\` already has ${h.limits.connections} sockets`,
358
+ })
359
+ return { message() {}, close() {}, recheck: async () => {} }
360
+ }
361
+ st.socks.add(c)
362
+ send(c, ['h', { k: c.k, e: h.epoch, b: h.build ?? '' }])
363
+ let ticks = 0
364
+ const every = Math.max(1, Math.round(h.limits.session / h.limits.heartbeat))
365
+ c.timers.push(
366
+ unref(
367
+ setInterval(() => {
368
+ if (Date.now() - c.last > h.limits.heartbeat * 3) return gone(h, c, 1001, 'idle')
369
+ if (++ticks % every === 0) void recheck(h, c)
370
+ }, h.limits.heartbeat),
371
+ ),
372
+ )
373
+ if (h.maxDuration)
374
+ c.timers.push(
375
+ unref(
376
+ setTimeout(() => gone(h, c, 1012, 'max duration'), Math.max(1, h.maxDuration - 10) * 1000),
377
+ ),
378
+ )
379
+ return {
380
+ message: (text) => frame(h, c, text),
381
+ close: () => gone(h, c, 1000),
382
+ recheck: () => recheck(h, c),
383
+ }
384
+ }
385
+
386
+ export { publish } from './socket/publish'
387
+
388
+ /** A shared value written by the server: `deckSlide.in(key).set(3)`. */
389
+ export const setShared = sharedWriter(stateOf)
390
+
391
+ runtime.channels = { publish, set: setShared }
392
+
393
+ /** Nitro reads `crossws` off the response (research 32 §1). A refusal is a hook that throws, so no socket opens. */
394
+ export function socketRoute(
395
+ request: Request,
396
+ scope: Scope,
397
+ origins: string[] = [],
398
+ ): Promise<Response> {
399
+ return socketRouteWith(request, scope, origins, attach)
400
+ }
package/src/stream.ts ADDED
@@ -0,0 +1,22 @@
1
+ // `stream`, connected to `data.ts`. `q.live()` does the same `use` on its first call (see `live.ts`). A call, not a
2
+ // top-level statement: `sideEffects: false` lets a bundler skip this file's own statements for a re-export.
3
+
4
+ import { liveApi } from './data'
5
+ import { stream as define, use } from './live'
6
+
7
+ /** `stream()`, with the realtime half connected on first use. */
8
+ export const stream = ((def: never) => {
9
+ use(liveApi)
10
+ return define(def)
11
+ }) as typeof define
12
+
13
+ export {
14
+ backoff,
15
+ hold,
16
+ type Link,
17
+ type Stream,
18
+ type StreamDef,
19
+ type StreamFn,
20
+ type StreamOptions,
21
+ type StreamStatus,
22
+ } from './live'