@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.
package/dist/node.cjs ADDED
@@ -0,0 +1,470 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/node.ts
31
+ var node_exports = {};
32
+ __export(node_exports, {
33
+ Chabi: () => Chabi,
34
+ ChabiError: () => ChabiError,
35
+ describeError: () => describeError,
36
+ describeResponse: () => describeResponse,
37
+ memoryStorage: () => memoryStorage
38
+ });
39
+ module.exports = __toCommonJS(node_exports);
40
+ var import_node_http = __toESM(require("http"), 1);
41
+
42
+ // src/errors.ts
43
+ var ChabiError = class extends Error {
44
+ info;
45
+ constructor(info) {
46
+ super(info.message);
47
+ this.name = "ChabiError";
48
+ this.info = info;
49
+ }
50
+ };
51
+ var MESSAGES = {
52
+ out_of_credits: "You're out of Chabi credits.",
53
+ app_limit: "You've reached the monthly limit you set for this app on Chabi.",
54
+ signed_out: "Sign in with Chabi to continue.",
55
+ access_denied: "You chose not to let this app use your Chabi plan.",
56
+ rate_limited: "Too many requests. Please wait a moment and try again.",
57
+ app_suspended: "This app can't use Chabi right now.",
58
+ bad_request: "Chabi couldn't handle that request.",
59
+ provider_error: "The AI provider is having trouble right now. Please try again.",
60
+ network: "Couldn't reach Chabi. Check your connection and try again.",
61
+ unknown: "Something went wrong. Please try again."
62
+ };
63
+ var str = (v) => typeof v === "string" && v ? v : void 0;
64
+ function kindOf(status, code) {
65
+ if (code === "insufficient_credits") return "out_of_credits";
66
+ if (code === "app_limit_reached") return "app_limit";
67
+ if (code === "app_suspended") return "app_suspended";
68
+ if (status === 401) return "signed_out";
69
+ if (status === 402) return "out_of_credits";
70
+ if (status === 403) return "app_suspended";
71
+ if (status === 429) return "rate_limited";
72
+ if (status >= 500) return "provider_error";
73
+ if (status >= 400) return "bad_request";
74
+ return "unknown";
75
+ }
76
+ function build(status, body, retryAfterHeader) {
77
+ const code = str(body?.code);
78
+ const kind = kindOf(status, code);
79
+ const info = { kind, status, message: MESSAGES[kind] };
80
+ if (code) info.code = code;
81
+ const upgradeUrl = str(body?.upgrade_url);
82
+ const manageUrl = str(body?.manage_url);
83
+ if (upgradeUrl) info.upgradeUrl = upgradeUrl;
84
+ if (manageUrl) info.manageUrl = manageUrl;
85
+ const retryAfter = Number(retryAfterHeader);
86
+ if (kind === "rate_limited" && retryAfterHeader && Number.isFinite(retryAfter)) info.retryAfter = retryAfter;
87
+ return info;
88
+ }
89
+ function describeError(e) {
90
+ if (e instanceof ChabiError) return e.info.message ? e.info : { ...e.info, message: MESSAGES[e.info.kind] };
91
+ const cause = e?.cause;
92
+ if (cause instanceof ChabiError) return describeError(cause);
93
+ const x = e;
94
+ if (x && typeof x === "object" && typeof x.status === "number") {
95
+ const outer = x.error;
96
+ const body = outer && typeof outer.error === "object" ? outer.error : outer;
97
+ const headers = x.headers;
98
+ const retry = typeof headers?.get === "function" ? headers.get("retry-after") : headers?.["retry-after"];
99
+ return build(x.status, body, retry);
100
+ }
101
+ const ctor = x?.constructor?.name;
102
+ if (e instanceof TypeError || typeof ctor === "string" && /Connection|Timeout/.test(ctor)) {
103
+ return { kind: "network", status: 0, message: MESSAGES.network };
104
+ }
105
+ return { kind: "unknown", status: 0, message: MESSAGES.unknown };
106
+ }
107
+ async function describeResponse(res) {
108
+ const body = await res.clone().json().catch(() => null);
109
+ return build(res.status, body?.error, res.headers.get("retry-after"));
110
+ }
111
+
112
+ // src/client.ts
113
+ var DEFAULT_BASE_URL = "https://chabi.dev";
114
+ var SIGN_OUT_CODES = /* @__PURE__ */ new Set(["missing_token", "token_revoked", "grant_revoked", "unknown_app"]);
115
+ var PLACEHOLDER_KEY = "chabi";
116
+ var ChabiBase = class {
117
+ constructor(core) {
118
+ this.core = core;
119
+ this.fetch = (input, init) => this.authorizedFetch(input, init);
120
+ }
121
+ core;
122
+ /** A fetch for the official SDKs. It only sets Authorization: bodies, models and other headers pass through. */
123
+ fetch;
124
+ get signedIn() {
125
+ return this.core.signedIn;
126
+ }
127
+ /** Options for `new OpenAI(...)`. In a browser, add `dangerouslyAllowBrowser: true`. */
128
+ openai() {
129
+ return { baseURL: `${this.core.baseUrl}/v1`, apiKey: PLACEHOLDER_KEY, fetch: this.fetch };
130
+ }
131
+ /** Options for `new Anthropic(...)`. In a browser, add `dangerouslyAllowBrowser: true`. */
132
+ anthropic() {
133
+ return { baseURL: this.core.baseUrl, apiKey: PLACEHOLDER_KEY, fetch: this.fetch };
134
+ }
135
+ /** The user's credit balance. */
136
+ async credits() {
137
+ const body = await this.getJson("/v1/credits");
138
+ return body.balance_credits;
139
+ }
140
+ /** The display name on the user's Chabi account, or null if they haven't set one. */
141
+ async me() {
142
+ const body = await this.getJson("/v1/me");
143
+ return { name: body.name ?? null };
144
+ }
145
+ /** Signs the user out of this app on this device. */
146
+ signOut() {
147
+ return this.core.end("signed_out");
148
+ }
149
+ /** Called when the user is signed in or out, here or in another tab. Returns a function that unsubscribes. */
150
+ onChange(listener) {
151
+ return this.core.onChange(listener);
152
+ }
153
+ async getJson(path) {
154
+ const res = await this.fetch(`${this.core.baseUrl}${path}`);
155
+ if (!res.ok) throw new ChabiError(await describeResponse(res));
156
+ return res.json();
157
+ }
158
+ async authorizedFetch(input, init) {
159
+ if (!this.isChabi(input)) return this.core.fetchImpl(input, init);
160
+ let token = await this.core.accessToken();
161
+ if (!token) return signedOutResponse();
162
+ const spare = input instanceof Request ? input.clone() : null;
163
+ const replayable = !(init?.body instanceof ReadableStream);
164
+ let res = await this.send(input, init, token);
165
+ if (res.status !== 401) return res;
166
+ let code = await errorCode(res);
167
+ if (code === "invalid_token") {
168
+ const fresh = await this.core.refreshAfterReject(token);
169
+ if (!fresh || !replayable) return res;
170
+ token = fresh;
171
+ res = await this.send(spare ?? input, init, token);
172
+ if (res.status !== 401) return res;
173
+ code = await errorCode(res);
174
+ }
175
+ if (code && SIGN_OUT_CODES.has(code)) await this.core.end("access_removed");
176
+ return res;
177
+ }
178
+ isChabi(input) {
179
+ try {
180
+ const url = new URL(input instanceof Request ? input.url : String(input));
181
+ return url.origin === new URL(this.core.baseUrl).origin;
182
+ } catch {
183
+ return false;
184
+ }
185
+ }
186
+ send(input, init, token) {
187
+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));
188
+ headers.set("Authorization", `Bearer ${token}`);
189
+ headers.delete("x-api-key");
190
+ return this.core.fetchImpl(input, { ...init, headers });
191
+ }
192
+ };
193
+ var signedOutResponse = () => new Response(JSON.stringify({ error: { code: "missing_token", message: "Sign in with Chabi to continue." } }), {
194
+ status: 401,
195
+ headers: { "Content-Type": "application/json", "x-should-retry": "false" }
196
+ });
197
+ async function errorCode(res) {
198
+ const body = await res.clone().json().catch(() => null);
199
+ return typeof body?.error?.code === "string" ? body.error.code : void 0;
200
+ }
201
+
202
+ // src/pkce.ts
203
+ var base64url = (bytes) => {
204
+ let s = "";
205
+ for (const b of bytes) s += String.fromCharCode(b);
206
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
207
+ };
208
+ function randomString(bytes = 32) {
209
+ return base64url(globalThis.crypto.getRandomValues(new Uint8Array(bytes)));
210
+ }
211
+ async function challengeFor(verifier) {
212
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
213
+ return base64url(new Uint8Array(digest));
214
+ }
215
+
216
+ // src/session.ts
217
+ var REFRESH_EARLY_MS = 6e4;
218
+ var SessionCore = class {
219
+ baseUrl;
220
+ clientId;
221
+ storage;
222
+ lock;
223
+ /** The underlying fetch, for requests that carry the user's token (see ChabiBase.fetch). */
224
+ fetchImpl;
225
+ now;
226
+ tokens = null;
227
+ // Bumped by sign-in and sign-out, so a refresh that finishes afterwards can't bring an old session back.
228
+ generation = 0;
229
+ listeners = /* @__PURE__ */ new Set();
230
+ constructor(opts) {
231
+ this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
232
+ this.clientId = opts.clientId;
233
+ this.storage = opts.storage;
234
+ this.lock = opts.lock;
235
+ this.fetchImpl = opts.fetch ?? ((input, init) => globalThis.fetch(input, init));
236
+ this.now = opts.now ?? Date.now;
237
+ const loaded = this.storage.load();
238
+ if (!isPromise(loaded)) this.tokens = loaded;
239
+ else loaded.catch(() => {
240
+ });
241
+ }
242
+ get signedIn() {
243
+ return this.tokens !== null;
244
+ }
245
+ /** Reads storage into memory. Needed once at start for asynchronous storage (Node, Electron). */
246
+ async load() {
247
+ this.tokens = await this.storage.load();
248
+ }
249
+ /** The access token to send, refreshed first when it's within a minute of expiring. Null when signed out. */
250
+ async accessToken() {
251
+ const t = this.tokens;
252
+ if (!t) return null;
253
+ if (t.expiresAt - this.now() > REFRESH_EARLY_MS) return t.accessToken;
254
+ return this.refreshLocked(t.refreshToken, null);
255
+ }
256
+ /** The gateway said `rejected` is no longer valid: refresh, unless that already happened since it was sent. */
257
+ async refreshAfterReject(rejected) {
258
+ const t = this.tokens;
259
+ if (!t) return null;
260
+ if (t.accessToken !== rejected) return t.accessToken;
261
+ return this.refreshLocked(t.refreshToken, rejected);
262
+ }
263
+ /** Swaps the code from the sign-in redirect for tokens, saves them and tells listeners. */
264
+ async exchangeCode(p) {
265
+ const res = await this.tokenRequest({
266
+ grant_type: "authorization_code",
267
+ code: p.code,
268
+ redirect_uri: p.redirectUri,
269
+ client_id: this.clientId,
270
+ code_verifier: p.verifier
271
+ });
272
+ const tokens = res.ok ? await this.parseTokens(res) : null;
273
+ if (!tokens) {
274
+ throw new ChabiError({ kind: "signed_out", status: res.status, code: "sign_in_failed", message: "Sign-in didn't complete. Please try again." });
275
+ }
276
+ this.generation += 1;
277
+ await this.storage.save(tokens);
278
+ this.tokens = tokens;
279
+ this.emit(true, "signed_in");
280
+ }
281
+ /** Forgets the tokens (memory and storage) and tells listeners why. */
282
+ async end(reason) {
283
+ this.generation += 1;
284
+ const was = this.tokens !== null;
285
+ this.tokens = null;
286
+ await this.storage.clear();
287
+ if (was) this.emit(false, reason);
288
+ }
289
+ /** Another tab changed the stored tokens: take its copy, and tell listeners if that signed the user in or out. */
290
+ adopt(tokens) {
291
+ const was = this.tokens !== null;
292
+ if (!tokens) this.generation += 1;
293
+ this.tokens = tokens;
294
+ if (was !== (tokens !== null)) this.emit(tokens !== null, tokens ? "signed_in" : "signed_out");
295
+ }
296
+ onChange(listener) {
297
+ this.listeners.add(listener);
298
+ return () => void this.listeners.delete(listener);
299
+ }
300
+ emit(signedIn, reason) {
301
+ for (const l of [...this.listeners]) {
302
+ try {
303
+ l(signedIn, reason);
304
+ } catch {
305
+ }
306
+ }
307
+ }
308
+ refreshLocked(startedWith, rejected) {
309
+ return this.lock(async () => {
310
+ const generation = this.generation;
311
+ const stored = await this.storage.load();
312
+ if (generation !== this.generation) return null;
313
+ if (!stored) {
314
+ this.adopt(null);
315
+ return null;
316
+ }
317
+ if (stored.refreshToken !== startedWith) {
318
+ this.tokens = stored;
319
+ return stored.accessToken;
320
+ }
321
+ if (rejected === null && stored.expiresAt - this.now() > REFRESH_EARLY_MS) {
322
+ this.tokens = stored;
323
+ return stored.accessToken;
324
+ }
325
+ const res = await this.tokenRequest({ grant_type: "refresh_token", refresh_token: stored.refreshToken, client_id: this.clientId });
326
+ if (generation !== this.generation) return null;
327
+ if (!res.ok) {
328
+ if (res.status === 400 || res.status === 401) {
329
+ await this.end("expired");
330
+ return null;
331
+ }
332
+ throw new ChabiError({ kind: "provider_error", status: res.status, message: "Chabi is having trouble right now. Please try again." });
333
+ }
334
+ const fresh = await this.parseTokens(res);
335
+ if (generation !== this.generation) return null;
336
+ if (!fresh) throw new ChabiError({ kind: "unknown", status: res.status, message: "Chabi sent an unexpected reply. Please try again." });
337
+ await this.storage.save(fresh);
338
+ if (generation !== this.generation) {
339
+ if ((await this.storage.load())?.refreshToken === fresh.refreshToken) await this.storage.clear();
340
+ return null;
341
+ }
342
+ this.tokens = fresh;
343
+ return fresh.accessToken;
344
+ });
345
+ }
346
+ async tokenRequest(fields) {
347
+ try {
348
+ return await this.fetchImpl(`${this.baseUrl}/oauth/token`, {
349
+ method: "POST",
350
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
351
+ body: new URLSearchParams(fields).toString()
352
+ });
353
+ } catch {
354
+ throw new ChabiError({ kind: "network", status: 0, message: "Couldn't reach Chabi. Check your connection and try again." });
355
+ }
356
+ }
357
+ async parseTokens(res) {
358
+ const b = await res.json().catch(() => ({}));
359
+ if (typeof b.access_token !== "string" || typeof b.refresh_token !== "string" || typeof b.expires_in !== "number") return null;
360
+ return { accessToken: b.access_token, refreshToken: b.refresh_token, expiresAt: this.now() + b.expires_in * 1e3 };
361
+ }
362
+ };
363
+ var isPromise = (v) => typeof v?.then === "function";
364
+
365
+ // src/node.ts
366
+ var DEFAULT_TIMEOUT_MS = 5 * 6e4;
367
+ var Chabi = class extends ChabiBase {
368
+ opts;
369
+ baseUrl;
370
+ constructor(opts) {
371
+ const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
372
+ super(new SessionCore({ baseUrl, clientId: opts.clientId, storage: opts.storage, lock: processLock() }));
373
+ this.opts = opts;
374
+ this.baseUrl = baseUrl;
375
+ }
376
+ /** Reads the saved tokens. Await it once at start, before checking `signedIn`. */
377
+ load() {
378
+ return this.core.load();
379
+ }
380
+ /**
381
+ * Opens Chabi in the system browser and waits for the user to come back. Resolves once signed in; throws a
382
+ * ChabiError if they declined (`access_denied`), the sign-in didn't come from here, or it timed out.
383
+ */
384
+ async signIn() {
385
+ const verifier = randomString();
386
+ const state = randomString(16);
387
+ const server = import_node_http.default.createServer();
388
+ await new Promise((ready, fail) => {
389
+ server.once("error", fail);
390
+ server.listen(0, "127.0.0.1", ready);
391
+ });
392
+ const redirectUri = `http://127.0.0.1:${server.address().port}/callback`;
393
+ let timer;
394
+ try {
395
+ const returned = new Promise((done, fail) => {
396
+ timer = setTimeout(
397
+ () => fail(new ChabiError({ kind: "signed_out", status: 0, code: "sign_in_timeout", message: "Sign-in timed out. Please try again." })),
398
+ this.opts.timeoutMs ?? DEFAULT_TIMEOUT_MS
399
+ );
400
+ server.on("request", (req, res) => {
401
+ const url2 = new URL(req.url ?? "/", redirectUri);
402
+ if (url2.pathname !== "/callback") return void res.writeHead(404).end();
403
+ const p2 = url2.searchParams;
404
+ const outcome = p2.get("state") !== state || !p2.get("code") && !p2.get("error") ? "failed" : p2.get("error") === "access_denied" ? "denied" : p2.get("error") ? "failed" : "signed_in";
405
+ this.opts.onReturn?.();
406
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", Connection: "close" });
407
+ res.end((this.opts.returnPage ?? defaultReturnPage)(outcome));
408
+ done(p2);
409
+ });
410
+ });
411
+ returned.catch(() => {
412
+ });
413
+ const url = new URL(`${this.baseUrl}/oauth/authorize`);
414
+ url.search = new URLSearchParams({
415
+ response_type: "code",
416
+ client_id: this.opts.clientId,
417
+ redirect_uri: redirectUri,
418
+ code_challenge: await challengeFor(verifier),
419
+ code_challenge_method: "S256",
420
+ state
421
+ }).toString();
422
+ await this.opts.openBrowser(url.toString());
423
+ const p = await returned;
424
+ if (p.get("state") !== state) {
425
+ throw new ChabiError({ kind: "signed_out", status: 0, code: "sign_in_not_started", message: "That sign-in didn't start here. Please try again." });
426
+ }
427
+ if (p.get("error") === "access_denied") {
428
+ throw new ChabiError({ kind: "access_denied", status: 0, code: "access_denied", message: "You chose not to let this app use your Chabi plan." });
429
+ }
430
+ const code = p.get("code");
431
+ if (p.get("error") || !code) {
432
+ throw new ChabiError({ kind: "signed_out", status: 0, code: p.get("error") ?? "sign_in_failed", message: "Sign-in didn't complete. Please try again." });
433
+ }
434
+ await this.core.exchangeCode({ code, redirectUri, verifier });
435
+ } finally {
436
+ clearTimeout(timer);
437
+ server.close();
438
+ server.closeAllConnections();
439
+ }
440
+ }
441
+ };
442
+ function memoryStorage(initial = null) {
443
+ let tokens = initial;
444
+ return {
445
+ load: () => tokens,
446
+ save: (t) => void (tokens = t),
447
+ clear: () => void (tokens = null)
448
+ };
449
+ }
450
+ function processLock() {
451
+ let tail = Promise.resolve();
452
+ return (run) => {
453
+ const next = tail.then(run, run);
454
+ tail = next.catch(() => void 0);
455
+ return next;
456
+ };
457
+ }
458
+ function defaultReturnPage(outcome) {
459
+ const [title, body] = outcome === "signed_in" ? ["You're signed in", "You can close this tab and go back to the app."] : outcome === "denied" ? ["Sign-in cancelled", "The app won't use your Chabi plan. You can close this tab."] : ["Sign-in didn't finish", "Go back to the app and try again."];
460
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${title}</title><style>body{margin:0;min-height:100vh;display:grid;place-items:center;font:16px/1.5 system-ui,sans-serif;background:#fff;color:#121212}@media (prefers-color-scheme:dark){body{background:#121212;color:#fff}}main{max-width:420px;padding:32px 28px}h1{margin:0 0 6px;font-size:22px}p{margin:0;opacity:.75}</style></head><body><main><h1>${title}</h1><p>${body}</p></main></body></html>`;
461
+ }
462
+ // Annotate the CommonJS export names for ESM import in node:
463
+ 0 && (module.exports = {
464
+ Chabi,
465
+ ChabiError,
466
+ describeError,
467
+ describeResponse,
468
+ memoryStorage
469
+ });
470
+ //# sourceMappingURL=node.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/node.ts","../src/errors.ts","../src/client.ts","../src/pkce.ts","../src/session.ts"],"sourcesContent":["// \"Sign in with Chabi\" for Node and Electron (main process): sign-in in the system browser with a loopback\n// redirect (RFC 8252), tokens kept wherever the app's storage puts them (the OS keychain, ideally).\nimport http from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\nimport { ChabiBase, DEFAULT_BASE_URL } from \"./client.js\";\nimport { ChabiError } from \"./errors.js\";\nimport { challengeFor, randomString } from \"./pkce.js\";\nimport { SessionCore } from \"./session.js\";\nimport type { RefreshLock, TokenStorage, Tokens } from \"./types.js\";\n\nexport { ChabiError, describeError, describeResponse } from \"./errors.js\";\nexport type * from \"./types.js\";\nexport type { ChabiBase } from \"./client.js\";\n\n/** What the browser tab shows once it has handed the sign-in back. */\nexport type Outcome = \"signed_in\" | \"denied\" | \"failed\";\n\nexport type NodeOptions = {\n clientId: string;\n baseUrl?: string;\n /** Where tokens live. In Electron, encrypt them with safeStorage; `memoryStorage()` keeps them for this run only. */\n storage: TokenStorage;\n /** Opens the sign-in page in the system browser (Electron: `shell.openExternal`). Never a web view in the app. */\n openBrowser: (url: string) => void | Promise<void>;\n /** Called the moment the browser comes back, before the tab is answered: bring the app's window to the front. */\n onReturn?: () => void;\n /** The HTML the tab shows afterwards. The default says the user can close the tab. */\n returnPage?: (outcome: Outcome) => string;\n /** How long to wait for the user to finish in the browser. Default 5 minutes. */\n timeoutMs?: number;\n};\n\nconst DEFAULT_TIMEOUT_MS = 5 * 60_000;\n\nexport class Chabi extends ChabiBase {\n private readonly opts: NodeOptions;\n private readonly baseUrl: string;\n\n constructor(opts: NodeOptions) {\n const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n super(new SessionCore({ baseUrl, clientId: opts.clientId, storage: opts.storage, lock: processLock() }));\n this.opts = opts;\n this.baseUrl = baseUrl;\n }\n\n /** Reads the saved tokens. Await it once at start, before checking `signedIn`. */\n load(): Promise<void> {\n return this.core.load();\n }\n\n /**\n * Opens Chabi in the system browser and waits for the user to come back. Resolves once signed in; throws a\n * ChabiError if they declined (`access_denied`), the sign-in didn't come from here, or it timed out.\n */\n async signIn(): Promise<void> {\n const verifier = randomString();\n const state = randomString(16);\n const server = http.createServer();\n await new Promise<void>((ready, fail) => {\n server.once(\"error\", fail);\n server.listen(0, \"127.0.0.1\", ready);\n });\n // Any free port: the registered redirect is http://127.0.0.1/callback and the port doesn't have to match.\n const redirectUri = `http://127.0.0.1:${(server.address() as AddressInfo).port}/callback`;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n try {\n const returned = new Promise<URLSearchParams>((done, fail) => {\n timer = setTimeout(\n () => fail(new ChabiError({ kind: \"signed_out\", status: 0, code: \"sign_in_timeout\", message: \"Sign-in timed out. Please try again.\" })),\n this.opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n );\n server.on(\"request\", (req, res) => {\n const url = new URL(req.url ?? \"/\", redirectUri);\n if (url.pathname !== \"/callback\") return void res.writeHead(404).end();\n const p = url.searchParams;\n const outcome: Outcome =\n p.get(\"state\") !== state || (!p.get(\"code\") && !p.get(\"error\")) ? \"failed\"\n : p.get(\"error\") === \"access_denied\" ? \"denied\"\n : p.get(\"error\") ? \"failed\"\n : \"signed_in\";\n this.opts.onReturn?.(); // in front of the tab by the time it finishes loading\n res.writeHead(200, { \"Content-Type\": \"text/html; charset=utf-8\", \"Cache-Control\": \"no-store\", Connection: \"close\" });\n res.end((this.opts.returnPage ?? defaultReturnPage)(outcome));\n done(p);\n });\n });\n\n returned.catch(() => {}); // a timeout while openBrowser is still running is handled below, not unhandled\n const url = new URL(`${this.baseUrl}/oauth/authorize`);\n url.search = new URLSearchParams({\n response_type: \"code\",\n client_id: this.opts.clientId,\n redirect_uri: redirectUri,\n code_challenge: await challengeFor(verifier),\n code_challenge_method: \"S256\",\n state,\n }).toString();\n await this.opts.openBrowser(url.toString());\n\n const p = await returned;\n if (p.get(\"state\") !== state) {\n throw new ChabiError({ kind: \"signed_out\", status: 0, code: \"sign_in_not_started\", message: \"That sign-in didn't start here. Please try again.\" });\n }\n if (p.get(\"error\") === \"access_denied\") {\n throw new ChabiError({ kind: \"access_denied\", status: 0, code: \"access_denied\", message: \"You chose not to let this app use your Chabi plan.\" });\n }\n const code = p.get(\"code\");\n if (p.get(\"error\") || !code) {\n throw new ChabiError({ kind: \"signed_out\", status: 0, code: p.get(\"error\") ?? \"sign_in_failed\", message: \"Sign-in didn't complete. Please try again.\" });\n }\n await this.core.exchangeCode({ code, redirectUri, verifier });\n } finally {\n clearTimeout(timer);\n server.close();\n server.closeAllConnections();\n }\n }\n}\n\n/** Tokens kept in memory for this run only (tests, or when the OS has no keychain). */\nexport function memoryStorage(initial: Tokens | null = null): TokenStorage {\n let tokens = initial;\n return {\n load: () => tokens,\n save: (t) => void (tokens = t),\n clear: () => void (tokens = null),\n };\n}\n\n// One process owns the tokens, so a promise chain is enough to keep refreshes one at a time.\nfunction processLock(): RefreshLock {\n let tail: Promise<unknown> = Promise.resolve();\n return (run) => {\n const next = tail.then(run, run);\n tail = next.catch(() => undefined);\n return next;\n };\n}\n\nfunction defaultReturnPage(outcome: Outcome): string {\n const [title, body] =\n outcome === \"signed_in\" ? [\"You're signed in\", \"You can close this tab and go back to the app.\"]\n : outcome === \"denied\" ? [\"Sign-in cancelled\", \"The app won't use your Chabi plan. You can close this tab.\"]\n : [\"Sign-in didn't finish\", \"Go back to the app and try again.\"];\n return `<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>${title}</title><style>body{margin:0;min-height:100vh;display:grid;place-items:center;font:16px/1.5 system-ui,sans-serif;background:#fff;color:#121212}@media (prefers-color-scheme:dark){body{background:#121212;color:#fff}}main{max-width:420px;padding:32px 28px}h1{margin:0 0 6px;font-size:22px}p{margin:0;opacity:.75}</style></head><body><main><h1>${title}</h1><p>${body}</p></main></body></html>`;\n}\n","import type { ChabiErrorInfo, ErrorKind } from \"./types.js\";\n\n/** An error the SDK raises itself. `info` is what `describeError` returns for it. */\nexport class ChabiError extends Error {\n readonly info: ChabiErrorInfo;\n constructor(info: ChabiErrorInfo) {\n super(info.message);\n this.name = \"ChabiError\";\n this.info = info;\n }\n}\n\nconst MESSAGES: Record<ErrorKind, string> = {\n out_of_credits: \"You're out of Chabi credits.\",\n app_limit: \"You've reached the monthly limit you set for this app on Chabi.\",\n signed_out: \"Sign in with Chabi to continue.\",\n access_denied: \"You chose not to let this app use your Chabi plan.\",\n rate_limited: \"Too many requests. Please wait a moment and try again.\",\n app_suspended: \"This app can't use Chabi right now.\",\n bad_request: \"Chabi couldn't handle that request.\",\n provider_error: \"The AI provider is having trouble right now. Please try again.\",\n network: \"Couldn't reach Chabi. Check your connection and try again.\",\n unknown: \"Something went wrong. Please try again.\",\n};\n\ntype GatewayBody = { code?: unknown; message?: unknown; upgrade_url?: unknown; manage_url?: unknown };\n\nconst str = (v: unknown) => (typeof v === \"string\" && v ? v : undefined);\n\nfunction kindOf(status: number, code: string | undefined): ErrorKind {\n if (code === \"insufficient_credits\") return \"out_of_credits\";\n if (code === \"app_limit_reached\") return \"app_limit\";\n if (code === \"app_suspended\") return \"app_suspended\";\n if (status === 401) return \"signed_out\";\n if (status === 402) return \"out_of_credits\";\n if (status === 403) return \"app_suspended\";\n if (status === 429) return \"rate_limited\";\n if (status >= 500) return \"provider_error\";\n if (status >= 400) return \"bad_request\";\n return \"unknown\";\n}\n\nfunction build(status: number, body: GatewayBody | undefined, retryAfterHeader: string | null | undefined): ChabiErrorInfo {\n const code = str(body?.code);\n const kind = kindOf(status, code);\n const info: ChabiErrorInfo = { kind, status, message: MESSAGES[kind] };\n if (code) info.code = code;\n const upgradeUrl = str(body?.upgrade_url);\n const manageUrl = str(body?.manage_url);\n if (upgradeUrl) info.upgradeUrl = upgradeUrl;\n if (manageUrl) info.manageUrl = manageUrl;\n const retryAfter = Number(retryAfterHeader);\n if (kind === \"rate_limited\" && retryAfterHeader && Number.isFinite(retryAfter)) info.retryAfter = retryAfter;\n return info;\n}\n\n/**\n * Any error from a Chabi request in one shape: an OpenAI or Anthropic SDK error, a ChabiError, a failed fetch.\n * For a `Response` you got from `chabi.fetch` yourself, use `describeResponse`.\n */\nexport function describeError(e: unknown): ChabiErrorInfo {\n if (e instanceof ChabiError) return e.info.message ? e.info : { ...e.info, message: MESSAGES[e.info.kind] };\n // The official SDKs wrap anything chabi.fetch throws (a failed refresh, say) in their own connection error.\n const cause = (e as { cause?: unknown } | null)?.cause;\n if (cause instanceof ChabiError) return describeError(cause);\n const x = e as { status?: unknown; error?: unknown; headers?: unknown; name?: unknown } | null;\n if (x && typeof x === \"object\" && typeof x.status === \"number\") {\n // OpenAI's SDK puts the gateway's `error` object in err.error; Anthropic's puts the whole body there.\n const outer = x.error as { error?: GatewayBody } & GatewayBody | undefined;\n const body = outer && typeof outer.error === \"object\" ? outer.error : outer;\n const headers = x.headers as { get?: (k: string) => string | null } | Record<string, string> | undefined;\n const retry = typeof (headers as Headers | undefined)?.get === \"function\"\n ? (headers as Headers).get(\"retry-after\")\n : (headers as Record<string, string> | undefined)?.[\"retry-after\"];\n return build(x.status, body, retry);\n }\n // A failed fetch, or the SDKs' APIConnectionError (and its timeout subclass) wrapping one.\n const ctor = (x as { constructor?: { name?: unknown } } | null)?.constructor?.name;\n if (e instanceof TypeError || (typeof ctor === \"string\" && /Connection|Timeout/.test(ctor))) {\n return { kind: \"network\", status: 0, message: MESSAGES.network };\n }\n return { kind: \"unknown\", status: 0, message: MESSAGES.unknown };\n}\n\n/** `describeError` for a `Response`, such as one from `chabi.fetch` that wasn't ok. */\nexport async function describeResponse(res: Response): Promise<ChabiErrorInfo> {\n const body = (await res.clone().json().catch(() => null)) as { error?: GatewayBody } | null;\n return build(res.status, body?.error, res.headers.get(\"retry-after\"));\n}\n","import { ChabiError, describeResponse } from \"./errors.js\";\nimport type { SessionCore } from \"./session.js\";\nimport type { ChangeListener } from \"./types.js\";\n\n/** Where Chabi lives unless an app says otherwise. */\nexport const DEFAULT_BASE_URL = \"https://chabi.dev\";\n\n/** 401 codes that mean the user's access is gone: refreshing can't help, so the SDK signs out. */\nexport const SIGN_OUT_CODES = new Set([\"missing_token\", \"token_revoked\", \"grant_revoked\", \"unknown_app\"]);\n\n/** The placeholder API key handed to the official SDKs. `fetch` replaces it with the user's token. */\nconst PLACEHOLDER_KEY = \"chabi\";\n\ntype SdkConfig = { baseURL: string; apiKey: string; fetch: typeof fetch };\n\n/** What the browser and Node clients share: requests with the user's token, account calls and sign-out. */\nexport class ChabiBase {\n /** A fetch for the official SDKs. It only sets Authorization: bodies, models and other headers pass through. */\n readonly fetch: typeof fetch;\n\n constructor(protected readonly core: SessionCore) {\n this.fetch = (input, init) => this.authorizedFetch(input, init);\n }\n\n get signedIn(): boolean {\n return this.core.signedIn;\n }\n\n /** Options for `new OpenAI(...)`. In a browser, add `dangerouslyAllowBrowser: true`. */\n openai(): SdkConfig {\n return { baseURL: `${this.core.baseUrl}/v1`, apiKey: PLACEHOLDER_KEY, fetch: this.fetch };\n }\n\n /** Options for `new Anthropic(...)`. In a browser, add `dangerouslyAllowBrowser: true`. */\n anthropic(): SdkConfig {\n return { baseURL: this.core.baseUrl, apiKey: PLACEHOLDER_KEY, fetch: this.fetch };\n }\n\n /** The user's credit balance. */\n async credits(): Promise<number> {\n const body = (await this.getJson(\"/v1/credits\")) as { balance_credits: number };\n return body.balance_credits;\n }\n\n /** The display name on the user's Chabi account, or null if they haven't set one. */\n async me(): Promise<{ name: string | null }> {\n const body = (await this.getJson(\"/v1/me\")) as { name?: string | null };\n return { name: body.name ?? null };\n }\n\n /** Signs the user out of this app on this device. */\n signOut(): Promise<void> {\n return this.core.end(\"signed_out\");\n }\n\n /** Called when the user is signed in or out, here or in another tab. Returns a function that unsubscribes. */\n onChange(listener: ChangeListener): () => void {\n return this.core.onChange(listener);\n }\n\n protected async getJson(path: string): Promise<unknown> {\n const res = await this.fetch(`${this.core.baseUrl}${path}`);\n if (!res.ok) throw new ChabiError(await describeResponse(res));\n return res.json();\n }\n\n private async authorizedFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n // The user's token only ever goes to Chabi, even if an app points an SDK somewhere else.\n if (!this.isChabi(input)) return this.core.fetchImpl(input, init);\n\n let token = await this.core.accessToken();\n // Answered like the gateway would, so the official SDKs raise their normal 401 error, without retrying.\n if (!token) return signedOutResponse();\n\n // A Request carries its body as a stream; clone it now so it can be sent again after a refresh.\n const spare = input instanceof Request ? input.clone() : null;\n const replayable = !(init?.body instanceof ReadableStream);\n\n let res = await this.send(input, init, token);\n if (res.status !== 401) return res;\n\n let code = await errorCode(res);\n if (code === \"invalid_token\") {\n const fresh = await this.core.refreshAfterReject(token);\n if (!fresh || !replayable) return res; // signed out by the refresh, or a stream body that's already spent\n token = fresh;\n res = await this.send(spare ?? input, init, token);\n if (res.status !== 401) return res;\n code = await errorCode(res);\n }\n if (code && SIGN_OUT_CODES.has(code)) await this.core.end(\"access_removed\");\n return res;\n }\n\n private isChabi(input: RequestInfo | URL): boolean {\n try {\n const url = new URL(input instanceof Request ? input.url : String(input));\n return url.origin === new URL(this.core.baseUrl).origin;\n } catch {\n return false;\n }\n }\n\n private send(input: RequestInfo | URL, init: RequestInit | undefined, token: string): Promise<Response> {\n const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));\n headers.set(\"Authorization\", `Bearer ${token}`);\n headers.delete(\"x-api-key\"); // the Anthropic SDK's placeholder key\n return this.core.fetchImpl(input, { ...init, headers });\n }\n}\n\nconst signedOutResponse = () =>\n new Response(JSON.stringify({ error: { code: \"missing_token\", message: \"Sign in with Chabi to continue.\" } }), {\n status: 401,\n headers: { \"Content-Type\": \"application/json\", \"x-should-retry\": \"false\" },\n });\n\nasync function errorCode(res: Response): Promise<string | undefined> {\n const body = (await res.clone().json().catch(() => null)) as { error?: { code?: unknown } } | null;\n return typeof body?.error?.code === \"string\" ? body.error.code : undefined;\n}\n","// PKCE (RFC 7636) on Web Crypto, which browsers and Node 20+ both have as globalThis.crypto.\n\nconst base64url = (bytes: Uint8Array): string => {\n let s = \"\";\n for (const b of bytes) s += String.fromCharCode(b);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n};\n\n/** A random base64url string: 32 bytes gives 43 characters, the verifier length RFC 7636 recommends. */\nexport function randomString(bytes = 32): string {\n return base64url(globalThis.crypto.getRandomValues(new Uint8Array(bytes)));\n}\n\n/** The S256 code challenge for a verifier: base64url(SHA-256(verifier)). */\nexport async function challengeFor(verifier: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(verifier));\n return base64url(new Uint8Array(digest));\n}\n","import { ChabiError } from \"./errors.js\";\nimport type { ChangeListener, ChangeReason, RefreshLock, TokenStorage, Tokens } from \"./types.js\";\n\n/** Refresh this long before the access token expires, so a request never goes out with one about to lapse. */\nexport const REFRESH_EARLY_MS = 60_000;\n\nexport type SessionOptions = {\n baseUrl: string;\n clientId: string;\n storage: TokenStorage;\n lock: RefreshLock;\n fetch?: typeof fetch;\n now?: () => number;\n};\n\ntype TokenResponse = { access_token?: unknown; refresh_token?: unknown; expires_in?: unknown };\n\n/**\n * The signed-in user's tokens and everything that changes them. Each refresh token works once, and the gateway\n * ends the whole sign-in when one is sent twice, so every refresh runs inside `lock` and first rereads storage:\n * if another tab (or caller) already refreshed, its tokens are used instead.\n */\nexport class SessionCore {\n readonly baseUrl: string;\n readonly clientId: string;\n private readonly storage: TokenStorage;\n private readonly lock: RefreshLock;\n /** The underlying fetch, for requests that carry the user's token (see ChabiBase.fetch). */\n readonly fetchImpl: typeof fetch;\n private readonly now: () => number;\n private tokens: Tokens | null = null;\n // Bumped by sign-in and sign-out, so a refresh that finishes afterwards can't bring an old session back.\n private generation = 0;\n private readonly listeners = new Set<ChangeListener>();\n\n constructor(opts: SessionOptions) {\n this.baseUrl = opts.baseUrl.replace(/\\/+$/, \"\");\n this.clientId = opts.clientId;\n this.storage = opts.storage;\n this.lock = opts.lock;\n this.fetchImpl = opts.fetch ?? ((input, init) => globalThis.fetch(input, init));\n this.now = opts.now ?? Date.now;\n // Synchronous storage (the browser's) is read at once, so `signedIn` is right from the start.\n const loaded = this.storage.load();\n if (!isPromise(loaded)) this.tokens = loaded;\n else loaded.catch(() => {}); // asynchronous storage is read by load(); a failure here must not crash the app\n }\n\n get signedIn(): boolean {\n return this.tokens !== null;\n }\n\n /** Reads storage into memory. Needed once at start for asynchronous storage (Node, Electron). */\n async load(): Promise<void> {\n this.tokens = await this.storage.load();\n }\n\n /** The access token to send, refreshed first when it's within a minute of expiring. Null when signed out. */\n async accessToken(): Promise<string | null> {\n const t = this.tokens;\n if (!t) return null;\n if (t.expiresAt - this.now() > REFRESH_EARLY_MS) return t.accessToken;\n return this.refreshLocked(t.refreshToken, null);\n }\n\n /** The gateway said `rejected` is no longer valid: refresh, unless that already happened since it was sent. */\n async refreshAfterReject(rejected: string): Promise<string | null> {\n const t = this.tokens;\n if (!t) return null;\n if (t.accessToken !== rejected) return t.accessToken;\n return this.refreshLocked(t.refreshToken, rejected);\n }\n\n /** Swaps the code from the sign-in redirect for tokens, saves them and tells listeners. */\n async exchangeCode(p: { code: string; redirectUri: string; verifier: string }): Promise<void> {\n const res = await this.tokenRequest({\n grant_type: \"authorization_code\",\n code: p.code,\n redirect_uri: p.redirectUri,\n client_id: this.clientId,\n code_verifier: p.verifier,\n });\n const tokens = res.ok ? await this.parseTokens(res) : null;\n if (!tokens) {\n throw new ChabiError({ kind: \"signed_out\", status: res.status, code: \"sign_in_failed\", message: \"Sign-in didn't complete. Please try again.\" });\n }\n this.generation += 1;\n await this.storage.save(tokens);\n this.tokens = tokens;\n this.emit(true, \"signed_in\");\n }\n\n /** Forgets the tokens (memory and storage) and tells listeners why. */\n async end(reason: ChangeReason): Promise<void> {\n this.generation += 1;\n const was = this.tokens !== null;\n this.tokens = null;\n await this.storage.clear();\n if (was) this.emit(false, reason);\n }\n\n /** Another tab changed the stored tokens: take its copy, and tell listeners if that signed the user in or out. */\n adopt(tokens: Tokens | null): void {\n const was = this.tokens !== null;\n if (!tokens) this.generation += 1;\n this.tokens = tokens;\n if (was !== (tokens !== null)) this.emit(tokens !== null, tokens ? \"signed_in\" : \"signed_out\");\n }\n\n onChange(listener: ChangeListener): () => void {\n this.listeners.add(listener);\n return () => void this.listeners.delete(listener);\n }\n\n private emit(signedIn: boolean, reason: ChangeReason): void {\n for (const l of [...this.listeners]) {\n try {\n l(signedIn, reason);\n } catch {\n // A listener's own error must not break sign-in or a request.\n }\n }\n }\n\n private refreshLocked(startedWith: string, rejected: string | null): Promise<string | null> {\n return this.lock(async () => {\n const generation = this.generation;\n const stored = await this.storage.load();\n if (generation !== this.generation) return null;\n if (!stored) {\n this.adopt(null); // signed out elsewhere\n return null;\n }\n if (stored.refreshToken !== startedWith) {\n // Someone else refreshed while this caller waited for the lock: use theirs, never resend ours.\n this.tokens = stored;\n return stored.accessToken;\n }\n if (rejected === null && stored.expiresAt - this.now() > REFRESH_EARLY_MS) {\n this.tokens = stored;\n return stored.accessToken;\n }\n\n const res = await this.tokenRequest({ grant_type: \"refresh_token\", refresh_token: stored.refreshToken, client_id: this.clientId });\n if (generation !== this.generation) return null; // signed out while the request was out\n if (!res.ok) {\n if (res.status === 400 || res.status === 401) {\n await this.end(\"expired\");\n return null;\n }\n throw new ChabiError({ kind: \"provider_error\", status: res.status, message: \"Chabi is having trouble right now. Please try again.\" });\n }\n const fresh = await this.parseTokens(res);\n if (generation !== this.generation) return null; // signed out while the reply was read\n if (!fresh) throw new ChabiError({ kind: \"unknown\", status: res.status, message: \"Chabi sent an unexpected reply. Please try again.\" });\n await this.storage.save(fresh); // at once: the old refresh token is already spent\n if (generation !== this.generation) {\n // Signed out while saving: take back what this refresh wrote, but never a newer sign-in's tokens.\n if ((await this.storage.load())?.refreshToken === fresh.refreshToken) await this.storage.clear();\n return null;\n }\n this.tokens = fresh;\n return fresh.accessToken;\n });\n }\n\n private async tokenRequest(fields: Record<string, string>): Promise<Response> {\n try {\n return await this.fetchImpl(`${this.baseUrl}/oauth/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams(fields).toString(),\n });\n } catch {\n throw new ChabiError({ kind: \"network\", status: 0, message: \"Couldn't reach Chabi. Check your connection and try again.\" });\n }\n }\n\n private async parseTokens(res: Response): Promise<Tokens | null> {\n const b = (await res.json().catch(() => ({}))) as TokenResponse;\n if (typeof b.access_token !== \"string\" || typeof b.refresh_token !== \"string\" || typeof b.expires_in !== \"number\") return null;\n return { accessToken: b.access_token, refreshToken: b.refresh_token, expiresAt: this.now() + b.expires_in * 1000 };\n }\n}\n\nconst isPromise = <T>(v: T | Promise<T>): v is Promise<T> => typeof (v as { then?: unknown })?.then === \"function\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,uBAAiB;;;ACCV,IAAM,aAAN,cAAyB,MAAM;AAAA,EAC3B;AAAA,EACT,YAAY,MAAsB;AAChC,UAAM,KAAK,OAAO;AAClB,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAEA,IAAM,WAAsC;AAAA,EAC1C,gBAAgB;AAAA,EAChB,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,cAAc;AAAA,EAC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,EAC9B;AACF;AAGA,SAAS,cAA2B;AAClC,MAAI,OAAyB,QAAQ,QAAQ;AAC7C,SAAO,CAAC,QAAQ;AACd,UAAM,OAAO,KAAK,KAAK,KAAK,GAAG;AAC/B,WAAO,KAAK,MAAM,MAAM,MAAS;AACjC,WAAO;AAAA,EACT;AACF;AAEA,SAAS,kBAAkB,SAA0B;AACnD,QAAM,CAAC,OAAO,IAAI,IAChB,YAAY,cAAc,CAAC,oBAAoB,gDAAgD,IAC7F,YAAY,WAAW,CAAC,qBAAqB,4DAA4D,IACzG,CAAC,yBAAyB,mCAAmC;AACjE,SAAO,yIAAyI,KAAK,uVAAuV,KAAK,WAAW,IAAI;AAClgB;","names":["http","url","p"]}
@@ -0,0 +1,37 @@
1
+ import { C as ChabiBase, T as TokenStorage, d as Tokens } from './client-X74kWdDv.cjs';
2
+ export { a as ChabiErrorInfo, b as ChangeListener, c as ChangeReason, E as ErrorKind, R as RefreshLock } from './client-X74kWdDv.cjs';
3
+ export { C as ChabiError, d as describeError, a as describeResponse } from './errors-DcA-sSRY.cjs';
4
+
5
+ /** What the browser tab shows once it has handed the sign-in back. */
6
+ type Outcome = "signed_in" | "denied" | "failed";
7
+ type NodeOptions = {
8
+ clientId: string;
9
+ baseUrl?: string;
10
+ /** Where tokens live. In Electron, encrypt them with safeStorage; `memoryStorage()` keeps them for this run only. */
11
+ storage: TokenStorage;
12
+ /** Opens the sign-in page in the system browser (Electron: `shell.openExternal`). Never a web view in the app. */
13
+ openBrowser: (url: string) => void | Promise<void>;
14
+ /** Called the moment the browser comes back, before the tab is answered: bring the app's window to the front. */
15
+ onReturn?: () => void;
16
+ /** The HTML the tab shows afterwards. The default says the user can close the tab. */
17
+ returnPage?: (outcome: Outcome) => string;
18
+ /** How long to wait for the user to finish in the browser. Default 5 minutes. */
19
+ timeoutMs?: number;
20
+ };
21
+ declare class Chabi extends ChabiBase {
22
+ private readonly opts;
23
+ private readonly baseUrl;
24
+ constructor(opts: NodeOptions);
25
+ /** Reads the saved tokens. Await it once at start, before checking `signedIn`. */
26
+ load(): Promise<void>;
27
+ /**
28
+ * Opens Chabi in the system browser and waits for the user to come back. Resolves once signed in; throws a
29
+ * ChabiError if they declined (`access_denied`), the sign-in didn't come from here, or it timed out.
30
+ */
31
+ signIn(): Promise<void>;
32
+ }
33
+ /** Tokens kept in memory for this run only (tests, or when the OS has no keychain). */
34
+ declare function memoryStorage(initial?: Tokens | null): TokenStorage;
35
+
36
+ export { Chabi, ChabiBase, TokenStorage, Tokens, memoryStorage };
37
+ export type { NodeOptions, Outcome };
package/dist/node.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { C as ChabiBase, T as TokenStorage, d as Tokens } from './client-X74kWdDv.js';
2
+ export { a as ChabiErrorInfo, b as ChangeListener, c as ChangeReason, E as ErrorKind, R as RefreshLock } from './client-X74kWdDv.js';
3
+ export { C as ChabiError, d as describeError, a as describeResponse } from './errors-BD8FIApC.js';
4
+
5
+ /** What the browser tab shows once it has handed the sign-in back. */
6
+ type Outcome = "signed_in" | "denied" | "failed";
7
+ type NodeOptions = {
8
+ clientId: string;
9
+ baseUrl?: string;
10
+ /** Where tokens live. In Electron, encrypt them with safeStorage; `memoryStorage()` keeps them for this run only. */
11
+ storage: TokenStorage;
12
+ /** Opens the sign-in page in the system browser (Electron: `shell.openExternal`). Never a web view in the app. */
13
+ openBrowser: (url: string) => void | Promise<void>;
14
+ /** Called the moment the browser comes back, before the tab is answered: bring the app's window to the front. */
15
+ onReturn?: () => void;
16
+ /** The HTML the tab shows afterwards. The default says the user can close the tab. */
17
+ returnPage?: (outcome: Outcome) => string;
18
+ /** How long to wait for the user to finish in the browser. Default 5 minutes. */
19
+ timeoutMs?: number;
20
+ };
21
+ declare class Chabi extends ChabiBase {
22
+ private readonly opts;
23
+ private readonly baseUrl;
24
+ constructor(opts: NodeOptions);
25
+ /** Reads the saved tokens. Await it once at start, before checking `signedIn`. */
26
+ load(): Promise<void>;
27
+ /**
28
+ * Opens Chabi in the system browser and waits for the user to come back. Resolves once signed in; throws a
29
+ * ChabiError if they declined (`access_denied`), the sign-in didn't come from here, or it timed out.
30
+ */
31
+ signIn(): Promise<void>;
32
+ }
33
+ /** Tokens kept in memory for this run only (tests, or when the OS has no keychain). */
34
+ declare function memoryStorage(initial?: Tokens | null): TokenStorage;
35
+
36
+ export { Chabi, ChabiBase, TokenStorage, Tokens, memoryStorage };
37
+ export type { NodeOptions, Outcome };