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