@baclet/sdk 0.2.0 → 0.2.2

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.
Files changed (3) hide show
  1. package/README.md +325 -0
  2. package/dist/index.js +1 -1
  3. package/package.json +1 -1
package/README.md ADDED
@@ -0,0 +1,325 @@
1
+ # BACLET SDK
2
+
3
+ **Identity and user infrastructure for modern applications — in one typed, framework-agnostic client.**
4
+
5
+ `@baclet/sdk` is the official TypeScript/JavaScript client for BACLET. It gives your app a single, predictable interface for authentication, sessions, token refresh, OAuth redirects, and account recovery across browsers and server runtimes.
6
+
7
+ - **Typed by default** — complete TypeScript definitions ship with the package.
8
+ - **Framework agnostic** — use it with React, Next.js, Vue, Svelte, or plain JavaScript.
9
+ - **Session-aware** — access tokens, refresh tokens, and user state are managed for you.
10
+ - **Portable storage** — browser `localStorage` by default, in-memory fallback everywhere else.
11
+ - **Small surface area** — one client, one `auth` namespace, no lock-in.
12
+
13
+ ---
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install @baclet/sdk
19
+ ```
20
+
21
+ Requires Node.js 18+ or a modern browser with `fetch` support.
22
+
23
+ ### Where to get your keys
24
+
25
+ Open the dashboard, choose a workspace, then go to **Projects → your project → API Keys**. You can also use **API Keys** in the workspace sidebar and select **Manage keys** beside the project.
26
+
27
+ - **API URL** → use as `apiUrl`
28
+ - **Publishable key** → use as `publishableKey`; safe for client code
29
+ - **Secret key** → server-only; shown in full only when created or rotated
30
+
31
+ ---
32
+
33
+ ## Quickstart
34
+
35
+ ### 1. Initialize once
36
+
37
+ ```ts
38
+ import { initializeBaclet, getAuth } from "@baclet/sdk";
39
+
40
+ export const baclet = initializeBaclet({
41
+ apiUrl: process.env.BACLET_API_URL!,
42
+ publishableKey: process.env.BACLET_PUBLISHABLE_KEY!,
43
+ });
44
+
45
+ export const auth = getAuth(baclet);
46
+ ```
47
+
48
+ `initializeBaclet()` is idempotent. Calling it again with the same name and credentials returns the existing client. Calling it with different credentials throws a `BacletError` with status `409`.
49
+
50
+ The client derives your project ID from the publishable key (`pb_<uuid>_...`), so there is no separate project ID to configure.
51
+
52
+ ### 2. Sign a user in
53
+
54
+ ```ts
55
+ const session = await auth.signIn({
56
+ email: "ada@example.com",
57
+ password: "correct-horse-battery-staple",
58
+ });
59
+
60
+ console.log(session.user.display_name);
61
+ ```
62
+
63
+ A successful sign-in persists the session and notifies every `onAuthStateChanged` listener.
64
+
65
+ ### 3. Read the current session
66
+
67
+ ```ts
68
+ const session = await auth.getSession();
69
+
70
+ if (session) {
71
+ console.log("Signed in as", session.user.email ?? session.user.id);
72
+ } else {
73
+ console.log("No active session");
74
+ }
75
+ ```
76
+
77
+ `getSession()` validates the stored access token against `/me`. If the token is expired and `autoRefresh` is enabled, it refreshes the session automatically before giving up.
78
+
79
+ ---
80
+
81
+ ## Configuration
82
+
83
+ ### `initializeBaclet(config, name?)`
84
+
85
+ Registers a named client in the SDK registry. Defaults to `"DEFAULT"`.
86
+
87
+ ```ts
88
+ const baclet = initializeBaclet(config, "MARKETING_SITE");
89
+ const auth = getAuth(getBaclet("MARKETING_SITE"));
90
+ ```
91
+
92
+ ### `createBacletClient(options)`
93
+
94
+ Creates an isolated client without registering it. Useful for servers, tests, and multi-project processes.
95
+
96
+ ```ts
97
+ import { createBacletClient } from "@baclet/sdk";
98
+
99
+ const baclet = createBacletClient({
100
+ apiUrl: process.env.BACLET_API_URL!,
101
+ publishableKey: process.env.BACLET_PUBLISHABLE_KEY!,
102
+ storage: null,
103
+ autoRefresh: false,
104
+ });
105
+ ```
106
+
107
+ | Option | Type | Default | Description |
108
+ | --- | --- | --- | --- |
109
+ | `apiUrl` | `string` | required | Base BACLET API URL. `https://` is added when omitted; a trailing `/v1` is removed automatically. |
110
+ | `publishableKey` | `string` | required | Your project publishable key. Safe to use in browser bundles. |
111
+ | `secretKey` | `string` | `undefined` | Optional server-side key. Validated when provided; omit it from browser code. |
112
+ | `storage` | `StorageLike \| null` | `localStorage`, or memory | Custom key/value store. Pass `null` to force in-memory storage. |
113
+ | `autoRefresh` | `boolean` | `true` | Refresh the session automatically when `getSession()` sees an expired access token. |
114
+ | `fetch` | `typeof fetch` | `globalThis.fetch` | Custom fetch implementation for non-standard runtimes. |
115
+
116
+ A `StorageLike` object only needs `getItem`, `setItem`, and `removeItem`.
117
+
118
+ ---
119
+
120
+ ## Authentication
121
+
122
+ All methods are available on `baclet.auth` and directly on the client.
123
+
124
+ ### Email and password
125
+
126
+ ```ts
127
+ const session = await auth.signUp({
128
+ fullName: "Ada Lovelace",
129
+ email: "ada@example.com",
130
+ password: "correct-horse-battery-staple",
131
+ });
132
+
133
+ await auth.signIn({ email: "ada@example.com", password: "correct-horse-battery-staple" });
134
+ ```
135
+
136
+ | Method | Returns | Notes |
137
+ | --- | --- | --- |
138
+ | `signUp(input)` | `BacletSession` | Creates the account and signs it in immediately. |
139
+ | `signIn(input)` | `BacletSession` | Exchanges credentials for a session. |
140
+ | `signInAnonymously()` | `BacletSession` | Creates a guest session. |
141
+ | `signOut()` | `void` | Revokes the server-side session when possible, then clears local state. |
142
+ | `signOutWithTokens(accessToken, refreshToken?)` | `{ message }` | Server-side sign-out for explicit tokens. |
143
+
144
+ ### Account verification and recovery
145
+
146
+ ```ts
147
+ await auth.resendVerification("ada@example.com");
148
+ await auth.verifyEmail(tokenFromEmail);
149
+
150
+ await auth.forgotPassword("ada@example.com");
151
+ await auth.resetPassword(tokenFromEmail, "a-new-strong-password");
152
+ ```
153
+
154
+ | Method | Returns |
155
+ | --- | --- |
156
+ | `verifyEmail(token)` | `{ message }` |
157
+ | `resendVerification(email)` | `{ message }` |
158
+ | `forgotPassword(email)` | `{ message }` |
159
+ | `resetPassword(token, password)` | `{ message }` |
160
+
161
+ ### Google sign-in
162
+
163
+ ```ts
164
+ // Redirect the browser to Google and return the generated URL.
165
+ const url = await auth.signInWithGoogle({
166
+ redirectTo: "/dashboard",
167
+ });
168
+ ```
169
+
170
+ On your callback page:
171
+
172
+ ```ts
173
+ const session = await auth.handleOAuthRedirect();
174
+ ```
175
+
176
+ `handleOAuthRedirect()` reads tokens from the URL fragment, clears the fragment from browser history, persists the session, and returns it. If the provider reports an error, it clears local session state and throws a `BacletError`.
177
+
178
+ Use `getGoogleAuthorizationURL()` when you want to handle navigation yourself:
179
+
180
+ ```ts
181
+ const url = await auth.getGoogleAuthorizationURL({ redirectTo: "/dashboard" });
182
+ window.location.assign(url);
183
+ ```
184
+
185
+ Pass `redirect: false` to `signInWithGoogle()` to receive the URL without navigating.
186
+
187
+ ---
188
+
189
+ ## Sessions and state
190
+
191
+ ### Session methods
192
+
193
+ | Method | Returns | Notes |
194
+ | --- | --- | --- |
195
+ | `getSession()` | `BacletSession \| null` | Validates stored tokens; refreshes on `401` when enabled. |
196
+ | `refreshSession(refreshToken?)` | `BacletSession` | Uses the stored refresh token when none is passed. |
197
+ | `getUser()` | `BacletUser \| null` | Convenience wrapper around `getSession()`. |
198
+ | `getUserByToken(accessToken)` | `BacletUser` | Looks up a user for an explicitly supplied token. |
199
+ | `capabilities()` | `AuthCapabilities` | Returns enabled providers and auth setup status. |
200
+
201
+ ### React example
202
+
203
+ ```tsx
204
+ "use client";
205
+
206
+ import { useEffect, useState } from "react";
207
+ import { getAuth, type BacletSession } from "@baclet/sdk";
208
+
209
+ const auth = getAuth();
210
+
211
+ export function AuthBoundary() {
212
+ const [session, setSession] = useState<BacletSession | null>(null);
213
+
214
+ useEffect(() => {
215
+ void auth.getSession().then(setSession);
216
+ return auth.onAuthStateChanged(setSession);
217
+ }, []);
218
+
219
+ if (!session) return <SignInButton />;
220
+
221
+ return <span>Welcome, {session.user.display_name}</span>;
222
+ }
223
+ ```
224
+
225
+ `onAuthStateChanged()` returns an unsubscribe function. It emits on local session writes and clears.
226
+
227
+ ### Server-side example
228
+
229
+ ```ts
230
+ import { createBacletClient } from "@baclet/sdk";
231
+
232
+ const baclet = createBacletClient({
233
+ apiUrl: process.env.BACLET_API_URL!,
234
+ publishableKey: process.env.BACLET_PUBLISHABLE_KEY!,
235
+ storage: null,
236
+ });
237
+
238
+ export async function getCurrentUser(accessToken: string) {
239
+ return baclet.auth.getUserByToken(accessToken);
240
+ }
241
+ ```
242
+
243
+ Passing `storage: null` prevents server processes from sharing session state through a global memory store.
244
+
245
+ ---
246
+
247
+ ## Errors
248
+
249
+ Every non-2xx response becomes a `BacletError` with a numeric `status` and the parsed response body in `details`.
250
+
251
+ ```ts
252
+ import { BacletError } from "@baclet/sdk";
253
+
254
+ try {
255
+ await auth.signIn({ email, password });
256
+ } catch (error) {
257
+ if (error instanceof BacletError) {
258
+ console.error(error.status, error.message, error.details);
259
+ } else {
260
+ throw error;
261
+ }
262
+ }
263
+ ```
264
+
265
+ Common statuses include `400` for invalid configuration or input, `401` for expired or missing credentials, `404` for an unregistered named client, and `409` for conflicting initialization.
266
+
267
+ ---
268
+
269
+ ## API surface
270
+
271
+ ```ts
272
+ import Baclet, {
273
+ BacletClient,
274
+ BacletError,
275
+ createBacletClient,
276
+ getAuth,
277
+ getBaclet,
278
+ initializeBaclet,
279
+ } from "@baclet/sdk";
280
+
281
+ import type {
282
+ AuthCapabilities,
283
+ AuthStateListener,
284
+ BacletClientOptions,
285
+ BacletConfig,
286
+ BacletSession,
287
+ BacletTokens,
288
+ BacletUser,
289
+ GoogleSignInOptions,
290
+ SignInInput,
291
+ SignUpInput,
292
+ StorageLike,
293
+ } from "@baclet/sdk";
294
+ ```
295
+
296
+ `Baclet` is an alias for `BacletClient`. The class is also the default export.
297
+
298
+ ---
299
+
300
+ ## Security notes
301
+
302
+ - Use `publishableKey` in client applications. It is designed to be public.
303
+ - Do not bundle `secretKey` into browser code.
304
+ - Sessions are stored under `baclet:<project-id>:tokens` and `baclet:<project-id>:user`.
305
+ - Provide a custom `storage` implementation when your environment needs encrypted, persisted, or scoped storage.
306
+ - Always call `handleOAuthRedirect()` before rendering protected UI on your OAuth callback route.
307
+
308
+ ---
309
+
310
+ ## Development
311
+
312
+ ```bash
313
+ npm install
314
+ npm run build
315
+ npm run typecheck
316
+ npm test
317
+ ```
318
+
319
+ `npm test` rebuilds `dist` before running the Node test suite.
320
+
321
+ ---
322
+
323
+ ## BACLET
324
+
325
+ BACLET is built for teams that want production-grade user infrastructure without assembling it from scratch. This SDK is the client layer: small, typed, and designed to stay out of your way as your application grows.
package/dist/index.js CHANGED
@@ -119,7 +119,7 @@ export class BacletClient {
119
119
  this.secretKey = options.secretKey;
120
120
  this.projectID = projectIDFromKey(options.publishableKey);
121
121
  this.storage = resolveStorage(options.storage);
122
- this.fetchImpl = options.fetch ?? globalThis.fetch;
122
+ this.fetchImpl = (options.fetch ?? globalThis.fetch).bind(globalThis);
123
123
  if (typeof this.fetchImpl !== "function") {
124
124
  throw new BacletError("This runtime does not provide fetch; pass options.fetch.", 500);
125
125
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@baclet/sdk",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "BACLET users database SDK for browsers and servers",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",