@freehour/supabase-core 2.0.4 → 2.1.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/dist/index.js CHANGED
@@ -1,74 +1,3525 @@
1
1
  import { assert as e } from "@freehour/assert";
2
2
  import t from "zod";
3
- import { PostgrestError as n } from "@supabase/supabase-js";
4
- import * as r from "@supabase/postgrest-js";
3
+ import * as n from "@supabase/postgrest-js";
4
+ import { PostgrestError as r } from "@supabase/postgrest-js";
5
5
  import "@supabase/storage-js";
6
+ //#region node_modules/tslib/tslib.es6.mjs
7
+ function i(e, t) {
8
+ var n = {};
9
+ for (var r in e) Object.prototype.hasOwnProperty.call(e, r) && t.indexOf(r) < 0 && (n[r] = e[r]);
10
+ if (e != null && typeof Object.getOwnPropertySymbols == "function") for (var i = 0, r = Object.getOwnPropertySymbols(e); i < r.length; i++) t.indexOf(r[i]) < 0 && Object.prototype.propertyIsEnumerable.call(e, r[i]) && (n[r[i]] = e[r[i]]);
11
+ return n;
12
+ }
13
+ //#endregion
14
+ //#region node_modules/@supabase/realtime-js/dist/module/lib/transformers.js
15
+ var a;
16
+ (function(e) {
17
+ e.abstime = "abstime", e.bool = "bool", e.date = "date", e.daterange = "daterange", e.float4 = "float4", e.float8 = "float8", e.int2 = "int2", e.int4 = "int4", e.int4range = "int4range", e.int8 = "int8", e.int8range = "int8range", e.json = "json", e.jsonb = "jsonb", e.money = "money", e.numeric = "numeric", e.oid = "oid", e.reltime = "reltime", e.text = "text", e.time = "time", e.timestamp = "timestamp", e.timestamptz = "timestamptz", e.timetz = "timetz", e.tsrange = "tsrange", e.tstzrange = "tstzrange";
18
+ })(a ||= {});
19
+ //#endregion
20
+ //#region node_modules/@supabase/realtime-js/dist/module/RealtimePresence.js
21
+ var o;
22
+ (function(e) {
23
+ e.SYNC = "sync", e.JOIN = "join", e.LEAVE = "leave";
24
+ })(o ||= {});
25
+ //#endregion
26
+ //#region node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.js
27
+ var s;
28
+ (function(e) {
29
+ e.ALL = "*", e.INSERT = "INSERT", e.UPDATE = "UPDATE", e.DELETE = "DELETE";
30
+ })(s ||= {});
31
+ var c;
32
+ (function(e) {
33
+ e.BROADCAST = "broadcast", e.PRESENCE = "presence", e.POSTGRES_CHANGES = "postgres_changes", e.SYSTEM = "system";
34
+ })(c ||= {});
35
+ var l;
36
+ (function(e) {
37
+ e.SUBSCRIBED = "SUBSCRIBED", e.TIMED_OUT = "TIMED_OUT", e.CLOSED = "CLOSED", e.CHANNEL_ERROR = "CHANNEL_ERROR";
38
+ })(l ||= {});
39
+ //#endregion
40
+ //#region node_modules/@supabase/auth-js/dist/module/lib/version.js
41
+ var u = "2.104.0", d = 30 * 1e3, f = 3 * d, p = "http://localhost:9999", m = "supabase.auth.token", h = { "X-Client-Info": `gotrue-js/${u}` }, g = "X-Supabase-Api-Version", ee = { "2024-01-01": {
42
+ timestamp: Date.parse("2024-01-01T00:00:00.0Z"),
43
+ name: "2024-01-01"
44
+ } }, te = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i, _ = class extends Error {
45
+ constructor(e, t, n) {
46
+ super(e), this.__isAuthError = !0, this.name = "AuthError", this.status = t, this.code = n;
47
+ }
48
+ toJSON() {
49
+ return {
50
+ name: this.name,
51
+ message: this.message,
52
+ status: this.status,
53
+ code: this.code
54
+ };
55
+ }
56
+ };
57
+ function v(e) {
58
+ return typeof e == "object" && !!e && "__isAuthError" in e;
59
+ }
60
+ var ne = class extends _ {
61
+ constructor(e, t, n) {
62
+ super(e, t, n), this.name = "AuthApiError", this.status = t, this.code = n;
63
+ }
64
+ };
65
+ function re(e) {
66
+ return v(e) && e.name === "AuthApiError";
67
+ }
68
+ var y = class extends _ {
69
+ constructor(e, t) {
70
+ super(e), this.name = "AuthUnknownError", this.originalError = t;
71
+ }
72
+ }, b = class extends _ {
73
+ constructor(e, t, n, r) {
74
+ super(e, n, r), this.name = t, this.status = n;
75
+ }
76
+ }, x = class extends b {
77
+ constructor() {
78
+ super("Auth session missing!", "AuthSessionMissingError", 400, void 0);
79
+ }
80
+ };
81
+ function S(e) {
82
+ return v(e) && e.name === "AuthSessionMissingError";
83
+ }
84
+ var C = class extends b {
85
+ constructor() {
86
+ super("Auth session or user missing", "AuthInvalidTokenResponseError", 500, void 0);
87
+ }
88
+ }, w = class extends b {
89
+ constructor(e) {
90
+ super(e, "AuthInvalidCredentialsError", 400, void 0);
91
+ }
92
+ }, T = class extends b {
93
+ constructor(e, t = null) {
94
+ super(e, "AuthImplicitGrantRedirectError", 500, void 0), this.details = null, this.details = t;
95
+ }
96
+ toJSON() {
97
+ return Object.assign(Object.assign({}, super.toJSON()), { details: this.details });
98
+ }
99
+ };
100
+ function ie(e) {
101
+ return v(e) && e.name === "AuthImplicitGrantRedirectError";
102
+ }
103
+ var ae = class extends b {
104
+ constructor(e, t = null) {
105
+ super(e, "AuthPKCEGrantCodeExchangeError", 500, void 0), this.details = null, this.details = t;
106
+ }
107
+ toJSON() {
108
+ return Object.assign(Object.assign({}, super.toJSON()), { details: this.details });
109
+ }
110
+ }, oe = class extends b {
111
+ constructor() {
112
+ super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.", "AuthPKCECodeVerifierMissingError", 400, "pkce_code_verifier_not_found");
113
+ }
114
+ }, se = class extends b {
115
+ constructor(e, t) {
116
+ super(e, "AuthRetryableFetchError", t, void 0);
117
+ }
118
+ };
119
+ function ce(e) {
120
+ return v(e) && e.name === "AuthRetryableFetchError";
121
+ }
122
+ var le = class extends b {
123
+ constructor(e, t, n) {
124
+ super(e, "AuthWeakPasswordError", t, "weak_password"), this.reasons = n;
125
+ }
126
+ toJSON() {
127
+ return Object.assign(Object.assign({}, super.toJSON()), { reasons: this.reasons });
128
+ }
129
+ }, ue = class extends b {
130
+ constructor(e) {
131
+ super(e, "AuthInvalidJwtError", 400, "invalid_jwt");
132
+ }
133
+ }, E = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""), de = " \n\r=".split(""), fe = (() => {
134
+ let e = Array(128);
135
+ for (let t = 0; t < e.length; t += 1) e[t] = -1;
136
+ for (let t = 0; t < de.length; t += 1) e[de[t].charCodeAt(0)] = -2;
137
+ for (let t = 0; t < E.length; t += 1) e[E[t].charCodeAt(0)] = t;
138
+ return e;
139
+ })();
140
+ function pe(e, t, n) {
141
+ if (e !== null) for (t.queue = t.queue << 8 | e, t.queuedBits += 8; t.queuedBits >= 6;) n(E[t.queue >> t.queuedBits - 6 & 63]), t.queuedBits -= 6;
142
+ else if (t.queuedBits > 0) for (t.queue <<= 6 - t.queuedBits, t.queuedBits = 6; t.queuedBits >= 6;) n(E[t.queue >> t.queuedBits - 6 & 63]), t.queuedBits -= 6;
143
+ }
144
+ function me(e, t, n) {
145
+ let r = fe[e];
146
+ if (r > -1) for (t.queue = t.queue << 6 | r, t.queuedBits += 6; t.queuedBits >= 8;) n(t.queue >> t.queuedBits - 8 & 255), t.queuedBits -= 8;
147
+ else if (r === -2) return;
148
+ else throw Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`);
149
+ }
150
+ function he(e) {
151
+ let t = [], n = (e) => {
152
+ t.push(String.fromCodePoint(e));
153
+ }, r = {
154
+ utf8seq: 0,
155
+ codepoint: 0
156
+ }, i = {
157
+ queue: 0,
158
+ queuedBits: 0
159
+ }, a = (e) => {
160
+ ve(e, r, n);
161
+ };
162
+ for (let t = 0; t < e.length; t += 1) me(e.charCodeAt(t), i, a);
163
+ return t.join("");
164
+ }
165
+ function ge(e, t) {
166
+ if (e <= 127) {
167
+ t(e);
168
+ return;
169
+ } else if (e <= 2047) {
170
+ t(192 | e >> 6), t(128 | e & 63);
171
+ return;
172
+ } else if (e <= 65535) {
173
+ t(224 | e >> 12), t(128 | e >> 6 & 63), t(128 | e & 63);
174
+ return;
175
+ } else if (e <= 1114111) {
176
+ t(240 | e >> 18), t(128 | e >> 12 & 63), t(128 | e >> 6 & 63), t(128 | e & 63);
177
+ return;
178
+ }
179
+ throw Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`);
180
+ }
181
+ function _e(e, t) {
182
+ for (let n = 0; n < e.length; n += 1) {
183
+ let r = e.charCodeAt(n);
184
+ if (r > 55295 && r <= 56319) {
185
+ let t = (r - 55296) * 1024 & 65535;
186
+ r = (e.charCodeAt(n + 1) - 56320 & 65535 | t) + 65536, n += 1;
187
+ }
188
+ ge(r, t);
189
+ }
190
+ }
191
+ function ve(e, t, n) {
192
+ if (t.utf8seq === 0) {
193
+ if (e <= 127) {
194
+ n(e);
195
+ return;
196
+ }
197
+ for (let n = 1; n < 6; n += 1) if (!(e >> 7 - n & 1)) {
198
+ t.utf8seq = n;
199
+ break;
200
+ }
201
+ if (t.utf8seq === 2) t.codepoint = e & 31;
202
+ else if (t.utf8seq === 3) t.codepoint = e & 15;
203
+ else if (t.utf8seq === 4) t.codepoint = e & 7;
204
+ else throw Error("Invalid UTF-8 sequence");
205
+ --t.utf8seq;
206
+ } else if (t.utf8seq > 0) {
207
+ if (e <= 127) throw Error("Invalid UTF-8 sequence");
208
+ t.codepoint = t.codepoint << 6 | e & 63, --t.utf8seq, t.utf8seq === 0 && n(t.codepoint);
209
+ }
210
+ }
211
+ function D(e) {
212
+ let t = [], n = {
213
+ queue: 0,
214
+ queuedBits: 0
215
+ }, r = (e) => {
216
+ t.push(e);
217
+ };
218
+ for (let t = 0; t < e.length; t += 1) me(e.charCodeAt(t), n, r);
219
+ return new Uint8Array(t);
220
+ }
221
+ function ye(e) {
222
+ let t = [];
223
+ return _e(e, (e) => t.push(e)), new Uint8Array(t);
224
+ }
225
+ function O(e) {
226
+ let t = [], n = {
227
+ queue: 0,
228
+ queuedBits: 0
229
+ }, r = (e) => {
230
+ t.push(e);
231
+ };
232
+ return e.forEach((e) => pe(e, n, r)), pe(null, n, r), t.join("");
233
+ }
234
+ //#endregion
235
+ //#region node_modules/@supabase/auth-js/dist/module/lib/helpers.js
236
+ function be(e) {
237
+ return Math.round(Date.now() / 1e3) + e;
238
+ }
239
+ function xe() {
240
+ return Symbol("auth-callback");
241
+ }
242
+ var k = () => typeof window < "u" && typeof document < "u", A = {
243
+ tested: !1,
244
+ writable: !1
245
+ }, Se = () => {
246
+ if (!k()) return !1;
247
+ try {
248
+ if (typeof globalThis.localStorage != "object") return !1;
249
+ } catch {
250
+ return !1;
251
+ }
252
+ if (A.tested) return A.writable;
253
+ let e = `lswt-${Math.random()}${Math.random()}`;
254
+ try {
255
+ globalThis.localStorage.setItem(e, e), globalThis.localStorage.removeItem(e), A.tested = !0, A.writable = !0;
256
+ } catch {
257
+ A.tested = !0, A.writable = !1;
258
+ }
259
+ return A.writable;
260
+ };
261
+ function Ce(e) {
262
+ let t = {}, n = new URL(e);
263
+ if (n.hash && n.hash[0] === "#") try {
264
+ new URLSearchParams(n.hash.substring(1)).forEach((e, n) => {
265
+ t[n] = e;
266
+ });
267
+ } catch {}
268
+ return n.searchParams.forEach((e, n) => {
269
+ t[n] = e;
270
+ }), t;
271
+ }
272
+ var we = (e) => e ? (...t) => e(...t) : (...e) => fetch(...e), Te = (e) => typeof e == "object" && !!e && "status" in e && "ok" in e && "json" in e && typeof e.json == "function", j = async (e, t, n) => {
273
+ await e.setItem(t, JSON.stringify(n));
274
+ }, M = async (e, t) => {
275
+ let n = await e.getItem(t);
276
+ if (!n) return null;
277
+ try {
278
+ return JSON.parse(n);
279
+ } catch {
280
+ return n;
281
+ }
282
+ }, N = async (e, t) => {
283
+ await e.removeItem(t);
284
+ }, Ee = class e {
285
+ constructor() {
286
+ this.promise = new e.promiseConstructor((e, t) => {
287
+ this.resolve = e, this.reject = t;
288
+ });
289
+ }
290
+ };
291
+ Ee.promiseConstructor = Promise;
292
+ function P(e) {
293
+ let t = e.split(".");
294
+ if (t.length !== 3) throw new ue("Invalid JWT structure");
295
+ for (let e = 0; e < t.length; e++) if (!te.test(t[e])) throw new ue("JWT not in base64url format");
296
+ return {
297
+ header: JSON.parse(he(t[0])),
298
+ payload: JSON.parse(he(t[1])),
299
+ signature: D(t[2]),
300
+ raw: {
301
+ header: t[0],
302
+ payload: t[1]
303
+ }
304
+ };
305
+ }
306
+ async function De(e) {
307
+ return await new Promise((t) => {
308
+ setTimeout(() => t(null), e);
309
+ });
310
+ }
311
+ function Oe(e, t) {
312
+ return new Promise((n, r) => {
313
+ (async () => {
314
+ for (let i = 0; i < Infinity; i++) try {
315
+ let r = await e(i);
316
+ if (!t(i, null, r)) {
317
+ n(r);
318
+ return;
319
+ }
320
+ } catch (e) {
321
+ if (!t(i, e)) {
322
+ r(e);
323
+ return;
324
+ }
325
+ }
326
+ })();
327
+ });
328
+ }
329
+ function ke(e) {
330
+ return ("0" + e.toString(16)).substr(-2);
331
+ }
332
+ function Ae() {
333
+ let e = new Uint32Array(56);
334
+ if (typeof crypto > "u") {
335
+ let e = "";
336
+ for (let t = 0; t < 56; t++) e += "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~".charAt(Math.floor(Math.random() * 66));
337
+ return e;
338
+ }
339
+ return crypto.getRandomValues(e), Array.from(e, ke).join("");
340
+ }
341
+ async function je(e) {
342
+ let t = new TextEncoder().encode(e), n = await crypto.subtle.digest("SHA-256", t), r = new Uint8Array(n);
343
+ return Array.from(r).map((e) => String.fromCharCode(e)).join("");
344
+ }
345
+ async function Me(e) {
346
+ if (!(typeof crypto < "u" && crypto.subtle !== void 0 && typeof TextEncoder < "u")) return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."), e;
347
+ let t = await je(e);
348
+ return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
349
+ }
350
+ async function F(e, t, n = !1) {
351
+ let r = Ae(), i = r;
352
+ n && (i += "/PASSWORD_RECOVERY"), await j(e, `${t}-code-verifier`, i);
353
+ let a = await Me(r);
354
+ return [a, r === a ? "plain" : "s256"];
355
+ }
356
+ var Ne = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;
357
+ function Pe(e) {
358
+ let t = e.headers.get(g);
359
+ if (!t || !t.match(Ne)) return null;
360
+ try {
361
+ return /* @__PURE__ */ new Date(`${t}T00:00:00.0Z`);
362
+ } catch {
363
+ return null;
364
+ }
365
+ }
366
+ function Fe(e) {
367
+ if (!e) throw Error("Missing exp claim");
368
+ if (e <= Math.floor(Date.now() / 1e3)) throw Error("JWT has expired");
369
+ }
370
+ function Ie(e) {
371
+ switch (e) {
372
+ case "RS256": return {
373
+ name: "RSASSA-PKCS1-v1_5",
374
+ hash: { name: "SHA-256" }
375
+ };
376
+ case "ES256": return {
377
+ name: "ECDSA",
378
+ namedCurve: "P-256",
379
+ hash: { name: "SHA-256" }
380
+ };
381
+ default: throw Error("Invalid alg claim");
382
+ }
383
+ }
384
+ var Le = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
385
+ function I(e) {
386
+ if (!Le.test(e)) throw Error("@supabase/auth-js: Expected parameter to be UUID but is not");
387
+ }
388
+ function L() {
389
+ return new Proxy({}, {
390
+ get: (e, t) => {
391
+ if (t === "__isUserNotAvailableProxy") return !0;
392
+ if (typeof t == "symbol") {
393
+ let e = t.toString();
394
+ if (e === "Symbol(Symbol.toPrimitive)" || e === "Symbol(Symbol.toStringTag)" || e === "Symbol(util.inspect.custom)") return;
395
+ }
396
+ throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`);
397
+ },
398
+ set: (e, t) => {
399
+ throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`);
400
+ },
401
+ deleteProperty: (e, t) => {
402
+ throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`);
403
+ }
404
+ });
405
+ }
406
+ function Re(e, t) {
407
+ return new Proxy(e, { get: (e, n, r) => {
408
+ if (n === "__isInsecureUserWarningProxy") return !0;
409
+ if (typeof n == "symbol") {
410
+ let t = n.toString();
411
+ if (t === "Symbol(Symbol.toPrimitive)" || t === "Symbol(Symbol.toStringTag)" || t === "Symbol(util.inspect.custom)" || t === "Symbol(nodejs.util.inspect.custom)") return Reflect.get(e, n, r);
412
+ }
413
+ return !t.value && typeof n == "string" && (console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."), t.value = !0), Reflect.get(e, n, r);
414
+ } });
415
+ }
416
+ function ze(e) {
417
+ return JSON.parse(JSON.stringify(e));
418
+ }
419
+ //#endregion
420
+ //#region node_modules/@supabase/auth-js/dist/module/lib/fetch.js
421
+ var R = (e) => e.msg || e.message || e.error_description || e.error || JSON.stringify(e), Be = [
422
+ 502,
423
+ 503,
424
+ 504,
425
+ 520,
426
+ 521,
427
+ 522,
428
+ 523,
429
+ 524,
430
+ 530
431
+ ];
432
+ async function Ve(e) {
433
+ if (!Te(e)) throw new se(R(e), 0);
434
+ if (Be.includes(e.status)) throw new se(R(e), e.status);
435
+ let t;
436
+ try {
437
+ t = await e.json();
438
+ } catch (e) {
439
+ throw new y(R(e), e);
440
+ }
441
+ let n, r = Pe(e);
442
+ if (r && r.getTime() >= ee["2024-01-01"].timestamp && typeof t == "object" && t && typeof t.code == "string" ? n = t.code : typeof t == "object" && t && typeof t.error_code == "string" && (n = t.error_code), !n) {
443
+ if (typeof t == "object" && t && typeof t.weak_password == "object" && t.weak_password && Array.isArray(t.weak_password.reasons) && t.weak_password.reasons.length && t.weak_password.reasons.reduce((e, t) => e && typeof t == "string", !0)) throw new le(R(t), e.status, t.weak_password.reasons);
444
+ } else if (n === "weak_password") throw new le(R(t), e.status, t.weak_password?.reasons || []);
445
+ else if (n === "session_not_found") throw new x();
446
+ throw new ne(R(t), e.status || 500, n);
447
+ }
448
+ var He = (e, t, n, r) => {
449
+ let i = {
450
+ method: e,
451
+ headers: t?.headers || {}
452
+ };
453
+ return e === "GET" ? i : (i.headers = Object.assign({ "Content-Type": "application/json;charset=UTF-8" }, t?.headers), i.body = JSON.stringify(r), Object.assign(Object.assign({}, i), n));
454
+ };
455
+ async function z(e, t, n, r) {
456
+ let i = Object.assign({}, r?.headers);
457
+ i["X-Supabase-Api-Version"] || (i[g] = ee["2024-01-01"].name), r?.jwt && (i.Authorization = `Bearer ${r.jwt}`);
458
+ let a = r?.query ?? {};
459
+ r?.redirectTo && (a.redirect_to = r.redirectTo);
460
+ let o = await Ue(e, t, n + (Object.keys(a).length ? "?" + new URLSearchParams(a).toString() : ""), {
461
+ headers: i,
462
+ noResolveJson: r?.noResolveJson
463
+ }, {}, r?.body);
464
+ return r?.xform ? r?.xform(o) : {
465
+ data: Object.assign({}, o),
466
+ error: null
467
+ };
468
+ }
469
+ async function Ue(e, t, n, r, i, a) {
470
+ let o = He(t, r, i, a), s;
471
+ try {
472
+ s = await e(n, Object.assign({}, o));
473
+ } catch (e) {
474
+ throw console.error(e), new se(R(e), 0);
475
+ }
476
+ if (s.ok || await Ve(s), r?.noResolveJson) return s;
477
+ try {
478
+ return await s.json();
479
+ } catch (e) {
480
+ await Ve(e);
481
+ }
482
+ }
483
+ function B(e) {
484
+ let t = null;
485
+ Je(e) && (t = Object.assign({}, e), e.expires_at || (t.expires_at = be(e.expires_in)));
486
+ let n = e.user ?? e;
487
+ return {
488
+ data: {
489
+ session: t,
490
+ user: n
491
+ },
492
+ error: null
493
+ };
494
+ }
495
+ function We(e) {
496
+ let t = B(e);
497
+ return !t.error && e.weak_password && typeof e.weak_password == "object" && Array.isArray(e.weak_password.reasons) && e.weak_password.reasons.length && e.weak_password.message && typeof e.weak_password.message == "string" && e.weak_password.reasons.reduce((e, t) => e && typeof t == "string", !0) && (t.data.weak_password = e.weak_password), t;
498
+ }
499
+ function V(e) {
500
+ return {
501
+ data: { user: e.user ?? e },
502
+ error: null
503
+ };
504
+ }
505
+ function Ge(e) {
506
+ return {
507
+ data: e,
508
+ error: null
509
+ };
510
+ }
511
+ function Ke(e) {
512
+ let { action_link: t, email_otp: n, hashed_token: r, redirect_to: a, verification_type: o } = e, s = i(e, [
513
+ "action_link",
514
+ "email_otp",
515
+ "hashed_token",
516
+ "redirect_to",
517
+ "verification_type"
518
+ ]);
519
+ return {
520
+ data: {
521
+ properties: {
522
+ action_link: t,
523
+ email_otp: n,
524
+ hashed_token: r,
525
+ redirect_to: a,
526
+ verification_type: o
527
+ },
528
+ user: Object.assign({}, s)
529
+ },
530
+ error: null
531
+ };
532
+ }
533
+ function qe(e) {
534
+ return e;
535
+ }
536
+ function Je(e) {
537
+ return e.access_token && e.refresh_token && e.expires_in;
538
+ }
539
+ //#endregion
540
+ //#region node_modules/@supabase/auth-js/dist/module/lib/types.js
541
+ var H = [
542
+ "global",
543
+ "local",
544
+ "others"
545
+ ], Ye = class {
546
+ constructor({ url: e = "", headers: t = {}, fetch: n }) {
547
+ this.url = e, this.headers = t, this.fetch = we(n), this.mfa = {
548
+ listFactors: this._listFactors.bind(this),
549
+ deleteFactor: this._deleteFactor.bind(this)
550
+ }, this.oauth = {
551
+ listClients: this._listOAuthClients.bind(this),
552
+ createClient: this._createOAuthClient.bind(this),
553
+ getClient: this._getOAuthClient.bind(this),
554
+ updateClient: this._updateOAuthClient.bind(this),
555
+ deleteClient: this._deleteOAuthClient.bind(this),
556
+ regenerateClientSecret: this._regenerateOAuthClientSecret.bind(this)
557
+ }, this.customProviders = {
558
+ listProviders: this._listCustomProviders.bind(this),
559
+ createProvider: this._createCustomProvider.bind(this),
560
+ getProvider: this._getCustomProvider.bind(this),
561
+ updateProvider: this._updateCustomProvider.bind(this),
562
+ deleteProvider: this._deleteCustomProvider.bind(this)
563
+ };
564
+ }
565
+ async signOut(e, t = H[0]) {
566
+ if (H.indexOf(t) < 0) throw Error(`@supabase/auth-js: Parameter scope must be one of ${H.join(", ")}`);
567
+ try {
568
+ return await z(this.fetch, "POST", `${this.url}/logout?scope=${t}`, {
569
+ headers: this.headers,
570
+ jwt: e,
571
+ noResolveJson: !0
572
+ }), {
573
+ data: null,
574
+ error: null
575
+ };
576
+ } catch (e) {
577
+ if (v(e)) return {
578
+ data: null,
579
+ error: e
580
+ };
581
+ throw e;
582
+ }
583
+ }
584
+ async inviteUserByEmail(e, t = {}) {
585
+ try {
586
+ return await z(this.fetch, "POST", `${this.url}/invite`, {
587
+ body: {
588
+ email: e,
589
+ data: t.data
590
+ },
591
+ headers: this.headers,
592
+ redirectTo: t.redirectTo,
593
+ xform: V
594
+ });
595
+ } catch (e) {
596
+ if (v(e)) return {
597
+ data: { user: null },
598
+ error: e
599
+ };
600
+ throw e;
601
+ }
602
+ }
603
+ async generateLink(e) {
604
+ try {
605
+ let { options: t } = e, n = i(e, ["options"]), r = Object.assign(Object.assign({}, n), t);
606
+ return "newEmail" in n && (r.new_email = n?.newEmail, delete r.newEmail), await z(this.fetch, "POST", `${this.url}/admin/generate_link`, {
607
+ body: r,
608
+ headers: this.headers,
609
+ xform: Ke,
610
+ redirectTo: t?.redirectTo
611
+ });
612
+ } catch (e) {
613
+ if (v(e)) return {
614
+ data: {
615
+ properties: null,
616
+ user: null
617
+ },
618
+ error: e
619
+ };
620
+ throw e;
621
+ }
622
+ }
623
+ async createUser(e) {
624
+ try {
625
+ return await z(this.fetch, "POST", `${this.url}/admin/users`, {
626
+ body: e,
627
+ headers: this.headers,
628
+ xform: V
629
+ });
630
+ } catch (e) {
631
+ if (v(e)) return {
632
+ data: { user: null },
633
+ error: e
634
+ };
635
+ throw e;
636
+ }
637
+ }
638
+ async listUsers(e) {
639
+ try {
640
+ let t = {
641
+ nextPage: null,
642
+ lastPage: 0,
643
+ total: 0
644
+ }, n = await z(this.fetch, "GET", `${this.url}/admin/users`, {
645
+ headers: this.headers,
646
+ noResolveJson: !0,
647
+ query: {
648
+ page: (e?.page)?.toString() ?? "",
649
+ per_page: (e?.perPage)?.toString() ?? ""
650
+ },
651
+ xform: qe
652
+ });
653
+ if (n.error) throw n.error;
654
+ let r = await n.json(), i = n.headers.get("x-total-count") ?? 0, a = n.headers.get("link")?.split(",") ?? [];
655
+ return a.length > 0 && (a.forEach((e) => {
656
+ let n = parseInt(e.split(";")[0].split("=")[1].substring(0, 1)), r = JSON.parse(e.split(";")[1].split("=")[1]);
657
+ t[`${r}Page`] = n;
658
+ }), t.total = parseInt(i)), {
659
+ data: Object.assign(Object.assign({}, r), t),
660
+ error: null
661
+ };
662
+ } catch (e) {
663
+ if (v(e)) return {
664
+ data: { users: [] },
665
+ error: e
666
+ };
667
+ throw e;
668
+ }
669
+ }
670
+ async getUserById(e) {
671
+ I(e);
672
+ try {
673
+ return await z(this.fetch, "GET", `${this.url}/admin/users/${e}`, {
674
+ headers: this.headers,
675
+ xform: V
676
+ });
677
+ } catch (e) {
678
+ if (v(e)) return {
679
+ data: { user: null },
680
+ error: e
681
+ };
682
+ throw e;
683
+ }
684
+ }
685
+ async updateUserById(e, t) {
686
+ I(e);
687
+ try {
688
+ return await z(this.fetch, "PUT", `${this.url}/admin/users/${e}`, {
689
+ body: t,
690
+ headers: this.headers,
691
+ xform: V
692
+ });
693
+ } catch (e) {
694
+ if (v(e)) return {
695
+ data: { user: null },
696
+ error: e
697
+ };
698
+ throw e;
699
+ }
700
+ }
701
+ async deleteUser(e, t = !1) {
702
+ I(e);
703
+ try {
704
+ return await z(this.fetch, "DELETE", `${this.url}/admin/users/${e}`, {
705
+ headers: this.headers,
706
+ body: { should_soft_delete: t },
707
+ xform: V
708
+ });
709
+ } catch (e) {
710
+ if (v(e)) return {
711
+ data: { user: null },
712
+ error: e
713
+ };
714
+ throw e;
715
+ }
716
+ }
717
+ async _listFactors(e) {
718
+ I(e.userId);
719
+ try {
720
+ let { data: t, error: n } = await z(this.fetch, "GET", `${this.url}/admin/users/${e.userId}/factors`, {
721
+ headers: this.headers,
722
+ xform: (e) => ({
723
+ data: { factors: e },
724
+ error: null
725
+ })
726
+ });
727
+ return {
728
+ data: t,
729
+ error: n
730
+ };
731
+ } catch (e) {
732
+ if (v(e)) return {
733
+ data: null,
734
+ error: e
735
+ };
736
+ throw e;
737
+ }
738
+ }
739
+ async _deleteFactor(e) {
740
+ I(e.userId), I(e.id);
741
+ try {
742
+ return {
743
+ data: await z(this.fetch, "DELETE", `${this.url}/admin/users/${e.userId}/factors/${e.id}`, { headers: this.headers }),
744
+ error: null
745
+ };
746
+ } catch (e) {
747
+ if (v(e)) return {
748
+ data: null,
749
+ error: e
750
+ };
751
+ throw e;
752
+ }
753
+ }
754
+ async _listOAuthClients(e) {
755
+ try {
756
+ let t = {
757
+ nextPage: null,
758
+ lastPage: 0,
759
+ total: 0
760
+ }, n = await z(this.fetch, "GET", `${this.url}/admin/oauth/clients`, {
761
+ headers: this.headers,
762
+ noResolveJson: !0,
763
+ query: {
764
+ page: (e?.page)?.toString() ?? "",
765
+ per_page: (e?.perPage)?.toString() ?? ""
766
+ },
767
+ xform: qe
768
+ });
769
+ if (n.error) throw n.error;
770
+ let r = await n.json(), i = n.headers.get("x-total-count") ?? 0, a = n.headers.get("link")?.split(",") ?? [];
771
+ return a.length > 0 && (a.forEach((e) => {
772
+ let n = parseInt(e.split(";")[0].split("=")[1].substring(0, 1)), r = JSON.parse(e.split(";")[1].split("=")[1]);
773
+ t[`${r}Page`] = n;
774
+ }), t.total = parseInt(i)), {
775
+ data: Object.assign(Object.assign({}, r), t),
776
+ error: null
777
+ };
778
+ } catch (e) {
779
+ if (v(e)) return {
780
+ data: { clients: [] },
781
+ error: e
782
+ };
783
+ throw e;
784
+ }
785
+ }
786
+ async _createOAuthClient(e) {
787
+ try {
788
+ return await z(this.fetch, "POST", `${this.url}/admin/oauth/clients`, {
789
+ body: e,
790
+ headers: this.headers,
791
+ xform: (e) => ({
792
+ data: e,
793
+ error: null
794
+ })
795
+ });
796
+ } catch (e) {
797
+ if (v(e)) return {
798
+ data: null,
799
+ error: e
800
+ };
801
+ throw e;
802
+ }
803
+ }
804
+ async _getOAuthClient(e) {
805
+ try {
806
+ return await z(this.fetch, "GET", `${this.url}/admin/oauth/clients/${e}`, {
807
+ headers: this.headers,
808
+ xform: (e) => ({
809
+ data: e,
810
+ error: null
811
+ })
812
+ });
813
+ } catch (e) {
814
+ if (v(e)) return {
815
+ data: null,
816
+ error: e
817
+ };
818
+ throw e;
819
+ }
820
+ }
821
+ async _updateOAuthClient(e, t) {
822
+ try {
823
+ return await z(this.fetch, "PUT", `${this.url}/admin/oauth/clients/${e}`, {
824
+ body: t,
825
+ headers: this.headers,
826
+ xform: (e) => ({
827
+ data: e,
828
+ error: null
829
+ })
830
+ });
831
+ } catch (e) {
832
+ if (v(e)) return {
833
+ data: null,
834
+ error: e
835
+ };
836
+ throw e;
837
+ }
838
+ }
839
+ async _deleteOAuthClient(e) {
840
+ try {
841
+ return await z(this.fetch, "DELETE", `${this.url}/admin/oauth/clients/${e}`, {
842
+ headers: this.headers,
843
+ noResolveJson: !0
844
+ }), {
845
+ data: null,
846
+ error: null
847
+ };
848
+ } catch (e) {
849
+ if (v(e)) return {
850
+ data: null,
851
+ error: e
852
+ };
853
+ throw e;
854
+ }
855
+ }
856
+ async _regenerateOAuthClientSecret(e) {
857
+ try {
858
+ return await z(this.fetch, "POST", `${this.url}/admin/oauth/clients/${e}/regenerate_secret`, {
859
+ headers: this.headers,
860
+ xform: (e) => ({
861
+ data: e,
862
+ error: null
863
+ })
864
+ });
865
+ } catch (e) {
866
+ if (v(e)) return {
867
+ data: null,
868
+ error: e
869
+ };
870
+ throw e;
871
+ }
872
+ }
873
+ async _listCustomProviders(e) {
874
+ try {
875
+ let t = {};
876
+ return e?.type && (t.type = e.type), await z(this.fetch, "GET", `${this.url}/admin/custom-providers`, {
877
+ headers: this.headers,
878
+ query: t,
879
+ xform: (e) => ({
880
+ data: { providers: e?.providers ?? [] },
881
+ error: null
882
+ })
883
+ });
884
+ } catch (e) {
885
+ if (v(e)) return {
886
+ data: { providers: [] },
887
+ error: e
888
+ };
889
+ throw e;
890
+ }
891
+ }
892
+ async _createCustomProvider(e) {
893
+ try {
894
+ return await z(this.fetch, "POST", `${this.url}/admin/custom-providers`, {
895
+ body: e,
896
+ headers: this.headers,
897
+ xform: (e) => ({
898
+ data: e,
899
+ error: null
900
+ })
901
+ });
902
+ } catch (e) {
903
+ if (v(e)) return {
904
+ data: null,
905
+ error: e
906
+ };
907
+ throw e;
908
+ }
909
+ }
910
+ async _getCustomProvider(e) {
911
+ try {
912
+ return await z(this.fetch, "GET", `${this.url}/admin/custom-providers/${e}`, {
913
+ headers: this.headers,
914
+ xform: (e) => ({
915
+ data: e,
916
+ error: null
917
+ })
918
+ });
919
+ } catch (e) {
920
+ if (v(e)) return {
921
+ data: null,
922
+ error: e
923
+ };
924
+ throw e;
925
+ }
926
+ }
927
+ async _updateCustomProvider(e, t) {
928
+ try {
929
+ return await z(this.fetch, "PUT", `${this.url}/admin/custom-providers/${e}`, {
930
+ body: t,
931
+ headers: this.headers,
932
+ xform: (e) => ({
933
+ data: e,
934
+ error: null
935
+ })
936
+ });
937
+ } catch (e) {
938
+ if (v(e)) return {
939
+ data: null,
940
+ error: e
941
+ };
942
+ throw e;
943
+ }
944
+ }
945
+ async _deleteCustomProvider(e) {
946
+ try {
947
+ return await z(this.fetch, "DELETE", `${this.url}/admin/custom-providers/${e}`, {
948
+ headers: this.headers,
949
+ noResolveJson: !0
950
+ }), {
951
+ data: null,
952
+ error: null
953
+ };
954
+ } catch (e) {
955
+ if (v(e)) return {
956
+ data: null,
957
+ error: e
958
+ };
959
+ throw e;
960
+ }
961
+ }
962
+ };
963
+ //#endregion
964
+ //#region node_modules/@supabase/auth-js/dist/module/lib/local-storage.js
965
+ function Xe(e = {}) {
966
+ return {
967
+ getItem: (t) => e[t] || null,
968
+ setItem: (t, n) => {
969
+ e[t] = n;
970
+ },
971
+ removeItem: (t) => {
972
+ delete e[t];
973
+ }
974
+ };
975
+ }
976
+ //#endregion
977
+ //#region node_modules/@supabase/auth-js/dist/module/lib/locks.js
978
+ var U = { debug: !!(globalThis && Se() && globalThis.localStorage && globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug") === "true") }, Ze = class extends Error {
979
+ constructor(e) {
980
+ super(e), this.isAcquireTimeout = !0;
981
+ }
982
+ }, Qe = class extends Ze {};
983
+ async function $e(e, t, n) {
984
+ U.debug && console.log("@supabase/gotrue-js: navigatorLock: acquire lock", e, t);
985
+ let r = new globalThis.AbortController(), i;
986
+ t > 0 && (i = setTimeout(() => {
987
+ r.abort(), U.debug && console.log("@supabase/gotrue-js: navigatorLock acquire timed out", e);
988
+ }, t)), await Promise.resolve();
989
+ try {
990
+ return await globalThis.navigator.locks.request(e, t === 0 ? {
991
+ mode: "exclusive",
992
+ ifAvailable: !0
993
+ } : {
994
+ mode: "exclusive",
995
+ signal: r.signal
996
+ }, async (r) => {
997
+ if (r) {
998
+ clearTimeout(i), U.debug && console.log("@supabase/gotrue-js: navigatorLock: acquired", e, r.name);
999
+ try {
1000
+ return await n();
1001
+ } finally {
1002
+ U.debug && console.log("@supabase/gotrue-js: navigatorLock: released", e, r.name);
1003
+ }
1004
+ } else if (t === 0) throw U.debug && console.log("@supabase/gotrue-js: navigatorLock: not immediately available", e), new Qe(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);
1005
+ else {
1006
+ if (U.debug) try {
1007
+ let e = await globalThis.navigator.locks.query();
1008
+ console.log("@supabase/gotrue-js: Navigator LockManager state", JSON.stringify(e, null, " "));
1009
+ } catch (e) {
1010
+ console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state", e);
1011
+ }
1012
+ return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"), clearTimeout(i), await n();
1013
+ }
1014
+ });
1015
+ } catch (a) {
1016
+ if (t > 0 && clearTimeout(i), a?.name === "AbortError" && t > 0) {
1017
+ if (r.signal.aborted) return U.debug && console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock", e), console.warn(`@supabase/gotrue-js: Lock "${e}" was not released within ${t}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`), await Promise.resolve().then(() => globalThis.navigator.locks.request(e, {
1018
+ mode: "exclusive",
1019
+ steal: !0
1020
+ }, async (t) => {
1021
+ if (t) {
1022
+ U.debug && console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)", e, t.name);
1023
+ try {
1024
+ return await n();
1025
+ } finally {
1026
+ U.debug && console.log("@supabase/gotrue-js: navigatorLock: released (stolen)", e, t.name);
1027
+ }
1028
+ } else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"), await n();
1029
+ }));
1030
+ throw U.debug && console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request", e), new Qe(`Lock "${e}" was released because another request stole it`);
1031
+ }
1032
+ throw a;
1033
+ }
1034
+ }
1035
+ //#endregion
1036
+ //#region node_modules/@supabase/auth-js/dist/module/lib/polyfills.js
1037
+ function et() {
1038
+ if (typeof globalThis != "object") try {
1039
+ Object.defineProperty(Object.prototype, "__magic__", {
1040
+ get: function() {
1041
+ return this;
1042
+ },
1043
+ configurable: !0
1044
+ }), __magic__.globalThis = __magic__, delete Object.prototype.__magic__;
1045
+ } catch {
1046
+ typeof self < "u" && (self.globalThis = self);
1047
+ }
1048
+ }
1049
+ //#endregion
1050
+ //#region node_modules/@supabase/auth-js/dist/module/lib/web3/ethereum.js
1051
+ function tt(e) {
1052
+ if (!/^0x[a-fA-F0-9]{40}$/.test(e)) throw Error(`@supabase/auth-js: Address "${e}" is invalid.`);
1053
+ return e.toLowerCase();
1054
+ }
1055
+ function nt(e) {
1056
+ return parseInt(e, 16);
1057
+ }
1058
+ function rt(e) {
1059
+ let t = new TextEncoder().encode(e);
1060
+ return "0x" + Array.from(t, (e) => e.toString(16).padStart(2, "0")).join("");
1061
+ }
1062
+ function it(e) {
1063
+ let { chainId: t, domain: n, expirationTime: r, issuedAt: i = /* @__PURE__ */ new Date(), nonce: a, notBefore: o, requestId: s, resources: c, scheme: l, uri: u, version: d } = e;
1064
+ if (!Number.isInteger(t)) throw Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);
1065
+ if (!n) throw Error("@supabase/auth-js: Invalid SIWE message field \"domain\". Domain must be provided.");
1066
+ if (a && a.length < 8) throw Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);
1067
+ if (!u) throw Error("@supabase/auth-js: Invalid SIWE message field \"uri\". URI must be provided.");
1068
+ if (d !== "1") throw Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);
1069
+ if (e.statement?.includes("\n")) throw Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);
1070
+ let f = tt(e.address), p = `${l ? `${l}://${n}` : n} wants you to sign in with your Ethereum account:\n${f}\n\n${e.statement ? `${e.statement}\n` : ""}`, m = `URI: ${u}\nVersion: ${d}\nChain ID: ${t}${a ? `\nNonce: ${a}` : ""}\nIssued At: ${i.toISOString()}`;
1071
+ if (r && (m += `\nExpiration Time: ${r.toISOString()}`), o && (m += `\nNot Before: ${o.toISOString()}`), s && (m += `\nRequest ID: ${s}`), c) {
1072
+ let e = "\nResources:";
1073
+ for (let t of c) {
1074
+ if (!t || typeof t != "string") throw Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);
1075
+ e += `\n- ${t}`;
1076
+ }
1077
+ m += e;
1078
+ }
1079
+ return `${p}\n${m}`;
1080
+ }
1081
+ //#endregion
1082
+ //#region node_modules/@supabase/auth-js/dist/module/lib/webauthn.errors.js
1083
+ var W = class extends Error {
1084
+ constructor({ message: e, code: t, cause: n, name: r }) {
1085
+ super(e, { cause: n }), this.__isWebAuthnError = !0, this.name = r ?? (n instanceof Error ? n.name : void 0) ?? "Unknown Error", this.code = t;
1086
+ }
1087
+ }, G = class extends W {
1088
+ constructor(e, t) {
1089
+ super({
1090
+ code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",
1091
+ cause: t,
1092
+ message: e
1093
+ }), this.name = "WebAuthnUnknownError", this.originalError = t;
1094
+ }
1095
+ };
1096
+ function at({ error: e, options: t }) {
1097
+ let { publicKey: n } = t;
1098
+ if (!n) throw Error("options was missing required publicKey property");
1099
+ if (e.name === "AbortError") {
1100
+ if (t.signal instanceof AbortSignal) return new W({
1101
+ message: "Registration ceremony was sent an abort signal",
1102
+ code: "ERROR_CEREMONY_ABORTED",
1103
+ cause: e
1104
+ });
1105
+ } else if (e.name === "ConstraintError") {
1106
+ if (n.authenticatorSelection?.requireResidentKey === !0) return new W({
1107
+ message: "Discoverable credentials were required but no available authenticator supported it",
1108
+ code: "ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",
1109
+ cause: e
1110
+ });
1111
+ if (t.mediation === "conditional" && n.authenticatorSelection?.userVerification === "required") return new W({
1112
+ message: "User verification was required during automatic registration but it could not be performed",
1113
+ code: "ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",
1114
+ cause: e
1115
+ });
1116
+ if (n.authenticatorSelection?.userVerification === "required") return new W({
1117
+ message: "User verification was required but no available authenticator supported it",
1118
+ code: "ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",
1119
+ cause: e
1120
+ });
1121
+ } else if (e.name === "InvalidStateError") return new W({
1122
+ message: "The authenticator was previously registered",
1123
+ code: "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",
1124
+ cause: e
1125
+ });
1126
+ else if (e.name === "NotAllowedError") return new W({
1127
+ message: e.message,
1128
+ code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",
1129
+ cause: e
1130
+ });
1131
+ else if (e.name === "NotSupportedError") return n.pubKeyCredParams.filter((e) => e.type === "public-key").length === 0 ? new W({
1132
+ message: "No entry in pubKeyCredParams was of type \"public-key\"",
1133
+ code: "ERROR_MALFORMED_PUBKEYCREDPARAMS",
1134
+ cause: e
1135
+ }) : new W({
1136
+ message: "No available authenticator supported any of the specified pubKeyCredParams algorithms",
1137
+ code: "ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",
1138
+ cause: e
1139
+ });
1140
+ else if (e.name === "SecurityError") {
1141
+ let t = window.location.hostname;
1142
+ if (!ft(t)) return new W({
1143
+ message: `${window.location.hostname} is an invalid domain`,
1144
+ code: "ERROR_INVALID_DOMAIN",
1145
+ cause: e
1146
+ });
1147
+ if (n.rp.id !== t) return new W({
1148
+ message: `The RP ID "${n.rp.id}" is invalid for this domain`,
1149
+ code: "ERROR_INVALID_RP_ID",
1150
+ cause: e
1151
+ });
1152
+ } else if (e.name === "TypeError") {
1153
+ if (n.user.id.byteLength < 1 || n.user.id.byteLength > 64) return new W({
1154
+ message: "User ID was not between 1 and 64 characters",
1155
+ code: "ERROR_INVALID_USER_ID_LENGTH",
1156
+ cause: e
1157
+ });
1158
+ } else if (e.name === "UnknownError") return new W({
1159
+ message: "The authenticator was unable to process the specified options, or could not create a new credential",
1160
+ code: "ERROR_AUTHENTICATOR_GENERAL_ERROR",
1161
+ cause: e
1162
+ });
1163
+ return new W({
1164
+ message: "a Non-Webauthn related error has occurred",
1165
+ code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",
1166
+ cause: e
1167
+ });
1168
+ }
1169
+ function ot({ error: e, options: t }) {
1170
+ let { publicKey: n } = t;
1171
+ if (!n) throw Error("options was missing required publicKey property");
1172
+ if (e.name === "AbortError") {
1173
+ if (t.signal instanceof AbortSignal) return new W({
1174
+ message: "Authentication ceremony was sent an abort signal",
1175
+ code: "ERROR_CEREMONY_ABORTED",
1176
+ cause: e
1177
+ });
1178
+ } else if (e.name === "NotAllowedError") return new W({
1179
+ message: e.message,
1180
+ code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",
1181
+ cause: e
1182
+ });
1183
+ else if (e.name === "SecurityError") {
1184
+ let t = window.location.hostname;
1185
+ if (!ft(t)) return new W({
1186
+ message: `${window.location.hostname} is an invalid domain`,
1187
+ code: "ERROR_INVALID_DOMAIN",
1188
+ cause: e
1189
+ });
1190
+ if (n.rpId !== t) return new W({
1191
+ message: `The RP ID "${n.rpId}" is invalid for this domain`,
1192
+ code: "ERROR_INVALID_RP_ID",
1193
+ cause: e
1194
+ });
1195
+ } else if (e.name === "UnknownError") return new W({
1196
+ message: "The authenticator was unable to process the specified options, or could not create a new assertion signature",
1197
+ code: "ERROR_AUTHENTICATOR_GENERAL_ERROR",
1198
+ cause: e
1199
+ });
1200
+ return new W({
1201
+ message: "a Non-Webauthn related error has occurred",
1202
+ code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",
1203
+ cause: e
1204
+ });
1205
+ }
1206
+ var st = new class {
1207
+ createNewAbortSignal() {
1208
+ if (this.controller) {
1209
+ let e = /* @__PURE__ */ Error("Cancelling existing WebAuthn API call for new one");
1210
+ e.name = "AbortError", this.controller.abort(e);
1211
+ }
1212
+ let e = new AbortController();
1213
+ return this.controller = e, e.signal;
1214
+ }
1215
+ cancelCeremony() {
1216
+ if (this.controller) {
1217
+ let e = /* @__PURE__ */ Error("Manually cancelling existing WebAuthn API call");
1218
+ e.name = "AbortError", this.controller.abort(e), this.controller = void 0;
1219
+ }
1220
+ }
1221
+ }();
1222
+ function ct(e) {
1223
+ if (!e) throw Error("Credential creation options are required");
1224
+ if (typeof PublicKeyCredential < "u" && "parseCreationOptionsFromJSON" in PublicKeyCredential && typeof PublicKeyCredential.parseCreationOptionsFromJSON == "function") return PublicKeyCredential.parseCreationOptionsFromJSON(e);
1225
+ let { challenge: t, user: n, excludeCredentials: r } = e, a = i(e, [
1226
+ "challenge",
1227
+ "user",
1228
+ "excludeCredentials"
1229
+ ]), o = D(t).buffer, s = Object.assign(Object.assign({}, n), { id: D(n.id).buffer }), c = Object.assign(Object.assign({}, a), {
1230
+ challenge: o,
1231
+ user: s
1232
+ });
1233
+ if (r && r.length > 0) {
1234
+ c.excludeCredentials = Array(r.length);
1235
+ for (let e = 0; e < r.length; e++) {
1236
+ let t = r[e];
1237
+ c.excludeCredentials[e] = Object.assign(Object.assign({}, t), {
1238
+ id: D(t.id).buffer,
1239
+ type: t.type || "public-key",
1240
+ transports: t.transports
1241
+ });
1242
+ }
1243
+ }
1244
+ return c;
1245
+ }
1246
+ function lt(e) {
1247
+ if (!e) throw Error("Credential request options are required");
1248
+ if (typeof PublicKeyCredential < "u" && "parseRequestOptionsFromJSON" in PublicKeyCredential && typeof PublicKeyCredential.parseRequestOptionsFromJSON == "function") return PublicKeyCredential.parseRequestOptionsFromJSON(e);
1249
+ let { challenge: t, allowCredentials: n } = e, r = i(e, ["challenge", "allowCredentials"]), a = D(t).buffer, o = Object.assign(Object.assign({}, r), { challenge: a });
1250
+ if (n && n.length > 0) {
1251
+ o.allowCredentials = Array(n.length);
1252
+ for (let e = 0; e < n.length; e++) {
1253
+ let t = n[e];
1254
+ o.allowCredentials[e] = Object.assign(Object.assign({}, t), {
1255
+ id: D(t.id).buffer,
1256
+ type: t.type || "public-key",
1257
+ transports: t.transports
1258
+ });
1259
+ }
1260
+ }
1261
+ return o;
1262
+ }
1263
+ function ut(e) {
1264
+ if ("toJSON" in e && typeof e.toJSON == "function") return e.toJSON();
1265
+ let t = e;
1266
+ return {
1267
+ id: e.id,
1268
+ rawId: e.id,
1269
+ response: {
1270
+ attestationObject: O(new Uint8Array(e.response.attestationObject)),
1271
+ clientDataJSON: O(new Uint8Array(e.response.clientDataJSON))
1272
+ },
1273
+ type: "public-key",
1274
+ clientExtensionResults: e.getClientExtensionResults(),
1275
+ authenticatorAttachment: t.authenticatorAttachment ?? void 0
1276
+ };
1277
+ }
1278
+ function dt(e) {
1279
+ if ("toJSON" in e && typeof e.toJSON == "function") return e.toJSON();
1280
+ let t = e, n = e.getClientExtensionResults(), r = e.response;
1281
+ return {
1282
+ id: e.id,
1283
+ rawId: e.id,
1284
+ response: {
1285
+ authenticatorData: O(new Uint8Array(r.authenticatorData)),
1286
+ clientDataJSON: O(new Uint8Array(r.clientDataJSON)),
1287
+ signature: O(new Uint8Array(r.signature)),
1288
+ userHandle: r.userHandle ? O(new Uint8Array(r.userHandle)) : void 0
1289
+ },
1290
+ type: "public-key",
1291
+ clientExtensionResults: n,
1292
+ authenticatorAttachment: t.authenticatorAttachment ?? void 0
1293
+ };
1294
+ }
1295
+ function ft(e) {
1296
+ return e === "localhost" || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e);
1297
+ }
1298
+ function pt() {
1299
+ return !!(k() && "PublicKeyCredential" in window && window.PublicKeyCredential && "credentials" in navigator && typeof (navigator == null ? void 0 : navigator.credentials)?.create == "function" && typeof (navigator == null ? void 0 : navigator.credentials)?.get == "function");
1300
+ }
1301
+ async function mt(e) {
1302
+ try {
1303
+ let t = await navigator.credentials.create(e);
1304
+ return t ? t instanceof PublicKeyCredential ? {
1305
+ data: t,
1306
+ error: null
1307
+ } : {
1308
+ data: null,
1309
+ error: new G("Browser returned unexpected credential type", t)
1310
+ } : {
1311
+ data: null,
1312
+ error: new G("Empty credential response", t)
1313
+ };
1314
+ } catch (t) {
1315
+ return {
1316
+ data: null,
1317
+ error: at({
1318
+ error: t,
1319
+ options: e
1320
+ })
1321
+ };
1322
+ }
1323
+ }
1324
+ async function ht(e) {
1325
+ try {
1326
+ let t = await navigator.credentials.get(e);
1327
+ return t ? t instanceof PublicKeyCredential ? {
1328
+ data: t,
1329
+ error: null
1330
+ } : {
1331
+ data: null,
1332
+ error: new G("Browser returned unexpected credential type", t)
1333
+ } : {
1334
+ data: null,
1335
+ error: new G("Empty credential response", t)
1336
+ };
1337
+ } catch (t) {
1338
+ return {
1339
+ data: null,
1340
+ error: ot({
1341
+ error: t,
1342
+ options: e
1343
+ })
1344
+ };
1345
+ }
1346
+ }
1347
+ var gt = {
1348
+ hints: ["security-key"],
1349
+ authenticatorSelection: {
1350
+ authenticatorAttachment: "cross-platform",
1351
+ requireResidentKey: !1,
1352
+ userVerification: "preferred",
1353
+ residentKey: "discouraged"
1354
+ },
1355
+ attestation: "direct"
1356
+ }, _t = {
1357
+ userVerification: "preferred",
1358
+ hints: ["security-key"],
1359
+ attestation: "direct"
1360
+ };
1361
+ function K(...e) {
1362
+ let t = (e) => typeof e == "object" && !!e && !Array.isArray(e), n = (e) => e instanceof ArrayBuffer || ArrayBuffer.isView(e), r = {};
1363
+ for (let i of e) if (i) for (let e in i) {
1364
+ let a = i[e];
1365
+ if (a !== void 0) if (Array.isArray(a)) r[e] = a;
1366
+ else if (n(a)) r[e] = a;
1367
+ else if (t(a)) {
1368
+ let n = r[e];
1369
+ t(n) ? r[e] = K(n, a) : r[e] = K(a);
1370
+ } else r[e] = a;
1371
+ }
1372
+ return r;
1373
+ }
1374
+ function vt(e, t) {
1375
+ return K(gt, e, t || {});
1376
+ }
1377
+ function yt(e, t) {
1378
+ return K(_t, e, t || {});
1379
+ }
1380
+ var bt = class {
1381
+ constructor(e) {
1382
+ this.client = e, this.enroll = this._enroll.bind(this), this.challenge = this._challenge.bind(this), this.verify = this._verify.bind(this), this.authenticate = this._authenticate.bind(this), this.register = this._register.bind(this);
1383
+ }
1384
+ async _enroll(e) {
1385
+ return this.client.mfa.enroll(Object.assign(Object.assign({}, e), { factorType: "webauthn" }));
1386
+ }
1387
+ async _challenge({ factorId: e, webauthn: t, friendlyName: n, signal: r }, i) {
1388
+ try {
1389
+ let { data: a, error: o } = await this.client.mfa.challenge({
1390
+ factorId: e,
1391
+ webauthn: t
1392
+ });
1393
+ if (!a) return {
1394
+ data: null,
1395
+ error: o
1396
+ };
1397
+ let s = r ?? st.createNewAbortSignal();
1398
+ if (a.webauthn.type === "create") {
1399
+ let { user: e } = a.webauthn.credential_options.publicKey;
1400
+ if (!e.name) {
1401
+ let t = n;
1402
+ if (t) e.name = `${e.id}:${t}`;
1403
+ else {
1404
+ let t = (await this.client.getUser()).data.user, n = t?.user_metadata?.name || t?.email || t?.id || "User";
1405
+ e.name = `${e.id}:${n}`;
1406
+ }
1407
+ }
1408
+ e.displayName ||= e.name;
1409
+ }
1410
+ switch (a.webauthn.type) {
1411
+ case "create": {
1412
+ let { data: t, error: n } = await mt({
1413
+ publicKey: vt(a.webauthn.credential_options.publicKey, i?.create),
1414
+ signal: s
1415
+ });
1416
+ return t ? {
1417
+ data: {
1418
+ factorId: e,
1419
+ challengeId: a.id,
1420
+ webauthn: {
1421
+ type: a.webauthn.type,
1422
+ credential_response: t
1423
+ }
1424
+ },
1425
+ error: null
1426
+ } : {
1427
+ data: null,
1428
+ error: n
1429
+ };
1430
+ }
1431
+ case "request": {
1432
+ let t = yt(a.webauthn.credential_options.publicKey, i?.request), { data: n, error: r } = await ht(Object.assign(Object.assign({}, a.webauthn.credential_options), {
1433
+ publicKey: t,
1434
+ signal: s
1435
+ }));
1436
+ return n ? {
1437
+ data: {
1438
+ factorId: e,
1439
+ challengeId: a.id,
1440
+ webauthn: {
1441
+ type: a.webauthn.type,
1442
+ credential_response: n
1443
+ }
1444
+ },
1445
+ error: null
1446
+ } : {
1447
+ data: null,
1448
+ error: r
1449
+ };
1450
+ }
1451
+ }
1452
+ } catch (e) {
1453
+ return v(e) ? {
1454
+ data: null,
1455
+ error: e
1456
+ } : {
1457
+ data: null,
1458
+ error: new y("Unexpected error in challenge", e)
1459
+ };
1460
+ }
1461
+ }
1462
+ async _verify({ challengeId: e, factorId: t, webauthn: n }) {
1463
+ return this.client.mfa.verify({
1464
+ factorId: t,
1465
+ challengeId: e,
1466
+ webauthn: n
1467
+ });
1468
+ }
1469
+ async _authenticate({ factorId: e, webauthn: { rpId: t = typeof window < "u" ? window.location.hostname : void 0, rpOrigins: n = typeof window < "u" ? [window.location.origin] : void 0, signal: r } = {} }, i) {
1470
+ if (!t) return {
1471
+ data: null,
1472
+ error: new _("rpId is required for WebAuthn authentication")
1473
+ };
1474
+ try {
1475
+ if (!pt()) return {
1476
+ data: null,
1477
+ error: new y("Browser does not support WebAuthn", null)
1478
+ };
1479
+ let { data: a, error: o } = await this.challenge({
1480
+ factorId: e,
1481
+ webauthn: {
1482
+ rpId: t,
1483
+ rpOrigins: n
1484
+ },
1485
+ signal: r
1486
+ }, { request: i });
1487
+ if (!a) return {
1488
+ data: null,
1489
+ error: o
1490
+ };
1491
+ let { webauthn: s } = a;
1492
+ return this._verify({
1493
+ factorId: e,
1494
+ challengeId: a.challengeId,
1495
+ webauthn: {
1496
+ type: s.type,
1497
+ rpId: t,
1498
+ rpOrigins: n,
1499
+ credential_response: s.credential_response
1500
+ }
1501
+ });
1502
+ } catch (e) {
1503
+ return v(e) ? {
1504
+ data: null,
1505
+ error: e
1506
+ } : {
1507
+ data: null,
1508
+ error: new y("Unexpected error in authenticate", e)
1509
+ };
1510
+ }
1511
+ }
1512
+ async _register({ friendlyName: e, webauthn: { rpId: t = typeof window < "u" ? window.location.hostname : void 0, rpOrigins: n = typeof window < "u" ? [window.location.origin] : void 0, signal: r } = {} }, i) {
1513
+ if (!t) return {
1514
+ data: null,
1515
+ error: new _("rpId is required for WebAuthn registration")
1516
+ };
1517
+ try {
1518
+ if (!pt()) return {
1519
+ data: null,
1520
+ error: new y("Browser does not support WebAuthn", null)
1521
+ };
1522
+ let { data: a, error: o } = await this._enroll({ friendlyName: e });
1523
+ if (!a) return await this.client.mfa.listFactors().then((t) => t.data?.all.find((t) => t.factor_type === "webauthn" && t.friendly_name === e && t.status !== "unverified")).then((e) => e ? this.client.mfa.unenroll({ factorId: e?.id }) : void 0), {
1524
+ data: null,
1525
+ error: o
1526
+ };
1527
+ let { data: s, error: c } = await this._challenge({
1528
+ factorId: a.id,
1529
+ friendlyName: a.friendly_name,
1530
+ webauthn: {
1531
+ rpId: t,
1532
+ rpOrigins: n
1533
+ },
1534
+ signal: r
1535
+ }, { create: i });
1536
+ return s ? this._verify({
1537
+ factorId: a.id,
1538
+ challengeId: s.challengeId,
1539
+ webauthn: {
1540
+ rpId: t,
1541
+ rpOrigins: n,
1542
+ type: s.webauthn.type,
1543
+ credential_response: s.webauthn.credential_response
1544
+ }
1545
+ }) : {
1546
+ data: null,
1547
+ error: c
1548
+ };
1549
+ } catch (e) {
1550
+ return v(e) ? {
1551
+ data: null,
1552
+ error: e
1553
+ } : {
1554
+ data: null,
1555
+ error: new y("Unexpected error in register", e)
1556
+ };
1557
+ }
1558
+ }
1559
+ };
1560
+ //#endregion
1561
+ //#region node_modules/@supabase/auth-js/dist/module/GoTrueClient.js
1562
+ et();
1563
+ var xt = {
1564
+ url: p,
1565
+ storageKey: m,
1566
+ autoRefreshToken: !0,
1567
+ persistSession: !0,
1568
+ detectSessionInUrl: !0,
1569
+ headers: h,
1570
+ flowType: "implicit",
1571
+ debug: !1,
1572
+ hasCustomAuthorizationHeader: !1,
1573
+ throwOnError: !1,
1574
+ lockAcquireTimeout: 5e3,
1575
+ skipAutoInitialize: !1
1576
+ };
1577
+ async function St(e, t, n) {
1578
+ return await n();
1579
+ }
1580
+ var q = {}, Ct = class e {
1581
+ get jwks() {
1582
+ return q[this.storageKey]?.jwks ?? { keys: [] };
1583
+ }
1584
+ set jwks(e) {
1585
+ q[this.storageKey] = Object.assign(Object.assign({}, q[this.storageKey]), { jwks: e });
1586
+ }
1587
+ get jwks_cached_at() {
1588
+ return q[this.storageKey]?.cachedAt ?? -(2 ** 53 - 1);
1589
+ }
1590
+ set jwks_cached_at(e) {
1591
+ q[this.storageKey] = Object.assign(Object.assign({}, q[this.storageKey]), { cachedAt: e });
1592
+ }
1593
+ constructor(t) {
1594
+ var n;
1595
+ this.userStorage = null, this.memoryStorage = null, this.stateChangeEmitters = /* @__PURE__ */ new Map(), this.autoRefreshTicker = null, this.autoRefreshTickTimeout = null, this.visibilityChangedCallback = null, this.refreshingDeferred = null, this.initializePromise = null, this.detectSessionInUrl = !0, this.hasCustomAuthorizationHeader = !1, this.suppressGetSessionWarning = !1, this.lockAcquired = !1, this.pendingInLock = [], this.broadcastChannel = null, this.logger = console.log;
1596
+ let r = Object.assign(Object.assign({}, xt), t);
1597
+ if (this.storageKey = r.storageKey, this.instanceID = e.nextInstanceID[this.storageKey] ?? 0, e.nextInstanceID[this.storageKey] = this.instanceID + 1, this.logDebugMessages = !!r.debug, typeof r.debug == "function" && (this.logger = r.debug), this.instanceID > 0 && k()) {
1598
+ let e = `${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;
1599
+ console.warn(e), this.logDebugMessages && console.trace(e);
1600
+ }
1601
+ if (this.persistSession = r.persistSession, this.autoRefreshToken = r.autoRefreshToken, this.admin = new Ye({
1602
+ url: r.url,
1603
+ headers: r.headers,
1604
+ fetch: r.fetch
1605
+ }), this.url = r.url, this.headers = r.headers, this.fetch = we(r.fetch), this.lock = r.lock || St, this.detectSessionInUrl = r.detectSessionInUrl, this.flowType = r.flowType, this.hasCustomAuthorizationHeader = r.hasCustomAuthorizationHeader, this.throwOnError = r.throwOnError, this.lockAcquireTimeout = r.lockAcquireTimeout, r.lock ? this.lock = r.lock : this.persistSession && k() && (globalThis == null ? void 0 : globalThis.navigator)?.locks ? this.lock = $e : this.lock = St, this.jwks || (this.jwks = { keys: [] }, this.jwks_cached_at = -(2 ** 53 - 1)), this.mfa = {
1606
+ verify: this._verify.bind(this),
1607
+ enroll: this._enroll.bind(this),
1608
+ unenroll: this._unenroll.bind(this),
1609
+ challenge: this._challenge.bind(this),
1610
+ listFactors: this._listFactors.bind(this),
1611
+ challengeAndVerify: this._challengeAndVerify.bind(this),
1612
+ getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this),
1613
+ webauthn: new bt(this)
1614
+ }, this.oauth = {
1615
+ getAuthorizationDetails: this._getAuthorizationDetails.bind(this),
1616
+ approveAuthorization: this._approveAuthorization.bind(this),
1617
+ denyAuthorization: this._denyAuthorization.bind(this),
1618
+ listGrants: this._listOAuthGrants.bind(this),
1619
+ revokeGrant: this._revokeOAuthGrant.bind(this)
1620
+ }, this.persistSession ? (r.storage ? this.storage = r.storage : Se() ? this.storage = globalThis.localStorage : (this.memoryStorage = {}, this.storage = Xe(this.memoryStorage)), r.userStorage && (this.userStorage = r.userStorage)) : (this.memoryStorage = {}, this.storage = Xe(this.memoryStorage)), k() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) {
1621
+ try {
1622
+ this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey);
1623
+ } catch (e) {
1624
+ console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available", e);
1625
+ }
1626
+ (n = this.broadcastChannel) == null || n.addEventListener("message", async (e) => {
1627
+ this._debug("received broadcast notification from other tab or client", e);
1628
+ try {
1629
+ await this._notifyAllSubscribers(e.data.event, e.data.session, !1);
1630
+ } catch (e) {
1631
+ this._debug("#broadcastChannel", "error", e);
1632
+ }
1633
+ });
1634
+ }
1635
+ r.skipAutoInitialize || this.initialize().catch((e) => {
1636
+ this._debug("#initialize()", "error", e);
1637
+ });
1638
+ }
1639
+ isThrowOnErrorEnabled() {
1640
+ return this.throwOnError;
1641
+ }
1642
+ _returnResult(e) {
1643
+ if (this.throwOnError && e && e.error) throw e.error;
1644
+ return e;
1645
+ }
1646
+ _logPrefix() {
1647
+ return `GoTrueClient@${this.storageKey}:${this.instanceID} (${u}) ${(/* @__PURE__ */ new Date()).toISOString()}`;
1648
+ }
1649
+ _debug(...e) {
1650
+ return this.logDebugMessages && this.logger(this._logPrefix(), ...e), this;
1651
+ }
1652
+ async initialize() {
1653
+ return this.initializePromise ||= (async () => await this._acquireLock(this.lockAcquireTimeout, async () => await this._initialize()))(), await this.initializePromise;
1654
+ }
1655
+ async _initialize() {
1656
+ try {
1657
+ let e = {}, t = "none";
1658
+ if (k() && (e = Ce(window.location.href), this._isImplicitGrantCallback(e) ? t = "implicit" : await this._isPKCECallback(e) && (t = "pkce")), k() && this.detectSessionInUrl && t !== "none") {
1659
+ let { data: n, error: r } = await this._getSessionFromURL(e, t);
1660
+ if (r) {
1661
+ if (this._debug("#_initialize()", "error detecting session from URL", r), ie(r)) {
1662
+ let e = r.details?.code;
1663
+ if (e === "identity_already_exists" || e === "identity_not_found" || e === "single_identity_not_deletable") return { error: r };
1664
+ }
1665
+ return { error: r };
1666
+ }
1667
+ let { session: i, redirectType: a } = n;
1668
+ return this._debug("#_initialize()", "detected session in URL", i, "redirect type", a), await this._saveSession(i), setTimeout(async () => {
1669
+ a === "recovery" ? await this._notifyAllSubscribers("PASSWORD_RECOVERY", i) : await this._notifyAllSubscribers("SIGNED_IN", i);
1670
+ }, 0), { error: null };
1671
+ }
1672
+ return await this._recoverAndRefresh(), { error: null };
1673
+ } catch (e) {
1674
+ return v(e) ? this._returnResult({ error: e }) : this._returnResult({ error: new y("Unexpected error during initialization", e) });
1675
+ } finally {
1676
+ await this._handleVisibilityChange(), this._debug("#_initialize()", "end");
1677
+ }
1678
+ }
1679
+ async signInAnonymously(e) {
1680
+ try {
1681
+ let { data: t, error: n } = await z(this.fetch, "POST", `${this.url}/signup`, {
1682
+ headers: this.headers,
1683
+ body: {
1684
+ data: e?.options?.data ?? {},
1685
+ gotrue_meta_security: { captcha_token: e?.options?.captchaToken }
1686
+ },
1687
+ xform: B
1688
+ });
1689
+ if (n || !t) return this._returnResult({
1690
+ data: {
1691
+ user: null,
1692
+ session: null
1693
+ },
1694
+ error: n
1695
+ });
1696
+ let r = t.session, i = t.user;
1697
+ return t.session && (await this._saveSession(t.session), await this._notifyAllSubscribers("SIGNED_IN", r)), this._returnResult({
1698
+ data: {
1699
+ user: i,
1700
+ session: r
1701
+ },
1702
+ error: null
1703
+ });
1704
+ } catch (e) {
1705
+ if (v(e)) return this._returnResult({
1706
+ data: {
1707
+ user: null,
1708
+ session: null
1709
+ },
1710
+ error: e
1711
+ });
1712
+ throw e;
1713
+ }
1714
+ }
1715
+ async signUp(e) {
1716
+ try {
1717
+ let t;
1718
+ if ("email" in e) {
1719
+ let { email: n, password: r, options: i } = e, a = null, o = null;
1720
+ this.flowType === "pkce" && ([a, o] = await F(this.storage, this.storageKey)), t = await z(this.fetch, "POST", `${this.url}/signup`, {
1721
+ headers: this.headers,
1722
+ redirectTo: i?.emailRedirectTo,
1723
+ body: {
1724
+ email: n,
1725
+ password: r,
1726
+ data: i?.data ?? {},
1727
+ gotrue_meta_security: { captcha_token: i?.captchaToken },
1728
+ code_challenge: a,
1729
+ code_challenge_method: o
1730
+ },
1731
+ xform: B
1732
+ });
1733
+ } else if ("phone" in e) {
1734
+ let { phone: n, password: r, options: i } = e;
1735
+ t = await z(this.fetch, "POST", `${this.url}/signup`, {
1736
+ headers: this.headers,
1737
+ body: {
1738
+ phone: n,
1739
+ password: r,
1740
+ data: i?.data ?? {},
1741
+ channel: i?.channel ?? "sms",
1742
+ gotrue_meta_security: { captcha_token: i?.captchaToken }
1743
+ },
1744
+ xform: B
1745
+ });
1746
+ } else throw new w("You must provide either an email or phone number and a password");
1747
+ let { data: n, error: r } = t;
1748
+ if (r || !n) return await N(this.storage, `${this.storageKey}-code-verifier`), this._returnResult({
1749
+ data: {
1750
+ user: null,
1751
+ session: null
1752
+ },
1753
+ error: r
1754
+ });
1755
+ let i = n.session, a = n.user;
1756
+ return n.session && (await this._saveSession(n.session), await this._notifyAllSubscribers("SIGNED_IN", i)), this._returnResult({
1757
+ data: {
1758
+ user: a,
1759
+ session: i
1760
+ },
1761
+ error: null
1762
+ });
1763
+ } catch (e) {
1764
+ if (await N(this.storage, `${this.storageKey}-code-verifier`), v(e)) return this._returnResult({
1765
+ data: {
1766
+ user: null,
1767
+ session: null
1768
+ },
1769
+ error: e
1770
+ });
1771
+ throw e;
1772
+ }
1773
+ }
1774
+ async signInWithPassword(e) {
1775
+ try {
1776
+ let t;
1777
+ if ("email" in e) {
1778
+ let { email: n, password: r, options: i } = e;
1779
+ t = await z(this.fetch, "POST", `${this.url}/token?grant_type=password`, {
1780
+ headers: this.headers,
1781
+ body: {
1782
+ email: n,
1783
+ password: r,
1784
+ gotrue_meta_security: { captcha_token: i?.captchaToken }
1785
+ },
1786
+ xform: We
1787
+ });
1788
+ } else if ("phone" in e) {
1789
+ let { phone: n, password: r, options: i } = e;
1790
+ t = await z(this.fetch, "POST", `${this.url}/token?grant_type=password`, {
1791
+ headers: this.headers,
1792
+ body: {
1793
+ phone: n,
1794
+ password: r,
1795
+ gotrue_meta_security: { captcha_token: i?.captchaToken }
1796
+ },
1797
+ xform: We
1798
+ });
1799
+ } else throw new w("You must provide either an email or phone number and a password");
1800
+ let { data: n, error: r } = t;
1801
+ if (r) return this._returnResult({
1802
+ data: {
1803
+ user: null,
1804
+ session: null
1805
+ },
1806
+ error: r
1807
+ });
1808
+ if (!n || !n.session || !n.user) {
1809
+ let e = new C();
1810
+ return this._returnResult({
1811
+ data: {
1812
+ user: null,
1813
+ session: null
1814
+ },
1815
+ error: e
1816
+ });
1817
+ }
1818
+ return n.session && (await this._saveSession(n.session), await this._notifyAllSubscribers("SIGNED_IN", n.session)), this._returnResult({
1819
+ data: Object.assign({
1820
+ user: n.user,
1821
+ session: n.session
1822
+ }, n.weak_password ? { weakPassword: n.weak_password } : null),
1823
+ error: r
1824
+ });
1825
+ } catch (e) {
1826
+ if (v(e)) return this._returnResult({
1827
+ data: {
1828
+ user: null,
1829
+ session: null
1830
+ },
1831
+ error: e
1832
+ });
1833
+ throw e;
1834
+ }
1835
+ }
1836
+ async signInWithOAuth(e) {
1837
+ return await this._handleProviderSignIn(e.provider, {
1838
+ redirectTo: e.options?.redirectTo,
1839
+ scopes: e.options?.scopes,
1840
+ queryParams: e.options?.queryParams,
1841
+ skipBrowserRedirect: e.options?.skipBrowserRedirect
1842
+ });
1843
+ }
1844
+ async exchangeCodeForSession(e) {
1845
+ return await this.initializePromise, this._acquireLock(this.lockAcquireTimeout, async () => this._exchangeCodeForSession(e));
1846
+ }
1847
+ async signInWithWeb3(e) {
1848
+ let { chain: t } = e;
1849
+ switch (t) {
1850
+ case "ethereum": return await this.signInWithEthereum(e);
1851
+ case "solana": return await this.signInWithSolana(e);
1852
+ default: throw Error(`@supabase/auth-js: Unsupported chain "${t}"`);
1853
+ }
1854
+ }
1855
+ async signInWithEthereum(e) {
1856
+ let t, n;
1857
+ if ("message" in e) t = e.message, n = e.signature;
1858
+ else {
1859
+ let { chain: r, wallet: i, statement: a, options: o } = e, s;
1860
+ if (!k()) {
1861
+ if (typeof i != "object" || !o?.url) throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");
1862
+ s = i;
1863
+ } else if (typeof i == "object") s = i;
1864
+ else {
1865
+ let e = window;
1866
+ if ("ethereum" in e && typeof e.ethereum == "object" && "request" in e.ethereum && typeof e.ethereum.request == "function") s = e.ethereum;
1867
+ else throw Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.");
1868
+ }
1869
+ let c = new URL(o?.url ?? window.location.href), l = await s.request({ method: "eth_requestAccounts" }).then((e) => e).catch(() => {
1870
+ throw Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid");
1871
+ });
1872
+ if (!l || l.length === 0) throw Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");
1873
+ let u = tt(l[0]), d = o?.signInWithEthereum?.chainId;
1874
+ d ||= nt(await s.request({ method: "eth_chainId" })), t = it({
1875
+ domain: c.host,
1876
+ address: u,
1877
+ statement: a,
1878
+ uri: c.href,
1879
+ version: "1",
1880
+ chainId: d,
1881
+ nonce: o?.signInWithEthereum?.nonce,
1882
+ issuedAt: o?.signInWithEthereum?.issuedAt ?? /* @__PURE__ */ new Date(),
1883
+ expirationTime: o?.signInWithEthereum?.expirationTime,
1884
+ notBefore: o?.signInWithEthereum?.notBefore,
1885
+ requestId: o?.signInWithEthereum?.requestId,
1886
+ resources: o?.signInWithEthereum?.resources
1887
+ }), n = await s.request({
1888
+ method: "personal_sign",
1889
+ params: [rt(t), u]
1890
+ });
1891
+ }
1892
+ try {
1893
+ let { data: r, error: i } = await z(this.fetch, "POST", `${this.url}/token?grant_type=web3`, {
1894
+ headers: this.headers,
1895
+ body: Object.assign({
1896
+ chain: "ethereum",
1897
+ message: t,
1898
+ signature: n
1899
+ }, e.options?.captchaToken ? { gotrue_meta_security: { captcha_token: e.options?.captchaToken } } : null),
1900
+ xform: B
1901
+ });
1902
+ if (i) throw i;
1903
+ if (!r || !r.session || !r.user) {
1904
+ let e = new C();
1905
+ return this._returnResult({
1906
+ data: {
1907
+ user: null,
1908
+ session: null
1909
+ },
1910
+ error: e
1911
+ });
1912
+ }
1913
+ return r.session && (await this._saveSession(r.session), await this._notifyAllSubscribers("SIGNED_IN", r.session)), this._returnResult({
1914
+ data: Object.assign({}, r),
1915
+ error: i
1916
+ });
1917
+ } catch (e) {
1918
+ if (v(e)) return this._returnResult({
1919
+ data: {
1920
+ user: null,
1921
+ session: null
1922
+ },
1923
+ error: e
1924
+ });
1925
+ throw e;
1926
+ }
1927
+ }
1928
+ async signInWithSolana(e) {
1929
+ let t, n;
1930
+ if ("message" in e) t = e.message, n = e.signature;
1931
+ else {
1932
+ let { chain: r, wallet: i, statement: a, options: o } = e, s;
1933
+ if (!k()) {
1934
+ if (typeof i != "object" || !o?.url) throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");
1935
+ s = i;
1936
+ } else if (typeof i == "object") s = i;
1937
+ else {
1938
+ let e = window;
1939
+ if ("solana" in e && typeof e.solana == "object" && ("signIn" in e.solana && typeof e.solana.signIn == "function" || "signMessage" in e.solana && typeof e.solana.signMessage == "function")) s = e.solana;
1940
+ else throw Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.");
1941
+ }
1942
+ let c = new URL(o?.url ?? window.location.href);
1943
+ if ("signIn" in s && s.signIn) {
1944
+ let e = await s.signIn(Object.assign(Object.assign(Object.assign({ issuedAt: (/* @__PURE__ */ new Date()).toISOString() }, o?.signInWithSolana), {
1945
+ version: "1",
1946
+ domain: c.host,
1947
+ uri: c.href
1948
+ }), a ? { statement: a } : null)), r;
1949
+ if (Array.isArray(e) && e[0] && typeof e[0] == "object") r = e[0];
1950
+ else if (e && typeof e == "object" && "signedMessage" in e && "signature" in e) r = e;
1951
+ else throw Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");
1952
+ if ("signedMessage" in r && "signature" in r && (typeof r.signedMessage == "string" || r.signedMessage instanceof Uint8Array) && r.signature instanceof Uint8Array) t = typeof r.signedMessage == "string" ? r.signedMessage : new TextDecoder().decode(r.signedMessage), n = r.signature;
1953
+ else throw Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields");
1954
+ } else {
1955
+ if (!("signMessage" in s) || typeof s.signMessage != "function" || !("publicKey" in s) || typeof s != "object" || !s.publicKey || !("toBase58" in s.publicKey) || typeof s.publicKey.toBase58 != "function") throw Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");
1956
+ t = [
1957
+ `${c.host} wants you to sign in with your Solana account:`,
1958
+ s.publicKey.toBase58(),
1959
+ ...a ? [
1960
+ "",
1961
+ a,
1962
+ ""
1963
+ ] : [""],
1964
+ "Version: 1",
1965
+ `URI: ${c.href}`,
1966
+ `Issued At: ${o?.signInWithSolana?.issuedAt ?? (/* @__PURE__ */ new Date()).toISOString()}`,
1967
+ ...o?.signInWithSolana?.notBefore ? [`Not Before: ${o.signInWithSolana.notBefore}`] : [],
1968
+ ...o?.signInWithSolana?.expirationTime ? [`Expiration Time: ${o.signInWithSolana.expirationTime}`] : [],
1969
+ ...o?.signInWithSolana?.chainId ? [`Chain ID: ${o.signInWithSolana.chainId}`] : [],
1970
+ ...o?.signInWithSolana?.nonce ? [`Nonce: ${o.signInWithSolana.nonce}`] : [],
1971
+ ...o?.signInWithSolana?.requestId ? [`Request ID: ${o.signInWithSolana.requestId}`] : [],
1972
+ ...o?.signInWithSolana?.resources?.length ? ["Resources", ...o.signInWithSolana.resources.map((e) => `- ${e}`)] : []
1973
+ ].join("\n");
1974
+ let e = await s.signMessage(new TextEncoder().encode(t), "utf8");
1975
+ if (!e || !(e instanceof Uint8Array)) throw Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");
1976
+ n = e;
1977
+ }
1978
+ }
1979
+ try {
1980
+ let { data: r, error: i } = await z(this.fetch, "POST", `${this.url}/token?grant_type=web3`, {
1981
+ headers: this.headers,
1982
+ body: Object.assign({
1983
+ chain: "solana",
1984
+ message: t,
1985
+ signature: O(n)
1986
+ }, e.options?.captchaToken ? { gotrue_meta_security: { captcha_token: e.options?.captchaToken } } : null),
1987
+ xform: B
1988
+ });
1989
+ if (i) throw i;
1990
+ if (!r || !r.session || !r.user) {
1991
+ let e = new C();
1992
+ return this._returnResult({
1993
+ data: {
1994
+ user: null,
1995
+ session: null
1996
+ },
1997
+ error: e
1998
+ });
1999
+ }
2000
+ return r.session && (await this._saveSession(r.session), await this._notifyAllSubscribers("SIGNED_IN", r.session)), this._returnResult({
2001
+ data: Object.assign({}, r),
2002
+ error: i
2003
+ });
2004
+ } catch (e) {
2005
+ if (v(e)) return this._returnResult({
2006
+ data: {
2007
+ user: null,
2008
+ session: null
2009
+ },
2010
+ error: e
2011
+ });
2012
+ throw e;
2013
+ }
2014
+ }
2015
+ async _exchangeCodeForSession(e) {
2016
+ let [t, n] = (await M(this.storage, `${this.storageKey}-code-verifier`) ?? "").split("/");
2017
+ try {
2018
+ if (!t && this.flowType === "pkce") throw new oe();
2019
+ let { data: r, error: i } = await z(this.fetch, "POST", `${this.url}/token?grant_type=pkce`, {
2020
+ headers: this.headers,
2021
+ body: {
2022
+ auth_code: e,
2023
+ code_verifier: t
2024
+ },
2025
+ xform: B
2026
+ });
2027
+ if (await N(this.storage, `${this.storageKey}-code-verifier`), i) throw i;
2028
+ if (!r || !r.session || !r.user) {
2029
+ let e = new C();
2030
+ return this._returnResult({
2031
+ data: {
2032
+ user: null,
2033
+ session: null,
2034
+ redirectType: null
2035
+ },
2036
+ error: e
2037
+ });
2038
+ }
2039
+ return r.session && (await this._saveSession(r.session), await this._notifyAllSubscribers("SIGNED_IN", r.session)), this._returnResult({
2040
+ data: Object.assign(Object.assign({}, r), { redirectType: n ?? null }),
2041
+ error: i
2042
+ });
2043
+ } catch (e) {
2044
+ if (await N(this.storage, `${this.storageKey}-code-verifier`), v(e)) return this._returnResult({
2045
+ data: {
2046
+ user: null,
2047
+ session: null,
2048
+ redirectType: null
2049
+ },
2050
+ error: e
2051
+ });
2052
+ throw e;
2053
+ }
2054
+ }
2055
+ async signInWithIdToken(e) {
2056
+ try {
2057
+ let { options: t, provider: n, token: r, access_token: i, nonce: a } = e, { data: o, error: s } = await z(this.fetch, "POST", `${this.url}/token?grant_type=id_token`, {
2058
+ headers: this.headers,
2059
+ body: {
2060
+ provider: n,
2061
+ id_token: r,
2062
+ access_token: i,
2063
+ nonce: a,
2064
+ gotrue_meta_security: { captcha_token: t?.captchaToken }
2065
+ },
2066
+ xform: B
2067
+ });
2068
+ if (s) return this._returnResult({
2069
+ data: {
2070
+ user: null,
2071
+ session: null
2072
+ },
2073
+ error: s
2074
+ });
2075
+ if (!o || !o.session || !o.user) {
2076
+ let e = new C();
2077
+ return this._returnResult({
2078
+ data: {
2079
+ user: null,
2080
+ session: null
2081
+ },
2082
+ error: e
2083
+ });
2084
+ }
2085
+ return o.session && (await this._saveSession(o.session), await this._notifyAllSubscribers("SIGNED_IN", o.session)), this._returnResult({
2086
+ data: o,
2087
+ error: s
2088
+ });
2089
+ } catch (e) {
2090
+ if (v(e)) return this._returnResult({
2091
+ data: {
2092
+ user: null,
2093
+ session: null
2094
+ },
2095
+ error: e
2096
+ });
2097
+ throw e;
2098
+ }
2099
+ }
2100
+ async signInWithOtp(e) {
2101
+ try {
2102
+ if ("email" in e) {
2103
+ let { email: t, options: n } = e, r = null, i = null;
2104
+ this.flowType === "pkce" && ([r, i] = await F(this.storage, this.storageKey));
2105
+ let { error: a } = await z(this.fetch, "POST", `${this.url}/otp`, {
2106
+ headers: this.headers,
2107
+ body: {
2108
+ email: t,
2109
+ data: n?.data ?? {},
2110
+ create_user: n?.shouldCreateUser ?? !0,
2111
+ gotrue_meta_security: { captcha_token: n?.captchaToken },
2112
+ code_challenge: r,
2113
+ code_challenge_method: i
2114
+ },
2115
+ redirectTo: n?.emailRedirectTo
2116
+ });
2117
+ return this._returnResult({
2118
+ data: {
2119
+ user: null,
2120
+ session: null
2121
+ },
2122
+ error: a
2123
+ });
2124
+ }
2125
+ if ("phone" in e) {
2126
+ let { phone: t, options: n } = e, { data: r, error: i } = await z(this.fetch, "POST", `${this.url}/otp`, {
2127
+ headers: this.headers,
2128
+ body: {
2129
+ phone: t,
2130
+ data: n?.data ?? {},
2131
+ create_user: n?.shouldCreateUser ?? !0,
2132
+ gotrue_meta_security: { captcha_token: n?.captchaToken },
2133
+ channel: n?.channel ?? "sms"
2134
+ }
2135
+ });
2136
+ return this._returnResult({
2137
+ data: {
2138
+ user: null,
2139
+ session: null,
2140
+ messageId: r?.message_id
2141
+ },
2142
+ error: i
2143
+ });
2144
+ }
2145
+ throw new w("You must provide either an email or phone number.");
2146
+ } catch (e) {
2147
+ if (await N(this.storage, `${this.storageKey}-code-verifier`), v(e)) return this._returnResult({
2148
+ data: {
2149
+ user: null,
2150
+ session: null
2151
+ },
2152
+ error: e
2153
+ });
2154
+ throw e;
2155
+ }
2156
+ }
2157
+ async verifyOtp(e) {
2158
+ try {
2159
+ let t, n;
2160
+ "options" in e && (t = e.options?.redirectTo, n = e.options?.captchaToken);
2161
+ let { data: r, error: i } = await z(this.fetch, "POST", `${this.url}/verify`, {
2162
+ headers: this.headers,
2163
+ body: Object.assign(Object.assign({}, e), { gotrue_meta_security: { captcha_token: n } }),
2164
+ redirectTo: t,
2165
+ xform: B
2166
+ });
2167
+ if (i) throw i;
2168
+ if (!r) throw /* @__PURE__ */ Error("An error occurred on token verification.");
2169
+ let a = r.session, o = r.user;
2170
+ return a?.access_token && (await this._saveSession(a), await this._notifyAllSubscribers(e.type == "recovery" ? "PASSWORD_RECOVERY" : "SIGNED_IN", a)), this._returnResult({
2171
+ data: {
2172
+ user: o,
2173
+ session: a
2174
+ },
2175
+ error: null
2176
+ });
2177
+ } catch (e) {
2178
+ if (v(e)) return this._returnResult({
2179
+ data: {
2180
+ user: null,
2181
+ session: null
2182
+ },
2183
+ error: e
2184
+ });
2185
+ throw e;
2186
+ }
2187
+ }
2188
+ async signInWithSSO(e) {
2189
+ try {
2190
+ let t = null, n = null;
2191
+ this.flowType === "pkce" && ([t, n] = await F(this.storage, this.storageKey));
2192
+ let r = await z(this.fetch, "POST", `${this.url}/sso`, {
2193
+ body: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, "providerId" in e ? { provider_id: e.providerId } : null), "domain" in e ? { domain: e.domain } : null), { redirect_to: e.options?.redirectTo ?? void 0 }), e?.options?.captchaToken ? { gotrue_meta_security: { captcha_token: e.options.captchaToken } } : null), {
2194
+ skip_http_redirect: !0,
2195
+ code_challenge: t,
2196
+ code_challenge_method: n
2197
+ }),
2198
+ headers: this.headers,
2199
+ xform: Ge
2200
+ });
2201
+ return r.data?.url && k() && !e.options?.skipBrowserRedirect && window.location.assign(r.data.url), this._returnResult(r);
2202
+ } catch (e) {
2203
+ if (await N(this.storage, `${this.storageKey}-code-verifier`), v(e)) return this._returnResult({
2204
+ data: null,
2205
+ error: e
2206
+ });
2207
+ throw e;
2208
+ }
2209
+ }
2210
+ async reauthenticate() {
2211
+ return await this.initializePromise, await this._acquireLock(this.lockAcquireTimeout, async () => await this._reauthenticate());
2212
+ }
2213
+ async _reauthenticate() {
2214
+ try {
2215
+ return await this._useSession(async (e) => {
2216
+ let { data: { session: t }, error: n } = e;
2217
+ if (n) throw n;
2218
+ if (!t) throw new x();
2219
+ let { error: r } = await z(this.fetch, "GET", `${this.url}/reauthenticate`, {
2220
+ headers: this.headers,
2221
+ jwt: t.access_token
2222
+ });
2223
+ return this._returnResult({
2224
+ data: {
2225
+ user: null,
2226
+ session: null
2227
+ },
2228
+ error: r
2229
+ });
2230
+ });
2231
+ } catch (e) {
2232
+ if (v(e)) return this._returnResult({
2233
+ data: {
2234
+ user: null,
2235
+ session: null
2236
+ },
2237
+ error: e
2238
+ });
2239
+ throw e;
2240
+ }
2241
+ }
2242
+ async resend(e) {
2243
+ try {
2244
+ let t = `${this.url}/resend`;
2245
+ if ("email" in e) {
2246
+ let { email: n, type: r, options: i } = e, { error: a } = await z(this.fetch, "POST", t, {
2247
+ headers: this.headers,
2248
+ body: {
2249
+ email: n,
2250
+ type: r,
2251
+ gotrue_meta_security: { captcha_token: i?.captchaToken }
2252
+ },
2253
+ redirectTo: i?.emailRedirectTo
2254
+ });
2255
+ return this._returnResult({
2256
+ data: {
2257
+ user: null,
2258
+ session: null
2259
+ },
2260
+ error: a
2261
+ });
2262
+ } else if ("phone" in e) {
2263
+ let { phone: n, type: r, options: i } = e, { data: a, error: o } = await z(this.fetch, "POST", t, {
2264
+ headers: this.headers,
2265
+ body: {
2266
+ phone: n,
2267
+ type: r,
2268
+ gotrue_meta_security: { captcha_token: i?.captchaToken }
2269
+ }
2270
+ });
2271
+ return this._returnResult({
2272
+ data: {
2273
+ user: null,
2274
+ session: null,
2275
+ messageId: a?.message_id
2276
+ },
2277
+ error: o
2278
+ });
2279
+ }
2280
+ throw new w("You must provide either an email or phone number and a type");
2281
+ } catch (e) {
2282
+ if (v(e)) return this._returnResult({
2283
+ data: {
2284
+ user: null,
2285
+ session: null
2286
+ },
2287
+ error: e
2288
+ });
2289
+ throw e;
2290
+ }
2291
+ }
2292
+ async getSession() {
2293
+ return await this.initializePromise, await this._acquireLock(this.lockAcquireTimeout, async () => this._useSession(async (e) => e));
2294
+ }
2295
+ async _acquireLock(e, t) {
2296
+ this._debug("#_acquireLock", "begin", e);
2297
+ try {
2298
+ if (this.lockAcquired) {
2299
+ let e = this.pendingInLock.length ? this.pendingInLock[this.pendingInLock.length - 1] : Promise.resolve(), n = (async () => (await e, await t()))();
2300
+ return this.pendingInLock.push((async () => {
2301
+ try {
2302
+ await n;
2303
+ } catch {}
2304
+ })()), n;
2305
+ }
2306
+ return await this.lock(`lock:${this.storageKey}`, e, async () => {
2307
+ this._debug("#_acquireLock", "lock acquired for storage key", this.storageKey);
2308
+ try {
2309
+ this.lockAcquired = !0;
2310
+ let e = t();
2311
+ for (this.pendingInLock.push((async () => {
2312
+ try {
2313
+ await e;
2314
+ } catch {}
2315
+ })()), await e; this.pendingInLock.length;) {
2316
+ let e = [...this.pendingInLock];
2317
+ await Promise.all(e), this.pendingInLock.splice(0, e.length);
2318
+ }
2319
+ return await e;
2320
+ } finally {
2321
+ this._debug("#_acquireLock", "lock released for storage key", this.storageKey), this.lockAcquired = !1;
2322
+ }
2323
+ });
2324
+ } finally {
2325
+ this._debug("#_acquireLock", "end");
2326
+ }
2327
+ }
2328
+ async _useSession(e) {
2329
+ this._debug("#_useSession", "begin");
2330
+ try {
2331
+ return await e(await this.__loadSession());
2332
+ } finally {
2333
+ this._debug("#_useSession", "end");
2334
+ }
2335
+ }
2336
+ async __loadSession() {
2337
+ this._debug("#__loadSession()", "begin"), this.lockAcquired || this._debug("#__loadSession()", "used outside of an acquired lock!", (/* @__PURE__ */ Error()).stack);
2338
+ try {
2339
+ let e = null, t = await M(this.storage, this.storageKey);
2340
+ if (this._debug("#getSession()", "session from storage", t), t !== null && (this._isValidSession(t) ? e = t : (this._debug("#getSession()", "session from storage is not valid"), await this._removeSession())), !e) return {
2341
+ data: { session: null },
2342
+ error: null
2343
+ };
2344
+ let n = e.expires_at ? e.expires_at * 1e3 - Date.now() < f : !1;
2345
+ if (this._debug("#__loadSession()", `session has${n ? "" : " not"} expired`, "expires_at", e.expires_at), !n) {
2346
+ if (this.userStorage) {
2347
+ let t = await M(this.userStorage, this.storageKey + "-user");
2348
+ t?.user ? e.user = t.user : e.user = L();
2349
+ }
2350
+ if (this.storage.isServer && e.user && !e.user.__isUserNotAvailableProxy) {
2351
+ let t = { value: this.suppressGetSessionWarning };
2352
+ e.user = Re(e.user, t), t.value && (this.suppressGetSessionWarning = !0);
2353
+ }
2354
+ return {
2355
+ data: { session: e },
2356
+ error: null
2357
+ };
2358
+ }
2359
+ let { data: r, error: i } = await this._callRefreshToken(e.refresh_token);
2360
+ return i ? this._returnResult({
2361
+ data: { session: null },
2362
+ error: i
2363
+ }) : this._returnResult({
2364
+ data: { session: r },
2365
+ error: null
2366
+ });
2367
+ } finally {
2368
+ this._debug("#__loadSession()", "end");
2369
+ }
2370
+ }
2371
+ async getUser(e) {
2372
+ if (e) return await this._getUser(e);
2373
+ await this.initializePromise;
2374
+ let t = await this._acquireLock(this.lockAcquireTimeout, async () => await this._getUser());
2375
+ return t.data.user && (this.suppressGetSessionWarning = !0), t;
2376
+ }
2377
+ async _getUser(e) {
2378
+ try {
2379
+ return e ? await z(this.fetch, "GET", `${this.url}/user`, {
2380
+ headers: this.headers,
2381
+ jwt: e,
2382
+ xform: V
2383
+ }) : await this._useSession(async (e) => {
2384
+ let { data: t, error: n } = e;
2385
+ if (n) throw n;
2386
+ return !t.session?.access_token && !this.hasCustomAuthorizationHeader ? {
2387
+ data: { user: null },
2388
+ error: new x()
2389
+ } : await z(this.fetch, "GET", `${this.url}/user`, {
2390
+ headers: this.headers,
2391
+ jwt: t.session?.access_token ?? void 0,
2392
+ xform: V
2393
+ });
2394
+ });
2395
+ } catch (e) {
2396
+ if (v(e)) return S(e) && (await this._removeSession(), await N(this.storage, `${this.storageKey}-code-verifier`)), this._returnResult({
2397
+ data: { user: null },
2398
+ error: e
2399
+ });
2400
+ throw e;
2401
+ }
2402
+ }
2403
+ async updateUser(e, t = {}) {
2404
+ return await this.initializePromise, await this._acquireLock(this.lockAcquireTimeout, async () => await this._updateUser(e, t));
2405
+ }
2406
+ async _updateUser(e, t = {}) {
2407
+ try {
2408
+ return await this._useSession(async (n) => {
2409
+ let { data: r, error: i } = n;
2410
+ if (i) throw i;
2411
+ if (!r.session) throw new x();
2412
+ let a = r.session, o = null, s = null;
2413
+ this.flowType === "pkce" && e.email != null && ([o, s] = await F(this.storage, this.storageKey));
2414
+ let { data: c, error: l } = await z(this.fetch, "PUT", `${this.url}/user`, {
2415
+ headers: this.headers,
2416
+ redirectTo: t?.emailRedirectTo,
2417
+ body: Object.assign(Object.assign({}, e), {
2418
+ code_challenge: o,
2419
+ code_challenge_method: s
2420
+ }),
2421
+ jwt: a.access_token,
2422
+ xform: V
2423
+ });
2424
+ if (l) throw l;
2425
+ return a.user = c.user, await this._saveSession(a), await this._notifyAllSubscribers("USER_UPDATED", a), this._returnResult({
2426
+ data: { user: a.user },
2427
+ error: null
2428
+ });
2429
+ });
2430
+ } catch (e) {
2431
+ if (await N(this.storage, `${this.storageKey}-code-verifier`), v(e)) return this._returnResult({
2432
+ data: { user: null },
2433
+ error: e
2434
+ });
2435
+ throw e;
2436
+ }
2437
+ }
2438
+ async setSession(e) {
2439
+ return await this.initializePromise, await this._acquireLock(this.lockAcquireTimeout, async () => await this._setSession(e));
2440
+ }
2441
+ async _setSession(e) {
2442
+ try {
2443
+ if (!e.access_token || !e.refresh_token) throw new x();
2444
+ let t = Date.now() / 1e3, n = t, r = !0, i = null, { payload: a } = P(e.access_token);
2445
+ if (a.exp && (n = a.exp, r = n <= t), r) {
2446
+ let { data: t, error: n } = await this._callRefreshToken(e.refresh_token);
2447
+ if (n) return this._returnResult({
2448
+ data: {
2449
+ user: null,
2450
+ session: null
2451
+ },
2452
+ error: n
2453
+ });
2454
+ if (!t) return {
2455
+ data: {
2456
+ user: null,
2457
+ session: null
2458
+ },
2459
+ error: null
2460
+ };
2461
+ i = t;
2462
+ } else {
2463
+ let { data: r, error: a } = await this._getUser(e.access_token);
2464
+ if (a) return this._returnResult({
2465
+ data: {
2466
+ user: null,
2467
+ session: null
2468
+ },
2469
+ error: a
2470
+ });
2471
+ i = {
2472
+ access_token: e.access_token,
2473
+ refresh_token: e.refresh_token,
2474
+ user: r.user,
2475
+ token_type: "bearer",
2476
+ expires_in: n - t,
2477
+ expires_at: n
2478
+ }, await this._saveSession(i), await this._notifyAllSubscribers("SIGNED_IN", i);
2479
+ }
2480
+ return this._returnResult({
2481
+ data: {
2482
+ user: i.user,
2483
+ session: i
2484
+ },
2485
+ error: null
2486
+ });
2487
+ } catch (e) {
2488
+ if (v(e)) return this._returnResult({
2489
+ data: {
2490
+ session: null,
2491
+ user: null
2492
+ },
2493
+ error: e
2494
+ });
2495
+ throw e;
2496
+ }
2497
+ }
2498
+ async refreshSession(e) {
2499
+ return await this.initializePromise, await this._acquireLock(this.lockAcquireTimeout, async () => await this._refreshSession(e));
2500
+ }
2501
+ async _refreshSession(e) {
2502
+ try {
2503
+ return await this._useSession(async (t) => {
2504
+ if (!e) {
2505
+ let { data: n, error: r } = t;
2506
+ if (r) throw r;
2507
+ e = n.session ?? void 0;
2508
+ }
2509
+ if (!e?.refresh_token) throw new x();
2510
+ let { data: n, error: r } = await this._callRefreshToken(e.refresh_token);
2511
+ return r ? this._returnResult({
2512
+ data: {
2513
+ user: null,
2514
+ session: null
2515
+ },
2516
+ error: r
2517
+ }) : n ? this._returnResult({
2518
+ data: {
2519
+ user: n.user,
2520
+ session: n
2521
+ },
2522
+ error: null
2523
+ }) : this._returnResult({
2524
+ data: {
2525
+ user: null,
2526
+ session: null
2527
+ },
2528
+ error: null
2529
+ });
2530
+ });
2531
+ } catch (e) {
2532
+ if (v(e)) return this._returnResult({
2533
+ data: {
2534
+ user: null,
2535
+ session: null
2536
+ },
2537
+ error: e
2538
+ });
2539
+ throw e;
2540
+ }
2541
+ }
2542
+ async _getSessionFromURL(e, t) {
2543
+ try {
2544
+ if (!k()) throw new T("No browser detected.");
2545
+ if (e.error || e.error_description || e.error_code) throw new T(e.error_description || "Error in URL with unspecified error_description", {
2546
+ error: e.error || "unspecified_error",
2547
+ code: e.error_code || "unspecified_code"
2548
+ });
2549
+ switch (t) {
2550
+ case "implicit":
2551
+ if (this.flowType === "pkce") throw new ae("Not a valid PKCE flow url.");
2552
+ break;
2553
+ case "pkce":
2554
+ if (this.flowType === "implicit") throw new T("Not a valid implicit grant flow url.");
2555
+ break;
2556
+ default:
2557
+ }
2558
+ if (t === "pkce") {
2559
+ if (this._debug("#_initialize()", "begin", "is PKCE flow", !0), !e.code) throw new ae("No code detected.");
2560
+ let { data: t, error: n } = await this._exchangeCodeForSession(e.code);
2561
+ if (n) throw n;
2562
+ let r = new URL(window.location.href);
2563
+ return r.searchParams.delete("code"), window.history.replaceState(window.history.state, "", r.toString()), {
2564
+ data: {
2565
+ session: t.session,
2566
+ redirectType: null
2567
+ },
2568
+ error: null
2569
+ };
2570
+ }
2571
+ let { provider_token: n, provider_refresh_token: r, access_token: i, refresh_token: a, expires_in: o, expires_at: s, token_type: c } = e;
2572
+ if (!i || !o || !a || !c) throw new T("No session defined in URL");
2573
+ let l = Math.round(Date.now() / 1e3), u = parseInt(o), d = l + u;
2574
+ s && (d = parseInt(s));
2575
+ let f = d - l;
2576
+ f * 1e3 <= 3e4 && console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);
2577
+ let p = d - u;
2578
+ l - p >= 120 ? console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale", p, d, l) : l - p < 0 && console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew", p, d, l);
2579
+ let { data: m, error: h } = await this._getUser(i);
2580
+ if (h) throw h;
2581
+ let g = {
2582
+ provider_token: n,
2583
+ provider_refresh_token: r,
2584
+ access_token: i,
2585
+ expires_in: u,
2586
+ expires_at: d,
2587
+ refresh_token: a,
2588
+ token_type: c,
2589
+ user: m.user
2590
+ };
2591
+ return window.location.hash = "", this._debug("#_getSessionFromURL()", "clearing window.location.hash"), this._returnResult({
2592
+ data: {
2593
+ session: g,
2594
+ redirectType: e.type
2595
+ },
2596
+ error: null
2597
+ });
2598
+ } catch (e) {
2599
+ if (v(e)) return this._returnResult({
2600
+ data: {
2601
+ session: null,
2602
+ redirectType: null
2603
+ },
2604
+ error: e
2605
+ });
2606
+ throw e;
2607
+ }
2608
+ }
2609
+ _isImplicitGrantCallback(e) {
2610
+ return typeof this.detectSessionInUrl == "function" ? this.detectSessionInUrl(new URL(window.location.href), e) : !!(e.access_token || e.error_description);
2611
+ }
2612
+ async _isPKCECallback(e) {
2613
+ let t = await M(this.storage, `${this.storageKey}-code-verifier`);
2614
+ return !!(e.code && t);
2615
+ }
2616
+ async signOut(e = { scope: "global" }) {
2617
+ return await this.initializePromise, await this._acquireLock(this.lockAcquireTimeout, async () => await this._signOut(e));
2618
+ }
2619
+ async _signOut({ scope: e } = { scope: "global" }) {
2620
+ return await this._useSession(async (t) => {
2621
+ let { data: n, error: r } = t;
2622
+ if (r && !S(r)) return this._returnResult({ error: r });
2623
+ let i = n.session?.access_token;
2624
+ if (i) {
2625
+ let { error: t } = await this.admin.signOut(i, e);
2626
+ if (t && !(re(t) && (t.status === 404 || t.status === 401 || t.status === 403) || S(t))) return this._returnResult({ error: t });
2627
+ }
2628
+ return e !== "others" && (await this._removeSession(), await N(this.storage, `${this.storageKey}-code-verifier`)), this._returnResult({ error: null });
2629
+ });
2630
+ }
2631
+ onAuthStateChange(e) {
2632
+ let t = xe(), n = {
2633
+ id: t,
2634
+ callback: e,
2635
+ unsubscribe: () => {
2636
+ this._debug("#unsubscribe()", "state change callback with id removed", t), this.stateChangeEmitters.delete(t);
2637
+ }
2638
+ };
2639
+ return this._debug("#onAuthStateChange()", "registered callback with id", t), this.stateChangeEmitters.set(t, n), (async () => {
2640
+ await this.initializePromise, await this._acquireLock(this.lockAcquireTimeout, async () => {
2641
+ this._emitInitialSession(t);
2642
+ });
2643
+ })(), { data: { subscription: n } };
2644
+ }
2645
+ async _emitInitialSession(e) {
2646
+ return await this._useSession(async (t) => {
2647
+ try {
2648
+ let { data: { session: n }, error: r } = t;
2649
+ if (r) throw r;
2650
+ await this.stateChangeEmitters.get(e)?.callback("INITIAL_SESSION", n), this._debug("INITIAL_SESSION", "callback id", e, "session", n);
2651
+ } catch (t) {
2652
+ await this.stateChangeEmitters.get(e)?.callback("INITIAL_SESSION", null), this._debug("INITIAL_SESSION", "callback id", e, "error", t), S(t) ? console.warn(t) : console.error(t);
2653
+ }
2654
+ });
2655
+ }
2656
+ async resetPasswordForEmail(e, t = {}) {
2657
+ let n = null, r = null;
2658
+ this.flowType === "pkce" && ([n, r] = await F(this.storage, this.storageKey, !0));
2659
+ try {
2660
+ return await z(this.fetch, "POST", `${this.url}/recover`, {
2661
+ body: {
2662
+ email: e,
2663
+ code_challenge: n,
2664
+ code_challenge_method: r,
2665
+ gotrue_meta_security: { captcha_token: t.captchaToken }
2666
+ },
2667
+ headers: this.headers,
2668
+ redirectTo: t.redirectTo
2669
+ });
2670
+ } catch (e) {
2671
+ if (await N(this.storage, `${this.storageKey}-code-verifier`), v(e)) return this._returnResult({
2672
+ data: null,
2673
+ error: e
2674
+ });
2675
+ throw e;
2676
+ }
2677
+ }
2678
+ async getUserIdentities() {
2679
+ try {
2680
+ let { data: e, error: t } = await this.getUser();
2681
+ if (t) throw t;
2682
+ return this._returnResult({
2683
+ data: { identities: e.user.identities ?? [] },
2684
+ error: null
2685
+ });
2686
+ } catch (e) {
2687
+ if (v(e)) return this._returnResult({
2688
+ data: null,
2689
+ error: e
2690
+ });
2691
+ throw e;
2692
+ }
2693
+ }
2694
+ async linkIdentity(e) {
2695
+ return "token" in e ? this.linkIdentityIdToken(e) : this.linkIdentityOAuth(e);
2696
+ }
2697
+ async linkIdentityOAuth(e) {
2698
+ try {
2699
+ let { data: t, error: n } = await this._useSession(async (t) => {
2700
+ let { data: n, error: r } = t;
2701
+ if (r) throw r;
2702
+ let i = await this._getUrlForProvider(`${this.url}/user/identities/authorize`, e.provider, {
2703
+ redirectTo: e.options?.redirectTo,
2704
+ scopes: e.options?.scopes,
2705
+ queryParams: e.options?.queryParams,
2706
+ skipBrowserRedirect: !0
2707
+ });
2708
+ return await z(this.fetch, "GET", i, {
2709
+ headers: this.headers,
2710
+ jwt: n.session?.access_token ?? void 0
2711
+ });
2712
+ });
2713
+ if (n) throw n;
2714
+ return k() && !e.options?.skipBrowserRedirect && window.location.assign(t?.url), this._returnResult({
2715
+ data: {
2716
+ provider: e.provider,
2717
+ url: t?.url
2718
+ },
2719
+ error: null
2720
+ });
2721
+ } catch (t) {
2722
+ if (v(t)) return this._returnResult({
2723
+ data: {
2724
+ provider: e.provider,
2725
+ url: null
2726
+ },
2727
+ error: t
2728
+ });
2729
+ throw t;
2730
+ }
2731
+ }
2732
+ async linkIdentityIdToken(e) {
2733
+ return await this._useSession(async (t) => {
2734
+ try {
2735
+ let { error: n, data: { session: r } } = t;
2736
+ if (n) throw n;
2737
+ let { options: i, provider: a, token: o, access_token: s, nonce: c } = e, { data: l, error: u } = await z(this.fetch, "POST", `${this.url}/token?grant_type=id_token`, {
2738
+ headers: this.headers,
2739
+ jwt: r?.access_token ?? void 0,
2740
+ body: {
2741
+ provider: a,
2742
+ id_token: o,
2743
+ access_token: s,
2744
+ nonce: c,
2745
+ link_identity: !0,
2746
+ gotrue_meta_security: { captcha_token: i?.captchaToken }
2747
+ },
2748
+ xform: B
2749
+ });
2750
+ return u ? this._returnResult({
2751
+ data: {
2752
+ user: null,
2753
+ session: null
2754
+ },
2755
+ error: u
2756
+ }) : !l || !l.session || !l.user ? this._returnResult({
2757
+ data: {
2758
+ user: null,
2759
+ session: null
2760
+ },
2761
+ error: new C()
2762
+ }) : (l.session && (await this._saveSession(l.session), await this._notifyAllSubscribers("USER_UPDATED", l.session)), this._returnResult({
2763
+ data: l,
2764
+ error: u
2765
+ }));
2766
+ } catch (e) {
2767
+ if (await N(this.storage, `${this.storageKey}-code-verifier`), v(e)) return this._returnResult({
2768
+ data: {
2769
+ user: null,
2770
+ session: null
2771
+ },
2772
+ error: e
2773
+ });
2774
+ throw e;
2775
+ }
2776
+ });
2777
+ }
2778
+ async unlinkIdentity(e) {
2779
+ try {
2780
+ return await this._useSession(async (t) => {
2781
+ let { data: n, error: r } = t;
2782
+ if (r) throw r;
2783
+ return await z(this.fetch, "DELETE", `${this.url}/user/identities/${e.identity_id}`, {
2784
+ headers: this.headers,
2785
+ jwt: n.session?.access_token ?? void 0
2786
+ });
2787
+ });
2788
+ } catch (e) {
2789
+ if (v(e)) return this._returnResult({
2790
+ data: null,
2791
+ error: e
2792
+ });
2793
+ throw e;
2794
+ }
2795
+ }
2796
+ async _refreshAccessToken(e) {
2797
+ let t = `#_refreshAccessToken(${e.substring(0, 5)}...)`;
2798
+ this._debug(t, "begin");
2799
+ try {
2800
+ let n = Date.now();
2801
+ return await Oe(async (n) => (n > 0 && await De(200 * 2 ** (n - 1)), this._debug(t, "refreshing attempt", n), await z(this.fetch, "POST", `${this.url}/token?grant_type=refresh_token`, {
2802
+ body: { refresh_token: e },
2803
+ headers: this.headers,
2804
+ xform: B
2805
+ })), (e, t) => {
2806
+ let r = 200 * 2 ** e;
2807
+ return t && ce(t) && Date.now() + r - n < 3e4;
2808
+ });
2809
+ } catch (e) {
2810
+ if (this._debug(t, "error", e), v(e)) return this._returnResult({
2811
+ data: {
2812
+ session: null,
2813
+ user: null
2814
+ },
2815
+ error: e
2816
+ });
2817
+ throw e;
2818
+ } finally {
2819
+ this._debug(t, "end");
2820
+ }
2821
+ }
2822
+ _isValidSession(e) {
2823
+ return typeof e == "object" && !!e && "access_token" in e && "refresh_token" in e && "expires_at" in e;
2824
+ }
2825
+ async _handleProviderSignIn(e, t) {
2826
+ let n = await this._getUrlForProvider(`${this.url}/authorize`, e, {
2827
+ redirectTo: t.redirectTo,
2828
+ scopes: t.scopes,
2829
+ queryParams: t.queryParams
2830
+ });
2831
+ return this._debug("#_handleProviderSignIn()", "provider", e, "options", t, "url", n), k() && !t.skipBrowserRedirect && window.location.assign(n), {
2832
+ data: {
2833
+ provider: e,
2834
+ url: n
2835
+ },
2836
+ error: null
2837
+ };
2838
+ }
2839
+ async _recoverAndRefresh() {
2840
+ let e = "#_recoverAndRefresh()";
2841
+ this._debug(e, "begin");
2842
+ try {
2843
+ let t = await M(this.storage, this.storageKey);
2844
+ if (t && this.userStorage) {
2845
+ let e = await M(this.userStorage, this.storageKey + "-user");
2846
+ !this.storage.isServer && Object.is(this.storage, this.userStorage) && !e && (e = { user: t.user }, await j(this.userStorage, this.storageKey + "-user", e)), t.user = e?.user ?? L();
2847
+ } else if (t && !t.user && !t.user) {
2848
+ let e = await M(this.storage, this.storageKey + "-user");
2849
+ e && e?.user ? (t.user = e.user, await N(this.storage, this.storageKey + "-user"), await j(this.storage, this.storageKey, t)) : t.user = L();
2850
+ }
2851
+ if (this._debug(e, "session from storage", t), !this._isValidSession(t)) {
2852
+ this._debug(e, "session is not valid"), t !== null && await this._removeSession();
2853
+ return;
2854
+ }
2855
+ let n = (t.expires_at ?? Infinity) * 1e3 - Date.now() < f;
2856
+ if (this._debug(e, `session has${n ? "" : " not"} expired with margin of ${f}s`), n) {
2857
+ if (this.autoRefreshToken && t.refresh_token) {
2858
+ let { error: n } = await this._callRefreshToken(t.refresh_token);
2859
+ n && (console.error(n), ce(n) || (this._debug(e, "refresh failed with a non-retryable error, removing the session", n), await this._removeSession()));
2860
+ }
2861
+ } else if (t.user && t.user.__isUserNotAvailableProxy === !0) try {
2862
+ let { data: n, error: r } = await this._getUser(t.access_token);
2863
+ !r && n?.user ? (t.user = n.user, await this._saveSession(t), await this._notifyAllSubscribers("SIGNED_IN", t)) : this._debug(e, "could not get user data, skipping SIGNED_IN notification");
2864
+ } catch (t) {
2865
+ console.error("Error getting user data:", t), this._debug(e, "error getting user data, skipping SIGNED_IN notification", t);
2866
+ }
2867
+ else await this._notifyAllSubscribers("SIGNED_IN", t);
2868
+ } catch (t) {
2869
+ this._debug(e, "error", t), console.error(t);
2870
+ return;
2871
+ } finally {
2872
+ this._debug(e, "end");
2873
+ }
2874
+ }
2875
+ async _callRefreshToken(e) {
2876
+ var t, n;
2877
+ if (!e) throw new x();
2878
+ if (this.refreshingDeferred) return this.refreshingDeferred.promise;
2879
+ let r = `#_callRefreshToken(${e.substring(0, 5)}...)`;
2880
+ this._debug(r, "begin");
2881
+ try {
2882
+ this.refreshingDeferred = new Ee();
2883
+ let { data: t, error: n } = await this._refreshAccessToken(e);
2884
+ if (n) throw n;
2885
+ if (!t.session) throw new x();
2886
+ await this._saveSession(t.session), await this._notifyAllSubscribers("TOKEN_REFRESHED", t.session);
2887
+ let r = {
2888
+ data: t.session,
2889
+ error: null
2890
+ };
2891
+ return this.refreshingDeferred.resolve(r), r;
2892
+ } catch (e) {
2893
+ if (this._debug(r, "error", e), v(e)) {
2894
+ let n = {
2895
+ data: null,
2896
+ error: e
2897
+ };
2898
+ return ce(e) || await this._removeSession(), (t = this.refreshingDeferred) == null || t.resolve(n), n;
2899
+ }
2900
+ throw (n = this.refreshingDeferred) == null || n.reject(e), e;
2901
+ } finally {
2902
+ this.refreshingDeferred = null, this._debug(r, "end");
2903
+ }
2904
+ }
2905
+ async _notifyAllSubscribers(e, t, n = !0) {
2906
+ let r = `#_notifyAllSubscribers(${e})`;
2907
+ this._debug(r, "begin", t, `broadcast = ${n}`);
2908
+ try {
2909
+ this.broadcastChannel && n && this.broadcastChannel.postMessage({
2910
+ event: e,
2911
+ session: t
2912
+ });
2913
+ let r = [], i = Array.from(this.stateChangeEmitters.values()).map(async (n) => {
2914
+ try {
2915
+ await n.callback(e, t);
2916
+ } catch (e) {
2917
+ r.push(e);
2918
+ }
2919
+ });
2920
+ if (await Promise.all(i), r.length > 0) {
2921
+ for (let e = 0; e < r.length; e += 1) console.error(r[e]);
2922
+ throw r[0];
2923
+ }
2924
+ } finally {
2925
+ this._debug(r, "end");
2926
+ }
2927
+ }
2928
+ async _saveSession(e) {
2929
+ this._debug("#_saveSession()", e), this.suppressGetSessionWarning = !0, await N(this.storage, `${this.storageKey}-code-verifier`);
2930
+ let t = Object.assign({}, e), n = t.user && t.user.__isUserNotAvailableProxy === !0;
2931
+ if (this.userStorage) {
2932
+ !n && t.user && await j(this.userStorage, this.storageKey + "-user", { user: t.user });
2933
+ let e = Object.assign({}, t);
2934
+ delete e.user;
2935
+ let r = ze(e);
2936
+ await j(this.storage, this.storageKey, r);
2937
+ } else {
2938
+ let e = ze(t);
2939
+ await j(this.storage, this.storageKey, e);
2940
+ }
2941
+ }
2942
+ async _removeSession() {
2943
+ this._debug("#_removeSession()"), this.suppressGetSessionWarning = !1, await N(this.storage, this.storageKey), await N(this.storage, this.storageKey + "-code-verifier"), await N(this.storage, this.storageKey + "-user"), this.userStorage && await N(this.userStorage, this.storageKey + "-user"), await this._notifyAllSubscribers("SIGNED_OUT", null);
2944
+ }
2945
+ _removeVisibilityChangedCallback() {
2946
+ this._debug("#_removeVisibilityChangedCallback()");
2947
+ let e = this.visibilityChangedCallback;
2948
+ this.visibilityChangedCallback = null;
2949
+ try {
2950
+ e && k() && window != null && window.removeEventListener && window.removeEventListener("visibilitychange", e);
2951
+ } catch (e) {
2952
+ console.error("removing visibilitychange callback failed", e);
2953
+ }
2954
+ }
2955
+ async _startAutoRefresh() {
2956
+ await this._stopAutoRefresh(), this._debug("#_startAutoRefresh()");
2957
+ let e = setInterval(() => this._autoRefreshTokenTick(), d);
2958
+ this.autoRefreshTicker = e, e && typeof e == "object" && typeof e.unref == "function" ? e.unref() : typeof Deno < "u" && typeof Deno.unrefTimer == "function" && Deno.unrefTimer(e);
2959
+ let t = setTimeout(async () => {
2960
+ await this.initializePromise, await this._autoRefreshTokenTick();
2961
+ }, 0);
2962
+ this.autoRefreshTickTimeout = t, t && typeof t == "object" && typeof t.unref == "function" ? t.unref() : typeof Deno < "u" && typeof Deno.unrefTimer == "function" && Deno.unrefTimer(t);
2963
+ }
2964
+ async _stopAutoRefresh() {
2965
+ this._debug("#_stopAutoRefresh()");
2966
+ let e = this.autoRefreshTicker;
2967
+ this.autoRefreshTicker = null, e && clearInterval(e);
2968
+ let t = this.autoRefreshTickTimeout;
2969
+ this.autoRefreshTickTimeout = null, t && clearTimeout(t);
2970
+ }
2971
+ async startAutoRefresh() {
2972
+ this._removeVisibilityChangedCallback(), await this._startAutoRefresh();
2973
+ }
2974
+ async stopAutoRefresh() {
2975
+ this._removeVisibilityChangedCallback(), await this._stopAutoRefresh();
2976
+ }
2977
+ async _autoRefreshTokenTick() {
2978
+ this._debug("#_autoRefreshTokenTick()", "begin");
2979
+ try {
2980
+ await this._acquireLock(0, async () => {
2981
+ try {
2982
+ let e = Date.now();
2983
+ try {
2984
+ return await this._useSession(async (t) => {
2985
+ let { data: { session: n } } = t;
2986
+ if (!n || !n.refresh_token || !n.expires_at) {
2987
+ this._debug("#_autoRefreshTokenTick()", "no session");
2988
+ return;
2989
+ }
2990
+ let r = Math.floor((n.expires_at * 1e3 - e) / d);
2991
+ this._debug("#_autoRefreshTokenTick()", `access token expires in ${r} ticks, a tick lasts ${d}ms, refresh threshold is 3 ticks`), r <= 3 && await this._callRefreshToken(n.refresh_token);
2992
+ });
2993
+ } catch (e) {
2994
+ console.error("Auto refresh tick failed with error. This is likely a transient error.", e);
2995
+ }
2996
+ } finally {
2997
+ this._debug("#_autoRefreshTokenTick()", "end");
2998
+ }
2999
+ });
3000
+ } catch (e) {
3001
+ if (e.isAcquireTimeout || e instanceof Ze) this._debug("auto refresh token tick lock not available");
3002
+ else throw e;
3003
+ }
3004
+ }
3005
+ async _handleVisibilityChange() {
3006
+ if (this._debug("#_handleVisibilityChange()"), !k() || !(window != null && window.addEventListener)) return this.autoRefreshToken && this.startAutoRefresh(), !1;
3007
+ try {
3008
+ this.visibilityChangedCallback = async () => {
3009
+ try {
3010
+ await this._onVisibilityChanged(!1);
3011
+ } catch (e) {
3012
+ this._debug("#visibilityChangedCallback", "error", e);
3013
+ }
3014
+ }, window == null || window.addEventListener("visibilitychange", this.visibilityChangedCallback), await this._onVisibilityChanged(!0);
3015
+ } catch (e) {
3016
+ console.error("_handleVisibilityChange", e);
3017
+ }
3018
+ }
3019
+ async _onVisibilityChanged(e) {
3020
+ let t = `#_onVisibilityChanged(${e})`;
3021
+ this._debug(t, "visibilityState", document.visibilityState), document.visibilityState === "visible" ? (this.autoRefreshToken && this._startAutoRefresh(), e || (await this.initializePromise, await this._acquireLock(this.lockAcquireTimeout, async () => {
3022
+ if (document.visibilityState !== "visible") {
3023
+ this._debug(t, "acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");
3024
+ return;
3025
+ }
3026
+ await this._recoverAndRefresh();
3027
+ }))) : document.visibilityState === "hidden" && this.autoRefreshToken && this._stopAutoRefresh();
3028
+ }
3029
+ async _getUrlForProvider(e, t, n) {
3030
+ let r = [`provider=${encodeURIComponent(t)}`];
3031
+ if (n?.redirectTo && r.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`), n?.scopes && r.push(`scopes=${encodeURIComponent(n.scopes)}`), this.flowType === "pkce") {
3032
+ let [e, t] = await F(this.storage, this.storageKey), n = new URLSearchParams({
3033
+ code_challenge: `${encodeURIComponent(e)}`,
3034
+ code_challenge_method: `${encodeURIComponent(t)}`
3035
+ });
3036
+ r.push(n.toString());
3037
+ }
3038
+ if (n?.queryParams) {
3039
+ let e = new URLSearchParams(n.queryParams);
3040
+ r.push(e.toString());
3041
+ }
3042
+ return n?.skipBrowserRedirect && r.push(`skip_http_redirect=${n.skipBrowserRedirect}`), `${e}?${r.join("&")}`;
3043
+ }
3044
+ async _unenroll(e) {
3045
+ try {
3046
+ return await this._useSession(async (t) => {
3047
+ let { data: n, error: r } = t;
3048
+ return r ? this._returnResult({
3049
+ data: null,
3050
+ error: r
3051
+ }) : await z(this.fetch, "DELETE", `${this.url}/factors/${e.factorId}`, {
3052
+ headers: this.headers,
3053
+ jwt: n?.session?.access_token
3054
+ });
3055
+ });
3056
+ } catch (e) {
3057
+ if (v(e)) return this._returnResult({
3058
+ data: null,
3059
+ error: e
3060
+ });
3061
+ throw e;
3062
+ }
3063
+ }
3064
+ async _enroll(e) {
3065
+ try {
3066
+ return await this._useSession(async (t) => {
3067
+ let { data: n, error: r } = t;
3068
+ if (r) return this._returnResult({
3069
+ data: null,
3070
+ error: r
3071
+ });
3072
+ let i = Object.assign({
3073
+ friendly_name: e.friendlyName,
3074
+ factor_type: e.factorType
3075
+ }, e.factorType === "phone" ? { phone: e.phone } : e.factorType === "totp" ? { issuer: e.issuer } : {}), { data: a, error: o } = await z(this.fetch, "POST", `${this.url}/factors`, {
3076
+ body: i,
3077
+ headers: this.headers,
3078
+ jwt: n?.session?.access_token
3079
+ });
3080
+ return o ? this._returnResult({
3081
+ data: null,
3082
+ error: o
3083
+ }) : (e.factorType === "totp" && a.type === "totp" && a?.totp?.qr_code && (a.totp.qr_code = `data:image/svg+xml;utf-8,${a.totp.qr_code}`), this._returnResult({
3084
+ data: a,
3085
+ error: null
3086
+ }));
3087
+ });
3088
+ } catch (e) {
3089
+ if (v(e)) return this._returnResult({
3090
+ data: null,
3091
+ error: e
3092
+ });
3093
+ throw e;
3094
+ }
3095
+ }
3096
+ async _verify(e) {
3097
+ return this._acquireLock(this.lockAcquireTimeout, async () => {
3098
+ try {
3099
+ return await this._useSession(async (t) => {
3100
+ let { data: n, error: r } = t;
3101
+ if (r) return this._returnResult({
3102
+ data: null,
3103
+ error: r
3104
+ });
3105
+ let i = Object.assign({ challenge_id: e.challengeId }, "webauthn" in e ? { webauthn: Object.assign(Object.assign({}, e.webauthn), { credential_response: e.webauthn.type === "create" ? ut(e.webauthn.credential_response) : dt(e.webauthn.credential_response) }) } : { code: e.code }), { data: a, error: o } = await z(this.fetch, "POST", `${this.url}/factors/${e.factorId}/verify`, {
3106
+ body: i,
3107
+ headers: this.headers,
3108
+ jwt: n?.session?.access_token
3109
+ });
3110
+ return o ? this._returnResult({
3111
+ data: null,
3112
+ error: o
3113
+ }) : (await this._saveSession(Object.assign({ expires_at: Math.round(Date.now() / 1e3) + a.expires_in }, a)), await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED", a), this._returnResult({
3114
+ data: a,
3115
+ error: o
3116
+ }));
3117
+ });
3118
+ } catch (e) {
3119
+ if (v(e)) return this._returnResult({
3120
+ data: null,
3121
+ error: e
3122
+ });
3123
+ throw e;
3124
+ }
3125
+ });
3126
+ }
3127
+ async _challenge(e) {
3128
+ return this._acquireLock(this.lockAcquireTimeout, async () => {
3129
+ try {
3130
+ return await this._useSession(async (t) => {
3131
+ let { data: n, error: r } = t;
3132
+ if (r) return this._returnResult({
3133
+ data: null,
3134
+ error: r
3135
+ });
3136
+ let i = await z(this.fetch, "POST", `${this.url}/factors/${e.factorId}/challenge`, {
3137
+ body: e,
3138
+ headers: this.headers,
3139
+ jwt: n?.session?.access_token
3140
+ });
3141
+ if (i.error) return i;
3142
+ let { data: a } = i;
3143
+ if (a.type !== "webauthn") return {
3144
+ data: a,
3145
+ error: null
3146
+ };
3147
+ switch (a.webauthn.type) {
3148
+ case "create": return {
3149
+ data: Object.assign(Object.assign({}, a), { webauthn: Object.assign(Object.assign({}, a.webauthn), { credential_options: Object.assign(Object.assign({}, a.webauthn.credential_options), { publicKey: ct(a.webauthn.credential_options.publicKey) }) }) }),
3150
+ error: null
3151
+ };
3152
+ case "request": return {
3153
+ data: Object.assign(Object.assign({}, a), { webauthn: Object.assign(Object.assign({}, a.webauthn), { credential_options: Object.assign(Object.assign({}, a.webauthn.credential_options), { publicKey: lt(a.webauthn.credential_options.publicKey) }) }) }),
3154
+ error: null
3155
+ };
3156
+ }
3157
+ });
3158
+ } catch (e) {
3159
+ if (v(e)) return this._returnResult({
3160
+ data: null,
3161
+ error: e
3162
+ });
3163
+ throw e;
3164
+ }
3165
+ });
3166
+ }
3167
+ async _challengeAndVerify(e) {
3168
+ let { data: t, error: n } = await this._challenge({ factorId: e.factorId });
3169
+ return n ? this._returnResult({
3170
+ data: null,
3171
+ error: n
3172
+ }) : await this._verify({
3173
+ factorId: e.factorId,
3174
+ challengeId: t.id,
3175
+ code: e.code
3176
+ });
3177
+ }
3178
+ async _listFactors() {
3179
+ let { data: { user: e }, error: t } = await this.getUser();
3180
+ if (t) return {
3181
+ data: null,
3182
+ error: t
3183
+ };
3184
+ let n = {
3185
+ all: [],
3186
+ phone: [],
3187
+ totp: [],
3188
+ webauthn: []
3189
+ };
3190
+ for (let t of e?.factors ?? []) n.all.push(t), t.status === "verified" && n[t.factor_type].push(t);
3191
+ return {
3192
+ data: n,
3193
+ error: null
3194
+ };
3195
+ }
3196
+ async _getAuthenticatorAssuranceLevel(e) {
3197
+ if (e) try {
3198
+ let { payload: t } = P(e), n = null;
3199
+ t.aal && (n = t.aal);
3200
+ let r = n, { data: { user: i }, error: a } = await this.getUser(e);
3201
+ if (a) return this._returnResult({
3202
+ data: null,
3203
+ error: a
3204
+ });
3205
+ ((i?.factors)?.filter((e) => e.status === "verified") ?? []).length > 0 && (r = "aal2");
3206
+ let o = t.amr || [];
3207
+ return {
3208
+ data: {
3209
+ currentLevel: n,
3210
+ nextLevel: r,
3211
+ currentAuthenticationMethods: o
3212
+ },
3213
+ error: null
3214
+ };
3215
+ } catch (e) {
3216
+ if (v(e)) return this._returnResult({
3217
+ data: null,
3218
+ error: e
3219
+ });
3220
+ throw e;
3221
+ }
3222
+ let { data: { session: t }, error: n } = await this.getSession();
3223
+ if (n) return this._returnResult({
3224
+ data: null,
3225
+ error: n
3226
+ });
3227
+ if (!t) return {
3228
+ data: {
3229
+ currentLevel: null,
3230
+ nextLevel: null,
3231
+ currentAuthenticationMethods: []
3232
+ },
3233
+ error: null
3234
+ };
3235
+ let { payload: r } = P(t.access_token), i = null;
3236
+ r.aal && (i = r.aal);
3237
+ let a = i;
3238
+ (t.user.factors?.filter((e) => e.status === "verified") ?? []).length > 0 && (a = "aal2");
3239
+ let o = r.amr || [];
3240
+ return {
3241
+ data: {
3242
+ currentLevel: i,
3243
+ nextLevel: a,
3244
+ currentAuthenticationMethods: o
3245
+ },
3246
+ error: null
3247
+ };
3248
+ }
3249
+ async _getAuthorizationDetails(e) {
3250
+ try {
3251
+ return await this._useSession(async (t) => {
3252
+ let { data: { session: n }, error: r } = t;
3253
+ return r ? this._returnResult({
3254
+ data: null,
3255
+ error: r
3256
+ }) : n ? await z(this.fetch, "GET", `${this.url}/oauth/authorizations/${e}`, {
3257
+ headers: this.headers,
3258
+ jwt: n.access_token,
3259
+ xform: (e) => ({
3260
+ data: e,
3261
+ error: null
3262
+ })
3263
+ }) : this._returnResult({
3264
+ data: null,
3265
+ error: new x()
3266
+ });
3267
+ });
3268
+ } catch (e) {
3269
+ if (v(e)) return this._returnResult({
3270
+ data: null,
3271
+ error: e
3272
+ });
3273
+ throw e;
3274
+ }
3275
+ }
3276
+ async _approveAuthorization(e, t) {
3277
+ try {
3278
+ return await this._useSession(async (n) => {
3279
+ let { data: { session: r }, error: i } = n;
3280
+ if (i) return this._returnResult({
3281
+ data: null,
3282
+ error: i
3283
+ });
3284
+ if (!r) return this._returnResult({
3285
+ data: null,
3286
+ error: new x()
3287
+ });
3288
+ let a = await z(this.fetch, "POST", `${this.url}/oauth/authorizations/${e}/consent`, {
3289
+ headers: this.headers,
3290
+ jwt: r.access_token,
3291
+ body: { action: "approve" },
3292
+ xform: (e) => ({
3293
+ data: e,
3294
+ error: null
3295
+ })
3296
+ });
3297
+ return a.data && a.data.redirect_url && k() && !t?.skipBrowserRedirect && window.location.assign(a.data.redirect_url), a;
3298
+ });
3299
+ } catch (e) {
3300
+ if (v(e)) return this._returnResult({
3301
+ data: null,
3302
+ error: e
3303
+ });
3304
+ throw e;
3305
+ }
3306
+ }
3307
+ async _denyAuthorization(e, t) {
3308
+ try {
3309
+ return await this._useSession(async (n) => {
3310
+ let { data: { session: r }, error: i } = n;
3311
+ if (i) return this._returnResult({
3312
+ data: null,
3313
+ error: i
3314
+ });
3315
+ if (!r) return this._returnResult({
3316
+ data: null,
3317
+ error: new x()
3318
+ });
3319
+ let a = await z(this.fetch, "POST", `${this.url}/oauth/authorizations/${e}/consent`, {
3320
+ headers: this.headers,
3321
+ jwt: r.access_token,
3322
+ body: { action: "deny" },
3323
+ xform: (e) => ({
3324
+ data: e,
3325
+ error: null
3326
+ })
3327
+ });
3328
+ return a.data && a.data.redirect_url && k() && !t?.skipBrowserRedirect && window.location.assign(a.data.redirect_url), a;
3329
+ });
3330
+ } catch (e) {
3331
+ if (v(e)) return this._returnResult({
3332
+ data: null,
3333
+ error: e
3334
+ });
3335
+ throw e;
3336
+ }
3337
+ }
3338
+ async _listOAuthGrants() {
3339
+ try {
3340
+ return await this._useSession(async (e) => {
3341
+ let { data: { session: t }, error: n } = e;
3342
+ return n ? this._returnResult({
3343
+ data: null,
3344
+ error: n
3345
+ }) : t ? await z(this.fetch, "GET", `${this.url}/user/oauth/grants`, {
3346
+ headers: this.headers,
3347
+ jwt: t.access_token,
3348
+ xform: (e) => ({
3349
+ data: e,
3350
+ error: null
3351
+ })
3352
+ }) : this._returnResult({
3353
+ data: null,
3354
+ error: new x()
3355
+ });
3356
+ });
3357
+ } catch (e) {
3358
+ if (v(e)) return this._returnResult({
3359
+ data: null,
3360
+ error: e
3361
+ });
3362
+ throw e;
3363
+ }
3364
+ }
3365
+ async _revokeOAuthGrant(e) {
3366
+ try {
3367
+ return await this._useSession(async (t) => {
3368
+ let { data: { session: n }, error: r } = t;
3369
+ return r ? this._returnResult({
3370
+ data: null,
3371
+ error: r
3372
+ }) : n ? (await z(this.fetch, "DELETE", `${this.url}/user/oauth/grants`, {
3373
+ headers: this.headers,
3374
+ jwt: n.access_token,
3375
+ query: { client_id: e.clientId },
3376
+ noResolveJson: !0
3377
+ }), {
3378
+ data: {},
3379
+ error: null
3380
+ }) : this._returnResult({
3381
+ data: null,
3382
+ error: new x()
3383
+ });
3384
+ });
3385
+ } catch (e) {
3386
+ if (v(e)) return this._returnResult({
3387
+ data: null,
3388
+ error: e
3389
+ });
3390
+ throw e;
3391
+ }
3392
+ }
3393
+ async fetchJwk(e, t = { keys: [] }) {
3394
+ let n = t.keys.find((t) => t.kid === e);
3395
+ if (n) return n;
3396
+ let r = Date.now();
3397
+ if (n = this.jwks.keys.find((t) => t.kid === e), n && this.jwks_cached_at + 6e5 > r) return n;
3398
+ let { data: i, error: a } = await z(this.fetch, "GET", `${this.url}/.well-known/jwks.json`, { headers: this.headers });
3399
+ if (a) throw a;
3400
+ return !i.keys || i.keys.length === 0 || (this.jwks = i, this.jwks_cached_at = r, n = i.keys.find((t) => t.kid === e), !n) ? null : n;
3401
+ }
3402
+ async getClaims(e, t = {}) {
3403
+ try {
3404
+ let n = e;
3405
+ if (!n) {
3406
+ let { data: e, error: t } = await this.getSession();
3407
+ if (t || !e.session) return this._returnResult({
3408
+ data: null,
3409
+ error: t
3410
+ });
3411
+ n = e.session.access_token;
3412
+ }
3413
+ let { header: r, payload: i, signature: a, raw: { header: o, payload: s } } = P(n);
3414
+ t?.allowExpired || Fe(i.exp);
3415
+ let c = !r.alg || r.alg.startsWith("HS") || !r.kid || !("crypto" in globalThis && "subtle" in globalThis.crypto) ? null : await this.fetchJwk(r.kid, t?.keys ? { keys: t.keys } : t?.jwks);
3416
+ if (!c) {
3417
+ let { error: e } = await this.getUser(n);
3418
+ if (e) throw e;
3419
+ return {
3420
+ data: {
3421
+ claims: i,
3422
+ header: r,
3423
+ signature: a
3424
+ },
3425
+ error: null
3426
+ };
3427
+ }
3428
+ let l = Ie(r.alg), u = await crypto.subtle.importKey("jwk", c, l, !0, ["verify"]);
3429
+ if (!await crypto.subtle.verify(l, u, a, ye(`${o}.${s}`))) throw new ue("Invalid JWT signature");
3430
+ return {
3431
+ data: {
3432
+ claims: i,
3433
+ header: r,
3434
+ signature: a
3435
+ },
3436
+ error: null
3437
+ };
3438
+ } catch (e) {
3439
+ if (v(e)) return this._returnResult({
3440
+ data: null,
3441
+ error: e
3442
+ });
3443
+ throw e;
3444
+ }
3445
+ }
3446
+ };
3447
+ Ct.nextInstanceID = {};
3448
+ //#endregion
3449
+ //#region node_modules/@supabase/supabase-js/dist/index.mjs
3450
+ var wt = "2.104.0", Tt = "";
3451
+ Tt = typeof Deno < "u" ? "deno" : typeof document < "u" ? "web" : typeof navigator < "u" && navigator.product === "ReactNative" ? "react-native" : "node", `${Tt}${wt}`;
3452
+ function Et() {
3453
+ if (typeof window < "u") return !1;
3454
+ let e = globalThis.process;
3455
+ if (!e) return !1;
3456
+ let t = e.version;
3457
+ if (t == null) return !1;
3458
+ let n = t.match(/^v(\d+)\./);
3459
+ return n ? parseInt(n[1], 10) <= 18 : !1;
3460
+ }
3461
+ Et() && console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");
3462
+ //#endregion
6
3463
  //#region lib/errors.ts
7
- var i = class extends Error {
3464
+ var J = class extends Error {
8
3465
  constructor(e, t = {}) {
9
3466
  super(e, t), this.name = this.constructor.name, Error.captureStackTrace(this, this.constructor);
10
3467
  }
11
- }, a = class extends i {
3468
+ }, Dt = class extends J {
12
3469
  fileId;
13
3470
  bucket;
14
3471
  path;
15
3472
  constructor(e, { fileId: t, bucket: n, path: r } = {}) {
16
3473
  super(e), this.fileId = t, this.bucket = n, this.path = r;
17
3474
  }
18
- }, o = class extends Error {
19
- fileName;
20
- fileType;
21
- constructor(e, { fileName: t, fileType: n, ...r } = {}) {
22
- super(e, r), this.fileName = t, this.fileType = n;
23
- }
24
- }, s = class extends i {
3475
+ }, Ot = class extends J {
25
3476
  expression;
26
3477
  format;
27
3478
  constructor(e, { expression: t, format: n, ...r } = {}) {
28
3479
  super(e, r), this.expression = t, this.format = n;
29
3480
  }
30
- }, c = class extends i {
3481
+ }, kt = class extends J {
31
3482
  schema;
32
3483
  relation;
33
3484
  id;
34
3485
  constructor(e, { schema: t, relation: n, id: r } = {}) {
35
3486
  super(e), this.schema = t, this.relation = n, this.id = r;
36
3487
  }
37
- }, l = t.object({
3488
+ }, At = t.object({
38
3489
  code: t.string(),
39
3490
  details: t.string().nullable(),
40
3491
  hint: t.string().nullable(),
41
3492
  name: t.string().optional(),
42
3493
  message: t.string().optional()
43
3494
  });
44
- function u(e) {
45
- return e instanceof n || l.safeParse(e).success;
3495
+ function jt(e) {
3496
+ return e instanceof r || At.safeParse(e).success;
46
3497
  }
47
3498
  //#endregion
48
3499
  //#region lib/utils.ts
49
- function d(e, t = "/") {
3500
+ function Mt(e, t = "/") {
50
3501
  let n = e.lastIndexOf(t);
51
3502
  return n === -1 ? ["", e] : [e.substring(0, n), e.substring(n + 1)];
52
3503
  }
53
- function f(e) {
3504
+ function Y(e) {
54
3505
  return Array.isArray(e) ? e : [e];
55
3506
  }
56
- function p(e, t) {
3507
+ function Nt(e, t) {
57
3508
  return e.reduce((e, n) => {
58
3509
  let r = t(n);
59
3510
  return (e[r] ??= []).push(n), e;
60
3511
  }, {});
61
3512
  }
62
- function m(e, t) {
3513
+ function Pt(e, t) {
63
3514
  let n = e.findIndex(t);
64
3515
  return n !== -1 && e.splice(n, 1), e;
65
3516
  }
66
- function h(e) {
3517
+ function Ft(e) {
67
3518
  return Object.entries(e);
68
3519
  }
69
3520
  //#endregion
70
3521
  //#region lib/data-service.ts
71
- var g = class {
3522
+ var X = class {
72
3523
  database;
73
3524
  schema;
74
3525
  relation;
@@ -76,7 +3527,7 @@ var g = class {
76
3527
  this.database = e, this.schema = t, this.relation = n;
77
3528
  }
78
3529
  recordNotFoundError(e) {
79
- return new c(`Record with id ${e} not found in ${this.schema}.${this.relation}`, {
3530
+ return new kt(`Record with id ${e} not found in ${this.schema}.${this.relation}`, {
80
3531
  schema: this.schema,
81
3532
  relation: this.relation,
82
3533
  id: e
@@ -124,7 +3575,7 @@ var g = class {
124
3575
  }
125
3576
  async upsert(e, { onConflict: t, ...n } = {}) {
126
3577
  let { data: r } = await this.query.upsert(e, {
127
- onConflict: t === void 0 ? void 0 : f(t).join(","),
3578
+ onConflict: t === void 0 ? void 0 : Y(t).join(","),
128
3579
  ...n
129
3580
  }).select().single().throwOnError();
130
3581
  return r;
@@ -133,7 +3584,7 @@ var g = class {
133
3584
  let { data: n } = await this.query.update(t).eq("id", e).select().single().throwOnError();
134
3585
  return n;
135
3586
  }
136
- }, _ = class extends g {
3587
+ }, It = class extends X {
137
3588
  constructor({ database: e, schema: t, table: n }) {
138
3589
  super({
139
3590
  database: e,
@@ -141,7 +3592,7 @@ var g = class {
141
3592
  relation: n
142
3593
  });
143
3594
  }
144
- }, v = class extends g {
3595
+ }, Lt = class extends X {
145
3596
  constructor({ database: e, schema: t, view: n }) {
146
3597
  super({
147
3598
  database: e,
@@ -150,13 +3601,13 @@ var g = class {
150
3601
  });
151
3602
  }
152
3603
  };
153
- function y(t) {
3604
+ function Rt(t) {
154
3605
  if (t.error) throw t.error;
155
3606
  return e(t.count !== null, "Response does not contain a count. Make sure to set the `count` option in the request."), t;
156
3607
  }
157
3608
  //#endregion
158
3609
  //#region lib/filter.ts
159
- var b = [
3610
+ var zt = [
160
3611
  "eq",
161
3612
  "neq",
162
3613
  "gt",
@@ -182,17 +3633,17 @@ var b = [
182
3633
  "nxr",
183
3634
  "nxl",
184
3635
  "adj"
185
- ], x = ["and", "or"], S = ",", C = "~", w = (e) => (n = {}) => {
3636
+ ], Bt = ["and", "or"], Vt = ",", Ht = "~", Ut = (e) => (n = {}) => {
186
3637
  let r = (e) => n[e] ?? e, i = Object.keys(e.shape);
187
3638
  return t.string().transform((e, t) => {
188
3639
  try {
189
- return A(e, i, r);
3640
+ return qt(e, i, r);
190
3641
  } catch (n) {
191
3642
  return t.addIssue({
192
3643
  code: "custom",
193
3644
  input: e,
194
3645
  message: n instanceof Error ? n.message : void 0,
195
- params: n instanceof s ? {
3646
+ params: n instanceof Ot ? {
196
3647
  expression: n.expression,
197
3648
  format: n.format
198
3649
  } : void 0
@@ -200,26 +3651,26 @@ var b = [
200
3651
  }
201
3652
  });
202
3653
  };
203
- function T(e) {
3654
+ function Wt(e) {
204
3655
  return e.startsWith("not.") ? e.slice(4) : `not.${e}`;
205
3656
  }
206
- function E(e) {
3657
+ function Gt(e) {
207
3658
  return {
208
3659
  ...e,
209
- op: T(e.op)
3660
+ op: Wt(e.op)
210
3661
  };
211
3662
  }
212
- function D(e, t = (e) => e) {
3663
+ function Z(e, t = (e) => e) {
213
3664
  if (e.type === "logical") {
214
- let n = e.args.map((e) => D(e, t));
3665
+ let n = e.args.map((e) => Z(e, t));
215
3666
  return `${e.op}(${n})`;
216
3667
  }
217
3668
  return `${t(e.key)}.${e.op}.${e.value}`;
218
3669
  }
219
- function O(e, t = (e) => e, n = "~") {
220
- return e.map((e) => D(e, t)).join(n);
3670
+ function Kt(e, t = (e) => e, n = "~") {
3671
+ return e.map((e) => Z(e, t)).join(n);
221
3672
  }
222
- function k(t, n = [], r = (e) => e) {
3673
+ function Q(t, n = [], r = (e) => e) {
223
3674
  function i(e) {
224
3675
  let t = [], n = 0, r = "", i = !1;
225
3676
  for (let a of e) a === "\"" ? (i = !i, r += a) : a === "(" && !i ? (n++, r += a) : a === ")" && !i ? (n--, r += a) : a === "," && n === 0 && !i ? (t.push(r.trim()), r = "") : r += a;
@@ -229,57 +3680,57 @@ function k(t, n = [], r = (e) => e) {
229
3680
  if (t.startsWith("and(")) return {
230
3681
  type: "logical",
231
3682
  op: "and",
232
- args: i(t.slice(4, -1)).map((e) => k(e, n, r))
3683
+ args: i(t.slice(4, -1)).map((e) => Q(e, n, r))
233
3684
  };
234
3685
  if (t.startsWith("or(")) return {
235
3686
  type: "logical",
236
3687
  op: "or",
237
- args: i(t.slice(3, -1)).map((e) => k(e, n, r))
3688
+ args: i(t.slice(3, -1)).map((e) => Q(e, n, r))
238
3689
  };
239
3690
  if (t.startsWith("not.and(")) return {
240
3691
  type: "logical",
241
3692
  op: "not.and",
242
- args: i(t.slice(8, -1)).map((e) => k(e, n, r))
3693
+ args: i(t.slice(8, -1)).map((e) => Q(e, n, r))
243
3694
  };
244
3695
  if (t.startsWith("not.or(")) return {
245
3696
  type: "logical",
246
3697
  op: "not.or",
247
- args: i(t.slice(7, -1)).map((e) => k(e, n, r))
3698
+ args: i(t.slice(7, -1)).map((e) => Q(e, n, r))
248
3699
  };
249
3700
  }
250
- let a = `^(${n.length === 0 ? "[a-zA-Z_][a-zA-Z0-9_]*" : n.join("|")})\\.((?:not\\.)?(?:${b.join("|")}))\\.(.+)$`, o = new RegExp(a).exec(t);
251
- if (!o) throw new s(`Invalid filter expression '${t}'`, {
3701
+ let a = `^(${n.length === 0 ? "[a-zA-Z_][a-zA-Z0-9_]*" : n.join("|")})\\.((?:not\\.)?(?:${zt.join("|")}))\\.(.+)$`, o = new RegExp(a).exec(t);
3702
+ if (!o) throw new Ot(`Invalid filter expression '${t}'`, {
252
3703
  expression: t,
253
3704
  format: {
254
3705
  syntax: "key.(not.)op.value",
255
3706
  keys: n.length === 0 ? "*" : n,
256
- operators: b
3707
+ operators: zt
257
3708
  }
258
3709
  });
259
- let [, c, l, u] = o;
3710
+ let [, s, c, l] = o;
260
3711
  return {
261
3712
  type: "condition",
262
- key: r(c),
263
- op: l,
264
- value: e.defined(u)
3713
+ key: r(s),
3714
+ op: c,
3715
+ value: e.defined(l)
265
3716
  };
266
3717
  }
267
- function A(e, t = [], n = (e) => e, r = "~") {
268
- return e.length === 0 ? [] : e.split(r).map((e) => k(e, t, n));
3718
+ function qt(e, t = [], n = (e) => e, r = "~") {
3719
+ return e.length === 0 ? [] : e.split(r).map((e) => Q(e, t, n));
269
3720
  }
270
3721
  //#endregion
271
3722
  //#region lib/postgrest.ts
272
- var j = class t extends r.PostgrestFilterBuilder {
3723
+ var $ = class t extends n.PostgrestFilterBuilder {
273
3724
  pagination;
274
3725
  constructor(e) {
275
3726
  super(e);
276
3727
  }
277
3728
  select(e = "*") {
278
- return new t(super.select(f(e).join(",")));
3729
+ return new t(super.select(Y(e).join(",")));
279
3730
  }
280
3731
  where(e) {
281
3732
  if (e.type === "logical") {
282
- let t = e.args.map((e) => D(e)).join(",");
3733
+ let t = e.args.map((e) => Z(e)).join(",");
283
3734
  this.url.searchParams.append(e.op, `(${t})`);
284
3735
  } else this.url.searchParams.append(e.key, `${e.op}.${e.value}`);
285
3736
  return this;
@@ -317,70 +3768,70 @@ var j = class t extends r.PostgrestFilterBuilder {
317
3768
  return t;
318
3769
  });
319
3770
  }
320
- }, M = class {
3771
+ }, Jt = class {
321
3772
  builder;
322
3773
  constructor(e) {
323
3774
  this.builder = e;
324
3775
  }
325
3776
  select(e = "*", t) {
326
- return new j(this.builder.select(f(e).join(","), t));
3777
+ return new $(this.builder.select(Y(e).join(","), t));
327
3778
  }
328
3779
  count(e = "exact") {
329
- return new j(this.select("*", {
3780
+ return new $(this.select("*", {
330
3781
  count: e,
331
3782
  head: !0
332
3783
  }));
333
3784
  }
334
3785
  insert(e, t) {
335
- return new j(this.builder.insert(e, t));
3786
+ return new $(this.builder.insert(e, t));
336
3787
  }
337
3788
  upsert(e, { onConflict: t, ...n } = {}) {
338
- return new j(this.builder.upsert(e, {
339
- onConflict: f(t).join(","),
3789
+ return new $(this.builder.upsert(e, {
3790
+ onConflict: Y(t).join(","),
340
3791
  ...n
341
3792
  }));
342
3793
  }
343
3794
  update(e, t) {
344
- return new j(this.builder.update(e, t));
3795
+ return new $(this.builder.update(e, t));
345
3796
  }
346
3797
  delete() {
347
- return new j(this.builder.delete());
3798
+ return new $(this.builder.delete());
348
3799
  }
349
- }, N = class {
3800
+ }, Yt = class {
350
3801
  client;
351
3802
  constructor(e) {
352
3803
  this.client = e;
353
3804
  }
354
3805
  from(e) {
355
- return new M(this.client.from(e));
3806
+ return new Jt(this.client.from(e));
356
3807
  }
357
3808
  rpc(e, t, n) {
358
- return new j(this.client.rpc(e, t, n));
3809
+ return new $(this.client.rpc(e, t, n));
359
3810
  }
360
- }, P = class {
3811
+ }, Xt = class {
361
3812
  supabase;
362
3813
  constructor({ supabase: e }) {
363
3814
  this.supabase = e;
364
3815
  }
365
3816
  schema(e) {
366
- return new N(this.supabase.schema(e));
3817
+ return new Yt(this.supabase.schema(e));
367
3818
  }
368
3819
  relation(e, t) {
369
- return new g({
3820
+ return new X({
370
3821
  database: this,
371
3822
  schema: e,
372
3823
  relation: t
373
3824
  });
374
3825
  }
375
3826
  table(e, t) {
376
- return new _({
3827
+ return new It({
377
3828
  database: this,
378
3829
  schema: e,
379
3830
  table: t
380
3831
  });
381
3832
  }
382
3833
  view(e, t) {
383
- return new v({
3834
+ return new Lt({
384
3835
  database: this,
385
3836
  schema: e,
386
3837
  view: t
@@ -389,15 +3840,15 @@ var j = class t extends r.PostgrestFilterBuilder {
389
3840
  };
390
3841
  //#endregion
391
3842
  //#region lib/storage.ts
392
- function F(e) {
3843
+ function Zt(e) {
393
3844
  return e.bucket !== void 0 && e.path !== void 0;
394
3845
  }
395
- function I(e) {
3846
+ function Qt(e) {
396
3847
  return e.fileId !== void 0 && e.bucket !== void 0;
397
3848
  }
398
3849
  //#endregion
399
3850
  //#region lib/storage-service.ts
400
- var L = class {
3851
+ var $t = class {
401
3852
  client;
402
3853
  database;
403
3854
  constructor({ client: e, database: t }) {
@@ -417,8 +3868,8 @@ var L = class {
417
3868
  return n;
418
3869
  }
419
3870
  async getFileStorageLocation(t) {
420
- if (I(t)) return t;
421
- if (F(t)) {
3871
+ if (Qt(t)) return t;
3872
+ if (Zt(t)) {
422
3873
  let { id: e } = await this.getFileObject(t);
423
3874
  return {
424
3875
  fileId: e,
@@ -426,7 +3877,7 @@ var L = class {
426
3877
  };
427
3878
  }
428
3879
  let { fileId: n } = t, r = await this.files.get(n, ["bucket_id", "path_tokens"]);
429
- if (!r) throw new a(`File with ID ${n} not found`, { fileId: n });
3880
+ if (!r) throw new Dt(`File with ID ${n} not found`, { fileId: n });
430
3881
  return {
431
3882
  fileId: n,
432
3883
  bucket: e.notNull(r.bucket_id, "bucket_id must not be null"),
@@ -457,7 +3908,7 @@ var L = class {
457
3908
  async assertExistsFile(e) {
458
3909
  let { bucket: t, path: n } = await this.getFileStorageLocation(e), { data: r, error: i } = await this.client.from(t).exists(n);
459
3910
  if (i) throw i;
460
- if (!r) throw new a(`File not found in bucket '${t}' at path '${n}'`, {
3911
+ if (!r) throw new Dt(`File not found in bucket '${t}' at path '${n}'`, {
461
3912
  bucket: t,
462
3913
  path: n
463
3914
  });
@@ -474,7 +3925,7 @@ var L = class {
474
3925
  async downloadFile(e) {
475
3926
  let { fileId: t, bucket: n, path: r, properties: i } = await this.getFileInfo(e), { data: a, error: o } = await this.client.from(n).download(r);
476
3927
  if (o) throw o;
477
- let [, s] = d(r);
3928
+ let [, s] = Mt(r);
478
3929
  return {
479
3930
  fileId: t,
480
3931
  bucket: n,
@@ -486,7 +3937,7 @@ var L = class {
486
3937
  let n = t.filter((e) => "fileId" in e).map((e) => e.fileId), r = (await this.files.query.select(["bucket_id", "path_tokens"]).containedBy("id", n).throwOnError()).data.map(({ bucket_id: t, path_tokens: n }) => ({
487
3938
  bucket: e.notNull(t, "bucket_id must not be null"),
488
3939
  path: e.notNull(n, "path_tokens must not be null").join("/")
489
- })), i = h(p(t.filter((e) => F(e)).concat(r), (e) => e.bucket)).map(([e, t]) => ({
3940
+ })), i = Ft(Nt(t.filter((e) => Zt(e)).concat(r), (e) => e.bucket)).map(([e, t]) => ({
490
3941
  bucket: e,
491
3942
  paths: t.map((e) => e.path)
492
3943
  }));
@@ -501,4 +3952,4 @@ var L = class {
501
3952
  }
502
3953
  };
503
3954
  //#endregion
504
- export { g as DataService, P as DatabaseService, a as FileNotFoundError, o as FileNotSupportedError, w as Filter, C as FilterChainSeparator, b as FilterOp, x as LogicalOp, S as LogicalOpSeparator, s as ParseError, N as PostgrestClient, l as PostgrestErrorInterface, j as PostgrestFilterBuilder, M as PostgrestQueryBuilder, c as RecordNotFoundError, L as StorageService, _ as TableDataService, i as TracedError, v as ViewDataService, y as assertCounted, f as coerceArray, O as encodeFilter, D as encodeFilterNode, h as entries, p as groupBy, u as isDatabaseApiError, E as negateFilterNode, T as negateOp, k as parseFilterExpression, A as parseFilterExpressionChain, m as removeElement, d as splitPath };
3955
+ export { X as DataService, Xt as DatabaseService, Dt as FileNotFoundError, Ut as Filter, Ht as FilterChainSeparator, zt as FilterOp, Bt as LogicalOp, Vt as LogicalOpSeparator, Ot as ParseError, Yt as PostgrestClient, At as PostgrestErrorInterface, $ as PostgrestFilterBuilder, Jt as PostgrestQueryBuilder, kt as RecordNotFoundError, $t as StorageService, It as TableDataService, J as TracedError, Lt as ViewDataService, Rt as assertCounted, Y as coerceArray, Kt as encodeFilter, Z as encodeFilterNode, Ft as entries, Nt as groupBy, jt as isDatabaseApiError, Gt as negateFilterNode, Wt as negateOp, Q as parseFilterExpression, qt as parseFilterExpressionChain, Pt as removeElement, Mt as splitPath };