@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,57 @@
1
+ // @kerf-js/core/test's realtime transport (research 30 §7): the real hub, a memory bus, frames through JSON.
2
+
3
+ import { fakeScope, FnError, net, runtime, type Fn } from './data'
4
+ import type { Body } from './hub'
5
+
6
+ const loadExec = async () => (runtime.exec ??= await import('./exec'))
7
+
8
+ /** A change to a connection's subscriptions, as the route would take it. */
9
+ export async function change(body: Body) {
10
+ const [{ hub }, exec] = await Promise.all([import('./hub'), loadExec()])
11
+ const c = hub().find(body.k!)
12
+ if (!c) throw new FnError({}, 404)
13
+ const request = new Request('http://localhost/_kerf/rt', { method: 'POST' })
14
+ await hub().change(c, request, fakeScope(exec, net()!, request).options, body)
15
+ }
16
+
17
+ /** A connection to the real hub in this process. */
18
+ export async function open(
19
+ body: Body,
20
+ frame: (event: string, data: unknown) => void,
21
+ signal: AbortSignal,
22
+ hooks: {
23
+ up: () => void
24
+ subs: Map<string, { fn: Fn; input: unknown }>
25
+ closing: (close: () => unknown) => void
26
+ },
27
+ ) {
28
+ const { up, subs, closing } = hooks
29
+ const n = net()!
30
+ const [{ hub, resetHub }, exec] = await Promise.all([import('./hub'), loadExec()])
31
+ if (!n.online()) throw Object.assign(new Error('offline'), { name: 'OfflineError' })
32
+ closing(resetHub)
33
+ const h = hub()
34
+ runtime.poke ??= (tags, origin) => hub().poke(tags, origin)
35
+ const request = new Request('http://localhost/_kerf/rt', { method: 'POST' })
36
+ return new Promise<void>((done, fail) => {
37
+ let conn: Parameters<typeof h.close>[0] | undefined
38
+ const sink = {
39
+ write: (e: string, d: string) => frame(e, JSON.parse(d)),
40
+ backlog: () => 0,
41
+ close: () => done(),
42
+ }
43
+ n.rt = {
44
+ push: (id, msg) => h.push(id, msg),
45
+ poke: (tags) => h.poke(tags),
46
+ drop: () => conn && h.close(conn),
47
+ subscriptions: () =>
48
+ [...subs.values()].map((s) => ({ kind: s.fn.kind, id: s.fn.$id, input: s.input })),
49
+ }
50
+ signal.addEventListener('abort', () => (conn ? h.close(conn) : done()))
51
+ h.connect(request, fakeScope(exec, n, request), body, sink).then((c) => {
52
+ conn = c
53
+ if (signal.aborted) h.close(c)
54
+ up()
55
+ }, fail)
56
+ })
57
+ }
@@ -0,0 +1,231 @@
1
+ // What a deploy target can do for live data, from its preset and config alone: `kerf check`, `kerf build` and `kerf
2
+ // doctor` read this. What only a running server can know (a pooler, a missing trigger) the server probes at startup.
3
+
4
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+
7
+ const LISTENER =
8
+ "run `kerf db listen` on any always-on host (a VPS, Fly, Railway), publishing into a shared bus, and set `dbChanges(db, tables, { listener: 'external' })`"
9
+ const SERVER =
10
+ 'deploy to a server preset (`node_server`, `bun`, `deno_server`, or a container on Fly, Railway or Render)'
11
+ const POLLED = 'or poll the query yourself by reloading: `.live()` still updates on mutations'
12
+
13
+ /** Presets that give each request its own short-lived process. */
14
+ const FUNCTIONS = [
15
+ [/^vercel/, 'Vercel Functions'],
16
+ [/^netlify/, 'Netlify Functions'],
17
+ [/^aws[-_]lambda/, 'AWS Lambda'],
18
+ [/^azure/, 'Azure Functions'],
19
+ [/^firebase/, 'Firebase Functions'],
20
+ [/^cloudflare/, 'Cloudflare Workers'],
21
+ [/^deno[-_]deploy/, 'Deno Deploy'],
22
+ ]
23
+
24
+ /**
25
+ * @param {string} [preset]
26
+ * @returns {{ preset: string, held: boolean, host: string }} `held`: one process outlives a request, so it can hold a connection and a timer
27
+ */
28
+ export function liveTarget(preset = 'node') {
29
+ const hit = FUNCTIONS.find(([re]) => re.test(preset))
30
+ return hit
31
+ ? { preset, held: false, host: hit[1] }
32
+ : { preset, held: true, host: 'a long-running server' }
33
+ }
34
+
35
+ /** Whether a deploy can hold a browser's socket: a long-running server, a Durable Object, or Deno's upgraded request. */
36
+ export const holdsSockets = (preset = 'node') =>
37
+ liveTarget(preset).held || /^(cloudflare[-_]durable|deno[-_]deploy)/.test(preset)
38
+
39
+ /**
40
+ * Whether the page dials a socket (`__KERF_SOCKETS__`): only when the server answers one, an app with a channel or
41
+ * shared state (`sockets`) on a host that can hold it. A socket nobody serves never fails, so a page that dialed one
42
+ * would wait on it for good; without one, streams and live queries go straight to SSE.
43
+ * @param {{ sockets: boolean, build: boolean, preset?: string }} app
44
+ */
45
+ export const pageSockets = ({ sockets, build, preset }) =>
46
+ sockets && (!build || holdsSockets(preset))
47
+
48
+ const SKIP = new Set(['node_modules', '.kerf', '.output', 'dist'])
49
+
50
+ /** `live: { required: true }` on a query, and `.live(input, { required: true })` in a component, with where. */
51
+ export function scanRequired(root) {
52
+ const out = []
53
+ const walk = (dir) => {
54
+ for (const d of readdirSync(dir, { withFileTypes: true })) {
55
+ const f = join(dir, d.name)
56
+ if (d.isDirectory()) {
57
+ if (!SKIP.has(d.name)) walk(f)
58
+ } else if (/\.[cm]?[jt]sx?$/.test(d.name) && !/\.test\./.test(d.name)) read(f)
59
+ }
60
+ }
61
+ const read = (file) => {
62
+ const text = readFileSync(file, 'utf8')
63
+ if (!/required:\s*true/.test(text)) return
64
+ for (const m of text.matchAll(/\blive:\s*\{[^}]*required:\s*true/g)) {
65
+ const name = [...text.slice(0, m.index).matchAll(/\b(\w+)\s*=\s*query\s*[(<]/g)].at(-1)?.[1]
66
+ if (name) out.push({ name, file: file.slice(root.length + 1) })
67
+ }
68
+ for (const m of text.matchAll(/\b(\w+)\.live\(([^;\n]*?)\brequired:\s*true/g))
69
+ out.push({ name: m[1], file: file.slice(root.length + 1) })
70
+ }
71
+ const src = join(root, 'src')
72
+ if (existsSync(src)) walk(src)
73
+ return [...new Map(out.map((r) => [r.name, r])).values()]
74
+ }
75
+
76
+ /**
77
+ * What this deploy gets, for `kerf doctor`, and the diagnostics `kerf check` and `kerf build` report.
78
+ * @param {{ preset?: string, source?: { name: string, external?: boolean, tables: string[] }, required?: { name: string, file: string }[] }} input
79
+ */
80
+ export function livePlan({ preset, source, required = [] }) {
81
+ const target = liveTarget(preset)
82
+ const names = required.map((r) => `\`${r.name}\``).join(', ')
83
+ const diagnostics = []
84
+ const options = target.held ? [] : [LISTENER, SERVER]
85
+ let mode, says
86
+ if (!source) {
87
+ mode = 'app'
88
+ says =
89
+ 'Mutations update `.live()` queries. Writes from outside the app do not: nothing listens to the database.'
90
+ if (required.length)
91
+ diagnostics.push({
92
+ code: 'R013',
93
+ severity: 'error',
94
+ why: `${names} require${required.length > 1 ? '' : 's'} a live feed, and \`src/realtime.server.ts\` sets no \`changes\`. Add \`changes: dbChanges(db, [tables])\`, or drop \`required\`.`,
95
+ })
96
+ } else if (source.external) {
97
+ mode = 'external'
98
+ says = `A separate listener reports writes to ${source.tables.join(', ')} through the bus. It is yours to keep running; \`.live()\` shows \`reconnecting\` when it goes quiet.`
99
+ } else if (target.held) {
100
+ mode = 'feed'
101
+ says = `This server listens to ${source.name} for writes to ${source.tables.join(', ')}. At startup it probes what the database allows, and logs what it settled on.`
102
+ } else {
103
+ mode = 'off'
104
+ says = `${target.host} ends a process with its request, so nothing can hold a connection to ${source.name}: mutations update \`.live()\`, and writes from outside the app do not. \`.live()\` shows \`degraded\`.`
105
+ if (required.length)
106
+ diagnostics.push({
107
+ code: 'R013',
108
+ severity: 'error',
109
+ why: `${names} require${required.length > 1 ? '' : 's'} a live feed, and \`${target.preset}\` can't hold one: ${target.host} ends a process with its request. Either ${LISTENER}, or ${SERVER}, or drop \`required\`.`,
110
+ })
111
+ else
112
+ diagnostics.push({
113
+ code: 'R014',
114
+ severity: 'warning',
115
+ why: `\`changes\` needs a process that stays up, and on \`${target.preset}\` none does: writes from outside the app won't reach \`.live()\`. Either ${LISTENER}, or ${SERVER}, ${POLLED}.`,
116
+ })
117
+ }
118
+ return {
119
+ preset: target.preset,
120
+ held: target.held,
121
+ host: target.host,
122
+ mode,
123
+ says,
124
+ required: required.map((r) => r.name),
125
+ options,
126
+ diagnostics,
127
+ }
128
+ }
129
+
130
+ // ---- `verify` ---------------------------------------------------------------------------------------------------------
131
+
132
+ const PRODUCTION = /(^|[.\-_])(prod|production|live|www|main|master)([.\-_]|$)/i
133
+ const NOT_PRODUCTION =
134
+ /(^|[.\-_])(staging|stage|stg|dev|develop|development|test|testing|qa|sandbox|preview|uat|demo)([.\-_]|$)|^localhost$|^127\.|^\[?::1\]?$/i
135
+
136
+ const hostOf = (url) => {
137
+ try {
138
+ return new URL(url).hostname
139
+ } catch {
140
+ return url
141
+ }
142
+ }
143
+ const dbNameOf = (url) => {
144
+ try {
145
+ return new URL(url).pathname.slice(1)
146
+ } catch {
147
+ return ''
148
+ }
149
+ }
150
+
151
+ const HOWTO =
152
+ 'Set `KERF_STAGING_URL` to a running staging app, `STAGING_DATABASE_URL` to its database, or both for the whole chain.'
153
+
154
+ /**
155
+ * Where a `verify` points, from the query's declaration, `live.targets` in kerf.config.ts and the environment.
156
+ * @returns {{ name: string, url?: string, db?: string, marked: boolean } | { missing: string }}
157
+ */
158
+ export function resolveTarget(verify, { targets = {}, env = process.env } = {}) {
159
+ if (typeof verify === 'object' && verify.target !== undefined)
160
+ return resolveTarget(verify.target, { targets, env })
161
+ if (verify === true) {
162
+ const url = env.KERF_STAGING_URL,
163
+ db = env.STAGING_DATABASE_URL
164
+ return url || db
165
+ ? { name: 'staging', url, db, marked: false }
166
+ : {
167
+ missing: `\`verify: true\` found neither \`KERF_STAGING_URL\` nor \`STAGING_DATABASE_URL\`. ${HOWTO}`,
168
+ }
169
+ }
170
+ if (typeof verify === 'string') {
171
+ const t = targets[verify]
172
+ if (!t)
173
+ return {
174
+ missing: `\`verify: '${verify}'\` names no target. Add it to kerf.config.ts: \`live: { targets: { ${verify}: { url: 'https://…', db: 'STAGING_DATABASE_URL', production: false } } }\``,
175
+ }
176
+ const db = t.db && (t.db.includes('://') ? t.db : env[t.db])
177
+ if (t.db && !db)
178
+ return {
179
+ missing: `target \`${verify}\` reads its database from \`${t.db}\`, which isn't set on this machine.`,
180
+ }
181
+ return { name: verify, url: t.url, db, marked: t.production === false }
182
+ }
183
+ if (!verify.url && !verify.db)
184
+ return { missing: `\`verify\` got an empty target (is its env var set?). ${HOWTO}` }
185
+ return { name: 'inline', url: verify.url, db: verify.db, marked: false }
186
+ }
187
+
188
+ /** Why this target must not be touched: R022. Anything that says production is refused, whatever config says. */
189
+ export function refusal(target, { targets = {} } = {}) {
190
+ const hosts = [target.url && hostOf(target.url), target.db && hostOf(target.db)].filter(Boolean)
191
+ const names = [target.name, ...hosts, ...(target.db ? [dbNameOf(target.db)] : [])]
192
+ const said = names.find((n) => PRODUCTION.test(n))
193
+ if (said) return `\`${said}\` looks like production: \`verify\` writes rows, and won't go near it`
194
+ if (
195
+ target.name !== 'inline' &&
196
+ target.name !== 'staging' &&
197
+ targets[target.name]?.production !== false
198
+ )
199
+ return `target \`${target.name}\` isn't marked: add \`production: false\` to it in kerf.config.ts`
200
+ if (target.marked) return
201
+ const unsure = hosts.find((h) => !NOT_PRODUCTION.test(h))
202
+ if (unsure)
203
+ return `nothing says \`${unsure}\` isn't production. Name it in kerf.config.ts: \`live: { targets: { staging: { db: 'STAGING_DATABASE_URL', production: false } } }\`, and use \`verify: 'staging'\``
204
+ }
205
+
206
+ const PASSWORD = /[a-z][a-z0-9+.-]*:\/\/[^\s'"`/:@]+:[^\s'"`/@]+@/i
207
+
208
+ /** R020: a connection string with a password, written into source. An env var's value never reaches this. */
209
+ export function literalSecrets(root) {
210
+ const out = []
211
+ const look = (file) => {
212
+ const text = readFileSync(file, 'utf8')
213
+ if (!/\b(verify|targets)\b/.test(text)) return
214
+ text.split('\n').forEach((line, i) => {
215
+ if (PASSWORD.test(line) && /\b(db|url|verify)\b/.test(line))
216
+ out.push({ file: file.slice(root.length + 1), line: i + 1 })
217
+ })
218
+ }
219
+ const walk = (dir) => {
220
+ for (const d of readdirSync(dir, { withFileTypes: true })) {
221
+ const f = join(dir, d.name)
222
+ if (d.isDirectory()) {
223
+ if (!SKIP.has(d.name)) walk(f)
224
+ } else if (/\.[cm]?[jt]sx?$/.test(d.name)) look(f)
225
+ }
226
+ }
227
+ if (existsSync(join(root, 'src'))) walk(join(root, 'src'))
228
+ for (const f of ['kerf.config.ts', 'kerf.config.js', 'kerf.config.mjs'])
229
+ if (existsSync(join(root, f))) look(join(root, f))
230
+ return out
231
+ }
package/src/live.ts ADDED
@@ -0,0 +1,390 @@
1
+ // The realtime client (research 30 §6): one connection per tab, a line on the browser's one socket (link.ts), one subscription per function + input, shared by every
2
+ // reader and owned by this module, not by a component (PLAN §4.2), so an unmounting tab loses neither its subscription
3
+ // nor its folded state for `keep`. `q.live()` imports this on its first call; `stream` through `stream.ts`, so an app
4
+ // that uses neither ships none of it.
5
+ //
6
+ // A poke is a local `cache.invalidate`: readers refetch through `query`, and the keyed list writes what changed.
7
+
8
+ import { DEV, batch, createRoot, state, untrack } from '@kerf-js/core'
9
+ import type { AuthScope, Fn, LiveMode, LiveOptions, LiveStatus, StandardSchemaV1 } from './data'
10
+ import type { SubEntry } from './hub'
11
+ import { noSockets } from './link'
12
+ import { transports } from './live/transport'
13
+ import { backoff, CAP } from './live/backoff'
14
+
15
+ import { cache, fns, FnError, keyOf, net, rt, runtime, track } from './live/api'
16
+
17
+ import type { In, StreamDef, StreamFn, StreamOptions } from './live/types'
18
+ import type { Sub } from './live/sub-types'
19
+ import { read } from './live/read'
20
+ import type { Link } from './live/transport'
21
+ import { ack, update, type Row } from './live/frames'
22
+ export { backoff } from './live/backoff'
23
+ export { use } from './live/api'
24
+ export type { StreamStatus, StreamDef, StreamOptions, Stream, StreamFn } from './live/types'
25
+ export type { Link } from './live/transport'
26
+
27
+ // ---- definitions ----------------------------------------------------------------------------------------------------
28
+
29
+ const FN = Symbol.for('kerf.fn')
30
+ let auto = 0
31
+
32
+ export function stream<
33
+ M,
34
+ S extends StandardSchemaV1 | undefined = undefined,
35
+ const A extends AuthScope | undefined = undefined,
36
+ >(def: StreamDef<S, M, A>): StreamFn<In<S>, M> {
37
+ const id = def.$id ?? `s${++auto}`
38
+ const fn: Fn = { kind: 'stream', $id: id, def: def as unknown as Fn['def'] }
39
+ fns.set(id, fn)
40
+ return Object.assign(
41
+ (input: unknown, options?: StreamOptions<never, unknown>) =>
42
+ read(fn, input, options, acquire, held),
43
+ { kind: 'stream', $id: id, [FN]: fn },
44
+ ) as unknown as StreamFn<In<S>, M>
45
+ }
46
+
47
+ // ---- subscriptions --------------------------------------------------------------------------------------------------
48
+
49
+ const subs = new Map<string, Sub>()
50
+ const byN = new Map<number, Sub>()
51
+ let nth = 0
52
+
53
+ const KEEP = 30_000
54
+ const ms = (keep: string | number = KEEP): number => {
55
+ if (typeof keep === 'number') return keep
56
+ const m = /^(\d+)(ms|s|m)$/.exec(keep)
57
+ return m ? +m[1]! * { ms: 1, s: 1000, m: 60_000 }[m[2] as 'ms' | 's' | 'm'] : Infinity // 'session'
58
+ }
59
+
60
+ function acquire(fn: Fn, input: unknown): Sub {
61
+ const key = keyOf(fn.$id, input)
62
+ let s = subs.get(key)
63
+ if (!s) {
64
+ s = createRoot(
65
+ () => ({
66
+ n: ++nth,
67
+ key,
68
+ fn,
69
+ input,
70
+ refs: 0,
71
+ tags: [],
72
+ acked: false,
73
+ views: new Map(),
74
+ error: state<unknown>(undefined),
75
+ done: state(false),
76
+ }),
77
+ null,
78
+ )
79
+ // Not at the top level: a side effect there would keep this chunk in apps that never read `.live`.
80
+ if (DEV && net() && !net()!.resets.includes(reset)) net()!.resets.push(reset)
81
+ subs.set(key, s)
82
+ byN.set(s.n, s)
83
+ sync()
84
+ }
85
+ clearTimeout(s.timer)
86
+ s.timer = undefined
87
+ s.refs++
88
+ return s
89
+ }
90
+
91
+ function release(s: Sub, keep?: string | number) {
92
+ if (--s.refs) return
93
+ const t = ms(keep)
94
+ if (t === Infinity) return
95
+ if (t) s.timer = setTimeout(() => drop(s), t)
96
+ else drop(s)
97
+ }
98
+
99
+ function drop(s: Sub) {
100
+ subs.delete(s.key)
101
+ byN.delete(s.n)
102
+ sync()
103
+ }
104
+
105
+ /** A reader in the owner of `hold`'s caller. T012 sees it until it lets go. */
106
+ function held(s: Sub, keep?: string | number): () => void {
107
+ const token = {}
108
+ const stop = () => {
109
+ net()?.open.delete(token)
110
+ release(s, keep)
111
+ }
112
+ if (DEV) net()?.open.set(token, [`live subscription \`${s.key}\``, stop])
113
+ return stop
114
+ }
115
+
116
+ /** `q.live()`'s subscription, from data.ts. */
117
+ export function hold(fn: Fn, input: unknown, options?: LiveOptions): () => void {
118
+ return held(acquire(fn, input), options?.keep)
119
+ }
120
+
121
+ // ---- the connection ---------------------------------------------------------------------------------------------------
122
+
123
+ const { http, socket } = transports(() => (retry = 0))
124
+
125
+ /**
126
+ * @kerf-js/core/test only (`live-fake.ts`). The specifier hides it from the bundler: an `import()` it can see would keep the
127
+ * fake, and through it the hub, as chunks of every app, used or not.
128
+ */
129
+ const FAKE = './live-fake.ts'
130
+ const fake: Link = {
131
+ open(body, heard, signal) {
132
+ let up!: () => void
133
+ void track(
134
+ new Promise<void>((ok) => {
135
+ up = ok
136
+ }),
137
+ ) // `net.settle()` waits for the connection, not for its end
138
+ return import(/* @vite-ignore */ FAKE)
139
+ .then((m) =>
140
+ m.open(body, heard, signal, {
141
+ up,
142
+ subs,
143
+ closing: (close: () => unknown) => (closeHub = close),
144
+ }),
145
+ )
146
+ .finally(up)
147
+ },
148
+ change: async (body) => (await import(/* @vite-ignore */ FAKE)).change(body),
149
+ }
150
+
151
+ /** Two sockets that never answered, and this host has none. */
152
+ const link = (): Link => (DEV && net() ? fake : noSockets() ? http : socket)
153
+ let via: Link = socket
154
+ let closeHub: (() => unknown) | undefined
155
+
156
+ const DEAD = 45_000,
157
+ HIDDEN = 300_000
158
+
159
+ interface Live {
160
+ ac: AbortController
161
+ k?: string
162
+ sent: Set<number>
163
+ }
164
+ let conn: Live | undefined
165
+ let running = false
166
+ let attempt = 0
167
+ /** The poke cursor. Seeded by the page, it covers what was published between the render and this connection. */
168
+ let cursor: string | undefined
169
+ let build: string | undefined
170
+ let seeded = false
171
+ let retry: number | undefined
172
+ let nudge: (() => void) | undefined
173
+ let hiddenAt: ReturnType<typeof setTimeout> | undefined
174
+ let parked = false
175
+ let changing: Promise<void> | undefined
176
+ let pokes = new Set<string>()
177
+ let pokeTimer: ReturnType<typeof setTimeout> | undefined
178
+
179
+ /** The page's `#kerf-rt`, on the tab's first connect. */
180
+ function readPage() {
181
+ const el = document.getElementById('kerf-rt')
182
+ if (!el) return
183
+ const page = JSON.parse(el.textContent) as { c?: string; b?: string }
184
+ el.remove()
185
+ cursor = page.c
186
+ build = page.b
187
+ seeded = !!cursor
188
+ }
189
+
190
+ const entry = (s: Sub): SubEntry =>
191
+ s.fn.kind === 'query'
192
+ ? [s.n, 'q', s.fn.$id, s.input]
193
+ : [s.n, 's', s.fn.$id, s.input, s.cursor ?? '', s.buffer ?? 0]
194
+ const set = (status: LiveStatus) => {
195
+ rt.status.value = status
196
+ }
197
+ interface Linked {
198
+ m: LiveMode
199
+ d?: 1
200
+ }
201
+ /** The connection is up: how live that is depends on the server's feed. */
202
+ function linked(l?: Linked) {
203
+ rt.mode.value = l?.m ?? 'app'
204
+ set(l?.d ? 'reconnecting' : l?.m === 'poll' || l?.m === 'off' ? 'degraded' : 'live')
205
+ if (DEV && l && l.m !== 'feed' && l.m !== 'external' && !warned) {
206
+ warned = true
207
+ console.warn(
208
+ `kerf: R016 live queries are \`degraded\` (mode \`${l.m}\`): writes from outside the app arrive late or not at all. The server log says why.`,
209
+ )
210
+ }
211
+ }
212
+ let warned = false
213
+ const offline = () => !navigator.onLine
214
+
215
+ function flushPokes() {
216
+ const tags = [...pokes]
217
+ pokes = new Set()
218
+ pokeTimer = undefined
219
+ void cache.invalidate(...tags)
220
+ }
221
+
222
+ function frame(event: string, data: unknown) {
223
+ const d = data as Row &
224
+ Record<'b' | 'k' | 'c', string> & { l?: Linked; t: string[]; retry: number }
225
+ batch(() => {
226
+ if (event === 'h') {
227
+ if (build && d.b && d.b !== build) rt.stale.value = true
228
+ build = d.b
229
+ if (conn) conn.k = runtime.conn = d.k
230
+ cursor ??= d.c
231
+ attempt = 0
232
+ linked(d.l)
233
+ sync() // what changed while connecting
234
+ } else if (event === 'a') {
235
+ ack(d, byN, () => seeded)
236
+ } else if (event === 'p') {
237
+ cursor = d.c
238
+ for (const t of d.t) pokes.add(t)
239
+ if (net()) flushPokes()
240
+ else pokeTimer ??= setTimeout(flushPokes, 50 + Math.random() * 250)
241
+ } else if (event === 'R') {
242
+ cursor = d.c
243
+ void cache.invalidate(...[...subs.values()].flatMap((s) => s.tags))
244
+ } else if (event === 'm' || event === 'r' || event === 'f' || event === 'e') {
245
+ update(event, d, byN)
246
+ } else if (event === 'L') linked(d as unknown as Linked)
247
+ else if (event === 'b') retry = d.retry
248
+ })
249
+ }
250
+
251
+ /** Woken early by `online`, by the tab showing again and by a change to the set. */
252
+ const sleep = (t: number) =>
253
+ new Promise<void>((ok) => {
254
+ const timer = setTimeout(ok, t)
255
+ nudge = () => {
256
+ clearTimeout(timer)
257
+ nudge = undefined
258
+ ok()
259
+ }
260
+ })
261
+
262
+ async function run() {
263
+ running = true
264
+ listen(true)
265
+ readPage()
266
+ while (subs.size) {
267
+ if (parked || offline()) {
268
+ set(parked ? 'reconnecting' : 'offline')
269
+ await sleep(CAP)
270
+ continue
271
+ }
272
+ const ac = new AbortController()
273
+ conn = { ac, sent: new Set(byN.keys()) }
274
+ let dead: ReturnType<typeof setTimeout> | undefined
275
+ const alive = () => {
276
+ clearTimeout(dead)
277
+ if (!net()) dead = setTimeout(() => ac.abort(), DEAD)
278
+ }
279
+ alive()
280
+ retry = undefined
281
+ try {
282
+ await (via = link()).open(
283
+ { c: cursor, s: [...subs.values()].filter((s) => !s.done.value).map(entry) },
284
+ frame,
285
+ ac.signal,
286
+ alive,
287
+ )
288
+ } catch (e) {
289
+ if (!ac.signal.aborted && e instanceof FnError)
290
+ for (const s of subs.values())
291
+ untrack(() => {
292
+ s.error.value = e
293
+ })
294
+ }
295
+ clearTimeout(dead)
296
+ conn = undefined
297
+ runtime.conn = undefined
298
+ seeded = false
299
+ if (!subs.size) break
300
+ const n = net()
301
+ if (n) n.reconnects++
302
+ set(offline() ? 'offline' : 'reconnecting')
303
+ if (!n) await sleep(retry ?? backoff(attempt++))
304
+ }
305
+ running = false
306
+ attempt = 0
307
+ listen(false)
308
+ set('connecting')
309
+ }
310
+
311
+ /** Bring the server's set up to date with `subs`, in place. A 404 (another instance, a restart) reconnects. */
312
+ function sync() {
313
+ if (changing) return
314
+ changing = Promise.resolve().then(async () => {
315
+ changing = undefined
316
+ if (!subs.size) return conn?.ac.abort()
317
+ if (!running) return void run()
318
+ const live = conn
319
+ // Between connections the loop sleeps: a changed set wakes it, as the sleep promises.
320
+ if (!live) return nudge?.()
321
+ if (!live.k) return
322
+ const add = [...byN.values()].filter((s) => !live.sent.has(s.n))
323
+ const gone = [...live.sent].filter((n) => !byN.has(n))
324
+ if (!add.length && !gone.length) return
325
+ for (const s of add) live.sent.add(s.n)
326
+ for (const n of gone) live.sent.delete(n)
327
+ try {
328
+ await via.change({ k: live.k, s: add.map(entry), d: gone })
329
+ } catch {
330
+ live.ac.abort()
331
+ }
332
+ })
333
+ void track(changing)
334
+ }
335
+
336
+ // ---- the page -------------------------------------------------------------------------------------------------------
337
+
338
+ const wake = () => {
339
+ parked = false
340
+ nudge?.()
341
+ }
342
+
343
+ function park() {
344
+ parked = true
345
+ conn?.ac.abort()
346
+ }
347
+
348
+ function onOffline() {
349
+ set('offline')
350
+ conn?.ac.abort()
351
+ }
352
+
353
+ function onVisibility() {
354
+ clearTimeout(hiddenAt)
355
+ if (document.visibilityState === 'hidden') hiddenAt = setTimeout(park, HIDDEN)
356
+ else wake()
357
+ }
358
+
359
+ function listen(on: boolean) {
360
+ if (typeof window === 'undefined') return
361
+ const m = on ? 'addEventListener' : 'removeEventListener'
362
+ window[m]('online', wake)
363
+ window[m]('offline', onOffline)
364
+ window[m]('pagehide', park)
365
+ window[m]('pageshow', wake)
366
+ document[m]('visibilitychange', onVisibility)
367
+ if (!on) clearTimeout(hiddenAt)
368
+ }
369
+
370
+ /** @kerf-js/core/test, after each test. */
371
+ function reset() {
372
+ for (const s of subs.values()) clearTimeout(s.timer)
373
+ subs.clear()
374
+ byN.clear()
375
+ conn?.ac.abort()
376
+ nudge?.()
377
+ clearTimeout(pokeTimer)
378
+ pokes = new Set()
379
+ cursor = build = retry = undefined
380
+ seeded = parked = false
381
+ attempt = 0
382
+ const n = net()!
383
+ n.reconnects = 0
384
+ n.rt = undefined
385
+ void closeHub?.()
386
+ untrack(() => {
387
+ rt.stale.value = false
388
+ rt.status.value = 'connecting'
389
+ })
390
+ }