@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/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0 (2026-11-29)
4
+
5
+ - `chabiAI(chabi, options?)` from `@chabi/js/ai`: the client for other makers' models (ids like `vendor/model`), chat and images. It's the official OpenAI client with Chabi's address and the user's token, so `openai` is now an optional peer dependency, needed only for `@chabi/js/ai`. Nothing else changes.
6
+
7
+ ## 0.1.0 (2026-11-29)
8
+
9
+ First release.
10
+
11
+ - Browser sign-in with redirect and PKCE: `Chabi`, `signIn()`, `handleRedirect()`. Tokens live in localStorage, and refreshes run one at a time across tabs.
12
+ - Node and Electron sign-in through the system browser and a loopback return: `@chabi/js/node`, with `memoryStorage()`.
13
+ - `openai()`, `anthropic()` and `fetch` for the official OpenAI and Anthropic SDKs. Expired tokens are refreshed and the request sent again; removed access signs the user out.
14
+ - `onChange`, `credits()`, `me()` and `signOut()`.
15
+ - `describeError` and `describeResponse` for Chabi's, OpenAI's and Anthropic's errors.
16
+ - `signInButton()`, the required Sign in with Chabi button.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aarit Gupta
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,184 @@
1
- # Temporary Holding Version
1
+ # @chabi/js
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Sign in with Chabi.** Your users bring their own AI: their Chabi plan covers the AI your app uses, so you skip the AI bill and earn a share of their subscription.
4
+
5
+ This package does the sign-in. It runs the OAuth flow, keeps each user's tokens, refreshes them (one refresh at a time, across tabs), and signs the user out when they remove your app's access. The official [OpenAI](https://www.npmjs.com/package/openai) and [Anthropic](https://www.npmjs.com/package/@anthropic-ai/sdk) SDKs still make every request: this package only gives them Chabi's address and the user's token.
6
+
7
+ No dependencies. ESM and CommonJS, with types. Node 20 or later, and every current browser.
8
+
9
+ ```sh
10
+ npm install @chabi/js
11
+ ```
12
+
13
+ Register your app in the [developer portal](https://chabi.dev/developers/portal) for a client ID, and add every redirect URI your app signs in from. Full docs: [chabi.dev/docs](https://chabi.dev/docs).
14
+
15
+ ## In the browser
16
+
17
+ ```js
18
+ import { Chabi, signInButton, describeError } from "@chabi/js";
19
+ import OpenAI from "openai";
20
+
21
+ const chabi = new Chabi({
22
+ clientId: "<your client_id>",
23
+ redirectUri: "https://myapp.com/", // exactly as registered
24
+ });
25
+
26
+ // On every page load: finishes the sign-in when the user comes back from Chabi.
27
+ await chabi.handleRedirect().catch((err) => showError(err.info.message));
28
+
29
+ if (!chabi.signedIn) {
30
+ const button = signInButton(); // the required Sign in with Chabi button
31
+ button.onclick = () => chabi.signIn();
32
+ document.body.append(button);
33
+ }
34
+
35
+ // Signed in or out, here or in another tab.
36
+ chabi.onChange((signedIn, reason) => render(signedIn, reason));
37
+
38
+ const openai = new OpenAI({ ...chabi.openai(), dangerouslyAllowBrowser: true });
39
+ const reply = await openai.chat.completions.create({
40
+ model: "gpt-6-luna",
41
+ messages: [{ role: "user", content: "Hello" }],
42
+ max_completion_tokens: 4096,
43
+ });
44
+ ```
45
+
46
+ `dangerouslyAllowBrowser` is safe here: the token only spends this user's credits, in your app.
47
+
48
+ Claude models work the same way:
49
+
50
+ ```js
51
+ import Anthropic from "@anthropic-ai/sdk";
52
+
53
+ const anthropic = new Anthropic({ ...chabi.anthropic(), dangerouslyAllowBrowser: true });
54
+ ```
55
+
56
+ ### `new Chabi(options)`
57
+
58
+ | Option | |
59
+ |---|---|
60
+ | `clientId` | From the developer portal. |
61
+ | `redirectUri` | Where Chabi sends the user back. It must exactly match one registered for the app. |
62
+ | `baseUrl` | Defaults to `https://chabi.dev`. |
63
+ | `storage` | Replaces localStorage: `{ load, save, clear }`, each sync or async. |
64
+ | `lock` | Replaces the Web Locks lock that keeps refreshes one at a time across tabs. |
65
+
66
+ | Method | |
67
+ |---|---|
68
+ | `signIn()` | Sends the user to Chabi to sign in and allow your app. They come back to `redirectUri`. |
69
+ | `handleRedirect()` | Call on every page load. Resolves `true` if this load finished a sign-in, `false` otherwise. Throws a `ChabiError` if the sign-in failed (`kind` is `access_denied` when the user declined). It removes only the sign-in parameters from the address bar and keeps your app's own. |
70
+
71
+ ## Other makers' models: `chabiAI`
72
+
73
+ GPT stays on the OpenAI SDK and Claude on the Anthropic SDK. Every other maker's model (DeepSeek, Mistral, Llama, Qwen, xAI and the rest, ids like `vendor/model`) goes through `chabiAI`, from `@chabi/js/ai`:
74
+
75
+ ```js
76
+ import { chabiAI } from "@chabi/js/ai";
77
+
78
+ const ai = chabiAI(chabi);
79
+
80
+ const reply = await ai.chat.completions.create({
81
+ model: "deepseek/deepseek-v4-flash",
82
+ messages: [{ role: "user", content: "Write a haiku about keys." }],
83
+ max_tokens: 1024,
84
+ });
85
+
86
+ const image = await ai.images.generate({
87
+ model: "black-forest-labs/flux-3-image",
88
+ prompt: "A brass key on a gold circle, flat illustration",
89
+ });
90
+ ```
91
+
92
+ These models speak OpenAI's API, the common format for many models behind one address, so `chabiAI` returns the official OpenAI client with Chabi's address and the user's token: streaming, tools and types work as its docs say. It needs `openai` installed (`npm install openai`). Pass any OpenAI client option except `baseURL`, `apiKey` and `fetch`, such as `chabiAI(chabi, { maxRetries: 0 })`. In a browser it's allowed without `dangerouslyAllowBrowser`. The full list of models is at [chabi.dev/docs/models](https://chabi.dev/docs/models).
93
+
94
+ ## In Node and Electron
95
+
96
+ Sign-in opens the system browser and comes back to a loopback address on this machine. Register `http://127.0.0.1/callback` as a redirect URI; any port works.
97
+
98
+ ```js
99
+ import { Chabi } from "@chabi/js/node";
100
+ import { app, shell } from "electron";
101
+ import OpenAI from "openai";
102
+
103
+ const chabi = new Chabi({
104
+ clientId: "<your client_id>",
105
+ storage: keychainStorage, // { load, save, clear }: encrypt with Electron's safeStorage
106
+ openBrowser: (url) => shell.openExternal(url),
107
+ onReturn: () => { win.show(); app.focus({ steal: true }); },
108
+ });
109
+
110
+ await chabi.load();
111
+ if (!chabi.signedIn) await chabi.signIn();
112
+
113
+ const openai = new OpenAI(chabi.openai());
114
+ ```
115
+
116
+ ### `new Chabi(options)` from `@chabi/js/node`
117
+
118
+ | Option | |
119
+ |---|---|
120
+ | `clientId` | From the developer portal. |
121
+ | `storage` | Required. Where the tokens live: `{ load, save, clear }`. Keep them in the OS keychain, or encrypted with Electron's `safeStorage`, never in a plain file. `memoryStorage()` keeps them for one run. |
122
+ | `openBrowser(url)` | Opens the sign-in page in the system browser (Electron: `shell.openExternal`). Never a web view inside your app. |
123
+ | `onReturn()` | Called the moment the browser comes back, before the tab is answered: bring your window to the front. |
124
+ | `returnPage(outcome)` | The HTML the browser tab shows afterwards (`signed_in`, `denied` or `failed`). The default tells the user they can close the tab. |
125
+ | `timeoutMs` | How long to wait for the user. Default 5 minutes. |
126
+ | `baseUrl` | Defaults to `https://chabi.dev`. |
127
+
128
+ | Method | |
129
+ |---|---|
130
+ | `load()` | Reads the saved tokens. Await it once at start, before checking `signedIn`. |
131
+ | `signIn()` | Opens Chabi in the system browser and resolves once the user is back and signed in. Throws a `ChabiError` if they declined, it timed out, or the return didn't come from this sign-in. |
132
+
133
+ ## Both
134
+
135
+ | | |
136
+ |---|---|
137
+ | `openai()` | Options for `new OpenAI(...)`: Chabi's URL, a placeholder key, and `fetch`. `chabiAI(chabi)` from `@chabi/js/ai` makes that client for you. |
138
+ | `anthropic()` | The same for `new Anthropic(...)`. |
139
+ | `fetch` | A `fetch` that adds the user's token to requests to Chabi, refreshing it when needed. Requests to any other address go out untouched, with no token. |
140
+ | `signedIn` | Whether a user is signed in. |
141
+ | `onChange((signedIn, reason) => …)` | Called when that changes. `reason` is `signed_in`, `signed_out`, `access_removed` (the user removed your app's access) or `expired`. Returns a function that unsubscribes. |
142
+ | `credits()` | The user's credit balance. |
143
+ | `me()` | `{ name }`, the name on the user's Chabi account (or `null`). |
144
+ | `signOut()` | Signs the user out of your app on this device. |
145
+
146
+ When a request comes back 401 with an expired token, the SDK refreshes and sends it again once. When the user's access is gone, it signs out and calls `onChange(false, "access_removed")`.
147
+
148
+ ## Errors
149
+
150
+ `describeError(err)` reads any error, whether from Chabi, the OpenAI SDK or the Anthropic SDK, into one shape:
151
+
152
+ ```js
153
+ try {
154
+ await openai.chat.completions.create(request);
155
+ } catch (err) {
156
+ const e = describeError(err);
157
+ if (e.kind === "out_of_credits") location.assign(e.upgradeUrl);
158
+ else if (e.kind === "app_limit") location.assign(e.manageUrl);
159
+ else showError(e.message); // plain English
160
+ }
161
+ ```
162
+
163
+ | `kind` | When | Extra |
164
+ |---|---|---|
165
+ | `out_of_credits` | 402: the user doesn't have enough credits for this request. A smaller `max_tokens` may fit. | `upgradeUrl` |
166
+ | `app_limit` | 402: the user's monthly limit for your app would be passed. | `manageUrl` |
167
+ | `signed_out` | 401: no user is signed in, or their access is gone. | |
168
+ | `access_denied` | The user chose not to allow your app. | |
169
+ | `rate_limited` | 429: too many requests. | `retryAfter` (seconds) |
170
+ | `app_suspended` | 403: your app is suspended. | |
171
+ | `bad_request` | 400 or 413: the request was refused, e.g. a model Chabi doesn't serve. | |
172
+ | `provider_error` | 5xx: Chabi or the model's provider had trouble. | |
173
+ | `network` | Chabi couldn't be reached. | |
174
+ | `unknown` | Anything else. | |
175
+
176
+ Every result has `kind`, `message`, `status` and, from Chabi, `code`. `describeResponse(res)` does the same for a `Response` from `chabi.fetch`. The SDK's own errors are `ChabiError`s, with the same shape in `err.info`.
177
+
178
+ ## The button
179
+
180
+ Every "Sign in with Chabi" button must show the Chabi key logo before the words, so users recognise it in every app. `signInButton()` makes one in gold, `signInButton({ style: "dark" })` in dark, and `label` can change the words to "Continue with Chabi". You may change its size, padding and corner radius. Don't redraw, recolor, stretch, rotate or crop the logo, and keep it at least 20px.
181
+
182
+ ## Versions
183
+
184
+ This package follows semver. Until 1.0, a minor version may change the API; the [changelog](./CHANGELOG.md) says what changed.
package/dist/ai.cjs ADDED
@@ -0,0 +1,49 @@
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/ai.ts
31
+ var ai_exports = {};
32
+ __export(ai_exports, {
33
+ chabiAI: () => chabiAI
34
+ });
35
+ module.exports = __toCommonJS(ai_exports);
36
+ var import_openai = __toESM(require("openai"), 1);
37
+ function chabiAI(chabi, options = {}) {
38
+ return new import_openai.default({
39
+ // The token only spends this user's credits in this app, so it's safe in a browser.
40
+ dangerouslyAllowBrowser: typeof window !== "undefined" && typeof window.document !== "undefined",
41
+ ...options,
42
+ ...chabi.openai()
43
+ });
44
+ }
45
+ // Annotate the CommonJS export names for ESM import in node:
46
+ 0 && (module.exports = {
47
+ chabiAI
48
+ });
49
+ //# sourceMappingURL=ai.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ai.ts"],"sourcesContent":["// The client for every other maker's models (DeepSeek, Mistral, Llama, Qwen, xAI and the rest, ids like\n// \"vendor/model\"), chat and images. They speak OpenAI's API, the common format for many models behind one address,\n// so this is the official OpenAI SDK with Chabi's address and the signed-in user's token: streaming, tools and types\n// work as documented. OpenAI's own models are just as happy here, but apps usually keep them on\n// `new OpenAI(chabi.openai())`; Claude models are served on /v1/messages, through `new Anthropic(chabi.anthropic())`.\nimport OpenAI, { type ClientOptions } from \"openai\";\nimport type { ChabiBase } from \"./client.js\";\n\n/** OpenAI client options an app may set. Chabi's address, the key and fetch always come from the signed-in user. */\nexport type ChabiAIOptions = Omit<ClientOptions, \"baseURL\" | \"apiKey\" | \"fetch\">;\n\n/** The client that `chabiAI` returns: the official OpenAI client. */\nexport type ChabiAI = OpenAI;\n\n/**\n * A client for other makers' models on Chabi: `ai.chat.completions.create` and `ai.images.generate` with ids like\n * \"deepseek/deepseek-v4-flash\". Needs the `openai` package installed.\n */\nexport function chabiAI(chabi: Pick<ChabiBase, \"openai\">, options: ChabiAIOptions = {}): ChabiAI {\n return new OpenAI({\n // The token only spends this user's credits in this app, so it's safe in a browser.\n dangerouslyAllowBrowser: typeof window !== \"undefined\" && typeof window.document !== \"undefined\",\n ...options,\n ...chabi.openai(),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,oBAA2C;AAapC,SAAS,QAAQ,OAAkC,UAA0B,CAAC,GAAY;AAC/F,SAAO,IAAI,cAAAA,QAAO;AAAA;AAAA,IAEhB,yBAAyB,OAAO,WAAW,eAAe,OAAO,OAAO,aAAa;AAAA,IACrF,GAAG;AAAA,IACH,GAAG,MAAM,OAAO;AAAA,EAClB,CAAC;AACH;","names":["OpenAI"]}
package/dist/ai.d.cts ADDED
@@ -0,0 +1,15 @@
1
+ import OpenAI, { ClientOptions } from 'openai';
2
+ import { ChabiBase } from './browser.cjs';
3
+
4
+ /** OpenAI client options an app may set. Chabi's address, the key and fetch always come from the signed-in user. */
5
+ type ChabiAIOptions = Omit<ClientOptions, "baseURL" | "apiKey" | "fetch">;
6
+ /** The client that `chabiAI` returns: the official OpenAI client. */
7
+ type ChabiAI = OpenAI;
8
+ /**
9
+ * A client for other makers' models on Chabi: `ai.chat.completions.create` and `ai.images.generate` with ids like
10
+ * "deepseek/deepseek-v4-flash". Needs the `openai` package installed.
11
+ */
12
+ declare function chabiAI(chabi: Pick<ChabiBase, "openai">, options?: ChabiAIOptions): ChabiAI;
13
+
14
+ export { chabiAI };
15
+ export type { ChabiAI, ChabiAIOptions };
package/dist/ai.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import OpenAI, { ClientOptions } from 'openai';
2
+ import { ChabiBase } from './browser.js';
3
+
4
+ /** OpenAI client options an app may set. Chabi's address, the key and fetch always come from the signed-in user. */
5
+ type ChabiAIOptions = Omit<ClientOptions, "baseURL" | "apiKey" | "fetch">;
6
+ /** The client that `chabiAI` returns: the official OpenAI client. */
7
+ type ChabiAI = OpenAI;
8
+ /**
9
+ * A client for other makers' models on Chabi: `ai.chat.completions.create` and `ai.images.generate` with ids like
10
+ * "deepseek/deepseek-v4-flash". Needs the `openai` package installed.
11
+ */
12
+ declare function chabiAI(chabi: Pick<ChabiBase, "openai">, options?: ChabiAIOptions): ChabiAI;
13
+
14
+ export { chabiAI };
15
+ export type { ChabiAI, ChabiAIOptions };
package/dist/ai.js ADDED
@@ -0,0 +1,14 @@
1
+ // src/ai.ts
2
+ import OpenAI from "openai";
3
+ function chabiAI(chabi, options = {}) {
4
+ return new OpenAI({
5
+ // The token only spends this user's credits in this app, so it's safe in a browser.
6
+ dangerouslyAllowBrowser: typeof window !== "undefined" && typeof window.document !== "undefined",
7
+ ...options,
8
+ ...chabi.openai()
9
+ });
10
+ }
11
+ export {
12
+ chabiAI
13
+ };
14
+ //# sourceMappingURL=ai.js.map
package/dist/ai.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ai.ts"],"sourcesContent":["// The client for every other maker's models (DeepSeek, Mistral, Llama, Qwen, xAI and the rest, ids like\n// \"vendor/model\"), chat and images. They speak OpenAI's API, the common format for many models behind one address,\n// so this is the official OpenAI SDK with Chabi's address and the signed-in user's token: streaming, tools and types\n// work as documented. OpenAI's own models are just as happy here, but apps usually keep them on\n// `new OpenAI(chabi.openai())`; Claude models are served on /v1/messages, through `new Anthropic(chabi.anthropic())`.\nimport OpenAI, { type ClientOptions } from \"openai\";\nimport type { ChabiBase } from \"./client.js\";\n\n/** OpenAI client options an app may set. Chabi's address, the key and fetch always come from the signed-in user. */\nexport type ChabiAIOptions = Omit<ClientOptions, \"baseURL\" | \"apiKey\" | \"fetch\">;\n\n/** The client that `chabiAI` returns: the official OpenAI client. */\nexport type ChabiAI = OpenAI;\n\n/**\n * A client for other makers' models on Chabi: `ai.chat.completions.create` and `ai.images.generate` with ids like\n * \"deepseek/deepseek-v4-flash\". Needs the `openai` package installed.\n */\nexport function chabiAI(chabi: Pick<ChabiBase, \"openai\">, options: ChabiAIOptions = {}): ChabiAI {\n return new OpenAI({\n // The token only spends this user's credits in this app, so it's safe in a browser.\n dangerouslyAllowBrowser: typeof window !== \"undefined\" && typeof window.document !== \"undefined\",\n ...options,\n ...chabi.openai(),\n });\n}\n"],"mappings":";AAKA,OAAO,YAAoC;AAapC,SAAS,QAAQ,OAAkC,UAA0B,CAAC,GAAY;AAC/F,SAAO,IAAI,OAAO;AAAA;AAAA,IAEhB,yBAAyB,OAAO,WAAW,eAAe,OAAO,OAAO,aAAa;AAAA,IACrF,GAAG;AAAA,IACH,GAAG,MAAM,OAAO;AAAA,EAClB,CAAC;AACH;","names":[]}