@feltdb/feltkit 0.3.16 → 0.3.18
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/dist/app.d.ts +222 -5
- package/dist/app.js +178 -3
- package/dist/app.js.map +1 -1
- package/dist/appboundry/build.d.ts +57 -0
- package/dist/appboundry/build.js +54 -2
- package/dist/appboundry/build.js.map +1 -1
- package/dist/appboundry/guest.js +73 -1
- package/dist/appboundry/guest.js.map +1 -1
- package/dist/appboundry/host.d.ts +15 -0
- package/dist/appboundry/host.js +45 -1
- package/dist/appboundry/host.js.map +1 -1
- package/dist/authorize.d.ts +3 -2
- package/dist/authorize.js +5 -3
- package/dist/authorize.js.map +1 -1
- package/dist/cli/deploy-appboundry-self-hosted.d.ts +2 -0
- package/dist/cli/deploy-appboundry-self-hosted.js +1 -1
- package/dist/cli/deploy-appboundry-self-hosted.js.map +1 -1
- package/dist/cli/deploy-appboundry.js +3 -0
- package/dist/cli/deploy-appboundry.js.map +1 -1
- package/dist/cli/main.js +6 -1
- package/dist/cli/main.js.map +1 -1
- package/dist/client/index.d.ts +242 -5
- package/dist/client/index.js +413 -29
- package/dist/client/index.js.map +1 -1
- package/dist/docs.d.ts +1 -1
- package/dist/docs.js +1 -0
- package/dist/docs.js.map +1 -1
- package/dist/event-stage.d.ts +13 -0
- package/dist/event-stage.js +15 -0
- package/dist/event-stage.js.map +1 -0
- package/dist/index.d.ts +5 -3
- package/dist/index.js.map +1 -1
- package/dist/react/auth.d.ts +131 -0
- package/dist/react/auth.js +830 -0
- package/dist/react/auth.js.map +1 -0
- package/dist/react/context.d.ts +8 -0
- package/dist/react/context.js +14 -0
- package/dist/react/context.js.map +1 -0
- package/dist/react/index.d.ts +17 -18
- package/dist/react/index.js +21 -13
- package/dist/react/index.js.map +1 -1
- package/dist/runtime/accounts.d.ts +33 -2
- package/dist/runtime/accounts.js +167 -27
- package/dist/runtime/accounts.js.map +1 -1
- package/dist/runtime/authority.d.ts +9 -1
- package/dist/runtime/authority.js +14 -2
- package/dist/runtime/authority.js.map +1 -1
- package/dist/runtime/challenges.d.ts +51 -0
- package/dist/runtime/challenges.js +121 -0
- package/dist/runtime/challenges.js.map +1 -0
- package/dist/runtime/changes.d.ts +22 -0
- package/dist/runtime/changes.js +51 -3
- package/dist/runtime/changes.js.map +1 -1
- package/dist/runtime/content.d.ts +32 -0
- package/dist/runtime/content.js +42 -1
- package/dist/runtime/content.js.map +1 -1
- package/dist/runtime/context.d.ts +50 -0
- package/dist/runtime/contract.js +14 -3
- package/dist/runtime/contract.js.map +1 -1
- package/dist/runtime/data.d.ts +36 -2
- package/dist/runtime/data.js +56 -17
- package/dist/runtime/data.js.map +1 -1
- package/dist/runtime/events.d.ts +21 -0
- package/dist/runtime/events.js +65 -0
- package/dist/runtime/events.js.map +1 -0
- package/dist/runtime/live.d.ts +48 -0
- package/dist/runtime/live.js +154 -0
- package/dist/runtime/live.js.map +1 -0
- package/dist/runtime/outbox.js +3 -0
- package/dist/runtime/outbox.js.map +1 -1
- package/dist/runtime/runtime.d.ts +70 -5
- package/dist/runtime/runtime.js +307 -36
- package/dist/runtime/runtime.js.map +1 -1
- package/dist/runtime/search.d.ts +54 -0
- package/dist/runtime/search.js +66 -0
- package/dist/runtime/search.js.map +1 -0
- package/dist/runtime/services.d.ts +45 -0
- package/dist/runtime/services.js +90 -0
- package/dist/runtime/services.js.map +1 -1
- package/dist/runtime/sessions.d.ts +16 -2
- package/dist/runtime/sessions.js +40 -4
- package/dist/runtime/sessions.js.map +1 -1
- package/dist/runtime/tenancy.d.ts +189 -0
- package/dist/runtime/tenancy.js +376 -0
- package/dist/runtime/tenancy.js.map +1 -0
- package/dist/runtime/tenant-scope.d.ts +9 -0
- package/dist/runtime/tenant-scope.js +127 -0
- package/dist/runtime/tenant-scope.js.map +1 -0
- package/dist/runtime/transactions.d.ts +45 -2
- package/dist/runtime/transactions.js +36 -9
- package/dist/runtime/transactions.js.map +1 -1
- package/dist/schema.d.ts +2 -1
- package/dist/schema.js +1 -1
- package/dist/schema.js.map +1 -1
- package/dist/server/http.d.ts +1 -0
- package/dist/server/http.js +14 -0
- package/dist/server/http.js.map +1 -1
- package/dist/server/index.d.ts +2 -1
- package/dist/server/index.js +325 -59
- package/dist/server/index.js.map +1 -1
- package/dist/server/mcp.js +6 -3
- package/dist/server/mcp.js.map +1 -1
- package/dist/server/session-http.d.ts +48 -0
- package/dist/server/session-http.js +116 -0
- package/dist/server/session-http.js.map +1 -0
- package/dist/server/tenancy.d.ts +40 -0
- package/dist/server/tenancy.js +191 -0
- package/dist/server/tenancy.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.js +7 -2
- package/dist/testing/index.js.map +1 -1
- package/docs/AGENT-OPERATIONS.md +1 -0
- package/docs/APPBOUNDRY.md +11 -1
- package/docs/ARCHITECTURE.md +4 -2
- package/docs/AUTH.md +262 -0
- package/docs/GUARANTEES.md +58 -4
- package/docs/README.md +3 -2
- package/docs/SECURITY.md +3 -2
- package/docs/TRANSACTIONS.md +98 -1
- package/docs/UPSTREAM-GAPS.md +3 -0
- package/package.json +11 -9
- package/skills/.claude-plugin/marketplace.json +1 -1
- package/skills/.claude-plugin/plugin.json +1 -1
- package/skills/feltkit-data/SKILL.md +6 -0
- package/dist/runtime/account-links.d.ts +0 -19
- package/dist/runtime/account-links.js +0 -45
- package/dist/runtime/account-links.js.map +0 -1
package/dist/client/index.js
CHANGED
|
@@ -9,10 +9,14 @@
|
|
|
9
9
|
* import type * as tasks from "../tasks.js";
|
|
10
10
|
* export const api = createApi<{ tasks: typeof tasks }>();
|
|
11
11
|
*
|
|
12
|
-
* Reactivity: the server returns the collections each query read
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
* the
|
|
12
|
+
* Reactivity: the server returns the collections each query read, and for a collection read
|
|
13
|
+
* only through equality predicates (`get` by id, `find({ channelId })`, …) an opaque key per
|
|
14
|
+
* predicate (`"messages#<key>"`). The client keeps one change stream open; each change names the
|
|
15
|
+
* collections that changed and, when the server could describe them record by record, the opaque
|
|
16
|
+
* keys of the changed records' keyed values, before and after. A watched query re-runs when a
|
|
17
|
+
* collection it read wholly changed, or when a change's keys meet its predicates (a change
|
|
18
|
+
* without keys re-runs every query that read the collection). Keys are server-side HMACs: the
|
|
19
|
+
* client only compares them. The re-run goes through the normal authorized query endpoint.
|
|
16
20
|
*/
|
|
17
21
|
/** Build typed references. At runtime, `api.tasks.list` is `{ name: "tasks:list" }`. */
|
|
18
22
|
export function createApi() {
|
|
@@ -76,6 +80,45 @@ export function browserTokenStore(key = "feltkit.session") {
|
|
|
76
80
|
},
|
|
77
81
|
};
|
|
78
82
|
}
|
|
83
|
+
/** A token store that holds nothing: in cookie mode the browser keeps the session, not the page. */
|
|
84
|
+
function noTokens() {
|
|
85
|
+
return { get: () => null, set: () => undefined };
|
|
86
|
+
}
|
|
87
|
+
const LEGACY_TOKEN_KEY = "feltkit.session";
|
|
88
|
+
/** Parse a query result's `reads` (names, then `collection#key` entries). */
|
|
89
|
+
export function parseReads(reads) {
|
|
90
|
+
const collections = new Set();
|
|
91
|
+
const predicates = new Map();
|
|
92
|
+
for (const entry of reads) {
|
|
93
|
+
const at = entry.indexOf("#");
|
|
94
|
+
if (at < 0) {
|
|
95
|
+
collections.add(entry);
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
const collection = entry.slice(0, at);
|
|
99
|
+
let keys = predicates.get(collection);
|
|
100
|
+
if (!keys)
|
|
101
|
+
predicates.set(collection, (keys = new Set()));
|
|
102
|
+
keys.add(entry.slice(at + 1));
|
|
103
|
+
}
|
|
104
|
+
return { collections, predicates };
|
|
105
|
+
}
|
|
106
|
+
/** Whether a change can affect a query that read `reads`. When in doubt: yes. */
|
|
107
|
+
export function changeAffects(reads, collections, keys) {
|
|
108
|
+
if (collections.includes("*") || reads.collections.has("*"))
|
|
109
|
+
return true;
|
|
110
|
+
for (const collection of collections) {
|
|
111
|
+
if (!reads.collections.has(collection))
|
|
112
|
+
continue;
|
|
113
|
+
const predicates = reads.predicates.get(collection);
|
|
114
|
+
const changed = keys?.[collection];
|
|
115
|
+
if (!predicates || !changed)
|
|
116
|
+
return true;
|
|
117
|
+
if (changed.some((key) => predicates.has(key)))
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
79
122
|
const PENDING_SIGN_IN = "feltkit.sign-in-started";
|
|
80
123
|
export class FeltKitClient {
|
|
81
124
|
url;
|
|
@@ -86,20 +129,72 @@ export class FeltKitClient {
|
|
|
86
129
|
#stream = null;
|
|
87
130
|
#connected = false;
|
|
88
131
|
#statusListeners = new Set();
|
|
132
|
+
/** "cookie" or "bearer": see ClientOptions.session. */
|
|
133
|
+
mode;
|
|
134
|
+
/** Cookie mode: the session's CSRF token (from the server; never the session token). */
|
|
135
|
+
#csrf = null;
|
|
136
|
+
/** Cookie mode: a one-time upgrade of a token an older client left in localStorage. */
|
|
137
|
+
#upgrade = null;
|
|
89
138
|
constructor(options = {}) {
|
|
90
139
|
this.url = (options.url ?? "").replace(/\/$/, "");
|
|
91
|
-
this.
|
|
140
|
+
this.mode = options.session ?? (options.tokens || typeof globalThis.document === "undefined" ? "bearer" : "cookie");
|
|
141
|
+
this.tokens = options.tokens ?? (this.mode === "cookie" ? noTokens() : browserTokenStore());
|
|
92
142
|
this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
143
|
+
if (this.mode === "cookie")
|
|
144
|
+
this.#upgrade = this.#upgradeLegacyToken();
|
|
145
|
+
}
|
|
146
|
+
/** An older client kept the session token in localStorage: move it into the HttpOnly cookie once. */
|
|
147
|
+
async #upgradeLegacyToken() {
|
|
148
|
+
let legacy = null;
|
|
149
|
+
try {
|
|
150
|
+
legacy = globalThis.localStorage?.getItem(LEGACY_TOKEN_KEY) ?? null;
|
|
151
|
+
if (legacy)
|
|
152
|
+
globalThis.localStorage?.removeItem(LEGACY_TOKEN_KEY);
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
legacy = null;
|
|
156
|
+
}
|
|
157
|
+
if (!legacy)
|
|
158
|
+
return;
|
|
159
|
+
try {
|
|
160
|
+
const response = await this.#fetch(`${this.url}/api/auth/cookie`, { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json", Authorization: `Bearer ${legacy}` }, body: "{}" });
|
|
161
|
+
const payload = (await response.json().catch(() => null));
|
|
162
|
+
if (payload?.csrf)
|
|
163
|
+
this.#csrf = payload.csrf;
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
/* the old session is dropped; the person signs in again */
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
/** Take what a sign-in (or the session endpoint) returned: a token in bearer mode, the CSRF token in cookie mode. */
|
|
170
|
+
#accept(payload, notify = true) {
|
|
171
|
+
if (payload?.token && this.mode === "bearer")
|
|
172
|
+
this.tokens.set(payload.token);
|
|
173
|
+
if (payload?.csrf)
|
|
174
|
+
this.#csrf = payload.csrf;
|
|
175
|
+
if (notify)
|
|
176
|
+
this.#notifySession();
|
|
93
177
|
}
|
|
94
178
|
get connected() {
|
|
95
179
|
return this.#connected;
|
|
96
180
|
}
|
|
97
181
|
#headers() {
|
|
182
|
+
if (this.mode === "cookie")
|
|
183
|
+
return { "Content-Type": "application/json", "X-FeltKit-Session": "cookie", ...(this.#csrf ? { "X-FeltKit-CSRF": this.#csrf } : {}) };
|
|
98
184
|
const token = this.tokens.get();
|
|
99
185
|
return { "Content-Type": "application/json", ...(token ? { Authorization: `Bearer ${token}` } : {}) };
|
|
100
186
|
}
|
|
101
|
-
|
|
102
|
-
|
|
187
|
+
/** Cookie mode: the CSRF token, asked for once per session. */
|
|
188
|
+
async #ensureCsrf() {
|
|
189
|
+
if (this.mode !== "cookie")
|
|
190
|
+
return;
|
|
191
|
+
await this.#upgrade;
|
|
192
|
+
if (!this.#csrf)
|
|
193
|
+
await this.session().catch(() => undefined);
|
|
194
|
+
}
|
|
195
|
+
async #post(path, body, retried = false) {
|
|
196
|
+
await this.#ensureCsrf();
|
|
197
|
+
const response = await this.#fetch(`${this.url}${path}`, { method: "POST", credentials: "same-origin", headers: this.#headers(), body: JSON.stringify(body) });
|
|
103
198
|
let payload;
|
|
104
199
|
try {
|
|
105
200
|
payload = await response.json();
|
|
@@ -109,6 +204,12 @@ export class FeltKitClient {
|
|
|
109
204
|
}
|
|
110
205
|
if (!payload?.ok) {
|
|
111
206
|
const error = payload?.error ?? { code: "INTERNAL", message: `Request failed (${response.status}).` };
|
|
207
|
+
// The session changed under this page (signed in elsewhere, rotated): take the new CSRF token once.
|
|
208
|
+
if (this.mode === "cookie" && !retried && error.code === "FORBIDDEN" && error.hint === "CSRF") {
|
|
209
|
+
this.#csrf = null;
|
|
210
|
+
await this.session().catch(() => undefined);
|
|
211
|
+
return this.#post(path, body, true);
|
|
212
|
+
}
|
|
112
213
|
if (error.code === "UNAUTHORIZED" && this.tokens.get() && /invalid or expired/.test(error.message)) {
|
|
113
214
|
this.tokens.set(null);
|
|
114
215
|
this.#notifySession();
|
|
@@ -117,6 +218,34 @@ export class FeltKitClient {
|
|
|
117
218
|
}
|
|
118
219
|
return payload;
|
|
119
220
|
}
|
|
221
|
+
/** The absolute URL of a file link (`ctx.services.files.link`), for `<a href>` or `<img src>`. */
|
|
222
|
+
fileUrl(link) {
|
|
223
|
+
return /^https?:\/\//.test(link.url) ? link.url : `${this.url}${link.url}`;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Upload `content` through an upload link (`ctx.services.files.uploadLink`). Resolves with the
|
|
227
|
+
* created file; bind it to your resource with a mutation (check `file.owner` and `file.metadata`).
|
|
228
|
+
*/
|
|
229
|
+
async uploadFile(link, content, options = {}) {
|
|
230
|
+
const named = content.name;
|
|
231
|
+
const name = options.name ?? (typeof named === "string" ? named : undefined);
|
|
232
|
+
const type = options.contentType ?? (content.type || "application/octet-stream");
|
|
233
|
+
const response = await this.#fetch(this.fileUrl(link), {
|
|
234
|
+
method: "PUT",
|
|
235
|
+
headers: { "Content-Type": type, ...(name ? { "X-File-Name": encodeURIComponent(name) } : {}) },
|
|
236
|
+
body: content,
|
|
237
|
+
});
|
|
238
|
+
let payload;
|
|
239
|
+
try {
|
|
240
|
+
payload = await response.json();
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
throw new FeltKitClientError({ code: "UNAVAILABLE", message: `The server answered ${response.status} without JSON.` });
|
|
244
|
+
}
|
|
245
|
+
if (!payload?.ok)
|
|
246
|
+
throw new FeltKitClientError(payload?.error ?? { code: "INTERNAL", message: `Upload failed (${response.status}).` });
|
|
247
|
+
return payload.file;
|
|
248
|
+
}
|
|
120
249
|
/** Run a query. Resolves with its value. */
|
|
121
250
|
async query(fn, args) {
|
|
122
251
|
return (await this.queryWithReads(fn, args)).value;
|
|
@@ -130,14 +259,17 @@ export class FeltKitClient {
|
|
|
130
259
|
return (await this.#post(`/api/mutation/${encodeURIComponent(fn.name)}`, { args: args ?? {} })).value;
|
|
131
260
|
}
|
|
132
261
|
async session() {
|
|
133
|
-
|
|
134
|
-
|
|
262
|
+
await this.#upgrade;
|
|
263
|
+
const response = await this.#fetch(`${this.url}/api/session`, { credentials: "same-origin", headers: this.#headers() });
|
|
264
|
+
const info = (await response.json());
|
|
265
|
+
if (this.mode === "cookie")
|
|
266
|
+
this.#csrf = info.csrf ?? null;
|
|
267
|
+
return info;
|
|
135
268
|
}
|
|
136
269
|
/** Development only: sign in as a dev user declared in feltkit({ dev: { users } }). */
|
|
137
270
|
async signInAsDevUser(userId) {
|
|
138
271
|
const payload = await this.#post("/api/auth/dev", { userId });
|
|
139
|
-
this
|
|
140
|
-
this.#notifySession();
|
|
272
|
+
this.#accept(payload);
|
|
141
273
|
return payload.principal;
|
|
142
274
|
}
|
|
143
275
|
/**
|
|
@@ -147,10 +279,9 @@ export class FeltKitClient {
|
|
|
147
279
|
*/
|
|
148
280
|
async signUp(input) {
|
|
149
281
|
const payload = await this.#post("/api/auth/signup", input);
|
|
150
|
-
if (!payload.
|
|
282
|
+
if (!payload.principal || payload.verificationRequired)
|
|
151
283
|
return null;
|
|
152
|
-
this
|
|
153
|
-
this.#notifySession();
|
|
284
|
+
this.#accept(payload);
|
|
154
285
|
return payload.principal;
|
|
155
286
|
}
|
|
156
287
|
/** Account e-mail: send a password reset link to this address (same answer whether or not it has an account). */
|
|
@@ -160,8 +291,7 @@ export class FeltKitClient {
|
|
|
160
291
|
/** Set a new password with the token from a reset link, and sign in. Every other session of the account ends. */
|
|
161
292
|
async resetPassword(token, password) {
|
|
162
293
|
const payload = await this.#post("/api/auth/reset", { token, password });
|
|
163
|
-
this
|
|
164
|
-
this.#notifySession();
|
|
294
|
+
this.#accept(payload);
|
|
165
295
|
return payload.principal;
|
|
166
296
|
}
|
|
167
297
|
/** Account e-mail: send a new verification link to this address. */
|
|
@@ -174,6 +304,154 @@ export class FeltKitClient {
|
|
|
174
304
|
this.#notifySession();
|
|
175
305
|
return { email: payload.email };
|
|
176
306
|
}
|
|
307
|
+
/** Your account: address, verification, name, whether a password is set, connected providers. */
|
|
308
|
+
async account() {
|
|
309
|
+
const response = await this.#fetch(`${this.url}/api/account`, { credentials: "same-origin", headers: this.#headers() });
|
|
310
|
+
const payload = (await response.json());
|
|
311
|
+
if (!payload.ok)
|
|
312
|
+
throw new FeltKitClientError(payload.error ?? { code: "INTERNAL", message: "Could not load the account." });
|
|
313
|
+
return payload.account;
|
|
314
|
+
}
|
|
315
|
+
async updateProfile(input) {
|
|
316
|
+
await this.#post("/api/account/profile", input);
|
|
317
|
+
this.#notifySession();
|
|
318
|
+
}
|
|
319
|
+
/** Change your password. Every other session ends; this one continues with a new token. */
|
|
320
|
+
async changePassword(input) {
|
|
321
|
+
this.#accept(await this.#post("/api/account/password", input));
|
|
322
|
+
}
|
|
323
|
+
/** Ask to move your account to a new address: it changes when the link sent there is opened. */
|
|
324
|
+
async requestEmailChange(email) {
|
|
325
|
+
return { message: (await this.#post("/api/account/email", { email })).message };
|
|
326
|
+
}
|
|
327
|
+
/** Confirm a new address with the token from its link (handleRedirect does this for you). */
|
|
328
|
+
async confirmEmailChange(token) {
|
|
329
|
+
const payload = await this.#post("/api/account/email/confirm", { token });
|
|
330
|
+
this.#notifySession();
|
|
331
|
+
return { email: payload.email };
|
|
332
|
+
}
|
|
333
|
+
async unlinkProvider(provider) {
|
|
334
|
+
await this.#post("/api/account/providers/unlink", { provider });
|
|
335
|
+
this.#notifySession();
|
|
336
|
+
}
|
|
337
|
+
/** Your active sessions. `current` is this one. */
|
|
338
|
+
async sessions() {
|
|
339
|
+
const response = await this.#fetch(`${this.url}/api/auth/sessions`, { credentials: "same-origin", headers: this.#headers() });
|
|
340
|
+
const payload = (await response.json());
|
|
341
|
+
if (!payload.ok)
|
|
342
|
+
throw new FeltKitClientError(payload.error ?? { code: "INTERNAL", message: "Could not load sessions." });
|
|
343
|
+
return payload.sessions;
|
|
344
|
+
}
|
|
345
|
+
/** End one of your sessions by ref. Ending this one signs you out. */
|
|
346
|
+
async revokeSession(ref) {
|
|
347
|
+
const payload = await this.#post("/api/auth/sessions/revoke", { ref });
|
|
348
|
+
if (payload.signedOut)
|
|
349
|
+
this.#signedOut();
|
|
350
|
+
}
|
|
351
|
+
/** End your other sessions (`keepCurrent`, the default), or all of them (and sign out here). */
|
|
352
|
+
async signOutEverywhere(options = {}) {
|
|
353
|
+
const keepCurrent = options.keepCurrent !== false;
|
|
354
|
+
const payload = await this.#post("/api/auth/sessions/revoke", { all: true, keepCurrent });
|
|
355
|
+
if (payload.signedOut)
|
|
356
|
+
this.#signedOut();
|
|
357
|
+
return payload.revoked;
|
|
358
|
+
}
|
|
359
|
+
#signedOut() {
|
|
360
|
+
this.tokens.set(null);
|
|
361
|
+
this.#csrf = null;
|
|
362
|
+
this.#notifySession();
|
|
363
|
+
}
|
|
364
|
+
// ── Tenancy (auth.tenant) ────────────────────────────────────────────────────
|
|
365
|
+
async #get(path) {
|
|
366
|
+
await this.#upgrade;
|
|
367
|
+
const response = await this.#fetch(`${this.url}${path}`, { credentials: "same-origin", headers: this.#headers() });
|
|
368
|
+
const payload = (await response.json().catch(() => null));
|
|
369
|
+
if (!payload?.ok)
|
|
370
|
+
throw new FeltKitClientError(payload?.error ?? { code: "UNAVAILABLE", message: `The server answered ${response.status}.` });
|
|
371
|
+
return payload;
|
|
372
|
+
}
|
|
373
|
+
/** Your tenants, the one this session works in, and what you may do there. */
|
|
374
|
+
async tenants() {
|
|
375
|
+
const { tenants, current, settings } = await this.#get("/api/tenants");
|
|
376
|
+
return { tenants, current, settings };
|
|
377
|
+
}
|
|
378
|
+
/** Create a tenant (you hold its top role) and switch to it. */
|
|
379
|
+
async createTenant(name) {
|
|
380
|
+
const payload = await this.#post("/api/tenants", { name });
|
|
381
|
+
this.#accept(payload);
|
|
382
|
+
return payload.tenant;
|
|
383
|
+
}
|
|
384
|
+
/** Work in another of your tenants (null: none). Every live query re-runs for it. */
|
|
385
|
+
async switchTenant(tenantId) {
|
|
386
|
+
const payload = await this.#post("/api/tenants/switch", { tenantId });
|
|
387
|
+
this.#accept(payload);
|
|
388
|
+
return payload.tenant;
|
|
389
|
+
}
|
|
390
|
+
async members() {
|
|
391
|
+
return (await this.#get("/api/tenants/current/members")).members;
|
|
392
|
+
}
|
|
393
|
+
async setMemberRole(principalId, role) {
|
|
394
|
+
await this.#post("/api/tenants/current/members/role", { principalId, role });
|
|
395
|
+
this.#notifySession();
|
|
396
|
+
}
|
|
397
|
+
/** Add an agent or service (an operator-issued identity) to the current tenant. People are invited instead. */
|
|
398
|
+
async addMember(principalId, role) {
|
|
399
|
+
await this.#post("/api/tenants/current/members/add", { principalId, role });
|
|
400
|
+
}
|
|
401
|
+
async setMemberClaims(principalId, claims) {
|
|
402
|
+
await this.#post("/api/tenants/current/members/claims", { principalId, claims });
|
|
403
|
+
this.#notifySession();
|
|
404
|
+
}
|
|
405
|
+
async removeMember(principalId) {
|
|
406
|
+
await this.#post("/api/tenants/current/members/remove", { principalId });
|
|
407
|
+
}
|
|
408
|
+
/** Leave the current tenant; the session moves to your next one (or none). */
|
|
409
|
+
async leaveTenant() {
|
|
410
|
+
const payload = await this.#post("/api/tenants/current/leave", {});
|
|
411
|
+
this.#accept(payload);
|
|
412
|
+
return payload.tenant;
|
|
413
|
+
}
|
|
414
|
+
async renameTenant(name) {
|
|
415
|
+
await this.#post("/api/tenants/current/rename", { name });
|
|
416
|
+
this.#notifySession();
|
|
417
|
+
}
|
|
418
|
+
async invitations() {
|
|
419
|
+
return (await this.#get("/api/tenants/current/invitations")).invitations;
|
|
420
|
+
}
|
|
421
|
+
/** Invite an address with a role. `link` is the invitation link (to share yourself); `sent` says whether it was e-mailed. */
|
|
422
|
+
async invite(input) {
|
|
423
|
+
const payload = await this.#post("/api/tenants/current/invitations", input);
|
|
424
|
+
return { invitation: payload.invitation, link: payload.link, sent: payload.sent };
|
|
425
|
+
}
|
|
426
|
+
async revokeInvitation(id) {
|
|
427
|
+
await this.#post("/api/tenants/current/invitations/revoke", { id });
|
|
428
|
+
}
|
|
429
|
+
/** What an invitation link is for, before accepting it (no sign-in needed). */
|
|
430
|
+
async previewInvitation(token) {
|
|
431
|
+
return (await this.#post("/api/invitations/preview", { token })).invitation;
|
|
432
|
+
}
|
|
433
|
+
/** Accept an invitation (signed in with the invited address) and switch to its tenant. */
|
|
434
|
+
async acceptInvitation(token) {
|
|
435
|
+
const payload = await this.#post("/api/invitations/accept", { token });
|
|
436
|
+
this.#accept(payload);
|
|
437
|
+
return payload.tenant;
|
|
438
|
+
}
|
|
439
|
+
/** Magic link: e-mail a sign-in link and code to this address (same answer whether or not it can sign in). */
|
|
440
|
+
async requestMagicLink(email) {
|
|
441
|
+
return { message: (await this.#post("/api/auth/magic/request", { email })).message };
|
|
442
|
+
}
|
|
443
|
+
/** Magic link: sign in with the 8-digit code from the e-mail (typed on another device than the one that opened it). */
|
|
444
|
+
async signInWithCode(email, code) {
|
|
445
|
+
const payload = await this.#post("/api/auth/magic", { email, code });
|
|
446
|
+
this.#accept(payload);
|
|
447
|
+
return payload.principal;
|
|
448
|
+
}
|
|
449
|
+
/** Magic link: sign in with the token from the link (handleRedirect does this for you). */
|
|
450
|
+
async signInWithLink(token) {
|
|
451
|
+
const payload = await this.#post("/api/auth/magic", { token });
|
|
452
|
+
this.#accept(payload);
|
|
453
|
+
return payload.principal;
|
|
454
|
+
}
|
|
177
455
|
/** Sign in with a provider from `session().accounts.providers`: leaves the page for its consent screen. */
|
|
178
456
|
signInWith(provider, returnPath = globalThis.location?.pathname ?? "/") {
|
|
179
457
|
// Marks this browser as the one signing in: handleRedirect() takes a session from the URL only then.
|
|
@@ -200,9 +478,32 @@ export class FeltKitClient {
|
|
|
200
478
|
const error = params.get("feltkit-error");
|
|
201
479
|
const reset = params.get("feltkit-reset");
|
|
202
480
|
const verify = params.get("feltkit-verify");
|
|
203
|
-
|
|
481
|
+
const magic = params.get("feltkit-magic-link");
|
|
482
|
+
const emailChange = params.get("feltkit-email-change");
|
|
483
|
+
const invitation = params.get("feltkit-invitation");
|
|
484
|
+
if (!session && !error && !reset && !verify && !magic && !emailChange && !invitation)
|
|
204
485
|
return null;
|
|
205
486
|
clear();
|
|
487
|
+
// An invitation is not accepted here: the person may need to sign in (as the invited address) first.
|
|
488
|
+
if (invitation)
|
|
489
|
+
return { kind: "invitation", token: invitation };
|
|
490
|
+
if (magic) {
|
|
491
|
+
try {
|
|
492
|
+
await this.signInWithLink(magic);
|
|
493
|
+
return { kind: "signed-in" };
|
|
494
|
+
}
|
|
495
|
+
catch (e) {
|
|
496
|
+
return { kind: "magic-link-failed", message: e instanceof Error ? e.message : String(e) };
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
if (emailChange) {
|
|
500
|
+
try {
|
|
501
|
+
return { kind: "email-changed", ...(await this.confirmEmailChange(emailChange)) };
|
|
502
|
+
}
|
|
503
|
+
catch (e) {
|
|
504
|
+
return { kind: "email-change-failed", message: e instanceof Error ? e.message : String(e) };
|
|
505
|
+
}
|
|
506
|
+
}
|
|
206
507
|
if (session) {
|
|
207
508
|
// Only a sign-in this browser started (signInWith) is accepted, within 15 minutes: a link
|
|
208
509
|
// carrying someone else's session must not sign this person in as them.
|
|
@@ -233,8 +534,7 @@ export class FeltKitClient {
|
|
|
233
534
|
/** Built-in accounts: sign in with an e-mail address and password. */
|
|
234
535
|
async signIn(input) {
|
|
235
536
|
const payload = await this.#post("/api/auth/signin", input);
|
|
236
|
-
this
|
|
237
|
-
this.#notifySession();
|
|
537
|
+
this.#accept(payload);
|
|
238
538
|
return payload.principal;
|
|
239
539
|
}
|
|
240
540
|
/** Use a session token obtained elsewhere (your login flow, `feltkit session create`). */
|
|
@@ -248,6 +548,7 @@ export class FeltKitClient {
|
|
|
248
548
|
}
|
|
249
549
|
finally {
|
|
250
550
|
this.tokens.set(null);
|
|
551
|
+
this.#csrf = null;
|
|
251
552
|
this.#notifySession();
|
|
252
553
|
}
|
|
253
554
|
}
|
|
@@ -299,7 +600,7 @@ export class FeltKitClient {
|
|
|
299
600
|
while (!controller.signal.aborted) {
|
|
300
601
|
try {
|
|
301
602
|
const token = this.tokens.get();
|
|
302
|
-
const response = await this.#fetch(`${this.url}/api/events`, { headers: { Accept: "text/event-stream", ...(token ? { Authorization: `Bearer ${token}` } : {}) }, signal: controller.signal });
|
|
603
|
+
const response = await this.#fetch(`${this.url}/api/events`, { credentials: "same-origin", headers: { Accept: "text/event-stream", ...(token ? { Authorization: `Bearer ${token}` } : {}) }, signal: controller.signal });
|
|
303
604
|
if (response.status === 401) {
|
|
304
605
|
// Not signed in: nothing to stream until the session changes (which reconnects).
|
|
305
606
|
await response.body?.cancel();
|
|
@@ -330,7 +631,7 @@ export class FeltKitClient {
|
|
|
330
631
|
continue;
|
|
331
632
|
const payload = JSON.parse(data);
|
|
332
633
|
if (event === "change")
|
|
333
|
-
this.#emit(payload.collections);
|
|
634
|
+
this.#emit(payload.collections, payload.keys && typeof payload.keys === "object" ? payload.keys : undefined);
|
|
334
635
|
// After a reconnect (or a backend reload) anything may have changed.
|
|
335
636
|
if ((event === "ready" && !first) || event === "reload")
|
|
336
637
|
this.#emit(["*"]);
|
|
@@ -346,21 +647,77 @@ export class FeltKitClient {
|
|
|
346
647
|
this.#setConnected(false);
|
|
347
648
|
if (controller.signal.aborted)
|
|
348
649
|
break;
|
|
349
|
-
|
|
350
|
-
|
|
650
|
+
// Back off, but reconnect at once when the browser says the network is back or the page is
|
|
651
|
+
// visible again: a client that comes back online catches up in ~one round trip, not ~10 s.
|
|
652
|
+
const woken = await waitOrWake(delay, controller.signal);
|
|
653
|
+
delay = woken ? 500 : Math.min(delay * 2, 10_000);
|
|
351
654
|
this.#emit(["*"]);
|
|
352
655
|
}
|
|
353
656
|
}
|
|
354
|
-
#emit(collections) {
|
|
657
|
+
#emit(collections, keys) {
|
|
355
658
|
for (const listener of this.#changeListeners)
|
|
356
|
-
listener(collections);
|
|
659
|
+
listener(collections, keys);
|
|
357
660
|
}
|
|
358
661
|
/**
|
|
359
662
|
* Run a query now and again whenever a collection it read changes (or the session
|
|
360
663
|
* changes). Returns a function that stops watching.
|
|
361
664
|
*/
|
|
665
|
+
/**
|
|
666
|
+
* Receive an ephemeral event (`app.event`) while subscribed: at most once, only events published
|
|
667
|
+
* after the subscription is open, only for `scope` when given (a subscription without a scope
|
|
668
|
+
* receives only unscoped events). Uses AppPort's event stream (`/appport/events`), which checks
|
|
669
|
+
* the caller may observe it on subscribe and before every delivery. Reconnects like the change
|
|
670
|
+
* stream (at once when the network returns). Returns a function that stops it.
|
|
671
|
+
*/
|
|
672
|
+
subscribe(event, options, listener) {
|
|
673
|
+
const name = typeof event === "string" ? event : event.name;
|
|
674
|
+
const controller = new AbortController();
|
|
675
|
+
const query = new URLSearchParams({ events: name, ...(options.scope !== undefined ? { scope: options.scope } : {}) });
|
|
676
|
+
void (async () => {
|
|
677
|
+
let delay = 500;
|
|
678
|
+
while (!controller.signal.aborted) {
|
|
679
|
+
try {
|
|
680
|
+
const token = this.tokens.get();
|
|
681
|
+
const response = await this.#fetch(`${this.url}/appport/events?${query}`, { credentials: "same-origin", headers: { Accept: "text/event-stream", ...(token ? { Authorization: `Bearer ${token}` } : {}) }, signal: controller.signal });
|
|
682
|
+
if (!response.ok || !response.body)
|
|
683
|
+
throw new Error(`event stream answered ${response.status}`);
|
|
684
|
+
delay = 500;
|
|
685
|
+
const reader = response.body.getReader();
|
|
686
|
+
const decoder = new TextDecoder();
|
|
687
|
+
let buffer = "";
|
|
688
|
+
for (;;) {
|
|
689
|
+
const { value, done } = await reader.read();
|
|
690
|
+
if (done)
|
|
691
|
+
break;
|
|
692
|
+
buffer += decoder.decode(value, { stream: true });
|
|
693
|
+
let index;
|
|
694
|
+
while ((index = buffer.indexOf("\n\n")) >= 0) {
|
|
695
|
+
const frame = buffer.slice(0, index);
|
|
696
|
+
buffer = buffer.slice(index + 2);
|
|
697
|
+
const data = /^data: (.+)$/m.exec(frame)?.[1];
|
|
698
|
+
if (!data)
|
|
699
|
+
continue;
|
|
700
|
+
const envelope = JSON.parse(data);
|
|
701
|
+
if (envelope.type !== "event" || envelope.event?.name !== name)
|
|
702
|
+
continue;
|
|
703
|
+
listener(envelope.payload, { ...(envelope.scope !== undefined ? { scope: envelope.scope } : {}), eventId: envelope.eventId, timestamp: envelope.timestamp });
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
catch {
|
|
708
|
+
if (controller.signal.aborted)
|
|
709
|
+
break;
|
|
710
|
+
}
|
|
711
|
+
if (controller.signal.aborted)
|
|
712
|
+
break;
|
|
713
|
+
const woken = await waitOrWake(delay, controller.signal);
|
|
714
|
+
delay = woken ? 500 : Math.min(delay * 2, 10_000);
|
|
715
|
+
}
|
|
716
|
+
})();
|
|
717
|
+
return () => controller.abort();
|
|
718
|
+
}
|
|
362
719
|
watchQuery(fn, args, handlers) {
|
|
363
|
-
let reads =
|
|
720
|
+
let reads = parseReads(["*"]);
|
|
364
721
|
let stopped = false;
|
|
365
722
|
let running = false;
|
|
366
723
|
let again = false;
|
|
@@ -372,7 +729,7 @@ export class FeltKitClient {
|
|
|
372
729
|
running = true;
|
|
373
730
|
try {
|
|
374
731
|
const result = await this.queryWithReads(fn, args);
|
|
375
|
-
reads =
|
|
732
|
+
reads = parseReads(result.reads);
|
|
376
733
|
if (!stopped)
|
|
377
734
|
handlers.next(result.value);
|
|
378
735
|
}
|
|
@@ -388,8 +745,8 @@ export class FeltKitClient {
|
|
|
388
745
|
}
|
|
389
746
|
}
|
|
390
747
|
};
|
|
391
|
-
const offChange = this.onChange((collections) => {
|
|
392
|
-
if (
|
|
748
|
+
const offChange = this.onChange((collections, keys) => {
|
|
749
|
+
if (changeAffects(reads, collections, keys))
|
|
393
750
|
void run();
|
|
394
751
|
});
|
|
395
752
|
const offSession = this.onSessionChange(() => void run());
|
|
@@ -401,6 +758,33 @@ export class FeltKitClient {
|
|
|
401
758
|
};
|
|
402
759
|
}
|
|
403
760
|
}
|
|
761
|
+
/**
|
|
762
|
+
* Wait `ms`, or less: resolves true early on `online`, or on `visibilitychange` to visible, where the
|
|
763
|
+
* environment has them (browsers); false after the full wait or on abort. No-op listeners elsewhere.
|
|
764
|
+
*/
|
|
765
|
+
export function waitOrWake(ms, signal, target = globalThis, doc = globalThis.document) {
|
|
766
|
+
return new Promise((resolve) => {
|
|
767
|
+
let done = false;
|
|
768
|
+
const finish = (woken) => {
|
|
769
|
+
if (done)
|
|
770
|
+
return;
|
|
771
|
+
done = true;
|
|
772
|
+
clearTimeout(timer);
|
|
773
|
+
target?.removeEventListener?.("online", online);
|
|
774
|
+
doc?.removeEventListener?.("visibilitychange", visible);
|
|
775
|
+
signal.removeEventListener("abort", aborted);
|
|
776
|
+
resolve(woken);
|
|
777
|
+
};
|
|
778
|
+
const online = () => finish(true);
|
|
779
|
+
const visible = () => { if (doc?.visibilityState === "visible")
|
|
780
|
+
finish(true); };
|
|
781
|
+
const aborted = () => finish(false);
|
|
782
|
+
const timer = setTimeout(() => finish(false), ms);
|
|
783
|
+
target?.addEventListener?.("online", online);
|
|
784
|
+
doc?.addEventListener?.("visibilitychange", visible);
|
|
785
|
+
signal.addEventListener("abort", aborted, { once: true });
|
|
786
|
+
});
|
|
787
|
+
}
|
|
404
788
|
export function createClient(options) {
|
|
405
789
|
return new FeltKitClient(options);
|
|
406
790
|
}
|