@genation/sdk 0.1.0 → 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.
@@ -1,43 +1,43 @@
1
- class w extends Error {
1
+ class m extends Error {
2
2
  code;
3
3
  cause;
4
- constructor(e, t, r) {
5
- super(e), this.name = "GenationError", this.code = t, this.cause = r;
4
+ constructor(e, t, s) {
5
+ super(e), this.name = "GenationError", this.code = t, this.cause = s;
6
6
  }
7
7
  }
8
- class h extends w {
9
- constructor(e, t, r) {
10
- super(e, t, r), this.name = "AuthError";
8
+ class l extends m {
9
+ constructor(e, t, s) {
10
+ super(e, t, s), this.name = "AuthError";
11
11
  }
12
12
  static invalidGrant(e = "Invalid authorization code or refresh token") {
13
- return new h(e, "invalid_grant");
13
+ return new l(e, "invalid_grant");
14
14
  }
15
15
  static accessDenied(e = "User denied access") {
16
- return new h(e, "access_denied");
16
+ return new l(e, "access_denied");
17
17
  }
18
18
  static expiredToken(e = "Token has expired") {
19
- return new h(e, "expired_token");
19
+ return new l(e, "expired_token");
20
20
  }
21
21
  static invalidState(e = "State mismatch, possible CSRF attack") {
22
- return new h(e, "invalid_state");
22
+ return new l(e, "invalid_state");
23
23
  }
24
24
  static pkceVerificationFailed(e = "PKCE verification failed") {
25
- return new h(e, "pkce_verification_failed");
25
+ return new l(e, "pkce_verification_failed");
26
26
  }
27
27
  }
28
- class c extends w {
28
+ class h extends m {
29
29
  status;
30
- constructor(e, t, r) {
31
- super(e, "network_error", r), this.name = "NetworkError", this.status = t;
30
+ constructor(e, t, s) {
31
+ super(e, "network_error", s), this.name = "NetworkError", this.status = t;
32
32
  }
33
33
  static fromResponse(e) {
34
- return new c(
34
+ return new h(
35
35
  `HTTP ${e.status}: ${e.statusText}`,
36
36
  e.status
37
37
  );
38
38
  }
39
39
  }
40
- class u extends w {
40
+ class u extends m {
41
41
  constructor(e) {
42
42
  super(e, "config_error"), this.name = "ConfigError";
43
43
  }
@@ -55,78 +55,78 @@ class p {
55
55
  * Make an HTTP request
56
56
  */
57
57
  async request(e, t = {}) {
58
- const { method: r = "GET", headers: n = {}, body: a, params: l } = t;
59
- let o = `${this.baseUrl}${e}`;
60
- if (l) {
61
- const i = new URLSearchParams(l);
62
- o += `?${i.toString()}`;
58
+ const { method: s = "GET", headers: n = {}, body: i, params: o } = t;
59
+ let c = `${this.baseUrl}${e}`;
60
+ if (o) {
61
+ const a = new URLSearchParams(o);
62
+ c += `?${a.toString()}`;
63
63
  }
64
- const m = new AbortController(), y = setTimeout(() => m.abort(), this.timeout);
64
+ const y = new AbortController(), S = setTimeout(() => y.abort(), this.timeout);
65
65
  try {
66
- const i = await fetch(o, {
67
- method: r,
66
+ const a = await fetch(c, {
67
+ method: s,
68
68
  headers: {
69
69
  "Content-Type": "application/json",
70
70
  ...n
71
71
  },
72
- body: a ? JSON.stringify(a) : void 0,
73
- signal: m.signal
72
+ body: i ? JSON.stringify(i) : void 0,
73
+ signal: y.signal
74
74
  });
75
- if (clearTimeout(y), !i.ok)
76
- throw c.fromResponse(i);
77
- return await i.json();
78
- } catch (i) {
79
- throw clearTimeout(y), i instanceof c ? i : i instanceof Error && i.name === "AbortError" ? new c("Request timeout", void 0, i) : new c("Network request failed", void 0, i);
75
+ if (clearTimeout(S), !a.ok)
76
+ throw h.fromResponse(a);
77
+ return await a.json();
78
+ } catch (a) {
79
+ throw clearTimeout(S), a instanceof h ? a : a instanceof Error && a.name === "AbortError" ? new h("Request timeout", void 0, a) : new h("Network request failed", void 0, a);
80
80
  }
81
81
  }
82
82
  /**
83
83
  * POST request with form data (for OAuth token exchange)
84
84
  */
85
- async postForm(e, t, r = {}) {
86
- const n = `${this.baseUrl}${e}`, a = new AbortController(), l = setTimeout(() => a.abort(), this.timeout);
85
+ async postForm(e, t, s = {}) {
86
+ const n = `${this.baseUrl}${e}`, i = new AbortController(), o = setTimeout(() => i.abort(), this.timeout);
87
87
  try {
88
- const o = await fetch(n, {
88
+ const c = await fetch(n, {
89
89
  method: "POST",
90
90
  headers: {
91
91
  "Content-Type": "application/x-www-form-urlencoded",
92
- ...r
92
+ ...s
93
93
  },
94
94
  body: new URLSearchParams(t).toString(),
95
- signal: a.signal
95
+ signal: i.signal
96
96
  });
97
- if (clearTimeout(l), !o.ok)
98
- throw c.fromResponse(o);
99
- return await o.json();
100
- } catch (o) {
101
- throw clearTimeout(l), o instanceof c ? o : new c("Network request failed", void 0, o);
97
+ if (clearTimeout(o), !c.ok)
98
+ throw h.fromResponse(c);
99
+ return await c.json();
100
+ } catch (c) {
101
+ throw clearTimeout(o), c instanceof h ? c : new h("Network request failed", void 0, c);
102
102
  }
103
103
  }
104
104
  }
105
- function k(s) {
106
- return btoa(String.fromCharCode(...s)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
105
+ function k(r) {
106
+ return btoa(String.fromCharCode(...r)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
107
107
  }
108
- function T() {
109
- const s = new Uint8Array(32);
110
- return crypto.getRandomValues(s), k(s);
108
+ function b() {
109
+ const r = new Uint8Array(32);
110
+ return crypto.getRandomValues(r), k(r);
111
111
  }
112
- async function b(s) {
113
- const t = new TextEncoder().encode(s), r = await crypto.subtle.digest("SHA-256", t);
114
- return k(new Uint8Array(r));
112
+ async function C(r) {
113
+ const t = new TextEncoder().encode(r), s = await crypto.subtle.digest("SHA-256", t);
114
+ return k(new Uint8Array(s));
115
115
  }
116
- async function v() {
117
- const s = T(), e = await b(s);
116
+ async function _() {
117
+ const r = b(), e = await C(r);
118
118
  return {
119
- codeVerifier: s,
119
+ codeVerifier: r,
120
120
  codeChallenge: e,
121
121
  codeChallengeMethod: "S256"
122
122
  };
123
123
  }
124
- function _() {
125
- const s = new Uint8Array(16);
126
- return crypto.getRandomValues(s), k(s);
124
+ function v() {
125
+ const r = new Uint8Array(16);
126
+ return crypto.getRandomValues(r), k(r);
127
127
  }
128
128
  const d = "tokens", g = "pkce", f = "state";
129
- class C {
129
+ class U {
130
130
  storage;
131
131
  constructor(e) {
132
132
  this.storage = e;
@@ -198,7 +198,7 @@ class C {
198
198
  }
199
199
  }
200
200
  const I = "https://mnnoheowoowbtpuoguul.supabase.co/auth/v1";
201
- class U {
201
+ class x {
202
202
  config;
203
203
  http;
204
204
  tokenManager;
@@ -216,9 +216,9 @@ class U {
216
216
  * Stores PKCE verifier and state for later validation
217
217
  */
218
218
  async getAuthorizationUrl() {
219
- const e = await v(), t = _();
219
+ const e = await _(), t = v();
220
220
  await this.tokenManager.setPKCE(e.codeVerifier), await this.tokenManager.setState(t);
221
- const r = new URLSearchParams({
221
+ const s = new URLSearchParams({
222
222
  response_type: "code",
223
223
  client_id: this.config.clientId,
224
224
  redirect_uri: this.config.redirectUri,
@@ -226,19 +226,19 @@ class U {
226
226
  code_challenge: e.codeChallenge,
227
227
  code_challenge_method: e.codeChallengeMethod
228
228
  });
229
- return this.config.scopes && this.config.scopes.length > 0 && r.append("scope", this.config.scopes.join(" ")), `${this.config.authUrl}/oauth/authorize?${r.toString()}`;
229
+ return this.config.scopes && this.config.scopes.length > 0 && s.append("scope", this.config.scopes.join(" ")), `${this.config.authUrl}/oauth/authorize?${s.toString()}`;
230
230
  }
231
231
  /**
232
232
  * Exchange authorization code for tokens
233
233
  */
234
234
  async exchangeCode(e, t) {
235
- const r = await this.tokenManager.consumeState();
236
- if (!r || r !== t)
237
- throw h.invalidState();
235
+ const s = await this.tokenManager.consumeState();
236
+ if (!s || s !== t)
237
+ throw l.invalidState();
238
238
  const n = await this.tokenManager.consumePKCE();
239
239
  if (!n)
240
- throw h.pkceVerificationFailed("Missing code verifier");
241
- const a = await this.http.postForm(
240
+ throw l.pkceVerificationFailed("Missing code verifier");
241
+ const i = await this.http.postForm(
242
242
  "/oauth/token",
243
243
  {
244
244
  grant_type: "authorization_code",
@@ -248,8 +248,8 @@ class U {
248
248
  client_secret: this.config.clientSecret,
249
249
  code_verifier: n
250
250
  }
251
- ), l = this.mapTokenResponse(a);
252
- return await this.tokenManager.setTokens(l), l;
251
+ ), o = this.mapTokenResponse(i);
252
+ return await this.tokenManager.setTokens(o), o;
253
253
  }
254
254
  /**
255
255
  * Refresh access token using refresh token
@@ -257,7 +257,7 @@ class U {
257
257
  async refreshToken() {
258
258
  const e = await this.tokenManager.getTokens();
259
259
  if (!e?.refreshToken)
260
- throw h.invalidGrant("No refresh token available");
260
+ throw l.invalidGrant("No refresh token available");
261
261
  const t = await this.http.postForm(
262
262
  "/oauth/token",
263
263
  {
@@ -266,8 +266,8 @@ class U {
266
266
  client_id: this.config.clientId,
267
267
  client_secret: this.config.clientSecret
268
268
  }
269
- ), r = this.mapTokenResponse(t);
270
- return await this.tokenManager.setTokens(r), r;
269
+ ), s = this.mapTokenResponse(t);
270
+ return await this.tokenManager.setTokens(s), s;
271
271
  }
272
272
  /**
273
273
  * Revoke current tokens
@@ -299,7 +299,7 @@ class U {
299
299
  };
300
300
  }
301
301
  }
302
- class x {
302
+ class E {
303
303
  store = /* @__PURE__ */ new Map();
304
304
  async get(e) {
305
305
  return this.store.get(e) ?? null;
@@ -314,7 +314,7 @@ class x {
314
314
  this.store.clear();
315
315
  }
316
316
  }
317
- class S {
317
+ class T {
318
318
  prefix;
319
319
  constructor(e = "genation") {
320
320
  this.prefix = e;
@@ -338,7 +338,7 @@ class S {
338
338
  ).forEach((t) => localStorage.removeItem(t));
339
339
  }
340
340
  }
341
- class E {
341
+ class A {
342
342
  prefix;
343
343
  constructor(e = "genation") {
344
344
  this.prefix = e;
@@ -362,19 +362,27 @@ class E {
362
362
  ).forEach((t) => sessionStorage.removeItem(t));
363
363
  }
364
364
  }
365
- function A(s = "localStorage") {
366
- switch (s) {
365
+ function M(r = "localStorage") {
366
+ switch (r) {
367
367
  case "memory":
368
- return new x();
368
+ return new E();
369
369
  case "localStorage":
370
- return new S();
370
+ return new T();
371
371
  case "sessionStorage":
372
- return new E();
372
+ return new A();
373
373
  default:
374
- return new S();
374
+ return new T();
375
375
  }
376
376
  }
377
- class M {
377
+ function w(r) {
378
+ return Array.isArray(r) ? r.map(w) : typeof r == "object" && r !== null ? Object.fromEntries(
379
+ Object.entries(r).map(([e, t]) => [
380
+ e.replace(/_([a-z])/g, (s, n) => n.toUpperCase()),
381
+ w(t)
382
+ ])
383
+ ) : r;
384
+ }
385
+ class K {
378
386
  oauth;
379
387
  tokenManager;
380
388
  http;
@@ -383,8 +391,8 @@ class M {
383
391
  initialized = !1;
384
392
  constructor(e) {
385
393
  this.validateConfig(e);
386
- const t = typeof e.storage == "object" ? e.storage : A(e.storage);
387
- this.tokenManager = new C(t), this.oauth = new U(e, this.tokenManager), this.http = new p({
394
+ const t = typeof e.storage == "object" ? e.storage : M(e.storage);
395
+ this.tokenManager = new U(t), this.oauth = new x(e, this.tokenManager), this.http = new p({
388
396
  baseUrl: e.authUrl ?? "https://mnnoheowoowbtpuoguul.supabase.co/auth/v1"
389
397
  }), this.httpServer = new p({
390
398
  baseUrl: "https://ff-api.genation.ai/api/v2/client"
@@ -401,9 +409,9 @@ class M {
401
409
  */
402
410
  async emitAuthStateChange(e) {
403
411
  const t = await this.getSession();
404
- this.listeners.forEach((r) => {
412
+ this.listeners.forEach((s) => {
405
413
  try {
406
- r(e, t);
414
+ s(e, t);
407
415
  } catch (n) {
408
416
  console.error("Error in auth state change callback:", n);
409
417
  }
@@ -492,44 +500,43 @@ class M {
492
500
  * ```typescript
493
501
  * // On your /callback page
494
502
  * async function handleCallback() {
495
- * const params = new URLSearchParams(window.location.search);
496
- * const code = params.get('code');
497
- * const state = params.get('state');
498
- *
499
- * if (code && state) {
500
- * await client.handleCallback(code, state);
501
- * // onAuthStateChange will fire with SIGNED_IN event
502
- * }
503
+ * const url = window.location.href;
504
+ * await client.handleCallback(url);
505
+ * // onAuthStateChange will fire with SIGNED_IN event
503
506
  * }
504
507
  * ```
505
508
  */
506
- async handleCallback(e, t) {
507
- const r = await this.oauth.exchangeCode(e, t);
509
+ async handleCallback(e) {
510
+ const t = new URLSearchParams(e), s = t.get("code"), n = t.get("state");
511
+ if (!s || !n)
512
+ throw new Error("Missing code or state");
513
+ const i = await this.oauth.exchangeCode(s, n);
508
514
  try {
509
- const n = await this.fetchUser(r.accessToken);
510
- console.log("Debug: handleCallback fetched user:", n);
511
- } catch (n) {
512
- console.error("Debug: handleCallback fetchUser failed:", n);
515
+ const o = await this.fetchUser(i.accessToken);
516
+ console.log("Debug: handleCallback fetched user:", o);
517
+ } catch (o) {
518
+ console.error("Debug: handleCallback fetchUser failed:", o);
513
519
  }
514
- return await this.emitAuthStateChange("SIGNED_IN"), r;
515
- }
516
- /**
517
- * Sign out and revoke tokens
518
- *
519
- * Clears local session and revokes tokens on server.
520
- * Triggers `SIGNED_OUT` event for all listeners.
521
- *
522
- * @example
523
- * ```typescript
524
- * async function handleLogout() {
525
- * await client.signOut();
526
- * // onAuthStateChange will fire with SIGNED_OUT event
527
- * }
528
- * ```
529
- */
530
- async signOut() {
531
- await this.oauth.revokeToken(), await this.emitAuthStateChange("SIGNED_OUT");
532
- }
520
+ return await this.emitAuthStateChange("SIGNED_IN"), i;
521
+ }
522
+ // /**
523
+ // * Sign out and revoke tokens
524
+ // *
525
+ // * Clears local session and revokes tokens on server.
526
+ // * Triggers `SIGNED_OUT` event for all listeners.
527
+ // *
528
+ // * @example
529
+ // * ```typescript
530
+ // * async function handleLogout() {
531
+ // * await client.signOut();
532
+ // * // onAuthStateChange will fire with SIGNED_OUT event
533
+ // * }
534
+ // * ```
535
+ // */
536
+ // async signOut(): Promise<void> {
537
+ // await this.oauth.revokeToken();
538
+ // await this.emitAuthStateChange("SIGNED_OUT");
539
+ // }
533
540
  /**
534
541
  * Get current session
535
542
  *
@@ -560,13 +567,13 @@ class M {
560
567
  }
561
568
  const t = await this.tokenManager.getTokens();
562
569
  if (!t) return null;
563
- const r = await this.fetchUser(t.accessToken);
570
+ const s = await this.fetchUser(t.accessToken);
564
571
  return {
565
572
  accessToken: t.accessToken,
566
573
  refreshToken: t.refreshToken,
567
574
  expiresIn: t.expiresIn,
568
575
  expiresAt: t.issuedAt + t.expiresIn * 1e3,
569
- user: r
576
+ user: s
570
577
  };
571
578
  }
572
579
  /**
@@ -580,11 +587,15 @@ class M {
580
587
  const t = await this.getSession();
581
588
  if (!t)
582
589
  return null;
583
- const r = t.accessToken, { expiresAfter: n = /* @__PURE__ */ new Date() } = e, a = await this.httpServer.request("/licenses", {
584
- headers: { Authorization: `Bearer ${r}` },
590
+ const s = t.accessToken, { expiresAfter: n = /* @__PURE__ */ new Date() } = e, i = await this.httpServer.request("/licenses", {
591
+ headers: { Authorization: `Bearer ${s}` },
585
592
  params: { expiresAfter: n.toISOString() }
586
593
  });
587
- return a.ok ? a.data : (console.error("GenationClient: Error fetching licenses:", a.error), null);
594
+ if (!i.ok)
595
+ return console.error("GenationClient: Error fetching licenses:", i.error), null;
596
+ console.log("GenationClient: Response data:", i.data);
597
+ const o = w(i.data);
598
+ return console.log("GenationClient: Licenses:", o), o;
588
599
  }
589
600
  /**
590
601
  * Fetch user info from auth server
@@ -608,19 +619,19 @@ class M {
608
619
  }
609
620
  }
610
621
  }
611
- function K(s) {
612
- return new M(s);
622
+ function $(r) {
623
+ return new K(r);
613
624
  }
614
625
  export {
615
- h as AuthError,
626
+ l as AuthError,
616
627
  u as ConfigError,
617
- M as GenationClient,
618
- w as GenationError,
619
- S as LocalStorage,
620
- x as MemoryStorage,
621
- c as NetworkError,
622
- E as SessionStorage,
623
- K as createClient,
624
- A as createStorage
628
+ K as GenationClient,
629
+ m as GenationError,
630
+ T as LocalStorage,
631
+ E as MemoryStorage,
632
+ h as NetworkError,
633
+ A as SessionStorage,
634
+ $ as createClient,
635
+ M as createStorage
625
636
  };
626
637
  //# sourceMappingURL=genation.es.js.map