@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/Runtime.ts ADDED
@@ -0,0 +1,1409 @@
1
+ /**
2
+ * The client core (decision 14): one portable, framework-free runtime that owns the guarantees every client needs
3
+ * and none should implement twice. It holds the person's session (the shared `sessionController`), the selected
4
+ * organisation with a **generation**, the replica of `{ person, organisation, session }` (`connectSync`, its storage
5
+ * injected), live named queries (`materialize` and listeners, snapshots copied out and tagged with their
6
+ * generation), optimistic writes (the app's generated mutators through `write`: predicted, then confirmed, rejected
7
+ * after the rollback, or not confirmed), non-optimistic action calls (`makeClient`), and teardown: an organisation
8
+ * change, a sign-out or `needs-auth` destroys every view and closes the replica before anything of the next context
9
+ * is emitted, and late results of an older generation are dropped.
10
+ *
11
+ * Its events are the LocalClient contract's (`Event`, without the per-stream `seq`), so the daemon serves it as
12
+ * LocalClient v1 unchanged; an in-process client (a JavaScript host) can listen to it directly. Runs wherever the
13
+ * root SDK runs: no DOM, no Node built-ins (the portable rule pack covers it).
14
+ *
15
+ * const runtime = makeClientRuntime({ kernelUrl, zeroUrl, schema, queries, mutators, modules, sessionStore })
16
+ * runtime.onEvent((event) => ...)
17
+ * await runtime.start()
18
+ * const { id } = await runtime.subscribe({ query: "hello.greetings" }, "window-1")
19
+ * await runtime.write({ mutator: "hello.greet", input: { message: "Hi", visibility: "org" } }, "window-1")
20
+ */
21
+ import {
22
+ ActionFailed,
23
+ actionRegistry,
24
+ actionResult,
25
+ CLIENT_VERSION_HEADER,
26
+ Forbidden,
27
+ IDEMPOTENCY_HEADER,
28
+ InvalidInput,
29
+ InvocationError,
30
+ MAKE_ACTIONS_PATH,
31
+ MAKE_MODULE_PREFIX,
32
+ NotSignedIn,
33
+ SignInFailed,
34
+ StaleGeneration,
35
+ UnknownMutator,
36
+ UnknownQuery,
37
+ UnknownSubscription,
38
+ type AnyModuleContract,
39
+ type EngineReadiness,
40
+ type LocalClientEvent,
41
+ type LocalClientSessionState,
42
+ } from "@eloxiv/contracts"
43
+ import { Exit, Schema } from "effect"
44
+ import { changePassword as changeAccountPassword, type verifyTwoFactor } from "./Account.ts"
45
+ import { AuthError, listOrganizations, signOut as revokeSession, type OrganizationMembership } from "./Auth.ts"
46
+ import { makeClient } from "./Client.ts"
47
+ import { copyRows } from "./Rows.ts"
48
+ import { beginDesktopSignIn, completeDesktopSignIn, type DesktopSignIn } from "./Desktop.ts"
49
+ import { runErrorOf, runFollower } from "./RuntimeRuns.ts"
50
+ import { write as optimisticWrite, WriteNotConfirmed } from "./Optimistic.ts"
51
+ import {
52
+ sessionController,
53
+ type RememberedContext,
54
+ type RevocationStatus,
55
+ type RevocationStore,
56
+ type SessionState,
57
+ type SessionStore,
58
+ } from "./Session.ts"
59
+ import { connectSync, ORG_HEADER, type SyncClient, type SyncSchema, type SyncStorage } from "./Sync.ts"
60
+
61
+ /** A LocalClient event without its stream's `seq`, and the client it is for (`undefined`: every client). */
62
+ export type RuntimeEvent = (LocalClientEvent extends infer E ? (E extends unknown ? Omit<E, "seq"> : never) : never) & {
63
+ readonly owner?: string | undefined
64
+ }
65
+
66
+ export interface ClientRuntimeOptions<S extends SyncSchema = SyncSchema> {
67
+ /** The kernel's base URL (`http://localhost:4100`). */
68
+ readonly kernelUrl: string
69
+ /** zero-cache's URL (`http://localhost:4848`). */
70
+ readonly zeroUrl: string
71
+ /** The app's sync schema, named queries and mutators (`eloxiv.sync.ts`). */
72
+ readonly schema: S
73
+ readonly queries: object
74
+ readonly mutators?: object | undefined
75
+ /** The app's module contracts (`eloxiv.modules.ts`): its typed actions. */
76
+ readonly modules: ReadonlyArray<AnyModuleContract>
77
+ /** Where the person's session token is kept between launches (the daemon's secret store). */
78
+ readonly sessionStore: SessionStore
79
+ /** Replica storage (default memory): one store per person and organisation (`sqliteStorage` on desktop). */
80
+ readonly storage?: SyncStorage | undefined
81
+ /** The app build's version, sent with calls and writes. */
82
+ readonly clientVersion?: string | undefined
83
+ /** Retries of the session's checks and revocation (`sessionController`). */
84
+ readonly retry?: { readonly attempts?: number; readonly baseMs?: number } | undefined
85
+ /** How often to check a session the kernel could not be reached to check (ms, default 5 s). */
86
+ readonly recheckMs?: number | undefined
87
+ /**
88
+ * How long the launch's check of a stored session with a remembered context waits before the remembered replica is
89
+ * opened offline (ms, default 3 s; `sessionController`'s `offlineProbeMs`). The check goes on in the background.
90
+ * The same deadline bounds the listing of that session's organisations once the kernel accepted it: unanswered by
91
+ * then, the remembered organisation opens, and the listing reconciles it when it comes.
92
+ */
93
+ readonly offlineProbeMs?: number | undefined
94
+ readonly log?: ((line: string) => void) | undefined
95
+ /** How a followed run's event stream reconnects to the kernel (ms; the chat SDK's default 500, doubling to 10 000). */
96
+ readonly runReconnect?: { readonly base: number; readonly max: number } | undefined
97
+ /**
98
+ * A durable sign-out (a browser's storage, `sessionController`'s `revocations`): a sign-out keeps its revocation
99
+ * here before the person is signed out, and pending ones are retried at start, every `revocationRetryMs` (15 s)
100
+ * and on `retryRevocations`, each attempt waiting `revocationTimeoutMs` (10 s), until the kernel confirms them.
101
+ */
102
+ readonly revocations?: RevocationStore | undefined
103
+ readonly revocationTimeoutMs?: number | undefined
104
+ readonly revocationRetryMs?: number | undefined
105
+ /**
106
+ * Which organisation a newly adopted session starts in (default: `previous`, the organisation selected before when
107
+ * the same person's session is adopted again, while they still belong to it; else their first).
108
+ */
109
+ readonly initialOrg?: ((context: InitialOrgContext) => string | null) | undefined
110
+ }
111
+
112
+ /** What `initialOrg` chooses from: the person, their organisations, and the one selected before (same person). */
113
+ export interface InitialOrgContext {
114
+ readonly user: { readonly id: string; readonly email: string; readonly name: string }
115
+ readonly organizations: ReadonlyArray<OrganizationMembership>
116
+ readonly previous: string | null
117
+ }
118
+
119
+ type Listener = (rows: unknown, status: string, error?: unknown) => void
120
+ interface View {
121
+ addListener(listener: Listener): () => void
122
+ destroy(): void
123
+ }
124
+
125
+ interface Subscription {
126
+ readonly id: string
127
+ readonly owner: string
128
+ readonly generation: number
129
+ readonly view: View
130
+ }
131
+
132
+ interface OpenReplica {
133
+ readonly zero: SyncClient
134
+ readonly generation: number
135
+ readonly stop: () => void
136
+ }
137
+
138
+ /** Every callable leaf of a query or mutator registry, by its dotted name. */
139
+ const leaves = (registry: object, field: "queryName" | "mutatorName"): Map<string, (args?: unknown) => unknown> => {
140
+ const found = new Map<string, (args?: unknown) => unknown>()
141
+ const walk = (node: unknown, path: ReadonlyArray<string>) => {
142
+ if (node === null || (typeof node !== "object" && typeof node !== "function")) return
143
+ const named = (node as Record<string, unknown>)[field]
144
+ if (typeof node === "function" && typeof named === "string") {
145
+ found.set(named, node as (args?: unknown) => unknown)
146
+ return
147
+ }
148
+ for (const [key, child] of Object.entries(node)) {
149
+ if (key === "~") continue
150
+ walk(child, [...path, key])
151
+ }
152
+ }
153
+ walk(registry, [])
154
+ return found
155
+ }
156
+
157
+ const errorText = (error: unknown): string => {
158
+ if (error instanceof Error) return error.message
159
+ const message = (error as { readonly message?: unknown } | undefined)?.message
160
+ return typeof message === "string" ? message : JSON.stringify(error)
161
+ }
162
+
163
+ const encodeInvocationError = Schema.encodeUnknownSync(InvocationError)
164
+ const decodeInvocationError = Schema.decodeUnknownExit(InvocationError)
165
+
166
+ /** The kernel's typed error, as it travels (`{ _tag, message, ... }`), or `ActionFailed` for anything else. */
167
+ export const invocationErrorOf = (action: string, error: unknown): InvocationError => {
168
+ const decoded = decodeInvocationError(
169
+ typeof error === "object" && error !== null && "_tag" in error ? safeEncode(error) : error,
170
+ )
171
+ return Exit.isSuccess(decoded) ? decoded.value : new ActionFailed({ action, message: errorText(error) })
172
+ }
173
+ /** A failed query's cause: the kernel's typed error a sync server's refusal carries (`details`), else the error. */
174
+ const queryErrorOf = (error: unknown): unknown => {
175
+ const details = (error as { readonly details?: unknown } | undefined)?.details
176
+ return typeof details === "object" && details !== null && "_tag" in details ? details : error
177
+ }
178
+ const safeEncode = (error: object): unknown => {
179
+ try {
180
+ return encodeInvocationError(error)
181
+ } catch {
182
+ return { ...error }
183
+ }
184
+ }
185
+
186
+ /** Web Crypto, read from `globalThis` (the root SDK declares no DOM types). */
187
+ const webCrypto = (globalThis as { readonly crypto?: { randomUUID?: () => string } }).crypto
188
+ const randomId = () =>
189
+ typeof webCrypto?.randomUUID === "function"
190
+ ? webCrypto.randomUUID()
191
+ : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
192
+
193
+ const CONNECTION: Record<string, "connecting" | "connected" | "disconnected" | "needsAuth"> = {
194
+ initializing: "connecting",
195
+ connecting: "connecting",
196
+ connected: "connected",
197
+ disconnected: "disconnected",
198
+ error: "disconnected",
199
+ closed: "disconnected",
200
+ "needs-auth": "needsAuth",
201
+ }
202
+
203
+ export const makeClientRuntime = <const S extends SyncSchema>(options: ClientRuntimeOptions<S>) => {
204
+ const log = options.log ?? (() => undefined)
205
+ const controller = sessionController({
206
+ baseUrl: options.kernelUrl,
207
+ store: options.sessionStore,
208
+ retry: options.retry,
209
+ revocations: options.revocations,
210
+ revocationTimeoutMs: options.revocationTimeoutMs,
211
+ offlineProbeMs: options.offlineProbeMs,
212
+ })
213
+ const queries = leaves(options.queries, "queryName")
214
+ const mutators = leaves(options.mutators ?? {}, "mutatorName")
215
+ const registry = actionRegistry(options.modules)
216
+ const listeners = new Set<(event: RuntimeEvent) => void>()
217
+
218
+ let generation = 0
219
+ let orgId: string | null = null
220
+ let organizations: ReadonlyArray<OrganizationMembership> = []
221
+ let signingIn = false
222
+ /**
223
+ * The current sign-in attempt: advanced by a new sign-in, a cancellation, a sign-out and `close`, so an attempt
224
+ * whose redemption finishes afterwards adopts nothing (and its session is revoked).
225
+ */
226
+ let signInEpoch = 0
227
+ const attempts = new WeakMap<DesktopSignIn, number>()
228
+ /** A redeemed sign-in being adopted (its account checked): a sign-out waits until it is adopted or revoked. */
229
+ let adoptingSignIn: Promise<unknown> | undefined
230
+ let closed = false
231
+ let replica: OpenReplica | undefined
232
+ /**
233
+ * An offline start (`SessionStore.recall`): the stored session the kernel could not be reached to check, and the
234
+ * person and organisation its store remembered for it. While it holds (the check `unavailable`), the session is
235
+ * reported signed in as that person in that organisation and their replica is open from disk; the check's answer
236
+ * ends it (reconciled when the kernel accepts the token, torn down when it refuses it).
237
+ */
238
+ let offline: { readonly token: string; readonly context: RememberedContext } | undefined
239
+ /** The token the current context was made for (a new one is a new context). */
240
+ let contextToken: string | undefined
241
+ /** The person the current context was made for (a session of theirs adopted again keeps its organisation). */
242
+ let contextUser: string | undefined
243
+ /** A token the sync server refused (`needs-auth`): no replica is opened for it again. */
244
+ let refusedToken: string | undefined
245
+ let lastSession = ""
246
+ let lastConnection: string | undefined
247
+ let recheck: ReturnType<typeof setTimeout> | undefined
248
+ const subscriptions = new Map<string, Subscription>()
249
+ /** Writes in flight: their owner and generation. */
250
+ const writes = new Map<string, { readonly owner: string; readonly generation: number }>()
251
+ /** Context changes run one at a time, in order. */
252
+ let transition: Promise<unknown> = Promise.resolve()
253
+ /** The adoption of a new session in progress (its organisations listed, then its first context). */
254
+ let adopting: Promise<void> = Promise.resolve()
255
+
256
+ /** The token calls and the replica use: the checked session's, or an offline start's stored one. */
257
+ const currentToken = (): string | undefined => controller.token() ?? offline?.token
258
+ /** Whether a context can be open: a checked session, or an offline start. */
259
+ const contextOpen = () => controller.state().status === "authenticated" || offline !== undefined
260
+
261
+ const client = makeClient({
262
+ baseUrl: options.kernelUrl,
263
+ modules: options.modules,
264
+ token: currentToken,
265
+ orgId: () => orgId ?? undefined,
266
+ clientVersion: options.clientVersion,
267
+ })
268
+
269
+ /** Agent runs followed for their owners (LocalClient 1.1.0): every one stopped when the context resets. */
270
+ const runs = runFollower({
271
+ kernelUrl: options.kernelUrl,
272
+ clientVersion: options.clientVersion,
273
+ token: currentToken,
274
+ reconnect: options.runReconnect,
275
+ log,
276
+ })
277
+
278
+ const emit = (event: RuntimeEvent) => {
279
+ if (closed) return
280
+ for (const listener of listeners) {
281
+ try {
282
+ listener(event)
283
+ } catch (error) {
284
+ log(`a runtime listener failed: ${errorText(error)}`)
285
+ }
286
+ }
287
+ }
288
+
289
+ /** An event of `of` (a generation): sent only while that generation is current. */
290
+ const emitFor = (of: number, event: RuntimeEvent) => {
291
+ if (of === generation) emit(event)
292
+ }
293
+
294
+ const sessionState = (state: SessionState = controller.state()): LocalClientSessionState => {
295
+ switch (state.status) {
296
+ case "authenticated":
297
+ return {
298
+ state: "signedIn",
299
+ user: { id: state.account.id, email: state.account.email, name: state.account.name },
300
+ organizations: organizations.map((o) => ({ orgId: o.orgId, name: o.name, roles: [...o.roles] })),
301
+ orgId,
302
+ generation,
303
+ }
304
+ case "signing-out":
305
+ return { state: "signingOut" }
306
+ case "unavailable":
307
+ // An offline start: the remembered person, in the remembered organisation, until the check answers.
308
+ if (offline !== undefined) {
309
+ return {
310
+ state: "signedIn",
311
+ user: { ...offline.context.user },
312
+ organizations: organizations.map((o) => ({ orgId: o.orgId, name: o.name, roles: [...o.roles] })),
313
+ orgId,
314
+ generation,
315
+ }
316
+ }
317
+ return signingIn ? { state: "signingIn" } : { state: "signedOut" }
318
+ default:
319
+ return signingIn ? { state: "signingIn" } : { state: "signedOut" }
320
+ }
321
+ }
322
+
323
+ /** Context changes under way: their session is announced after their `context` event, never before it. */
324
+ let resetting = 0
325
+ /** The token whose context was last announced: a session adopted since is announced with its own context. */
326
+ let announcedToken: string | undefined
327
+ const emitSession = () => {
328
+ if (resetting > 0) return
329
+ const state = controller.state()
330
+ if (state.status === "authenticated" && state.token !== announcedToken) return
331
+ const session = sessionState()
332
+ const text = JSON.stringify(session)
333
+ if (text === lastSession) return
334
+ lastSession = text
335
+ emit({ type: "session", session })
336
+ }
337
+
338
+ const destroyViews = (which: (subscription: Subscription) => boolean) => {
339
+ for (const subscription of subscriptions.values()) {
340
+ if (!which(subscription)) continue
341
+ subscriptions.delete(subscription.id)
342
+ try {
343
+ subscription.view.destroy()
344
+ } catch {
345
+ // The replica closed first: its views went with it.
346
+ }
347
+ }
348
+ }
349
+
350
+ const closeReplica = async () => {
351
+ const open = replica
352
+ replica = undefined
353
+ lastConnection = undefined
354
+ if (open === undefined) return
355
+ open.stop()
356
+ await open.zero.close().catch((error: unknown) => log(`closing the replica failed: ${errorText(error)}`))
357
+ }
358
+
359
+ const openReplica = (): OpenReplica => {
360
+ if (closed) throw new NotSignedIn({ message: "The client has stopped" })
361
+ if (replica !== undefined) return replica
362
+ const token = currentToken()
363
+ const state = controller.state()
364
+ const userId = state.status === "authenticated" ? state.account.id : offline?.context.user.id
365
+ if (token === undefined || userId === undefined || orgId === null) {
366
+ throw new NotSignedIn({ message: "Sign in and select an organisation first" })
367
+ }
368
+ if (token === refusedToken) throw new NotSignedIn({ message: "The sync server refused this session" })
369
+ const zero = connectSync({
370
+ server: options.zeroUrl,
371
+ schema: options.schema,
372
+ userId,
373
+ token,
374
+ orgId,
375
+ storage: options.storage,
376
+ mutators: options.mutators as never,
377
+ clientVersion: options.clientVersion,
378
+ }) as unknown as SyncClient
379
+ const of = generation
380
+ const source = (
381
+ zero as unknown as {
382
+ readonly connection: {
383
+ readonly state: {
384
+ readonly current: { readonly name: string }
385
+ subscribe(listener: (state: { readonly name: string }) => void): () => void
386
+ }
387
+ }
388
+ }
389
+ ).connection.state
390
+ const onState = (current: { readonly name: string }) => {
391
+ if (of !== generation || replica?.zero !== zero) return
392
+ const mapped = CONNECTION[current.name] ?? "disconnected"
393
+ if (mapped !== lastConnection) {
394
+ lastConnection = mapped
395
+ emitFor(of, { type: "connection", state: mapped })
396
+ }
397
+ if (mapped === "needsAuth") void needsAuth(token)
398
+ }
399
+ const stop = source.subscribe(onState)
400
+ replica = { zero, generation: of, stop }
401
+ onState(source.current)
402
+ return replica
403
+ }
404
+
405
+ /**
406
+ * Reset the context: a new generation, every view destroyed and every write forgotten, the replica closed, and
407
+ * only then `context` and `session` sent; a replica for the new organisation is opened afterwards.
408
+ */
409
+ const reset = (
410
+ reason: "org" | "signOut" | "needsAuth",
411
+ next: string | null,
412
+ reopen = true,
413
+ /** Whether the request is still the current session's when its turn comes (refused `StaleGeneration` if not). */
414
+ still?: () => boolean,
415
+ ): Promise<number> => {
416
+ const run = async () => {
417
+ // Stopped: a reset queued (or an adoption finished) after `close` opens nothing.
418
+ if (closed) return generation
419
+ if (still !== undefined && !still()) throw overtaken()
420
+ // The session this context is for: storage and reopening after an await happen only while it still is.
421
+ const token = currentToken()
422
+ const same = () => !closed && currentToken() === token
423
+ resetting += 1
424
+ try {
425
+ generation += 1
426
+ orgId = next
427
+ destroyViews(() => true)
428
+ runs.stopAll()
429
+ writes.clear()
430
+ await closeReplica()
431
+ } finally {
432
+ resetting -= 1
433
+ }
434
+ announcedToken = controller.token()
435
+ // What an offline start would reopen follows the context, durably, before the change is announced: the new
436
+ // organisation, or none when the kernel's own listing left the person in none.
437
+ if (next !== null) await rememberContext(next, token)
438
+ else if (reason === "org" && organizationsProblem === undefined) await forgetRememberedContext(token)
439
+ emit({ type: "context", generation, reason })
440
+ emitSession()
441
+ if (reopen && same() && next !== null && contextOpen()) {
442
+ try {
443
+ openReplica()
444
+ } catch (error) {
445
+ log(`opening the replica failed: ${errorText(error)}`)
446
+ }
447
+ }
448
+ return generation
449
+ }
450
+ const done = transition.then(run, run)
451
+ transition = done.catch(() => undefined)
452
+ return done
453
+ }
454
+
455
+ /** A request of a session that no longer owns the runtime (signed out, another person's since): nothing changed. */
456
+ const overtaken = () =>
457
+ new StaleGeneration({ generation, message: "The session changed while the organisation was selected" })
458
+
459
+ /** Wait for the adoption and the context changes requested so far. */
460
+ const settled = async () => {
461
+ await adopting
462
+ await transition
463
+ }
464
+
465
+ const needsAuth = async (token: string) => {
466
+ if (refusedToken === token) return
467
+ refusedToken = token
468
+ log("the sync server refused the session (needs-auth)")
469
+ await reset("needsAuth", orgId, false)
470
+ const state = await controller.invalidate()
471
+ if (state.status === "authenticated" && state.token !== token) return
472
+ if (state.status === "authenticated") {
473
+ // The kernel still accepts it: one more replica, with the refusal remembered if it comes again.
474
+ refusedToken = undefined
475
+ try {
476
+ openReplica()
477
+ } catch (error) {
478
+ log(`reopening the replica failed: ${errorText(error)}`)
479
+ }
480
+ }
481
+ }
482
+
483
+ /**
484
+ * A new session (signed in, or found stored and checked): its organisations, and the one `initialOrg` chooses (by
485
+ * default the one selected before when it is the same person's session again, or the one its store remembers for
486
+ * this token, else the first) selected.
487
+ */
488
+ const adopted = async (token: string) => {
489
+ const state = controller.state()
490
+ const account = state.status === "authenticated" && state.token === token ? state.account : undefined
491
+ // Another person (an offline start's, or a session signed in over another's): the previous person's context closes
492
+ // now, in a new generation, before this person's organisations are awaited, so nothing of theirs stays live or
493
+ // reported meanwhile.
494
+ const handoff =
495
+ account !== undefined &&
496
+ contextUser !== undefined &&
497
+ account.id !== contextUser &&
498
+ (orgId !== null || replica !== undefined || subscriptions.size > 0)
499
+ contextToken = token
500
+ refusedToken = undefined
501
+ offline = undefined
502
+ /** This session still owns the runtime: what was awaited is applied only then. */
503
+ const owns = () => !closed && controller.token() === token && contextToken === token
504
+ if (handoff) {
505
+ forgetListing()
506
+ await reset("signOut", null, false, owns)
507
+ }
508
+ const person = adoptedPerson()
509
+ const listing = listFor(token)
510
+ const remembered = person.previous === null ? await recallFor(token) : undefined
511
+ if (!owns()) return
512
+ // A session its store remembers a context for (a launch's): a listing that does not come in time opens it.
513
+ const fallback = remembered !== undefined && remembered.user.id === person.user?.id ? remembered : undefined
514
+ const answer = fallback === undefined ? await listing : await withinProbe(listing)
515
+ if (!owns()) return
516
+ if (answer === undefined) {
517
+ organizations = [{ ...fallback!.organization, roles: [...fallback!.organization.roles] }]
518
+ lateListing = "The kernel has not listed your organisations yet"
519
+ await reset("org", fallback!.organization.orgId, true, owns)
520
+ void listing
521
+ .then((late) => settleLate(token, late, owns))
522
+ .catch((error: unknown) => log(`listing organisations failed: ${errorText(error)}`))
523
+ return
524
+ }
525
+ keepListing(answer)
526
+ const previous =
527
+ person.previous ??
528
+ (remembered !== undefined && remembered.user.id === person.user?.id ? remembered.organization.orgId : null)
529
+ await reset("org", chooseOrg({ user: person.user, previous }), true, owns)
530
+ }
531
+
532
+ /** `work`'s answer, or `undefined` when it has not come within `offlineProbeMs`. */
533
+ const withinProbe = async <A>(work: Promise<A>): Promise<A | undefined> => {
534
+ let timer: ReturnType<typeof setTimeout> | undefined
535
+ const deadline = new Promise<undefined>((resolve) => {
536
+ timer = setTimeout(() => resolve(undefined), options.offlineProbeMs ?? 3_000)
537
+ })
538
+ try {
539
+ return await Promise.race([work, deadline])
540
+ } finally {
541
+ clearTimeout(timer)
542
+ }
543
+ }
544
+ /** A listing that came after the deadline opened the remembered organisation, while its session owns the runtime. */
545
+ let lateListing: string | undefined
546
+ const settleLate = async (token: string, listing: Awaited<ReturnType<typeof listFor>>, owns: () => boolean) => {
547
+ if (!owns()) return
548
+ lateListing = undefined
549
+ const shown = organizations
550
+ keepListing(listing)
551
+ if (listing.problem !== undefined) {
552
+ // Still unknown: the remembered organisation stays, and the listing is retried.
553
+ organizations = shown
554
+ emitSession()
555
+ return
556
+ }
557
+ if (orgId !== null && organizations.some((o) => o.orgId === orgId)) {
558
+ await rememberContext(orgId, token)
559
+ emitSession()
560
+ return
561
+ }
562
+ const state = controller.state()
563
+ await reset(
564
+ "org",
565
+ chooseOrg({ user: state.status === "authenticated" ? state.account : undefined, previous: null }),
566
+ true,
567
+ owns,
568
+ )
569
+ }
570
+
571
+ /** The context the store remembers for `token` (`SessionStore.recall`), or none. */
572
+ const recallFor = async (token: string): Promise<RememberedContext | undefined> => {
573
+ if (options.sessionStore.recall === undefined) return undefined
574
+ try {
575
+ return await options.sessionStore.recall(token)
576
+ } catch (error) {
577
+ log(`recalling the session's context failed: ${errorText(error)}`)
578
+ return undefined
579
+ }
580
+ }
581
+
582
+ /**
583
+ * Keep the context now open (a checked session's person and organisation) for an offline start. When it cannot be
584
+ * kept, the one remembered before (perhaps an organisation the person has left) is forgotten instead.
585
+ */
586
+ const rememberContext = async (org: string, token: string | undefined = controller.token()) => {
587
+ const state = controller.state()
588
+ const organization = organizations.find((o) => o.orgId === org)
589
+ if (
590
+ options.sessionStore.remember === undefined ||
591
+ state.status !== "authenticated" ||
592
+ state.token !== token ||
593
+ organization === undefined
594
+ ) {
595
+ return
596
+ }
597
+ const context: RememberedContext = {
598
+ user: { id: state.account.id, email: state.account.email, name: state.account.name },
599
+ organization: { orgId: organization.orgId, name: organization.name, roles: [...organization.roles] },
600
+ }
601
+ try {
602
+ await options.sessionStore.remember(state.token, context)
603
+ } catch (error) {
604
+ log(`remembering the session's context failed: ${errorText(error)}`)
605
+ await forgetRememberedContext(token)
606
+ }
607
+ }
608
+
609
+ /**
610
+ * The kernel listed the person's organisations and none is selected (they belong to none now): an offline start
611
+ * must not reopen the one remembered for this session (`SessionStore.forgetContext`; the session itself is kept).
612
+ */
613
+ const forgetRememberedContext = async (token: string | undefined = controller.token()) => {
614
+ const state = controller.state()
615
+ if (options.sessionStore.forgetContext === undefined || state.status !== "authenticated" || state.token !== token) {
616
+ return
617
+ }
618
+ await options.sessionStore
619
+ .forgetContext(state.token)
620
+ .catch((error: unknown) => log(`forgetting the session's remembered context failed: ${errorText(error)}`))
621
+ }
622
+
623
+ /**
624
+ * An offline start: the kernel could not be reached to check the stored session, and its store remembers the
625
+ * context last open with that token. Only that person's replica of that organisation is opened (from disk), never
626
+ * for a token a sign-out left pending; the check goes on (`recheckMs`) and its answer ends it.
627
+ */
628
+ let openingOffline = false
629
+ const openOffline = async () => {
630
+ if (openingOffline) return
631
+ openingOffline = true
632
+ try {
633
+ const unchecked = () => !closed && controller.state().status === "unavailable" && contextToken === undefined
634
+ const token = await options.sessionStore.load().catch(() => undefined)
635
+ // A token the kernel refused in this process is never reopened, even while the store still holds it.
636
+ if (token === undefined || controller.isRefused(token) || !unchecked()) return
637
+ const context = await recallFor(token)
638
+ if (context === undefined || !unchecked()) return
639
+ // A revocation store that cannot be read counts as holding the token: nothing is reopened for it.
640
+ const pending = options.revocations === undefined ? [] : await options.revocations.load().catch(() => [token])
641
+ if (pending.includes(token) || !unchecked()) return
642
+ offline = { token, context }
643
+ contextToken = token
644
+ contextUser = context.user.id
645
+ organizations = [{ ...context.organization, roles: [...context.organization.roles] }]
646
+ log("the kernel cannot be reached: the remembered replica is opened offline")
647
+ await reset("org", context.organization.orgId, true, () => offline?.token === token)
648
+ } finally {
649
+ openingOffline = false
650
+ }
651
+ }
652
+
653
+ /**
654
+ * The kernel accepted an offline start's token: its organisations are listed, and the remembered organisation stays
655
+ * selected (same generation, same replica, which reconnects and reconciles by itself) while the person still belongs
656
+ * to it; otherwise one is chosen in a new context. While they cannot be listed, the remembered one stays.
657
+ */
658
+ const reconcile = async (token: string) => {
659
+ const was = offline
660
+ const listing = await listFor(token)
661
+ const state = controller.state()
662
+ if (closed || was === undefined || offline !== was) return
663
+ if (state.status !== "authenticated" || state.token !== token) return
664
+ offline = undefined
665
+ announcedToken = token
666
+ keepListing(listing)
667
+ if (listing.problem !== undefined) {
668
+ organizations = [was.context.organization]
669
+ emitSession()
670
+ return
671
+ }
672
+ const member = orgId !== null && organizations.some((o) => o.orgId === orgId)
673
+ if (member && state.account.id === was.context.user.id) {
674
+ await rememberContext(orgId!)
675
+ emitSession()
676
+ return
677
+ }
678
+ await reset("org", chooseOrg({ user: state.account, previous: null }))
679
+ }
680
+
681
+ /**
682
+ * Why the person's organisations could not be listed (a transient failure: their memberships are unknown, not
683
+ * none), until a listing succeeds; it is retried on a timer (`recheckMs`) and by `start`.
684
+ */
685
+ let organizationsProblem: string | undefined
686
+ let organizationsRetry: ReturnType<typeof setTimeout> | undefined
687
+ /** The listing a session's retries share (by its token: another session's retry never stands in for its own). */
688
+ let relisting: { readonly token: string | undefined; readonly promise: Promise<void> } | undefined
689
+ const listFor = async (
690
+ token: string,
691
+ ): Promise<{ readonly listed: ReadonlyArray<OrganizationMembership>; readonly problem: string | undefined }> => {
692
+ try {
693
+ return { listed: await listOrganizations(options.kernelUrl, token), problem: undefined }
694
+ } catch (error) {
695
+ log(`listing organisations failed: ${errorText(error)}`)
696
+ // The kernel refused the session itself: torn down like a refused check, never retried as a listing failure
697
+ // (the caller sees the session gone and applies nothing).
698
+ if (refusesSession(error)) await controller.refuse(token)
699
+ return { listed: [], problem: errorText(error) }
700
+ }
701
+ }
702
+ /** A 401: the kernel no longer accepts the session (not a listing that failed). */
703
+ const refusesSession = (error: unknown) => error instanceof AuthError && error.status === 401
704
+ /** The current session's listing kept (inside the session's ownership): a failure is retried. */
705
+ const keepListing = (listing: Awaited<ReturnType<typeof listFor>>) => {
706
+ organizations = listing.listed
707
+ organizationsProblem = listing.problem
708
+ if (organizationsRetry !== undefined) clearTimeout(organizationsRetry)
709
+ organizationsRetry = undefined
710
+ if (listing.problem !== undefined && !closed) {
711
+ organizationsRetry = setTimeout(() => {
712
+ organizationsRetry = undefined
713
+ void relist()
714
+ }, options.recheckMs ?? 5_000)
715
+ }
716
+ }
717
+ const forgetListing = () => {
718
+ lateListing = undefined
719
+ keepListing({ listed: [], problem: undefined })
720
+ }
721
+ /**
722
+ * List the current session's organisations again after a failure: once they come, its organisation is chosen (as
723
+ * for a new session) in a new context; while they still fail, retried. Calls made together share one listing.
724
+ */
725
+ const relist = (): Promise<void> => {
726
+ const token = controller.token()
727
+ if (relisting !== undefined && relisting.token === token) return relisting.promise
728
+ const promise: Promise<void> = (async () => {
729
+ if (closed || organizationsProblem === undefined || token === undefined || token !== contextToken) return
730
+ const listing = await listFor(token)
731
+ const current = () => !closed && controller.token() === token && contextToken === token
732
+ if (!current()) return
733
+ keepListing(listing)
734
+ if (listing.problem !== undefined) return
735
+ const state = controller.state()
736
+ const user = state.status === "authenticated" ? state.account : undefined
737
+ await reset("org", chooseOrg({ user, previous: orgId }), true, current)
738
+ })()
739
+ .catch((error: unknown) => log(`listing organisations again failed: ${errorText(error)}`))
740
+ .finally(() => {
741
+ if (relisting?.promise === promise) relisting = undefined
742
+ })
743
+ relisting = { token, promise }
744
+ return promise
745
+ }
746
+ /** Who the adopted session is, and the organisation selected before when it is the same person's again. */
747
+ const adoptedPerson = () => {
748
+ const state = controller.state()
749
+ const user = state.status === "authenticated" ? state.account : undefined
750
+ const previous = user?.id === contextUser ? orgId : null
751
+ contextUser = user?.id
752
+ return { user, previous }
753
+ }
754
+ /** The organisation a session starts in: `initialOrg`'s choice when it is one of theirs, else the default's. */
755
+ const chooseOrg = (person: {
756
+ readonly user: InitialOrgContext["user"] | undefined
757
+ readonly previous: string | null
758
+ }) => {
759
+ const member = (id: string | null | undefined): id is string =>
760
+ typeof id === "string" && organizations.some((o) => o.orgId === id)
761
+ return [initialChoice(person), person.previous, organizations[0]?.orgId].find(member) ?? null
762
+ }
763
+ const initialChoice = (person: {
764
+ readonly user: InitialOrgContext["user"] | undefined
765
+ readonly previous: string | null
766
+ }) => {
767
+ if (person.user === undefined || options.initialOrg === undefined) return null
768
+ try {
769
+ return options.initialOrg({ user: person.user, organizations, previous: person.previous })
770
+ } catch (error) {
771
+ log(`choosing the organisation failed: ${errorText(error)}`)
772
+ return null
773
+ }
774
+ }
775
+
776
+ const onSession = (state: SessionState) => {
777
+ if (closed) return
778
+ if (recheck !== undefined) {
779
+ clearTimeout(recheck)
780
+ recheck = undefined
781
+ }
782
+ if (state.status === "authenticated" && state.token !== contextToken) {
783
+ signingIn = false
784
+ adopting = adopted(state.token).catch((error: unknown) => log(`adopting the session failed: ${errorText(error)}`))
785
+ return
786
+ }
787
+ if (state.status === "authenticated" && offline !== undefined && state.token === offline.token) {
788
+ adopting = reconcile(state.token).catch((error: unknown) =>
789
+ log(`reconciling the offline session failed: ${errorText(error)}`),
790
+ )
791
+ return
792
+ }
793
+ if (state.status !== "unavailable") offline = undefined
794
+ if (state.status === "unauthenticated" && contextToken !== undefined) {
795
+ // The kernel refused the session (or it was signed out): nothing of it may stay.
796
+ contextToken = undefined
797
+ forgetListing()
798
+ void reset("needsAuth", null, false)
799
+ return
800
+ }
801
+ if (state.status === "unavailable") {
802
+ recheck = setTimeout(() => void controller.refresh(), options.recheckMs ?? 5_000)
803
+ if (contextToken === undefined && options.sessionStore.recall !== undefined) {
804
+ adopting = openOffline().catch((error: unknown) =>
805
+ log(`opening the replica offline failed: ${errorText(error)}`),
806
+ )
807
+ }
808
+ }
809
+ emitSession()
810
+ }
811
+ const unsubscribeSession = controller.subscribe(onSession)
812
+
813
+ // A durable sign-out's pending revocations, retried on a timer while any is left (`revocations`).
814
+ let revocationTimer: ReturnType<typeof setTimeout> | undefined
815
+ const retryRevocations = async () => {
816
+ if (revocationTimer !== undefined) clearTimeout(revocationTimer)
817
+ revocationTimer = undefined
818
+ const outcome = await controller.retryRevocations()
819
+ if (outcome.stillPending) scheduleRevocations()
820
+ return outcome
821
+ }
822
+ const scheduleRevocations = () => {
823
+ if (closed || revocationTimer !== undefined || options.revocations === undefined) return
824
+ revocationTimer = setTimeout(() => {
825
+ revocationTimer = undefined
826
+ void retryRevocations().catch((error: unknown) => log(`retrying revocations failed: ${errorText(error)}`))
827
+ }, options.revocationRetryMs ?? 15_000)
828
+ }
829
+ const unsubscribeRevocation = controller.subscribeRevocation((status) => {
830
+ if (status === "pending") scheduleRevocations()
831
+ })
832
+
833
+ /**
834
+ * Adopt a session a password or two-factor sign-in obtains, as the current sign-in attempt: one abandoned while it
835
+ * completes (a sign-out, another sign-in, `close`) adopts nothing, and its session is revoked. The kernel's own
836
+ * errors (`AuthError`, `TwoFactorRequired`, `UnsavedSignOut`) are thrown as they are, for the caller to show.
837
+ */
838
+ const signInWith = async (obtain: (guard: { readonly current: () => boolean }) => Promise<boolean>) => {
839
+ if (closed) throw new SignInFailed({ message: "The client has stopped" })
840
+ if (controller.state().status === "authenticated") {
841
+ throw new SignInFailed({ message: "A person is already signed in: sign out first" })
842
+ }
843
+ const attempt = ++signInEpoch
844
+ const current = () => !closed && attempt === signInEpoch
845
+ const adoption = obtain({ current })
846
+ const waiting = adoption.catch(() => undefined)
847
+ adoptingSignIn = waiting
848
+ try {
849
+ if (!(await adoption)) {
850
+ throw new SignInFailed({ message: "The sign-in was cancelled while it completed; its session was revoked" })
851
+ }
852
+ } finally {
853
+ if (adoptingSignIn === waiting) adoptingSignIn = undefined
854
+ }
855
+ await settled()
856
+ }
857
+
858
+ const requireContext = () => {
859
+ if (!contextOpen() || orgId === null) {
860
+ throw new NotSignedIn({ message: "Sign in and select an organisation first" })
861
+ }
862
+ }
863
+ /** A request the client made in generation `expected` (its precondition): refused, with nothing run, in another. */
864
+ const requireGeneration = (expected: number | undefined) => {
865
+ if (expected !== undefined && expected !== generation) {
866
+ throw new StaleGeneration({ generation, message: `The context changed (made in ${expected}): nothing was run` })
867
+ }
868
+ }
869
+
870
+ /** The headers of a call as the person in the selected organisation. */
871
+ const callHeaders = (idempotencyKey: string | undefined): Record<string, string> => {
872
+ const token = currentToken()
873
+ return {
874
+ "content-type": "application/json",
875
+ ...(token === undefined ? {} : { authorization: `Bearer ${token}` }),
876
+ ...(orgId === null ? {} : { [ORG_HEADER]: orgId }),
877
+ ...(options.clientVersion === undefined ? {} : { [CLIENT_VERSION_HEADER]: options.clientVersion }),
878
+ ...(idempotencyKey === undefined ? {} : { [IDEMPOTENCY_HEADER]: idempotencyKey }),
879
+ }
880
+ }
881
+
882
+ /** A MAKE module's or kernel action over HTTP, as the person in the organisation: its envelope or typed error. */
883
+ const httpCall = async (action: string, input: unknown, idempotencyKey: string | undefined) => {
884
+ const path = action.startsWith(MAKE_MODULE_PREFIX) ? MAKE_ACTIONS_PATH : "/api/actions"
885
+ const response = await fetch(`${options.kernelUrl}${path}/${encodeURIComponent(action)}`, {
886
+ method: "POST",
887
+ headers: callHeaders(idempotencyKey),
888
+ body: JSON.stringify(input ?? {}),
889
+ })
890
+ const text = await response.text()
891
+ let body: unknown
892
+ try {
893
+ body = text.length === 0 ? {} : JSON.parse(text)
894
+ } catch {
895
+ throw new ActionFailed({ action, message: `The kernel answered ${response.status} with no JSON` })
896
+ }
897
+ if (!response.ok) throw invocationErrorOf(action, body)
898
+ return body
899
+ }
900
+
901
+ return {
902
+ /** The protocol-facing app description: its named queries, mutators and actions. */
903
+ app: {
904
+ queries: [...queries.keys()].sort(),
905
+ mutators: [...mutators.keys()].sort(),
906
+ actions: [...registry.keys(), "make.view", "make.renderView"].sort(),
907
+ },
908
+ /**
909
+ * Check a stored session (once at start): when it holds, the first organisation is selected. Called again, it
910
+ * also lists the person's organisations again when they could not be listed (`organizationsStatus`).
911
+ */
912
+ start: async (): Promise<LocalClientSessionState> => {
913
+ // Pending revocations of earlier sign-outs (a durable sign-out a reload interrupted) are retried meanwhile.
914
+ if (options.revocations !== undefined) {
915
+ void retryRevocations().catch((error: unknown) => log(`retrying revocations failed: ${errorText(error)}`))
916
+ }
917
+ await controller.start()
918
+ emitSession()
919
+ await settled()
920
+ await relist()
921
+ await settled()
922
+ return sessionState()
923
+ },
924
+ session: (): LocalClientSessionState => sessionState(),
925
+ /**
926
+ * Whether the signed-in person's organisations were listed (`listed`), or could not be (`unavailable`, and why):
927
+ * then the session's empty `organizations` are unknown, not none, and they are listed again on a timer
928
+ * (`recheckMs`) and by `start`; once they come, an organisation is selected in a new context.
929
+ */
930
+ organizationsStatus: ():
931
+ | { readonly status: "listed" }
932
+ | { readonly status: "unavailable"; readonly reason: string } =>
933
+ organizationsProblem === undefined && lateListing === undefined
934
+ ? { status: "listed" }
935
+ : { status: "unavailable", reason: organizationsProblem ?? lateListing! },
936
+ generation: (): number => generation,
937
+ onEvent: (listener: (event: RuntimeEvent) => void): (() => void) => {
938
+ listeners.add(listener)
939
+ return () => void listeners.delete(listener)
940
+ },
941
+
942
+ /** Start a desktop sign-in for `redirectUri`: the login to keep (its verifier never leaves the caller). */
943
+ beginSignIn: async (redirectUri: string): Promise<DesktopSignIn> => {
944
+ if (controller.state().status === "authenticated") {
945
+ throw new SignInFailed({ message: "A person is already signed in: sign out first" })
946
+ }
947
+ const login = await beginDesktopSignIn({ redirectUri })
948
+ if (closed) throw new SignInFailed({ message: "The client has stopped" })
949
+ attempts.set(login, ++signInEpoch)
950
+ signingIn = true
951
+ emitSession()
952
+ return login
953
+ },
954
+ /** The browser came back with a code for `login`: redeem it and adopt the session. */
955
+ completeSignIn: async (login: DesktopSignIn, received: { readonly code: string; readonly state: string }) => {
956
+ const attempt = attempts.get(login)
957
+ attempts.delete(login)
958
+ const current = () => !closed && attempt !== undefined && attempt === signInEpoch
959
+ if (!current()) throw new SignInFailed({ message: "This sign-in was cancelled or replaced" })
960
+ const abandoned = () =>
961
+ new SignInFailed({ message: "The sign-in was cancelled while it completed; its session was revoked" })
962
+ let adoption: Promise<boolean> | undefined
963
+ try {
964
+ const session = await completeDesktopSignIn(options.kernelUrl, login, received)
965
+ if (!current()) {
966
+ // Signed out, cancelled, replaced or stopped while the code was redeemed: the session must not stay live.
967
+ await revokeSession(options.kernelUrl, session.token).catch((error: unknown) =>
968
+ log(`revoking an abandoned sign-in's session failed: ${errorText(error)}`),
969
+ )
970
+ throw abandoned()
971
+ }
972
+ // Abandoned while its account is checked (or the check fails): the controller stores and reports nothing,
973
+ // and revokes the session; the attempt is adopted only while it is still current.
974
+ adoption = controller.adopt(session, { current })
975
+ adoptingSignIn = adoption.catch(() => undefined)
976
+ if (!(await adoption)) throw abandoned()
977
+ } catch (error) {
978
+ if (current()) {
979
+ signingIn = false
980
+ emitSession()
981
+ }
982
+ if (error instanceof SignInFailed) throw error
983
+ throw new SignInFailed({ message: `The sign-in could not be completed: ${errorText(error)}` })
984
+ } finally {
985
+ if (adoption !== undefined) adoptingSignIn = undefined
986
+ }
987
+ await settled()
988
+ },
989
+ /** A started sign-in was abandoned (expired, refused). */
990
+ cancelSignIn: () => {
991
+ signInEpoch += 1
992
+ if (!signingIn) return
993
+ signingIn = false
994
+ emitSession()
995
+ },
996
+
997
+ /**
998
+ * Select an organisation the person belongs to: a new generation (its `context` and `session` events sent). One
999
+ * whose session ended while it ran (a sign-out, another person's sign-in, `close`) changes nothing and is refused
1000
+ * with `StaleGeneration`.
1001
+ */
1002
+ selectOrg: async (next: string): Promise<number> => {
1003
+ await settled()
1004
+ const token = controller.token()
1005
+ if (token === undefined && offline !== undefined) {
1006
+ // An offline start: the memberships cannot be checked, so the remembered organisation stays.
1007
+ throw new ActionFailed({
1008
+ action: "client.selectOrg",
1009
+ message: "Cannot reach the kernel; try again when online",
1010
+ })
1011
+ }
1012
+ if (token === undefined) throw new NotSignedIn({ message: "Sign in first" })
1013
+ let listed: ReadonlyArray<OrganizationMembership>
1014
+ try {
1015
+ listed = await listOrganizations(options.kernelUrl, token)
1016
+ } catch (error) {
1017
+ if (!refusesSession(error)) throw error
1018
+ // The kernel refused the session: torn down, as a refused check would.
1019
+ await controller.refuse(token)
1020
+ throw new NotSignedIn({ message: "Your session has ended: sign in again" })
1021
+ }
1022
+ const current = () => !closed && controller.token() === token && contextToken === token
1023
+ if (!current()) throw overtaken()
1024
+ keepListing({ listed, problem: undefined })
1025
+ lateListing = undefined
1026
+ if (!organizations.some((o) => o.orgId === next)) {
1027
+ // The listing is authoritative: one that no longer has the open organisation resets it before refusing.
1028
+ if (orgId !== null && !organizations.some((o) => o.orgId === orgId)) {
1029
+ const state = controller.state()
1030
+ await reset(
1031
+ "org",
1032
+ chooseOrg({ user: state.status === "authenticated" ? state.account : undefined, previous: null }),
1033
+ true,
1034
+ current,
1035
+ )
1036
+ }
1037
+ throw new Forbidden({ action: "client.selectOrg", message: `You are not a member of ${next}` })
1038
+ }
1039
+ return reset("org", next, true, current)
1040
+ },
1041
+
1042
+ /**
1043
+ * Sign out: reads stop at once (`signingOut`), the context is reset (every view destroyed, the replica closed),
1044
+ * and the revocation is sent and retried; resolves once the kernel confirmed it.
1045
+ */
1046
+ signOut: async (): Promise<void> => {
1047
+ signInEpoch += 1
1048
+ // A redeemed session being adopted is abandoned (the epoch advanced): wait until the controller revoked it.
1049
+ if (adoptingSignIn !== undefined) await adoptingSignIn
1050
+ const state = controller.state()
1051
+ // Unauthenticated is not proof that nothing is stored: a stored session is revoked and forgotten below.
1052
+ if (
1053
+ (state.status === "unauthenticated" || state.status === "loading") &&
1054
+ (await options.sessionStore.load()) === undefined
1055
+ ) {
1056
+ signingIn = false
1057
+ emitSession()
1058
+ return
1059
+ }
1060
+ // An offline start's token is known here even when the store cannot be read now: it is the one revoked.
1061
+ const revoking = controller.signOut(offline?.token)
1062
+ revoking.catch(() => undefined)
1063
+ contextToken = undefined
1064
+ offline = undefined
1065
+ forgetListing()
1066
+ await reset("signOut", null, false)
1067
+ try {
1068
+ await revoking
1069
+ } catch (error) {
1070
+ throw new SignInFailed({ message: `The sign-out was not confirmed (try again): ${errorText(error)}` })
1071
+ }
1072
+ emitSession()
1073
+ },
1074
+
1075
+ /** Run a named query live for `owner`; its snapshots arrive as `rows` events of the current generation. */
1076
+ subscribe: async (
1077
+ request: {
1078
+ readonly query: string
1079
+ readonly args?: unknown
1080
+ readonly id?: string | undefined
1081
+ /** In process: refused (`StaleGeneration`) unless the context is still this generation. */
1082
+ readonly generation?: number | undefined
1083
+ },
1084
+ owner: string,
1085
+ ): Promise<{ readonly id: string; readonly generation: number }> => {
1086
+ await settled()
1087
+ requireContext()
1088
+ requireGeneration(request.generation)
1089
+ const query = queries.get(request.query)
1090
+ if (query === undefined) throw new UnknownQuery({ query: request.query, message: `No query ${request.query}` })
1091
+ const id = request.id ?? randomId()
1092
+ if (subscriptions.has(id)) throw new InvalidInput({ message: `A subscription ${id} already exists` })
1093
+ let named: unknown
1094
+ try {
1095
+ named = request.args === undefined ? query() : query(request.args)
1096
+ } catch (error) {
1097
+ throw new InvalidInput({ message: `Invalid arguments for ${request.query}: ${errorText(error)}` })
1098
+ }
1099
+ const open = openReplica()
1100
+ const of = generation
1101
+ const view = (open.zero as unknown as { materialize(query: unknown): View }).materialize(named)
1102
+ subscriptions.set(id, { id, owner, generation: of, view })
1103
+ // Snapshots are sent after the answer is made, so a client hears its id before its rows.
1104
+ setTimeout(() => {
1105
+ if (!subscriptions.has(id)) return
1106
+ view.addListener((data, status, error) => {
1107
+ if (!subscriptions.has(id)) return
1108
+ emitFor(of, {
1109
+ type: "rows",
1110
+ subscription: id,
1111
+ generation: of,
1112
+ status: (["unknown", "cached", "complete", "error"].includes(status) ? status : "unknown") as
1113
+ | "unknown"
1114
+ | "cached"
1115
+ | "complete"
1116
+ | "error",
1117
+ rows: copyRows(data) as never,
1118
+ ...(error === undefined
1119
+ ? {}
1120
+ : // The error as it travels (`{ _tag, message, ... }`), like a rejected write's.
1121
+ { error: encodeInvocationError(invocationErrorOf(request.query, queryErrorOf(error))) as never }),
1122
+ owner,
1123
+ })
1124
+ })
1125
+ }, 0)
1126
+ return { id, generation: of }
1127
+ },
1128
+ /** Stop one of `owner`'s subscriptions. */
1129
+ unsubscribe: (id: string, owner: string) => {
1130
+ const subscription = subscriptions.get(id)
1131
+ if (subscription === undefined || subscription.owner !== owner) {
1132
+ throw new UnknownSubscription({ id, message: `No subscription ${id}` })
1133
+ }
1134
+ destroyViews((s) => s.id === id)
1135
+ },
1136
+ /** Stop every subscription of `owner` (its stream closed). */
1137
+ unsubscribeAll: (owner: string) => destroyViews((s) => s.owner === owner),
1138
+ /** The subscriptions `owner` holds (diagnostics and tests). */
1139
+ subscriptionsOf: (owner: string): ReadonlyArray<string> =>
1140
+ [...subscriptions.values()].filter((s) => s.owner === owner).map((s) => s.id),
1141
+
1142
+ /**
1143
+ * An optimistic write through the app's mutator: resolves once the prediction is in the replica (`predicted`
1144
+ * sent); its outcome follows as a `write` event. An input the action refuses is refused here (`InvalidInput`),
1145
+ * with nothing predicted or sent.
1146
+ */
1147
+ write: async (
1148
+ request: {
1149
+ readonly mutator: string
1150
+ readonly input: unknown
1151
+ readonly id?: string | undefined
1152
+ /** Refused (`StaleGeneration`), nothing predicted or sent, unless the context is still this generation. */
1153
+ readonly generation?: number | undefined
1154
+ },
1155
+ owner: string,
1156
+ ): Promise<{ readonly id: string; readonly generation: number }> => {
1157
+ await settled()
1158
+ requireContext()
1159
+ requireGeneration(request.generation)
1160
+ const mutator = mutators.get(request.mutator)
1161
+ if (mutator === undefined) {
1162
+ throw new UnknownMutator({ mutator: request.mutator, message: `No optimistic mutator ${request.mutator}` })
1163
+ }
1164
+ const id = request.id ?? randomId()
1165
+ if (writes.has(id)) throw new InvalidInput({ message: `A write ${id} is already in flight` })
1166
+ const open = openReplica()
1167
+ const of = generation
1168
+ let pending: ReturnType<typeof optimisticWrite>
1169
+ try {
1170
+ pending = optimisticWrite(open.zero as never, mutator(request.input) as never)
1171
+ } catch (error) {
1172
+ throw new InvalidInput({ message: `Invalid input for ${request.mutator}: ${errorText(error)}` })
1173
+ }
1174
+ writes.set(id, { owner, generation: of })
1175
+ let predicted = true
1176
+ try {
1177
+ await pending.client
1178
+ } catch (error) {
1179
+ // Offline (or closed): nothing was predicted; the write is reported not confirmed, after this answer.
1180
+ if (!(error instanceof WriteNotConfirmed)) {
1181
+ writes.delete(id)
1182
+ throw invocationErrorOf(request.mutator, error)
1183
+ }
1184
+ predicted = false
1185
+ }
1186
+ const settle = (phase: "confirmed" | "rejected" | "notConfirmed", extra: Record<string, unknown> = {}) => {
1187
+ const known = writes.get(id)
1188
+ writes.delete(id)
1189
+ if (known === undefined || known.generation !== of) return
1190
+ emitFor(of, { type: "write", id, generation: of, phase, ...extra, owner })
1191
+ }
1192
+ if (!predicted) {
1193
+ setTimeout(
1194
+ () => settle("notConfirmed", { message: "The replica is offline: nothing was predicted or sent" }),
1195
+ 0,
1196
+ )
1197
+ return { id, generation: of }
1198
+ }
1199
+ emitFor(of, { type: "write", id, generation: of, phase: "predicted", owner })
1200
+ pending.server.then(
1201
+ () => settle("confirmed"),
1202
+ (error: unknown) =>
1203
+ error instanceof WriteNotConfirmed
1204
+ ? settle("notConfirmed", { message: error.message })
1205
+ : settle("rejected", { error: encodeInvocationError(invocationErrorOf(request.mutator, error)) }),
1206
+ )
1207
+ return { id, generation: of }
1208
+ },
1209
+
1210
+ /**
1211
+ * Call an action (not optimistically) as the person in the selected organisation: its result envelope as it
1212
+ * travels. An app action goes through the typed client; `make.*` and MAKE modules' actions over HTTP. A call
1213
+ * whose context changed while it ran is answered `StaleGeneration` naming its own generation (it may have run).
1214
+ * Made for generation `expected` while another is current, it is refused with `StaleGeneration` naming the current
1215
+ * one, and nothing is run.
1216
+ */
1217
+ call: async (action: string, input: unknown, idempotencyKey?: string, expected?: number): Promise<unknown> => {
1218
+ await settled()
1219
+ requireContext()
1220
+ requireGeneration(expected)
1221
+ const of = generation
1222
+ const contract = registry.get(action)
1223
+ let envelope: unknown
1224
+ try {
1225
+ if (contract === undefined) {
1226
+ envelope = await httpCall(action, input, idempotencyKey)
1227
+ } else {
1228
+ const decoded = Schema.decodeUnknownExit(contract.input as Schema.Codec<unknown, unknown>)(input ?? {})
1229
+ if (Exit.isFailure(decoded)) {
1230
+ throw new InvalidInput({ message: `Invalid input for ${action}: ${String(decoded.cause)}` })
1231
+ }
1232
+ const result = await client.call(action as never, decoded.value as never, { idempotencyKey })
1233
+ envelope = Schema.encodeUnknownSync(actionResult(contract) as unknown as Schema.Codec<unknown, unknown>)(
1234
+ result,
1235
+ )
1236
+ }
1237
+ } catch (error) {
1238
+ if (of !== generation) {
1239
+ throw new StaleGeneration({ generation: of, message: "The context changed while the call ran" })
1240
+ }
1241
+ throw invocationErrorOf(action, error)
1242
+ }
1243
+ if (of !== generation) {
1244
+ throw new StaleGeneration({ generation: of, message: "The context changed while the call ran" })
1245
+ }
1246
+ return envelope
1247
+ },
1248
+
1249
+ /**
1250
+ * Follow an agent run's events for `owner` (LocalClient 1.1.0), as the person in the selected organisation: they
1251
+ * arrive as `run` events of the current generation (each stored event once, streamed text as it comes), ending
1252
+ * after `run-finished`, or with the kernel's refusal (`error`). The stream reconnects to the kernel by itself; a
1253
+ * context reset ends it.
1254
+ */
1255
+ followRun: async (
1256
+ request: { readonly runId: string; readonly after?: number | undefined; readonly id?: string | undefined },
1257
+ owner: string,
1258
+ ): Promise<{ readonly id: string; readonly generation: number }> => {
1259
+ await settled()
1260
+ requireContext()
1261
+ const id = request.id ?? randomId()
1262
+ if (runs.has(id)) throw new InvalidInput({ message: `A run subscription ${id} already exists` })
1263
+ const of = generation
1264
+ runs.follow(
1265
+ { id, runId: request.runId, after: request.after ?? -1 },
1266
+ {
1267
+ owner,
1268
+ generation: of,
1269
+ orgId: orgId!,
1270
+ deliver: (delivery, alive) =>
1271
+ // After the answer is made (as a row subscription's snapshots), so a client hears its id first; nothing of
1272
+ // a subscription stopped meanwhile (unfollowed, its stream closed or replaced).
1273
+ setTimeout(() => {
1274
+ if (!alive()) return
1275
+ emitFor(
1276
+ of,
1277
+ delivery.kind === "event"
1278
+ ? { type: "run", subscription: id, generation: of, event: delivery.event, owner }
1279
+ : {
1280
+ type: "run",
1281
+ subscription: id,
1282
+ generation: of,
1283
+ // The error as it travels (`{ _tag, message, ... }`), like a rejected write's.
1284
+ error: encodeInvocationError(
1285
+ invocationErrorOf("agent.events", runErrorOf(delivery.error)),
1286
+ ) as never,
1287
+ owner,
1288
+ },
1289
+ )
1290
+ }, 0),
1291
+ },
1292
+ )
1293
+ return { id, generation: of }
1294
+ },
1295
+ /** Stop following one of `owner`'s runs. */
1296
+ unfollowRun: (id: string, owner: string) => {
1297
+ if (!runs.stop(id, owner)) throw new UnknownSubscription({ id, message: `No run subscription ${id}` })
1298
+ },
1299
+ /** Stop following every run of `owner` (its stream closed). */
1300
+ unfollowAll: (owner: string) => runs.stopOwner(owner),
1301
+ /** The runs `owner` follows (diagnostics and tests). */
1302
+ runsOf: (owner: string): ReadonlyArray<string> => runs.of(owner),
1303
+ /**
1304
+ * Whether the person's agent can answer in the selected organisation (the kernel's readiness, as the chat SDK
1305
+ * asks it): `unknown` when the kernel could not be asked; a refusal of the caller is its typed error.
1306
+ */
1307
+ agentReadiness: async (): Promise<EngineReadiness> => {
1308
+ await settled()
1309
+ requireContext()
1310
+ try {
1311
+ return await runs.readiness(orgId!)
1312
+ } catch (error) {
1313
+ throw invocationErrorOf("agent.readiness", error)
1314
+ }
1315
+ },
1316
+
1317
+ // -- In-process sign-in methods and session details (a JavaScript host: the web shell) ---------------------
1318
+
1319
+ /**
1320
+ * Sign in with email and password and adopt the session (its organisations listed and one selected before this
1321
+ * resolves). Rejects with the kernel's error as it is: `AuthError` (wrong credentials), `TwoFactorRequired` (finish
1322
+ * with `completeTwoFactor`), `UnsavedSignOut` (a durable sign-out's revocation only memory holds); `SignInFailed`
1323
+ * when a person is already signed in or the attempt was abandoned while it completed.
1324
+ */
1325
+ signInWithPassword: (credentials: { readonly email: string; readonly password: string }): Promise<void> =>
1326
+ signInWith((guard) => controller.signIn(credentials, guard)),
1327
+ /** Finish a password sign-in that `TwoFactorRequired` interrupted (its challenge and a code). */
1328
+ completeTwoFactor: (input: Parameters<typeof verifyTwoFactor>[1]): Promise<void> =>
1329
+ signInWith((guard) => controller.completeTwoFactor(input, guard)),
1330
+ /**
1331
+ * Change the signed-in person's password. When the kernel rotates the session, the new token is adopted (the
1332
+ * same person's, so their organisation stays selected, in a new generation); the old one is never reported again.
1333
+ * A rotation answered after the session it rotates ended (a sign-out, `close`) is not adopted: it rejects with
1334
+ * `SignInFailed`, and the rotated session is revoked.
1335
+ */
1336
+ changePassword: async (input: {
1337
+ readonly currentPassword: string
1338
+ readonly newPassword: string
1339
+ readonly revokeOtherSessions?: boolean
1340
+ }): Promise<void> => {
1341
+ await settled()
1342
+ const state = controller.state()
1343
+ if (state.status !== "authenticated") throw new NotSignedIn({ message: "Sign in first" })
1344
+ const { token } = await changeAccountPassword(options.kernelUrl, state.token, input)
1345
+ if (token === state.token) return
1346
+ const user = { id: state.account.id, email: state.account.email, name: state.account.name }
1347
+ // Adopted only while the session it rotates still owns the runtime: one answered after a sign-out, another
1348
+ // session or `close` adopts nothing, and the rotated session is discarded (revoked unless another holds it).
1349
+ const current = () => !closed && controller.token() === state.token
1350
+ if (!(await controller.adopt({ token, user }, { current }))) {
1351
+ throw new SignInFailed({ message: "The session changed while the password was changed" })
1352
+ }
1353
+ await settled()
1354
+ },
1355
+ /**
1356
+ * The session's bearer token, for an in-process host's own requests (a screen's HTTP calls): never sent in an
1357
+ * event, and `undefined` while nobody is signed in.
1358
+ */
1359
+ token: (): string | undefined => currentToken(),
1360
+ /**
1361
+ * The session check's own state: `loading` before the stored session is checked, `unavailable` (and why), and
1362
+ * `signing-out` with `error` while a sign-out that failed waits to be tried again (`signOut`).
1363
+ */
1364
+ sessionStatus: (): {
1365
+ readonly status: SessionState["status"]
1366
+ readonly reason?: string | undefined
1367
+ readonly error?: string | undefined
1368
+ } => {
1369
+ const state = controller.state()
1370
+ if (state.status === "unavailable") return { status: state.status, reason: state.reason }
1371
+ // A sign-out that failed (`SignOutNotSaved`, or a revocation not confirmed): the host offers to try again.
1372
+ if (state.status === "signing-out" && state.error !== undefined)
1373
+ return { status: state.status, error: state.error }
1374
+ return { status: state.status }
1375
+ },
1376
+ /** Where the last durable sign-out's revocation stands (`revocations`). */
1377
+ revocation: (): RevocationStatus => controller.revocationStatus(),
1378
+ onRevocation: (listener: (status: RevocationStatus) => void): (() => void) =>
1379
+ controller.subscribeRevocation((status) => {
1380
+ if (!closed) listener(status)
1381
+ }),
1382
+ /** Try every pending revocation once more now (the network came back). */
1383
+ retryRevocations: () => retryRevocations(),
1384
+
1385
+ /** Stop: every view destroyed, the replica closed, nothing more emitted. */
1386
+ close: async () => {
1387
+ if (closed) return
1388
+ closed = true
1389
+ signInEpoch += 1
1390
+ signingIn = false
1391
+ if (recheck !== undefined) clearTimeout(recheck)
1392
+ if (organizationsRetry !== undefined) clearTimeout(organizationsRetry)
1393
+ if (revocationTimer !== undefined) clearTimeout(revocationTimer)
1394
+ unsubscribeRevocation()
1395
+ unsubscribeSession()
1396
+ controller.dispose()
1397
+ // A context change already running finishes first (queued ones and late adoptions open nothing now).
1398
+ await transition
1399
+ destroyViews(() => true)
1400
+ runs.stopAll()
1401
+ writes.clear()
1402
+ await closeReplica()
1403
+ await client.dispose().catch(() => undefined)
1404
+ listeners.clear()
1405
+ },
1406
+ }
1407
+ }
1408
+
1409
+ export type ClientRuntime = ReturnType<typeof makeClientRuntime>