@baclet/sdk 0.0.0-stage → 0.2.1

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/README.md CHANGED
@@ -1,3 +1,317 @@
1
- # Temporary Holding Version
1
+ # BACLET SDK
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
+ **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
+ ---
24
+
25
+ ## Quickstart
26
+
27
+ ### 1. Initialize once
28
+
29
+ ```ts
30
+ import { initializeBaclet, getAuth } from "@baclet/sdk";
31
+
32
+ export const baclet = initializeBaclet({
33
+ apiUrl: process.env.BACLET_API_URL!,
34
+ publishableKey: process.env.BACLET_PUBLISHABLE_KEY!,
35
+ });
36
+
37
+ export const auth = getAuth(baclet);
38
+ ```
39
+
40
+ `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`.
41
+
42
+ The client derives your project ID from the publishable key (`pb_<uuid>_...`), so there is no separate project ID to configure.
43
+
44
+ ### 2. Sign a user in
45
+
46
+ ```ts
47
+ const session = await auth.signIn({
48
+ email: "ada@example.com",
49
+ password: "correct-horse-battery-staple",
50
+ });
51
+
52
+ console.log(session.user.display_name);
53
+ ```
54
+
55
+ A successful sign-in persists the session and notifies every `onAuthStateChanged` listener.
56
+
57
+ ### 3. Read the current session
58
+
59
+ ```ts
60
+ const session = await auth.getSession();
61
+
62
+ if (session) {
63
+ console.log("Signed in as", session.user.email ?? session.user.id);
64
+ } else {
65
+ console.log("No active session");
66
+ }
67
+ ```
68
+
69
+ `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.
70
+
71
+ ---
72
+
73
+ ## Configuration
74
+
75
+ ### `initializeBaclet(config, name?)`
76
+
77
+ Registers a named client in the SDK registry. Defaults to `"DEFAULT"`.
78
+
79
+ ```ts
80
+ const baclet = initializeBaclet(config, "MARKETING_SITE");
81
+ const auth = getAuth(getBaclet("MARKETING_SITE"));
82
+ ```
83
+
84
+ ### `createBacletClient(options)`
85
+
86
+ Creates an isolated client without registering it. Useful for servers, tests, and multi-project processes.
87
+
88
+ ```ts
89
+ import { createBacletClient } from "@baclet/sdk";
90
+
91
+ const baclet = createBacletClient({
92
+ apiUrl: process.env.BACLET_API_URL!,
93
+ publishableKey: process.env.BACLET_PUBLISHABLE_KEY!,
94
+ storage: null,
95
+ autoRefresh: false,
96
+ });
97
+ ```
98
+
99
+ | Option | Type | Default | Description |
100
+ | --- | --- | --- | --- |
101
+ | `apiUrl` | `string` | required | Base BACLET API URL. `https://` is added when omitted; a trailing `/v1` is removed automatically. |
102
+ | `publishableKey` | `string` | required | Your project publishable key. Safe to use in browser bundles. |
103
+ | `secretKey` | `string` | `undefined` | Optional server-side key. Validated when provided; omit it from browser code. |
104
+ | `storage` | `StorageLike \| null` | `localStorage`, or memory | Custom key/value store. Pass `null` to force in-memory storage. |
105
+ | `autoRefresh` | `boolean` | `true` | Refresh the session automatically when `getSession()` sees an expired access token. |
106
+ | `fetch` | `typeof fetch` | `globalThis.fetch` | Custom fetch implementation for non-standard runtimes. |
107
+
108
+ A `StorageLike` object only needs `getItem`, `setItem`, and `removeItem`.
109
+
110
+ ---
111
+
112
+ ## Authentication
113
+
114
+ All methods are available on `baclet.auth` and directly on the client.
115
+
116
+ ### Email and password
117
+
118
+ ```ts
119
+ const session = await auth.signUp({
120
+ fullName: "Ada Lovelace",
121
+ email: "ada@example.com",
122
+ password: "correct-horse-battery-staple",
123
+ });
124
+
125
+ await auth.signIn({ email: "ada@example.com", password: "correct-horse-battery-staple" });
126
+ ```
127
+
128
+ | Method | Returns | Notes |
129
+ | --- | --- | --- |
130
+ | `signUp(input)` | `BacletSession` | Creates the account and signs it in immediately. |
131
+ | `signIn(input)` | `BacletSession` | Exchanges credentials for a session. |
132
+ | `signInAnonymously()` | `BacletSession` | Creates a guest session. |
133
+ | `signOut()` | `void` | Revokes the server-side session when possible, then clears local state. |
134
+ | `signOutWithTokens(accessToken, refreshToken?)` | `{ message }` | Server-side sign-out for explicit tokens. |
135
+
136
+ ### Account verification and recovery
137
+
138
+ ```ts
139
+ await auth.resendVerification("ada@example.com");
140
+ await auth.verifyEmail(tokenFromEmail);
141
+
142
+ await auth.forgotPassword("ada@example.com");
143
+ await auth.resetPassword(tokenFromEmail, "a-new-strong-password");
144
+ ```
145
+
146
+ | Method | Returns |
147
+ | --- | --- |
148
+ | `verifyEmail(token)` | `{ message }` |
149
+ | `resendVerification(email)` | `{ message }` |
150
+ | `forgotPassword(email)` | `{ message }` |
151
+ | `resetPassword(token, password)` | `{ message }` |
152
+
153
+ ### Google sign-in
154
+
155
+ ```ts
156
+ // Redirect the browser to Google and return the generated URL.
157
+ const url = await auth.signInWithGoogle({
158
+ redirectTo: "/dashboard",
159
+ });
160
+ ```
161
+
162
+ On your callback page:
163
+
164
+ ```ts
165
+ const session = await auth.handleOAuthRedirect();
166
+ ```
167
+
168
+ `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`.
169
+
170
+ Use `getGoogleAuthorizationURL()` when you want to handle navigation yourself:
171
+
172
+ ```ts
173
+ const url = await auth.getGoogleAuthorizationURL({ redirectTo: "/dashboard" });
174
+ window.location.assign(url);
175
+ ```
176
+
177
+ Pass `redirect: false` to `signInWithGoogle()` to receive the URL without navigating.
178
+
179
+ ---
180
+
181
+ ## Sessions and state
182
+
183
+ ### Session methods
184
+
185
+ | Method | Returns | Notes |
186
+ | --- | --- | --- |
187
+ | `getSession()` | `BacletSession \| null` | Validates stored tokens; refreshes on `401` when enabled. |
188
+ | `refreshSession(refreshToken?)` | `BacletSession` | Uses the stored refresh token when none is passed. |
189
+ | `getUser()` | `BacletUser \| null` | Convenience wrapper around `getSession()`. |
190
+ | `getUserByToken(accessToken)` | `BacletUser` | Looks up a user for an explicitly supplied token. |
191
+ | `capabilities()` | `AuthCapabilities` | Returns enabled providers and auth setup status. |
192
+
193
+ ### React example
194
+
195
+ ```tsx
196
+ "use client";
197
+
198
+ import { useEffect, useState } from "react";
199
+ import { getAuth, type BacletSession } from "@baclet/sdk";
200
+
201
+ const auth = getAuth();
202
+
203
+ export function AuthBoundary() {
204
+ const [session, setSession] = useState<BacletSession | null>(null);
205
+
206
+ useEffect(() => {
207
+ void auth.getSession().then(setSession);
208
+ return auth.onAuthStateChanged(setSession);
209
+ }, []);
210
+
211
+ if (!session) return <SignInButton />;
212
+
213
+ return <span>Welcome, {session.user.display_name}</span>;
214
+ }
215
+ ```
216
+
217
+ `onAuthStateChanged()` returns an unsubscribe function. It emits on local session writes and clears.
218
+
219
+ ### Server-side example
220
+
221
+ ```ts
222
+ import { createBacletClient } from "@baclet/sdk";
223
+
224
+ const baclet = createBacletClient({
225
+ apiUrl: process.env.BACLET_API_URL!,
226
+ publishableKey: process.env.BACLET_PUBLISHABLE_KEY!,
227
+ storage: null,
228
+ });
229
+
230
+ export async function getCurrentUser(accessToken: string) {
231
+ return baclet.auth.getUserByToken(accessToken);
232
+ }
233
+ ```
234
+
235
+ Passing `storage: null` prevents server processes from sharing session state through a global memory store.
236
+
237
+ ---
238
+
239
+ ## Errors
240
+
241
+ Every non-2xx response becomes a `BacletError` with a numeric `status` and the parsed response body in `details`.
242
+
243
+ ```ts
244
+ import { BacletError } from "@baclet/sdk";
245
+
246
+ try {
247
+ await auth.signIn({ email, password });
248
+ } catch (error) {
249
+ if (error instanceof BacletError) {
250
+ console.error(error.status, error.message, error.details);
251
+ } else {
252
+ throw error;
253
+ }
254
+ }
255
+ ```
256
+
257
+ 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.
258
+
259
+ ---
260
+
261
+ ## API surface
262
+
263
+ ```ts
264
+ import Baclet, {
265
+ BacletClient,
266
+ BacletError,
267
+ createBacletClient,
268
+ getAuth,
269
+ getBaclet,
270
+ initializeBaclet,
271
+ } from "@baclet/sdk";
272
+
273
+ import type {
274
+ AuthCapabilities,
275
+ AuthStateListener,
276
+ BacletClientOptions,
277
+ BacletConfig,
278
+ BacletSession,
279
+ BacletTokens,
280
+ BacletUser,
281
+ GoogleSignInOptions,
282
+ SignInInput,
283
+ SignUpInput,
284
+ StorageLike,
285
+ } from "@baclet/sdk";
286
+ ```
287
+
288
+ `Baclet` is an alias for `BacletClient`. The class is also the default export.
289
+
290
+ ---
291
+
292
+ ## Security notes
293
+
294
+ - Use `publishableKey` in client applications. It is designed to be public.
295
+ - Do not bundle `secretKey` into browser code.
296
+ - Sessions are stored under `baclet:<project-id>:tokens` and `baclet:<project-id>:user`.
297
+ - Provide a custom `storage` implementation when your environment needs encrypted, persisted, or scoped storage.
298
+ - Always call `handleOAuthRedirect()` before rendering protected UI on your OAuth callback route.
299
+
300
+ ---
301
+
302
+ ## Development
303
+
304
+ ```bash
305
+ npm install
306
+ npm run build
307
+ npm run typecheck
308
+ npm test
309
+ ```
310
+
311
+ `npm test` rebuilds `dist` before running the Node test suite.
312
+
313
+ ---
314
+
315
+ ## BACLET
316
+
317
+ 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.
@@ -0,0 +1,155 @@
1
+ export interface BacletTokens {
2
+ access_token: string;
3
+ refresh_token: string;
4
+ expires_in: number;
5
+ token_type: string;
6
+ }
7
+ export interface BacletUser {
8
+ id: string;
9
+ email?: string;
10
+ phone?: string;
11
+ display_name: string;
12
+ avatar_url?: string;
13
+ email_verified_at?: string;
14
+ phone_verified_at?: string;
15
+ status: string;
16
+ prefs: string;
17
+ last_active_at?: string;
18
+ created_at: string;
19
+ updated_at: string;
20
+ }
21
+ export interface BacletSession {
22
+ user: BacletUser;
23
+ tokens: BacletTokens;
24
+ }
25
+ export interface AuthStatus {
26
+ installed: boolean;
27
+ enabled: boolean;
28
+ setup_complete: boolean;
29
+ version: number;
30
+ installed_at?: string;
31
+ last_error?: string;
32
+ }
33
+ export interface AuthCapabilities {
34
+ providers: string[];
35
+ publishable_key: string;
36
+ status: AuthStatus;
37
+ }
38
+ export interface StorageLike {
39
+ getItem(key: string): string | null;
40
+ setItem(key: string, value: string): void;
41
+ removeItem(key: string): void;
42
+ }
43
+ export interface BacletConfig {
44
+ apiUrl: string;
45
+ publishableKey: string;
46
+ secretKey?: string;
47
+ }
48
+ export interface BacletClientOptions extends BacletConfig {
49
+ storage?: StorageLike | null;
50
+ autoRefresh?: boolean;
51
+ fetch?: typeof fetch;
52
+ }
53
+ export interface SignUpInput {
54
+ fullName: string;
55
+ email: string;
56
+ password: string;
57
+ }
58
+ export interface SignInInput {
59
+ email: string;
60
+ password: string;
61
+ }
62
+ export interface GoogleSignInOptions {
63
+ redirectTo?: string;
64
+ redirect?: boolean;
65
+ }
66
+ export type AuthStateListener = (session: BacletSession | null) => void;
67
+ type MessageResponse = {
68
+ message: string;
69
+ };
70
+ export interface BacletAuth {
71
+ capabilities(): Promise<AuthCapabilities>;
72
+ signUp(input: SignUpInput): Promise<BacletSession>;
73
+ signIn(input: SignInInput): Promise<BacletSession>;
74
+ signInAnonymously(): Promise<BacletSession>;
75
+ getGoogleAuthorizationURL(options?: GoogleSignInOptions): Promise<string>;
76
+ signInWithGoogle(options?: GoogleSignInOptions): Promise<string>;
77
+ handleOAuthRedirect(): Promise<BacletSession | null>;
78
+ verifyEmail(token: string): Promise<{
79
+ message: string;
80
+ }>;
81
+ resendVerification(email: string): Promise<{
82
+ message: string;
83
+ }>;
84
+ forgotPassword(email: string): Promise<{
85
+ message: string;
86
+ }>;
87
+ resetPassword(token: string, password: string): Promise<{
88
+ message: string;
89
+ }>;
90
+ getSession(): Promise<BacletSession | null>;
91
+ refreshSession(refreshToken?: string): Promise<BacletSession>;
92
+ getUser(): Promise<BacletUser | null>;
93
+ getUserByToken(accessToken: string): Promise<BacletUser>;
94
+ signOut(): Promise<void>;
95
+ signOutWithTokens(accessToken: string, refreshToken?: string): Promise<{
96
+ message: string;
97
+ }>;
98
+ onAuthStateChanged(listener: AuthStateListener): () => void;
99
+ }
100
+ export declare class BacletError extends Error {
101
+ readonly status: number;
102
+ readonly details: unknown;
103
+ constructor(message: string, status: number, details?: unknown);
104
+ }
105
+ export declare class BacletClient {
106
+ readonly apiUrl: string;
107
+ readonly publishableKey: string;
108
+ readonly secretKey?: string;
109
+ readonly projectID: string;
110
+ private readonly storage;
111
+ private readonly fetchImpl;
112
+ private readonly autoRefresh;
113
+ private readonly tokensKey;
114
+ private readonly userKey;
115
+ private readonly listeners;
116
+ private readonly authService;
117
+ constructor(options: BacletClientOptions);
118
+ get auth(): BacletAuth;
119
+ private createAuthService;
120
+ capabilities(): Promise<AuthCapabilities>;
121
+ signUp(input: SignUpInput): Promise<BacletSession>;
122
+ signIn(input: SignInInput): Promise<BacletSession>;
123
+ signInAnonymously(): Promise<BacletSession>;
124
+ getGoogleAuthorizationURL(options?: GoogleSignInOptions): Promise<string>;
125
+ signInWithGoogle(options?: GoogleSignInOptions): Promise<string>;
126
+ handleOAuthRedirect(): Promise<BacletSession | null>;
127
+ verifyEmail(token: string): Promise<MessageResponse>;
128
+ resendVerification(email: string): Promise<MessageResponse>;
129
+ forgotPassword(email: string): Promise<MessageResponse>;
130
+ resetPassword(token: string, password: string): Promise<MessageResponse>;
131
+ getSession(): Promise<BacletSession | null>;
132
+ refreshSession(refreshToken?: string): Promise<BacletSession>;
133
+ getUser(): Promise<BacletUser | null>;
134
+ getUserByToken(accessToken: string): Promise<BacletUser>;
135
+ signOutWithTokens(accessToken: string, refreshToken?: string): Promise<MessageResponse>;
136
+ signOut(): Promise<void>;
137
+ onAuthStateChanged(listener: AuthStateListener): () => void;
138
+ private authPath;
139
+ private currentUser;
140
+ private request;
141
+ private throwResponseError;
142
+ private readTokens;
143
+ private writeSession;
144
+ private applySession;
145
+ private clearSession;
146
+ private emit;
147
+ private tokensFromParams;
148
+ private clearLocationFragment;
149
+ }
150
+ export declare function initializeBaclet(config: BacletConfig, name?: string): BacletClient;
151
+ export declare function getBaclet(name?: string): BacletClient;
152
+ export declare function getAuth(client?: BacletClient): BacletAuth;
153
+ export declare function createBacletClient(options: BacletClientOptions): BacletClient;
154
+ export declare const Baclet: typeof BacletClient;
155
+ export default BacletClient;
package/dist/index.js ADDED
@@ -0,0 +1,441 @@
1
+ const bacletApps = new Map();
2
+ const memoryValues = new Map();
3
+ const memoryStorage = {
4
+ getItem: (key) => memoryValues.get(key) ?? null,
5
+ setItem: (key, value) => {
6
+ memoryValues.set(key, value);
7
+ },
8
+ removeItem: (key) => {
9
+ memoryValues.delete(key);
10
+ },
11
+ };
12
+ function resolveStorage(storage) {
13
+ if (storage !== undefined)
14
+ return storage ?? memoryStorage;
15
+ try {
16
+ if (typeof localStorage !== "undefined")
17
+ return localStorage;
18
+ }
19
+ catch {
20
+ return memoryStorage;
21
+ }
22
+ return memoryStorage;
23
+ }
24
+ function projectIDFromKey(publishableKey) {
25
+ const match = publishableKey.match(/^pb_([0-9a-fA-F-]{36})_/);
26
+ if (!match) {
27
+ throw new BacletError("Invalid BACLET publishable key.", 400);
28
+ }
29
+ return match[1];
30
+ }
31
+ function validateSecretKey(secretKey) {
32
+ if (secretKey === undefined)
33
+ return;
34
+ if (!/^sk_[A-Za-z0-9_-]{43}$/.test(secretKey)) {
35
+ throw new BacletError("Invalid BACLET secret key.", 400);
36
+ }
37
+ }
38
+ function normalizeAPIURL(apiUrl) {
39
+ const raw = apiUrl.trim();
40
+ if (!raw) {
41
+ throw new BacletError("A BACLET API URL is required.", 400);
42
+ }
43
+ const withProtocol = /^[a-z][a-z\d+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`;
44
+ let parsed;
45
+ try {
46
+ parsed = new URL(withProtocol);
47
+ }
48
+ catch {
49
+ throw new BacletError("Invalid BACLET API URL.", 400);
50
+ }
51
+ if ((parsed.protocol !== "http:" && parsed.protocol !== "https:") || !parsed.hostname) {
52
+ throw new BacletError("Invalid BACLET API URL.", 400);
53
+ }
54
+ let pathname = parsed.pathname.replace(/\/+$/, "");
55
+ if (pathname.endsWith("/v1"))
56
+ pathname = pathname.slice(0, -3);
57
+ parsed.pathname = pathname;
58
+ parsed.search = "";
59
+ parsed.hash = "";
60
+ return parsed.toString().replace(/\/+$/, "");
61
+ }
62
+ function isBrowser() {
63
+ return typeof window !== "undefined" && typeof document !== "undefined";
64
+ }
65
+ function hasStatus(error, status) {
66
+ return error instanceof BacletError && error.status === status;
67
+ }
68
+ function parseTokens(value) {
69
+ if (!value)
70
+ return null;
71
+ try {
72
+ const parsed = JSON.parse(value);
73
+ if (typeof parsed.access_token !== "string" ||
74
+ typeof parsed.refresh_token !== "string" ||
75
+ typeof parsed.expires_in !== "number" ||
76
+ typeof parsed.token_type !== "string") {
77
+ return null;
78
+ }
79
+ return parsed;
80
+ }
81
+ catch {
82
+ return null;
83
+ }
84
+ }
85
+ function parseResponse(response) {
86
+ if (response.status === 204)
87
+ return Promise.resolve(undefined);
88
+ return response.text().then((text) => (text ? JSON.parse(text) : undefined));
89
+ }
90
+ export class BacletError extends Error {
91
+ status;
92
+ details;
93
+ constructor(message, status, details) {
94
+ super(message);
95
+ this.name = "BacletError";
96
+ this.status = status;
97
+ this.details = details;
98
+ }
99
+ }
100
+ export class BacletClient {
101
+ apiUrl;
102
+ publishableKey;
103
+ secretKey;
104
+ projectID;
105
+ storage;
106
+ fetchImpl;
107
+ autoRefresh;
108
+ tokensKey;
109
+ userKey;
110
+ listeners = new Set();
111
+ authService;
112
+ constructor(options) {
113
+ if (!options.publishableKey) {
114
+ throw new BacletError("A BACLET publishable key is required.", 400);
115
+ }
116
+ validateSecretKey(options.secretKey);
117
+ this.apiUrl = normalizeAPIURL(options.apiUrl);
118
+ this.publishableKey = options.publishableKey;
119
+ this.secretKey = options.secretKey;
120
+ this.projectID = projectIDFromKey(options.publishableKey);
121
+ this.storage = resolveStorage(options.storage);
122
+ this.fetchImpl = options.fetch ?? globalThis.fetch;
123
+ if (typeof this.fetchImpl !== "function") {
124
+ throw new BacletError("This runtime does not provide fetch; pass options.fetch.", 500);
125
+ }
126
+ this.autoRefresh = options.autoRefresh ?? true;
127
+ this.tokensKey = `baclet:${this.projectID}:tokens`;
128
+ this.userKey = `baclet:${this.projectID}:user`;
129
+ this.authService = this.createAuthService();
130
+ }
131
+ get auth() {
132
+ return this.authService;
133
+ }
134
+ createAuthService() {
135
+ return {
136
+ capabilities: () => this.capabilities(),
137
+ signUp: (input) => this.signUp(input),
138
+ signIn: (input) => this.signIn(input),
139
+ signInAnonymously: () => this.signInAnonymously(),
140
+ getGoogleAuthorizationURL: (options) => this.getGoogleAuthorizationURL(options),
141
+ signInWithGoogle: (options) => this.signInWithGoogle(options),
142
+ handleOAuthRedirect: () => this.handleOAuthRedirect(),
143
+ verifyEmail: (token) => this.verifyEmail(token),
144
+ resendVerification: (email) => this.resendVerification(email),
145
+ forgotPassword: (email) => this.forgotPassword(email),
146
+ resetPassword: (token, password) => this.resetPassword(token, password),
147
+ getSession: () => this.getSession(),
148
+ refreshSession: (refreshToken) => this.refreshSession(refreshToken),
149
+ getUser: () => this.getUser(),
150
+ signOut: () => this.signOut(),
151
+ signOutWithTokens: (accessToken, refreshToken) => this.signOutWithTokens(accessToken, refreshToken),
152
+ getUserByToken: (accessToken) => this.getUserByToken(accessToken),
153
+ onAuthStateChanged: (listener) => this.onAuthStateChanged(listener),
154
+ };
155
+ }
156
+ capabilities() {
157
+ return this.request(`/v1/projects/${this.projectID}/auth/capabilities`);
158
+ }
159
+ async signUp(input) {
160
+ const result = await this.request(this.authPath("/signup"), {
161
+ method: "POST",
162
+ body: {
163
+ full_name: input.fullName,
164
+ email: input.email,
165
+ password: input.password,
166
+ },
167
+ });
168
+ this.applySession(result);
169
+ return result;
170
+ }
171
+ async signIn(input) {
172
+ const result = await this.request(this.authPath("/login"), {
173
+ method: "POST",
174
+ body: {
175
+ email: input.email,
176
+ password: input.password,
177
+ },
178
+ });
179
+ this.applySession(result);
180
+ return result;
181
+ }
182
+ async signInAnonymously() {
183
+ const result = await this.request(this.authPath("/anonymous"), {
184
+ method: "POST",
185
+ });
186
+ this.applySession(result);
187
+ return result;
188
+ }
189
+ async getGoogleAuthorizationURL(options = {}) {
190
+ const query = options.redirectTo
191
+ ? `?redirect_to=${encodeURIComponent(options.redirectTo)}`
192
+ : "";
193
+ const result = await this.request(this.authPath(`/google/url${query}`));
194
+ return result.url;
195
+ }
196
+ async signInWithGoogle(options = {}) {
197
+ const url = await this.getGoogleAuthorizationURL(options);
198
+ if (options.redirect !== false && isBrowser()) {
199
+ window.location.assign(url);
200
+ }
201
+ return url;
202
+ }
203
+ async handleOAuthRedirect() {
204
+ if (!isBrowser())
205
+ return null;
206
+ const params = new URLSearchParams(window.location.hash.replace(/^#/, ""));
207
+ const status = params.get("auth");
208
+ if (!status)
209
+ return null;
210
+ this.clearLocationFragment();
211
+ if (status === "error") {
212
+ this.clearSession();
213
+ throw new BacletError(params.get("reason") ?? "OAuth sign-in failed.", 400);
214
+ }
215
+ if (status !== "success")
216
+ return null;
217
+ const tokens = this.tokensFromParams(params);
218
+ if (!tokens) {
219
+ this.clearSession();
220
+ throw new BacletError("OAuth response did not include tokens.", 400);
221
+ }
222
+ this.storage.setItem(this.tokensKey, JSON.stringify(tokens));
223
+ const session = await this.getSession();
224
+ if (!session) {
225
+ throw new BacletError("OAuth sign-in could not load the user.", 401);
226
+ }
227
+ return session;
228
+ }
229
+ verifyEmail(token) {
230
+ return this.request(this.authPath("/verify-email"), {
231
+ method: "POST",
232
+ body: { token },
233
+ });
234
+ }
235
+ resendVerification(email) {
236
+ return this.request(this.authPath("/resend-verification"), {
237
+ method: "POST",
238
+ body: { email },
239
+ });
240
+ }
241
+ forgotPassword(email) {
242
+ return this.request(this.authPath("/forgot-password"), {
243
+ method: "POST",
244
+ body: { email },
245
+ });
246
+ }
247
+ resetPassword(token, password) {
248
+ return this.request(this.authPath("/reset-password"), {
249
+ method: "POST",
250
+ body: { token, password },
251
+ });
252
+ }
253
+ async getSession() {
254
+ const tokens = this.readTokens();
255
+ if (!tokens)
256
+ return null;
257
+ try {
258
+ const user = await this.currentUser(tokens.access_token);
259
+ const session = { user, tokens };
260
+ this.writeSession(session);
261
+ return session;
262
+ }
263
+ catch (error) {
264
+ if (hasStatus(error, 401) && this.autoRefresh && tokens.refresh_token) {
265
+ try {
266
+ return await this.refreshSession(tokens.refresh_token);
267
+ }
268
+ catch {
269
+ this.clearSession();
270
+ return null;
271
+ }
272
+ }
273
+ if (hasStatus(error, 401)) {
274
+ this.clearSession();
275
+ return null;
276
+ }
277
+ throw error;
278
+ }
279
+ }
280
+ async refreshSession(refreshToken) {
281
+ const token = refreshToken ?? this.readTokens()?.refresh_token;
282
+ if (!token) {
283
+ throw new BacletError("No refresh token is available.", 401);
284
+ }
285
+ const result = await this.request(this.authPath("/refresh"), {
286
+ method: "POST",
287
+ body: { refresh_token: token },
288
+ });
289
+ this.applySession(result);
290
+ return result;
291
+ }
292
+ getUser() {
293
+ return this.getSession().then((session) => session?.user ?? null);
294
+ }
295
+ getUserByToken(accessToken) {
296
+ return this.currentUser(accessToken);
297
+ }
298
+ async signOutWithTokens(accessToken, refreshToken) {
299
+ return this.request(this.authPath("/logout"), {
300
+ method: "POST",
301
+ body: { refresh_token: refreshToken },
302
+ accessToken,
303
+ });
304
+ }
305
+ async signOut() {
306
+ const tokens = this.readTokens();
307
+ if (!tokens) {
308
+ this.clearSession();
309
+ return;
310
+ }
311
+ try {
312
+ await this.signOutWithTokens(tokens.access_token, tokens.refresh_token);
313
+ }
314
+ catch (error) {
315
+ if (!hasStatus(error, 401))
316
+ throw error;
317
+ }
318
+ finally {
319
+ this.clearSession();
320
+ }
321
+ }
322
+ onAuthStateChanged(listener) {
323
+ this.listeners.add(listener);
324
+ return () => {
325
+ this.listeners.delete(listener);
326
+ };
327
+ }
328
+ authPath(suffix) {
329
+ return `/v1/auth/${this.projectID}${suffix}`;
330
+ }
331
+ currentUser(accessToken) {
332
+ return this.request(this.authPath("/me"), {
333
+ accessToken,
334
+ }).then((result) => result.user);
335
+ }
336
+ async request(path, options = {}) {
337
+ const headers = {
338
+ Accept: "application/json",
339
+ "X-Baclet-Publishable-Key": this.publishableKey,
340
+ };
341
+ if (options.body !== undefined)
342
+ headers["Content-Type"] = "application/json";
343
+ if (options.accessToken)
344
+ headers.Authorization = `Bearer ${options.accessToken}`;
345
+ const response = await this.fetchImpl(`${this.apiUrl}${path}`, {
346
+ method: options.method ?? "GET",
347
+ headers,
348
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
349
+ });
350
+ if (!response.ok)
351
+ return this.throwResponseError(response);
352
+ return parseResponse(response);
353
+ }
354
+ async throwResponseError(response) {
355
+ let payload;
356
+ try {
357
+ payload = await response.json();
358
+ }
359
+ catch {
360
+ payload = undefined;
361
+ }
362
+ const body = payload;
363
+ const message = (typeof body?.detail === "string" && body.detail) ||
364
+ (typeof body?.message === "string" && body.message) ||
365
+ (typeof body?.title === "string" && body.title) ||
366
+ `BACLET request failed with status ${response.status}`;
367
+ throw new BacletError(message, response.status, payload);
368
+ }
369
+ readTokens() {
370
+ const tokens = parseTokens(this.storage.getItem(this.tokensKey));
371
+ if (!tokens)
372
+ this.storage.removeItem(this.tokensKey);
373
+ return tokens;
374
+ }
375
+ writeSession(session) {
376
+ this.storage.setItem(this.tokensKey, JSON.stringify(session.tokens));
377
+ this.storage.setItem(this.userKey, JSON.stringify(session.user));
378
+ this.emit(session);
379
+ }
380
+ applySession(session) {
381
+ this.writeSession(session);
382
+ }
383
+ clearSession() {
384
+ this.storage.removeItem(this.tokensKey);
385
+ this.storage.removeItem(this.userKey);
386
+ this.emit(null);
387
+ }
388
+ emit(session) {
389
+ for (const listener of this.listeners)
390
+ listener(session);
391
+ }
392
+ tokensFromParams(params) {
393
+ const accessToken = params.get("access_token");
394
+ const refreshToken = params.get("refresh_token");
395
+ const expiresIn = Number(params.get("expires_in"));
396
+ const tokenType = params.get("token_type");
397
+ if (!accessToken || !refreshToken || !Number.isFinite(expiresIn) || !tokenType) {
398
+ return null;
399
+ }
400
+ return {
401
+ access_token: accessToken,
402
+ refresh_token: refreshToken,
403
+ expires_in: expiresIn,
404
+ token_type: tokenType,
405
+ };
406
+ }
407
+ clearLocationFragment() {
408
+ if (isBrowser()) {
409
+ window.history.replaceState(null, document.title, window.location.pathname + window.location.search);
410
+ }
411
+ }
412
+ }
413
+ export function initializeBaclet(config, name = "DEFAULT") {
414
+ const existing = bacletApps.get(name);
415
+ if (existing) {
416
+ if (existing.apiUrl !== normalizeAPIURL(config.apiUrl) ||
417
+ existing.publishableKey !== config.publishableKey ||
418
+ existing.secretKey !== config.secretKey) {
419
+ throw new BacletError(`BACLET app "${name}" already exists with different credentials.`, 409);
420
+ }
421
+ return existing;
422
+ }
423
+ const client = new BacletClient(config);
424
+ bacletApps.set(name, client);
425
+ return client;
426
+ }
427
+ export function getBaclet(name = "DEFAULT") {
428
+ const client = bacletApps.get(name);
429
+ if (!client) {
430
+ throw new BacletError(`No BACLET app named "${name}" has been initialized.`, 404);
431
+ }
432
+ return client;
433
+ }
434
+ export function getAuth(client = getBaclet()) {
435
+ return client.auth;
436
+ }
437
+ export function createBacletClient(options) {
438
+ return new BacletClient(options);
439
+ }
440
+ export const Baclet = BacletClient;
441
+ export default BacletClient;
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "@baclet/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "description": "BACLET users database SDK for browsers and servers",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "scripts": {
18
+ "build": "tsc -p tsconfig.json",
19
+ "typecheck": "tsc -p tsconfig.json --noEmit",
20
+ "test": "npm run build && node --test"
21
+ },
22
+ "devDependencies": {
23
+ "typescript": "^5.7.2"
24
+ }
25
+ }