@eloxiv/client 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 (269) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +6 -2
  3. package/dist/Account.d.ts +131 -0
  4. package/dist/Account.d.ts.map +1 -0
  5. package/dist/Account.js +169 -0
  6. package/dist/Account.js.map +1 -0
  7. package/dist/Agent.d.ts +496 -0
  8. package/dist/Agent.d.ts.map +1 -0
  9. package/dist/Agent.js +228 -0
  10. package/dist/Agent.js.map +1 -0
  11. package/dist/AgentSync.d.ts +990 -0
  12. package/dist/AgentSync.d.ts.map +1 -0
  13. package/dist/AgentSync.js +46 -0
  14. package/dist/AgentSync.js.map +1 -0
  15. package/dist/AppState.d.ts +127 -0
  16. package/dist/AppState.d.ts.map +1 -0
  17. package/dist/AppState.js +145 -0
  18. package/dist/AppState.js.map +1 -0
  19. package/dist/AppStateSync.d.ts +193 -0
  20. package/dist/AppStateSync.d.ts.map +1 -0
  21. package/dist/AppStateSync.js +23 -0
  22. package/dist/AppStateSync.js.map +1 -0
  23. package/dist/Auth.d.ts +95 -0
  24. package/dist/Auth.d.ts.map +1 -0
  25. package/dist/Auth.js +139 -0
  26. package/dist/Auth.js.map +1 -0
  27. package/dist/Avatars.d.ts +53 -0
  28. package/dist/Avatars.d.ts.map +1 -0
  29. package/dist/Avatars.js +121 -0
  30. package/dist/Avatars.js.map +1 -0
  31. package/dist/BrowserAnalytics.d.ts +56 -0
  32. package/dist/BrowserAnalytics.d.ts.map +1 -0
  33. package/dist/BrowserAnalytics.js +94 -0
  34. package/dist/BrowserAnalytics.js.map +1 -0
  35. package/dist/Chat.d.ts +712 -0
  36. package/dist/Chat.d.ts.map +1 -0
  37. package/dist/Chat.js +883 -0
  38. package/dist/Chat.js.map +1 -0
  39. package/dist/ChatIntegrity.d.ts +63 -0
  40. package/dist/ChatIntegrity.d.ts.map +1 -0
  41. package/dist/ChatIntegrity.js +89 -0
  42. package/dist/ChatIntegrity.js.map +1 -0
  43. package/dist/ChatSends.d.ts +103 -0
  44. package/dist/ChatSends.d.ts.map +1 -0
  45. package/dist/ChatSends.js +157 -0
  46. package/dist/ChatSends.js.map +1 -0
  47. package/dist/Client.d.ts +113 -0
  48. package/dist/Client.d.ts.map +1 -0
  49. package/dist/Client.js +189 -0
  50. package/dist/Client.js.map +1 -0
  51. package/dist/Collab.d.ts +138 -0
  52. package/dist/Collab.d.ts.map +1 -0
  53. package/dist/Collab.js +454 -0
  54. package/dist/Collab.js.map +1 -0
  55. package/dist/CollabTools.d.ts +129 -0
  56. package/dist/CollabTools.d.ts.map +1 -0
  57. package/dist/CollabTools.js +277 -0
  58. package/dist/CollabTools.js.map +1 -0
  59. package/dist/Connections.d.ts +288 -0
  60. package/dist/Connections.d.ts.map +1 -0
  61. package/dist/Connections.js +316 -0
  62. package/dist/Connections.js.map +1 -0
  63. package/dist/Consent.d.ts +338 -0
  64. package/dist/Consent.d.ts.map +1 -0
  65. package/dist/Consent.js +142 -0
  66. package/dist/Consent.js.map +1 -0
  67. package/dist/Desktop.d.ts +61 -0
  68. package/dist/Desktop.d.ts.map +1 -0
  69. package/dist/Desktop.js +101 -0
  70. package/dist/Desktop.js.map +1 -0
  71. package/dist/Directory.d.ts +36 -0
  72. package/dist/Directory.d.ts.map +1 -0
  73. package/dist/Directory.js +42 -0
  74. package/dist/Directory.js.map +1 -0
  75. package/dist/ErrorReporter.d.ts +48 -0
  76. package/dist/ErrorReporter.d.ts.map +1 -0
  77. package/dist/ErrorReporter.js +70 -0
  78. package/dist/ErrorReporter.js.map +1 -0
  79. package/dist/ExpoSqlite.d.ts +7 -0
  80. package/dist/ExpoSqlite.d.ts.map +1 -0
  81. package/dist/ExpoSqlite.js +7 -0
  82. package/dist/ExpoSqlite.js.map +1 -0
  83. package/dist/FileSync.d.ts +265 -0
  84. package/dist/FileSync.d.ts.map +1 -0
  85. package/dist/FileSync.js +29 -0
  86. package/dist/FileSync.js.map +1 -0
  87. package/dist/FileTables.gen.d.ts +109 -0
  88. package/dist/FileTables.gen.d.ts.map +1 -0
  89. package/dist/FileTables.gen.js +23 -0
  90. package/dist/FileTables.gen.js.map +1 -0
  91. package/dist/Foldkit.d.ts +487 -0
  92. package/dist/Foldkit.d.ts.map +1 -0
  93. package/dist/Foldkit.js +617 -0
  94. package/dist/Foldkit.js.map +1 -0
  95. package/dist/History.d.ts +133 -0
  96. package/dist/History.d.ts.map +1 -0
  97. package/dist/History.js +210 -0
  98. package/dist/History.js.map +1 -0
  99. package/dist/InboxSync.d.ts +428 -0
  100. package/dist/InboxSync.d.ts.map +1 -0
  101. package/dist/InboxSync.js +37 -0
  102. package/dist/InboxSync.js.map +1 -0
  103. package/dist/KernelTables.gen.d.ts +1522 -0
  104. package/dist/KernelTables.gen.d.ts.map +1 -0
  105. package/dist/KernelTables.gen.js +307 -0
  106. package/dist/KernelTables.gen.js.map +1 -0
  107. package/dist/Make.d.ts +75 -0
  108. package/dist/Make.d.ts.map +1 -0
  109. package/dist/Make.js +70 -0
  110. package/dist/Make.js.map +1 -0
  111. package/dist/Models.d.ts +88 -0
  112. package/dist/Models.d.ts.map +1 -0
  113. package/dist/Models.js +80 -0
  114. package/dist/Models.js.map +1 -0
  115. package/dist/Optimistic.d.ts +120 -0
  116. package/dist/Optimistic.d.ts.map +1 -0
  117. package/dist/Optimistic.js +231 -0
  118. package/dist/Optimistic.js.map +1 -0
  119. package/dist/PlatformSync.d.ts +273 -0
  120. package/dist/PlatformSync.d.ts.map +1 -0
  121. package/dist/PlatformSync.js +92 -0
  122. package/dist/PlatformSync.js.map +1 -0
  123. package/dist/Poll.d.ts +113 -0
  124. package/dist/Poll.d.ts.map +1 -0
  125. package/dist/Poll.js +179 -0
  126. package/dist/Poll.js.map +1 -0
  127. package/dist/Preferences.d.ts +18 -0
  128. package/dist/Preferences.d.ts.map +1 -0
  129. package/dist/Preferences.js +22 -0
  130. package/dist/Preferences.js.map +1 -0
  131. package/dist/Proposals.d.ts +29 -0
  132. package/dist/Proposals.d.ts.map +1 -0
  133. package/dist/Proposals.js +41 -0
  134. package/dist/Proposals.js.map +1 -0
  135. package/dist/React.d.ts +17 -0
  136. package/dist/React.d.ts.map +1 -0
  137. package/dist/React.js +17 -0
  138. package/dist/React.js.map +1 -0
  139. package/dist/Reader.d.ts +35 -0
  140. package/dist/Reader.d.ts.map +1 -0
  141. package/dist/Reader.js +136 -0
  142. package/dist/Reader.js.map +1 -0
  143. package/dist/Resources.d.ts +98 -0
  144. package/dist/Resources.d.ts.map +1 -0
  145. package/dist/Resources.js +161 -0
  146. package/dist/Resources.js.map +1 -0
  147. package/dist/Rows.d.ts +4 -0
  148. package/dist/Rows.d.ts.map +1 -0
  149. package/dist/Rows.js +16 -0
  150. package/dist/Rows.js.map +1 -0
  151. package/dist/Runtime.d.ts +254 -0
  152. package/dist/Runtime.d.ts.map +1 -0
  153. package/dist/Runtime.js +1249 -0
  154. package/dist/Runtime.js.map +1 -0
  155. package/dist/RuntimeRuns.d.ts +74 -0
  156. package/dist/RuntimeRuns.d.ts.map +1 -0
  157. package/dist/RuntimeRuns.js +118 -0
  158. package/dist/RuntimeRuns.js.map +1 -0
  159. package/dist/ServicesSync.d.ts +286 -0
  160. package/dist/ServicesSync.d.ts.map +1 -0
  161. package/dist/ServicesSync.js +40 -0
  162. package/dist/ServicesSync.js.map +1 -0
  163. package/dist/Session.d.ts +226 -0
  164. package/dist/Session.d.ts.map +1 -0
  165. package/dist/Session.js +763 -0
  166. package/dist/Session.js.map +1 -0
  167. package/dist/ShareGrant.d.ts +47 -0
  168. package/dist/ShareGrant.d.ts.map +1 -0
  169. package/dist/ShareGrant.js +20 -0
  170. package/dist/ShareGrant.js.map +1 -0
  171. package/dist/Sharing.d.ts +203 -0
  172. package/dist/Sharing.d.ts.map +1 -0
  173. package/dist/Sharing.js +520 -0
  174. package/dist/Sharing.js.map +1 -0
  175. package/dist/Skew.d.ts +52 -0
  176. package/dist/Skew.d.ts.map +1 -0
  177. package/dist/Skew.js +77 -0
  178. package/dist/Skew.js.map +1 -0
  179. package/dist/SpacesSync.d.ts +247 -0
  180. package/dist/SpacesSync.d.ts.map +1 -0
  181. package/dist/SpacesSync.js +30 -0
  182. package/dist/SpacesSync.js.map +1 -0
  183. package/dist/Storage.d.ts +51 -0
  184. package/dist/Storage.d.ts.map +1 -0
  185. package/dist/Storage.js +107 -0
  186. package/dist/Storage.js.map +1 -0
  187. package/dist/Sync.d.ts +48 -0
  188. package/dist/Sync.d.ts.map +1 -0
  189. package/dist/Sync.js +48 -0
  190. package/dist/Sync.js.map +1 -0
  191. package/dist/SyncTables.d.ts +13 -0
  192. package/dist/SyncTables.d.ts.map +1 -0
  193. package/dist/SyncTables.js +13 -0
  194. package/dist/SyncTables.js.map +1 -0
  195. package/dist/Tab.d.ts +36 -0
  196. package/dist/Tab.d.ts.map +1 -0
  197. package/dist/Tab.js +44 -0
  198. package/dist/Tab.js.map +1 -0
  199. package/dist/Transport.d.ts +139 -0
  200. package/dist/Transport.d.ts.map +1 -0
  201. package/dist/Transport.js +232 -0
  202. package/dist/Transport.js.map +1 -0
  203. package/dist/Upload.d.ts +41 -0
  204. package/dist/Upload.d.ts.map +1 -0
  205. package/dist/Upload.js +93 -0
  206. package/dist/Upload.js.map +1 -0
  207. package/dist/WebMcp.d.ts +78 -0
  208. package/dist/WebMcp.d.ts.map +1 -0
  209. package/dist/WebMcp.js +204 -0
  210. package/dist/WebMcp.js.map +1 -0
  211. package/dist/index.d.ts +27 -0
  212. package/dist/index.d.ts.map +1 -0
  213. package/dist/index.js +27 -0
  214. package/dist/index.js.map +1 -0
  215. package/package.json +97 -3
  216. package/src/Account.ts +249 -0
  217. package/src/Agent.ts +387 -0
  218. package/src/AgentSync.ts +59 -0
  219. package/src/AppState.ts +222 -0
  220. package/src/AppStateSync.ts +26 -0
  221. package/src/Auth.ts +225 -0
  222. package/src/Avatars.ts +144 -0
  223. package/src/BrowserAnalytics.ts +133 -0
  224. package/src/Chat.ts +1150 -0
  225. package/src/ChatIntegrity.ts +130 -0
  226. package/src/ChatSends.ts +209 -0
  227. package/src/Client.ts +319 -0
  228. package/src/Collab.ts +524 -0
  229. package/src/CollabTools.ts +381 -0
  230. package/src/Connections.ts +517 -0
  231. package/src/Consent.ts +176 -0
  232. package/src/Desktop.ts +139 -0
  233. package/src/Directory.ts +71 -0
  234. package/src/ErrorReporter.ts +112 -0
  235. package/src/ExpoSqlite.ts +6 -0
  236. package/src/FileSync.ts +34 -0
  237. package/src/FileTables.gen.ts +23 -0
  238. package/src/Foldkit.ts +960 -0
  239. package/src/History.ts +337 -0
  240. package/src/InboxSync.ts +47 -0
  241. package/src/KernelTables.gen.ts +329 -0
  242. package/src/Make.ts +120 -0
  243. package/src/Models.ts +134 -0
  244. package/src/Optimistic.ts +364 -0
  245. package/src/PlatformSync.ts +156 -0
  246. package/src/Poll.ts +227 -0
  247. package/src/Preferences.ts +42 -0
  248. package/src/Proposals.ts +57 -0
  249. package/src/React.ts +26 -0
  250. package/src/Reader.ts +180 -0
  251. package/src/Resources.ts +257 -0
  252. package/src/Rows.ts +16 -0
  253. package/src/Runtime.ts +1409 -0
  254. package/src/RuntimeRuns.ts +180 -0
  255. package/src/ServicesSync.ts +58 -0
  256. package/src/Session.ts +814 -0
  257. package/src/ShareGrant.ts +20 -0
  258. package/src/Sharing.ts +696 -0
  259. package/src/Skew.ts +97 -0
  260. package/src/SpacesSync.ts +61 -0
  261. package/src/Storage.ts +167 -0
  262. package/src/Sync.ts +125 -0
  263. package/src/SyncTables.ts +12 -0
  264. package/src/Tab.ts +59 -0
  265. package/src/Transport.ts +321 -0
  266. package/src/Upload.ts +125 -0
  267. package/src/WebMcp.ts +279 -0
  268. package/src/index.ts +26 -0
  269. package/src/web-globals.d.ts +103 -0
package/src/Poll.ts ADDED
@@ -0,0 +1,227 @@
1
+ /**
2
+ * Polling and status probes, runtime-neutral (timers, `fetch` and `AbortController` only): a host that knows
3
+ * whether it is visible passes a `Visibility` (`@eloxiv/shell-core/web`'s `webVisibility()` in a browser).
4
+ *
5
+ * - `poll`: one attempt at a time, each abortable and bounded by a timeout, on an interval; paused or slowed while
6
+ * hidden; `now()` polls at once (or right after the attempt in flight).
7
+ * - `makeProbe`: a status read shared by everyone who asks: one request in flight at a time, its answer kept for a
8
+ * while, and "the backend could not be reached" (`unavailable`) kept apart from what the backend answered.
9
+ * - `sessionProbe` and `engineProbe`: the person's session (signed in, signed out) and the kernel's readiness, as
10
+ * probes, so a network failure is never taken for a sign-out.
11
+ */
12
+ import { fetchSignal, type SignalLike } from "./Transport.ts"
13
+
14
+ /** Whether the host is visible, and a way to hear when that changes. */
15
+ export interface Visibility {
16
+ readonly hidden: () => boolean
17
+ /** Calls `listener` on every change; returns the unsubscribe. */
18
+ readonly subscribe: (listener: () => void) => () => void
19
+ }
20
+
21
+ export interface PollOptions<A> {
22
+ /** Between the end of one attempt and the start of the next (ms). */
23
+ readonly intervalMs: number
24
+ /** While hidden: `"pause"` (the default: no attempts) or a slower interval (ms). */
25
+ readonly hiddenIntervalMs?: number | "pause" | undefined
26
+ /** An attempt still running after this long is aborted and reported as a `Timeout` error (default 30 000). */
27
+ readonly timeoutMs?: number | undefined
28
+ /** Start with an attempt at once (default true), rather than after the first interval. */
29
+ readonly immediate?: boolean | undefined
30
+ readonly visibility?: Visibility | undefined
31
+ readonly onResult?: ((result: A) => void) | undefined
32
+ readonly onError?: ((error: unknown) => void) | undefined
33
+ }
34
+
35
+ /** A poller's handle. */
36
+ export interface Poller {
37
+ /** Poll now; with an attempt in flight, poll again as soon as it ends (never two at once). */
38
+ readonly now: () => void
39
+ /** Stop: the attempt in flight is aborted and nothing more runs. */
40
+ readonly stop: () => void
41
+ }
42
+
43
+ export class PollTimeout extends Error {
44
+ override readonly name = "PollTimeout"
45
+ readonly _tag = "Timeout"
46
+ }
47
+
48
+ export const poll = <A>(attempt: (signal: SignalLike) => Promise<A>, options: PollOptions<A>): Poller => {
49
+ let stopped = false
50
+ let running: AbortController | undefined
51
+ let again = false
52
+ let timer: ReturnType<typeof setTimeout> | undefined
53
+ const hidden = () => options.visibility?.hidden() === true
54
+ const interval = (): number | undefined => {
55
+ if (!hidden()) return options.intervalMs
56
+ const slow = options.hiddenIntervalMs ?? "pause"
57
+ return slow === "pause" ? undefined : slow
58
+ }
59
+ const schedule = (ms: number | undefined) => {
60
+ if (timer !== undefined) clearTimeout(timer)
61
+ timer = undefined
62
+ if (stopped || ms === undefined) return
63
+ timer = setTimeout(run, ms)
64
+ }
65
+ function run() {
66
+ timer = undefined
67
+ if (stopped) return
68
+ if (running !== undefined) {
69
+ again = true
70
+ return
71
+ }
72
+ const controller = new AbortController()
73
+ running = controller
74
+ let timedOut = false
75
+ const deadline = setTimeout(() => {
76
+ timedOut = true
77
+ controller.abort()
78
+ }, options.timeoutMs ?? 30_000)
79
+ void (async () => {
80
+ let outcome: { readonly ok: true; readonly result: A } | { readonly ok: false; readonly error: unknown }
81
+ try {
82
+ outcome = { ok: true, result: await attempt(controller.signal as unknown as SignalLike) }
83
+ } catch (error) {
84
+ outcome = { ok: false, error }
85
+ }
86
+ clearTimeout(deadline)
87
+ running = undefined
88
+ if (stopped) return
89
+ if (outcome.ok) options.onResult?.(outcome.result)
90
+ else
91
+ options.onError?.(
92
+ timedOut ? new PollTimeout(`The attempt took longer than ${options.timeoutMs ?? 30_000} ms`) : outcome.error,
93
+ )
94
+ next()
95
+ })()
96
+ }
97
+ const next = () => {
98
+ if (again) {
99
+ again = false
100
+ schedule(hidden() && interval() === undefined ? undefined : 0)
101
+ } else schedule(interval())
102
+ }
103
+ // Becoming visible polls at once; becoming hidden reschedules at the hidden pace (or pauses).
104
+ const unsubscribe = options.visibility?.subscribe(() => {
105
+ if (running !== undefined) return
106
+ schedule(hidden() ? interval() : 0)
107
+ })
108
+ schedule(options.immediate === false ? interval() : hidden() ? interval() : 0)
109
+ return {
110
+ now: () => {
111
+ if (stopped) return
112
+ if (running !== undefined) again = true
113
+ else schedule(0)
114
+ },
115
+ stop: () => {
116
+ stopped = true
117
+ if (timer !== undefined) clearTimeout(timer)
118
+ running?.abort()
119
+ unsubscribe?.()
120
+ },
121
+ }
122
+ }
123
+
124
+ /** What a probe found: the backend's answer, or that it could not be had (and why). */
125
+ export type Probed<A> =
126
+ | { readonly status: "available"; readonly value: A; readonly at: number }
127
+ | { readonly status: "unavailable"; readonly reason: string; readonly at: number }
128
+
129
+ export interface ProbeOptions {
130
+ /** How long an answer is kept (ms, default 5 000). */
131
+ readonly ttlMs?: number | undefined
132
+ /** How long "unavailable" is kept (ms, default 1 000): sooner asked again. */
133
+ readonly unavailableTtlMs?: number | undefined
134
+ /** A probe still running after this long is aborted, and found unavailable (ms, default 10 000). */
135
+ readonly timeoutMs?: number | undefined
136
+ readonly now?: (() => number) | undefined
137
+ }
138
+
139
+ /**
140
+ * A status read shared by its callers: `get()` returns the kept answer while it is fresh, else joins the request in
141
+ * flight, else makes one. `load` resolving is `available` with its value; `load` throwing or timing out is
142
+ * `unavailable` with the reason, never a value.
143
+ */
144
+ export const makeProbe = <A>(load: (signal: SignalLike) => Promise<A>, options: ProbeOptions = {}) => {
145
+ const now = options.now ?? Date.now
146
+ let kept: Probed<A> | undefined
147
+ let inFlight: Promise<Probed<A>> | undefined
148
+ let generation = 0
149
+ const fresh = (probed: Probed<A>) =>
150
+ now() - probed.at < (probed.status === "available" ? (options.ttlMs ?? 5_000) : (options.unavailableTtlMs ?? 1_000))
151
+ return {
152
+ get: (): Promise<Probed<A>> => {
153
+ if (kept !== undefined && fresh(kept)) return Promise.resolve(kept)
154
+ if (inFlight !== undefined) return inFlight
155
+ const mine = generation
156
+ const controller = new AbortController()
157
+ const timeoutMs = options.timeoutMs ?? 10_000
158
+ const deadline = setTimeout(() => controller.abort(), timeoutMs)
159
+ const request = load(controller.signal as unknown as SignalLike).then(
160
+ (value): Probed<A> => ({ status: "available", value, at: now() }),
161
+ (error: unknown): Probed<A> => ({
162
+ status: "unavailable",
163
+ reason: controller.signal.aborted ? `No answer within ${timeoutMs} ms` : String(error),
164
+ at: now(),
165
+ }),
166
+ )
167
+ const settled = request.then((probed) => {
168
+ clearTimeout(deadline)
169
+ if (mine === generation) {
170
+ kept = probed
171
+ inFlight = undefined
172
+ }
173
+ return probed
174
+ })
175
+ inFlight = settled
176
+ return settled
177
+ },
178
+ /** Forget the kept answer (after a sign-in or sign-out): the next `get` asks again. */
179
+ invalidate: () => {
180
+ generation += 1
181
+ kept = undefined
182
+ inFlight = undefined
183
+ },
184
+ }
185
+ }
186
+ export type Probe<A> = ReturnType<typeof makeProbe<A>>
187
+
188
+ /** The person's session as the kernel sees it. */
189
+ export type ProbedSession =
190
+ | { readonly signedIn: true; readonly user: { readonly id: string; readonly email: string; readonly name: string } }
191
+ | { readonly signedIn: false }
192
+
193
+ /**
194
+ * The session `token` names, as a probe (Better Auth's `GET /auth/get-session`): `available` with `signedIn: true`
195
+ * and the user, or `signedIn: false` when the kernel says there is no such session (a 401, or no session in its
196
+ * answer); `unavailable` when the kernel could not be reached or failed, which is not a sign-out.
197
+ */
198
+ export const sessionProbe = (baseUrl: string, token: () => string | undefined, options?: ProbeOptions) =>
199
+ makeProbe<ProbedSession>(async (signal) => {
200
+ const bearer = token()
201
+ if (bearer === undefined) return { signedIn: false }
202
+ const response = await fetch(`${baseUrl}/auth/get-session`, {
203
+ headers: { authorization: `Bearer ${bearer}` },
204
+ signal: fetchSignal(signal),
205
+ })
206
+ if (response.status === 401) return { signedIn: false }
207
+ if (!response.ok) throw new Error(`/auth/get-session answered ${response.status}`)
208
+ const body = (await response.json()) as { readonly user?: { id: string; email: string; name: string } } | null
209
+ return body?.user === undefined ? { signedIn: false } : { signedIn: true, user: body.user }
210
+ }, options)
211
+
212
+ /** The kernel's readiness (`GET /ready`): every check with its verdict. */
213
+ export interface EngineState {
214
+ readonly status: "ready" | "degraded" | "not-ready"
215
+ readonly checks?: ReadonlyArray<{ readonly name: string; readonly status: string; readonly reason?: string }>
216
+ }
217
+
218
+ /**
219
+ * The kernel's readiness as a probe: `available` with its report (ready, degraded or not ready: the kernel
220
+ * answered), `unavailable` when it could not be reached.
221
+ */
222
+ export const engineProbe = (baseUrl: string, options?: ProbeOptions) =>
223
+ makeProbe<EngineState>(async (signal) => {
224
+ const response = await fetch(`${baseUrl}/ready`, { signal: fetchSignal(signal) })
225
+ if (response.status !== 200 && response.status !== 503) throw new Error(`/ready answered ${response.status}`)
226
+ return (await response.json()) as EngineState
227
+ }, options)
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Each person's preferences (the Settings contract's `PREFERENCE_SETTINGS`: language, time zone, theme), read from
3
+ * their replica as the kernel resolves them (their own value, else their organisation's, else the default) and saved
4
+ * as their own value through `settings.set`, so every device of theirs, the agent and their schedules see the same.
5
+ */
6
+ import { PREFERENCE_DECLARATIONS, PREFERENCE_SETTINGS, SETTINGS_ACTIONS } from "@eloxiv/contracts"
7
+ import { settingFromReplica } from "./PlatformSync.ts"
8
+ import { type Circuit, httpAction, makeCircuit, type TransportOptions } from "./Transport.ts"
9
+
10
+ export interface Preferences {
11
+ readonly locale: string | null
12
+ readonly timeZone: string | null
13
+ readonly theme: "system" | "light" | "dark"
14
+ }
15
+
16
+ type Rows = ReadonlyArray<{ readonly level: string; readonly value?: unknown }>
17
+
18
+ /** The preferences from the replica's rows of each key (`settings.value` with that key). */
19
+ export const preferencesFromReplica = (rows: (key: string) => Rows): Preferences => {
20
+ const read = (key: keyof typeof PREFERENCE_DECLARATIONS) =>
21
+ settingFromReplica(PREFERENCE_DECLARATIONS[key], rows(key)).value
22
+ return {
23
+ locale: read(PREFERENCE_SETTINGS.locale) as string | null,
24
+ timeZone: read(PREFERENCE_SETTINGS.timeZone) as string | null,
25
+ theme: read(PREFERENCE_SETTINGS.theme) as Preferences["theme"],
26
+ }
27
+ }
28
+
29
+ /** Save one preference as the person's own value (`null` for the locale or time zone: the browser's or device's). */
30
+ export const savePreference = <K extends keyof Preferences>(
31
+ options: TransportOptions,
32
+ key: K,
33
+ value: Preferences[K],
34
+ circuit: Circuit = options.circuit ?? makeCircuit(),
35
+ ) => httpAction(options, circuit, SETTINGS_ACTIONS.set, { key: PREFERENCE_SETTINGS[key], level: "user", value })
36
+
37
+ /** Drop the person's own value: they get their organisation's, else the default. */
38
+ export const clearPreference = (
39
+ options: TransportOptions,
40
+ key: keyof Preferences,
41
+ circuit: Circuit = options.circuit ?? makeCircuit(),
42
+ ) => httpAction(options, circuit, SETTINGS_ACTIONS.clear, { key: PREFERENCE_SETTINGS[key], level: "user" })
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Applying an accepted proposal item (the Approvals contract, "Proposals"): the decider makes the item's call (its
3
+ * action with its input) under the item's apply key, through the one invocation path as themselves, then tells the
4
+ * kernel (`proposals.applied`), which records it only once it finds that call's committed receipt. A retry after a
5
+ * lost answer replays the call's receipt instead of running it again. Web-standard `fetch` only.
6
+ */
7
+ import type { ProposalItem } from "@eloxiv/contracts"
8
+ import { CLIENT_VERSION_HEADER, IDEMPOTENCY_HEADER, PROPOSALS_ACTIONS } from "@eloxiv/contracts"
9
+
10
+ export interface ProposalClientOptions {
11
+ readonly baseUrl: string
12
+ readonly token: () => string | undefined
13
+ readonly orgId: string
14
+ readonly clientVersion?: string | undefined
15
+ }
16
+
17
+ /** A refused or failed request: the HTTP status and the kernel's error. */
18
+ export class ProposalRequestError extends Error {
19
+ override readonly name = "ProposalRequestError"
20
+ readonly status: number
21
+ readonly error: { readonly _tag: string; readonly [field: string]: unknown }
22
+ constructor(status: number, error: { readonly _tag: string; readonly [field: string]: unknown }) {
23
+ super(`${error._tag}: ${typeof error["message"] === "string" ? error["message"] : ""}`)
24
+ this.status = status
25
+ this.error = error
26
+ }
27
+ }
28
+
29
+ const post = async (options: ProposalClientOptions, action: string, input: unknown, key?: string) => {
30
+ const headers: Record<string, string> = { "content-type": "application/json", "x-eloxiv-org": options.orgId }
31
+ const token = options.token()
32
+ if (token !== undefined) headers["authorization"] = `Bearer ${token}`
33
+ if (key !== undefined) headers[IDEMPOTENCY_HEADER] = key
34
+ if (options.clientVersion !== undefined) headers[CLIENT_VERSION_HEADER] = options.clientVersion
35
+ const response = await fetch(`${options.baseUrl}/api/actions/${action}`, {
36
+ method: "POST",
37
+ headers,
38
+ body: JSON.stringify(input),
39
+ })
40
+ const body = (await response.json().catch(() => ({}))) as Record<string, unknown>
41
+ if (!response.ok) {
42
+ throw new ProposalRequestError(response.status, {
43
+ ...body,
44
+ _tag: typeof body["_tag"] === "string" ? body["_tag"] : `HTTP ${response.status}`,
45
+ })
46
+ }
47
+ return body
48
+ }
49
+
50
+ /** Apply an item you accepted: its call, under its key, then `proposals.applied`. The proposal as it now stands. */
51
+ export const applyProposalItem = async (
52
+ options: ProposalClientOptions,
53
+ item: Pick<ProposalItem, "id" | "action" | "input" | "applyKey">,
54
+ ) => {
55
+ await post(options, item.action, item.input, item.applyKey)
56
+ return (await post(options, PROPOSALS_ACTIONS.applied, { item: item.id }))["output"]
57
+ }
package/src/React.ts ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * React bindings for the replica (`@eloxiv/client/react`), so UI reaches sync only through Eloxiv's client
3
+ * (decision 9). They are Zero's own, re-exported (one React context: the provider and the hooks are the same
4
+ * module objects Zero's are). The headless SDK (`@eloxiv/client`) does not load React; this entry needs React 19
5
+ * in the app.
6
+ *
7
+ * @deprecated It served the React shell, retired at its last published version (`shell` 0.4.0; decision 10: the
8
+ * shell is Foldkit, through `@eloxiv/client/foldkit`). It stays so an app still on that version keeps building;
9
+ * nothing on the default path loads it.
10
+ *
11
+ * ```tsx
12
+ * <ZeroProvider zero={connectSync({ schema, ... })}>...</ZeroProvider>
13
+ * const [greetings, result] = useQuery(queries.hello.greetings())
14
+ * ```
15
+ */
16
+ export {
17
+ useConnectionState,
18
+ useQuery,
19
+ useSuspenseQuery,
20
+ useZero,
21
+ ZeroProvider,
22
+ type MaybeQueryResult,
23
+ type QueryResult,
24
+ type UseQueryOptions,
25
+ type ZeroProviderProps,
26
+ } from "@rocicorp/zero/react"
package/src/Reader.ts ADDED
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Read-only action calls coalesced into read batches (`POST /api/batch`, the kernel's ReadBatchRequest): reads
3
+ * made within one window, acting as the same person in the same organisation, go out as one request; the same
4
+ * read twice in a batch is sent once and answers both. Each item is still its own call on the kernel (its own
5
+ * policy, audit and failure). Under the transport's rules (`Transport.ts`): a disabled backend or an open circuit
6
+ * refuses at once, a failed batch is retried only when nothing definitive came back, and a refused credential is
7
+ * not used again: once a read with a token is answered 401, every read with that token is refused without being
8
+ * sent, until the token changes (no request storm after a sign-out elsewhere).
9
+ */
10
+ import { READ_BATCH_MAX_ITEMS, READ_BATCH_PATH, type ReadBatchItemResult } from "@eloxiv/contracts"
11
+ import {
12
+ backendStatus,
13
+ type Circuit,
14
+ makeCircuit,
15
+ RequestError,
16
+ type SignalLike,
17
+ sendJson,
18
+ type TransportOptions,
19
+ } from "./Transport.ts"
20
+
21
+ export interface ReaderOptions extends TransportOptions {
22
+ /** How long reads gather before their batch goes out (ms, default 0: those made in the same turn). */
23
+ readonly windowMs?: number | undefined
24
+ /** The most distinct reads in one batch (default and at most the kernel's 25). */
25
+ readonly maxItems?: number | undefined
26
+ /** Tries of a failed batch after the first, when nothing definitive came back (default 2). */
27
+ readonly retries?: number | undefined
28
+ readonly retryBaseMs?: number | undefined
29
+ /** Give up on a batch after this long (ms, default 30 000). */
30
+ readonly timeoutMs?: number | undefined
31
+ }
32
+
33
+ interface Waiter {
34
+ readonly resolve: (result: unknown) => void
35
+ readonly reject: (error: RequestError) => void
36
+ readonly signal: SignalLike | undefined
37
+ readonly onAbort: () => void
38
+ }
39
+
40
+ interface Item {
41
+ readonly action: string
42
+ readonly input: unknown
43
+ readonly waiters: Array<Waiter>
44
+ }
45
+
46
+ interface Batch {
47
+ readonly token: string | undefined
48
+ readonly orgId: string | undefined
49
+ readonly items: Map<string, Item>
50
+ timer: ReturnType<typeof setTimeout> | undefined
51
+ }
52
+
53
+ const aborted = () => new RequestError(0, { _tag: "Aborted", message: "aborted" })
54
+
55
+ export const makeReader = (options: ReaderOptions, circuit: Circuit = options.circuit ?? makeCircuit()) => {
56
+ const maxItems = Math.min(Math.max(1, options.maxItems ?? READ_BATCH_MAX_ITEMS), READ_BATCH_MAX_ITEMS)
57
+ const batches = new Map<string, Batch>()
58
+ /** The token last answered 401: never sent again. */
59
+ let refusedToken: string | undefined
60
+ let refusal: RequestError | undefined
61
+
62
+ const settle = (item: Item, outcome: { ok: true; result: unknown } | { ok: false; error: RequestError }) => {
63
+ for (const waiter of item.waiters) {
64
+ waiter.signal?.removeEventListener("abort", waiter.onAbort)
65
+ if (outcome.ok) waiter.resolve(outcome.result)
66
+ else waiter.reject(outcome.error)
67
+ }
68
+ item.waiters.length = 0
69
+ }
70
+
71
+ const send = async (batch: Batch) => {
72
+ if (batch.timer !== undefined) clearTimeout(batch.timer)
73
+ const items = [...batch.items.values()].filter((item) => item.waiters.length > 0)
74
+ if (items.length === 0) return
75
+ const fail = (error: RequestError) => {
76
+ if (error.status === 401 && batch.token !== undefined) {
77
+ refusedToken = batch.token
78
+ refusal = error
79
+ }
80
+ for (const item of items) settle(item, { ok: false, error })
81
+ }
82
+ try {
83
+ const answer = (await sendJson(
84
+ {
85
+ ...options,
86
+ // The batch acts as its reads were made: the person and organisation read when they were queued.
87
+ token: () => batch.token,
88
+ orgId: batch.orgId,
89
+ },
90
+ circuit,
91
+ READ_BATCH_PATH,
92
+ { items: items.map((item) => ({ action: item.action, input: item.input })) },
93
+ { retries: options.retries ?? 2, retryBaseMs: options.retryBaseMs, timeoutMs: options.timeoutMs ?? 30_000 },
94
+ )) as { readonly results?: ReadonlyArray<ReadBatchItemResult> }
95
+ const results = answer.results ?? []
96
+ items.forEach((item, index) => {
97
+ const result = results[index]
98
+ if (result === undefined) {
99
+ settle(item, { ok: false, error: new RequestError(0, { _tag: "NetworkError", message: "No answer" }) })
100
+ } else if (result.ok) {
101
+ settle(item, { ok: true, result: result.result })
102
+ } else {
103
+ const error = new RequestError(result.status, result.error)
104
+ if (result.status === 401 && batch.token !== undefined) {
105
+ refusedToken = batch.token
106
+ refusal = error
107
+ }
108
+ settle(item, { ok: false, error })
109
+ }
110
+ })
111
+ } catch (error) {
112
+ fail(
113
+ error instanceof RequestError ? error : new RequestError(0, { _tag: "NetworkError", message: String(error) }),
114
+ )
115
+ }
116
+ }
117
+
118
+ return {
119
+ /**
120
+ * A read-only action's result envelope (`{ kind: "output", output }`), read in the next batch. Rejects with
121
+ * `RequestError`: the item's own refusal (`Forbidden`, `InvalidInput`, ... with its status), the batch's failure,
122
+ * or the transport's (`BackendDisabled`, `BackendUnavailable`, `Aborted`). Aborting `signal` drops this read
123
+ * only; the batch still answers the others.
124
+ */
125
+ read: (action: string, input: unknown, request: { readonly signal?: SignalLike | undefined } = {}) =>
126
+ new Promise<unknown>((resolve, reject) => {
127
+ const status = backendStatus(options, circuit)
128
+ if (status.state === "disabled") {
129
+ return reject(new RequestError(0, { _tag: "BackendDisabled", message: status.reason }))
130
+ }
131
+ if (status.state === "unavailable" && circuit.isOpen()) {
132
+ return reject(
133
+ new RequestError(0, { _tag: "BackendUnavailable", message: status.reason, retryAt: status.retryAt }),
134
+ )
135
+ }
136
+ const token = options.token?.()
137
+ if (token !== undefined && token === refusedToken && refusal !== undefined) return reject(refusal)
138
+ if (request.signal?.aborted === true) return reject(aborted())
139
+ const orgId = typeof options.orgId === "function" ? options.orgId() : options.orgId
140
+ const batchKey = JSON.stringify([token ?? null, orgId ?? null])
141
+ let batch = batches.get(batchKey)
142
+ if (batch === undefined) {
143
+ const created: Batch = { token, orgId, items: new Map(), timer: undefined }
144
+ created.timer = setTimeout(() => {
145
+ if (batches.get(batchKey) === created) batches.delete(batchKey)
146
+ void send(created)
147
+ }, options.windowMs ?? 0)
148
+ batches.set(batchKey, created)
149
+ batch = created
150
+ }
151
+ const itemKey = JSON.stringify([action, input ?? null])
152
+ let item = batch.items.get(itemKey)
153
+ if (item === undefined) {
154
+ item = { action, input, waiters: [] }
155
+ batch.items.set(itemKey, item)
156
+ }
157
+ const owner = item
158
+ const waiter: Waiter = {
159
+ resolve,
160
+ reject,
161
+ signal: request.signal,
162
+ onAbort: () => {
163
+ const index = owner.waiters.indexOf(waiter)
164
+ if (index >= 0) owner.waiters.splice(index, 1)
165
+ reject(aborted())
166
+ },
167
+ }
168
+ request.signal?.addEventListener("abort", waiter.onAbort, { once: true })
169
+ owner.waiters.push(waiter)
170
+ if (batch.items.size >= maxItems) {
171
+ batches.delete(batchKey)
172
+ void send(batch)
173
+ }
174
+ }),
175
+ /** The backend's status as this reader sees it (disabled, its circuit's). */
176
+ status: () => backendStatus(options, circuit),
177
+ circuit,
178
+ }
179
+ }
180
+ export type Reader = ReturnType<typeof makeReader>