@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/channel.ts ADDED
@@ -0,0 +1,250 @@
1
+ // `channel` and `sharedState` (research 32): definitions on both sides, and the browser's half. One line per tab on the
2
+ // browser's one socket (link.ts), one join per id + params, shared by every reader and held by this module, so a remount within `keep`
3
+ // finds its messages. The socket server is socket.ts, and `room.in(params).publish` reaches it through
4
+ // `runtime.channels`, so nothing of the server ships here.
5
+
6
+ import { type Derived, type State } from '@kerf-js/core'
7
+ import {
8
+ fns,
9
+ runtime,
10
+ StartError,
11
+ track,
12
+ type Context,
13
+ type Fn,
14
+ type Skip,
15
+ type StandardSchemaV1,
16
+ } from './data'
17
+ import { connect, shared, connectBuiltIn } from './channel/connections'
18
+ import { keepOpen, wakeSocket, setFake, type Frame, type SocketLink } from './channel/socket'
19
+
20
+ export { connectBuiltIn, keepOpen, wakeSocket }
21
+ export type { Frame, SocketLink }
22
+
23
+ // ---- definitions ----------------------------------------------------------------------------------------------------
24
+
25
+ type In<S> = S extends StandardSchemaV1<infer I, unknown> ? I : void
26
+ type Out<S> = S extends StandardSchemaV1<unknown, infer O> ? O : undefined
27
+ type Schemas = Record<string, StandardSchemaV1>
28
+ type Inputs<T extends Schemas> = { [K in keyof T]: In<T[K]> }
29
+ type Outputs<T extends Schemas> = { [K in keyof T]: Out<T[K]> }
30
+
31
+ /**
32
+ * Where a connection stands; `unauthorized` waits for `rejoin`. `unavailable`: this deploy can't hold a socket (a
33
+ * function host, R024), so nothing connects and nothing is retried.
34
+ */
35
+ export type ChannelStatus =
36
+ | 'connecting'
37
+ | 'open'
38
+ | 'reconnecting'
39
+ | 'closed'
40
+ | 'unauthorized'
41
+ | 'unavailable'
42
+
43
+ /** `room.publish`: who a message goes to, and whether it can be replayed. */
44
+ export interface PublishOptions {
45
+ /** Not back to the sender. */
46
+ exceptSelf?: boolean
47
+ /** Only to this connection, wherever it is: the `id` a handler was given. */
48
+ to?: string
49
+ /** Not kept for a resume: a cursor, a heartbeat, anything the next one replaces. */
50
+ volatile?: boolean
51
+ }
52
+
53
+ /** A channel instance as a server handler has it. */
54
+ export interface Room<P, M> {
55
+ params: P
56
+ /** To everyone in the room, on every instance. */
57
+ publish<K extends keyof M & string>(
58
+ name: K,
59
+ message: M[K],
60
+ options?: PublishOptions,
61
+ ): Promise<void>
62
+ }
63
+
64
+ /** `channel()`: the params, the messages each side may send, and who may join. */
65
+ export interface ChannelDef<
66
+ P extends StandardSchemaV1 | undefined,
67
+ C extends Schemas,
68
+ S extends Schemas,
69
+ > {
70
+ params?: P
71
+ /** Required (R001). Runs on every join and at each session re-check. `() => true` must be written out. */
72
+ authorize: (args: { ctx: Context; params: Out<P> }) => boolean | Promise<boolean>
73
+ /** Client → server, always validated. */
74
+ client?: C
75
+ /** Server → client, validated in dev and tests. */
76
+ server?: S
77
+ /** `id` is the sender's connection, the same one `left` gets. */
78
+ on?: {
79
+ [K in keyof C]?: (args: {
80
+ msg: Out<C[K]>
81
+ id: string
82
+ ctx: Context
83
+ params: Out<P>
84
+ room: Room<Out<P>, Inputs<S>>
85
+ }) => unknown
86
+ }
87
+ /** A connection stopped being in the room: it left, closed, or lost `authorize`. Not called if its instance dies. */
88
+ left?: (args: {
89
+ id: string
90
+ ctx: Context
91
+ params: Out<P>
92
+ room: Room<Out<P>, Inputs<S>>
93
+ }) => unknown
94
+ limits?: { perSecond?: number }
95
+ $id?: string
96
+ }
97
+
98
+ /** A live join of a channel, from `.connect()`. */
99
+ export interface Connection<C, S> {
100
+ readonly status: Derived<ChannelStatus>
101
+ /** Which room this is. Changes when a function argument moves to another, even one already open. */
102
+ readonly room: Derived<string | undefined>
103
+ /** The last refusal or failure. */
104
+ readonly error: unknown
105
+ /** Ticks when the server couldn't resume: messages may be missing, so refetch what the room's history is. */
106
+ readonly resets: Derived<number>
107
+ /** Keep a room's messages of one name, in the cache: a remount within `keep` finds them. `key` drops a repeat. */
108
+ collect<K extends keyof S & string>(
109
+ name: K,
110
+ options?: { max?: number; key?: (message: S[K]) => unknown },
111
+ ): Derived<S[K][]>
112
+ /** Each message of one name, until the owner is disposed. */
113
+ on<K extends keyof S & string>(name: K, fn: (message: S[K]) => void): () => void
114
+ onReset(fn: () => void): () => void
115
+ /** Resolves on the server's ack, rejects with what it refused. Waits up to 10 s for the socket; never retries. */
116
+ send<K extends keyof C & string>(name: K, message: C[K]): Promise<void>
117
+ /** Join again after `unauthorized`. */
118
+ retry(): void
119
+ }
120
+
121
+ type Arg<P> = P | (() => P | Skip)
122
+ /** How long a join outlives the last component using it. */
123
+ export interface ConnectOptions {
124
+ keep?: string | number
125
+ }
126
+
127
+ /** What `channel()` returns: connect from a page, publish from the server. */
128
+ export interface Channel<P, C, S> {
129
+ /** In a component or scope. A function argument re-joins when what it reads changes; `skip` leaves. */
130
+ connect(
131
+ ...args: [P] extends [void]
132
+ ? [params?: undefined | (() => undefined | Skip), options?: ConnectOptions]
133
+ : [params: Arg<P>, options?: ConnectOptions]
134
+ ): Connection<C, S>
135
+ /** On the server, from a mutation or a job. */
136
+ in(...args: [P] extends [void] ? [] : [params: P]): {
137
+ publish<K extends keyof S & string>(name: K, message: S[K]): Promise<void>
138
+ }
139
+ readonly kind: 'channel'
140
+ readonly $id: string
141
+ }
142
+
143
+ const FN = Symbol.for('kerf.fn')
144
+ let auto = 0
145
+
146
+ /** A named room of schema-checked messages over the shared socket. */
147
+ export function channel<
148
+ P extends StandardSchemaV1 | undefined = undefined,
149
+ C extends Schemas = {},
150
+ S extends Schemas = {},
151
+ >(def: ChannelDef<P, C, S>): Channel<In<P>, Inputs<C>, Outputs<S>> {
152
+ const id = def.$id ?? `c${++auto}`
153
+ if (!(def as { $stub?: boolean }).$stub && !def.authorize)
154
+ throw new StartError(
155
+ 'R001',
156
+ `\`${id}\` has no \`authorize\`: anyone could join it`,
157
+ 'add `authorize` (`() => true` must be written out)',
158
+ )
159
+ const fn: Fn = { kind: 'channel', $id: id, def: def as Fn['def'] }
160
+ fns.set(id, fn)
161
+ return {
162
+ kind: 'channel',
163
+ $id: id,
164
+ [FN]: fn,
165
+ connect: (params?: unknown, options?: ConnectOptions) => connect(fn, params, options),
166
+ in: (params?: unknown) => ({
167
+ publish: (name: string, message: unknown) =>
168
+ runtime.channels!.publish(fn, params, name, message),
169
+ }),
170
+ } as never
171
+ }
172
+
173
+ /** `sharedState()`: the key and value schemas, the first value, and who reads and writes. */
174
+ export interface SharedDef<K extends StandardSchemaV1, V extends StandardSchemaV1> {
175
+ key: K
176
+ value: V
177
+ /** What a reader has until the server says otherwise. Kept in the client bundle, so plain data. */
178
+ initial: Out<V>
179
+ /** Both required (R001). */
180
+ authorize: {
181
+ read: (args: { ctx: Context; key: Out<K> }) => boolean | Promise<boolean>
182
+ write: (args: { ctx: Context; key: Out<K> }) => boolean | Promise<boolean>
183
+ }
184
+ $id?: string
185
+ }
186
+
187
+ /** A box in a scope: reads as a value, and a write is optimistic, sent, and last writer wins on the server. */
188
+ export type SharedBox<T> = State<T> & {
189
+ readonly status: Derived<ChannelStatus>
190
+ readonly error: unknown
191
+ }
192
+
193
+ /** What `sharedState()` returns: read a value on a page, set it from the server. */
194
+ export interface SharedState<K, V> {
195
+ connect(key: K | (() => K | Skip), options?: ConnectOptions): SharedBox<V>
196
+ /** On the server: write it from a mutation or a job. */
197
+ in(key: K): { set(value: V): Promise<void> }
198
+ readonly kind: 'shared'
199
+ readonly $id: string
200
+ }
201
+
202
+ /** One value per key that every client holding that key sees change. */
203
+ export function sharedState<K extends StandardSchemaV1, V extends StandardSchemaV1>(
204
+ name: string,
205
+ def: SharedDef<K, V>,
206
+ ): SharedState<In<K>, Out<V>> {
207
+ const id = def.$id ?? `shared:${name}`
208
+ if (!(def as { $stub?: boolean }).$stub && (!def.authorize?.read || !def.authorize?.write))
209
+ throw new StartError(
210
+ 'R001',
211
+ `\`${id}\` needs \`authorize: { read, write }\`: anyone could read or write it`,
212
+ '`() => true` must be written out',
213
+ )
214
+ const fn: Fn = { kind: 'shared', $id: id, def }
215
+ fns.set(id, fn)
216
+ return {
217
+ kind: 'shared',
218
+ $id: id,
219
+ [FN]: fn,
220
+ connect: (key: unknown, options?: ConnectOptions) => shared(fn, key, options),
221
+ in: (key: unknown) => ({ set: (value: unknown) => runtime.channels!.set(fn, key, value) }),
222
+ } as never
223
+ }
224
+
225
+ /** @kerf-js/core/test only: an opaque specifier, so a bundler keeps neither the fake nor the socket server (research 30 §10). */
226
+ const FAKE = './channel-fake.ts' // with its extension: nothing resolves this one for a linked package
227
+ function fake(onFrame: (d: Frame) => void, closed: (code: number) => void): SocketLink {
228
+ let link: SocketLink | undefined
229
+ let up!: () => void
230
+ void track(
231
+ new Promise<void>((ok) => {
232
+ up = ok
233
+ }),
234
+ )
235
+ const loading = import(/* @vite-ignore */ FAKE)
236
+ .then((m) => m.open(onFrame, closed, up))
237
+ .then(
238
+ (l) => (link = l),
239
+ (e) => (up(), closed(1006), Promise.reject(e)),
240
+ )
241
+ .catch(() => {})
242
+ return {
243
+ send: (t) => void track(loading.then(() => link?.send(t))),
244
+ close: () => {
245
+ void loading.then(() => link?.close())
246
+ },
247
+ }
248
+ }
249
+
250
+ setFake(fake)
package/src/client.tsx ADDED
@@ -0,0 +1,27 @@
1
+ // What an app's entry imports. `run.tsx` is the client: the router, the runtime and whatever hydrates. It's a chunk of its
2
+ // own so a page with only lazy islands can be read without it (`boot.ts`, PLAN §11); a page with work to do has it
3
+ // preloaded, and starts it at once.
4
+
5
+ import './gate.css'
6
+ import { boot } from './boot'
7
+ import type { ClientRoutes, start as run } from './run'
8
+
9
+ export type { ClientRoutes } from './run'
10
+
11
+ /**
12
+ * Hydrate the page in `#app` and take over its links. Resolves once hydrated, which on a page of lazy islands is when
13
+ * one is first needed. `eager`: don't wait for that.
14
+ */
15
+ export function start(
16
+ routes: ClientRoutes,
17
+ options: { container?: Element; eager?: boolean } = {},
18
+ ): ReturnType<typeof run> {
19
+ return new Promise((settle, fail) => {
20
+ const full = () =>
21
+ import('./run')
22
+ .then((m) => m.start(routes, options))
23
+ .then(settle)
24
+ .catch((e) => (fail(e), Promise.reject(e)))
25
+ options.eager ? void full() : boot(full)
26
+ })
27
+ }
@@ -0,0 +1,237 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { toJson } from '../shape.mjs'
3
+
4
+ const tagsOf = (t) => (typeof t === 'function' ? 'dynamic' : [...(t ?? [])])
5
+
6
+ /** The first string or array in a JSON Schema with no upper bound, as a path. */
7
+ function unbounded(s, path = 'input') {
8
+ if (!s || typeof s !== 'object') return
9
+ if (s.type === 'string' && s.maxLength === undefined && !s.enum && s.const === undefined)
10
+ return path
11
+ if (s.type === 'array' && s.maxItems === undefined) return path
12
+ if (s.items) {
13
+ const hit = unbounded(s.items, `${path}[]`)
14
+ if (hit) return hit
15
+ }
16
+ for (const [k, v] of Object.entries(s.properties ?? {})) {
17
+ const hit = unbounded(v, `${path}.${k}`)
18
+ if (hit) return hit
19
+ }
20
+ for (const v of [...(s.anyOf ?? []), ...(s.oneOf ?? [])]) {
21
+ const hit = unbounded(v, path)
22
+ if (hit) return hit
23
+ }
24
+ }
25
+
26
+ /** A one-way `.transform()` or `preprocess` in a Zod schema: parsed input it touched can't be sent on (`encode` throws). */
27
+ function oneWay(schema, seen = new Set()) {
28
+ if (!schema || typeof schema !== 'object' || seen.has(schema)) return false
29
+ seen.add(schema)
30
+ const def = schema._zod?.def
31
+ if (def?.type === 'transform') return true
32
+ return Object.values(def ?? schema).some((v) => oneWay(v, seen)) // arrays and `shape` hold schemas too
33
+ }
34
+
35
+ /** The first union in a JSON Schema with two object or array arms, as a path: typify has no faithful type for one. */
36
+ function plainUnion(s, path) {
37
+ if (!s || typeof s !== 'object') return
38
+ const arms = s.anyOf?.filter((x) => x.type !== 'null')
39
+ if (arms?.length > 1 && arms.some((x) => x.type === 'object' || x.type === 'array' || x.$ref))
40
+ return path
41
+ for (const [k, v] of Object.entries(s.properties ?? {})) {
42
+ const hit = plainUnion(v, `${path}.${k}`)
43
+ if (hit) return hit
44
+ }
45
+ for (const v of [
46
+ s.items,
47
+ ...(s.prefixItems ?? []),
48
+ ...(s.anyOf ?? []),
49
+ ...(s.oneOf ?? []),
50
+ ...Object.values(s.$defs ?? {}),
51
+ ]) {
52
+ const hit = plainUnion(v, path)
53
+ if (hit) return hit
54
+ }
55
+ }
56
+
57
+ const CODEC =
58
+ '`z.codec(z.iso.datetime(), z.date(), { decode, encode })` for a date, `z.codec(z.string(), z.bigint(), …)` for a bigint'
59
+
60
+ /**
61
+ * A function with `impl`, as a sidecar sees it (research 36 §3). The wire is the *input* side of every schema: TS sends
62
+ * parsed input encoded back, and parses what comes back, so codecs and transforms on an output are TS's business.
63
+ */
64
+ function implOf(f, report) {
65
+ const { impl, input, output, errors = {} } = f.def
66
+ const r101 = (why) => report({ code: 'R101', severity: 'error', why: `\`${f.$id}\`: ${why}` })
67
+ const wire = (schema, what) => {
68
+ const json = toJson(schema, 'input')
69
+ if (!json)
70
+ r101(`${what} has a type JSON can't carry, so no Rust type can be generated. Use ${CODEC}.`)
71
+ return json ?? {}
72
+ }
73
+ if (input) wire(input, '`input`')
74
+ if (input && oneWay(input))
75
+ r101(
76
+ "`input` has a one-way `.transform()`, so its parsed value can't be sent. Use `z.codec(…)`, or do it in Rust.",
77
+ )
78
+ if (!output)
79
+ r101(
80
+ 'a function with `impl` needs `output`: it\'s the contract for what comes back, and `z.null()` says "nothing".',
81
+ )
82
+ return {
83
+ kind: impl.kind,
84
+ target: impl.target,
85
+ service: impl.service,
86
+ ctx:
87
+ f.def.cache && f.def.cache.scope !== 'user'
88
+ ? 'shared'
89
+ : f.def.auth && f.def.auth !== 'public'
90
+ ? 'user'
91
+ : 'ctx',
92
+ output: output ? wire(output, '`output`') : {},
93
+ errors: Object.fromEntries(
94
+ Object.entries(errors).map(([code, schema]) => [code, wire(schema, `error \`${code}\``)]),
95
+ ),
96
+ }
97
+ }
98
+
99
+ /** What a sidecar is built from, per service: a binary whose hash differs was built from another contract (R103). */
100
+ function services(functions) {
101
+ const out = {}
102
+ for (const f of functions)
103
+ if (f.impl)
104
+ (out[f.impl.service] ??= {
105
+ kind: f.impl.kind,
106
+ hash: createHash('sha256'),
107
+ functions: [],
108
+ }).functions.push(f.id)
109
+ for (const f of functions)
110
+ if (f.impl) out[f.impl.service].hash.update(JSON.stringify([f.id, f.kind, f.input, f.impl]))
111
+ return Object.fromEntries(
112
+ Object.entries(out).map(([k, v]) => [
113
+ k,
114
+ { kind: v.kind, hash: v.hash.digest('hex').slice(0, 16), functions: v.functions },
115
+ ]),
116
+ )
117
+ }
118
+
119
+ /** Presets with no file for an addon or a `.wasm` to be read from. */
120
+ function channelDescription(f, bound) {
121
+ const part = (key) => (f.def[key] ? (toJson(f.def[key], 'input') ?? {}) : undefined)
122
+ const messages = (list) =>
123
+ Object.fromEntries(Object.entries(list ?? {}).map(([k, s]) => [k, toJson(s, 'input') ?? {}]))
124
+ const client = f.kind === 'shared' ? { value: part('value') } : messages(f.def.client)
125
+ bound(part(f.kind === 'shared' ? 'key' : 'params'), f.kind === 'shared' ? 'key' : 'params')
126
+ for (const [k, json] of Object.entries(client)) bound(json, `client.${k}`)
127
+ return {
128
+ id: f.$id,
129
+ name: f.$id.replace(/\..*$/, ''),
130
+ kind: f.kind,
131
+ input: part(f.kind === 'shared' ? 'key' : 'params') ?? null,
132
+ output: null,
133
+ client,
134
+ server: messages(f.def.server),
135
+ auth: 'authorize',
136
+ errors: ['R011', 'Q002'],
137
+ }
138
+ }
139
+
140
+ function describeFunction(f, rust, diagnostics) {
141
+ const schema = (key, side) => {
142
+ const s = f.def[key]
143
+ if (!s) return undefined
144
+ const json = toJson(s, side)
145
+ if (!json)
146
+ diagnostics.push({
147
+ code: 'C001',
148
+ severity: 'warning',
149
+ why: `\`${f.$id}\`'s \`${key}\` schema can't become JSON Schema: the contract says \`{}\`.`,
150
+ })
151
+ return json ?? {}
152
+ }
153
+ const errors = [
154
+ ...(f.def.input ? ['Q002'] : []),
155
+ ...(f.def.auth && f.def.auth !== 'public' ? ['A002'] : []),
156
+ ...(typeof f.def.auth === 'object' ? ['A006'] : []),
157
+ ...(f.kind === 'mutation' ? ['Q010'] : []),
158
+ ...Object.keys(f.def.errors ?? {}),
159
+ ]
160
+ const impl = f.def.impl && implOf(f, (d) => diagnostics.push(d))
161
+ const input = impl
162
+ ? f.def.input
163
+ ? (toJson(f.def.input, 'input') ?? {})
164
+ : null
165
+ : (schema('input', 'input') ?? null)
166
+ if (impl && rust.unions !== 'allow') {
167
+ const hit = [
168
+ ['input', input],
169
+ ['output', impl.output],
170
+ ...Object.entries(impl.errors).map(([k, v]) => [`error ${k}`, v]),
171
+ ]
172
+ .map(([name, s]) => plainUnion(s, name))
173
+ .find(Boolean)
174
+ if (hit)
175
+ diagnostics.push({
176
+ code: 'R102',
177
+ severity: 'error',
178
+ why: `\`${f.$id}\`'s \`${hit}\` is a plain \`z.union\` of objects: it has no tag, so Rust can't tell its arms apart reliably. Use \`z.discriminatedUnion\`, or set \`rust: { unions: 'allow' }\` in kerf.config.ts.`,
179
+ })
180
+ }
181
+ const bound = (json, path) => {
182
+ const hit = unbounded(json, path)
183
+ if (hit)
184
+ diagnostics.push({
185
+ code: 'R005',
186
+ severity: 'warning',
187
+ why: `\`${f.$id}\`'s \`${hit}\` has no upper bound: a client decides how much the server holds. Add \`.max()\`.`,
188
+ })
189
+ }
190
+ if (f.kind === 'stream') bound(input)
191
+ if (f.kind === 'channel' || f.kind === 'shared') return channelDescription(f, bound)
192
+
193
+ return {
194
+ id: f.$id,
195
+ name: f.$id.replace(/\..*$/, ''),
196
+ kind: f.kind,
197
+ input,
198
+ output: impl
199
+ ? impl.output
200
+ : (schema(f.kind === 'stream' ? 'message' : 'output', 'output') ?? null),
201
+ ...(impl && { impl }),
202
+ ...(f.kind === 'query'
203
+ ? { tags: tagsOf(f.def.tags), cache: f.def.cache ?? null }
204
+ : f.kind === 'mutation'
205
+ ? { invalidates: tagsOf(f.def.invalidates) }
206
+ : {}),
207
+ auth:
208
+ typeof f.def.auth === 'object'
209
+ ? 'role' in f.def.auth
210
+ ? { role: [f.def.auth.role].flat() }
211
+ : 'policy'
212
+ : (f.def.auth ?? (f.kind === 'mutation' ? 'default' : 'public')),
213
+ errors,
214
+ }
215
+ }
216
+
217
+ /** @param {Map<string, any>} fns @param {{ unions?: 'allow' }} [rust] the config's `rust` */
218
+ export function describe(fns, rust = {}) {
219
+ const diagnostics = []
220
+ const functions = [...fns.values()]
221
+ .sort((a, b) => a.$id.localeCompare(b.$id))
222
+ .map((f) => describeFunction(f, rust, diagnostics))
223
+ const rusts = services(functions)
224
+ for (const f of functions)
225
+ if (f.impl && f.impl.kind !== rusts[f.impl.service].kind)
226
+ diagnostics.push({
227
+ code: 'R109',
228
+ severity: 'error',
229
+ why: `\`${f.impl.service}\` is named by both \`remote()\` and \`native()\`: a crate is one or the other. Rename one.`,
230
+ })
231
+ return {
232
+ version: 1,
233
+ ...(Object.keys(rusts).length && { services: rusts }),
234
+ functions,
235
+ diagnostics,
236
+ }
237
+ }