@baclet/sdk 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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.0",
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
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.