@eloxiv/client 0.0.0-stage → 0.1.1

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 +1283 -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 +228 -0
  164. package/dist/Session.d.ts.map +1 -0
  165. package/dist/Session.js +792 -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 +1442 -0
  254. package/src/RuntimeRuns.ts +180 -0
  255. package/src/ServicesSync.ts +58 -0
  256. package/src/Session.ts +844 -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
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The agent in each person's replica: conversations, their messages and runs (the kernel-provided `agent`
3
+ * module's synced tables, generated from its Drizzle tables, `KernelTables.gen.ts`) and their named queries. An
4
+ * app that installs the kernel's agent module adds `agentTables` and `agentQueries` to its sync schema. The kernel
5
+ * filters every query by the read policy of the entity whose table it reads: a person's replica holds only their
6
+ * own conversations, messages and runs, in the organisation they act in.
7
+ */
8
+ import { createBuilder, createSchema, defineQueryWithType } from "@rocicorp/zero"
9
+ import {
10
+ agentCheckpointTable,
11
+ agentConversationRelationships,
12
+ agentConversationTable,
13
+ agentMessageRelationships,
14
+ agentMessageTable,
15
+ agentRunRelationships,
16
+ agentRunTable,
17
+ agentSubmissionTable,
18
+ } from "./KernelTables.gen.ts"
19
+ import { shareGrant } from "./ShareGrant.ts"
20
+
21
+ export const conversationTable = agentConversationTable
22
+ export const messageTable = agentMessageTable
23
+ export const runTable = agentRunTable
24
+ /** Messages queued behind a conversation's active run (`agent.send` with `queue`), until they start. */
25
+ export const submissionTable = agentSubmissionTable
26
+ /** A conversation's saved checkpoints (`agent.saveCheckpoint`), to restore. */
27
+ export const checkpointTable = agentCheckpointTable
28
+
29
+ export const agentTables = [conversationTable, messageTable, runTable, submissionTable, checkpointTable] as const
30
+
31
+ /**
32
+ * The agent tables' relationships: a conversation's sharing grants (`shares`), and a message's and a run's
33
+ * conversation, which the read filters of a shared conversation follow. Add them with the tables.
34
+ */
35
+ export const agentRelationships = [
36
+ agentConversationRelationships,
37
+ agentMessageRelationships,
38
+ agentRunRelationships,
39
+ ] as const
40
+
41
+ const localSchema = createSchema({ tables: [...agentTables, shareGrant], relationships: [...agentRelationships] })
42
+ const zql = createBuilder(localSchema)
43
+ const defineQuery = defineQueryWithType<typeof localSchema>()
44
+
45
+ /** Named queries (`agent.conversations`, `agent.messages`, `agent.runs`, `agent.submissions`, `agent.checkpoints`). */
46
+ export const agentQueries = {
47
+ agent: {
48
+ /** Your conversations with your agent, newest first. */
49
+ conversations: defineQuery(() => zql.agentConversation.orderBy("updatedAt", "desc").limit(200)),
50
+ /** Messages of your conversations, in order (filter by conversation on the client). */
51
+ messages: defineQuery(() => zql.agentMessage.orderBy("seq", "asc").limit(2_000)),
52
+ /** Your agent's runs, newest first. */
53
+ runs: defineQuery(() => zql.agentRun.orderBy("createdAt", "desc").limit(200)),
54
+ /** Your queued messages and what became of them (queued, promoted, cancelled, expired), in the order sent. */
55
+ submissions: defineQuery(() => zql.agentSubmission.orderBy("seq", "asc").limit(500)),
56
+ /** Your conversations' saved checkpoints, newest first. */
57
+ checkpoints: defineQuery(() => zql.agentCheckpoint.orderBy("createdAt", "desc").limit(500)),
58
+ },
59
+ }
@@ -0,0 +1,222 @@
1
+ /**
2
+ * Durable application state and the agent's commands for the screen, from the client (the ScreenContext
3
+ * contract's `appState` actions, over the transport's rules): keyed entries per tab or shared, read in batches with
4
+ * the client's other reads, written with compare-and-set (and `keepalive` while the page goes away); the published
5
+ * screen snapshot; and a consumer that hands each pending command to the shell once and acknowledges it only after
6
+ * the shell handled it.
7
+ */
8
+ import {
9
+ APP_STATE_ACTIONS,
10
+ type AppCommand,
11
+ type AppCommandOutcome,
12
+ type AppStateEntry,
13
+ type PendingAppCommand,
14
+ SCREEN_STATE_KEY,
15
+ type ScreenSnapshot,
16
+ } from "@eloxiv/contracts"
17
+ import { poll, type Poller, type Visibility } from "./Poll.ts"
18
+ import { randomHex } from "./Tab.ts"
19
+ import { makeReader, type Reader } from "./Reader.ts"
20
+ import {
21
+ type Circuit,
22
+ httpAction,
23
+ makeCircuit,
24
+ RequestError,
25
+ type SignalLike,
26
+ type TransportOptions,
27
+ } from "./Transport.ts"
28
+
29
+ export interface AppStateOptions extends TransportOptions {
30
+ /** This tab's id (`tabIdentity`): per-tab entries are this tab's, and its writes are marked as its own. */
31
+ readonly tabId?: string | undefined
32
+ /** The reader to batch reads with (default: one of its own over the same circuit). */
33
+ readonly reader?: Reader | undefined
34
+ }
35
+
36
+ const outputOf = (envelope: unknown): unknown => {
37
+ const result = envelope as { kind?: string; output?: unknown }
38
+ if (result.kind !== "output") throw new RequestError(0, { _tag: "UnexpectedReplay", message: "Not an output" })
39
+ return result.output
40
+ }
41
+
42
+ const randomId = () => randomHex(12)
43
+
44
+ export const appStateClient = (options: AppStateOptions, circuit: Circuit = options.circuit ?? makeCircuit()) => {
45
+ const reader = options.reader ?? makeReader(options, circuit)
46
+ const tab = (shared: boolean | undefined) =>
47
+ shared === true || options.tabId === undefined ? {} : { tabId: options.tabId }
48
+ const writer = options.tabId === undefined ? {} : { writer: options.tabId }
49
+ const send = async <A>(action: string, input: unknown, keepalive?: boolean) =>
50
+ outputOf(await httpAction(options, circuit, action, input, keepalive === true ? { keepalive } : {})) as A
51
+
52
+ const read = async (keys: ReadonlyArray<string>): Promise<ReadonlyArray<AppStateEntry>> =>
53
+ (
54
+ outputOf(await reader.read(APP_STATE_ACTIONS.read, { keys, ...tab(false) })) as {
55
+ entries: ReadonlyArray<AppStateEntry>
56
+ }
57
+ ).entries
58
+
59
+ return {
60
+ /** The entries for `keys` this tab sees (its own and the shared ones), read in the next batch. */
61
+ read,
62
+ /** A key's entry as this tab sees it: its own if it has one, else the shared one. */
63
+ get: async (key: string): Promise<AppStateEntry | undefined> => {
64
+ const entries = (await read([key])).filter((entry) => entry.key === key)
65
+ return entries.find((entry) => entry.tabId !== null) ?? entries.find((entry) => entry.tabId === null)
66
+ },
67
+ /**
68
+ * Set a key: this tab's entry, or with `shared` the one every tab sees. With `expectedVersion` (0: only if
69
+ * none), `written: false` and the current version when someone else wrote first.
70
+ */
71
+ write: (
72
+ key: string,
73
+ value: unknown,
74
+ write: { readonly shared?: boolean; readonly expectedVersion?: number; readonly keepalive?: boolean } = {},
75
+ ) =>
76
+ send<{ written: boolean; version: number }>(
77
+ APP_STATE_ACTIONS.write,
78
+ {
79
+ key,
80
+ value,
81
+ ...tab(write.shared),
82
+ ...writer,
83
+ ...(write.expectedVersion === undefined ? {} : { expectedVersion: write.expectedVersion }),
84
+ },
85
+ write.keepalive,
86
+ ),
87
+ remove: (key: string, remove: { readonly shared?: boolean; readonly expectedVersion?: number } = {}) =>
88
+ send<{ removed: boolean; version: number }>(APP_STATE_ACTIONS.remove, {
89
+ key,
90
+ ...tab(remove.shared),
91
+ ...(remove.expectedVersion === undefined ? {} : { expectedVersion: remove.expectedVersion }),
92
+ }),
93
+ /**
94
+ * Publish this tab's screen (a ScreenContext snapshot, already through its privacy rules) for the agent to
95
+ * read (`app_state.get` of `screen`); `null` (sharing off, a private view) removes it. `keepalive` lets the
96
+ * last one go out as the page goes away.
97
+ */
98
+ publishScreen: async (snapshot: ScreenSnapshot | null, publish: { readonly keepalive?: boolean } = {}) => {
99
+ if (snapshot === null) await send(APP_STATE_ACTIONS.remove, { key: SCREEN_STATE_KEY, ...tab(false) })
100
+ else
101
+ await send(
102
+ APP_STATE_ACTIONS.write,
103
+ { key: SCREEN_STATE_KEY, value: snapshot, ...tab(false), ...writer },
104
+ publish.keepalive,
105
+ )
106
+ },
107
+ /** Issue a command for the person's screen (for a tab, or any): once under `id` (default: a new one). */
108
+ issue: (command: AppCommand, issue: { readonly id?: string; readonly tabId?: string } = {}) =>
109
+ send<{ id: string; issued: boolean }>(APP_STATE_ACTIONS.issue, {
110
+ id: issue.id ?? randomId(),
111
+ command,
112
+ ...(issue.tabId === undefined ? {} : { tabId: issue.tabId }),
113
+ }),
114
+ /** The commands no tab has handled yet that this tab may handle (its own and those for any tab). */
115
+ pending: async (
116
+ request: { readonly signal?: SignalLike | undefined } = {},
117
+ ): Promise<ReadonlyArray<PendingAppCommand>> =>
118
+ (
119
+ outputOf(await reader.read(APP_STATE_ACTIONS.pending, tab(false), request)) as {
120
+ commands: ReadonlyArray<PendingAppCommand>
121
+ }
122
+ ).commands,
123
+ /** How a command issued went: pending, or acknowledged with its outcome and detail (an `ask`'s answer). */
124
+ outcome: async (id: string) =>
125
+ outputOf(await reader.read(APP_STATE_ACTIONS.outcome, { id })) as {
126
+ readonly id: string
127
+ readonly state: "pending" | "acknowledged" | "unknown"
128
+ readonly outcome: AppCommandOutcome | null
129
+ readonly detail: string | null
130
+ },
131
+ acknowledge: (id: string, outcome: AppCommandOutcome, detail?: string) =>
132
+ send<{ acknowledged: boolean; outcome: AppCommandOutcome | null }>(APP_STATE_ACTIONS.acknowledge, {
133
+ id,
134
+ outcome,
135
+ ...(detail === undefined ? {} : { detail: detail.slice(0, 500) }),
136
+ ...tab(false),
137
+ }),
138
+ reader,
139
+ circuit,
140
+ }
141
+ }
142
+ export type AppStateClient = ReturnType<typeof appStateClient>
143
+
144
+ /** What handling a command came to: its outcome, and why when it was refused or failed. */
145
+ export type CommandHandled = AppCommandOutcome | { readonly outcome: AppCommandOutcome; readonly detail?: string }
146
+
147
+ /**
148
+ * Hands each pending command to `handle` once, in order, and acknowledges it with the outcome only after `handle`
149
+ * finished (a `handle` that throws is `failed`, with the error). Feed it what the replica or `pending()` lists
150
+ * (`receive`); a command already handled here is never handed over again, and an acknowledgement whose answer was
151
+ * lost is sent again on the next `receive` without handling the command again. A command whose page went away
152
+ * before its acknowledgement is still pending, and the next page handles it: delivery is at least once per page,
153
+ * once per page load.
154
+ */
155
+ export const commandConsumer = (
156
+ state: Pick<AppStateClient, "acknowledge">,
157
+ handle: (command: PendingAppCommand) => CommandHandled | Promise<CommandHandled>,
158
+ ) => {
159
+ const outcomes = new Map<string, { outcome: AppCommandOutcome; detail?: string | undefined; sent: boolean }>()
160
+ let working: Promise<void> = Promise.resolve()
161
+ const acknowledge = async (id: string) => {
162
+ const done = outcomes.get(id)
163
+ if (done === undefined || done.sent) return
164
+ try {
165
+ await state.acknowledge(id, done.outcome, done.detail)
166
+ done.sent = true
167
+ } catch {
168
+ // Sent again on the next receive.
169
+ }
170
+ }
171
+ const step = async (commands: ReadonlyArray<PendingAppCommand>, signal: SignalLike | undefined) => {
172
+ for (const command of commands) {
173
+ // Stopped (signed out, another organisation): nothing more is handed over, nor any listed before the stop.
174
+ if (signal?.aborted === true) return
175
+ if (!outcomes.has(command.id)) {
176
+ let handled: CommandHandled
177
+ try {
178
+ handled = await handle(command)
179
+ } catch (error) {
180
+ handled = { outcome: "failed", detail: String(error) }
181
+ }
182
+ outcomes.set(
183
+ command.id,
184
+ typeof handled === "string"
185
+ ? { outcome: handled, sent: false }
186
+ : { outcome: handled.outcome, detail: handled.detail, sent: false },
187
+ )
188
+ }
189
+ await acknowledge(command.id)
190
+ }
191
+ }
192
+ return {
193
+ /** The pending commands as listed now; resolves once each is handled and its acknowledgement tried. */
194
+ receive: (commands: ReadonlyArray<PendingAppCommand>, signal?: SignalLike) => {
195
+ working = working.then(() => step(commands, signal))
196
+ return working
197
+ },
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Poll `pending()` and hand each command to `handle` (`commandConsumer`), every `intervalMs` (default 2 s), paused
203
+ * while the host is hidden. A shell with a replica feeds `commandConsumer` from the synced commands instead.
204
+ */
205
+ export const consumeCommands = (
206
+ state: {
207
+ readonly pending: (request: {
208
+ readonly signal?: SignalLike | undefined
209
+ }) => Promise<ReadonlyArray<PendingAppCommand>>
210
+ readonly acknowledge: AppStateClient["acknowledge"]
211
+ },
212
+ handle: (command: PendingAppCommand) => CommandHandled | Promise<CommandHandled>,
213
+ options: { readonly intervalMs?: number; readonly visibility?: Visibility } = {},
214
+ ): Poller => {
215
+ const consumer = commandConsumer(state, handle)
216
+ // The poller's signal goes to the read and to the consumer: an answer that arrives after `stop()` (an organisation
217
+ // switch) hands nothing over.
218
+ return poll(async (signal) => consumer.receive(await state.pending({ signal }), signal), {
219
+ intervalMs: options.intervalMs ?? 2_000,
220
+ visibility: options.visibility,
221
+ })
222
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Application state and screen commands in each person's replica (the ScreenContext contract's durable state):
3
+ * the kernel-provided `app_state` module's synced tables (generated from its Drizzle tables, `KernelTables.gen.ts`)
4
+ * and named queries. An app that installs `appStateModule` adds `appStateTables` and `appStateQueries` to its sync
5
+ * schema; the kernel filters both to the person's own rows in the organisation the replica acts in.
6
+ */
7
+ import { createBuilder, createSchema, defineQueryWithType } from "@rocicorp/zero"
8
+ import { appCommandTable, appStateEntryTable } from "./KernelTables.gen.ts"
9
+
10
+ export { appCommandTable, appStateEntryTable }
11
+
12
+ export const appStateTables = [appStateEntryTable, appCommandTable] as const
13
+
14
+ const localSchema = createSchema({ tables: [appStateEntryTable, appCommandTable] })
15
+ const zql = createBuilder(localSchema)
16
+ const defineQuery = defineQueryWithType<typeof localSchema>()
17
+
18
+ /** Named queries, namespaced like a module's (`app_state.entries`, `app_state.pending`). */
19
+ export const appStateQueries = {
20
+ app_state: {
21
+ /** Your application state entries (every tab's and the shared ones); a removed one has a null value. */
22
+ entries: defineQuery(() => zql.appStateEntry),
23
+ /** The commands for your screen no tab has acknowledged yet, oldest first. */
24
+ pending: defineQuery(() => zql.appCommand.where("acknowledgedAt", "IS", null).orderBy("issuedAt", "asc")),
25
+ },
26
+ }
package/src/Auth.ts ADDED
@@ -0,0 +1,225 @@
1
+ /** Email and password sign-in against the kernel's Better Auth routes, returning a bearer token. */
2
+ export interface Session {
3
+ readonly token: string
4
+ readonly user: { readonly id: string; readonly email: string; readonly name: string }
5
+ }
6
+
7
+ export class AuthError extends Error {
8
+ override readonly name = "AuthError"
9
+ readonly status: number
10
+ constructor(message: string, status: number) {
11
+ super(message)
12
+ this.status = status
13
+ }
14
+ }
15
+
16
+ /**
17
+ * A password sign-in of an account with two-factor authentication: no session yet. Finish it with
18
+ * `verifyTwoFactor({ challenge, code })` (Account.ts) within ten minutes; the challenge allows a few attempts.
19
+ */
20
+ export class TwoFactorRequired extends AuthError {
21
+ readonly challenge: string
22
+ /** The second factors the account can use: `totp` (and every account with it has backup codes). */
23
+ readonly methods: ReadonlyArray<string>
24
+ constructor(challenge: string, methods: ReadonlyArray<string>) {
25
+ super("This account needs a second factor: a code from an authenticator app or a backup code", 401)
26
+ this.challenge = challenge
27
+ this.methods = methods
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Better Auth rejects state-changing requests without an Origin header. Browsers
33
+ * set it themselves (and ignore ours); other runtimes (React Native, Bun, Node)
34
+ * send the kernel's own origin, which Better Auth trusts.
35
+ */
36
+ export const originOf = (baseUrl: string): string => /^[a-z][a-z0-9+.-]*:\/\/[^/]+/i.exec(baseUrl)?.[0] ?? baseUrl
37
+
38
+ const post = async (baseUrl: string, path: string, body: unknown): Promise<Session> => {
39
+ const response = await fetch(`${baseUrl}/auth${path}`, {
40
+ method: "POST",
41
+ headers: { "content-type": "application/json", origin: originOf(baseUrl) },
42
+ body: JSON.stringify(body),
43
+ })
44
+ if (!response.ok) throw new AuthError(`${path} failed: ${await response.text()}`, response.status)
45
+ const json = (await response.json()) as {
46
+ user: Session["user"]
47
+ twoFactorRedirect?: boolean
48
+ challenge?: string
49
+ twoFactorMethods?: ReadonlyArray<string>
50
+ }
51
+ // An account with two-factor authentication: no session until a second factor (Account.ts `verifyTwoFactor`).
52
+ if (json.twoFactorRedirect === true) {
53
+ throw new TwoFactorRequired(json.challenge ?? "", json.twoFactorMethods ?? [])
54
+ }
55
+ const token = response.headers.get("set-auth-token")
56
+ if (token === null) throw new AuthError("The server did not return a bearer token", response.status)
57
+ return { token, user: json.user }
58
+ }
59
+
60
+ /**
61
+ * Email and password to a session. An account with two-factor authentication rejects with `TwoFactorRequired`
62
+ * (holding the challenge `verifyTwoFactor` finishes it with); wrong credentials with `AuthError` (401).
63
+ */
64
+ export const signIn = (baseUrl: string, credentials: { readonly email: string; readonly password: string }) =>
65
+ post(baseUrl, "/sign-in/email", credentials)
66
+
67
+ export const signUp = (
68
+ baseUrl: string,
69
+ account: { readonly email: string; readonly password: string; readonly name: string },
70
+ ) => post(baseUrl, "/sign-up/email", account)
71
+
72
+ /** One organisation the signed-in user belongs to. */
73
+ export interface OrganizationMembership {
74
+ readonly orgId: string
75
+ readonly name: string
76
+ readonly roles: ReadonlyArray<string>
77
+ }
78
+
79
+ /**
80
+ * The organisations the signed-in user belongs to, oldest membership first (the first is where calls act when
81
+ * they name no organisation). Rejects with `AuthError` (status 401) without a valid session.
82
+ */
83
+ export const listOrganizations = async (
84
+ baseUrl: string,
85
+ token: string,
86
+ ): Promise<ReadonlyArray<OrganizationMembership>> => {
87
+ const response = await fetch(`${baseUrl}/api/me/organizations`, { headers: { authorization: `Bearer ${token}` } })
88
+ if (!response.ok) throw new AuthError(`/api/me/organizations failed: ${await response.text()}`, response.status)
89
+ return (await response.json()) as ReadonlyArray<OrganizationMembership>
90
+ }
91
+
92
+ /** A member of an organisation, with their roles and groups (Directory `listMembers`). */
93
+ export interface OrganizationMember {
94
+ readonly userId: string
95
+ readonly email: string
96
+ readonly roles: ReadonlyArray<string>
97
+ readonly groups: ReadonlyArray<string>
98
+ }
99
+
100
+ /** The members of `orgId` (the caller must be one of them), oldest membership first. */
101
+ export const listMembers = async (
102
+ baseUrl: string,
103
+ token: string,
104
+ orgId: string,
105
+ ): Promise<ReadonlyArray<OrganizationMember>> => {
106
+ const response = await fetch(`${baseUrl}/api/org/members`, {
107
+ headers: { authorization: `Bearer ${token}`, "x-eloxiv-org": orgId },
108
+ })
109
+ if (!response.ok) throw new AuthError(`/api/org/members failed: ${await response.text()}`, response.status)
110
+ return (await response.json()) as ReadonlyArray<OrganizationMember>
111
+ }
112
+
113
+ /** A role of an organisation, with the permissions it grants (Directory `listRoles`). */
114
+ export interface OrganizationRole {
115
+ readonly id: string
116
+ readonly name: string
117
+ readonly permissions: ReadonlyArray<string>
118
+ }
119
+
120
+ /**
121
+ * Why a member administration call was refused: the kernel's typed error (`Unauthenticated`, `Forbidden`: no
122
+ * `eloxiv.directory.manage`, or not a person's own session; `InvalidInput`: no such account, role or member, or the
123
+ * change would leave the organisation with no one who can manage it), with its message.
124
+ */
125
+ export class MemberAdminError extends Error {
126
+ readonly tag: string
127
+ readonly status: number
128
+ constructor(tag: string, message: string, status: number) {
129
+ super(message)
130
+ this.tag = tag
131
+ this.status = status
132
+ }
133
+ }
134
+
135
+ const memberCall = async (
136
+ baseUrl: string,
137
+ token: string,
138
+ orgId: string,
139
+ method: "GET" | "POST" | "DELETE",
140
+ path: string,
141
+ body?: unknown,
142
+ ): Promise<unknown> => {
143
+ const response = await fetch(`${baseUrl}${path}`, {
144
+ method,
145
+ headers: {
146
+ authorization: `Bearer ${token}`,
147
+ "x-eloxiv-org": orgId,
148
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
149
+ },
150
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
151
+ })
152
+ const text = await response.text()
153
+ let parsed: unknown
154
+ try {
155
+ parsed = text.length === 0 ? {} : JSON.parse(text)
156
+ } catch {
157
+ parsed = undefined
158
+ }
159
+ if (!response.ok) {
160
+ const error = (parsed ?? {}) as { _tag?: unknown; message?: unknown }
161
+ throw new MemberAdminError(
162
+ typeof error._tag === "string" ? error._tag : "Unknown",
163
+ typeof error.message === "string" ? error.message : `${path} failed (${response.status})`,
164
+ response.status,
165
+ )
166
+ }
167
+ return parsed
168
+ }
169
+
170
+ const member = (userId: string) => `/api/org/members/${encodeURIComponent(userId)}`
171
+
172
+ /** The roles of `orgId` (any member may list). */
173
+ export const listRoles = async (
174
+ baseUrl: string,
175
+ token: string,
176
+ orgId: string,
177
+ ): Promise<ReadonlyArray<OrganizationRole>> =>
178
+ (await memberCall(baseUrl, token, orgId, "GET", "/api/org/roles")) as ReadonlyArray<OrganizationRole>
179
+
180
+ /** Add the existing user with this address to `orgId`, with `roles` (default `member`). Needs directory management. */
181
+ export const addMember = async (
182
+ baseUrl: string,
183
+ token: string,
184
+ orgId: string,
185
+ input: { readonly email: string; readonly roles?: ReadonlyArray<string> },
186
+ ): Promise<void> => {
187
+ await memberCall(baseUrl, token, orgId, "POST", "/api/org/members", input)
188
+ }
189
+
190
+ /** Remove a member from `orgId`; their next call is refused. Never the organisation's last administrator. */
191
+ export const removeMember = async (baseUrl: string, token: string, orgId: string, userId: string): Promise<void> => {
192
+ await memberCall(baseUrl, token, orgId, "DELETE", member(userId))
193
+ }
194
+
195
+ /** Give a member a role. */
196
+ export const assignRole = async (
197
+ baseUrl: string,
198
+ token: string,
199
+ orgId: string,
200
+ userId: string,
201
+ roleId: string,
202
+ ): Promise<void> => {
203
+ await memberCall(baseUrl, token, orgId, "POST", `${member(userId)}/roles`, { roleId })
204
+ }
205
+
206
+ /** Take a role from a member. Never the last role that lets anyone manage the organisation. */
207
+ export const unassignRole = async (
208
+ baseUrl: string,
209
+ token: string,
210
+ orgId: string,
211
+ userId: string,
212
+ roleId: string,
213
+ ): Promise<void> => {
214
+ await memberCall(baseUrl, token, orgId, "DELETE", `${member(userId)}/roles/${encodeURIComponent(roleId)}`)
215
+ }
216
+
217
+ /** Revoke the session on the server (Better Auth `sign-out`); the token stops authenticating everywhere. */
218
+ export const signOut = async (baseUrl: string, token: string): Promise<void> => {
219
+ const response = await fetch(`${baseUrl}/auth/sign-out`, {
220
+ method: "POST",
221
+ headers: { "content-type": "application/json", origin: originOf(baseUrl), authorization: `Bearer ${token}` },
222
+ body: "{}",
223
+ })
224
+ if (!response.ok) throw new AuthError(`/sign-out failed: ${await response.text()}`, response.status)
225
+ }
package/src/Avatars.ts ADDED
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Avatars, headless: people's profile photos as the kernel keeps them (`/api/me/avatar`, `/api/users/<id>/avatar`).
3
+ * One client per signed-in person, shared by every view: a photo is fetched once however many views ask at once
4
+ * (lookups in flight are shared), kept until it changes (revalidated by its ETag), and every view subscribed to a
5
+ * person hears of their new photo the moment this client uploads or removes it. A person sees only their own photo
6
+ * and those of people who share an organisation with them (the kernel answers no photo for anyone else).
7
+ *
8
+ * The SDK owns no form and no image codec (it runs where there is no canvas): `compress` is the app's (a browser's
9
+ * canvas or `createImageBitmap`, a native module), applied to every upload; the kernel takes PNG, JPEG, WebP or GIF of
10
+ * at most 256 KiB, and the SDK refuses anything else before sending it.
11
+ */
12
+
13
+ /** An image's bytes and type. */
14
+ export interface AvatarImage {
15
+ readonly contentType: string
16
+ readonly bytes: Uint8Array
17
+ }
18
+
19
+ /** A person's photo, with its version (its ETag). */
20
+ export interface Avatar extends AvatarImage {
21
+ readonly etag: string
22
+ }
23
+
24
+ /** The largest photo the kernel keeps. */
25
+ export const MAX_AVATAR_BYTES = 256 * 1024
26
+ export const AVATAR_TYPES: ReadonlyArray<string> = ["image/png", "image/jpeg", "image/webp", "image/gif"]
27
+
28
+ export class AvatarError extends Error {
29
+ readonly status: number
30
+ constructor(message: string, status: number) {
31
+ super(message)
32
+ this.status = status
33
+ }
34
+ }
35
+
36
+ export interface AvatarClientOptions {
37
+ readonly baseUrl: string
38
+ /** The signed-in person's session token, read for every request. */
39
+ readonly token: () => string
40
+ /** The signed-in person's user id (whose photo `upload` and `remove` change). */
41
+ readonly userId: () => string
42
+ /** Make a chosen photo fit (resize, re-encode); applied to every upload. Default: sent as chosen. */
43
+ readonly compress?: ((image: AvatarImage) => Promise<AvatarImage>) | undefined
44
+ }
45
+
46
+ /** `undefined`: the person has no photo (or is not one this person may see). */
47
+ export type AvatarListener = (avatar: Avatar | undefined) => void
48
+
49
+ export const avatarClient = (options: AvatarClientOptions) => {
50
+ const cache = new Map<string, Avatar | undefined>()
51
+ const inflight = new Map<string, Promise<Avatar | undefined>>()
52
+ const listeners = new Map<string, Set<AvatarListener>>()
53
+ const base = options.baseUrl.replace(/\/+$/u, "")
54
+ const auth = () => ({ authorization: `Bearer ${options.token()}` })
55
+
56
+ const publish = (userId: string, avatar: Avatar | undefined) => {
57
+ cache.set(userId, avatar)
58
+ for (const listener of listeners.get(userId) ?? []) {
59
+ try {
60
+ listener(avatar)
61
+ } catch {
62
+ // A listener's failure is its own.
63
+ }
64
+ }
65
+ }
66
+
67
+ const fetchAvatar = async (userId: string): Promise<Avatar | undefined> => {
68
+ const cached = cache.get(userId)
69
+ const response = await fetch(`${base}/api/users/${encodeURIComponent(userId)}/avatar`, {
70
+ headers: { ...auth(), ...(cached === undefined ? {} : { "if-none-match": `"${cached.etag}"` }) },
71
+ })
72
+ if (response.status === 304 && cached !== undefined) return cached
73
+ if (response.status === 404) return undefined
74
+ if (!response.ok) throw new AvatarError(`The avatar could not be read (${response.status})`, response.status)
75
+ const etag = (response.headers.get("etag") ?? "").replaceAll('"', "")
76
+ return {
77
+ contentType: response.headers.get("content-type") ?? "application/octet-stream",
78
+ bytes: new Uint8Array(await response.arrayBuffer()),
79
+ etag,
80
+ }
81
+ }
82
+
83
+ /** A person's photo: the cached one, or one lookup shared by every caller asking at the same time. */
84
+ const get = (userId: string, lookup: { readonly refresh?: boolean } = {}): Promise<Avatar | undefined> => {
85
+ if (lookup.refresh !== true && cache.has(userId)) return Promise.resolve(cache.get(userId))
86
+ const pending = inflight.get(userId)
87
+ if (pending !== undefined) return pending
88
+ const started = fetchAvatar(userId)
89
+ .then((avatar) => {
90
+ const before = cache.get(userId)
91
+ if (!cache.has(userId) || before?.etag !== avatar?.etag) publish(userId, avatar)
92
+ return avatar
93
+ })
94
+ .finally(() => inflight.delete(userId))
95
+ inflight.set(userId, started)
96
+ return started
97
+ }
98
+
99
+ return {
100
+ get,
101
+ /** Hear of a person's photo changing (an upload or removal through this client, or a refreshed lookup). */
102
+ subscribe: (userId: string, listener: AvatarListener): (() => void) => {
103
+ const set = listeners.get(userId) ?? new Set<AvatarListener>()
104
+ set.add(listener)
105
+ listeners.set(userId, set)
106
+ return () => void set.delete(listener)
107
+ },
108
+ /** Forget a cached photo, so the next `get` asks the kernel. */
109
+ invalidate: (userId: string) => void cache.delete(userId),
110
+ /** Set the signed-in person's photo (compressed first, when the app gives a compressor). */
111
+ upload: async (chosen: AvatarImage): Promise<Avatar> => {
112
+ const image = options.compress === undefined ? chosen : await options.compress(chosen)
113
+ if (!AVATAR_TYPES.includes(image.contentType)) {
114
+ throw new AvatarError(`An avatar is PNG, JPEG, WebP or GIF, not ${image.contentType}`, 415)
115
+ }
116
+ if (image.bytes.length > MAX_AVATAR_BYTES) {
117
+ throw new AvatarError(`An avatar is at most ${MAX_AVATAR_BYTES} bytes (this one: ${image.bytes.length})`, 413)
118
+ }
119
+ const response = await fetch(`${base}/api/me/avatar`, {
120
+ method: "PUT",
121
+ headers: { ...auth(), "content-type": image.contentType },
122
+ // A copy on its own ArrayBuffer (what every runtime's fetch takes as a body).
123
+ body: new Uint8Array(image.bytes),
124
+ })
125
+ if (!response.ok) throw new AvatarError(`The avatar was refused: ${await response.text()}`, response.status)
126
+ const { etag } = (await response.json()) as { etag: string }
127
+ const avatar = { contentType: image.contentType, bytes: image.bytes, etag }
128
+ publish(options.userId(), avatar)
129
+ return avatar
130
+ },
131
+ /** Remove the signed-in person's photo. */
132
+ remove: async (): Promise<void> => {
133
+ const response = await fetch(`${base}/api/me/avatar`, {
134
+ method: "DELETE",
135
+ headers: { ...auth(), "content-type": "application/json" },
136
+ body: "{}",
137
+ })
138
+ if (!response.ok) throw new AvatarError(`The avatar could not be removed (${response.status})`, response.status)
139
+ publish(options.userId(), undefined)
140
+ },
141
+ }
142
+ }
143
+
144
+ export type AvatarClient = ReturnType<typeof avatarClient>