@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
package/src/email.ts ADDED
@@ -0,0 +1,146 @@
1
+ // `@kerf-js/start/email`: `sendEmail()` from any server code, through the mailer `src/email.server.ts` exports, or
2
+ // the one the environment names: `RESEND_API_KEY` sends through Resend, `SMTP_URL` over SMTP (nodemailer), and dev with
3
+ // neither prints each message to the server log. Auth's verification and reset emails go the same way.
4
+ import { StartError } from './data'
5
+
6
+ /** One email. `from` defaults to the mailer's, then `EMAIL_FROM`. Give `text`, `html` or both. */
7
+ export interface EmailMessage {
8
+ to: string | string[]
9
+ subject: string
10
+ text?: string
11
+ html?: string
12
+ from?: string
13
+ replyTo?: string
14
+ }
15
+
16
+ /** Something that sends email: what `src/email.server.ts` default-exports. */
17
+ export interface Mailer {
18
+ name: string
19
+ send(message: EmailMessage): Promise<void>
20
+ }
21
+
22
+ const fromOf = (m: EmailMessage, fallback?: string) => {
23
+ const from = m.from ?? fallback ?? process.env.EMAIL_FROM
24
+ if (!from)
25
+ throw new StartError(
26
+ 'E002',
27
+ `the email "${m.subject}" has no sender`,
28
+ 'set `EMAIL_FROM` (`Acme <hello@acme.dev>`), or pass `from` to the mailer or the message',
29
+ )
30
+ return from
31
+ }
32
+
33
+ /** Resend's HTTP API, with no package: `RESEND_API_KEY` unless you pass `apiKey`. */
34
+ export function resendMailer(options: { apiKey?: string; from?: string } = {}): Mailer {
35
+ return {
36
+ name: 'resend',
37
+ async send(m) {
38
+ const key = options.apiKey ?? process.env.RESEND_API_KEY
39
+ if (!key) throw new StartError('E003', 'Resend needs an API key', 'set `RESEND_API_KEY`')
40
+ const res = await fetch('https://api.resend.com/emails', {
41
+ method: 'POST',
42
+ headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json' },
43
+ body: JSON.stringify({
44
+ from: fromOf(m, options.from),
45
+ to: m.to,
46
+ subject: m.subject,
47
+ ...(m.text !== undefined && { text: m.text }),
48
+ ...(m.html !== undefined && { html: m.html }),
49
+ ...(m.replyTo && { reply_to: m.replyTo }),
50
+ }),
51
+ signal: AbortSignal.timeout(10_000),
52
+ })
53
+ if (!res.ok)
54
+ throw new StartError(
55
+ 'E003',
56
+ `Resend refused "${m.subject}": ${res.status} ${(await res.text()).slice(0, 300)}`,
57
+ 'check the API key and that the sender’s domain is verified in Resend',
58
+ )
59
+ },
60
+ }
61
+ }
62
+
63
+ /**
64
+ * SMTP through nodemailer (`pnpm add nodemailer`): `SMTP_URL` (`smtps://user:pass@smtp.example.com:465`) unless you
65
+ * pass `url`. One connection pool per mailer.
66
+ */
67
+ export function smtpMailer(options: { url?: string; from?: string } = {}): Mailer {
68
+ let transport: Promise<{ sendMail(m: object): Promise<unknown> }> | undefined
69
+ const open = () =>
70
+ (transport ??= (async () => {
71
+ const url = options.url ?? process.env.SMTP_URL
72
+ if (!url) throw new StartError('E004', 'SMTP needs a URL', 'set `SMTP_URL`')
73
+ let nodemailer: { createTransport(url: string): { sendMail(m: object): Promise<unknown> } }
74
+ try {
75
+ // Named at runtime, so an app without it builds; the build traces it when the app has it (app.mjs).
76
+ const name = 'nodemailer'
77
+ nodemailer = ((await import(/* @vite-ignore */ name)) as { default: typeof nodemailer })
78
+ .default
79
+ } catch {
80
+ throw new StartError('E004', 'SMTP needs nodemailer', '`pnpm add nodemailer`')
81
+ }
82
+ const pooled = new URL(url)
83
+ pooled.searchParams.set('pool', 'true')
84
+ return nodemailer.createTransport(pooled.toString())
85
+ })().catch((e) => {
86
+ transport = undefined
87
+ throw e
88
+ }))
89
+ return {
90
+ name: 'smtp',
91
+ async send(m) {
92
+ await (
93
+ await open()
94
+ ).sendMail({
95
+ from: fromOf(m, options.from),
96
+ to: m.to,
97
+ subject: m.subject,
98
+ text: m.text,
99
+ html: m.html,
100
+ replyTo: m.replyTo,
101
+ })
102
+ },
103
+ }
104
+ }
105
+
106
+ /** Dev: each message on the server log instead of sent, links and all, so sign-up and reset work with no provider. */
107
+ export function consoleMailer(): Mailer {
108
+ return {
109
+ name: 'console',
110
+ send(m) {
111
+ console.info(
112
+ `[kerf] email to ${[m.to].flat().join(', ')}: ${m.subject}\n${m.text ?? m.html ?? ''}\n`,
113
+ )
114
+ return Promise.resolve()
115
+ },
116
+ }
117
+ }
118
+
119
+ let chosen: Mailer | undefined
120
+ let dev = false
121
+
122
+ /** The server sets this from `src/email.server.ts` (or nothing) when it starts. */
123
+ export function useMailer(mailer: Mailer | undefined, isDev: boolean) {
124
+ chosen = mailer
125
+ dev = isDev
126
+ }
127
+
128
+ /** The mailer in use: the app's, else Resend or SMTP when the environment names one, else the log in dev. */
129
+ export function currentMailer(): Mailer | undefined {
130
+ if (chosen) return chosen
131
+ if (process.env.RESEND_API_KEY) return (chosen = resendMailer())
132
+ if (process.env.SMTP_URL) return (chosen = smtpMailer())
133
+ return dev ? consoleMailer() : undefined
134
+ }
135
+
136
+ /** Send one email through the app's mailer. E001 when production has none. */
137
+ export async function sendEmail(message: EmailMessage): Promise<void> {
138
+ const mailer = currentMailer()
139
+ if (!mailer)
140
+ throw new StartError(
141
+ 'E001',
142
+ `no way to send "${message.subject}"`,
143
+ 'set `RESEND_API_KEY` or `SMTP_URL`, or default-export a mailer from `src/email.server.ts`',
144
+ )
145
+ await mailer.send(message)
146
+ }
@@ -0,0 +1,87 @@
1
+ import { FnError, StartError, type Context, type Fn } from '../data'
2
+ import { unavailable } from '../db/core'
3
+
4
+ /** Whether a function names a rule that needs someone signed in (`'public'` and none don't). */
5
+ export const signedIn = (fn: Fn) => !!fn.def.auth && fn.def.auth !== 'public'
6
+
7
+ /** The roles a user has: Better Auth's `admin` plugin stores `'admin,user'`; an array works too. */
8
+ const rolesOf = (user: { role?: unknown }) =>
9
+ Array.isArray(user.role)
10
+ ? user.role.map(String)
11
+ : typeof user.role === 'string'
12
+ ? user.role.split(',').map((r) => r.trim())
13
+ : []
14
+
15
+ /**
16
+ * A function's `auth`: A003 when it needs a user and `ctx` has none at all, A002 when no one is signed in, A006 when
17
+ * the user lacks the role or fails `can`. A mutation that says nothing, in an app with auth, needs a signed-in user.
18
+ */
19
+ export async function guard(fn: Fn, ctx: Context) {
20
+ const rule = fn.def.auth ?? (fn.kind === 'mutation' && 'user' in ctx ? 'user' : undefined)
21
+ if (!rule || rule === 'public') return
22
+ if (!('user' in ctx))
23
+ throw new StartError(
24
+ 'A003',
25
+ `\`${fn.$id}\` has \`auth: 'user'\`, but \`ctx\` has no \`user\``,
26
+ 'spread `session(auth, request)` into what `src/context.server.ts` returns',
27
+ { status: 500 },
28
+ )
29
+ if (!(ctx as { user?: unknown }).user)
30
+ throw new StartError(
31
+ 'A002',
32
+ `\`${fn.$id}\` needs a signed-in user`,
33
+ fn.def.auth
34
+ ? 'sign in first, or guard the route with `redirect()` in its `load`'
35
+ : "sign in first; a mutation anyone may call (sign-in, sign-up) says `auth: 'public'`",
36
+ { status: 401 },
37
+ )
38
+ if (rule === 'user') return
39
+ const user = (ctx as { user: { role?: unknown } }).user
40
+ const allowed =
41
+ 'role' in rule
42
+ ? [rule.role].flat().some((r) => rolesOf(user).includes(r))
43
+ : await rule.can(ctx as never)
44
+ if (!allowed)
45
+ throw new StartError(
46
+ 'A006',
47
+ `\`${fn.$id}\` refused this user (${'role' in rule ? `needs role ${[rule.role].flat().join(' or ')}` : '`can` said no'})`,
48
+ 'sign in as a user it allows',
49
+ { status: 403 },
50
+ )
51
+ }
52
+
53
+ const DOWN =
54
+ /^(ECONNREFUSED|ECONNRESET|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT|CONNECT_TIMEOUT|CONNECTION_(CLOSED|ENDED|DESTROYED)|PROTOCOL_CONNECTION_LOST|P100[12])$/
55
+
56
+ interface Failure {
57
+ cause?: Failure | null
58
+ answer?: { message?: string; code?: string; status: number }
59
+ code?: string | number
60
+ message?: string
61
+ }
62
+
63
+ /** A dropped connection is Q016; a missing table is a migration that wasn't generated or applied (Q014): the driver's error, with the fix. */
64
+ export function dbError(e: unknown): unknown {
65
+ const failure = e as Failure | null | undefined
66
+ const cause = failure?.cause ?? failure
67
+ if (failure?.answer) return new FnError(failure.answer, failure.answer.status)
68
+ if (cause instanceof StartError) return cause // Drizzle wraps what a driver throws, the gate's Q016 included
69
+ if (!(e instanceof StartError) && DOWN.test(String(cause?.code ?? failure?.code ?? '')))
70
+ return unavailable(e)
71
+ const m = cause?.message ?? ''
72
+ if (
73
+ e instanceof StartError ||
74
+ !(
75
+ /no such (table|column)|has no column named/.test(m) ||
76
+ cause?.code === '42P01' ||
77
+ cause?.code === '42703'
78
+ )
79
+ )
80
+ return e
81
+ return new StartError(
82
+ 'Q014',
83
+ `the database doesn't match the schema: ${m}`,
84
+ 'run `kerf db generate`, then reload (new migrations apply on the next request)',
85
+ { status: 500 },
86
+ )
87
+ }
@@ -0,0 +1,21 @@
1
+ import type { Context, Fn } from '../data'
2
+ import type { Scope, Touched } from './scope'
3
+
4
+ /** A body in another process (research 36): what it adds to the tags and reports it touched arrive with the value. */
5
+ export async function callImpl(
6
+ fn: Fn,
7
+ input: unknown,
8
+ ctx: Context,
9
+ scope: Scope,
10
+ track: { touched?: Touched | undefined; added: string[] },
11
+ ) {
12
+ const { touched, added } = track
13
+ const {
14
+ value,
15
+ tags,
16
+ touched: tables,
17
+ } = await fn.def.impl!.call({ fn, input, ctx, request: scope.request })
18
+ added.push(...tags)
19
+ if (touched) for (const t of tables) touched[fn.kind === 'query' ? 'read' : 'write'].add(t)
20
+ return value
21
+ }
@@ -0,0 +1,66 @@
1
+ import { FnError, isRedirect, StartError } from '../data'
2
+ import type { Scope, ScopeEntry } from './scope'
3
+
4
+ /** How long a landed read waits for the others in flight, in ms: long enough for a pool's worth of replies. */
5
+ const GATHER = 4
6
+
7
+ interface Landing {
8
+ flying: number
9
+ held: (() => void)[]
10
+ timer?: ReturnType<typeof setTimeout> | undefined
11
+ }
12
+ const landings = new WeakMap<object, Landing>()
13
+
14
+ /**
15
+ * A read as a render sees it. Each landing costs a pass over the whole page, so reads land together: all of them once
16
+ * none is in flight, or `GATHER` after the first, so a slow query never holds a fast one for longer than that.
17
+ */
18
+ export function landed(scope: Scope, e: ScopeEntry): Promise<unknown> {
19
+ if (e.read) return e.read
20
+ let l = landings.get(scope.entries)
21
+ if (!l) landings.set(scope.entries, (l = { flying: 0, held: [] }))
22
+ const at = l
23
+ at.flying++
24
+ const release = () => {
25
+ clearTimeout(at.timer)
26
+ at.timer = undefined
27
+ for (const go of at.held.splice(0)) go()
28
+ }
29
+ e.read = new Promise((ok, no) => {
30
+ const land = () => {
31
+ at.held.push(() => (e.e !== undefined ? no(shown(e.e, scope)) : ok(e.v)))
32
+ if (!--at.flying) release()
33
+ else at.timer ??= setTimeout(release, GATHER)
34
+ }
35
+ e.p.then(land, land)
36
+ })
37
+ e.read.catch(() => {}) // a failure surfaces where the value is read
38
+ return e.read
39
+ }
40
+
41
+ const FAILED = 'Server function failed.'
42
+
43
+ /** A failure as the page may show it. In production a fault's text stays in the diagnostics: a driver's error names tables. */
44
+ export function shown(e: unknown, scope: Scope): unknown {
45
+ const { dev, onDiagnostic } = scope.options
46
+ const fault = !(
47
+ e instanceof FnError ||
48
+ isRedirect(e) ||
49
+ (e instanceof StartError && Number(e.extra.status ?? 500) < 500)
50
+ )
51
+ const { message, code } = (e ?? {}) as { message?: string; code?: string }
52
+ if (dev || !fault) {
53
+ if (message !== undefined) scope.said.add(message)
54
+ return e
55
+ }
56
+ onDiagnostic?.({
57
+ code: code ?? 'E_FN',
58
+ severity: 'error',
59
+ message: `a render read a failed query: ${e instanceof Error ? (e.stack ?? e.message) : String(e)}`,
60
+ })
61
+ return new Error(FAILED)
62
+ }
63
+
64
+ /** The message for a value that's going in a page: its own when `shown` passed it, else the plain one. */
65
+ export const said = (message: string, scope: Scope) =>
66
+ scope.options.dev || scope.said.has(message) ? message : FAILED
@@ -0,0 +1,25 @@
1
+ import { CLIENT_IP, StartError, type Context, type Fn } from '../data'
2
+ import type { Scope, Store } from './scope'
3
+
4
+ /**
5
+ * A function's `limit`: one more call by this caller, refused with 429 (Q019) and `Retry-After` once it's over. The
6
+ * caller is the signed-in user, or the client's address (`by: 'ip'`, or no one signed in).
7
+ */
8
+ export async function limitCall(fn: Fn, ctx: Context, scope: Scope, store: Store) {
9
+ const rule = fn.def.limit
10
+ if (!rule || !store.consume) return
11
+ const user = (ctx as { user?: { id?: string | number } | null }).user?.id
12
+ const who =
13
+ rule.by !== 'ip' && user != null
14
+ ? `u:${user}`
15
+ : `ip:${scope.request.headers.get(CLIENT_IP) ?? 'unknown'}`
16
+ const { allowed, retryAfter } = await store.consume(`limit:${fn.$id}:${who}`, rule)
17
+ if (allowed) return
18
+ scope.headers.set('retry-after', String(retryAfter ?? rule.window))
19
+ throw new StartError(
20
+ 'Q019',
21
+ `\`${fn.$id}\` was called too often (${rule.max} per ${rule.window} s)`,
22
+ `wait ${retryAfter ?? rule.window} s`,
23
+ { status: 429 },
24
+ )
25
+ }
@@ -0,0 +1,24 @@
1
+ /** Shared values being worked out now, by stored key. */
2
+ const running = new Map<string, Promise<{ v: unknown; tags: string[] }>>()
3
+
4
+ /**
5
+ * Concurrent misses on one shared value run it once: a caller that finds a run already working on `key` waits for its
6
+ * answer. If that run fails, the caller runs its own (errors aren't shared, as they aren't cached).
7
+ */
8
+ export async function once(
9
+ key: string,
10
+ run: () => Promise<{ v: unknown; tags: string[] }>,
11
+ ): Promise<{ v: unknown; tags: string[] }> {
12
+ const theirs = running.get(key)
13
+ if (theirs) {
14
+ const answer = await theirs.catch(() => undefined)
15
+ if (answer) return answer
16
+ }
17
+ const mine = run()
18
+ running.set(key, mine)
19
+ try {
20
+ return await mine
21
+ } finally {
22
+ if (running.get(key) === mine) running.delete(key)
23
+ }
24
+ }