This commit is contained in:
BenitoBB 2025-04-25 17:40:09 -06:00
parent 1d6f60d86a
commit 1bee7e8ea8
710 changed files with 109446 additions and 111 deletions
diplomas/src
node_modules

View File

@ -0,0 +1,7 @@
// lib/supabaseClient.js
import { createClient } from '@supabase/supabase-js';
const supabaseUrl = 'https://spvzldjtkrjnbhpqorjx.supabase.co';
const supabaseAnonKey = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InNwdnpsZGp0a3JqbmJocHFvcmp4Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDU0MTgxNTAsImV4cCI6MjA2MDk5NDE1MH0.KqW1jwctYi0oYx74I-ao6ghsM5YtxWNKolz9aVHfG8Y';
export const supabase = createClient(supabaseUrl, supabaseAnonKey);

View File

@ -0,0 +1,69 @@
export default function Alumnos() {
return (
<div className="p-6 max-w-xl mx-auto space-y-6">
<h1 className="text-2xl font-bold">Alta de Alumnos</h1>
<form className="space-y-4">
{/* Nombre */}
<div>
<label className="block font-medium">Nombre del alumno</label>
<input
type="text"
placeholder="Juan Pérez"
className="w-full px-4 py-2 border rounded-md shadow-sm"
/>
</div>
{/* Correo */}
<div>
<label className="block font-medium">Correo electrónico</label>
<input
type="email"
placeholder="correo@ejemplo.com"
className="w-full px-4 py-2 border rounded-md shadow-sm"
/>
</div>
{/* Curso */}
<div>
<label className="block font-medium">Curso</label>
<select className="w-full px-4 py-2 border rounded-md shadow-sm">
<option>Selecciona un curso</option>
<option>Curso 1</option>
<option>Curso 2</option>
</select>
</div>
{/* Tipo de diploma */}
<div>
<label className="block font-medium">Tipo de Diploma</label>
<select className="w-full px-4 py-2 border rounded-md shadow-sm">
<option>Píldora</option>
<option>Inyección</option>
<option>Micro grado</option>
</select>
</div>
{/* Términos y condiciones */}
<div className="flex items-center space-x-2">
<input type="checkbox" id="terminos" className="w-4 h-4" />
<label htmlFor="terminos">
Acepto los{" "}
<a href="/terminos" target="_blank" className="underline text-blue-600">
términos y condiciones
</a>
</label>
</div>
{/* Botón de enviar */}
<button
type="submit"
className="px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition"
>
Registrar alumno
</button>
</form>
</div>
);
}

View File

@ -1,115 +1,17 @@
import Image from "next/image";
import { Geist, Geist_Mono } from "next/font/google";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
import Link from 'next/link';
import React from 'react';
export default function Home() {
return (
<div
className={`${geistSans.className} ${geistMono.className} grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]`}
>
<main className="flex flex-col gap-[32px] row-start-2 items-center sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={180}
height={38}
priority
/>
<ol className="list-inside list-decimal text-sm/6 text-center sm:text-left font-[family-name:var(--font-geist-mono)]">
<li className="mb-2 tracking-[-.01em]">
Get started by editing{" "}
<code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-[family-name:var(--font-geist-mono)] font-semibold">
src/pages/index.js
</code>
.
</li>
<li className="tracking-[-.01em]">
Save and see your changes instantly.
</li>
</ol>
<div className="flex gap-4 items-center flex-col sm:flex-row">
<a
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:w-auto"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=default-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={20}
height={20}
/>
Deploy now
</a>
<a
className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 w-full sm:w-auto md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=default-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Read our docs
</a>
</div>
</main>
<footer className="row-start-3 flex gap-[24px] flex-wrap items-center justify-center">
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=default-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/file.svg"
alt="File icon"
width={16}
height={16}
/>
Learn
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=default-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/window.svg"
alt="Window icon"
width={16}
height={16}
/>
Examples
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org?utm_source=create-next-app&utm_medium=default-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/globe.svg"
alt="Globe icon"
width={16}
height={16}
/>
Go to nextjs.org
</a>
</footer>
<div>
<h1>Welcome to the Diploma Generator</h1>
<Link href="/alumnos" className="text-blue-500 hover:underline">
Go to Alumnos Page
</Link>
<br></br>
<Link href="/diplomas" className="text-blue-500 hover:underline">
Go to Diplomas Page
</Link>
</div>
);
}
}

View File

139
node_modules/.package-lock.json generated vendored Normal file
View File

@ -0,0 +1,139 @@
{
"name": "SIDAC",
"lockfileVersion": 3,
"requires": true,
"packages": {
"node_modules/@supabase/auth-js": {
"version": "2.69.1",
"resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.69.1.tgz",
"integrity": "sha512-FILtt5WjCNzmReeRLq5wRs3iShwmnWgBvxHfqapC/VoljJl+W8hDAyFmf1NVw3zH+ZjZ05AKxiKxVeb0HNWRMQ==",
"dependencies": {
"@supabase/node-fetch": "^2.6.14"
}
},
"node_modules/@supabase/functions-js": {
"version": "2.4.4",
"resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.4.4.tgz",
"integrity": "sha512-WL2p6r4AXNGwop7iwvul2BvOtuJ1YQy8EbOd0dhG1oN1q8el/BIRSFCFnWAMM/vJJlHWLi4ad22sKbKr9mvjoA==",
"dependencies": {
"@supabase/node-fetch": "^2.6.14"
}
},
"node_modules/@supabase/node-fetch": {
"version": "2.6.15",
"resolved": "https://registry.npmjs.org/@supabase/node-fetch/-/node-fetch-2.6.15.tgz",
"integrity": "sha512-1ibVeYUacxWYi9i0cf5efil6adJ9WRyZBLivgjs+AUpewx1F3xPi7gLgaASI2SmIQxPoCEjAsLAzKPgMJVgOUQ==",
"dependencies": {
"whatwg-url": "^5.0.0"
},
"engines": {
"node": "4.x || >=6.0.0"
}
},
"node_modules/@supabase/postgrest-js": {
"version": "1.19.4",
"resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-1.19.4.tgz",
"integrity": "sha512-O4soKqKtZIW3olqmbXXbKugUtByD2jPa8kL2m2c1oozAO11uCcGrRhkZL0kVxjBLrXHE0mdSkFsMj7jDSfyNpw==",
"dependencies": {
"@supabase/node-fetch": "^2.6.14"
}
},
"node_modules/@supabase/realtime-js": {
"version": "2.11.2",
"resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.11.2.tgz",
"integrity": "sha512-u/XeuL2Y0QEhXSoIPZZwR6wMXgB+RQbJzG9VErA3VghVt7uRfSVsjeqd7m5GhX3JR6dM/WRmLbVR8URpDWG4+w==",
"dependencies": {
"@supabase/node-fetch": "^2.6.14",
"@types/phoenix": "^1.5.4",
"@types/ws": "^8.5.10",
"ws": "^8.18.0"
}
},
"node_modules/@supabase/storage-js": {
"version": "2.7.1",
"resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.7.1.tgz",
"integrity": "sha512-asYHcyDR1fKqrMpytAS1zjyEfvxuOIp1CIXX7ji4lHHcJKqyk+sLl/Vxgm4sN6u8zvuUtae9e4kDxQP2qrwWBA==",
"dependencies": {
"@supabase/node-fetch": "^2.6.14"
}
},
"node_modules/@supabase/supabase-js": {
"version": "2.49.4",
"resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.49.4.tgz",
"integrity": "sha512-jUF0uRUmS8BKt37t01qaZ88H9yV1mbGYnqLeuFWLcdV+x1P4fl0yP9DGtaEhFPZcwSom7u16GkLEH9QJZOqOkw==",
"dependencies": {
"@supabase/auth-js": "2.69.1",
"@supabase/functions-js": "2.4.4",
"@supabase/node-fetch": "2.6.15",
"@supabase/postgrest-js": "1.19.4",
"@supabase/realtime-js": "2.11.2",
"@supabase/storage-js": "2.7.1"
}
},
"node_modules/@types/node": {
"version": "22.14.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.14.1.tgz",
"integrity": "sha512-u0HuPQwe/dHrItgHHpmw3N2fYCR6x4ivMNbPHRkBVP4CvN+kiRrKHWk3i8tXiO/joPwXLMYvF9TTF0eqgHIuOw==",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/@types/phoenix": {
"version": "1.6.6",
"resolved": "https://registry.npmjs.org/@types/phoenix/-/phoenix-1.6.6.tgz",
"integrity": "sha512-PIzZZlEppgrpoT2QgbnDU+MMzuR6BbCjllj0bM70lWoejMeNJAxCchxnv7J3XFkI8MpygtRpzXrIlmWUBclP5A=="
},
"node_modules/@types/ws": {
"version": "8.18.1",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
"integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="
},
"node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="
},
"node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"dependencies": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"node_modules/ws": {
"version": "8.18.1",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.1.tgz",
"integrity": "sha512-RKW2aJZMXeMxVpnZ6bck+RswznaxmzdULiBr6KY7XkTnW8uvt0iT9H5DkHUChXrc+uurzwa0rVI16n/Xzjdz1w==",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
}
}

21
node_modules/@supabase/auth-js/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Supabase
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

50
node_modules/@supabase/auth-js/README.md generated vendored Normal file
View File

@ -0,0 +1,50 @@
# `auth-js`
An isomorphic JavaScript client library for the [Supabase Auth](https://github.com/supabase/auth) API.
## Docs
- Using `auth-js`: https://supabase.com/docs/reference/javascript/auth-signup
- TypeDoc: https://supabase.github.io/auth-js/v2
## Quick start
Install
```bash
npm install --save @supabase/auth-js
```
Usage
```js
import { AuthClient } from '@supabase/auth-js'
const GOTRUE_URL = 'http://localhost:9999'
const auth = new AuthClient({ url: GOTRUE_URL })
```
- `signUp()`: https://supabase.io/docs/reference/javascript/auth-signup
- `signIn()`: https://supabase.io/docs/reference/javascript/auth-signin
- `signOut()`: https://supabase.io/docs/reference/javascript/auth-signout
### Custom `fetch` implementation
`auth-js` uses the [`cross-fetch`](https://www.npmjs.com/package/cross-fetch) library to make HTTP requests, but an alternative `fetch` implementation can be provided as an option. This is most useful in environments where `cross-fetch` is not compatible, for instance Cloudflare Workers:
```js
import { AuthClient } from '@supabase/auth-js'
const AUTH_URL = 'http://localhost:9999'
const auth = new AuthClient({ url: AUTH_URL, fetch: fetch })
```
## Sponsors
We are building the features of Firebase using enterprise-grade, open source products. We support existing communities wherever possible, and if the products dont exist we build them and open source them ourselves.
[![New Sponsor](https://user-images.githubusercontent.com/10214025/90518111-e74bbb00-e198-11ea-8f88-c9e3c1aa4b5b.png)](https://github.com/sponsors/supabase)
![Watch this repo](https://gitcdn.xyz/repo/supabase/monorepo/master/web/static/watch-repo.gif 'Watch this repo')

View File

@ -0,0 +1,4 @@
import GoTrueAdminApi from './GoTrueAdminApi';
declare const AuthAdminApi: typeof GoTrueAdminApi;
export default AuthAdminApi;
//# sourceMappingURL=AuthAdminApi.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"AuthAdminApi.d.ts","sourceRoot":"","sources":["../../src/AuthAdminApi.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAE7C,QAAA,MAAM,YAAY,uBAAiB,CAAA;AAEnC,eAAe,YAAY,CAAA"}

View File

@ -0,0 +1,9 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const GoTrueAdminApi_1 = __importDefault(require("./GoTrueAdminApi"));
const AuthAdminApi = GoTrueAdminApi_1.default;
exports.default = AuthAdminApi;
//# sourceMappingURL=AuthAdminApi.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"AuthAdminApi.js","sourceRoot":"","sources":["../../src/AuthAdminApi.ts"],"names":[],"mappings":";;;;;AAAA,sEAA6C;AAE7C,MAAM,YAAY,GAAG,wBAAc,CAAA;AAEnC,kBAAe,YAAY,CAAA"}

View File

@ -0,0 +1,4 @@
import GoTrueClient from './GoTrueClient';
declare const AuthClient: typeof GoTrueClient;
export default AuthClient;
//# sourceMappingURL=AuthClient.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"AuthClient.d.ts","sourceRoot":"","sources":["../../src/AuthClient.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,MAAM,gBAAgB,CAAA;AAEzC,QAAA,MAAM,UAAU,qBAAe,CAAA;AAE/B,eAAe,UAAU,CAAA"}

View File

@ -0,0 +1,9 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const GoTrueClient_1 = __importDefault(require("./GoTrueClient"));
const AuthClient = GoTrueClient_1.default;
exports.default = AuthClient;
//# sourceMappingURL=AuthClient.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"AuthClient.js","sourceRoot":"","sources":["../../src/AuthClient.ts"],"names":[],"mappings":";;;;;AAAA,kEAAyC;AAEzC,MAAM,UAAU,GAAG,sBAAY,CAAA;AAE/B,kBAAe,UAAU,CAAA"}

View File

@ -0,0 +1,99 @@
import { Fetch } from './lib/fetch';
import { AdminUserAttributes, GenerateLinkParams, GenerateLinkResponse, Pagination, User, UserResponse, GoTrueAdminMFAApi, PageParams } from './lib/types';
import { AuthError } from './lib/errors';
export default class GoTrueAdminApi {
/** Contains all MFA administration methods. */
mfa: GoTrueAdminMFAApi;
protected url: string;
protected headers: {
[key: string]: string;
};
protected fetch: Fetch;
constructor({ url, headers, fetch, }: {
url: string;
headers?: {
[key: string]: string;
};
fetch?: Fetch;
});
/**
* Removes a logged-in session.
* @param jwt A valid, logged-in JWT.
* @param scope The logout sope.
*/
signOut(jwt: string, scope?: 'global' | 'local' | 'others'): Promise<{
data: null;
error: AuthError | null;
}>;
/**
* Sends an invite link to an email address.
* @param email The email address of the user.
* @param options Additional options to be included when inviting.
*/
inviteUserByEmail(email: string, options?: {
/** A custom data object to store additional metadata about the user. This maps to the `auth.users.user_metadata` column. */
data?: object;
/** The URL which will be appended to the email link sent to the user's email address. Once clicked the user will end up on this URL. */
redirectTo?: string;
}): Promise<UserResponse>;
/**
* Generates email links and OTPs to be sent via a custom email provider.
* @param email The user's email.
* @param options.password User password. For signup only.
* @param options.data Optional user metadata. For signup only.
* @param options.redirectTo The redirect url which should be appended to the generated link
*/
generateLink(params: GenerateLinkParams): Promise<GenerateLinkResponse>;
/**
* Creates a new user.
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
createUser(attributes: AdminUserAttributes): Promise<UserResponse>;
/**
* Get a list of users.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
* @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results.
*/
listUsers(params?: PageParams): Promise<{
data: {
users: User[];
aud: string;
} & Pagination;
error: null;
} | {
data: {
users: [];
};
error: AuthError;
}>;
/**
* Get user by id.
*
* @param uid The user's unique identifier
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
getUserById(uid: string): Promise<UserResponse>;
/**
* Updates the user data.
*
* @param attributes The data you want to update.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
updateUserById(uid: string, attributes: AdminUserAttributes): Promise<UserResponse>;
/**
* Delete a user. Requires a `service_role` key.
*
* @param id The user id you want to remove.
* @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible.
* Defaults to false for backward compatibility.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
deleteUser(id: string, shouldSoftDelete?: boolean): Promise<UserResponse>;
private _listFactors;
private _deleteFactor;
}
//# sourceMappingURL=GoTrueAdminApi.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"GoTrueAdminApi.d.ts","sourceRoot":"","sources":["../../src/GoTrueAdminApi.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EAKN,MAAM,aAAa,CAAA;AAEpB,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,oBAAoB,EACpB,UAAU,EACV,IAAI,EACJ,YAAY,EACZ,iBAAiB,EAKjB,UAAU,EACX,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,SAAS,EAAe,MAAM,cAAc,CAAA;AAErD,MAAM,CAAC,OAAO,OAAO,cAAc;IACjC,+CAA+C;IAC/C,GAAG,EAAE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,EAAE,EAAE,CAAA;SAAE,CAAC;QAAC,KAAK,EAAE,SAAS,CAAA;KAAE,CAC5C;IAmCD;;;;;;OAMG;IACG,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;IAerD;;;;;;OAMG;IACG,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,mBAAmB,GAAG,OAAO,CAAC,YAAY,CAAC;IAgBzF;;;;;;;;OAQG;IACG,UAAU,CAAC,EAAE,EAAE,MAAM,EAAE,gBAAgB,UAAQ,GAAG,OAAO,CAAC,YAAY,CAAC;YAkB/D,YAAY;YAyBZ,aAAa;CAsB5B"}

View File

@ -0,0 +1,268 @@
"use strict";
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
const fetch_1 = require("./lib/fetch");
const helpers_1 = require("./lib/helpers");
const errors_1 = require("./lib/errors");
class GoTrueAdminApi {
constructor({ url = '', headers = {}, fetch, }) {
this.url = url;
this.headers = headers;
this.fetch = (0, helpers_1.resolveFetch)(fetch);
this.mfa = {
listFactors: this._listFactors.bind(this),
deleteFactor: this._deleteFactor.bind(this),
};
}
/**
* Removes a logged-in session.
* @param jwt A valid, logged-in JWT.
* @param scope The logout sope.
*/
async signOut(jwt, scope = 'global') {
try {
await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/logout?scope=${scope}`, {
headers: this.headers,
jwt,
noResolveJson: true,
});
return { data: null, error: null };
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* Sends an invite link to an email address.
* @param email The email address of the user.
* @param options Additional options to be included when inviting.
*/
async inviteUserByEmail(email, options = {}) {
try {
return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/invite`, {
body: { email, data: options.data },
headers: this.headers,
redirectTo: options.redirectTo,
xform: fetch_1._userResponse,
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
/**
* Generates email links and OTPs to be sent via a custom email provider.
* @param email The user's email.
* @param options.password User password. For signup only.
* @param options.data Optional user metadata. For signup only.
* @param options.redirectTo The redirect url which should be appended to the generated link
*/
async generateLink(params) {
try {
const { options } = params, rest = __rest(params, ["options"]);
const body = Object.assign(Object.assign({}, rest), options);
if ('newEmail' in rest) {
// replace newEmail with new_email in request body
body.new_email = rest === null || rest === void 0 ? void 0 : rest.newEmail;
delete body['newEmail'];
}
return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/generate_link`, {
body: body,
headers: this.headers,
xform: fetch_1._generateLinkResponse,
redirectTo: options === null || options === void 0 ? void 0 : options.redirectTo,
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return {
data: {
properties: null,
user: null,
},
error,
};
}
throw error;
}
}
// User Admin API
/**
* Creates a new user.
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
async createUser(attributes) {
try {
return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/users`, {
body: attributes,
headers: this.headers,
xform: fetch_1._userResponse,
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
/**
* Get a list of users.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
* @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results.
*/
async listUsers(params) {
var _a, _b, _c, _d, _e, _f, _g;
try {
const pagination = { nextPage: null, lastPage: 0, total: 0 };
const response = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users`, {
headers: this.headers,
noResolveJson: true,
query: {
page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '',
per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '',
},
xform: fetch_1._noResolveJsonResponse,
});
if (response.error)
throw response.error;
const users = await response.json();
const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0;
const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : [];
if (links.length > 0) {
links.forEach((link) => {
const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1));
const rel = JSON.parse(link.split(';')[1].split('=')[1]);
pagination[`${rel}Page`] = page;
});
pagination.total = parseInt(total);
}
return { data: Object.assign(Object.assign({}, users), pagination), error: null };
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: { users: [] }, error };
}
throw error;
}
}
/**
* Get user by id.
*
* @param uid The user's unique identifier
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
async getUserById(uid) {
try {
return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users/${uid}`, {
headers: this.headers,
xform: fetch_1._userResponse,
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
/**
* Updates the user data.
*
* @param attributes The data you want to update.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
async updateUserById(uid, attributes) {
try {
return await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/admin/users/${uid}`, {
body: attributes,
headers: this.headers,
xform: fetch_1._userResponse,
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
/**
* Delete a user. Requires a `service_role` key.
*
* @param id The user id you want to remove.
* @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible.
* Defaults to false for backward compatibility.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
async deleteUser(id, shouldSoftDelete = false) {
try {
return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, {
headers: this.headers,
body: {
should_soft_delete: shouldSoftDelete,
},
xform: fetch_1._userResponse,
});
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
async _listFactors(params) {
try {
const { data, error } = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users/${params.userId}/factors`, {
headers: this.headers,
xform: (factors) => {
return { data: { factors }, error: null };
},
});
return { data, error };
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: null, error };
}
throw error;
}
}
async _deleteFactor(params) {
try {
const data = await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/users/${params.userId}/factors/${params.id}`, {
headers: this.headers,
});
return { data, error: null };
}
catch (error) {
if ((0, errors_1.isAuthError)(error)) {
return { data: null, error };
}
throw error;
}
}
}
exports.default = GoTrueAdminApi;
//# sourceMappingURL=GoTrueAdminApi.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,474 @@
import GoTrueAdminApi from './GoTrueAdminApi';
import { AuthError } from './lib/errors';
import { Fetch } from './lib/fetch';
import { Deferred } from './lib/helpers';
import type { AuthChangeEvent, AuthResponse, AuthTokenResponse, AuthTokenResponsePassword, AuthOtpResponse, CallRefreshTokenResult, GoTrueClientOptions, InitializeResult, OAuthResponse, SSOResponse, Session, SignInWithIdTokenCredentials, SignInWithOAuthCredentials, SignInWithPasswordCredentials, SignInWithPasswordlessCredentials, SignUpWithPasswordCredentials, SignInWithSSO, SignOut, Subscription, SupportedStorage, UserAttributes, UserResponse, VerifyOtpParams, GoTrueMFAApi, ResendParams, AuthFlowType, LockFunc, UserIdentity, SignInAnonymouslyCredentials, JWK, JwtPayload, JwtHeader } from './lib/types';
export default class GoTrueClient {
private static nextInstanceID;
private instanceID;
/**
* Namespace for the GoTrue admin methods.
* These methods should only be used in a trusted server-side environment.
*/
admin: GoTrueAdminApi;
/**
* Namespace for the MFA methods.
*/
mfa: GoTrueMFAApi;
/**
* The storage key used to identify the values saved in localStorage
*/
protected storageKey: string;
protected flowType: AuthFlowType;
/**
* The JWKS used for verifying asymmetric JWTs
*/
protected jwks: {
keys: JWK[];
};
protected jwks_cached_at: number;
protected autoRefreshToken: boolean;
protected persistSession: boolean;
protected storage: SupportedStorage;
protected memoryStorage: {
[key: string]: string;
} | null;
protected stateChangeEmitters: Map<string, Subscription>;
protected autoRefreshTicker: ReturnType<typeof setInterval> | null;
protected visibilityChangedCallback: (() => Promise<any>) | null;
protected refreshingDeferred: Deferred<CallRefreshTokenResult> | null;
/**
* Keeps track of the async client initialization.
* When null or not yet resolved the auth state is `unknown`
* Once resolved the the auth state is known and it's save to call any further client methods.
* Keep extra care to never reject or throw uncaught errors
*/
protected initializePromise: Promise<InitializeResult> | null;
protected detectSessionInUrl: boolean;
protected url: string;
protected headers: {
[key: string]: string;
};
protected hasCustomAuthorizationHeader: boolean;
protected suppressGetSessionWarning: boolean;
protected fetch: Fetch;
protected lock: LockFunc;
protected lockAcquired: boolean;
protected pendingInLock: Promise<any>[];
/**
* Used to broadcast state change events to other tabs listening.
*/
protected broadcastChannel: BroadcastChannel | null;
protected logDebugMessages: boolean;
protected logger: (message: string, ...args: any[]) => void;
/**
* Create a new client for use in the browser.
*/
constructor(options: GoTrueClientOptions);
private _debug;
/**
* Initializes the client session either from the url or from storage.
* This method is automatically called when instantiating the client, but should also be called
* manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc).
*/
initialize(): Promise<InitializeResult>;
/**
* IMPORTANT:
* 1. Never throw in this method, as it is called from the constructor
* 2. Never return a session from this method as it would be cached over
* the whole lifetime of the client
*/
private _initialize;
/**
* Creates a new anonymous user.
*
* @returns A session where the is_anonymous claim in the access token JWT set to true
*/
signInAnonymously(credentials?: SignInAnonymouslyCredentials): Promise<AuthResponse>;
/**
* Creates a new user.
*
* Be aware that if a user account exists in the system you may get back an
* error message that attempts to hide this information from the user.
* This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled.
*
* @returns A logged-in session if the server has "autoconfirm" ON
* @returns A user if the server has "autoconfirm" OFF
*/
signUp(credentials: SignUpWithPasswordCredentials): Promise<AuthResponse>;
/**
* Log in an existing user with an email and password or phone and password.
*
* Be aware that you may get back an error message that will not distinguish
* between the cases where the account does not exist or that the
* email/phone and password combination is wrong or that the account can only
* be accessed via social login.
*/
signInWithPassword(credentials: SignInWithPasswordCredentials): Promise<AuthTokenResponsePassword>;
/**
* Log in an existing user via a third-party provider.
* This method supports the PKCE flow.
*/
signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse>;
/**
* Log in an existing user by exchanging an Auth Code issued during the PKCE flow.
*/
exchangeCodeForSession(authCode: string): Promise<AuthTokenResponse>;
private _exchangeCodeForSession;
/**
* Allows signing in with an OIDC ID token. The authentication provider used
* should be enabled and configured.
*/
signInWithIdToken(credentials: SignInWithIdTokenCredentials): Promise<AuthTokenResponse>;
/**
* Log in a user using magiclink or a one-time password (OTP).
*
* If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent.
* If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent.
* If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins.
*
* Be aware that you may get back an error message that will not distinguish
* between the cases where the account does not exist or, that the account
* can only be accessed via social login.
*
* Do note that you will need to configure a Whatsapp sender on Twilio
* if you are using phone sign in with the 'whatsapp' channel. The whatsapp
* channel is not supported on other providers
* at this time.
* This method supports PKCE when an email is passed.
*/
signInWithOtp(credentials: SignInWithPasswordlessCredentials): Promise<AuthOtpResponse>;
/**
* Log in a user given a User supplied OTP or TokenHash received through mobile or email.
*/
verifyOtp(params: VerifyOtpParams): Promise<AuthResponse>;
/**
* Attempts a single-sign on using an enterprise Identity Provider. A
* successful SSO attempt will redirect the current page to the identity
* provider authorization page. The redirect URL is implementation and SSO
* protocol specific.
*
* You can use it by providing a SSO domain. Typically you can extract this
* domain by asking users for their email address. If this domain is
* registered on the Auth instance the redirect will use that organization's
* currently active SSO Identity Provider for the login.
*
* If you have built an organization-specific login page, you can use the
* organization's SSO Identity Provider UUID directly instead.
*/
signInWithSSO(params: SignInWithSSO): Promise<SSOResponse>;
/**
* Sends a reauthentication OTP to the user's email or phone number.
* Requires the user to be signed-in.
*/
reauthenticate(): Promise<AuthResponse>;
private _reauthenticate;
/**
* Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP.
*/
resend(credentials: ResendParams): Promise<AuthOtpResponse>;
/**
* Returns the session, refreshing it if necessary.
*
* The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out.
*
* **IMPORTANT:** This method loads values directly from the storage attached
* to the client. If that storage is based on request cookies for example,
* the values in it may not be authentic and therefore it's strongly advised
* against using this method and its results in such circumstances. A warning
* will be emitted if this is detected. Use {@link #getUser()} instead.
*/
getSession(): Promise<{
data: {
session: Session;
};
error: null;
} | {
data: {
session: null;
};
error: AuthError;
} | {
data: {
session: null;
};
error: null;
}>;
/**
* Acquires a global lock based on the storage key.
*/
private _acquireLock;
/**
* Use instead of {@link #getSession} inside the library. It is
* semantically usually what you want, as getting a session involves some
* processing afterwards that requires only one client operating on the
* session at once across multiple tabs or processes.
*/
private _useSession;
/**
* NEVER USE DIRECTLY!
*
* Always use {@link #_useSession}.
*/
private __loadSession;
/**
* Gets the current user details if there is an existing session. This method
* performs a network request to the Supabase Auth server, so the returned
* value is authentic and can be used to base authorization rules on.
*
* @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used.
*/
getUser(jwt?: string): Promise<UserResponse>;
private _getUser;
/**
* Updates user data for a logged in user.
*/
updateUser(attributes: UserAttributes, options?: {
emailRedirectTo?: string | undefined;
}): Promise<UserResponse>;
protected _updateUser(attributes: UserAttributes, options?: {
emailRedirectTo?: string | undefined;
}): Promise<UserResponse>;
/**
* Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session.
* If the refresh token or access token in the current session is invalid, an error will be thrown.
* @param currentSession The current session that minimally contains an access token and refresh token.
*/
setSession(currentSession: {
access_token: string;
refresh_token: string;
}): Promise<AuthResponse>;
protected _setSession(currentSession: {
access_token: string;
refresh_token: string;
}): Promise<AuthResponse>;
/**
* Returns a new session, regardless of expiry status.
* Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession().
* If the current session's refresh token is invalid, an error will be thrown.
* @param currentSession The current session. If passed in, it must contain a refresh token.
*/
refreshSession(currentSession?: {
refresh_token: string;
}): Promise<AuthResponse>;
protected _refreshSession(currentSession?: {
refresh_token: string;
}): Promise<AuthResponse>;
/**
* Gets the session data from a URL string
*/
private _getSessionFromURL;
/**
* Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2)
*/
private _isImplicitGrantCallback;
/**
* Checks if the current URL and backing storage contain parameters given by a PKCE flow
*/
private _isPKCECallback;
/**
* Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event.
*
* For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`.
* There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason.
*
* If using `others` scope, no `SIGNED_OUT` event is fired!
*/
signOut(options?: SignOut): Promise<{
error: AuthError | null;
}>;
protected _signOut({ scope }?: SignOut): Promise<{
error: AuthError | null;
}>;
/**
* Receive a notification every time an auth event happens.
* @param callback A callback function to be invoked when an auth event happens.
*/
onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => void | Promise<void>): {
data: {
subscription: Subscription;
};
};
private _emitInitialSession;
/**
* Sends a password reset request to an email address. This method supports the PKCE flow.
*
* @param email The email address of the user.
* @param options.redirectTo The URL to send the user to after they click the password reset link.
* @param options.captchaToken Verification token received when the user completes the captcha on the site.
*/
resetPasswordForEmail(email: string, options?: {
redirectTo?: string;
captchaToken?: string;
}): Promise<{
data: {};
error: null;
} | {
data: null;
error: AuthError;
}>;
/**
* Gets all the identities linked to a user.
*/
getUserIdentities(): Promise<{
data: {
identities: UserIdentity[];
};
error: null;
} | {
data: null;
error: AuthError;
}>;
/**
* Links an oauth identity to an existing user.
* This method supports the PKCE flow.
*/
linkIdentity(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse>;
/**
* Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked.
*/
unlinkIdentity(identity: UserIdentity): Promise<{
data: {};
error: null;
} | {
data: null;
error: AuthError;
}>;
/**
* Generates a new JWT.
* @param refreshToken A valid refresh token that was returned on login.
*/
private _refreshAccessToken;
private _isValidSession;
private _handleProviderSignIn;
/**
* Recovers the session from LocalStorage and refreshes the token
* Note: this method is async to accommodate for AsyncStorage e.g. in React native.
*/
private _recoverAndRefresh;
private _callRefreshToken;
private _notifyAllSubscribers;
/**
* set currentSession and currentUser
* process to _startAutoRefreshToken if possible
*/
private _saveSession;
private _removeSession;
/**
* Removes any registered visibilitychange callback.
*
* {@see #startAutoRefresh}
* {@see #stopAutoRefresh}
*/
private _removeVisibilityChangedCallback;
/**
* This is the private implementation of {@link #startAutoRefresh}. Use this
* within the library.
*/
private _startAutoRefresh;
/**
* This is the private implementation of {@link #stopAutoRefresh}. Use this
* within the library.
*/
private _stopAutoRefresh;
/**
* Starts an auto-refresh process in the background. The session is checked
* every few seconds. Close to the time of expiration a process is started to
* refresh the session. If refreshing fails it will be retried for as long as
* necessary.
*
* If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need
* to call this function, it will be called for you.
*
* On browsers the refresh process works only when the tab/window is in the
* foreground to conserve resources as well as prevent race conditions and
* flooding auth with requests. If you call this method any managed
* visibility change callback will be removed and you must manage visibility
* changes on your own.
*
* On non-browser platforms the refresh process works *continuously* in the
* background, which may not be desirable. You should hook into your
* platform's foreground indication mechanism and call these methods
* appropriately to conserve resources.
*
* {@see #stopAutoRefresh}
*/
startAutoRefresh(): Promise<void>;
/**
* Stops an active auto refresh process running in the background (if any).
*
* If you call this method any managed visibility change callback will be
* removed and you must manage visibility changes on your own.
*
* See {@link #startAutoRefresh} for more details.
*/
stopAutoRefresh(): Promise<void>;
/**
* Runs the auto refresh token tick.
*/
private _autoRefreshTokenTick;
/**
* Registers callbacks on the browser / platform, which in-turn run
* algorithms when the browser window/tab are in foreground. On non-browser
* platforms it assumes always foreground.
*/
private _handleVisibilityChange;
/**
* Callback registered with `window.addEventListener('visibilitychange')`.
*/
private _onVisibilityChanged;
/**
* Generates the relevant login URL for a third-party provider.
* @param options.redirectTo A URL or mobile address to send the user to after they are confirmed.
* @param options.scopes A space-separated list of scopes granted to the OAuth application.
* @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application.
*/
private _getUrlForProvider;
private _unenroll;
/**
* {@see GoTrueMFAApi#enroll}
*/
private _enroll;
/**
* {@see GoTrueMFAApi#verify}
*/
private _verify;
/**
* {@see GoTrueMFAApi#challenge}
*/
private _challenge;
/**
* {@see GoTrueMFAApi#challengeAndVerify}
*/
private _challengeAndVerify;
/**
* {@see GoTrueMFAApi#listFactors}
*/
private _listFactors;
/**
* {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel}
*/
private _getAuthenticatorAssuranceLevel;
private fetchJwk;
/**
* @experimental This method may change in future versions.
* @description Gets the claims from a JWT. If the JWT is symmetric JWTs, it will call getUser() to verify against the server. If the JWT is asymmetric, it will be verified against the JWKS using the WebCrypto API.
*/
getClaims(jwt?: string, jwks?: {
keys: JWK[];
}): Promise<{
data: {
claims: JwtPayload;
header: JwtHeader;
signature: Uint8Array;
};
error: null;
} | {
data: null;
error: AuthError;
} | {
data: null;
error: null;
}>;
}
//# sourceMappingURL=GoTrueClient.d.ts.map

File diff suppressed because one or more lines are too long

2076
node_modules/@supabase/auth-js/dist/main/GoTrueClient.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

9
node_modules/@supabase/auth-js/dist/main/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,9 @@
import GoTrueAdminApi from './GoTrueAdminApi';
import GoTrueClient from './GoTrueClient';
import AuthAdminApi from './AuthAdminApi';
import AuthClient from './AuthClient';
export { GoTrueAdminApi, GoTrueClient, AuthAdminApi, AuthClient };
export * from './lib/types';
export * from './lib/errors';
export { navigatorLock, NavigatorLockAcquireTimeoutError, internals as lockInternals, } from './lib/locks';
//# sourceMappingURL=index.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAC7C,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,UAAU,MAAM,cAAc,CAAA;AACrC,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,CAAA;AACjE,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,OAAO,EACL,aAAa,EACb,gCAAgC,EAChC,SAAS,IAAI,aAAa,GAC3B,MAAM,aAAa,CAAA"}

35
node_modules/@supabase/auth-js/dist/main/index.js generated vendored Normal file
View File

@ -0,0 +1,35 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.lockInternals = exports.NavigatorLockAcquireTimeoutError = exports.navigatorLock = exports.AuthClient = exports.AuthAdminApi = exports.GoTrueClient = exports.GoTrueAdminApi = void 0;
const GoTrueAdminApi_1 = __importDefault(require("./GoTrueAdminApi"));
exports.GoTrueAdminApi = GoTrueAdminApi_1.default;
const GoTrueClient_1 = __importDefault(require("./GoTrueClient"));
exports.GoTrueClient = GoTrueClient_1.default;
const AuthAdminApi_1 = __importDefault(require("./AuthAdminApi"));
exports.AuthAdminApi = AuthAdminApi_1.default;
const AuthClient_1 = __importDefault(require("./AuthClient"));
exports.AuthClient = AuthClient_1.default;
__exportStar(require("./lib/types"), exports);
__exportStar(require("./lib/errors"), exports);
var locks_1 = require("./lib/locks");
Object.defineProperty(exports, "navigatorLock", { enumerable: true, get: function () { return locks_1.navigatorLock; } });
Object.defineProperty(exports, "NavigatorLockAcquireTimeoutError", { enumerable: true, get: function () { return locks_1.NavigatorLockAcquireTimeoutError; } });
Object.defineProperty(exports, "lockInternals", { enumerable: true, get: function () { return locks_1.internals; } });
//# sourceMappingURL=index.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,sEAA6C;AAIpC,yBAJF,wBAAc,CAIE;AAHvB,kEAAyC;AAGhB,uBAHlB,sBAAY,CAGkB;AAFrC,kEAAyC;AAEF,uBAFhC,sBAAY,CAEgC;AADnD,8DAAqC;AACgB,qBAD9C,oBAAU,CAC8C;AAC/D,8CAA2B;AAC3B,+CAA4B;AAC5B,qCAIoB;AAHlB,sGAAA,aAAa,OAAA;AACb,yHAAA,gCAAgC,OAAA;AAChC,sGAAA,SAAS,OAAiB"}

View File

@ -0,0 +1,74 @@
/**
* Avoid modifying this file. It's part of
* https://github.com/supabase-community/base64url-js. Submit all fixes on
* that repo!
*/
/**
* Converts a byte to a Base64-URL string.
*
* @param byte The byte to convert, or null to flush at the end of the byte sequence.
* @param state The Base64 conversion state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`.
* @param emit A function called with the next Base64 character when ready.
*/
export declare function byteToBase64URL(byte: number | null, state: {
queue: number;
queuedBits: number;
}, emit: (char: string) => void): void;
/**
* Converts a String char code (extracted using `string.charCodeAt(position)`) to a sequence of Base64-URL characters.
*
* @param charCode The char code of the JavaScript string.
* @param state The Base64 state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`.
* @param emit A function called with the next byte.
*/
export declare function byteFromBase64URL(charCode: number, state: {
queue: number;
queuedBits: number;
}, emit: (byte: number) => void): void;
/**
* Converts a JavaScript string (which may include any valid character) into a
* Base64-URL encoded string. The string is first encoded in UTF-8 which is
* then encoded as Base64-URL.
*
* @param str The string to convert.
*/
export declare function stringToBase64URL(str: string): string;
/**
* Converts a Base64-URL encoded string into a JavaScript string. It is assumed
* that the underlying string has been encoded as UTF-8.
*
* @param str The Base64-URL encoded string.
*/
export declare function stringFromBase64URL(str: string): string;
/**
* Converts a Unicode codepoint to a multi-byte UTF-8 sequence.
*
* @param codepoint The Unicode codepoint.
* @param emit Function which will be called for each UTF-8 byte that represents the codepoint.
*/
export declare function codepointToUTF8(codepoint: number, emit: (byte: number) => void): void;
/**
* Converts a JavaScript string to a sequence of UTF-8 bytes.
*
* @param str The string to convert to UTF-8.
* @param emit Function which will be called for each UTF-8 byte of the string.
*/
export declare function stringToUTF8(str: string, emit: (byte: number) => void): void;
/**
* Converts a UTF-8 byte to a Unicode codepoint.
*
* @param byte The UTF-8 byte next in the sequence.
* @param state The shared state between consecutive UTF-8 bytes in the
* sequence, an object with the shape `{ utf8seq: 0, codepoint: 0 }`.
* @param emit Function which will be called for each codepoint.
*/
export declare function stringFromUTF8(byte: number, state: {
utf8seq: number;
codepoint: number;
}, emit: (codepoint: number) => void): void;
/**
* Helper functions to convert different types of strings to Uint8Array
*/
export declare function base64UrlToUint8Array(str: string): Uint8Array;
export declare function stringToUint8Array(str: string): Uint8Array;
//# sourceMappingURL=base64url.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"base64url.d.ts","sourceRoot":"","sources":["../../../src/lib/base64url.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAoCH;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,MAAM,GAAG,IAAI,EACnB,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,EAC5C,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAqB7B;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,EAC5C,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAmB7B;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,UAgB5C;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,UAuB9C;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAsB9E;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAgBrE;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAC5B,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,EAC7C,IAAI,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,QAuClC;AAED;;GAEG;AAEH,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAa7D;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAI1D"}

View File

@ -0,0 +1,258 @@
"use strict";
/**
* Avoid modifying this file. It's part of
* https://github.com/supabase-community/base64url-js. Submit all fixes on
* that repo!
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.stringToUint8Array = exports.base64UrlToUint8Array = exports.stringFromUTF8 = exports.stringToUTF8 = exports.codepointToUTF8 = exports.stringFromBase64URL = exports.stringToBase64URL = exports.byteFromBase64URL = exports.byteToBase64URL = void 0;
/**
* An array of characters that encode 6 bits into a Base64-URL alphabet
* character.
*/
const TO_BASE64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'.split('');
/**
* An array of characters that can appear in a Base64-URL encoded string but
* should be ignored.
*/
const IGNORE_BASE64URL = ' \t\n\r='.split('');
/**
* An array of 128 numbers that map a Base64-URL character to 6 bits, or if -2
* used to skip the character, or if -1 used to error out.
*/
const FROM_BASE64URL = (() => {
const charMap = new Array(128);
for (let i = 0; i < charMap.length; i += 1) {
charMap[i] = -1;
}
for (let i = 0; i < IGNORE_BASE64URL.length; i += 1) {
charMap[IGNORE_BASE64URL[i].charCodeAt(0)] = -2;
}
for (let i = 0; i < TO_BASE64URL.length; i += 1) {
charMap[TO_BASE64URL[i].charCodeAt(0)] = i;
}
return charMap;
})();
/**
* Converts a byte to a Base64-URL string.
*
* @param byte The byte to convert, or null to flush at the end of the byte sequence.
* @param state The Base64 conversion state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`.
* @param emit A function called with the next Base64 character when ready.
*/
function byteToBase64URL(byte, state, emit) {
if (byte !== null) {
state.queue = (state.queue << 8) | byte;
state.queuedBits += 8;
while (state.queuedBits >= 6) {
const pos = (state.queue >> (state.queuedBits - 6)) & 63;
emit(TO_BASE64URL[pos]);
state.queuedBits -= 6;
}
}
else if (state.queuedBits > 0) {
state.queue = state.queue << (6 - state.queuedBits);
state.queuedBits = 6;
while (state.queuedBits >= 6) {
const pos = (state.queue >> (state.queuedBits - 6)) & 63;
emit(TO_BASE64URL[pos]);
state.queuedBits -= 6;
}
}
}
exports.byteToBase64URL = byteToBase64URL;
/**
* Converts a String char code (extracted using `string.charCodeAt(position)`) to a sequence of Base64-URL characters.
*
* @param charCode The char code of the JavaScript string.
* @param state The Base64 state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`.
* @param emit A function called with the next byte.
*/
function byteFromBase64URL(charCode, state, emit) {
const bits = FROM_BASE64URL[charCode];
if (bits > -1) {
// valid Base64-URL character
state.queue = (state.queue << 6) | bits;
state.queuedBits += 6;
while (state.queuedBits >= 8) {
emit((state.queue >> (state.queuedBits - 8)) & 0xff);
state.queuedBits -= 8;
}
}
else if (bits === -2) {
// ignore spaces, tabs, newlines, =
return;
}
else {
throw new Error(`Invalid Base64-URL character "${String.fromCharCode(charCode)}"`);
}
}
exports.byteFromBase64URL = byteFromBase64URL;
/**
* Converts a JavaScript string (which may include any valid character) into a
* Base64-URL encoded string. The string is first encoded in UTF-8 which is
* then encoded as Base64-URL.
*
* @param str The string to convert.
*/
function stringToBase64URL(str) {
const base64 = [];
const emitter = (char) => {
base64.push(char);
};
const state = { queue: 0, queuedBits: 0 };
stringToUTF8(str, (byte) => {
byteToBase64URL(byte, state, emitter);
});
byteToBase64URL(null, state, emitter);
return base64.join('');
}
exports.stringToBase64URL = stringToBase64URL;
/**
* Converts a Base64-URL encoded string into a JavaScript string. It is assumed
* that the underlying string has been encoded as UTF-8.
*
* @param str The Base64-URL encoded string.
*/
function stringFromBase64URL(str) {
const conv = [];
const utf8Emit = (codepoint) => {
conv.push(String.fromCodePoint(codepoint));
};
const utf8State = {
utf8seq: 0,
codepoint: 0,
};
const b64State = { queue: 0, queuedBits: 0 };
const byteEmit = (byte) => {
stringFromUTF8(byte, utf8State, utf8Emit);
};
for (let i = 0; i < str.length; i += 1) {
byteFromBase64URL(str.charCodeAt(i), b64State, byteEmit);
}
return conv.join('');
}
exports.stringFromBase64URL = stringFromBase64URL;
/**
* Converts a Unicode codepoint to a multi-byte UTF-8 sequence.
*
* @param codepoint The Unicode codepoint.
* @param emit Function which will be called for each UTF-8 byte that represents the codepoint.
*/
function codepointToUTF8(codepoint, emit) {
if (codepoint <= 0x7f) {
emit(codepoint);
return;
}
else if (codepoint <= 0x7ff) {
emit(0xc0 | (codepoint >> 6));
emit(0x80 | (codepoint & 0x3f));
return;
}
else if (codepoint <= 0xffff) {
emit(0xe0 | (codepoint >> 12));
emit(0x80 | ((codepoint >> 6) & 0x3f));
emit(0x80 | (codepoint & 0x3f));
return;
}
else if (codepoint <= 0x10ffff) {
emit(0xf0 | (codepoint >> 18));
emit(0x80 | ((codepoint >> 12) & 0x3f));
emit(0x80 | ((codepoint >> 6) & 0x3f));
emit(0x80 | (codepoint & 0x3f));
return;
}
throw new Error(`Unrecognized Unicode codepoint: ${codepoint.toString(16)}`);
}
exports.codepointToUTF8 = codepointToUTF8;
/**
* Converts a JavaScript string to a sequence of UTF-8 bytes.
*
* @param str The string to convert to UTF-8.
* @param emit Function which will be called for each UTF-8 byte of the string.
*/
function stringToUTF8(str, emit) {
for (let i = 0; i < str.length; i += 1) {
let codepoint = str.charCodeAt(i);
if (codepoint > 0xd7ff && codepoint <= 0xdbff) {
// most UTF-16 codepoints are Unicode codepoints, except values in this
// range where the next UTF-16 codepoint needs to be combined with the
// current one to get the Unicode codepoint
const highSurrogate = ((codepoint - 0xd800) * 0x400) & 0xffff;
const lowSurrogate = (str.charCodeAt(i + 1) - 0xdc00) & 0xffff;
codepoint = (lowSurrogate | highSurrogate) + 0x10000;
i += 1;
}
codepointToUTF8(codepoint, emit);
}
}
exports.stringToUTF8 = stringToUTF8;
/**
* Converts a UTF-8 byte to a Unicode codepoint.
*
* @param byte The UTF-8 byte next in the sequence.
* @param state The shared state between consecutive UTF-8 bytes in the
* sequence, an object with the shape `{ utf8seq: 0, codepoint: 0 }`.
* @param emit Function which will be called for each codepoint.
*/
function stringFromUTF8(byte, state, emit) {
if (state.utf8seq === 0) {
if (byte <= 0x7f) {
emit(byte);
return;
}
// count the number of 1 leading bits until you reach 0
for (let leadingBit = 1; leadingBit < 6; leadingBit += 1) {
if (((byte >> (7 - leadingBit)) & 1) === 0) {
state.utf8seq = leadingBit;
break;
}
}
if (state.utf8seq === 2) {
state.codepoint = byte & 31;
}
else if (state.utf8seq === 3) {
state.codepoint = byte & 15;
}
else if (state.utf8seq === 4) {
state.codepoint = byte & 7;
}
else {
throw new Error('Invalid UTF-8 sequence');
}
state.utf8seq -= 1;
}
else if (state.utf8seq > 0) {
if (byte <= 0x7f) {
throw new Error('Invalid UTF-8 sequence');
}
state.codepoint = (state.codepoint << 6) | (byte & 63);
state.utf8seq -= 1;
if (state.utf8seq === 0) {
emit(state.codepoint);
}
}
}
exports.stringFromUTF8 = stringFromUTF8;
/**
* Helper functions to convert different types of strings to Uint8Array
*/
function base64UrlToUint8Array(str) {
const result = [];
const state = { queue: 0, queuedBits: 0 };
const onByte = (byte) => {
result.push(byte);
};
for (let i = 0; i < str.length; i += 1) {
byteFromBase64URL(str.charCodeAt(i), state, onByte);
}
return new Uint8Array(result);
}
exports.base64UrlToUint8Array = base64UrlToUint8Array;
function stringToUint8Array(str) {
const result = [];
stringToUTF8(str, (byte) => result.push(byte));
return new Uint8Array(result);
}
exports.stringToUint8Array = stringToUint8Array;
//# sourceMappingURL=base64url.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,26 @@
/** Current session will be checked for refresh at this interval. */
export declare const AUTO_REFRESH_TICK_DURATION_MS: number;
/**
* A token refresh will be attempted this many ticks before the current session expires. */
export declare const AUTO_REFRESH_TICK_THRESHOLD = 3;
export declare const EXPIRY_MARGIN_MS: number;
export declare const GOTRUE_URL = "http://localhost:9999";
export declare const STORAGE_KEY = "supabase.auth.token";
export declare const AUDIENCE = "";
export declare const DEFAULT_HEADERS: {
'X-Client-Info': string;
};
export declare const NETWORK_FAILURE: {
MAX_RETRIES: number;
RETRY_INTERVAL: number;
};
export declare const API_VERSION_HEADER_NAME = "X-Supabase-Api-Version";
export declare const API_VERSIONS: {
'2024-01-01': {
timestamp: number;
name: string;
};
};
export declare const BASE64URL_REGEX: RegExp;
export declare const JWKS_TTL = 600000;
//# sourceMappingURL=constants.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AAEA,oEAAoE;AACpE,eAAO,MAAM,6BAA6B,QAAY,CAAA;AAEtD;2FAC2F;AAC3F,eAAO,MAAM,2BAA2B,IAAI,CAAA;AAK5C,eAAO,MAAM,gBAAgB,QAA8D,CAAA;AAE3F,eAAO,MAAM,UAAU,0BAA0B,CAAA;AACjD,eAAO,MAAM,WAAW,wBAAwB,CAAA;AAChD,eAAO,MAAM,QAAQ,KAAK,CAAA;AAC1B,eAAO,MAAM,eAAe;;CAA8C,CAAA;AAC1E,eAAO,MAAM,eAAe;;;CAG3B,CAAA;AAED,eAAO,MAAM,uBAAuB,2BAA2B,CAAA;AAC/D,eAAO,MAAM,YAAY;;;;;CAKxB,CAAA;AAED,eAAO,MAAM,eAAe,QAAyD,CAAA;AAErF,eAAO,MAAM,QAAQ,SAAS,CAAA"}

View File

@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.JWKS_TTL = exports.BASE64URL_REGEX = exports.API_VERSIONS = exports.API_VERSION_HEADER_NAME = exports.NETWORK_FAILURE = exports.DEFAULT_HEADERS = exports.AUDIENCE = exports.STORAGE_KEY = exports.GOTRUE_URL = exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD = exports.AUTO_REFRESH_TICK_DURATION_MS = void 0;
const version_1 = require("./version");
/** Current session will be checked for refresh at this interval. */
exports.AUTO_REFRESH_TICK_DURATION_MS = 30 * 1000;
/**
* A token refresh will be attempted this many ticks before the current session expires. */
exports.AUTO_REFRESH_TICK_THRESHOLD = 3;
/*
* Earliest time before an access token expires that the session should be refreshed.
*/
exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD * exports.AUTO_REFRESH_TICK_DURATION_MS;
exports.GOTRUE_URL = 'http://localhost:9999';
exports.STORAGE_KEY = 'supabase.auth.token';
exports.AUDIENCE = '';
exports.DEFAULT_HEADERS = { 'X-Client-Info': `gotrue-js/${version_1.version}` };
exports.NETWORK_FAILURE = {
MAX_RETRIES: 10,
RETRY_INTERVAL: 2, // in deciseconds
};
exports.API_VERSION_HEADER_NAME = 'X-Supabase-Api-Version';
exports.API_VERSIONS = {
'2024-01-01': {
timestamp: Date.parse('2024-01-01T00:00:00.0Z'),
name: '2024-01-01',
},
};
exports.BASE64URL_REGEX = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;
exports.JWKS_TTL = 600000; // 10 minutes
//# sourceMappingURL=constants.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":";;;AAAA,uCAAmC;AAEnC,oEAAoE;AACvD,QAAA,6BAA6B,GAAG,EAAE,GAAG,IAAI,CAAA;AAEtD;2FAC2F;AAC9E,QAAA,2BAA2B,GAAG,CAAC,CAAA;AAE5C;;GAEG;AACU,QAAA,gBAAgB,GAAG,mCAA2B,GAAG,qCAA6B,CAAA;AAE9E,QAAA,UAAU,GAAG,uBAAuB,CAAA;AACpC,QAAA,WAAW,GAAG,qBAAqB,CAAA;AACnC,QAAA,QAAQ,GAAG,EAAE,CAAA;AACb,QAAA,eAAe,GAAG,EAAE,eAAe,EAAE,aAAa,iBAAO,EAAE,EAAE,CAAA;AAC7D,QAAA,eAAe,GAAG;IAC7B,WAAW,EAAE,EAAE;IACf,cAAc,EAAE,CAAC,EAAE,iBAAiB;CACrC,CAAA;AAEY,QAAA,uBAAuB,GAAG,wBAAwB,CAAA;AAClD,QAAA,YAAY,GAAG;IAC1B,YAAY,EAAE;QACZ,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,wBAAwB,CAAC;QAC/C,IAAI,EAAE,YAAY;KACnB;CACF,CAAA;AAEY,QAAA,eAAe,GAAG,sDAAsD,CAAA;AAExE,QAAA,QAAQ,GAAG,MAAM,CAAA,CAAC,aAAa"}

View File

@ -0,0 +1,7 @@
/**
* Known error codes. Note that the server may also return other error codes
* not included in this list (if the client library is older than the version
* on the server).
*/
export declare type ErrorCode = 'unexpected_failure' | 'validation_failed' | 'bad_json' | 'email_exists' | 'phone_exists' | 'bad_jwt' | 'not_admin' | 'no_authorization' | 'user_not_found' | 'session_not_found' | 'session_expired' | 'refresh_token_not_found' | 'refresh_token_already_used' | 'flow_state_not_found' | 'flow_state_expired' | 'signup_disabled' | 'user_banned' | 'provider_email_needs_verification' | 'invite_not_found' | 'bad_oauth_state' | 'bad_oauth_callback' | 'oauth_provider_not_supported' | 'unexpected_audience' | 'single_identity_not_deletable' | 'email_conflict_identity_not_deletable' | 'identity_already_exists' | 'email_provider_disabled' | 'phone_provider_disabled' | 'too_many_enrolled_mfa_factors' | 'mfa_factor_name_conflict' | 'mfa_factor_not_found' | 'mfa_ip_address_mismatch' | 'mfa_challenge_expired' | 'mfa_verification_failed' | 'mfa_verification_rejected' | 'insufficient_aal' | 'captcha_failed' | 'saml_provider_disabled' | 'manual_linking_disabled' | 'sms_send_failed' | 'email_not_confirmed' | 'phone_not_confirmed' | 'reauth_nonce_missing' | 'saml_relay_state_not_found' | 'saml_relay_state_expired' | 'saml_idp_not_found' | 'saml_assertion_no_user_id' | 'saml_assertion_no_email' | 'user_already_exists' | 'sso_provider_not_found' | 'saml_metadata_fetch_failed' | 'saml_idp_already_exists' | 'sso_domain_already_exists' | 'saml_entity_id_mismatch' | 'conflict' | 'provider_disabled' | 'user_sso_managed' | 'reauthentication_needed' | 'same_password' | 'reauthentication_not_valid' | 'otp_expired' | 'otp_disabled' | 'identity_not_found' | 'weak_password' | 'over_request_rate_limit' | 'over_email_send_rate_limit' | 'over_sms_send_rate_limit' | 'bad_code_verifier' | 'anonymous_provider_disabled' | 'hook_timeout' | 'hook_timeout_after_retry' | 'hook_payload_over_size_limit' | 'hook_payload_invalid_content_type' | 'request_timeout' | 'mfa_phone_enroll_not_enabled' | 'mfa_phone_verify_not_enabled' | 'mfa_totp_enroll_not_enabled' | 'mfa_totp_verify_not_enabled' | 'mfa_webauthn_enroll_not_enabled' | 'mfa_webauthn_verify_not_enabled' | 'mfa_verified_factor_exists' | 'invalid_credentials' | 'email_address_not_authorized' | 'email_address_invalid';
//# sourceMappingURL=error-codes.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"error-codes.d.ts","sourceRoot":"","sources":["../../../src/lib/error-codes.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,oBAAY,SAAS,GACjB,oBAAoB,GACpB,mBAAmB,GACnB,UAAU,GACV,cAAc,GACd,cAAc,GACd,SAAS,GACT,WAAW,GACX,kBAAkB,GAClB,gBAAgB,GAChB,mBAAmB,GACnB,iBAAiB,GACjB,yBAAyB,GACzB,4BAA4B,GAC5B,sBAAsB,GACtB,oBAAoB,GACpB,iBAAiB,GACjB,aAAa,GACb,mCAAmC,GACnC,kBAAkB,GAClB,iBAAiB,GACjB,oBAAoB,GACpB,8BAA8B,GAC9B,qBAAqB,GACrB,+BAA+B,GAC/B,uCAAuC,GACvC,yBAAyB,GACzB,yBAAyB,GACzB,yBAAyB,GACzB,+BAA+B,GAC/B,0BAA0B,GAC1B,sBAAsB,GACtB,yBAAyB,GACzB,uBAAuB,GACvB,yBAAyB,GACzB,2BAA2B,GAC3B,kBAAkB,GAClB,gBAAgB,GAChB,wBAAwB,GACxB,yBAAyB,GACzB,iBAAiB,GACjB,qBAAqB,GACrB,qBAAqB,GACrB,sBAAsB,GACtB,4BAA4B,GAC5B,0BAA0B,GAC1B,oBAAoB,GACpB,2BAA2B,GAC3B,yBAAyB,GACzB,qBAAqB,GACrB,wBAAwB,GACxB,4BAA4B,GAC5B,yBAAyB,GACzB,2BAA2B,GAC3B,yBAAyB,GACzB,UAAU,GACV,mBAAmB,GACnB,kBAAkB,GAClB,yBAAyB,GACzB,eAAe,GACf,4BAA4B,GAC5B,aAAa,GACb,cAAc,GACd,oBAAoB,GACpB,eAAe,GACf,yBAAyB,GACzB,4BAA4B,GAC5B,0BAA0B,GAC1B,mBAAmB,GACnB,6BAA6B,GAC7B,cAAc,GACd,0BAA0B,GAC1B,8BAA8B,GAC9B,mCAAmC,GACnC,iBAAiB,GACjB,8BAA8B,GAC9B,8BAA8B,GAC9B,6BAA6B,GAC7B,6BAA6B,GAC7B,iCAAiC,GACjC,iCAAiC,GACjC,4BAA4B,GAC5B,qBAAqB,GACrB,8BAA8B,GAC9B,uBAAuB,CAAA"}

View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=error-codes.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"error-codes.js","sourceRoot":"","sources":["../../../src/lib/error-codes.ts"],"names":[],"mappings":""}

View File

@ -0,0 +1,100 @@
import { WeakPasswordReasons } from './types';
import { ErrorCode } from './error-codes';
export declare class AuthError extends Error {
/**
* Error code associated with the error. Most errors coming from
* HTTP responses will have a code, though some errors that occur
* before a response is received will not have one present. In that
* case {@link #status} will also be undefined.
*/
code: ErrorCode | (string & {}) | undefined;
/** HTTP status code that caused the error. */
status: number | undefined;
protected __isAuthError: boolean;
constructor(message: string, status?: number, code?: string);
}
export declare function isAuthError(error: unknown): error is AuthError;
export declare class AuthApiError extends AuthError {
status: number;
constructor(message: string, status: number, code: string | undefined);
}
export declare function isAuthApiError(error: unknown): error is AuthApiError;
export declare class AuthUnknownError extends AuthError {
originalError: unknown;
constructor(message: string, originalError: unknown);
}
export declare class CustomAuthError extends AuthError {
name: string;
status: number;
constructor(message: string, name: string, status: number, code: string | undefined);
}
export declare class AuthSessionMissingError extends CustomAuthError {
constructor();
}
export declare function isAuthSessionMissingError(error: any): error is AuthSessionMissingError;
export declare class AuthInvalidTokenResponseError extends CustomAuthError {
constructor();
}
export declare class AuthInvalidCredentialsError extends CustomAuthError {
constructor(message: string);
}
export declare class AuthImplicitGrantRedirectError extends CustomAuthError {
details: {
error: string;
code: string;
} | null;
constructor(message: string, details?: {
error: string;
code: string;
} | null);
toJSON(): {
name: string;
message: string;
status: number;
details: {
error: string;
code: string;
} | null;
};
}
export declare function isAuthImplicitGrantRedirectError(error: any): error is AuthImplicitGrantRedirectError;
export declare class AuthPKCEGrantCodeExchangeError extends CustomAuthError {
details: {
error: string;
code: string;
} | null;
constructor(message: string, details?: {
error: string;
code: string;
} | null);
toJSON(): {
name: string;
message: string;
status: number;
details: {
error: string;
code: string;
} | null;
};
}
export declare class AuthRetryableFetchError extends CustomAuthError {
constructor(message: string, status: number);
}
export declare function isAuthRetryableFetchError(error: unknown): error is AuthRetryableFetchError;
/**
* This error is thrown on certain methods when the password used is deemed
* weak. Inspect the reasons to identify what password strength rules are
* inadequate.
*/
export declare class AuthWeakPasswordError extends CustomAuthError {
/**
* Reasons why the password is deemed weak.
*/
reasons: WeakPasswordReasons[];
constructor(message: string, status: number, reasons: string[]);
}
export declare function isAuthWeakPasswordError(error: unknown): error is AuthWeakPasswordError;
export declare class AuthInvalidJwtError extends CustomAuthError {
constructor(message: string);
}
//# sourceMappingURL=errors.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/lib/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAA;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAA;AAEzC,qBAAa,SAAU,SAAQ,KAAK;IAClC;;;;;OAKG;IACH,IAAI,EAAE,SAAS,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,GAAG,SAAS,CAAA;IAE3C,8CAA8C;IAC9C,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AC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,IAAW;IAKnF,MAAM;;;;;;;;;CAQP;AAED,wBAAgB,gCAAgC,CAC9C,KAAK,EAAE,GAAG,GACT,KAAK,IAAI,8BAA8B,CAEzC;AAED,qBAAa,8BAA+B,SAAQ,eAAe;IACjE,OAAO,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAO;gBAE1C,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,IAAW;IAKnF,MAAM;;;;;;;;;CAQP;AAED,qBAAa,uBAAwB,SAAQ,eAAe;gBAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;CAG5C;AAED,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,uBAAuB,CAE1F;AAED;;;;GAIG;AACH,qBAAa,qBAAsB,SAAQ,eAAe;IACxD;;OAEG;IACH,OAAO,EAAE,mBAAmB,EAAE,CAAA;gBAElB,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE;CAK/D;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,qBAAqB,CAEtF;AAED,qBAAa,mBAAoB,SAAQ,eAAe;gBAC1C,OAAO,EAAE,MAAM;CAG5B"}

137
node_modules/@supabase/auth-js/dist/main/lib/errors.js generated vendored Normal file
View File

@ -0,0 +1,137 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthInvalidJwtError = exports.isAuthWeakPasswordError = exports.AuthWeakPasswordError = exports.isAuthRetryableFetchError = exports.AuthRetryableFetchError = exports.AuthPKCEGrantCodeExchangeError = exports.isAuthImplicitGrantRedirectError = exports.AuthImplicitGrantRedirectError = exports.AuthInvalidCredentialsError = exports.AuthInvalidTokenResponseError = exports.isAuthSessionMissingError = exports.AuthSessionMissingError = exports.CustomAuthError = exports.AuthUnknownError = exports.isAuthApiError = exports.AuthApiError = exports.isAuthError = exports.AuthError = void 0;
class AuthError extends Error {
constructor(message, status, code) {
super(message);
this.__isAuthError = true;
this.name = 'AuthError';
this.status = status;
this.code = code;
}
}
exports.AuthError = AuthError;
function isAuthError(error) {
return typeof error === 'object' && error !== null && '__isAuthError' in error;
}
exports.isAuthError = isAuthError;
class AuthApiError extends AuthError {
constructor(message, status, code) {
super(message, status, code);
this.name = 'AuthApiError';
this.status = status;
this.code = code;
}
}
exports.AuthApiError = AuthApiError;
function isAuthApiError(error) {
return isAuthError(error) && error.name === 'AuthApiError';
}
exports.isAuthApiError = isAuthApiError;
class AuthUnknownError extends AuthError {
constructor(message, originalError) {
super(message);
this.name = 'AuthUnknownError';
this.originalError = originalError;
}
}
exports.AuthUnknownError = AuthUnknownError;
class CustomAuthError extends AuthError {
constructor(message, name, status, code) {
super(message, status, code);
this.name = name;
this.status = status;
}
}
exports.CustomAuthError = CustomAuthError;
class AuthSessionMissingError extends CustomAuthError {
constructor() {
super('Auth session missing!', 'AuthSessionMissingError', 400, undefined);
}
}
exports.AuthSessionMissingError = AuthSessionMissingError;
function isAuthSessionMissingError(error) {
return isAuthError(error) && error.name === 'AuthSessionMissingError';
}
exports.isAuthSessionMissingError = isAuthSessionMissingError;
class AuthInvalidTokenResponseError extends CustomAuthError {
constructor() {
super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500, undefined);
}
}
exports.AuthInvalidTokenResponseError = AuthInvalidTokenResponseError;
class AuthInvalidCredentialsError extends CustomAuthError {
constructor(message) {
super(message, 'AuthInvalidCredentialsError', 400, undefined);
}
}
exports.AuthInvalidCredentialsError = AuthInvalidCredentialsError;
class AuthImplicitGrantRedirectError extends CustomAuthError {
constructor(message, details = null) {
super(message, 'AuthImplicitGrantRedirectError', 500, undefined);
this.details = null;
this.details = details;
}
toJSON() {
return {
name: this.name,
message: this.message,
status: this.status,
details: this.details,
};
}
}
exports.AuthImplicitGrantRedirectError = AuthImplicitGrantRedirectError;
function isAuthImplicitGrantRedirectError(error) {
return isAuthError(error) && error.name === 'AuthImplicitGrantRedirectError';
}
exports.isAuthImplicitGrantRedirectError = isAuthImplicitGrantRedirectError;
class AuthPKCEGrantCodeExchangeError extends CustomAuthError {
constructor(message, details = null) {
super(message, 'AuthPKCEGrantCodeExchangeError', 500, undefined);
this.details = null;
this.details = details;
}
toJSON() {
return {
name: this.name,
message: this.message,
status: this.status,
details: this.details,
};
}
}
exports.AuthPKCEGrantCodeExchangeError = AuthPKCEGrantCodeExchangeError;
class AuthRetryableFetchError extends CustomAuthError {
constructor(message, status) {
super(message, 'AuthRetryableFetchError', status, undefined);
}
}
exports.AuthRetryableFetchError = AuthRetryableFetchError;
function isAuthRetryableFetchError(error) {
return isAuthError(error) && error.name === 'AuthRetryableFetchError';
}
exports.isAuthRetryableFetchError = isAuthRetryableFetchError;
/**
* This error is thrown on certain methods when the password used is deemed
* weak. Inspect the reasons to identify what password strength rules are
* inadequate.
*/
class AuthWeakPasswordError extends CustomAuthError {
constructor(message, status, reasons) {
super(message, 'AuthWeakPasswordError', status, 'weak_password');
this.reasons = reasons;
}
}
exports.AuthWeakPasswordError = AuthWeakPasswordError;
function isAuthWeakPasswordError(error) {
return isAuthError(error) && error.name === 'AuthWeakPasswordError';
}
exports.isAuthWeakPasswordError = isAuthWeakPasswordError;
class AuthInvalidJwtError extends CustomAuthError {
constructor(message) {
super(message, 'AuthInvalidJwtError', 400, 'invalid_jwt');
}
}
exports.AuthInvalidJwtError = AuthInvalidJwtError;
//# sourceMappingURL=errors.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/lib/errors.ts"],"names":[],"mappings":";;;AAGA,MAAa,SAAU,SAAQ,KAAK;IAclC,YAAY,OAAe,EAAE,MAAe,EAAE,IAAa;QACzD,KAAK,CA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;CACF;AAJD,kDAIC"}

View File

@ -0,0 +1,34 @@
import { AuthResponse, AuthResponsePassword, SSOResponse, GenerateLinkResponse, UserResponse } from './types';
export declare type Fetch = typeof fetch;
export interface FetchOptions {
headers?: {
[key: string]: string;
};
noResolveJson?: boolean;
}
export interface FetchParameters {
signal?: AbortSignal;
}
export declare type RequestMethodType = 'GET' | 'POST' | 'PUT' | 'DELETE';
export declare function handleError(error: unknown): Promise<void>;
interface GotrueRequestOptions extends FetchOptions {
jwt?: string;
redirectTo?: string;
body?: object;
query?: {
[key: string]: string;
};
/**
* Function that transforms api response from gotrue into a desirable / standardised format
*/
xform?: (data: any) => any;
}
export declare function _request(fetcher: Fetch, method: RequestMethodType, url: string, options?: GotrueRequestOptions): Promise<any>;
export declare function _sessionResponse(data: any): AuthResponse;
export declare function _sessionResponsePassword(data: any): AuthResponsePassword;
export declare function _userResponse(data: any): UserResponse;
export declare function _ssoResponse(data: any): SSOResponse;
export declare function _generateLinkResponse(data: any): GenerateLinkResponse;
export declare function _noResolveJsonResponse(data: any): Response;
export {};
//# sourceMappingURL=fetch.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,YAAY,EACZ,oBAAoB,EACpB,WAAW,EAEX,oBAAoB,EAEpB,YAAY,EACb,MAAM,SAAS,CAAA;AAShB,oBAAY,KAAK,GAAG,OAAO,KAAK,CAAA;AAEhC,MAAM,WAAW,YAAY;IAC3B,OAAO,CAAC,EAAE;QACR,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KACtB,CAAA;IACD,aAAa,CAAC,EAAE,OAAO,CAAA;CACxB;AAED,MAAM,WAAW,eAAe;IAC9B,MAAM,CAAC,EAAE,WAAW,CAAA;CACrB;AAED,oBAAY,iBAAiB,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,CAAA;AAOjE,wBAAsB,WAAW,CAAC,KAAK,EAAE,OAAO,iBA+D/C;AAmBD,UAAU,oBAAqB,SAAQ,YAAY;IACjD,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,KAAK,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAA;IACjC;;OAEG;IACH,KAAK,CAAC,EAAE,CAAC,IAAI,EAAE,GAAG,KAAK,GAAG,CAAA;CAC3B;AAED,wBAAsB,QAAQ,CAC5B,OAAO,EAAE,KAAK,EACd,MAAM,EAAE,iBAAiB,EACzB,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,oBAAoB,gBAgC/B;AAwCD,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,GAAG,GAAG,YAAY,CAYxD;AAED,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,GAAG,GAAG,oBAAoB,CAiBxE;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,GAAG,GAAG,YAAY,CAGrD;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE,GAAG,GAAG,WAAW,CAEnD;AAED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,GAAG,GAAG,oBAAoB,CAmBrE;AAED,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,GAAG,GAAG,QAAQ,CAE1D"}

195
node_modules/@supabase/auth-js/dist/main/lib/fetch.js generated vendored Normal file
View File

@ -0,0 +1,195 @@
"use strict";
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports._noResolveJsonResponse = exports._generateLinkResponse = exports._ssoResponse = exports._userResponse = exports._sessionResponsePassword = exports._sessionResponse = exports._request = exports.handleError = void 0;
const constants_1 = require("./constants");
const helpers_1 = require("./helpers");
const errors_1 = require("./errors");
const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err);
const NETWORK_ERROR_CODES = [502, 503, 504];
async function handleError(error) {
var _a;
if (!(0, helpers_1.looksLikeFetchResponse)(error)) {
throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), 0);
}
if (NETWORK_ERROR_CODES.includes(error.status)) {
// status in 500...599 range - server had an error, request might be retryed.
throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), error.status);
}
let data;
try {
data = await error.json();
}
catch (e) {
throw new errors_1.AuthUnknownError(_getErrorMessage(e), e);
}
let errorCode = undefined;
const responseAPIVersion = (0, helpers_1.parseResponseAPIVersion)(error);
if (responseAPIVersion &&
responseAPIVersion.getTime() >= constants_1.API_VERSIONS['2024-01-01'].timestamp &&
typeof data === 'object' &&
data &&
typeof data.code === 'string') {
errorCode = data.code;
}
else if (typeof data === 'object' && data && typeof data.error_code === 'string') {
errorCode = data.error_code;
}
if (!errorCode) {
// Legacy support for weak password errors, when there were no error codes
if (typeof data === 'object' &&
data &&
typeof data.weak_password === 'object' &&
data.weak_password &&
Array.isArray(data.weak_password.reasons) &&
data.weak_password.reasons.length &&
data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) {
throw new errors_1.AuthWeakPasswordError(_getErrorMessage(data), error.status, data.weak_password.reasons);
}
}
else if (errorCode === 'weak_password') {
throw new errors_1.AuthWeakPasswordError(_getErrorMessage(data), error.status, ((_a = data.weak_password) === null || _a === void 0 ? void 0 : _a.reasons) || []);
}
else if (errorCode === 'session_not_found') {
// The `session_id` inside the JWT does not correspond to a row in the
// `sessions` table. This usually means the user has signed out, has been
// deleted, or their session has somehow been terminated.
throw new errors_1.AuthSessionMissingError();
}
throw new errors_1.AuthApiError(_getErrorMessage(data), error.status || 500, errorCode);
}
exports.handleError = handleError;
const _getRequestParams = (method, options, parameters, body) => {
const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} };
if (method === 'GET') {
return params;
}
params.headers = Object.assign({ 'Content-Type': 'application/json;charset=UTF-8' }, options === null || options === void 0 ? void 0 : options.headers);
params.body = JSON.stringify(body);
return Object.assign(Object.assign({}, params), parameters);
};
async function _request(fetcher, method, url, options) {
var _a;
const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers);
if (!headers[constants_1.API_VERSION_HEADER_NAME]) {
headers[constants_1.API_VERSION_HEADER_NAME] = constants_1.API_VERSIONS['2024-01-01'].name;
}
if (options === null || options === void 0 ? void 0 : options.jwt) {
headers['Authorization'] = `Bearer ${options.jwt}`;
}
const qs = (_a = options === null || options === void 0 ? void 0 : options.query) !== null && _a !== void 0 ? _a : {};
if (options === null || options === void 0 ? void 0 : options.redirectTo) {
qs['redirect_to'] = options.redirectTo;
}
const queryString = Object.keys(qs).length ? '?' + new URLSearchParams(qs).toString() : '';
const data = await _handleRequest(fetcher, method, url + queryString, {
headers,
noResolveJson: options === null || options === void 0 ? void 0 : options.noResolveJson,
}, {}, options === null || options === void 0 ? void 0 : options.body);
return (options === null || options === void 0 ? void 0 : options.xform) ? options === null || options === void 0 ? void 0 : options.xform(data) : { data: Object.assign({}, data), error: null };
}
exports._request = _request;
async function _handleRequest(fetcher, method, url, options, parameters, body) {
const requestParams = _getRequestParams(method, options, parameters, body);
let result;
try {
result = await fetcher(url, Object.assign({}, requestParams));
}
catch (e) {
console.error(e);
// fetch failed, likely due to a network or CORS error
throw new errors_1.AuthRetryableFetchError(_getErrorMessage(e), 0);
}
if (!result.ok) {
await handleError(result);
}
if (options === null || options === void 0 ? void 0 : options.noResolveJson) {
return result;
}
try {
return await result.json();
}
catch (e) {
await handleError(e);
}
}
function _sessionResponse(data) {
var _a;
let session = null;
if (hasSession(data)) {
session = Object.assign({}, data);
if (!data.expires_at) {
session.expires_at = (0, helpers_1.expiresAt)(data.expires_in);
}
}
const user = (_a = data.user) !== null && _a !== void 0 ? _a : data;
return { data: { session, user }, error: null };
}
exports._sessionResponse = _sessionResponse;
function _sessionResponsePassword(data) {
const response = _sessionResponse(data);
if (!response.error &&
data.weak_password &&
typeof data.weak_password === 'object' &&
Array.isArray(data.weak_password.reasons) &&
data.weak_password.reasons.length &&
data.weak_password.message &&
typeof data.weak_password.message === 'string' &&
data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) {
response.data.weak_password = data.weak_password;
}
return response;
}
exports._sessionResponsePassword = _sessionResponsePassword;
function _userResponse(data) {
var _a;
const user = (_a = data.user) !== null && _a !== void 0 ? _a : data;
return { data: { user }, error: null };
}
exports._userResponse = _userResponse;
function _ssoResponse(data) {
return { data, error: null };
}
exports._ssoResponse = _ssoResponse;
function _generateLinkResponse(data) {
const { action_link, email_otp, hashed_token, redirect_to, verification_type } = data, rest = __rest(data, ["action_link", "email_otp", "hashed_token", "redirect_to", "verification_type"]);
const properties = {
action_link,
email_otp,
hashed_token,
redirect_to,
verification_type,
};
const user = Object.assign({}, rest);
return {
data: {
properties,
user,
},
error: null,
};
}
exports._generateLinkResponse = _generateLinkResponse;
function _noResolveJsonResponse(data) {
return data;
}
exports._noResolveJsonResponse = _noResolveJsonResponse;
/**
* hasSession checks if the response object contains a valid session
* @param data A response object
* @returns true if a session is in the response
*/
function hasSession(data) {
return data.access_token && data.refresh_token && data.expires_in;
}
//# sourceMappingURL=fetch.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,59 @@
import { JwtHeader, JwtPayload, SupportedStorage } from './types';
export declare function expiresAt(expiresIn: number): number;
export declare function uuid(): string;
export declare const isBrowser: () => boolean;
/**
* Checks whether localStorage is supported on this browser.
*/
export declare const supportsLocalStorage: () => boolean;
/**
* Extracts parameters encoded in the URL both in the query and fragment.
*/
export declare function parseParametersFromURL(href: string): {
[parameter: string]: string;
};
declare type Fetch = typeof fetch;
export declare const resolveFetch: (customFetch?: Fetch) => Fetch;
export declare const looksLikeFetchResponse: (maybeResponse: unknown) => maybeResponse is Response;
export declare const setItemAsync: (storage: SupportedStorage, key: string, data: any) => Promise<void>;
export declare const getItemAsync: (storage: SupportedStorage, key: string) => Promise<unknown>;
export declare const removeItemAsync: (storage: SupportedStorage, key: string) => Promise<void>;
/**
* A deferred represents some asynchronous work that is not yet finished, which
* may or may not culminate in a value.
* Taken from: https://github.com/mike-north/types/blob/master/src/async.ts
*/
export declare class Deferred<T = any> {
static promiseConstructor: PromiseConstructor;
readonly promise: PromiseLike<T>;
readonly resolve: (value?: T | PromiseLike<T>) => void;
readonly reject: (reason?: any) => any;
constructor();
}
export declare function decodeJWT(token: string): {
header: JwtHeader;
payload: JwtPayload;
signature: Uint8Array;
raw: {
header: string;
payload: string;
};
};
/**
* Creates a promise that resolves to null after some time.
*/
export declare function sleep(time: number): Promise<null>;
/**
* Converts the provided async function into a retryable function. Each result
* or thrown error is sent to the isRetryable function which should return true
* if the function should run again.
*/
export declare function retryable<T>(fn: (attempt: number) => Promise<T>, isRetryable: (attempt: number, error: any | null, result?: T) => boolean): Promise<T>;
export declare function generatePKCEVerifier(): string;
export declare function generatePKCEChallenge(verifier: string): Promise<string>;
export declare function getCodeChallengeAndMethod(storage: SupportedStorage, storageKey: string, isPasswordRecovery?: boolean): Promise<string[]>;
export declare function parseResponseAPIVersion(response: Response): Date | null;
export declare function validateExp(exp: number): void;
export declare function getAlgorithm(alg: 'RS256' | 'ES256'): RsaHashedImportParams | EcKeyImportParams;
export {};
//# sourceMappingURL=helpers.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAEjE,wBAAgB,SAAS,CAAC,SAAS,EAAE,MAAM,UAG1C;AA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G,OAAO,CAAC,IAAI,CAAC,CAIvD;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,CAAC,EACzB,EAAE,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC,CAAC,EACnC,WAAW,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,IAAI,EAAE,MAAM,CAAC,EAAE,CAAC,KAAK,OAAO,GACvE,OAAO,CAAC,CAAC,CAAC,CAuBZ;AAOD,wBAAgB,oBAAoB,WAcnC;AAaD,wBAAsB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,mBAc3D;AAED,wBAAsB,yBAAyB,CAC7C,OAAO,EAAE,gBAAgB,EACzB,UAAU,EAAE,MAAM,EAClB,kBAAkB,UAAQ,qBAW3B;AAKD,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,QAAQ,eAiBzD;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,QAQtC;AAED,wBAAgB,YAAY,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,GAAG,qBAAqB,GAAG,iBAAiB,CAgB9F"}

334
node_modules/@supabase/auth-js/dist/main/lib/helpers.js generated vendored Normal file
View File

@ -0,0 +1,334 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAlgorithm = exports.validateExp = exports.parseResponseAPIVersion = exports.getCodeChallengeAndMethod = exports.generatePKCEChallenge = exports.generatePKCEVerifier = exports.retryable = exports.sleep = exports.decodeJWT = exports.Deferred = exports.removeItemAsync = exports.getItemAsync = exports.setItemAsync = exports.looksLikeFetchResponse = exports.resolveFetch = exports.parseParametersFromURL = exports.supportsLocalStorage = exports.isBrowser = exports.uuid = exports.expiresAt = void 0;
const constants_1 = require("./constants");
const errors_1 = require("./errors");
const base64url_1 = require("./base64url");
function expiresAt(expiresIn) {
const timeNow = Math.round(Date.now() / 1000);
return timeNow + expiresIn;
}
exports.expiresAt = expiresAt;
function uuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
exports.uuid = uuid;
const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined';
exports.isBrowser = isBrowser;
const localStorageWriteTests = {
tested: false,
writable: false,
};
/**
* Checks whether localStorage is supported on this browser.
*/
const supportsLocalStorage = () => {
if (!(0, exports.isBrowser)()) {
return false;
}
try {
if (typeof globalThis.localStorage !== 'object') {
return false;
}
}
catch (e) {
// DOM exception when accessing `localStorage`
return false;
}
if (localStorageWriteTests.tested) {
return localStorageWriteTests.writable;
}
const randomKey = `lswt-${Math.random()}${Math.random()}`;
try {
globalThis.localStorage.setItem(randomKey, randomKey);
globalThis.localStorage.removeItem(randomKey);
localStorageWriteTests.tested = true;
localStorageWriteTests.writable = true;
}
catch (e) {
// localStorage can't be written to
// https://www.chromium.org/for-testers/bug-reporting-guidelines/uncaught-securityerror-failed-to-read-the-localstorage-property-from-window-access-is-denied-for-this-document
localStorageWriteTests.tested = true;
localStorageWriteTests.writable = false;
}
return localStorageWriteTests.writable;
};
exports.supportsLocalStorage = supportsLocalStorage;
/**
* Extracts parameters encoded in the URL both in the query and fragment.
*/
function parseParametersFromURL(href) {
const result = {};
const url = new URL(href);
if (url.hash && url.hash[0] === '#') {
try {
const hashSearchParams = new URLSearchParams(url.hash.substring(1));
hashSearchParams.forEach((value, key) => {
result[key] = value;
});
}
catch (e) {
// hash is not a query string
}
}
// search parameters take precedence over hash parameters
url.searchParams.forEach((value, key) => {
result[key] = value;
});
return result;
}
exports.parseParametersFromURL = parseParametersFromURL;
const resolveFetch = (customFetch) => {
let _fetch;
if (customFetch) {
_fetch = customFetch;
}
else if (typeof fetch === 'undefined') {
_fetch = (...args) => Promise.resolve().then(() => __importStar(require('@supabase/node-fetch'))).then(({ default: fetch }) => fetch(...args));
}
else {
_fetch = fetch;
}
return (...args) => _fetch(...args);
};
exports.resolveFetch = resolveFetch;
const looksLikeFetchResponse = (maybeResponse) => {
return (typeof maybeResponse === 'object' &&
maybeResponse !== null &&
'status' in maybeResponse &&
'ok' in maybeResponse &&
'json' in maybeResponse &&
typeof maybeResponse.json === 'function');
};
exports.looksLikeFetchResponse = looksLikeFetchResponse;
// Storage helpers
const setItemAsync = async (storage, key, data) => {
await storage.setItem(key, JSON.stringify(data));
};
exports.setItemAsync = setItemAsync;
const getItemAsync = async (storage, key) => {
const value = await storage.getItem(key);
if (!value) {
return null;
}
try {
return JSON.parse(value);
}
catch (_a) {
return value;
}
};
exports.getItemAsync = getItemAsync;
const removeItemAsync = async (storage, key) => {
await storage.removeItem(key);
};
exports.removeItemAsync = removeItemAsync;
/**
* A deferred represents some asynchronous work that is not yet finished, which
* may or may not culminate in a value.
* Taken from: https://github.com/mike-north/types/blob/master/src/async.ts
*/
class Deferred {
constructor() {
// eslint-disable-next-line @typescript-eslint/no-extra-semi
;
this.promise = new Deferred.promiseConstructor((res, rej) => {
// eslint-disable-next-line @typescript-eslint/no-extra-semi
;
this.resolve = res;
this.reject = rej;
});
}
}
exports.Deferred = Deferred;
Deferred.promiseConstructor = Promise;
function decodeJWT(token) {
const parts = token.split('.');
if (parts.length !== 3) {
throw new errors_1.AuthInvalidJwtError('Invalid JWT structure');
}
// Regex checks for base64url format
for (let i = 0; i < parts.length; i++) {
if (!constants_1.BASE64URL_REGEX.test(parts[i])) {
throw new errors_1.AuthInvalidJwtError('JWT not in base64url format');
}
}
const data = {
// using base64url lib
header: JSON.parse((0, base64url_1.stringFromBase64URL)(parts[0])),
payload: JSON.parse((0, base64url_1.stringFromBase64URL)(parts[1])),
signature: (0, base64url_1.base64UrlToUint8Array)(parts[2]),
raw: {
header: parts[0],
payload: parts[1],
},
};
return data;
}
exports.decodeJWT = decodeJWT;
/**
* Creates a promise that resolves to null after some time.
*/
async function sleep(time) {
return await new Promise((accept) => {
setTimeout(() => accept(null), time);
});
}
exports.sleep = sleep;
/**
* Converts the provided async function into a retryable function. Each result
* or thrown error is sent to the isRetryable function which should return true
* if the function should run again.
*/
function retryable(fn, isRetryable) {
const promise = new Promise((accept, reject) => {
// eslint-disable-next-line @typescript-eslint/no-extra-semi
;
(async () => {
for (let attempt = 0; attempt < Infinity; attempt++) {
try {
const result = await fn(attempt);
if (!isRetryable(attempt, null, result)) {
accept(result);
return;
}
}
catch (e) {
if (!isRetryable(attempt, e)) {
reject(e);
return;
}
}
}
})();
});
return promise;
}
exports.retryable = retryable;
function dec2hex(dec) {
return ('0' + dec.toString(16)).substr(-2);
}
// Functions below taken from: https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs
function generatePKCEVerifier() {
const verifierLength = 56;
const array = new Uint32Array(verifierLength);
if (typeof crypto === 'undefined') {
const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
const charSetLen = charSet.length;
let verifier = '';
for (let i = 0; i < verifierLength; i++) {
verifier += charSet.charAt(Math.floor(Math.random() * charSetLen));
}
return verifier;
}
crypto.getRandomValues(array);
return Array.from(array, dec2hex).join('');
}
exports.generatePKCEVerifier = generatePKCEVerifier;
async function sha256(randomString) {
const encoder = new TextEncoder();
const encodedData = encoder.encode(randomString);
const hash = await crypto.subtle.digest('SHA-256', encodedData);
const bytes = new Uint8Array(hash);
return Array.from(bytes)
.map((c) => String.fromCharCode(c))
.join('');
}
async function generatePKCEChallenge(verifier) {
const hasCryptoSupport = typeof crypto !== 'undefined' &&
typeof crypto.subtle !== 'undefined' &&
typeof TextEncoder !== 'undefined';
if (!hasCryptoSupport) {
console.warn('WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.');
return verifier;
}
const hashed = await sha256(verifier);
return btoa(hashed).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
exports.generatePKCEChallenge = generatePKCEChallenge;
async function getCodeChallengeAndMethod(storage, storageKey, isPasswordRecovery = false) {
const codeVerifier = generatePKCEVerifier();
let storedCodeVerifier = codeVerifier;
if (isPasswordRecovery) {
storedCodeVerifier += '/PASSWORD_RECOVERY';
}
await (0, exports.setItemAsync)(storage, `${storageKey}-code-verifier`, storedCodeVerifier);
const codeChallenge = await generatePKCEChallenge(codeVerifier);
const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256';
return [codeChallenge, codeChallengeMethod];
}
exports.getCodeChallengeAndMethod = getCodeChallengeAndMethod;
/** Parses the API version which is 2YYY-MM-DD. */
const API_VERSION_REGEX = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;
function parseResponseAPIVersion(response) {
const apiVersion = response.headers.get(constants_1.API_VERSION_HEADER_NAME);
if (!apiVersion) {
return null;
}
if (!apiVersion.match(API_VERSION_REGEX)) {
return null;
}
try {
const date = new Date(`${apiVersion}T00:00:00.0Z`);
return date;
}
catch (e) {
return null;
}
}
exports.parseResponseAPIVersion = parseResponseAPIVersion;
function validateExp(exp) {
if (!exp) {
throw new Error('Missing exp claim');
}
const timeNow = Math.floor(Date.now() / 1000);
if (exp <= timeNow) {
throw new Error('JWT has expired');
}
}
exports.validateExp = validateExp;
function getAlgorithm(alg) {
switch (alg) {
case 'RS256':
return {
name: 'RSASSA-PKCS1-v1_5',
hash: { name: 'SHA-256' },
};
case 'ES256':
return {
name: 'ECDSA',
namedCurve: 'P-256',
hash: { name: 'SHA-256' },
};
default:
throw new Error('Invalid alg claim');
}
}
exports.getAlgorithm = getAlgorithm;
//# sourceMappingURL=helpers.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,13 @@
import { SupportedStorage } from './types';
/**
* Provides safe access to the globalThis.localStorage property.
*/
export declare const localStorageAdapter: SupportedStorage;
/**
* Returns a localStorage-like object that stores the key-value pairs in
* memory.
*/
export declare function memoryLocalStorageAdapter(store?: {
[key: string]: string;
}): SupportedStorage;
//# sourceMappingURL=local-storage.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"local-storage.d.ts","sourceRoot":"","sources":["../../../src/lib/local-storage.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAE1C;;GAEG;AACH,eAAO,MAAM,mBAAmB,EAAE,gBAsBjC,CAAA;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,GAAE;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;CAAO,GAAG,gBAAgB,CAcjG"}

View File

@ -0,0 +1,46 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.memoryLocalStorageAdapter = exports.localStorageAdapter = void 0;
const helpers_1 = require("./helpers");
/**
* Provides safe access to the globalThis.localStorage property.
*/
exports.localStorageAdapter = {
getItem: (key) => {
if (!(0, helpers_1.supportsLocalStorage)()) {
return null;
}
return globalThis.localStorage.getItem(key);
},
setItem: (key, value) => {
if (!(0, helpers_1.supportsLocalStorage)()) {
return;
}
globalThis.localStorage.setItem(key, value);
},
removeItem: (key) => {
if (!(0, helpers_1.supportsLocalStorage)()) {
return;
}
globalThis.localStorage.removeItem(key);
},
};
/**
* Returns a localStorage-like object that stores the key-value pairs in
* memory.
*/
function memoryLocalStorageAdapter(store = {}) {
return {
getItem: (key) => {
return store[key] || null;
},
setItem: (key, value) => {
store[key] = value;
},
removeItem: (key) => {
delete store[key];
},
};
}
exports.memoryLocalStorageAdapter = memoryLocalStorageAdapter;
//# sourceMappingURL=local-storage.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"local-storage.js","sourceRoot":"","sources":["../../../src/lib/local-storage.ts"],"names":[],"mappings":";;;AAAA,uCAAgD;AAGhD;;GAEG;AACU,QAAA,mBAAmB,GAAqB;IACnD,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE;QACf,IAAI,CAAC,IAAA,8BAAoB,GAAE,EAAE;YAC3B,OAAO,IAAI,CAAA;SACZ;QAED,OAAO,UAAU,CAAC,YAAY,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;IAC7C,CAAC;IACD,OAAO,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE;QACtB,IAAI,CAAC,IAAA,8BAAoB,GAAE,EAAE;YAC3B,OAAM;SACP;QAED,UAAU,CAAC,YAAY,CAAC,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;IAC7C,CAAC;IACD,UAAU,EAAE,CAAC,GAAG,EAAE,EAAE;QAClB,IAAI,CAAC,IAAA,8BAAoB,GAAE,EAAE;YAC3B,OAAM;SACP;QAED,UAAU,CAAC,YAAY,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;IACzC,CAAC;CACF,CAAA;AAED;;;GAGG;AACH,SAAgB,yBAAyB,CAAC,QAAmC,EAAE;IAC7E,OAAO;QACL,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE;YACf,OAAO,KAAK,CAAC,GAAG,CAAC,IAAI,IAAI,CAAA;QAC3B,CAAC;QAED,OAAO,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE;YACtB,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAA;QACpB,CAAC;QAED,UAAU,EAAE,CAAC,GAAG,EAAE,EAAE;YAClB,OAAO,KAAK,CAAC,GAAG,CAAC,CAAA;QACnB,CAAC;KACF,CAAA;AACH,CAAC;AAdD,8DAcC"}

View File

@ -0,0 +1,64 @@
/**
* @experimental
*/
export declare const internals: {
/**
* @experimental
*/
debug: boolean;
};
/**
* An error thrown when a lock cannot be acquired after some amount of time.
*
* Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`.
*/
export declare abstract class LockAcquireTimeoutError extends Error {
readonly isAcquireTimeout = true;
constructor(message: string);
}
export declare class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError {
}
export declare class ProcessLockAcquireTimeoutError extends LockAcquireTimeoutError {
}
/**
* Implements a global exclusive lock using the Navigator LockManager API. It
* is available on all browsers released after 2022-03-15 with Safari being the
* last one to release support. If the API is not available, this function will
* throw. Make sure you check availablility before configuring {@link
* GoTrueClient}.
*
* You can turn on debugging by setting the `supabase.gotrue-js.locks.debug`
* local storage item to `true`.
*
* Internals:
*
* Since the LockManager API does not preserve stack traces for the async
* function passed in the `request` method, a trick is used where acquiring the
* lock releases a previously started promise to run the operation in the `fn`
* function. The lock waits for that promise to finish (with or without error),
* while the function will finally wait for the result anyway.
*
* @param name Name of the lock to be acquired.
* @param acquireTimeout If negative, no timeout. If 0 an error is thrown if
* the lock can't be acquired without waiting. If positive, the lock acquire
* will time out after so many milliseconds. An error is
* a timeout if it has `isAcquireTimeout` set to true.
* @param fn The operation to run once the lock is acquired.
*/
export declare function navigatorLock<R>(name: string, acquireTimeout: number, fn: () => Promise<R>): Promise<R>;
/**
* Implements a global exclusive lock that works only in the current process.
* Useful for environments like React Native or other non-browser
* single-process (i.e. no concept of "tabs") environments.
*
* Use {@link #navigatorLock} in browser environments.
*
* @param name Name of the lock to be acquired.
* @param acquireTimeout If negative, no timeout. If 0 an error is thrown if
* the lock can't be acquired without waiting. If positive, the lock acquire
* will time out after so many milliseconds. An error is
* a timeout if it has `isAcquireTimeout` set to true.
* @param fn The operation to run once the lock is acquired.
*/
export declare function processLock<R>(name: string, acquireTimeout: number, fn: () => Promise<R>): Promise<R>;
//# sourceMappingURL=locks.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"locks.d.ts","sourceRoot":"","sources":["../../../src/lib/locks.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,eAAO,MAAM,SAAS;IACpB;;OAEG;;CAOJ,CAAA;AAED;;;;GAIG;AACH,8BAAsB,uBAAwB,SAAQ,KAAK;IACzD,SAAgB,gBAAgB,QAAO;gBAE3B,OAAO,EAAE,MAAM;CAG5B;AAED,qBAAa,gCAAiC,SAAQ,uBAAuB;CAAG;AAChF,qBAAa,8BAA+B,SAAQ,uBAAuB;CAAG;AAE9E;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAsB,aAAa,CAAC,CAAC,EACnC,IAAI,EAAE,MAAM,EACZ,cAAc,EAAE,MAAM,EACtB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACnB,OAAO,CAAC,CAAC,CAAC,CA0FZ;AAID;;;;;;;;;;;;;GAaG;AACH,wBAAsB,WAAW,CAAC,CAAC,EACjC,IAAI,EAAE,MAAM,EACZ,cAAc,EAAE,MAAM,EACtB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACnB,OAAO,CAAC,CAAC,CAAC,CAkDZ"}

187
node_modules/@supabase/auth-js/dist/main/lib/locks.js generated vendored Normal file
View File

@ -0,0 +1,187 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.processLock = exports.navigatorLock = exports.ProcessLockAcquireTimeoutError = exports.NavigatorLockAcquireTimeoutError = exports.LockAcquireTimeoutError = exports.internals = void 0;
const helpers_1 = require("./helpers");
/**
* @experimental
*/
exports.internals = {
/**
* @experimental
*/
debug: !!(globalThis &&
(0, helpers_1.supportsLocalStorage)() &&
globalThis.localStorage &&
globalThis.localStorage.getItem('supabase.gotrue-js.locks.debug') === 'true'),
};
/**
* An error thrown when a lock cannot be acquired after some amount of time.
*
* Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`.
*/
class LockAcquireTimeoutError extends Error {
constructor(message) {
super(message);
this.isAcquireTimeout = true;
}
}
exports.LockAcquireTimeoutError = LockAcquireTimeoutError;
class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError {
}
exports.NavigatorLockAcquireTimeoutError = NavigatorLockAcquireTimeoutError;
class ProcessLockAcquireTimeoutError extends LockAcquireTimeoutError {
}
exports.ProcessLockAcquireTimeoutError = ProcessLockAcquireTimeoutError;
/**
* Implements a global exclusive lock using the Navigator LockManager API. It
* is available on all browsers released after 2022-03-15 with Safari being the
* last one to release support. If the API is not available, this function will
* throw. Make sure you check availablility before configuring {@link
* GoTrueClient}.
*
* You can turn on debugging by setting the `supabase.gotrue-js.locks.debug`
* local storage item to `true`.
*
* Internals:
*
* Since the LockManager API does not preserve stack traces for the async
* function passed in the `request` method, a trick is used where acquiring the
* lock releases a previously started promise to run the operation in the `fn`
* function. The lock waits for that promise to finish (with or without error),
* while the function will finally wait for the result anyway.
*
* @param name Name of the lock to be acquired.
* @param acquireTimeout If negative, no timeout. If 0 an error is thrown if
* the lock can't be acquired without waiting. If positive, the lock acquire
* will time out after so many milliseconds. An error is
* a timeout if it has `isAcquireTimeout` set to true.
* @param fn The operation to run once the lock is acquired.
*/
async function navigatorLock(name, acquireTimeout, fn) {
if (exports.internals.debug) {
console.log('@supabase/gotrue-js: navigatorLock: acquire lock', name, acquireTimeout);
}
const abortController = new globalThis.AbortController();
if (acquireTimeout > 0) {
setTimeout(() => {
abortController.abort();
if (exports.internals.debug) {
console.log('@supabase/gotrue-js: navigatorLock acquire timed out', name);
}
}, acquireTimeout);
}
// MDN article: https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request
// Wrapping navigator.locks.request() with a plain Promise is done as some
// libraries like zone.js patch the Promise object to track the execution
// context. However, it appears that most browsers use an internal promise
// implementation when using the navigator.locks.request() API causing them
// to lose context and emit confusing log messages or break certain features.
// This wrapping is believed to help zone.js track the execution context
// better.
return await Promise.resolve().then(() => globalThis.navigator.locks.request(name, acquireTimeout === 0
? {
mode: 'exclusive',
ifAvailable: true,
}
: {
mode: 'exclusive',
signal: abortController.signal,
}, async (lock) => {
if (lock) {
if (exports.internals.debug) {
console.log('@supabase/gotrue-js: navigatorLock: acquired', name, lock.name);
}
try {
return await fn();
}
finally {
if (exports.internals.debug) {
console.log('@supabase/gotrue-js: navigatorLock: released', name, lock.name);
}
}
}
else {
if (acquireTimeout === 0) {
if (exports.internals.debug) {
console.log('@supabase/gotrue-js: navigatorLock: not immediately available', name);
}
throw new NavigatorLockAcquireTimeoutError(`Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed`);
}
else {
if (exports.internals.debug) {
try {
const result = await globalThis.navigator.locks.query();
console.log('@supabase/gotrue-js: Navigator LockManager state', JSON.stringify(result, null, ' '));
}
catch (e) {
console.warn('@supabase/gotrue-js: Error when querying Navigator LockManager state', e);
}
}
// Browser is not following the Navigator LockManager spec, it
// returned a null lock when we didn't use ifAvailable. So we can
// pretend the lock is acquired in the name of backward compatibility
// and user experience and just run the function.
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');
return await fn();
}
}
}));
}
exports.navigatorLock = navigatorLock;
const PROCESS_LOCKS = {};
/**
* Implements a global exclusive lock that works only in the current process.
* Useful for environments like React Native or other non-browser
* single-process (i.e. no concept of "tabs") environments.
*
* Use {@link #navigatorLock} in browser environments.
*
* @param name Name of the lock to be acquired.
* @param acquireTimeout If negative, no timeout. If 0 an error is thrown if
* the lock can't be acquired without waiting. If positive, the lock acquire
* will time out after so many milliseconds. An error is
* a timeout if it has `isAcquireTimeout` set to true.
* @param fn The operation to run once the lock is acquired.
*/
async function processLock(name, acquireTimeout, fn) {
var _a;
const previousOperation = (_a = PROCESS_LOCKS[name]) !== null && _a !== void 0 ? _a : Promise.resolve();
const currentOperation = Promise.race([
previousOperation.catch(() => {
// ignore error of previous operation that we're waiting to finish
return null;
}),
acquireTimeout >= 0
? new Promise((_, reject) => {
setTimeout(() => {
reject(new ProcessLockAcquireTimeoutError(`Acquring process lock with name "${name}" timed out`));
}, acquireTimeout);
})
: null,
].filter((x) => x))
.catch((e) => {
if (e && e.isAcquireTimeout) {
throw e;
}
return null;
})
.then(async () => {
// previous operations finished and we didn't get a race on the acquire
// timeout, so the current operation can finally start
return await fn();
});
PROCESS_LOCKS[name] = currentOperation.catch(async (e) => {
if (e && e.isAcquireTimeout) {
// if the current operation timed out, it doesn't mean that the previous
// operation finished, so we need contnue waiting for it to finish
await previousOperation;
return null;
}
throw e;
});
// finally wait for the current operation to finish successfully, with an
// error or with an acquire timeout error
return await currentOperation;
}
exports.processLock = processLock;
//# sourceMappingURL=locks.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"locks.js","sourceRoot":"","sources":["../../../src/lib/locks.ts"],"names":[],"mappings":";;;AAAA,uCAAgD;AAEhD;;GAEG;AACU,QAAA,SAAS,GAAG;IACvB;;OAEG;IACH,KAAK,EAAE,CAAC,CAAC,CACP,UAAU;QACV,IAAA,8BAAoB,GAAE;QACtB,UAAU,CAAC,YAAY;QACvB,UAAU,CAAC,YAAY,CAAC,OAAO,CAAC,gCAAgC,CAAC,KAAK,MAAM,CAC7E;CACF,CAAA;AAED;;;;GAIG;AACH,MAAsB,uBAAwB,SAAQ,KAAK;IAGzD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAA;QAHA,qBAAgB,GAAG,IAAI,CAAA;IAIvC,CAAC;CACF;AAND,0DAMC;AAED,MAAa,gCAAiC,SAAQ,uBAAuB;CAAG;AAAhF,4EAAgF;AAChF,MAAa,8BAA+B,SAAQ,uBAAuB;CAAG;AAA9E,wEAA8E;AAE9E;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACI,KAAK,UAAU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C;QACF,cAAc,IAAI,CAAC;YACjB,CAAC,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE;gBACxB,UAAU,CAAC,GAAG,EAAE;oBACd,MAAM,CACJ,IAAI,8BAA8B,CAChC,oCAAoC,IAAI,aAAa,CACtD,CACF,CAAA;gBACH,CAAC,EAAE,cAAc,CAAC,CAAA;YACpB,CAAC,CAAC;YACJ,CAAC,CAAC,IAAI;KACT,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CACnB;SACE,KAAK,CAAC,CAAC,CAAM,EAAE,EAAE;QAChB,IAAI,CAAC,IAAI,CAAC,CAAC,gBAAgB,EAAE;YAC3B,MAAM,CAAC,CAAA;SACR;QAED,OAAO,IAAI,CAAA;IACb,CAAC,CAAC;SACD,IAAI,CAAC,KAAK,IAAI,EAAE;QACf,uEAAuE;QACvE,sDAAsD;QACtD,OAAO,MAAM,EAAE,EAAE,CAAA;IACnB,CAAC,CAAC,CAAA;IAEJ,aAAa,CAAC,IAAI,CAAC,GAAG,gBAAgB,CAAC,KAAK,CAAC,KAAK,EAAE,CAAM,EAAE,EAAE;QAC5D,IAAI,CAAC,IAAI,CAAC,CAAC,gBAAgB,EAAE;YAC3B,wEAAwE;YACxE,kEAAkE;YAClE,MAAM,iBAAiB,CAAA;YAEvB,OAAO,IAAI,CAAA;SACZ;QAED,MAAM,CAAC,CAAA;IACT,CAAC,CAAC,CAAA;IAEF,yEAAyE;IACzE,yCAAyC;IACzC,OAAO,MAAM,gBAAgB,CAAA;AAC/B,CAAC;AAtDD,kCAsDC"}

View File

@ -0,0 +1,5 @@
/**
* https://mathiasbynens.be/notes/globalthis
*/
export declare function polyfillGlobalThis(): void;
//# sourceMappingURL=polyfills.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"polyfills.d.ts","sourceRoot":"","sources":["../../../src/lib/polyfills.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,wBAAgB,kBAAkB,SAmBjC"}

View File

@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.polyfillGlobalThis = void 0;
/**
* https://mathiasbynens.be/notes/globalthis
*/
function polyfillGlobalThis() {
if (typeof globalThis === 'object')
return;
try {
Object.defineProperty(Object.prototype, '__magic__', {
get: function () {
return this;
},
configurable: true,
});
// @ts-expect-error 'Allow access to magic'
__magic__.globalThis = __magic__;
// @ts-expect-error 'Allow access to magic'
delete Object.prototype.__magic__;
}
catch (e) {
if (typeof self !== 'undefined') {
// @ts-expect-error 'Allow access to globals'
self.globalThis = self;
}
}
}
exports.polyfillGlobalThis = polyfillGlobalThis;
//# sourceMappingURL=polyfills.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"polyfills.js","sourceRoot":"","sources":["../../../src/lib/polyfills.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,SAAgB,kBAAkB;IAChC,IAAI,OAAO,UAAU,KAAK,QAAQ;QAAE,OAAM;IAC1C,IAAI;QACF,MAAM,CAAC,cAAc,CAAC,MAAM,CAAC,SAAS,EAAE,WAAW,EAAE;YACnD,GAAG,EAAE;gBACH,OAAO,IAAI,CAAA;YACb,CAAC;YACD,YAAY,EAAE,IAAI;SACnB,CAAC,CAAA;QACF,2CAA2C;QAC3C,SAAS,CAAC,UAAU,GAAG,SAAS,CAAA;QAChC,2CAA2C;QAC3C,OAAO,MAAM,CAAC,SAAS,CAAC,SAAS,CAAA;KAClC;IAAC,OAAO,CAAC,EAAE;QACV,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;YAC/B,6CAA6C;YAC7C,IAAI,CAAC,UAAU,GAAG,IAAI,CAAA;SACvB;KACF;AACH,CAAC;AAnBD,gDAmBC"}

1041
node_modules/@supabase/auth-js/dist/main/lib/types.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=types.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":""}

View File

@ -0,0 +1,2 @@
export declare const version = "2.69.1";
//# sourceMappingURL=version.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,WAAW,CAAA"}

View File

@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.version = void 0;
exports.version = '2.69.1';
//# sourceMappingURL=version.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":";;;AAAa,QAAA,OAAO,GAAG,QAAQ,CAAA"}

View File

@ -0,0 +1,4 @@
import GoTrueAdminApi from './GoTrueAdminApi';
declare const AuthAdminApi: typeof GoTrueAdminApi;
export default AuthAdminApi;
//# sourceMappingURL=AuthAdminApi.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"AuthAdminApi.d.ts","sourceRoot":"","sources":["../../src/AuthAdminApi.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAE7C,QAAA,MAAM,YAAY,uBAAiB,CAAA;AAEnC,eAAe,YAAY,CAAA"}

View File

@ -0,0 +1,4 @@
import GoTrueAdminApi from './GoTrueAdminApi';
const AuthAdminApi = GoTrueAdminApi;
export default AuthAdminApi;
//# sourceMappingURL=AuthAdminApi.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"AuthAdminApi.js","sourceRoot":"","sources":["../../src/AuthAdminApi.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAE7C,MAAM,YAAY,GAAG,cAAc,CAAA;AAEnC,eAAe,YAAY,CAAA"}

View File

@ -0,0 +1,4 @@
import GoTrueClient from './GoTrueClient';
declare const AuthClient: typeof GoTrueClient;
export default AuthClient;
//# sourceMappingURL=AuthClient.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"AuthClient.d.ts","sourceRoot":"","sources":["../../src/AuthClient.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,MAAM,gBAAgB,CAAA;AAEzC,QAAA,MAAM,UAAU,qBAAe,CAAA;AAE/B,eAAe,UAAU,CAAA"}

View File

@ -0,0 +1,4 @@
import GoTrueClient from './GoTrueClient';
const AuthClient = GoTrueClient;
export default AuthClient;
//# sourceMappingURL=AuthClient.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"AuthClient.js","sourceRoot":"","sources":["../../src/AuthClient.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,MAAM,gBAAgB,CAAA;AAEzC,MAAM,UAAU,GAAG,YAAY,CAAA;AAE/B,eAAe,UAAU,CAAA"}

View File

@ -0,0 +1,99 @@
import { Fetch } from './lib/fetch';
import { AdminUserAttributes, GenerateLinkParams, GenerateLinkResponse, Pagination, User, UserResponse, GoTrueAdminMFAApi, PageParams } from './lib/types';
import { AuthError } from './lib/errors';
export default class GoTrueAdminApi {
/** Contains all MFA administration methods. */
mfa: GoTrueAdminMFAApi;
protected url: string;
protected headers: {
[key: string]: string;
};
protected fetch: Fetch;
constructor({ url, headers, fetch, }: {
url: string;
headers?: {
[key: string]: string;
};
fetch?: Fetch;
});
/**
* Removes a logged-in session.
* @param jwt A valid, logged-in JWT.
* @param scope The logout sope.
*/
signOut(jwt: string, scope?: 'global' | 'local' | 'others'): Promise<{
data: null;
error: AuthError | null;
}>;
/**
* Sends an invite link to an email address.
* @param email The email address of the user.
* @param options Additional options to be included when inviting.
*/
inviteUserByEmail(email: string, options?: {
/** A custom data object to store additional metadata about the user. This maps to the `auth.users.user_metadata` column. */
data?: object;
/** The URL which will be appended to the email link sent to the user's email address. Once clicked the user will end up on this URL. */
redirectTo?: string;
}): Promise<UserResponse>;
/**
* Generates email links and OTPs to be sent via a custom email provider.
* @param email The user's email.
* @param options.password User password. For signup only.
* @param options.data Optional user metadata. For signup only.
* @param options.redirectTo The redirect url which should be appended to the generated link
*/
generateLink(params: GenerateLinkParams): Promise<GenerateLinkResponse>;
/**
* Creates a new user.
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
createUser(attributes: AdminUserAttributes): Promise<UserResponse>;
/**
* Get a list of users.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
* @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results.
*/
listUsers(params?: PageParams): Promise<{
data: {
users: User[];
aud: string;
} & Pagination;
error: null;
} | {
data: {
users: [];
};
error: AuthError;
}>;
/**
* Get user by id.
*
* @param uid The user's unique identifier
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
getUserById(uid: string): Promise<UserResponse>;
/**
* Updates the user data.
*
* @param attributes The data you want to update.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
updateUserById(uid: string, attributes: AdminUserAttributes): Promise<UserResponse>;
/**
* Delete a user. Requires a `service_role` key.
*
* @param id The user id you want to remove.
* @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible.
* Defaults to false for backward compatibility.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
deleteUser(id: string, shouldSoftDelete?: boolean): Promise<UserResponse>;
private _listFactors;
private _deleteFactor;
}
//# sourceMappingURL=GoTrueAdminApi.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"GoTrueAdminApi.d.ts","sourceRoot":"","sources":["../../src/GoTrueAdminApi.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EAKN,MAAM,aAAa,CAAA;AAEpB,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,oBAAoB,EACpB,UAAU,EACV,IAAI,EACJ,YAAY,EACZ,iBAAiB,EAKjB,UAAU,EACX,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,SAAS,EAAe,MAAM,cAAc,CAAA;AAErD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AAK,EAAE,IAAI,CAAA;KAAE,GAClE;QAAE,IAAI,EAAE;YAAE,KAAK,EAAE,EAAE,CAAA;SAAE,CAAC;QAAC,KAAK,EAAE,SAAS,CAAA;KAAE,CAC5C;IAmCD;;;;;;OAMG;IACG,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;IAerD;;;;;;OAMG;IACG,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,mBAAmB,GAAG,OAAO,CAAC,YAAY,CAAC;IAgBzF;;;;;;;;OAQG;IACG,UAAU,CAAC,EAAE,EAAE,MAAM,EAAE,gBAAgB,UAAQ,GAAG,OAAO,CAAC,YAAY,CAAC;YAkB/D,YAAY;YAyBZ,aAAa;CAsB5B"}

View File

@ -0,0 +1,265 @@
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import { _generateLinkResponse, _noResolveJsonResponse, _request, _userResponse, } from './lib/fetch';
import { resolveFetch } from './lib/helpers';
import { isAuthError } from './lib/errors';
export default class GoTrueAdminApi {
constructor({ url = '', headers = {}, fetch, }) {
this.url = url;
this.headers = headers;
this.fetch = resolveFetch(fetch);
this.mfa = {
listFactors: this._listFactors.bind(this),
deleteFactor: this._deleteFactor.bind(this),
};
}
/**
* Removes a logged-in session.
* @param jwt A valid, logged-in JWT.
* @param scope The logout sope.
*/
async signOut(jwt, scope = 'global') {
try {
await _request(this.fetch, 'POST', `${this.url}/logout?scope=${scope}`, {
headers: this.headers,
jwt,
noResolveJson: true,
});
return { data: null, error: null };
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* Sends an invite link to an email address.
* @param email The email address of the user.
* @param options Additional options to be included when inviting.
*/
async inviteUserByEmail(email, options = {}) {
try {
return await _request(this.fetch, 'POST', `${this.url}/invite`, {
body: { email, data: options.data },
headers: this.headers,
redirectTo: options.redirectTo,
xform: _userResponse,
});
}
catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
/**
* Generates email links and OTPs to be sent via a custom email provider.
* @param email The user's email.
* @param options.password User password. For signup only.
* @param options.data Optional user metadata. For signup only.
* @param options.redirectTo The redirect url which should be appended to the generated link
*/
async generateLink(params) {
try {
const { options } = params, rest = __rest(params, ["options"]);
const body = Object.assign(Object.assign({}, rest), options);
if ('newEmail' in rest) {
// replace newEmail with new_email in request body
body.new_email = rest === null || rest === void 0 ? void 0 : rest.newEmail;
delete body['newEmail'];
}
return await _request(this.fetch, 'POST', `${this.url}/admin/generate_link`, {
body: body,
headers: this.headers,
xform: _generateLinkResponse,
redirectTo: options === null || options === void 0 ? void 0 : options.redirectTo,
});
}
catch (error) {
if (isAuthError(error)) {
return {
data: {
properties: null,
user: null,
},
error,
};
}
throw error;
}
}
// User Admin API
/**
* Creates a new user.
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
async createUser(attributes) {
try {
return await _request(this.fetch, 'POST', `${this.url}/admin/users`, {
body: attributes,
headers: this.headers,
xform: _userResponse,
});
}
catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
/**
* Get a list of users.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
* @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results.
*/
async listUsers(params) {
var _a, _b, _c, _d, _e, _f, _g;
try {
const pagination = { nextPage: null, lastPage: 0, total: 0 };
const response = await _request(this.fetch, 'GET', `${this.url}/admin/users`, {
headers: this.headers,
noResolveJson: true,
query: {
page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '',
per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '',
},
xform: _noResolveJsonResponse,
});
if (response.error)
throw response.error;
const users = await response.json();
const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0;
const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : [];
if (links.length > 0) {
links.forEach((link) => {
const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1));
const rel = JSON.parse(link.split(';')[1].split('=')[1]);
pagination[`${rel}Page`] = page;
});
pagination.total = parseInt(total);
}
return { data: Object.assign(Object.assign({}, users), pagination), error: null };
}
catch (error) {
if (isAuthError(error)) {
return { data: { users: [] }, error };
}
throw error;
}
}
/**
* Get user by id.
*
* @param uid The user's unique identifier
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
async getUserById(uid) {
try {
return await _request(this.fetch, 'GET', `${this.url}/admin/users/${uid}`, {
headers: this.headers,
xform: _userResponse,
});
}
catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
/**
* Updates the user data.
*
* @param attributes The data you want to update.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
async updateUserById(uid, attributes) {
try {
return await _request(this.fetch, 'PUT', `${this.url}/admin/users/${uid}`, {
body: attributes,
headers: this.headers,
xform: _userResponse,
});
}
catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
/**
* Delete a user. Requires a `service_role` key.
*
* @param id The user id you want to remove.
* @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible.
* Defaults to false for backward compatibility.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
async deleteUser(id, shouldSoftDelete = false) {
try {
return await _request(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, {
headers: this.headers,
body: {
should_soft_delete: shouldSoftDelete,
},
xform: _userResponse,
});
}
catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
async _listFactors(params) {
try {
const { data, error } = await _request(this.fetch, 'GET', `${this.url}/admin/users/${params.userId}/factors`, {
headers: this.headers,
xform: (factors) => {
return { data: { factors }, error: null };
},
});
return { data, error };
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
async _deleteFactor(params) {
try {
const data = await _request(this.fetch, 'DELETE', `${this.url}/admin/users/${params.userId}/factors/${params.id}`, {
headers: this.headers,
});
return { data, error: null };
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
}
//# sourceMappingURL=GoTrueAdminApi.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,474 @@
import GoTrueAdminApi from './GoTrueAdminApi';
import { AuthError } from './lib/errors';
import { Fetch } from './lib/fetch';
import { Deferred } from './lib/helpers';
import type { AuthChangeEvent, AuthResponse, AuthTokenResponse, AuthTokenResponsePassword, AuthOtpResponse, CallRefreshTokenResult, GoTrueClientOptions, InitializeResult, OAuthResponse, SSOResponse, Session, SignInWithIdTokenCredentials, SignInWithOAuthCredentials, SignInWithPasswordCredentials, SignInWithPasswordlessCredentials, SignUpWithPasswordCredentials, SignInWithSSO, SignOut, Subscription, SupportedStorage, UserAttributes, UserResponse, VerifyOtpParams, GoTrueMFAApi, ResendParams, AuthFlowType, LockFunc, UserIdentity, SignInAnonymouslyCredentials, JWK, JwtPayload, JwtHeader } from './lib/types';
export default class GoTrueClient {
private static nextInstanceID;
private instanceID;
/**
* Namespace for the GoTrue admin methods.
* These methods should only be used in a trusted server-side environment.
*/
admin: GoTrueAdminApi;
/**
* Namespace for the MFA methods.
*/
mfa: GoTrueMFAApi;
/**
* The storage key used to identify the values saved in localStorage
*/
protected storageKey: string;
protected flowType: AuthFlowType;
/**
* The JWKS used for verifying asymmetric JWTs
*/
protected jwks: {
keys: JWK[];
};
protected jwks_cached_at: number;
protected autoRefreshToken: boolean;
protected persistSession: boolean;
protected storage: SupportedStorage;
protected memoryStorage: {
[key: string]: string;
} | null;
protected stateChangeEmitters: Map<string, Subscription>;
protected autoRefreshTicker: ReturnType<typeof setInterval> | null;
protected visibilityChangedCallback: (() => Promise<any>) | null;
protected refreshingDeferred: Deferred<CallRefreshTokenResult> | null;
/**
* Keeps track of the async client initialization.
* When null or not yet resolved the auth state is `unknown`
* Once resolved the the auth state is known and it's save to call any further client methods.
* Keep extra care to never reject or throw uncaught errors
*/
protected initializePromise: Promise<InitializeResult> | null;
protected detectSessionInUrl: boolean;
protected url: string;
protected headers: {
[key: string]: string;
};
protected hasCustomAuthorizationHeader: boolean;
protected suppressGetSessionWarning: boolean;
protected fetch: Fetch;
protected lock: LockFunc;
protected lockAcquired: boolean;
protected pendingInLock: Promise<any>[];
/**
* Used to broadcast state change events to other tabs listening.
*/
protected broadcastChannel: BroadcastChannel | null;
protected logDebugMessages: boolean;
protected logger: (message: string, ...args: any[]) => void;
/**
* Create a new client for use in the browser.
*/
constructor(options: GoTrueClientOptions);
private _debug;
/**
* Initializes the client session either from the url or from storage.
* This method is automatically called when instantiating the client, but should also be called
* manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc).
*/
initialize(): Promise<InitializeResult>;
/**
* IMPORTANT:
* 1. Never throw in this method, as it is called from the constructor
* 2. Never return a session from this method as it would be cached over
* the whole lifetime of the client
*/
private _initialize;
/**
* Creates a new anonymous user.
*
* @returns A session where the is_anonymous claim in the access token JWT set to true
*/
signInAnonymously(credentials?: SignInAnonymouslyCredentials): Promise<AuthResponse>;
/**
* Creates a new user.
*
* Be aware that if a user account exists in the system you may get back an
* error message that attempts to hide this information from the user.
* This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled.
*
* @returns A logged-in session if the server has "autoconfirm" ON
* @returns A user if the server has "autoconfirm" OFF
*/
signUp(credentials: SignUpWithPasswordCredentials): Promise<AuthResponse>;
/**
* Log in an existing user with an email and password or phone and password.
*
* Be aware that you may get back an error message that will not distinguish
* between the cases where the account does not exist or that the
* email/phone and password combination is wrong or that the account can only
* be accessed via social login.
*/
signInWithPassword(credentials: SignInWithPasswordCredentials): Promise<AuthTokenResponsePassword>;
/**
* Log in an existing user via a third-party provider.
* This method supports the PKCE flow.
*/
signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse>;
/**
* Log in an existing user by exchanging an Auth Code issued during the PKCE flow.
*/
exchangeCodeForSession(authCode: string): Promise<AuthTokenResponse>;
private _exchangeCodeForSession;
/**
* Allows signing in with an OIDC ID token. The authentication provider used
* should be enabled and configured.
*/
signInWithIdToken(credentials: SignInWithIdTokenCredentials): Promise<AuthTokenResponse>;
/**
* Log in a user using magiclink or a one-time password (OTP).
*
* If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent.
* If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent.
* If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins.
*
* Be aware that you may get back an error message that will not distinguish
* between the cases where the account does not exist or, that the account
* can only be accessed via social login.
*
* Do note that you will need to configure a Whatsapp sender on Twilio
* if you are using phone sign in with the 'whatsapp' channel. The whatsapp
* channel is not supported on other providers
* at this time.
* This method supports PKCE when an email is passed.
*/
signInWithOtp(credentials: SignInWithPasswordlessCredentials): Promise<AuthOtpResponse>;
/**
* Log in a user given a User supplied OTP or TokenHash received through mobile or email.
*/
verifyOtp(params: VerifyOtpParams): Promise<AuthResponse>;
/**
* Attempts a single-sign on using an enterprise Identity Provider. A
* successful SSO attempt will redirect the current page to the identity
* provider authorization page. The redirect URL is implementation and SSO
* protocol specific.
*
* You can use it by providing a SSO domain. Typically you can extract this
* domain by asking users for their email address. If this domain is
* registered on the Auth instance the redirect will use that organization's
* currently active SSO Identity Provider for the login.
*
* If you have built an organization-specific login page, you can use the
* organization's SSO Identity Provider UUID directly instead.
*/
signInWithSSO(params: SignInWithSSO): Promise<SSOResponse>;
/**
* Sends a reauthentication OTP to the user's email or phone number.
* Requires the user to be signed-in.
*/
reauthenticate(): Promise<AuthResponse>;
private _reauthenticate;
/**
* Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP.
*/
resend(credentials: ResendParams): Promise<AuthOtpResponse>;
/**
* Returns the session, refreshing it if necessary.
*
* The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out.
*
* **IMPORTANT:** This method loads values directly from the storage attached
* to the client. If that storage is based on request cookies for example,
* the values in it may not be authentic and therefore it's strongly advised
* against using this method and its results in such circumstances. A warning
* will be emitted if this is detected. Use {@link #getUser()} instead.
*/
getSession(): Promise<{
data: {
session: Session;
};
error: null;
} | {
data: {
session: null;
};
error: AuthError;
} | {
data: {
session: null;
};
error: null;
}>;
/**
* Acquires a global lock based on the storage key.
*/
private _acquireLock;
/**
* Use instead of {@link #getSession} inside the library. It is
* semantically usually what you want, as getting a session involves some
* processing afterwards that requires only one client operating on the
* session at once across multiple tabs or processes.
*/
private _useSession;
/**
* NEVER USE DIRECTLY!
*
* Always use {@link #_useSession}.
*/
private __loadSession;
/**
* Gets the current user details if there is an existing session. This method
* performs a network request to the Supabase Auth server, so the returned
* value is authentic and can be used to base authorization rules on.
*
* @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used.
*/
getUser(jwt?: string): Promise<UserResponse>;
private _getUser;
/**
* Updates user data for a logged in user.
*/
updateUser(attributes: UserAttributes, options?: {
emailRedirectTo?: string | undefined;
}): Promise<UserResponse>;
protected _updateUser(attributes: UserAttributes, options?: {
emailRedirectTo?: string | undefined;
}): Promise<UserResponse>;
/**
* Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session.
* If the refresh token or access token in the current session is invalid, an error will be thrown.
* @param currentSession The current session that minimally contains an access token and refresh token.
*/
setSession(currentSession: {
access_token: string;
refresh_token: string;
}): Promise<AuthResponse>;
protected _setSession(currentSession: {
access_token: string;
refresh_token: string;
}): Promise<AuthResponse>;
/**
* Returns a new session, regardless of expiry status.
* Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession().
* If the current session's refresh token is invalid, an error will be thrown.
* @param currentSession The current session. If passed in, it must contain a refresh token.
*/
refreshSession(currentSession?: {
refresh_token: string;
}): Promise<AuthResponse>;
protected _refreshSession(currentSession?: {
refresh_token: string;
}): Promise<AuthResponse>;
/**
* Gets the session data from a URL string
*/
private _getSessionFromURL;
/**
* Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2)
*/
private _isImplicitGrantCallback;
/**
* Checks if the current URL and backing storage contain parameters given by a PKCE flow
*/
private _isPKCECallback;
/**
* Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event.
*
* For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`.
* There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason.
*
* If using `others` scope, no `SIGNED_OUT` event is fired!
*/
signOut(options?: SignOut): Promise<{
error: AuthError | null;
}>;
protected _signOut({ scope }?: SignOut): Promise<{
error: AuthError | null;
}>;
/**
* Receive a notification every time an auth event happens.
* @param callback A callback function to be invoked when an auth event happens.
*/
onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => void | Promise<void>): {
data: {
subscription: Subscription;
};
};
private _emitInitialSession;
/**
* Sends a password reset request to an email address. This method supports the PKCE flow.
*
* @param email The email address of the user.
* @param options.redirectTo The URL to send the user to after they click the password reset link.
* @param options.captchaToken Verification token received when the user completes the captcha on the site.
*/
resetPasswordForEmail(email: string, options?: {
redirectTo?: string;
captchaToken?: string;
}): Promise<{
data: {};
error: null;
} | {
data: null;
error: AuthError;
}>;
/**
* Gets all the identities linked to a user.
*/
getUserIdentities(): Promise<{
data: {
identities: UserIdentity[];
};
error: null;
} | {
data: null;
error: AuthError;
}>;
/**
* Links an oauth identity to an existing user.
* This method supports the PKCE flow.
*/
linkIdentity(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse>;
/**
* Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked.
*/
unlinkIdentity(identity: UserIdentity): Promise<{
data: {};
error: null;
} | {
data: null;
error: AuthError;
}>;
/**
* Generates a new JWT.
* @param refreshToken A valid refresh token that was returned on login.
*/
private _refreshAccessToken;
private _isValidSession;
private _handleProviderSignIn;
/**
* Recovers the session from LocalStorage and refreshes the token
* Note: this method is async to accommodate for AsyncStorage e.g. in React native.
*/
private _recoverAndRefresh;
private _callRefreshToken;
private _notifyAllSubscribers;
/**
* set currentSession and currentUser
* process to _startAutoRefreshToken if possible
*/
private _saveSession;
private _removeSession;
/**
* Removes any registered visibilitychange callback.
*
* {@see #startAutoRefresh}
* {@see #stopAutoRefresh}
*/
private _removeVisibilityChangedCallback;
/**
* This is the private implementation of {@link #startAutoRefresh}. Use this
* within the library.
*/
private _startAutoRefresh;
/**
* This is the private implementation of {@link #stopAutoRefresh}. Use this
* within the library.
*/
private _stopAutoRefresh;
/**
* Starts an auto-refresh process in the background. The session is checked
* every few seconds. Close to the time of expiration a process is started to
* refresh the session. If refreshing fails it will be retried for as long as
* necessary.
*
* If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need
* to call this function, it will be called for you.
*
* On browsers the refresh process works only when the tab/window is in the
* foreground to conserve resources as well as prevent race conditions and
* flooding auth with requests. If you call this method any managed
* visibility change callback will be removed and you must manage visibility
* changes on your own.
*
* On non-browser platforms the refresh process works *continuously* in the
* background, which may not be desirable. You should hook into your
* platform's foreground indication mechanism and call these methods
* appropriately to conserve resources.
*
* {@see #stopAutoRefresh}
*/
startAutoRefresh(): Promise<void>;
/**
* Stops an active auto refresh process running in the background (if any).
*
* If you call this method any managed visibility change callback will be
* removed and you must manage visibility changes on your own.
*
* See {@link #startAutoRefresh} for more details.
*/
stopAutoRefresh(): Promise<void>;
/**
* Runs the auto refresh token tick.
*/
private _autoRefreshTokenTick;
/**
* Registers callbacks on the browser / platform, which in-turn run
* algorithms when the browser window/tab are in foreground. On non-browser
* platforms it assumes always foreground.
*/
private _handleVisibilityChange;
/**
* Callback registered with `window.addEventListener('visibilitychange')`.
*/
private _onVisibilityChanged;
/**
* Generates the relevant login URL for a third-party provider.
* @param options.redirectTo A URL or mobile address to send the user to after they are confirmed.
* @param options.scopes A space-separated list of scopes granted to the OAuth application.
* @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application.
*/
private _getUrlForProvider;
private _unenroll;
/**
* {@see GoTrueMFAApi#enroll}
*/
private _enroll;
/**
* {@see GoTrueMFAApi#verify}
*/
private _verify;
/**
* {@see GoTrueMFAApi#challenge}
*/
private _challenge;
/**
* {@see GoTrueMFAApi#challengeAndVerify}
*/
private _challengeAndVerify;
/**
* {@see GoTrueMFAApi#listFactors}
*/
private _listFactors;
/**
* {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel}
*/
private _getAuthenticatorAssuranceLevel;
private fetchJwk;
/**
* @experimental This method may change in future versions.
* @description Gets the claims from a JWT. If the JWT is symmetric JWTs, it will call getUser() to verify against the server. If the JWT is asymmetric, it will be verified against the JWKS using the WebCrypto API.
*/
getClaims(jwt?: string, jwks?: {
keys: JWK[];
}): Promise<{
data: {
claims: JwtPayload;
header: JwtHeader;
signature: Uint8Array;
};
error: null;
} | {
data: null;
error: AuthError;
} | {
data: null;
error: null;
}>;
}
//# sourceMappingURL=GoTrueClient.d.ts.map

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,9 @@
import GoTrueAdminApi from './GoTrueAdminApi';
import GoTrueClient from './GoTrueClient';
import AuthAdminApi from './AuthAdminApi';
import AuthClient from './AuthClient';
export { GoTrueAdminApi, GoTrueClient, AuthAdminApi, AuthClient };
export * from './lib/types';
export * from './lib/errors';
export { navigatorLock, NavigatorLockAcquireTimeoutError, internals as lockInternals, } from './lib/locks';
//# sourceMappingURL=index.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAC7C,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,UAAU,MAAM,cAAc,CAAA;AACrC,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,CAAA;AACjE,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,OAAO,EACL,aAAa,EACb,gCAAgC,EAChC,SAAS,IAAI,aAAa,GAC3B,MAAM,aAAa,CAAA"}

9
node_modules/@supabase/auth-js/dist/module/index.js generated vendored Normal file
View File

@ -0,0 +1,9 @@
import GoTrueAdminApi from './GoTrueAdminApi';
import GoTrueClient from './GoTrueClient';
import AuthAdminApi from './AuthAdminApi';
import AuthClient from './AuthClient';
export { GoTrueAdminApi, GoTrueClient, AuthAdminApi, AuthClient };
export * from './lib/types';
export * from './lib/errors';
export { navigatorLock, NavigatorLockAcquireTimeoutError, internals as lockInternals, } from './lib/locks';
//# sourceMappingURL=index.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAC7C,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,UAAU,MAAM,cAAc,CAAA;AACrC,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,CAAA;AACjE,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,OAAO,EACL,aAAa,EACb,gCAAgC,EAChC,SAAS,IAAI,aAAa,GAC3B,MAAM,aAAa,CAAA"}

View File

@ -0,0 +1,74 @@
/**
* Avoid modifying this file. It's part of
* https://github.com/supabase-community/base64url-js. Submit all fixes on
* that repo!
*/
/**
* Converts a byte to a Base64-URL string.
*
* @param byte The byte to convert, or null to flush at the end of the byte sequence.
* @param state The Base64 conversion state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`.
* @param emit A function called with the next Base64 character when ready.
*/
export declare function byteToBase64URL(byte: number | null, state: {
queue: number;
queuedBits: number;
}, emit: (char: string) => void): void;
/**
* Converts a String char code (extracted using `string.charCodeAt(position)`) to a sequence of Base64-URL characters.
*
* @param charCode The char code of the JavaScript string.
* @param state The Base64 state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`.
* @param emit A function called with the next byte.
*/
export declare function byteFromBase64URL(charCode: number, state: {
queue: number;
queuedBits: number;
}, emit: (byte: number) => void): void;
/**
* Converts a JavaScript string (which may include any valid character) into a
* Base64-URL encoded string. The string is first encoded in UTF-8 which is
* then encoded as Base64-URL.
*
* @param str The string to convert.
*/
export declare function stringToBase64URL(str: string): string;
/**
* Converts a Base64-URL encoded string into a JavaScript string. It is assumed
* that the underlying string has been encoded as UTF-8.
*
* @param str The Base64-URL encoded string.
*/
export declare function stringFromBase64URL(str: string): string;
/**
* Converts a Unicode codepoint to a multi-byte UTF-8 sequence.
*
* @param codepoint The Unicode codepoint.
* @param emit Function which will be called for each UTF-8 byte that represents the codepoint.
*/
export declare function codepointToUTF8(codepoint: number, emit: (byte: number) => void): void;
/**
* Converts a JavaScript string to a sequence of UTF-8 bytes.
*
* @param str The string to convert to UTF-8.
* @param emit Function which will be called for each UTF-8 byte of the string.
*/
export declare function stringToUTF8(str: string, emit: (byte: number) => void): void;
/**
* Converts a UTF-8 byte to a Unicode codepoint.
*
* @param byte The UTF-8 byte next in the sequence.
* @param state The shared state between consecutive UTF-8 bytes in the
* sequence, an object with the shape `{ utf8seq: 0, codepoint: 0 }`.
* @param emit Function which will be called for each codepoint.
*/
export declare function stringFromUTF8(byte: number, state: {
utf8seq: number;
codepoint: number;
}, emit: (codepoint: number) => void): void;
/**
* Helper functions to convert different types of strings to Uint8Array
*/
export declare function base64UrlToUint8Array(str: string): Uint8Array;
export declare function stringToUint8Array(str: string): Uint8Array;
//# sourceMappingURL=base64url.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"base64url.d.ts","sourceRoot":"","sources":["../../../src/lib/base64url.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAoCH;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,MAAM,GAAG,IAAI,EACnB,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,EAC5C,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAqB7B;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,EAC5C,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAmB7B;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,UAgB5C;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,UAuB9C;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAsB9E;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAgBrE;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAC5B,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,EAC7C,IAAI,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,QAuClC;AAED;;GAEG;AAEH,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAa7D;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAI1D"}

View File

@ -0,0 +1,246 @@
/**
* Avoid modifying this file. It's part of
* https://github.com/supabase-community/base64url-js. Submit all fixes on
* that repo!
*/
/**
* An array of characters that encode 6 bits into a Base64-URL alphabet
* character.
*/
const TO_BASE64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'.split('');
/**
* An array of characters that can appear in a Base64-URL encoded string but
* should be ignored.
*/
const IGNORE_BASE64URL = ' \t\n\r='.split('');
/**
* An array of 128 numbers that map a Base64-URL character to 6 bits, or if -2
* used to skip the character, or if -1 used to error out.
*/
const FROM_BASE64URL = (() => {
const charMap = new Array(128);
for (let i = 0; i < charMap.length; i += 1) {
charMap[i] = -1;
}
for (let i = 0; i < IGNORE_BASE64URL.length; i += 1) {
charMap[IGNORE_BASE64URL[i].charCodeAt(0)] = -2;
}
for (let i = 0; i < TO_BASE64URL.length; i += 1) {
charMap[TO_BASE64URL[i].charCodeAt(0)] = i;
}
return charMap;
})();
/**
* Converts a byte to a Base64-URL string.
*
* @param byte The byte to convert, or null to flush at the end of the byte sequence.
* @param state The Base64 conversion state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`.
* @param emit A function called with the next Base64 character when ready.
*/
export function byteToBase64URL(byte, state, emit) {
if (byte !== null) {
state.queue = (state.queue << 8) | byte;
state.queuedBits += 8;
while (state.queuedBits >= 6) {
const pos = (state.queue >> (state.queuedBits - 6)) & 63;
emit(TO_BASE64URL[pos]);
state.queuedBits -= 6;
}
}
else if (state.queuedBits > 0) {
state.queue = state.queue << (6 - state.queuedBits);
state.queuedBits = 6;
while (state.queuedBits >= 6) {
const pos = (state.queue >> (state.queuedBits - 6)) & 63;
emit(TO_BASE64URL[pos]);
state.queuedBits -= 6;
}
}
}
/**
* Converts a String char code (extracted using `string.charCodeAt(position)`) to a sequence of Base64-URL characters.
*
* @param charCode The char code of the JavaScript string.
* @param state The Base64 state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`.
* @param emit A function called with the next byte.
*/
export function byteFromBase64URL(charCode, state, emit) {
const bits = FROM_BASE64URL[charCode];
if (bits > -1) {
// valid Base64-URL character
state.queue = (state.queue << 6) | bits;
state.queuedBits += 6;
while (state.queuedBits >= 8) {
emit((state.queue >> (state.queuedBits - 8)) & 0xff);
state.queuedBits -= 8;
}
}
else if (bits === -2) {
// ignore spaces, tabs, newlines, =
return;
}
else {
throw new Error(`Invalid Base64-URL character "${String.fromCharCode(charCode)}"`);
}
}
/**
* Converts a JavaScript string (which may include any valid character) into a
* Base64-URL encoded string. The string is first encoded in UTF-8 which is
* then encoded as Base64-URL.
*
* @param str The string to convert.
*/
export function stringToBase64URL(str) {
const base64 = [];
const emitter = (char) => {
base64.push(char);
};
const state = { queue: 0, queuedBits: 0 };
stringToUTF8(str, (byte) => {
byteToBase64URL(byte, state, emitter);
});
byteToBase64URL(null, state, emitter);
return base64.join('');
}
/**
* Converts a Base64-URL encoded string into a JavaScript string. It is assumed
* that the underlying string has been encoded as UTF-8.
*
* @param str The Base64-URL encoded string.
*/
export function stringFromBase64URL(str) {
const conv = [];
const utf8Emit = (codepoint) => {
conv.push(String.fromCodePoint(codepoint));
};
const utf8State = {
utf8seq: 0,
codepoint: 0,
};
const b64State = { queue: 0, queuedBits: 0 };
const byteEmit = (byte) => {
stringFromUTF8(byte, utf8State, utf8Emit);
};
for (let i = 0; i < str.length; i += 1) {
byteFromBase64URL(str.charCodeAt(i), b64State, byteEmit);
}
return conv.join('');
}
/**
* Converts a Unicode codepoint to a multi-byte UTF-8 sequence.
*
* @param codepoint The Unicode codepoint.
* @param emit Function which will be called for each UTF-8 byte that represents the codepoint.
*/
export function codepointToUTF8(codepoint, emit) {
if (codepoint <= 0x7f) {
emit(codepoint);
return;
}
else if (codepoint <= 0x7ff) {
emit(0xc0 | (codepoint >> 6));
emit(0x80 | (codepoint & 0x3f));
return;
}
else if (codepoint <= 0xffff) {
emit(0xe0 | (codepoint >> 12));
emit(0x80 | ((codepoint >> 6) & 0x3f));
emit(0x80 | (codepoint & 0x3f));
return;
}
else if (codepoint <= 0x10ffff) {
emit(0xf0 | (codepoint >> 18));
emit(0x80 | ((codepoint >> 12) & 0x3f));
emit(0x80 | ((codepoint >> 6) & 0x3f));
emit(0x80 | (codepoint & 0x3f));
return;
}
throw new Error(`Unrecognized Unicode codepoint: ${codepoint.toString(16)}`);
}
/**
* Converts a JavaScript string to a sequence of UTF-8 bytes.
*
* @param str The string to convert to UTF-8.
* @param emit Function which will be called for each UTF-8 byte of the string.
*/
export function stringToUTF8(str, emit) {
for (let i = 0; i < str.length; i += 1) {
let codepoint = str.charCodeAt(i);
if (codepoint > 0xd7ff && codepoint <= 0xdbff) {
// most UTF-16 codepoints are Unicode codepoints, except values in this
// range where the next UTF-16 codepoint needs to be combined with the
// current one to get the Unicode codepoint
const highSurrogate = ((codepoint - 0xd800) * 0x400) & 0xffff;
const lowSurrogate = (str.charCodeAt(i + 1) - 0xdc00) & 0xffff;
codepoint = (lowSurrogate | highSurrogate) + 0x10000;
i += 1;
}
codepointToUTF8(codepoint, emit);
}
}
/**
* Converts a UTF-8 byte to a Unicode codepoint.
*
* @param byte The UTF-8 byte next in the sequence.
* @param state The shared state between consecutive UTF-8 bytes in the
* sequence, an object with the shape `{ utf8seq: 0, codepoint: 0 }`.
* @param emit Function which will be called for each codepoint.
*/
export function stringFromUTF8(byte, state, emit) {
if (state.utf8seq === 0) {
if (byte <= 0x7f) {
emit(byte);
return;
}
// count the number of 1 leading bits until you reach 0
for (let leadingBit = 1; leadingBit < 6; leadingBit += 1) {
if (((byte >> (7 - leadingBit)) & 1) === 0) {
state.utf8seq = leadingBit;
break;
}
}
if (state.utf8seq === 2) {
state.codepoint = byte & 31;
}
else if (state.utf8seq === 3) {
state.codepoint = byte & 15;
}
else if (state.utf8seq === 4) {
state.codepoint = byte & 7;
}
else {
throw new Error('Invalid UTF-8 sequence');
}
state.utf8seq -= 1;
}
else if (state.utf8seq > 0) {
if (byte <= 0x7f) {
throw new Error('Invalid UTF-8 sequence');
}
state.codepoint = (state.codepoint << 6) | (byte & 63);
state.utf8seq -= 1;
if (state.utf8seq === 0) {
emit(state.codepoint);
}
}
}
/**
* Helper functions to convert different types of strings to Uint8Array
*/
export function base64UrlToUint8Array(str) {
const result = [];
const state = { queue: 0, queuedBits: 0 };
const onByte = (byte) => {
result.push(byte);
};
for (let i = 0; i < str.length; i += 1) {
byteFromBase64URL(str.charCodeAt(i), state, onByte);
}
return new Uint8Array(result);
}
export function stringToUint8Array(str) {
const result = [];
stringToUTF8(str, (byte) => result.push(byte));
return new Uint8Array(result);
}
//# sourceMappingURL=base64url.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,26 @@
/** Current session will be checked for refresh at this interval. */
export declare const AUTO_REFRESH_TICK_DURATION_MS: number;
/**
* A token refresh will be attempted this many ticks before the current session expires. */
export declare const AUTO_REFRESH_TICK_THRESHOLD = 3;
export declare const EXPIRY_MARGIN_MS: number;
export declare const GOTRUE_URL = "http://localhost:9999";
export declare const STORAGE_KEY = "supabase.auth.token";
export declare const AUDIENCE = "";
export declare const DEFAULT_HEADERS: {
'X-Client-Info': string;
};
export declare const NETWORK_FAILURE: {
MAX_RETRIES: number;
RETRY_INTERVAL: number;
};
export declare const API_VERSION_HEADER_NAME = "X-Supabase-Api-Version";
export declare const API_VERSIONS: {
'2024-01-01': {
timestamp: number;
name: string;
};
};
export declare const BASE64URL_REGEX: RegExp;
export declare const JWKS_TTL = 600000;
//# sourceMappingURL=constants.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AAEA,oEAAoE;AACpE,eAAO,MAAM,6BAA6B,QAAY,CAAA;AAEtD;2FAC2F;AAC3F,eAAO,MAAM,2BAA2B,IAAI,CAAA;AAK5C,eAAO,MAAM,gBAAgB,QAA8D,CAAA;AAE3F,eAAO,MAAM,UAAU,0BAA0B,CAAA;AACjD,eAAO,MAAM,WAAW,wBAAwB,CAAA;AAChD,eAAO,MAAM,QAAQ,KAAK,CAAA;AAC1B,eAAO,MAAM,eAAe;;CAA8C,CAAA;AAC1E,eAAO,MAAM,eAAe;;;CAG3B,CAAA;AAED,eAAO,MAAM,uBAAuB,2BAA2B,CAAA;AAC/D,eAAO,MAAM,YAAY;;;;;CAKxB,CAAA;AAED,eAAO,MAAM,eAAe,QAAyD,CAAA;AAErF,eAAO,MAAM,QAAQ,SAAS,CAAA"}

View File

@ -0,0 +1,28 @@
import { version } from './version';
/** Current session will be checked for refresh at this interval. */
export const AUTO_REFRESH_TICK_DURATION_MS = 30 * 1000;
/**
* A token refresh will be attempted this many ticks before the current session expires. */
export const AUTO_REFRESH_TICK_THRESHOLD = 3;
/*
* Earliest time before an access token expires that the session should be refreshed.
*/
export const EXPIRY_MARGIN_MS = AUTO_REFRESH_TICK_THRESHOLD * AUTO_REFRESH_TICK_DURATION_MS;
export const GOTRUE_URL = 'http://localhost:9999';
export const STORAGE_KEY = 'supabase.auth.token';
export const AUDIENCE = '';
export const DEFAULT_HEADERS = { 'X-Client-Info': `gotrue-js/${version}` };
export const NETWORK_FAILURE = {
MAX_RETRIES: 10,
RETRY_INTERVAL: 2, // in deciseconds
};
export const API_VERSION_HEADER_NAME = 'X-Supabase-Api-Version';
export const API_VERSIONS = {
'2024-01-01': {
timestamp: Date.parse('2024-01-01T00:00:00.0Z'),
name: '2024-01-01',
},
};
export const BASE64URL_REGEX = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;
export const JWKS_TTL = 600000; // 10 minutes
//# sourceMappingURL=constants.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAEnC,oEAAoE;AACpE,MAAM,CAAC,MAAM,6BAA6B,GAAG,EAAE,GAAG,IAAI,CAAA;AAEtD;2FAC2F;AAC3F,MAAM,CAAC,MAAM,2BAA2B,GAAG,CAAC,CAAA;AAE5C;;GAEG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,2BAA2B,GAAG,6BAA6B,CAAA;AAE3F,MAAM,CAAC,MAAM,UAAU,GAAG,uBAAuB,CAAA;AACjD,MAAM,CAAC,MAAM,WAAW,GAAG,qBAAqB,CAAA;AAChD,MAAM,CAAC,MAAM,QAAQ,GAAG,EAAE,CAAA;AAC1B,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,eAAe,EAAE,aAAa,OAAO,EAAE,EAAE,CAAA;AAC1E,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,WAAW,EAAE,EAAE;IACf,cAAc,EAAE,CAAC,EAAE,iBAAiB;CACrC,CAAA;AAED,MAAM,CAAC,MAAM,uBAAuB,GAAG,wBAAwB,CAAA;AAC/D,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,YAAY,EAAE;QACZ,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,wBAAwB,CAAC;QAC/C,IAAI,EAAE,YAAY;KACnB;CACF,CAAA;AAED,MAAM,CAAC,MAAM,eAAe,GAAG,sDAAsD,CAAA;AAErF,MAAM,CAAC,MAAM,QAAQ,GAAG,MAAM,CAAA,CAAC,aAAa"}

View File

@ -0,0 +1,7 @@
/**
* Known error codes. Note that the server may also return other error codes
* not included in this list (if the client library is older than the version
* on the server).
*/
export declare type ErrorCode = 'unexpected_failure' | 'validation_failed' | 'bad_json' | 'email_exists' | 'phone_exists' | 'bad_jwt' | 'not_admin' | 'no_authorization' | 'user_not_found' | 'session_not_found' | 'session_expired' | 'refresh_token_not_found' | 'refresh_token_already_used' | 'flow_state_not_found' | 'flow_state_expired' | 'signup_disabled' | 'user_banned' | 'provider_email_needs_verification' | 'invite_not_found' | 'bad_oauth_state' | 'bad_oauth_callback' | 'oauth_provider_not_supported' | 'unexpected_audience' | 'single_identity_not_deletable' | 'email_conflict_identity_not_deletable' | 'identity_already_exists' | 'email_provider_disabled' | 'phone_provider_disabled' | 'too_many_enrolled_mfa_factors' | 'mfa_factor_name_conflict' | 'mfa_factor_not_found' | 'mfa_ip_address_mismatch' | 'mfa_challenge_expired' | 'mfa_verification_failed' | 'mfa_verification_rejected' | 'insufficient_aal' | 'captcha_failed' | 'saml_provider_disabled' | 'manual_linking_disabled' | 'sms_send_failed' | 'email_not_confirmed' | 'phone_not_confirmed' | 'reauth_nonce_missing' | 'saml_relay_state_not_found' | 'saml_relay_state_expired' | 'saml_idp_not_found' | 'saml_assertion_no_user_id' | 'saml_assertion_no_email' | 'user_already_exists' | 'sso_provider_not_found' | 'saml_metadata_fetch_failed' | 'saml_idp_already_exists' | 'sso_domain_already_exists' | 'saml_entity_id_mismatch' | 'conflict' | 'provider_disabled' | 'user_sso_managed' | 'reauthentication_needed' | 'same_password' | 'reauthentication_not_valid' | 'otp_expired' | 'otp_disabled' | 'identity_not_found' | 'weak_password' | 'over_request_rate_limit' | 'over_email_send_rate_limit' | 'over_sms_send_rate_limit' | 'bad_code_verifier' | 'anonymous_provider_disabled' | 'hook_timeout' | 'hook_timeout_after_retry' | 'hook_payload_over_size_limit' | 'hook_payload_invalid_content_type' | 'request_timeout' | 'mfa_phone_enroll_not_enabled' | 'mfa_phone_verify_not_enabled' | 'mfa_totp_enroll_not_enabled' | 'mfa_totp_verify_not_enabled' | 'mfa_webauthn_enroll_not_enabled' | 'mfa_webauthn_verify_not_enabled' | 'mfa_verified_factor_exists' | 'invalid_credentials' | 'email_address_not_authorized' | 'email_address_invalid';
//# sourceMappingURL=error-codes.d.ts.map

Some files were not shown because too many files have changed in this diff Show More