@chabi/js 0.0.0-stage → 0.2.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.
@@ -0,0 +1,620 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/browser.ts
21
+ var browser_exports = {};
22
+ __export(browser_exports, {
23
+ Chabi: () => Chabi,
24
+ ChabiError: () => ChabiError,
25
+ describeError: () => describeError,
26
+ describeResponse: () => describeResponse,
27
+ signInButton: () => signInButton
28
+ });
29
+ module.exports = __toCommonJS(browser_exports);
30
+
31
+ // src/errors.ts
32
+ var ChabiError = class extends Error {
33
+ info;
34
+ constructor(info) {
35
+ super(info.message);
36
+ this.name = "ChabiError";
37
+ this.info = info;
38
+ }
39
+ };
40
+ var MESSAGES = {
41
+ out_of_credits: "You're out of Chabi credits.",
42
+ app_limit: "You've reached the monthly limit you set for this app on Chabi.",
43
+ signed_out: "Sign in with Chabi to continue.",
44
+ access_denied: "You chose not to let this app use your Chabi plan.",
45
+ rate_limited: "Too many requests. Please wait a moment and try again.",
46
+ app_suspended: "This app can't use Chabi right now.",
47
+ bad_request: "Chabi couldn't handle that request.",
48
+ provider_error: "The AI provider is having trouble right now. Please try again.",
49
+ network: "Couldn't reach Chabi. Check your connection and try again.",
50
+ unknown: "Something went wrong. Please try again."
51
+ };
52
+ var str = (v) => typeof v === "string" && v ? v : void 0;
53
+ function kindOf(status, code) {
54
+ if (code === "insufficient_credits") return "out_of_credits";
55
+ if (code === "app_limit_reached") return "app_limit";
56
+ if (code === "app_suspended") return "app_suspended";
57
+ if (status === 401) return "signed_out";
58
+ if (status === 402) return "out_of_credits";
59
+ if (status === 403) return "app_suspended";
60
+ if (status === 429) return "rate_limited";
61
+ if (status >= 500) return "provider_error";
62
+ if (status >= 400) return "bad_request";
63
+ return "unknown";
64
+ }
65
+ function build(status, body, retryAfterHeader) {
66
+ const code = str(body?.code);
67
+ const kind = kindOf(status, code);
68
+ const info = { kind, status, message: MESSAGES[kind] };
69
+ if (code) info.code = code;
70
+ const upgradeUrl = str(body?.upgrade_url);
71
+ const manageUrl = str(body?.manage_url);
72
+ if (upgradeUrl) info.upgradeUrl = upgradeUrl;
73
+ if (manageUrl) info.manageUrl = manageUrl;
74
+ const retryAfter = Number(retryAfterHeader);
75
+ if (kind === "rate_limited" && retryAfterHeader && Number.isFinite(retryAfter)) info.retryAfter = retryAfter;
76
+ return info;
77
+ }
78
+ function describeError(e) {
79
+ if (e instanceof ChabiError) return e.info.message ? e.info : { ...e.info, message: MESSAGES[e.info.kind] };
80
+ const cause = e?.cause;
81
+ if (cause instanceof ChabiError) return describeError(cause);
82
+ const x = e;
83
+ if (x && typeof x === "object" && typeof x.status === "number") {
84
+ const outer = x.error;
85
+ const body = outer && typeof outer.error === "object" ? outer.error : outer;
86
+ const headers = x.headers;
87
+ const retry = typeof headers?.get === "function" ? headers.get("retry-after") : headers?.["retry-after"];
88
+ return build(x.status, body, retry);
89
+ }
90
+ const ctor = x?.constructor?.name;
91
+ if (e instanceof TypeError || typeof ctor === "string" && /Connection|Timeout/.test(ctor)) {
92
+ return { kind: "network", status: 0, message: MESSAGES.network };
93
+ }
94
+ return { kind: "unknown", status: 0, message: MESSAGES.unknown };
95
+ }
96
+ async function describeResponse(res) {
97
+ const body = await res.clone().json().catch(() => null);
98
+ return build(res.status, body?.error, res.headers.get("retry-after"));
99
+ }
100
+
101
+ // src/client.ts
102
+ var DEFAULT_BASE_URL = "https://chabi.dev";
103
+ var SIGN_OUT_CODES = /* @__PURE__ */ new Set(["missing_token", "token_revoked", "grant_revoked", "unknown_app"]);
104
+ var PLACEHOLDER_KEY = "chabi";
105
+ var ChabiBase = class {
106
+ constructor(core) {
107
+ this.core = core;
108
+ this.fetch = (input, init) => this.authorizedFetch(input, init);
109
+ }
110
+ core;
111
+ /** A fetch for the official SDKs. It only sets Authorization: bodies, models and other headers pass through. */
112
+ fetch;
113
+ get signedIn() {
114
+ return this.core.signedIn;
115
+ }
116
+ /** Options for `new OpenAI(...)`. In a browser, add `dangerouslyAllowBrowser: true`. */
117
+ openai() {
118
+ return { baseURL: `${this.core.baseUrl}/v1`, apiKey: PLACEHOLDER_KEY, fetch: this.fetch };
119
+ }
120
+ /** Options for `new Anthropic(...)`. In a browser, add `dangerouslyAllowBrowser: true`. */
121
+ anthropic() {
122
+ return { baseURL: this.core.baseUrl, apiKey: PLACEHOLDER_KEY, fetch: this.fetch };
123
+ }
124
+ /** The user's credit balance. */
125
+ async credits() {
126
+ const body = await this.getJson("/v1/credits");
127
+ return body.balance_credits;
128
+ }
129
+ /** The display name on the user's Chabi account, or null if they haven't set one. */
130
+ async me() {
131
+ const body = await this.getJson("/v1/me");
132
+ return { name: body.name ?? null };
133
+ }
134
+ /** Signs the user out of this app on this device. */
135
+ signOut() {
136
+ return this.core.end("signed_out");
137
+ }
138
+ /** Called when the user is signed in or out, here or in another tab. Returns a function that unsubscribes. */
139
+ onChange(listener) {
140
+ return this.core.onChange(listener);
141
+ }
142
+ async getJson(path) {
143
+ const res = await this.fetch(`${this.core.baseUrl}${path}`);
144
+ if (!res.ok) throw new ChabiError(await describeResponse(res));
145
+ return res.json();
146
+ }
147
+ async authorizedFetch(input, init) {
148
+ if (!this.isChabi(input)) return this.core.fetchImpl(input, init);
149
+ let token = await this.core.accessToken();
150
+ if (!token) return signedOutResponse();
151
+ const spare = input instanceof Request ? input.clone() : null;
152
+ const replayable = !(init?.body instanceof ReadableStream);
153
+ let res = await this.send(input, init, token);
154
+ if (res.status !== 401) return res;
155
+ let code = await errorCode(res);
156
+ if (code === "invalid_token") {
157
+ const fresh = await this.core.refreshAfterReject(token);
158
+ if (!fresh || !replayable) return res;
159
+ token = fresh;
160
+ res = await this.send(spare ?? input, init, token);
161
+ if (res.status !== 401) return res;
162
+ code = await errorCode(res);
163
+ }
164
+ if (code && SIGN_OUT_CODES.has(code)) await this.core.end("access_removed");
165
+ return res;
166
+ }
167
+ isChabi(input) {
168
+ try {
169
+ const url = new URL(input instanceof Request ? input.url : String(input));
170
+ return url.origin === new URL(this.core.baseUrl).origin;
171
+ } catch {
172
+ return false;
173
+ }
174
+ }
175
+ send(input, init, token) {
176
+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));
177
+ headers.set("Authorization", `Bearer ${token}`);
178
+ headers.delete("x-api-key");
179
+ return this.core.fetchImpl(input, { ...init, headers });
180
+ }
181
+ };
182
+ var signedOutResponse = () => new Response(JSON.stringify({ error: { code: "missing_token", message: "Sign in with Chabi to continue." } }), {
183
+ status: 401,
184
+ headers: { "Content-Type": "application/json", "x-should-retry": "false" }
185
+ });
186
+ async function errorCode(res) {
187
+ const body = await res.clone().json().catch(() => null);
188
+ return typeof body?.error?.code === "string" ? body.error.code : void 0;
189
+ }
190
+
191
+ // src/pkce.ts
192
+ var base64url = (bytes) => {
193
+ let s = "";
194
+ for (const b of bytes) s += String.fromCharCode(b);
195
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
196
+ };
197
+ function randomString(bytes = 32) {
198
+ return base64url(globalThis.crypto.getRandomValues(new Uint8Array(bytes)));
199
+ }
200
+ async function challengeFor(verifier) {
201
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
202
+ return base64url(new Uint8Array(digest));
203
+ }
204
+
205
+ // src/session.ts
206
+ var REFRESH_EARLY_MS = 6e4;
207
+ var SessionCore = class {
208
+ baseUrl;
209
+ clientId;
210
+ storage;
211
+ lock;
212
+ /** The underlying fetch, for requests that carry the user's token (see ChabiBase.fetch). */
213
+ fetchImpl;
214
+ now;
215
+ tokens = null;
216
+ // Bumped by sign-in and sign-out, so a refresh that finishes afterwards can't bring an old session back.
217
+ generation = 0;
218
+ listeners = /* @__PURE__ */ new Set();
219
+ constructor(opts) {
220
+ this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
221
+ this.clientId = opts.clientId;
222
+ this.storage = opts.storage;
223
+ this.lock = opts.lock;
224
+ this.fetchImpl = opts.fetch ?? ((input, init) => globalThis.fetch(input, init));
225
+ this.now = opts.now ?? Date.now;
226
+ const loaded = this.storage.load();
227
+ if (!isPromise(loaded)) this.tokens = loaded;
228
+ else loaded.catch(() => {
229
+ });
230
+ }
231
+ get signedIn() {
232
+ return this.tokens !== null;
233
+ }
234
+ /** Reads storage into memory. Needed once at start for asynchronous storage (Node, Electron). */
235
+ async load() {
236
+ this.tokens = await this.storage.load();
237
+ }
238
+ /** The access token to send, refreshed first when it's within a minute of expiring. Null when signed out. */
239
+ async accessToken() {
240
+ const t = this.tokens;
241
+ if (!t) return null;
242
+ if (t.expiresAt - this.now() > REFRESH_EARLY_MS) return t.accessToken;
243
+ return this.refreshLocked(t.refreshToken, null);
244
+ }
245
+ /** The gateway said `rejected` is no longer valid: refresh, unless that already happened since it was sent. */
246
+ async refreshAfterReject(rejected) {
247
+ const t = this.tokens;
248
+ if (!t) return null;
249
+ if (t.accessToken !== rejected) return t.accessToken;
250
+ return this.refreshLocked(t.refreshToken, rejected);
251
+ }
252
+ /** Swaps the code from the sign-in redirect for tokens, saves them and tells listeners. */
253
+ async exchangeCode(p) {
254
+ const res = await this.tokenRequest({
255
+ grant_type: "authorization_code",
256
+ code: p.code,
257
+ redirect_uri: p.redirectUri,
258
+ client_id: this.clientId,
259
+ code_verifier: p.verifier
260
+ });
261
+ const tokens = res.ok ? await this.parseTokens(res) : null;
262
+ if (!tokens) {
263
+ throw new ChabiError({ kind: "signed_out", status: res.status, code: "sign_in_failed", message: "Sign-in didn't complete. Please try again." });
264
+ }
265
+ this.generation += 1;
266
+ await this.storage.save(tokens);
267
+ this.tokens = tokens;
268
+ this.emit(true, "signed_in");
269
+ }
270
+ /** Forgets the tokens (memory and storage) and tells listeners why. */
271
+ async end(reason) {
272
+ this.generation += 1;
273
+ const was = this.tokens !== null;
274
+ this.tokens = null;
275
+ await this.storage.clear();
276
+ if (was) this.emit(false, reason);
277
+ }
278
+ /** Another tab changed the stored tokens: take its copy, and tell listeners if that signed the user in or out. */
279
+ adopt(tokens) {
280
+ const was = this.tokens !== null;
281
+ if (!tokens) this.generation += 1;
282
+ this.tokens = tokens;
283
+ if (was !== (tokens !== null)) this.emit(tokens !== null, tokens ? "signed_in" : "signed_out");
284
+ }
285
+ onChange(listener) {
286
+ this.listeners.add(listener);
287
+ return () => void this.listeners.delete(listener);
288
+ }
289
+ emit(signedIn, reason) {
290
+ for (const l of [...this.listeners]) {
291
+ try {
292
+ l(signedIn, reason);
293
+ } catch {
294
+ }
295
+ }
296
+ }
297
+ refreshLocked(startedWith, rejected) {
298
+ return this.lock(async () => {
299
+ const generation = this.generation;
300
+ const stored = await this.storage.load();
301
+ if (generation !== this.generation) return null;
302
+ if (!stored) {
303
+ this.adopt(null);
304
+ return null;
305
+ }
306
+ if (stored.refreshToken !== startedWith) {
307
+ this.tokens = stored;
308
+ return stored.accessToken;
309
+ }
310
+ if (rejected === null && stored.expiresAt - this.now() > REFRESH_EARLY_MS) {
311
+ this.tokens = stored;
312
+ return stored.accessToken;
313
+ }
314
+ const res = await this.tokenRequest({ grant_type: "refresh_token", refresh_token: stored.refreshToken, client_id: this.clientId });
315
+ if (generation !== this.generation) return null;
316
+ if (!res.ok) {
317
+ if (res.status === 400 || res.status === 401) {
318
+ await this.end("expired");
319
+ return null;
320
+ }
321
+ throw new ChabiError({ kind: "provider_error", status: res.status, message: "Chabi is having trouble right now. Please try again." });
322
+ }
323
+ const fresh = await this.parseTokens(res);
324
+ if (generation !== this.generation) return null;
325
+ if (!fresh) throw new ChabiError({ kind: "unknown", status: res.status, message: "Chabi sent an unexpected reply. Please try again." });
326
+ await this.storage.save(fresh);
327
+ if (generation !== this.generation) {
328
+ if ((await this.storage.load())?.refreshToken === fresh.refreshToken) await this.storage.clear();
329
+ return null;
330
+ }
331
+ this.tokens = fresh;
332
+ return fresh.accessToken;
333
+ });
334
+ }
335
+ async tokenRequest(fields) {
336
+ try {
337
+ return await this.fetchImpl(`${this.baseUrl}/oauth/token`, {
338
+ method: "POST",
339
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
340
+ body: new URLSearchParams(fields).toString()
341
+ });
342
+ } catch {
343
+ throw new ChabiError({ kind: "network", status: 0, message: "Couldn't reach Chabi. Check your connection and try again." });
344
+ }
345
+ }
346
+ async parseTokens(res) {
347
+ const b = await res.json().catch(() => ({}));
348
+ if (typeof b.access_token !== "string" || typeof b.refresh_token !== "string" || typeof b.expires_in !== "number") return null;
349
+ return { accessToken: b.access_token, refreshToken: b.refresh_token, expiresAt: this.now() + b.expires_in * 1e3 };
350
+ }
351
+ };
352
+ var isPromise = (v) => typeof v?.then === "function";
353
+
354
+ // src/button.ts
355
+ var MASK = `<rect width="100" height="100" fill="#fff"/><circle cx="33" cy="50" r="15" fill="#000"/><circle cx="33" cy="50" r="7" fill="#fff"/><path d="M45 46L82 46L82 62L77 62L77 54L73 54L73 62L68 62L68 54L45 54Z" fill="#000"/>`;
356
+ var SIGN_IN_LOGO_SVG = `<svg width="22" height="22" viewBox="0 0 100 100" aria-hidden="true"><mask id="chabi-key">${MASK}</mask><circle cx="50" cy="50" r="50" fill="currentColor" mask="url(#chabi-key)"/></svg>`;
357
+ var BUTTON_CSS = [
358
+ ".chabi-signin { display: inline-flex; align-items: center; gap: 10px; padding: 10px 18px; border: 0;",
359
+ " border-radius: 8px; background: #E0A526; color: #121212; font: 700 16px/1.2 system-ui, sans-serif; cursor: pointer; }",
360
+ ".chabi-signin:hover { background: #C99520; }",
361
+ "/* Dark style: */",
362
+ ".chabi-signin.dark { background: #121212; color: #FFFFFF; }",
363
+ ".chabi-signin.dark svg { color: #E0A526; }"
364
+ ];
365
+ var count = 0;
366
+ function signInButton(opts = {}) {
367
+ if (!document.querySelector("style[data-chabi-signin]")) {
368
+ const style = document.createElement("style");
369
+ style.setAttribute("data-chabi-signin", "");
370
+ style.textContent = BUTTON_CSS.join("\n");
371
+ document.head.appendChild(style);
372
+ }
373
+ const button = document.createElement("button");
374
+ button.type = "button";
375
+ button.className = opts.style === "dark" ? "chabi-signin dark" : "chabi-signin";
376
+ const id = `chabi-key-${++count}`;
377
+ button.innerHTML = SIGN_IN_LOGO_SVG.replace('id="chabi-key"', `id="${id}"`).replace("url(#chabi-key)", `url(#${id})`);
378
+ button.append(opts.label ?? "Sign in with Chabi");
379
+ return button;
380
+ }
381
+
382
+ // src/browser.ts
383
+ var PENDING_MAX_AGE_MS = 15 * 60 * 1e3;
384
+ var Chabi = class extends ChabiBase {
385
+ clientId;
386
+ redirectUri;
387
+ baseUrl;
388
+ store;
389
+ pending = pendingStore();
390
+ finishing;
391
+ constructor(opts) {
392
+ const store = safeStore();
393
+ const tokensKey = `chabi.${opts.clientId}.tokens`;
394
+ const storage = opts.storage ?? tokenStorage(store, tokensKey);
395
+ const lock = opts.lock ?? webLock(`chabi-refresh:${opts.clientId}`);
396
+ const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
397
+ super(new SessionCore({ baseUrl, clientId: opts.clientId, storage, lock }));
398
+ this.store = store;
399
+ this.clientId = opts.clientId;
400
+ this.redirectUri = opts.redirectUri;
401
+ this.baseUrl = baseUrl;
402
+ if (!opts.storage && typeof window !== "undefined") {
403
+ window.addEventListener("storage", (e) => {
404
+ if (e.key === tokensKey || e.key === null) this.core.adopt(storage.load());
405
+ });
406
+ }
407
+ }
408
+ /** Sends the user to Chabi to sign in and allow this app. They come back to `redirectUri`. */
409
+ async signIn() {
410
+ const verifier = randomString();
411
+ const state = randomString();
412
+ this.prunePending();
413
+ this.pending.set(this.pendingKey(state), JSON.stringify({ verifier, createdAt: Date.now() }));
414
+ const url = new URL(`${this.baseUrl}/oauth/authorize`);
415
+ url.search = new URLSearchParams({
416
+ response_type: "code",
417
+ client_id: this.clientId,
418
+ redirect_uri: this.redirectUri,
419
+ code_challenge: await challengeFor(verifier),
420
+ code_challenge_method: "S256",
421
+ state
422
+ }).toString();
423
+ window.location.assign(url.toString());
424
+ }
425
+ /**
426
+ * Call on every page load. If this load is the return from Chabi, finishes the sign-in and returns true;
427
+ * otherwise returns false. Throws a ChabiError (kind `access_denied` when the user declined) if it fails.
428
+ */
429
+ handleRedirect() {
430
+ return this.finishing ??= this.finish();
431
+ }
432
+ async finish() {
433
+ const params = new URLSearchParams(window.location.search);
434
+ if (!params.has("code") && !params.has("error")) return false;
435
+ const code = params.get("code");
436
+ const state = params.get("state") ?? "";
437
+ const error = params.get("error");
438
+ for (const k of ["code", "state", "error", "error_description", "iss"]) params.delete(k);
439
+ const rest = params.toString();
440
+ window.history.replaceState(window.history.state, "", window.location.pathname + (rest ? `?${rest}` : "") + window.location.hash);
441
+ const pending = state ? parsePending(this.pending.get(this.pendingKey(state))) : null;
442
+ if (state) this.pending.del(this.pendingKey(state));
443
+ this.prunePending();
444
+ if (!pending || Date.now() - pending.createdAt > PENDING_MAX_AGE_MS) {
445
+ throw new ChabiError({ kind: "signed_out", status: 0, code: "sign_in_not_started", message: "Sign-in didn't complete. Please try again." });
446
+ }
447
+ if (error === "access_denied") {
448
+ throw new ChabiError({ kind: "access_denied", status: 0, code: "access_denied", message: "You chose not to let this app use your Chabi plan." });
449
+ }
450
+ if (error || !code) {
451
+ throw new ChabiError({ kind: "signed_out", status: 0, code: error ?? "sign_in_failed", message: "Sign-in didn't complete. Please try again." });
452
+ }
453
+ await this.core.exchangeCode({ code, redirectUri: this.redirectUri, verifier: pending.verifier });
454
+ return true;
455
+ }
456
+ pendingKey(state) {
457
+ return `chabi.${this.clientId}.signin.${state}`;
458
+ }
459
+ prunePending() {
460
+ const prefix = `chabi.${this.clientId}.signin.`;
461
+ for (const key of this.pending.keys()) {
462
+ if (!key.startsWith(prefix)) continue;
463
+ const p = parsePending(this.pending.get(key));
464
+ if (!p || Date.now() - p.createdAt > PENDING_MAX_AGE_MS) this.pending.del(key);
465
+ }
466
+ }
467
+ };
468
+ function parsePending(raw) {
469
+ try {
470
+ const p = JSON.parse(raw ?? "null");
471
+ return p && typeof p.verifier === "string" && typeof p.createdAt === "number" ? p : null;
472
+ } catch {
473
+ return null;
474
+ }
475
+ }
476
+ function safeStore() {
477
+ const memory = /* @__PURE__ */ new Map();
478
+ const ls = () => {
479
+ try {
480
+ return typeof localStorage === "undefined" ? null : localStorage;
481
+ } catch {
482
+ return null;
483
+ }
484
+ };
485
+ return {
486
+ get(key) {
487
+ if (memory.has(key)) return memory.get(key);
488
+ try {
489
+ return ls()?.getItem(key) ?? null;
490
+ } catch {
491
+ return null;
492
+ }
493
+ },
494
+ set(key, value) {
495
+ try {
496
+ const s = ls();
497
+ if (!s) throw new Error("no localStorage");
498
+ s.setItem(key, value);
499
+ memory.delete(key);
500
+ } catch {
501
+ memory.set(key, value);
502
+ }
503
+ },
504
+ del(key) {
505
+ memory.delete(key);
506
+ try {
507
+ ls()?.removeItem(key);
508
+ } catch {
509
+ }
510
+ },
511
+ keys() {
512
+ const out = new Set(memory.keys());
513
+ try {
514
+ const s = ls();
515
+ for (let i = 0; s && i < s.length; i++) {
516
+ const k = s.key(i);
517
+ if (k) out.add(k);
518
+ }
519
+ } catch {
520
+ }
521
+ return [...out];
522
+ }
523
+ };
524
+ }
525
+ function pendingStore() {
526
+ const stores = () => {
527
+ const out = [];
528
+ for (const get of [() => localStorage, () => sessionStorage]) {
529
+ try {
530
+ const s = get();
531
+ if (s) out.push(s);
532
+ } catch {
533
+ }
534
+ }
535
+ return out;
536
+ };
537
+ return {
538
+ get(key) {
539
+ for (const s of stores()) {
540
+ try {
541
+ const v = s.getItem(key);
542
+ if (v !== null) return v;
543
+ } catch {
544
+ }
545
+ }
546
+ return null;
547
+ },
548
+ set(key, value) {
549
+ for (const s of stores()) {
550
+ try {
551
+ s.setItem(key, value);
552
+ return;
553
+ } catch {
554
+ }
555
+ }
556
+ throw new ChabiError({
557
+ kind: "signed_out",
558
+ status: 0,
559
+ code: "storage_blocked",
560
+ message: "This browser is blocking storage, so sign-in can't finish. Allow site data for this page, or use a normal (not private) window."
561
+ });
562
+ },
563
+ del(key) {
564
+ for (const s of stores()) {
565
+ try {
566
+ s.removeItem(key);
567
+ } catch {
568
+ }
569
+ }
570
+ },
571
+ keys() {
572
+ const out = /* @__PURE__ */ new Set();
573
+ for (const s of stores()) {
574
+ try {
575
+ for (let i = 0; i < s.length; i++) {
576
+ const k = s.key(i);
577
+ if (k) out.add(k);
578
+ }
579
+ } catch {
580
+ }
581
+ }
582
+ return [...out];
583
+ }
584
+ };
585
+ }
586
+ function tokenStorage(store, key) {
587
+ return {
588
+ load() {
589
+ try {
590
+ const t = JSON.parse(store.get(key) ?? "null");
591
+ return t && typeof t.accessToken === "string" && typeof t.refreshToken === "string" && Number.isFinite(t.expiresAt) ? t : null;
592
+ } catch {
593
+ return null;
594
+ }
595
+ },
596
+ save: (t) => store.set(key, JSON.stringify(t)),
597
+ clear: () => store.del(key)
598
+ };
599
+ }
600
+ function webLock(name) {
601
+ let tail = Promise.resolve();
602
+ const inPage = (run) => {
603
+ const next = tail.then(run, run);
604
+ tail = next.catch(() => void 0);
605
+ return next;
606
+ };
607
+ return (run) => {
608
+ const locks = typeof navigator === "undefined" ? void 0 : navigator.locks;
609
+ return locks ? locks.request(name, run) : inPage(run);
610
+ };
611
+ }
612
+ // Annotate the CommonJS export names for ESM import in node:
613
+ 0 && (module.exports = {
614
+ Chabi,
615
+ ChabiError,
616
+ describeError,
617
+ describeResponse,
618
+ signInButton
619
+ });
620
+ //# sourceMappingURL=browser.cjs.map