main repo

This commit is contained in:
Basilosaurusrex
2025-11-24 18:09:40 +01:00
parent b636ee5e70
commit f027651f9b
34146 changed files with 4436636 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
> @supabase/auth-helpers-nextjs@0.10.0 build /home/runner/work/auth-helpers/auth-helpers/packages/nextjs
> tsup
CLI Building entry: src/index.ts
CLI Using tsconfig: tsconfig.json
CLI tsup v6.7.0
CLI Using tsup config: /home/runner/work/auth-helpers/auth-helpers/packages/nextjs/tsup.config.ts
CLI Target: node14
CLI Cleaning output folder
CJS Build start
CJS dist/index.js 12.61 KB
CJS dist/index.js.map 29.03 KB
CJS ⚡️ Build success in 27ms
DTS Build start
DTS ⚡️ Build success in 3560ms
DTS dist/index.d.ts 5.95 KB

424
node_modules/@supabase/auth-helpers-nextjs/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,424 @@
# @supabase/auth-helpers-nextjs
## 0.10.0
### Minor Changes
- 9e7ff76: upgrade supabase-js version to v2.42.0
### Patch Changes
- Updated dependencies [9e7ff76]
- @supabase/auth-helpers-shared@0.7.0
## 0.9.0
### Minor Changes
- 18327fc: add isServer property to server-side storage adaptors
## 0.8.7
### Patch Changes
- f7e5c2d: Revert cookie name to storage key change
- Updated dependencies [f7e5c2d]
- @supabase/auth-helpers-shared@0.6.3
## 0.8.6
### Patch Changes
- 5893215: Update storage key name with cookie name
- Updated dependencies [5893215]
- @supabase/auth-helpers-shared@0.6.2
## 0.8.5
### Patch Changes
- 7abfe9b: Fix header and cookie trying to read undefined response body
## 0.8.4
### Patch Changes
- Updated dependencies [841fce0]
- @supabase/auth-helpers-shared@0.6.1
## 0.8.3
### Patch Changes
- Updated dependencies [9fa8f2b]
- @supabase/auth-helpers-shared@0.6.0
## 0.8.2
### Patch Changes
- c8a121d: include cookie options for deleteCookie
## 0.8.1
### Patch Changes
- dfff00a: Remove the appending of a cookie to the response
## 0.8.0
### Minor Changes
- c48bb87: Remove max-age option from cookieOptions
### Patch Changes
- Updated dependencies [c48bb87]
- @supabase/auth-helpers-shared@0.5.0
## 0.7.4
### Patch Changes
- 8c77550: Fix type for next.js cookies and headers functions
## 0.7.3
### Patch Changes
- 1619e93: Add cookie options to set cookie for route handler
## 0.7.2
### Patch Changes
- d33aa1b: Upgrade patch version of Next.js to fix TS def for `cookies().set()`
- Updated dependencies [97e5541]
- @supabase/auth-helpers-shared@0.4.1
## 0.7.1
### Patch Changes
- b20cc32: Allow user to opt out of singleton pattern for Client Components
## 0.7.0
### Minor Changes
- 65bf8d4: Add cookie storage adapter per library following a shared storage adapter
- 65bf8d4: Add full server side support to auth helpers through PKCE
### Patch Changes
- 165ba70: Fix "Failed to parse cookie string" bug in middleware storage
- a128b9e: Fix typedefs and add deprecated functions for App Router createClient functions
- d46c2ed: fix cookie saving in middleware/routeHandler
- 067402a: Set cookie header to make new session from middleware available to server component
- 66b13b9: simplifying defaults for storage adapter
- 008a08c: Implement singleton pattern for createClientComponentClient to simplify implementation
- d90866f: [BREAKING CHANGES]: Renamed createBrowserSupabaseClient to createPagesBrowserClient, createServerSupabaseClient to createPagesServerClient and createMiddlewareSupabaseClient to createMiddlewareClient
- 1086021: Upgrade Next.js and remove custom type for WritableRequestCookies
- Updated dependencies [65bf8d4]
- Updated dependencies [353be76]
- Updated dependencies [56db807]
- Updated dependencies [56db807]
- Updated dependencies [66b13b9]
- Updated dependencies [65bf8d4]
- @supabase/auth-helpers-shared@0.4.0
## 0.7.0-next.8
### Patch Changes
- a128b9e: Fix typedefs and add deprecated functions for App Router createClient functions
## 0.7.0-next.7
### Patch Changes
- 067402a: Set cookie header to make new session from middleware available to server component
- 008a08c: Implement singleton pattern for createClientComponentClient to simplify implementation
- 1086021: Upgrade Next.js and remove custom type for WritableRequestCookies
## 0.7.0-next.6
### Patch Changes
- d90866f: [BREAKING CHANGES]: Renamed createBrowserSupabaseClient to createPagesBrowserClient, createServerSupabaseClient to createPagesServerClient and createMiddlewareSupabaseClient to createMiddlewareClient
## 0.7.0-next.5
### Patch Changes
- d46c2ed: fix cookie saving in middleware/routeHandler
## 0.7.0-next.4
### Patch Changes
- 165ba70: Fix "Failed to parse cookie string" bug in middleware storage
## 0.7.0-next.3
### Patch Changes
- Updated dependencies [56db807]
- Updated dependencies [56db807]
- @supabase/auth-helpers-shared@0.4.0-next.3
## 0.7.0-next.2
### Patch Changes
- Updated dependencies [353be76]
- @supabase/auth-helpers-shared@0.4.0-next.2
## 0.7.0-next.1
### Patch Changes
- 66b13b9: simplifying defaults for storage adapter
- Updated dependencies [66b13b9]
- @supabase/auth-helpers-shared@0.4.0-next.1
## 0.7.0-next.0
### Minor Changes
- 65bf8d4: Add cookie storage adapter per library following a shared storage adapter
- 65bf8d4: Add full server side support to auth helpers through PKCE
### Patch Changes
- Updated dependencies [65bf8d4]
- Updated dependencies [65bf8d4]
- @supabase/auth-helpers-shared@0.4.0-next.0
## 0.6.0
### Minor Changes
- 50d0a16: Remove deprecated methods from the nextjs package
## 0.5.9
### Patch Changes
- Updated dependencies [1ea258e]
- @supabase/auth-helpers-shared@0.3.3
## 0.5.8
### Patch Changes
- Updated dependencies [185e9cf]
- @supabase/auth-helpers-shared@0.3.2
## 0.5.7
### Patch Changes
- Updated dependencies [f86073d]
- @supabase/auth-helpers-shared@0.3.1
## 0.5.6
### Patch Changes
- 5ab18fe: Export function to create Supabase Client in Next.js Route Handler functions
## 0.5.5
### Patch Changes
- Updated dependencies [33c8a81]
- @supabase/auth-helpers-shared@0.3.0
## 0.5.4
### Patch Changes
- 849e447: allow overwriting client url and key
## 0.5.3
### Patch Changes
- d3366e4: Allow passing client options
- Updated dependencies [d3366e4]
- @supabase/auth-helpers-shared@0.2.4
## 0.5.2
### Patch Changes
- 2be3f10: feat: add helper for Next.js Server Components.
## 0.5.1
### Patch Changes
- Updated dependencies [bee77c7]
- @supabase/auth-helpers-shared@0.2.3
## 0.5.0
### Minor Changes
- d8f7446: chore: deprecate withApiAuth, withPageAuth, and withMiddlewareAuth.
## 0.4.5
### Patch Changes
- d6c43ef: fix: "host" request header is not available. #358
## 0.4.4
### Patch Changes
- 5cdc84c: Fix a bug with withPageAuth when a session is null and authRequired is set to false
## 0.4.3
### Patch Changes
- Updated dependencies [999e57e]
- @supabase/auth-helpers-shared@0.2.2
## 0.4.2
### Patch Changes
- 2fda843: add missing supabase-js peerDependency
- 2fda843: update supabase-js
- Updated dependencies [2fda843]
- Updated dependencies [2fda843]
- @supabase/auth-helpers-shared@0.2.1
## 0.4.1
### Patch Changes
- 5140f5a: fix: withPageAuth return user. [#314](https://github.com/supabase/auth-helpers/issues/314)
## 0.4.0
### Minor Changes
- fd30e33: Update to work with supabase-js v2 RC
### Patch Changes
- 20fa944: add sveltekit supabase v2 support
- fe5c4a6: chore: improve types.
- 2fdb094: chore: types and middleware improvements.
- af28db1: chore: export middleware at root.
- Updated dependencies [20fa944]
- Updated dependencies [fd30e33]
- Updated dependencies [fe5c4a6]
- Updated dependencies [2fdb094]
- @supabase/auth-helpers-shared@0.2.0
## 0.4.0-next.4
### Patch Changes
- 20fa944: add sveltekit supabase v2 support
- Updated dependencies [20fa944]
- @supabase/auth-helpers-shared@0.2.0-next.3
## 0.4.0-next.3
### Patch Changes
- 2fdb094: chore: types and middleware improvements.
- Updated dependencies [2fdb094]
- @supabase/auth-helpers-shared@0.2.0-next.2
## 0.4.0-next.2
### Patch Changes
- fe5c4a6: chore: improve types.
- Updated dependencies [fe5c4a6]
- @supabase/auth-helpers-shared@0.2.0-next.1
## 0.4.0-next.1
### Patch Changes
- af28db1: chore: export middleware at root.
## 0.4.0-next.0
### Minor Changes
- 1b33e44: Update to work with supabase-js v2 RC
### Patch Changes
- Updated dependencies [1b33e44]
- @supabase/auth-helpers-shared@0.2.0-next.0
## 0.2.7
### Patch Changes
- 0ab05cf: Update format of x-client-info header
## 0.2.6
### Patch Changes
- 50669a6: Add x-client-info header to show package name and version
## 0.2.5
### Patch Changes
- 8e0b747: Change error handling to not show flow disruption errors
## 0.2.4
### Patch Changes
- 56228e3: Add getProviderToken helper method
- Updated dependencies [56228e3]
- @supabase/auth-helpers-shared@0.1.3
## 0.2.3
### Patch Changes
- 69fefcb: Change logger to be a wrapper for console
## 0.2.2
### Patch Changes
- 38ccf1c: Logger can be imported in your own project for setting log levels
- Updated dependencies [38ccf1c]
- @supabase/auth-helpers-shared@0.1.2
## 0.2.1
### Patch Changes
- 9dda264: Add better error handling and error codes
- Updated dependencies [9dda264]
- @supabase/auth-helpers-shared@0.1.1
## 0.2.0
### Minor Changes
- f399820: Using shared package as a dependency
Update sveltekit package with latest code to update tokens
## 0.1.0
### Minor Changes
- a3c2991: Initial release of new library version

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

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 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.

View File

@@ -0,0 +1,236 @@
## Migrating to `0.5.X`
To make these helpers more flexible as well as more maintainable and easier to upgrade for new versions of Next.js, we're stripping them down to the most useful part which is managing the cookies and giving you an authenticated supabase-js client in any environment (client, server, middleware/edge).
Therefore we're marking the `withApiAuth`, `withPageAuth`, and `withMiddlewareAuth` higher order functions as deprectaed and they will be removed in the next **minor** release (v0.6.X).
Please follow the steps below to update your API routes, pages, and middleware handlers. Thanks!
### `withApiAuth` deprecated!
Use `createServerSupabaseClient` within your `NextApiHandler`:
#### Before
```tsx
// pages/api/protected-route.ts
import { withApiAuth } from '@supabase/auth-helpers-nextjs';
export default withApiAuth(async function ProtectedRoute(req, res, supabase) {
// Run queries with RLS on the server
const { data } = await supabase.from('test').select('*');
res.json(data);
});
```
#### After
```tsx
// pages/api/protected-route.ts
import { NextApiHandler } from 'next';
import { createServerSupabaseClient } from '@supabase/auth-helpers-nextjs';
const ProtectedRoute: NextApiHandler = async (req, res) => {
// Create authenticated Supabase Client
const supabase = createServerSupabaseClient({ req, res });
// Check if we have a session
const {
data: { session }
} = await supabase.auth.getSession();
if (!session)
return res.status(401).json({
error: 'not_authenticated',
description: 'The user does not have an active session or is not authenticated'
});
// Run queries with RLS on the server
const { data } = await supabase.from('test').select('*');
res.json(data);
};
export default ProtectedRoute;
```
### `withPageAuth` deprecated!
Use `createServerSupabaseClient` within `getServerSideProps`:
#### Before
```tsx
// pages/profile.js
import { withPageAuth, User } from '@supabase/auth-helpers-nextjs';
export default function Profile({ user }: { user: User }) {
return <pre>{JSON.stringify(user, null, 2)}</pre>;
}
export const getServerSideProps = withPageAuth({ redirectTo: '/' });
```
#### After
```tsx
// pages/profile.js
import { createServerSupabaseClient, User } from '@supabase/auth-helpers-nextjs';
import { GetServerSidePropsContext } from 'next';
export default function Profile({ user }: { user: User }) {
return <pre>{JSON.stringify(user, null, 2)}</pre>;
}
export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
// Create authenticated Supabase Client
const supabase = createServerSupabaseClient(ctx);
// Check if we have a session
const {
data: { session }
} = await supabase.auth.getSession();
if (!session)
return {
redirect: {
destination: '/',
permanent: false
}
};
return {
props: {
initialSession: session,
user: session.user
}
};
};
```
### `withMiddlewareAuth` deprecated!
#### Before
```tsx
import { withMiddlewareAuth } from '@supabase/auth-helpers-nextjs';
export const middleware = withMiddlewareAuth({
redirectTo: '/',
authGuard: {
isPermitted: async (user) => {
return user.email?.endsWith('@gmail.com') ?? false;
},
redirectTo: '/insufficient-permissions'
}
});
export const config = {
matcher: '/middleware-protected'
};
```
#### After
```tsx
import { createMiddlewareSupabaseClient } from '@supabase/auth-helpers-nextjs';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export async function middleware(req: NextRequest) {
// We need to create a response and hand it to the supabase client to be able to modify the response headers.
const res = NextResponse.next();
// Create authenticated Supabase Client.
const supabase = createMiddlewareSupabaseClient({ req, res });
// Check if we have a session
const {
data: { session }
} = await supabase.auth.getSession();
// Check auth condition
if (session?.user.email?.endsWith('@gmail.com')) {
// Authentication successful, forward request to protected route.
return res;
}
// Auth condition not met, redirect to home page.
const redirectUrl = req.nextUrl.clone();
redirectUrl.pathname = '/';
redirectUrl.searchParams.set(`redirectedFrom`, req.nextUrl.pathname);
return NextResponse.redirect(redirectUrl);
}
export const config = {
matcher: '/middleware-protected'
};
```
## Migrating to `0.4.X` and supabase-js v2
- With the update to `supabase-js` v2 the `auth` API routes are no longer required, therefore you can go ahead and delete your `auth` directory under the `/pages/api/` directory. Please refer to the [v2 migration guide](https://supabase.com/docs/reference/javascript/upgrade-guide) for the full set of changes within supabase-js.
- The `/api/auth/logout` API route has been removed, please use the `signout` method instead:
```jsx
<button
onClick={async () => {
await supabaseClient.auth.signOut();
router.push('/');
}}
>
Logout
</button>
```
- The `supabaseClient` and `supabaseServerClient` have been removed in favor of the `createBrowserSupabaseClient` and `createServerSupabaseClient` methods. This is so that you can provide the CLI generated types to the client, e.g.
```tsx
// client-side
import type { Database } from 'types_db';
const [supabaseClient] = useState(() => createBrowserSupabaseClient<Database>());
// server-side API route
import type { NextApiRequest, NextApiResponse } from 'next';
import type { Database } from 'types_db';
export default async (req: NextApiRequest, res: NextApiResponse) => {
const supabaseServerClient = createServerSupabaseClient<Database>({
req,
res
});
const {
data: { user }
} = await supabaseServerClient.auth.getUser();
res.status(200).json({ name: user?.name ?? '' });
};
```
- The `UserProvider` has been replaced by the `SessionContextProvider`. Make sure to wrap your `pages/_app.js` componenent with the `SessionContextProvider`. Then, throughout your application you can use the `useSessionContext` hook to get the `session` and the `useSupabaseClient` hook to get an authenticated `supabaseClient`.
- The `useUser` hook now returns the `user` object or `null`.
- Usage with TypeScript: You can pass types that were [generated with the Supabase CLI](https://supabase.com/docs/reference/javascript/next/typescript-support#generating-types) to the Supabase Client to get enhanced type safety and auto completion:
```tsx
// Creating a new supabase client object:
import { Database } from '../db_types';
const [supabaseClient] = useState(() => createBrowserSupabaseClient<Database>());
```
```tsx
// Retrieving a supabase client object from the SessionContext:
import { useSupabaseClient } from '@supabase/auth-helpers-react';
import { Database } from '../db_types';
const supabaseClient = useSupabaseClient<Database>();
```
## Migrating from @supabase/supabase-auth-helpers to @supabase/auth-helpers
This is a step by step guide on migrating away from the `@supabase/supabase-auth-helpers` to the newly released `@supabase/auth-helpers`.
1. Install `@supabase/supabase-js`, `@supabase/auth-helpers-nextjs` and `@supabase/auth-helpers-react` libraries from npm.
2. Replace all imports of `@supabase/supabase-auth-helpers/nextjs` in your project with `@supabase/auth-helpers-nextjs`.
3. Replace all imports of `@supabase/supabase-auth-helpers/react` in your project with `@supabase/auth-helpers-react`.
4. Replace all instances of `withAuthRequired` in any of your NextJS pages with `withPageAuth`.
5. Replace all instances of `withAuthRequired` in any of your NextJS API endpoints with `withApiAuth`.
6. Uninstall `@supabase/supabase-auth-helpers`.

6
node_modules/@supabase/auth-helpers-nextjs/README.md generated vendored Normal file
View File

@@ -0,0 +1,6 @@
# @supabase/auth-helpers-nextjs (BETA)
This submodule provides convenience helpers for implementing user authentication in Next.js applications.
- [Documentation](https://supabase.com/docs/guides/auth/auth-helpers/nextjs)
- [Example](https://github.com/supabase/supabase/tree/master/examples/auth/nextjs)

View File

@@ -0,0 +1,94 @@
import * as _supabase_supabase_js from '@supabase/supabase-js';
import { SupabaseClient } from '@supabase/supabase-js';
export { Session, SupabaseClient, User } from '@supabase/supabase-js';
import { SupabaseClientOptionsWithoutAuth, CookieOptionsWithName } from '@supabase/auth-helpers-shared';
import { GenericSchema } from '@supabase/supabase-js/dist/module/lib/types';
import { GetServerSidePropsContext, NextApiRequest, NextApiResponse } from 'next';
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
declare function createClientComponentClient<Database = any, SchemaName extends string & keyof Database = 'public' extends keyof Database ? 'public' : string & keyof Database, Schema extends GenericSchema = Database[SchemaName] extends GenericSchema ? Database[SchemaName] : any>({ supabaseUrl, supabaseKey, options, cookieOptions, isSingleton }?: {
supabaseUrl?: string;
supabaseKey?: string;
options?: SupabaseClientOptionsWithoutAuth<SchemaName>;
cookieOptions?: CookieOptionsWithName;
isSingleton?: boolean;
}): SupabaseClient<Database, SchemaName, Schema>;
declare const createPagesBrowserClient: typeof createClientComponentClient;
declare function createPagesServerClient<Database = any, SchemaName extends string & keyof Database = 'public' extends keyof Database ? 'public' : string & keyof Database, Schema extends GenericSchema = Database[SchemaName] extends GenericSchema ? Database[SchemaName] : any>(context: GetServerSidePropsContext | {
req: NextApiRequest;
res: NextApiResponse;
}, { supabaseUrl, supabaseKey, options, cookieOptions }?: {
supabaseUrl?: string;
supabaseKey?: string;
options?: SupabaseClientOptionsWithoutAuth<SchemaName>;
cookieOptions?: CookieOptionsWithName;
}): SupabaseClient<Database, SchemaName, Schema>;
declare function createMiddlewareClient<Database = any, SchemaName extends string & keyof Database = 'public' extends keyof Database ? 'public' : string & keyof Database, Schema extends GenericSchema = Database[SchemaName] extends GenericSchema ? Database[SchemaName] : any>(context: {
req: NextRequest;
res: NextResponse;
}, { supabaseUrl, supabaseKey, options, cookieOptions }?: {
supabaseUrl?: string;
supabaseKey?: string;
options?: SupabaseClientOptionsWithoutAuth<SchemaName>;
cookieOptions?: CookieOptionsWithName;
}): SupabaseClient<Database, SchemaName, Schema>;
declare function createServerComponentClient<Database = any, SchemaName extends string & keyof Database = 'public' extends keyof Database ? 'public' : string & keyof Database, Schema extends GenericSchema = Database[SchemaName] extends GenericSchema ? Database[SchemaName] : any>(context: {
cookies: () => ReturnType<typeof cookies>;
}, { supabaseUrl, supabaseKey, options, cookieOptions }?: {
supabaseUrl?: string;
supabaseKey?: string;
options?: SupabaseClientOptionsWithoutAuth<SchemaName>;
cookieOptions?: CookieOptionsWithName;
}): SupabaseClient<Database, SchemaName, Schema>;
declare function createRouteHandlerClient<Database = any, SchemaName extends string & keyof Database = 'public' extends keyof Database ? 'public' : string & keyof Database, Schema extends GenericSchema = Database[SchemaName] extends GenericSchema ? Database[SchemaName] : any>(context: {
cookies: () => ReturnType<typeof cookies>;
}, { supabaseUrl, supabaseKey, options, cookieOptions }?: {
supabaseUrl?: string;
supabaseKey?: string;
options?: SupabaseClientOptionsWithoutAuth<SchemaName>;
cookieOptions?: CookieOptionsWithName;
}): SupabaseClient<Database, SchemaName, Schema>;
declare const createServerActionClient: typeof createRouteHandlerClient;
/**
* @deprecated utilize the `createPagesBrowserClient` function instead
*/
declare function createBrowserSupabaseClient<Database = any, SchemaName extends string & keyof Database = 'public' extends keyof Database ? 'public' : string & keyof Database, Schema extends GenericSchema = Database[SchemaName] extends GenericSchema ? Database[SchemaName] : any>({ supabaseUrl, supabaseKey, options, cookieOptions }?: {
supabaseUrl?: string;
supabaseKey?: string;
options?: SupabaseClientOptionsWithoutAuth<SchemaName>;
cookieOptions?: CookieOptionsWithName;
}): _supabase_supabase_js.SupabaseClient<Database, SchemaName, Schema>;
/**
* @deprecated utilize the `createPagesServerClient` function instead
*/
declare function createServerSupabaseClient<Database = any, SchemaName extends string & keyof Database = 'public' extends keyof Database ? 'public' : string & keyof Database, Schema extends GenericSchema = Database[SchemaName] extends GenericSchema ? Database[SchemaName] : any>(context: GetServerSidePropsContext | {
req: NextApiRequest;
res: NextApiResponse;
}, { supabaseUrl, supabaseKey, options, cookieOptions }?: {
supabaseUrl?: string;
supabaseKey?: string;
options?: SupabaseClientOptionsWithoutAuth<SchemaName>;
cookieOptions?: CookieOptionsWithName;
}): _supabase_supabase_js.SupabaseClient<Database, SchemaName, Schema>;
/**
* @deprecated utilize the `createMiddlewareClient` function instead
*/
declare function createMiddlewareSupabaseClient<Database = any, SchemaName extends string & keyof Database = 'public' extends keyof Database ? 'public' : string & keyof Database, Schema extends GenericSchema = Database[SchemaName] extends GenericSchema ? Database[SchemaName] : any>(context: {
req: NextRequest;
res: NextResponse;
}, { supabaseUrl, supabaseKey, options, cookieOptions }?: {
supabaseUrl?: string;
supabaseKey?: string;
options?: SupabaseClientOptionsWithoutAuth<SchemaName>;
cookieOptions?: CookieOptionsWithName;
}): _supabase_supabase_js.SupabaseClient<Database, SchemaName, Schema>;
export { createBrowserSupabaseClient, createClientComponentClient, createMiddlewareClient, createMiddlewareSupabaseClient, createPagesBrowserClient, createPagesServerClient, createRouteHandlerClient, createServerActionClient, createServerComponentClient, createServerSupabaseClient };

View File

@@ -0,0 +1,373 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
createBrowserSupabaseClient: () => createBrowserSupabaseClient,
createClientComponentClient: () => createClientComponentClient,
createMiddlewareClient: () => createMiddlewareClient,
createMiddlewareSupabaseClient: () => createMiddlewareSupabaseClient,
createPagesBrowserClient: () => createPagesBrowserClient,
createPagesServerClient: () => createPagesServerClient,
createRouteHandlerClient: () => createRouteHandlerClient,
createServerActionClient: () => createServerActionClient,
createServerComponentClient: () => createServerComponentClient,
createServerSupabaseClient: () => createServerSupabaseClient
});
module.exports = __toCommonJS(src_exports);
// src/clientComponentClient.ts
var import_auth_helpers_shared = require("@supabase/auth-helpers-shared");
var supabase;
function createClientComponentClient({
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
cookieOptions,
isSingleton = true
} = {}) {
if (!supabaseUrl || !supabaseKey) {
throw new Error(
"either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!"
);
}
const createNewClient = () => {
var _a;
return (0, import_auth_helpers_shared.createSupabaseClient)(supabaseUrl, supabaseKey, {
...options,
global: {
...options == null ? void 0 : options.global,
headers: {
...(_a = options == null ? void 0 : options.global) == null ? void 0 : _a.headers,
"X-Client-Info": `${"@supabase/auth-helpers-nextjs"}@${"0.10.0"}`
}
},
auth: {
storage: new import_auth_helpers_shared.BrowserCookieAuthStorageAdapter(cookieOptions)
}
});
};
if (isSingleton) {
const _supabase = supabase ?? createNewClient();
if (typeof window === "undefined")
return _supabase;
if (!supabase)
supabase = _supabase;
return supabase;
}
return createNewClient();
}
// src/pagesBrowserClient.ts
var createPagesBrowserClient = createClientComponentClient;
// src/pagesServerClient.ts
var import_auth_helpers_shared2 = require("@supabase/auth-helpers-shared");
var import_set_cookie_parser = require("set-cookie-parser");
var NextServerAuthStorageAdapter = class extends import_auth_helpers_shared2.CookieAuthStorageAdapter {
constructor(context, cookieOptions) {
super(cookieOptions);
this.context = context;
}
getCookie(name) {
var _a, _b, _c;
const setCookie = (0, import_set_cookie_parser.splitCookiesString)(
((_b = (_a = this.context.res) == null ? void 0 : _a.getHeader("set-cookie")) == null ? void 0 : _b.toString()) ?? ""
).map((c) => (0, import_auth_helpers_shared2.parseCookies)(c)[name]).find((c) => !!c);
const value = setCookie ?? ((_c = this.context.req) == null ? void 0 : _c.cookies[name]);
return value;
}
setCookie(name, value) {
this._setCookie(name, value);
}
deleteCookie(name) {
this._setCookie(name, "", {
maxAge: 0
});
}
_setCookie(name, value, options) {
var _a;
const setCookies = (0, import_set_cookie_parser.splitCookiesString)(
((_a = this.context.res.getHeader("set-cookie")) == null ? void 0 : _a.toString()) ?? ""
).filter((c) => !(name in (0, import_auth_helpers_shared2.parseCookies)(c)));
const cookieStr = (0, import_auth_helpers_shared2.serializeCookie)(name, value, {
...this.cookieOptions,
...options,
// Allow supabase-js on the client to read the cookie as well
httpOnly: false
});
this.context.res.setHeader("set-cookie", [...setCookies, cookieStr]);
}
};
function createPagesServerClient(context, {
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
cookieOptions
} = {}) {
var _a;
if (!supabaseUrl || !supabaseKey) {
throw new Error(
"either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!"
);
}
return (0, import_auth_helpers_shared2.createSupabaseClient)(supabaseUrl, supabaseKey, {
...options,
global: {
...options == null ? void 0 : options.global,
headers: {
...(_a = options == null ? void 0 : options.global) == null ? void 0 : _a.headers,
"X-Client-Info": `${"@supabase/auth-helpers-nextjs"}@${"0.10.0"}`
}
},
auth: {
storage: new NextServerAuthStorageAdapter(context, cookieOptions)
}
});
}
// src/middlewareClient.ts
var import_auth_helpers_shared3 = require("@supabase/auth-helpers-shared");
var import_set_cookie_parser2 = require("set-cookie-parser");
var NextMiddlewareAuthStorageAdapter = class extends import_auth_helpers_shared3.CookieAuthStorageAdapter {
constructor(context, cookieOptions) {
super(cookieOptions);
this.context = context;
}
getCookie(name) {
var _a;
const setCookie = (0, import_set_cookie_parser2.splitCookiesString)(
((_a = this.context.res.headers.get("set-cookie")) == null ? void 0 : _a.toString()) ?? ""
).map((c) => (0, import_auth_helpers_shared3.parseCookies)(c)[name]).find((c) => !!c);
if (setCookie) {
return setCookie;
}
const cookies = (0, import_auth_helpers_shared3.parseCookies)(this.context.req.headers.get("cookie") ?? "");
return cookies[name];
}
setCookie(name, value) {
this._setCookie(name, value);
}
deleteCookie(name) {
this._setCookie(name, "", {
maxAge: 0
});
}
_setCookie(name, value, options) {
const newSessionStr = (0, import_auth_helpers_shared3.serializeCookie)(name, value, {
...this.cookieOptions,
...options,
// Allow supabase-js on the client to read the cookie as well
httpOnly: false
});
if (this.context.res.headers) {
this.context.res.headers.append("set-cookie", newSessionStr);
}
}
};
function createMiddlewareClient(context, {
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
cookieOptions
} = {}) {
var _a;
if (!supabaseUrl || !supabaseKey) {
throw new Error(
"either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!"
);
}
return (0, import_auth_helpers_shared3.createSupabaseClient)(supabaseUrl, supabaseKey, {
...options,
global: {
...options == null ? void 0 : options.global,
headers: {
...(_a = options == null ? void 0 : options.global) == null ? void 0 : _a.headers,
"X-Client-Info": `${"@supabase/auth-helpers-nextjs"}@${"0.10.0"}`
}
},
auth: {
storage: new NextMiddlewareAuthStorageAdapter(context, cookieOptions)
}
});
}
// src/serverComponentClient.ts
var import_auth_helpers_shared4 = require("@supabase/auth-helpers-shared");
var NextServerComponentAuthStorageAdapter = class extends import_auth_helpers_shared4.CookieAuthStorageAdapter {
constructor(context, cookieOptions) {
super(cookieOptions);
this.context = context;
this.isServer = true;
}
getCookie(name) {
var _a;
const nextCookies = this.context.cookies();
return (_a = nextCookies.get(name)) == null ? void 0 : _a.value;
}
setCookie(name, value) {
}
deleteCookie(name) {
}
};
function createServerComponentClient(context, {
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
cookieOptions
} = {}) {
var _a;
if (!supabaseUrl || !supabaseKey) {
throw new Error(
"either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!"
);
}
return (0, import_auth_helpers_shared4.createSupabaseClient)(supabaseUrl, supabaseKey, {
...options,
global: {
...options == null ? void 0 : options.global,
headers: {
...(_a = options == null ? void 0 : options.global) == null ? void 0 : _a.headers,
"X-Client-Info": `${"@supabase/auth-helpers-nextjs"}@${"0.10.0"}`
}
},
auth: {
storage: new NextServerComponentAuthStorageAdapter(context, cookieOptions)
}
});
}
// src/routeHandlerClient.ts
var import_auth_helpers_shared5 = require("@supabase/auth-helpers-shared");
var NextRouteHandlerAuthStorageAdapter = class extends import_auth_helpers_shared5.CookieAuthStorageAdapter {
constructor(context, cookieOptions) {
super(cookieOptions);
this.context = context;
}
getCookie(name) {
var _a;
const nextCookies = this.context.cookies();
return (_a = nextCookies.get(name)) == null ? void 0 : _a.value;
}
setCookie(name, value) {
const nextCookies = this.context.cookies();
nextCookies.set(name, value, this.cookieOptions);
}
deleteCookie(name) {
const nextCookies = this.context.cookies();
nextCookies.set(name, "", {
...this.cookieOptions,
maxAge: 0
});
}
};
function createRouteHandlerClient(context, {
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
cookieOptions
} = {}) {
var _a;
if (!supabaseUrl || !supabaseKey) {
throw new Error(
"either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!"
);
}
return (0, import_auth_helpers_shared5.createSupabaseClient)(supabaseUrl, supabaseKey, {
...options,
global: {
...options == null ? void 0 : options.global,
headers: {
...(_a = options == null ? void 0 : options.global) == null ? void 0 : _a.headers,
"X-Client-Info": `${"@supabase/auth-helpers-nextjs"}@${"0.10.0"}`
}
},
auth: {
storage: new NextRouteHandlerAuthStorageAdapter(context, cookieOptions)
}
});
}
// src/serverActionClient.ts
var createServerActionClient = createRouteHandlerClient;
// src/deprecated.ts
function createBrowserSupabaseClient({
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
cookieOptions
} = {}) {
console.warn(
"Please utilize the `createPagesBrowserClient` function instead of the deprecated `createBrowserSupabaseClient` function. Learn more: https://supabase.com/docs/guides/auth/auth-helpers/nextjs-pages"
);
return createPagesBrowserClient({
supabaseUrl,
supabaseKey,
options,
cookieOptions
});
}
function createServerSupabaseClient(context, {
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
cookieOptions
} = {}) {
console.warn(
"Please utilize the `createPagesServerClient` function instead of the deprecated `createServerSupabaseClient` function. Learn more: https://supabase.com/docs/guides/auth/auth-helpers/nextjs-pages"
);
return createPagesServerClient(context, {
supabaseUrl,
supabaseKey,
options,
cookieOptions
});
}
function createMiddlewareSupabaseClient(context, {
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
cookieOptions
} = {}) {
console.warn(
"Please utilize the `createMiddlewareClient` function instead of the deprecated `createMiddlewareSupabaseClient` function. Learn more: https://supabase.com/docs/guides/auth/auth-helpers/nextjs#middleware"
);
return createMiddlewareClient(context, {
supabaseUrl,
supabaseKey,
options,
cookieOptions
});
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
createBrowserSupabaseClient,
createClientComponentClient,
createMiddlewareClient,
createMiddlewareSupabaseClient,
createPagesBrowserClient,
createPagesServerClient,
createRouteHandlerClient,
createServerActionClient,
createServerComponentClient,
createServerSupabaseClient
});
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,49 @@
{
"name": "@supabase/auth-helpers-nextjs",
"version": "0.10.0",
"description": "A collection of framework specific Auth utilities for working with Supabase.",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/supabase/auth-helpers.git"
},
"keywords": [
"Supabase",
"Auth",
"Nextjs"
],
"author": "Supabase",
"license": "MIT",
"bugs": {
"url": "https://github.com/supabase/auth-helpers/issues"
},
"homepage": "https://github.com/supabase/auth-helpers/tree/main/packages/nextjs#readme",
"devDependencies": {
"@supabase/supabase-js": "2.42.0",
"@types/set-cookie-parser": "^2.4.3",
"next": "^13.5.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"rimraf": "^4.4.1",
"tslib": "^2.6.2",
"tsup": "^6.7.0",
"config": "0.1.0",
"tsconfig": "0.1.1"
},
"dependencies": {
"set-cookie-parser": "^2.6.0",
"@supabase/auth-helpers-shared": "0.7.0"
},
"peerDependencies": {
"@supabase/supabase-js": "^2.39.8"
},
"scripts": {
"lint": "tsc",
"build": "tsup",
"clean:all": "rimraf dist node_modules"
}
}

View File

@@ -0,0 +1,3 @@
// these variables are defined by tsup
declare const PACKAGE_NAME: string;
declare const PACKAGE_VERSION: string;

View File

@@ -0,0 +1,71 @@
import {
BrowserCookieAuthStorageAdapter,
CookieOptionsWithName,
SupabaseClientOptionsWithoutAuth,
createSupabaseClient
} from '@supabase/auth-helpers-shared';
import type { SupabaseClient } from '@supabase/supabase-js';
import type { GenericSchema } from '@supabase/supabase-js/dist/module/lib/types';
// can't type this properly as `Database`, `SchemaName` and `Schema` are only available within `createClientComponentClient` function
let supabase: any;
export function createClientComponentClient<
Database = any,
SchemaName extends string & keyof Database = 'public' extends keyof Database
? 'public'
: string & keyof Database,
Schema extends GenericSchema = Database[SchemaName] extends GenericSchema
? Database[SchemaName]
: any
>({
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
cookieOptions,
isSingleton = true
}: {
supabaseUrl?: string;
supabaseKey?: string;
options?: SupabaseClientOptionsWithoutAuth<SchemaName>;
cookieOptions?: CookieOptionsWithName;
isSingleton?: boolean;
} = {}): SupabaseClient<Database, SchemaName, Schema> {
if (!supabaseUrl || !supabaseKey) {
throw new Error(
'either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!'
);
}
const createNewClient = () =>
createSupabaseClient<Database, SchemaName, Schema>(supabaseUrl, supabaseKey, {
...options,
global: {
...options?.global,
headers: {
...options?.global?.headers,
'X-Client-Info': `${PACKAGE_NAME}@${PACKAGE_VERSION}`
}
},
auth: {
storage: new BrowserCookieAuthStorageAdapter(cookieOptions)
}
});
if (isSingleton) {
// The `Singleton` pattern is the default to simplify the instantiation
// of a Supabase client across Client Components.
const _supabase = supabase ?? createNewClient();
// For SSG and SSR always create a new Supabase client
if (typeof window === 'undefined') return _supabase;
// Create the Supabase client once in the client
if (!supabase) supabase = _supabase;
return supabase;
}
// This allows for multiple Supabase clients, which may be required when using
// multiple schemas. The user will be responsible for ensuring a single
// instance of Supabase is used across Client Components, for each schema.
return createNewClient();
}

View File

@@ -0,0 +1,239 @@
import {
SupabaseClientOptionsWithoutAuth,
CookieOptionsWithName
} from '@supabase/auth-helpers-shared';
import { NextResponse } from 'next/server';
import { createPagesBrowserClient } from './pagesBrowserClient';
import { createPagesServerClient } from './pagesServerClient';
import { createMiddlewareClient } from './middlewareClient';
import { createClientComponentClient } from './clientComponentClient';
import { createServerComponentClient } from './serverComponentClient';
import { createRouteHandlerClient } from './routeHandlerClient';
import { headers, cookies } from 'next/headers';
import type { GetServerSidePropsContext, NextApiRequest, NextApiResponse } from 'next';
import type { NextRequest } from 'next/server';
import type { GenericSchema } from '@supabase/supabase-js/dist/module/lib/types';
/**
* @deprecated utilize the `createPagesBrowserClient` function instead
*/
export function createBrowserSupabaseClient<
Database = any,
SchemaName extends string & keyof Database = 'public' extends keyof Database
? 'public'
: string & keyof Database,
Schema extends GenericSchema = Database[SchemaName] extends GenericSchema
? Database[SchemaName]
: any
>({
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
cookieOptions
}: {
supabaseUrl?: string;
supabaseKey?: string;
options?: SupabaseClientOptionsWithoutAuth<SchemaName>;
cookieOptions?: CookieOptionsWithName;
} = {}) {
console.warn(
'Please utilize the `createPagesBrowserClient` function instead of the deprecated `createBrowserSupabaseClient` function. Learn more: https://supabase.com/docs/guides/auth/auth-helpers/nextjs-pages'
);
return createPagesBrowserClient<Database, SchemaName, Schema>({
supabaseUrl,
supabaseKey,
options,
cookieOptions
});
}
/**
* @deprecated utilize the `createPagesServerClient` function instead
*/
export function createServerSupabaseClient<
Database = any,
SchemaName extends string & keyof Database = 'public' extends keyof Database
? 'public'
: string & keyof Database,
Schema extends GenericSchema = Database[SchemaName] extends GenericSchema
? Database[SchemaName]
: any
>(
context: GetServerSidePropsContext | { req: NextApiRequest; res: NextApiResponse },
{
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
cookieOptions
}: {
supabaseUrl?: string;
supabaseKey?: string;
options?: SupabaseClientOptionsWithoutAuth<SchemaName>;
cookieOptions?: CookieOptionsWithName;
} = {}
) {
console.warn(
'Please utilize the `createPagesServerClient` function instead of the deprecated `createServerSupabaseClient` function. Learn more: https://supabase.com/docs/guides/auth/auth-helpers/nextjs-pages'
);
return createPagesServerClient<Database, SchemaName, Schema>(context, {
supabaseUrl,
supabaseKey,
options,
cookieOptions
});
}
/**
* @deprecated utilize the `createMiddlewareClient` function instead
*/
export function createMiddlewareSupabaseClient<
Database = any,
SchemaName extends string & keyof Database = 'public' extends keyof Database
? 'public'
: string & keyof Database,
Schema extends GenericSchema = Database[SchemaName] extends GenericSchema
? Database[SchemaName]
: any
>(
context: { req: NextRequest; res: NextResponse },
{
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
cookieOptions
}: {
supabaseUrl?: string;
supabaseKey?: string;
options?: SupabaseClientOptionsWithoutAuth<SchemaName>;
cookieOptions?: CookieOptionsWithName;
} = {}
) {
console.warn(
'Please utilize the `createMiddlewareClient` function instead of the deprecated `createMiddlewareSupabaseClient` function. Learn more: https://supabase.com/docs/guides/auth/auth-helpers/nextjs#middleware'
);
return createMiddlewareClient<Database, SchemaName, Schema>(context, {
supabaseUrl,
supabaseKey,
options,
cookieOptions
});
}
/**
* @deprecated utilize the `createClientComponentClient` function instead
*/
export function createClientComponentSupabaseClient<
Database = any,
SchemaName extends string & keyof Database = 'public' extends keyof Database
? 'public'
: string & keyof Database,
Schema extends GenericSchema = Database[SchemaName] extends GenericSchema
? Database[SchemaName]
: any
>({
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
cookieOptions
}: {
supabaseUrl?: string;
supabaseKey?: string;
options?: SupabaseClientOptionsWithoutAuth<SchemaName>;
cookieOptions?: CookieOptionsWithName;
} = {}) {
console.warn(
'Please utilize the `createClientComponentClient` function instead of the deprecated `createClientComponentSupabaseClient` function. Learn more: https://supabase.com/docs/guides/auth/auth-helpers/nextjs#client-component'
);
return createClientComponentClient<Database, SchemaName, Schema>({
supabaseUrl,
supabaseKey,
options,
cookieOptions
});
}
/**
* @deprecated utilize the `createServerComponentClient` function instead
*/
export function createServerComponentSupabaseClient<
Database = any,
SchemaName extends string & keyof Database = 'public' extends keyof Database
? 'public'
: string & keyof Database,
Schema extends GenericSchema = Database[SchemaName] extends GenericSchema
? Database[SchemaName]
: any
>(
context: {
headers: () => ReturnType<typeof headers>;
cookies: () => ReturnType<typeof cookies>;
},
{
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
cookieOptions
}: {
supabaseUrl?: string;
supabaseKey?: string;
options?: SupabaseClientOptionsWithoutAuth<SchemaName>;
cookieOptions?: CookieOptionsWithName;
} = {}
) {
console.warn(
'Please utilize the `createServerComponentClient` function instead of the deprecated `createServerComponentSupabaseClient` function. Additionally, this function no longer requires the `headers` function as a parameter. Learn more: https://supabase.com/docs/guides/auth/auth-helpers/nextjs#server-component'
);
return createServerComponentClient<Database, SchemaName, Schema>(
{ cookies: context.cookies },
{
supabaseUrl,
supabaseKey,
options,
cookieOptions
}
);
}
/**
* @deprecated utilize the `createRouteHandlerClient` function instead
*/
export function createRouteHandlerSupabaseClient<
Database = any,
SchemaName extends string & keyof Database = 'public' extends keyof Database
? 'public'
: string & keyof Database,
Schema extends GenericSchema = Database[SchemaName] extends GenericSchema
? Database[SchemaName]
: any
>(
context: { headers: () => ReturnType<typeof headers>; cookies: () => ReturnType<typeof cookies> },
{
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
cookieOptions
}: {
supabaseUrl?: string;
supabaseKey?: string;
options?: SupabaseClientOptionsWithoutAuth<SchemaName>;
cookieOptions?: CookieOptionsWithName;
} = {}
) {
console.warn(
'Please utilize the `createRouteHandlerClient` function instead of the deprecated `createRouteHandlerSupabaseClient` function. Additionally, this function no longer requires the `headers` function as a parameter. Learn more: https://supabase.com/docs/guides/auth/auth-helpers/nextjs#route-handler'
);
return createRouteHandlerClient<Database, SchemaName, Schema>(
{ cookies: context.cookies },
{
supabaseUrl,
supabaseKey,
options,
cookieOptions
}
);
}

View File

@@ -0,0 +1,17 @@
// Types
export type { Session, User, SupabaseClient } from '@supabase/supabase-js';
export { createPagesBrowserClient } from './pagesBrowserClient';
export { createPagesServerClient } from './pagesServerClient';
export { createMiddlewareClient } from './middlewareClient';
export { createClientComponentClient } from './clientComponentClient';
export { createServerComponentClient } from './serverComponentClient';
export { createRouteHandlerClient } from './routeHandlerClient';
export { createServerActionClient } from './serverActionClient';
// Deprecated Functions
export {
createBrowserSupabaseClient,
createServerSupabaseClient,
createMiddlewareSupabaseClient
} from './deprecated';

View File

@@ -0,0 +1,104 @@
import {
CookieAuthStorageAdapter,
CookieOptions,
CookieOptionsWithName,
createSupabaseClient,
DefaultCookieOptions,
parseCookies,
serializeCookie,
SupabaseClientOptionsWithoutAuth
} from '@supabase/auth-helpers-shared';
import { NextResponse } from 'next/server';
import { splitCookiesString } from 'set-cookie-parser';
import type { NextRequest } from 'next/server';
import type { GenericSchema } from '@supabase/supabase-js/dist/module/lib/types';
import type { SupabaseClient } from '@supabase/supabase-js';
class NextMiddlewareAuthStorageAdapter extends CookieAuthStorageAdapter {
constructor(
private readonly context: { req: NextRequest; res: NextResponse },
cookieOptions?: CookieOptions
) {
super(cookieOptions);
}
protected getCookie(name: string): string | null | undefined {
const setCookie = splitCookiesString(
this.context.res.headers.get('set-cookie')?.toString() ?? ''
)
.map((c) => parseCookies(c)[name])
.find((c) => !!c);
if (setCookie) {
return setCookie;
}
const cookies = parseCookies(this.context.req.headers.get('cookie') ?? '');
return cookies[name];
}
protected setCookie(name: string, value: string): void {
this._setCookie(name, value);
}
protected deleteCookie(name: string): void {
this._setCookie(name, '', {
maxAge: 0
});
}
private _setCookie(name: string, value: string, options?: DefaultCookieOptions) {
const newSessionStr = serializeCookie(name, value, {
...this.cookieOptions,
...options,
// Allow supabase-js on the client to read the cookie as well
httpOnly: false
});
if (this.context.res.headers) {
this.context.res.headers.append('set-cookie', newSessionStr);
}
}
}
export function createMiddlewareClient<
Database = any,
SchemaName extends string & keyof Database = 'public' extends keyof Database
? 'public'
: string & keyof Database,
Schema extends GenericSchema = Database[SchemaName] extends GenericSchema
? Database[SchemaName]
: any
>(
context: { req: NextRequest; res: NextResponse },
{
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
cookieOptions
}: {
supabaseUrl?: string;
supabaseKey?: string;
options?: SupabaseClientOptionsWithoutAuth<SchemaName>;
cookieOptions?: CookieOptionsWithName;
} = {}
): SupabaseClient<Database, SchemaName, Schema> {
if (!supabaseUrl || !supabaseKey) {
throw new Error(
'either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!'
);
}
return createSupabaseClient<Database, SchemaName, Schema>(supabaseUrl, supabaseKey, {
...options,
global: {
...options?.global,
headers: {
...options?.global?.headers,
'X-Client-Info': `${PACKAGE_NAME}@${PACKAGE_VERSION}`
}
},
auth: {
storage: new NextMiddlewareAuthStorageAdapter(context, cookieOptions)
}
});
}

View File

@@ -0,0 +1,3 @@
import { createClientComponentClient } from './clientComponentClient';
export const createPagesBrowserClient = createClientComponentClient;

View File

@@ -0,0 +1,103 @@
import {
CookieAuthStorageAdapter,
CookieOptions,
CookieOptionsWithName,
createSupabaseClient,
DefaultCookieOptions,
parseCookies,
serializeCookie,
SupabaseClientOptionsWithoutAuth
} from '@supabase/auth-helpers-shared';
import { GetServerSidePropsContext, NextApiRequest, NextApiResponse } from 'next';
import { splitCookiesString } from 'set-cookie-parser';
import type { GenericSchema } from '@supabase/supabase-js/dist/module/lib/types';
import type { SupabaseClient } from '@supabase/supabase-js';
class NextServerAuthStorageAdapter extends CookieAuthStorageAdapter {
constructor(
private readonly context:
| GetServerSidePropsContext
| { req: NextApiRequest; res: NextApiResponse },
cookieOptions?: CookieOptions
) {
super(cookieOptions);
}
protected getCookie(name: string): string | null | undefined {
const setCookie = splitCookiesString(
this.context.res?.getHeader('set-cookie')?.toString() ?? ''
)
.map((c) => parseCookies(c)[name])
.find((c) => !!c);
const value = setCookie ?? this.context.req?.cookies[name];
return value;
}
protected setCookie(name: string, value: string): void {
this._setCookie(name, value);
}
protected deleteCookie(name: string): void {
this._setCookie(name, '', {
maxAge: 0
});
}
private _setCookie(name: string, value: string, options?: DefaultCookieOptions) {
const setCookies = splitCookiesString(
this.context.res.getHeader('set-cookie')?.toString() ?? ''
).filter((c) => !(name in parseCookies(c)));
const cookieStr = serializeCookie(name, value, {
...this.cookieOptions,
...options,
// Allow supabase-js on the client to read the cookie as well
httpOnly: false
});
this.context.res.setHeader('set-cookie', [...setCookies, cookieStr]);
}
}
export function createPagesServerClient<
Database = any,
SchemaName extends string & keyof Database = 'public' extends keyof Database
? 'public'
: string & keyof Database,
Schema extends GenericSchema = Database[SchemaName] extends GenericSchema
? Database[SchemaName]
: any
>(
context: GetServerSidePropsContext | { req: NextApiRequest; res: NextApiResponse },
{
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
cookieOptions
}: {
supabaseUrl?: string;
supabaseKey?: string;
options?: SupabaseClientOptionsWithoutAuth<SchemaName>;
cookieOptions?: CookieOptionsWithName;
} = {}
): SupabaseClient<Database, SchemaName, Schema> {
if (!supabaseUrl || !supabaseKey) {
throw new Error(
'either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!'
);
}
return createSupabaseClient<Database, SchemaName, Schema>(supabaseUrl, supabaseKey, {
...options,
global: {
...options?.global,
headers: {
...options?.global?.headers,
'X-Client-Info': `${PACKAGE_NAME}@${PACKAGE_VERSION}`
}
},
auth: {
storage: new NextServerAuthStorageAdapter(context, cookieOptions)
}
});
}

View File

@@ -0,0 +1,83 @@
import {
CookieAuthStorageAdapter,
CookieOptions,
CookieOptionsWithName,
SupabaseClientOptionsWithoutAuth,
createSupabaseClient
} from '@supabase/auth-helpers-shared';
import { cookies } from 'next/headers';
import type { GenericSchema } from '@supabase/supabase-js/dist/module/lib/types';
import type { SupabaseClient } from '@supabase/supabase-js';
class NextRouteHandlerAuthStorageAdapter extends CookieAuthStorageAdapter {
constructor(
private readonly context: {
cookies: () => ReturnType<typeof cookies>;
},
cookieOptions?: CookieOptions
) {
super(cookieOptions);
}
protected getCookie(name: string): string | null | undefined {
const nextCookies = this.context.cookies();
return nextCookies.get(name)?.value;
}
protected setCookie(name: string, value: string): void {
const nextCookies = this.context.cookies();
nextCookies.set(name, value, this.cookieOptions);
}
protected deleteCookie(name: string): void {
const nextCookies = this.context.cookies();
nextCookies.set(name, '', {
...this.cookieOptions,
maxAge: 0
});
}
}
export function createRouteHandlerClient<
Database = any,
SchemaName extends string & keyof Database = 'public' extends keyof Database
? 'public'
: string & keyof Database,
Schema extends GenericSchema = Database[SchemaName] extends GenericSchema
? Database[SchemaName]
: any
>(
context: {
cookies: () => ReturnType<typeof cookies>;
},
{
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
cookieOptions
}: {
supabaseUrl?: string;
supabaseKey?: string;
options?: SupabaseClientOptionsWithoutAuth<SchemaName>;
cookieOptions?: CookieOptionsWithName;
} = {}
): SupabaseClient<Database, SchemaName, Schema> {
if (!supabaseUrl || !supabaseKey) {
throw new Error(
'either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!'
);
}
return createSupabaseClient<Database, SchemaName, Schema>(supabaseUrl, supabaseKey, {
...options,
global: {
...options?.global,
headers: {
...options?.global?.headers,
'X-Client-Info': `${PACKAGE_NAME}@${PACKAGE_VERSION}`
}
},
auth: {
storage: new NextRouteHandlerAuthStorageAdapter(context, cookieOptions)
}
});
}

View File

@@ -0,0 +1,3 @@
import { createRouteHandlerClient } from './routeHandlerClient';
export const createServerActionClient = createRouteHandlerClient;

View File

@@ -0,0 +1,82 @@
import {
CookieAuthStorageAdapter,
CookieOptions,
CookieOptionsWithName,
SupabaseClientOptionsWithoutAuth,
createSupabaseClient
} from '@supabase/auth-helpers-shared';
import { cookies } from 'next/headers';
import type { SupabaseClient } from '@supabase/supabase-js';
import type { GenericSchema } from '@supabase/supabase-js/dist/module/lib/types';
class NextServerComponentAuthStorageAdapter extends CookieAuthStorageAdapter {
readonly isServer = true;
constructor(
private readonly context: {
cookies: () => ReturnType<typeof cookies>;
},
cookieOptions?: CookieOptions
) {
super(cookieOptions);
}
protected getCookie(name: string): string | null | undefined {
const nextCookies = this.context.cookies();
return nextCookies.get(name)?.value;
}
protected setCookie(name: string, value: string): void {
// Server Components cannot set cookies. Must use Middleware, Server Action or Route Handler
// https://github.com/vercel/next.js/discussions/41745#discussioncomment-5198848
}
protected deleteCookie(name: string): void {
// Server Components cannot set cookies. Must use Middleware, Server Action or Route Handler
// https://github.com/vercel/next.js/discussions/41745#discussioncomment-5198848
}
}
export function createServerComponentClient<
Database = any,
SchemaName extends string & keyof Database = 'public' extends keyof Database
? 'public'
: string & keyof Database,
Schema extends GenericSchema = Database[SchemaName] extends GenericSchema
? Database[SchemaName]
: any
>(
context: {
cookies: () => ReturnType<typeof cookies>;
},
{
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
cookieOptions
}: {
supabaseUrl?: string;
supabaseKey?: string;
options?: SupabaseClientOptionsWithoutAuth<SchemaName>;
cookieOptions?: CookieOptionsWithName;
} = {}
): SupabaseClient<Database, SchemaName, Schema> {
if (!supabaseUrl || !supabaseKey) {
throw new Error(
'either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!'
);
}
return createSupabaseClient<Database, SchemaName, Schema>(supabaseUrl, supabaseKey, {
...options,
global: {
...options?.global,
headers: {
...options?.global?.headers,
'X-Client-Info': `${PACKAGE_NAME}@${PACKAGE_VERSION}`
}
},
auth: {
storage: new NextServerComponentAuthStorageAdapter(context, cookieOptions)
}
});
}

View File

@@ -0,0 +1,9 @@
{
"extends": "tsconfig/base.json",
"compilerOptions": {
"incremental": false,
"importHelpers": true
},
"include": ["src"],
"exclude": ["node_modules"]
}

View File

@@ -0,0 +1,20 @@
import type { Options } from 'tsup';
import pkg from './package.json';
export const tsup: Options = {
dts: true,
entryPoints: ['src/index.ts'],
external: ['next', 'react', /^@supabase\//],
format: ['cjs'],
// inject: ['src/react-shim.js'],
// ! .cjs/.mjs doesn't work with Angular's webpack4 config by default!
legacyOutput: false,
sourcemap: true,
splitting: false,
bundle: true,
clean: true,
define: {
PACKAGE_NAME: JSON.stringify(pkg.name),
PACKAGE_VERSION: JSON.stringify(pkg.version)
}
};

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

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 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.

View File

@@ -0,0 +1,50 @@
import * as _supabase_supabase_js from '@supabase/supabase-js';
import { SupabaseClientOptions, GoTrueClientOptions, Session } from '@supabase/supabase-js';
import { CookieSerializeOptions } from 'cookie';
export { parse as parseCookies, serialize as serializeCookie } from 'cookie';
import { GenericSchema } from '@supabase/supabase-js/dist/module/lib/types';
type CookieOptions = Pick<CookieSerializeOptions, 'domain' | 'secure' | 'path' | 'sameSite'>;
type DefaultCookieOptions = Pick<CookieSerializeOptions, 'domain' | 'secure' | 'path' | 'sameSite' | 'maxAge'>;
type CookieOptionsWithName = {
name?: string;
} & CookieOptions;
type SupabaseClientOptionsWithoutAuth<SchemaName = 'public'> = Omit<SupabaseClientOptions<SchemaName>, 'auth'>;
interface StorageAdapter extends Exclude<GoTrueClientOptions['storage'], undefined> {
}
declare abstract class CookieAuthStorageAdapter implements StorageAdapter {
protected readonly cookieOptions: DefaultCookieOptions;
constructor(cookieOptions?: CookieOptions);
protected abstract getCookie(name: string): string | undefined | null;
protected abstract setCookie(name: string, value: string): void;
protected abstract deleteCookie(name: string): void;
getItem(key: string): string | Promise<string | null> | null;
setItem(key: string, value: string): void | Promise<void>;
removeItem(key: string): void | Promise<void>;
private _deleteSingleCookie;
private _deleteChunkedCookies;
}
declare class BrowserCookieAuthStorageAdapter extends CookieAuthStorageAdapter {
constructor(cookieOptions?: CookieOptions);
protected getCookie(name: string): string | null;
protected setCookie(name: string, value: string): null | undefined;
protected deleteCookie(name: string): null | undefined;
}
declare function createSupabaseClient<Database = any, SchemaName extends string & keyof Database = 'public' extends keyof Database ? 'public' : string & keyof Database, Schema extends GenericSchema = Database[SchemaName] extends GenericSchema ? Database[SchemaName] : any>(supabaseUrl: string, supabaseKey: string, options: SupabaseClientOptionsWithoutAuth<SchemaName> & {
auth: {
storage: StorageAdapter;
storageKey?: string;
};
}): _supabase_supabase_js.SupabaseClient<Database, SchemaName, Schema>;
declare function parseSupabaseCookie(str: string | null | undefined): Partial<Session> | null;
declare function stringifySupabaseSession(session: Session): string;
declare function isBrowser(): boolean;
declare const DEFAULT_COOKIE_OPTIONS: DefaultCookieOptions;
export { BrowserCookieAuthStorageAdapter, CookieAuthStorageAdapter, CookieOptions, CookieOptionsWithName, DEFAULT_COOKIE_OPTIONS, DefaultCookieOptions, StorageAdapter, SupabaseClientOptionsWithoutAuth, createSupabaseClient, isBrowser, parseSupabaseCookie, stringifySupabaseSession };

View File

@@ -0,0 +1,419 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// ../../node_modules/.pnpm/cookie@0.5.0/node_modules/cookie/index.js
var require_cookie = __commonJS({
"../../node_modules/.pnpm/cookie@0.5.0/node_modules/cookie/index.js"(exports) {
"use strict";
exports.parse = parse3;
exports.serialize = serialize3;
var __toString = Object.prototype.toString;
var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
function parse3(str, options) {
if (typeof str !== "string") {
throw new TypeError("argument str must be a string");
}
var obj = {};
var opt = options || {};
var dec = opt.decode || decode;
var index = 0;
while (index < str.length) {
var eqIdx = str.indexOf("=", index);
if (eqIdx === -1) {
break;
}
var endIdx = str.indexOf(";", index);
if (endIdx === -1) {
endIdx = str.length;
} else if (endIdx < eqIdx) {
index = str.lastIndexOf(";", eqIdx - 1) + 1;
continue;
}
var key = str.slice(index, eqIdx).trim();
if (void 0 === obj[key]) {
var val = str.slice(eqIdx + 1, endIdx).trim();
if (val.charCodeAt(0) === 34) {
val = val.slice(1, -1);
}
obj[key] = tryDecode(val, dec);
}
index = endIdx + 1;
}
return obj;
}
function serialize3(name, val, options) {
var opt = options || {};
var enc = opt.encode || encode;
if (typeof enc !== "function") {
throw new TypeError("option encode is invalid");
}
if (!fieldContentRegExp.test(name)) {
throw new TypeError("argument name is invalid");
}
var value = enc(val);
if (value && !fieldContentRegExp.test(value)) {
throw new TypeError("argument val is invalid");
}
var str = name + "=" + value;
if (null != opt.maxAge) {
var maxAge = opt.maxAge - 0;
if (isNaN(maxAge) || !isFinite(maxAge)) {
throw new TypeError("option maxAge is invalid");
}
str += "; Max-Age=" + Math.floor(maxAge);
}
if (opt.domain) {
if (!fieldContentRegExp.test(opt.domain)) {
throw new TypeError("option domain is invalid");
}
str += "; Domain=" + opt.domain;
}
if (opt.path) {
if (!fieldContentRegExp.test(opt.path)) {
throw new TypeError("option path is invalid");
}
str += "; Path=" + opt.path;
}
if (opt.expires) {
var expires = opt.expires;
if (!isDate(expires) || isNaN(expires.valueOf())) {
throw new TypeError("option expires is invalid");
}
str += "; Expires=" + expires.toUTCString();
}
if (opt.httpOnly) {
str += "; HttpOnly";
}
if (opt.secure) {
str += "; Secure";
}
if (opt.priority) {
var priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority;
switch (priority) {
case "low":
str += "; Priority=Low";
break;
case "medium":
str += "; Priority=Medium";
break;
case "high":
str += "; Priority=High";
break;
default:
throw new TypeError("option priority is invalid");
}
}
if (opt.sameSite) {
var sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite;
switch (sameSite) {
case true:
str += "; SameSite=Strict";
break;
case "lax":
str += "; SameSite=Lax";
break;
case "strict":
str += "; SameSite=Strict";
break;
case "none":
str += "; SameSite=None";
break;
default:
throw new TypeError("option sameSite is invalid");
}
}
return str;
}
function decode(str) {
return str.indexOf("%") !== -1 ? decodeURIComponent(str) : str;
}
function encode(val) {
return encodeURIComponent(val);
}
function isDate(val) {
return __toString.call(val) === "[object Date]" || val instanceof Date;
}
function tryDecode(str, decode2) {
try {
return decode2(str);
} catch (e) {
return str;
}
}
}
});
// src/index.ts
var src_exports = {};
__export(src_exports, {
BrowserCookieAuthStorageAdapter: () => BrowserCookieAuthStorageAdapter,
CookieAuthStorageAdapter: () => CookieAuthStorageAdapter,
DEFAULT_COOKIE_OPTIONS: () => DEFAULT_COOKIE_OPTIONS,
createSupabaseClient: () => createSupabaseClient,
isBrowser: () => isBrowser,
parseCookies: () => import_cookie.parse,
parseSupabaseCookie: () => parseSupabaseCookie,
serializeCookie: () => import_cookie.serialize,
stringifySupabaseSession: () => stringifySupabaseSession
});
module.exports = __toCommonJS(src_exports);
// src/browserCookieStorage.ts
var import_cookie2 = __toESM(require_cookie());
// src/utils/cookies.ts
var import_cookie = __toESM(require_cookie());
var import_jose = require("jose");
function parseSupabaseCookie(str) {
if (!str) {
return null;
}
try {
const session = JSON.parse(str);
if (!session) {
return null;
}
if (session.constructor.name === "Object") {
return session;
}
if (session.constructor.name !== "Array") {
throw new Error(`Unexpected format: ${session.constructor.name}`);
}
const [_header, payloadStr, _signature] = session[0].split(".");
const payload = import_jose.base64url.decode(payloadStr);
const decoder = new TextDecoder();
const { exp, sub, ...user } = JSON.parse(decoder.decode(payload));
return {
expires_at: exp,
expires_in: exp - Math.round(Date.now() / 1e3),
token_type: "bearer",
access_token: session[0],
refresh_token: session[1],
provider_token: session[2],
provider_refresh_token: session[3],
user: {
id: sub,
factors: session[4],
...user
}
};
} catch (err) {
console.warn("Failed to parse cookie string:", err);
return null;
}
}
function stringifySupabaseSession(session) {
var _a;
return JSON.stringify([
session.access_token,
session.refresh_token,
session.provider_token,
session.provider_refresh_token,
((_a = session.user) == null ? void 0 : _a.factors) ?? null
]);
}
// src/utils/helpers.ts
function isBrowser() {
return typeof window !== "undefined" && typeof window.document !== "undefined";
}
// src/utils/constants.ts
var DEFAULT_COOKIE_OPTIONS = {
path: "/",
sameSite: "lax",
maxAge: 60 * 60 * 24 * 365 * 1e3
};
// src/chunker.ts
function createChunkRegExp(chunkSize) {
return new RegExp(".{1," + chunkSize + "}", "g");
}
var MAX_CHUNK_SIZE = 3180;
var MAX_CHUNK_REGEXP = createChunkRegExp(MAX_CHUNK_SIZE);
function createChunks(key, value, chunkSize) {
const re = chunkSize !== void 0 ? createChunkRegExp(chunkSize) : MAX_CHUNK_REGEXP;
const chunkCount = Math.ceil(value.length / (chunkSize ?? MAX_CHUNK_SIZE));
if (chunkCount === 1) {
return [{ name: key, value }];
}
const chunks = [];
const values = value.match(re);
values == null ? void 0 : values.forEach((value2, i) => {
const name = `${key}.${i}`;
chunks.push({ name, value: value2 });
});
return chunks;
}
function combineChunks(key, retrieveChunk = () => {
return null;
}) {
let values = [];
for (let i = 0; ; i++) {
const chunkName = `${key}.${i}`;
const chunk = retrieveChunk(chunkName);
if (!chunk) {
break;
}
values.push(chunk);
}
return values.length ? values.join("") : null;
}
// src/cookieAuthStorageAdapter.ts
var CookieAuthStorageAdapter = class {
constructor(cookieOptions) {
this.cookieOptions = {
...DEFAULT_COOKIE_OPTIONS,
...cookieOptions,
maxAge: DEFAULT_COOKIE_OPTIONS.maxAge
};
}
getItem(key) {
const value = this.getCookie(key);
if (key.endsWith("-code-verifier") && value) {
return value;
}
if (value) {
return JSON.stringify(parseSupabaseCookie(value));
}
const chunks = combineChunks(key, (chunkName) => {
return this.getCookie(chunkName);
});
return chunks !== null ? JSON.stringify(parseSupabaseCookie(chunks)) : null;
}
setItem(key, value) {
if (key.endsWith("-code-verifier")) {
this.setCookie(key, value);
return;
}
let session = JSON.parse(value);
const sessionStr = stringifySupabaseSession(session);
const sessionChunks = createChunks(key, sessionStr);
sessionChunks.forEach((sess) => {
this.setCookie(sess.name, sess.value);
});
}
removeItem(key) {
this._deleteSingleCookie(key);
this._deleteChunkedCookies(key);
}
_deleteSingleCookie(key) {
if (this.getCookie(key)) {
this.deleteCookie(key);
}
}
_deleteChunkedCookies(key, from = 0) {
for (let i = from; ; i++) {
const cookieName = `${key}.${i}`;
const value = this.getCookie(cookieName);
if (value === void 0) {
break;
}
this.deleteCookie(cookieName);
}
}
};
// src/browserCookieStorage.ts
var BrowserCookieAuthStorageAdapter = class extends CookieAuthStorageAdapter {
constructor(cookieOptions) {
super(cookieOptions);
}
getCookie(name) {
if (!isBrowser())
return null;
const cookies = (0, import_cookie2.parse)(document.cookie);
return cookies[name];
}
setCookie(name, value) {
if (!isBrowser())
return null;
document.cookie = (0, import_cookie2.serialize)(name, value, {
...this.cookieOptions,
httpOnly: false
});
}
deleteCookie(name) {
if (!isBrowser())
return null;
document.cookie = (0, import_cookie2.serialize)(name, "", {
...this.cookieOptions,
maxAge: 0,
httpOnly: false
});
}
};
// src/createClient.ts
var import_supabase_js = require("@supabase/supabase-js");
function createSupabaseClient(supabaseUrl, supabaseKey, options) {
var _a;
const browser = isBrowser();
return (0, import_supabase_js.createClient)(supabaseUrl, supabaseKey, {
...options,
auth: {
flowType: "pkce",
autoRefreshToken: browser,
detectSessionInUrl: browser,
persistSession: true,
storage: options.auth.storage,
// fix this in supabase-js
...((_a = options.auth) == null ? void 0 : _a.storageKey) ? {
storageKey: options.auth.storageKey
} : {}
}
});
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BrowserCookieAuthStorageAdapter,
CookieAuthStorageAdapter,
DEFAULT_COOKIE_OPTIONS,
createSupabaseClient,
isBrowser,
parseCookies,
parseSupabaseCookie,
serializeCookie,
stringifySupabaseSession
});
/*! Bundled license information:
cookie/index.js:
(*!
* cookie
* Copyright(c) 2012-2014 Roman Shtylman
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*)
*/
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,399 @@
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
// ../../node_modules/.pnpm/cookie@0.5.0/node_modules/cookie/index.js
var require_cookie = __commonJS({
"../../node_modules/.pnpm/cookie@0.5.0/node_modules/cookie/index.js"(exports) {
"use strict";
exports.parse = parse3;
exports.serialize = serialize3;
var __toString = Object.prototype.toString;
var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
function parse3(str, options) {
if (typeof str !== "string") {
throw new TypeError("argument str must be a string");
}
var obj = {};
var opt = options || {};
var dec = opt.decode || decode;
var index = 0;
while (index < str.length) {
var eqIdx = str.indexOf("=", index);
if (eqIdx === -1) {
break;
}
var endIdx = str.indexOf(";", index);
if (endIdx === -1) {
endIdx = str.length;
} else if (endIdx < eqIdx) {
index = str.lastIndexOf(";", eqIdx - 1) + 1;
continue;
}
var key = str.slice(index, eqIdx).trim();
if (void 0 === obj[key]) {
var val = str.slice(eqIdx + 1, endIdx).trim();
if (val.charCodeAt(0) === 34) {
val = val.slice(1, -1);
}
obj[key] = tryDecode(val, dec);
}
index = endIdx + 1;
}
return obj;
}
function serialize3(name, val, options) {
var opt = options || {};
var enc = opt.encode || encode;
if (typeof enc !== "function") {
throw new TypeError("option encode is invalid");
}
if (!fieldContentRegExp.test(name)) {
throw new TypeError("argument name is invalid");
}
var value = enc(val);
if (value && !fieldContentRegExp.test(value)) {
throw new TypeError("argument val is invalid");
}
var str = name + "=" + value;
if (null != opt.maxAge) {
var maxAge = opt.maxAge - 0;
if (isNaN(maxAge) || !isFinite(maxAge)) {
throw new TypeError("option maxAge is invalid");
}
str += "; Max-Age=" + Math.floor(maxAge);
}
if (opt.domain) {
if (!fieldContentRegExp.test(opt.domain)) {
throw new TypeError("option domain is invalid");
}
str += "; Domain=" + opt.domain;
}
if (opt.path) {
if (!fieldContentRegExp.test(opt.path)) {
throw new TypeError("option path is invalid");
}
str += "; Path=" + opt.path;
}
if (opt.expires) {
var expires = opt.expires;
if (!isDate(expires) || isNaN(expires.valueOf())) {
throw new TypeError("option expires is invalid");
}
str += "; Expires=" + expires.toUTCString();
}
if (opt.httpOnly) {
str += "; HttpOnly";
}
if (opt.secure) {
str += "; Secure";
}
if (opt.priority) {
var priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority;
switch (priority) {
case "low":
str += "; Priority=Low";
break;
case "medium":
str += "; Priority=Medium";
break;
case "high":
str += "; Priority=High";
break;
default:
throw new TypeError("option priority is invalid");
}
}
if (opt.sameSite) {
var sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite;
switch (sameSite) {
case true:
str += "; SameSite=Strict";
break;
case "lax":
str += "; SameSite=Lax";
break;
case "strict":
str += "; SameSite=Strict";
break;
case "none":
str += "; SameSite=None";
break;
default:
throw new TypeError("option sameSite is invalid");
}
}
return str;
}
function decode(str) {
return str.indexOf("%") !== -1 ? decodeURIComponent(str) : str;
}
function encode(val) {
return encodeURIComponent(val);
}
function isDate(val) {
return __toString.call(val) === "[object Date]" || val instanceof Date;
}
function tryDecode(str, decode2) {
try {
return decode2(str);
} catch (e) {
return str;
}
}
}
});
// src/browserCookieStorage.ts
var import_cookie2 = __toESM(require_cookie());
// src/utils/cookies.ts
var import_cookie = __toESM(require_cookie());
import { base64url } from "jose";
function parseSupabaseCookie(str) {
if (!str) {
return null;
}
try {
const session = JSON.parse(str);
if (!session) {
return null;
}
if (session.constructor.name === "Object") {
return session;
}
if (session.constructor.name !== "Array") {
throw new Error(`Unexpected format: ${session.constructor.name}`);
}
const [_header, payloadStr, _signature] = session[0].split(".");
const payload = base64url.decode(payloadStr);
const decoder = new TextDecoder();
const { exp, sub, ...user } = JSON.parse(decoder.decode(payload));
return {
expires_at: exp,
expires_in: exp - Math.round(Date.now() / 1e3),
token_type: "bearer",
access_token: session[0],
refresh_token: session[1],
provider_token: session[2],
provider_refresh_token: session[3],
user: {
id: sub,
factors: session[4],
...user
}
};
} catch (err) {
console.warn("Failed to parse cookie string:", err);
return null;
}
}
function stringifySupabaseSession(session) {
var _a;
return JSON.stringify([
session.access_token,
session.refresh_token,
session.provider_token,
session.provider_refresh_token,
((_a = session.user) == null ? void 0 : _a.factors) ?? null
]);
}
// src/utils/helpers.ts
function isBrowser() {
return typeof window !== "undefined" && typeof window.document !== "undefined";
}
// src/utils/constants.ts
var DEFAULT_COOKIE_OPTIONS = {
path: "/",
sameSite: "lax",
maxAge: 60 * 60 * 24 * 365 * 1e3
};
// src/chunker.ts
function createChunkRegExp(chunkSize) {
return new RegExp(".{1," + chunkSize + "}", "g");
}
var MAX_CHUNK_SIZE = 3180;
var MAX_CHUNK_REGEXP = createChunkRegExp(MAX_CHUNK_SIZE);
function createChunks(key, value, chunkSize) {
const re = chunkSize !== void 0 ? createChunkRegExp(chunkSize) : MAX_CHUNK_REGEXP;
const chunkCount = Math.ceil(value.length / (chunkSize ?? MAX_CHUNK_SIZE));
if (chunkCount === 1) {
return [{ name: key, value }];
}
const chunks = [];
const values = value.match(re);
values == null ? void 0 : values.forEach((value2, i) => {
const name = `${key}.${i}`;
chunks.push({ name, value: value2 });
});
return chunks;
}
function combineChunks(key, retrieveChunk = () => {
return null;
}) {
let values = [];
for (let i = 0; ; i++) {
const chunkName = `${key}.${i}`;
const chunk = retrieveChunk(chunkName);
if (!chunk) {
break;
}
values.push(chunk);
}
return values.length ? values.join("") : null;
}
// src/cookieAuthStorageAdapter.ts
var CookieAuthStorageAdapter = class {
constructor(cookieOptions) {
this.cookieOptions = {
...DEFAULT_COOKIE_OPTIONS,
...cookieOptions,
maxAge: DEFAULT_COOKIE_OPTIONS.maxAge
};
}
getItem(key) {
const value = this.getCookie(key);
if (key.endsWith("-code-verifier") && value) {
return value;
}
if (value) {
return JSON.stringify(parseSupabaseCookie(value));
}
const chunks = combineChunks(key, (chunkName) => {
return this.getCookie(chunkName);
});
return chunks !== null ? JSON.stringify(parseSupabaseCookie(chunks)) : null;
}
setItem(key, value) {
if (key.endsWith("-code-verifier")) {
this.setCookie(key, value);
return;
}
let session = JSON.parse(value);
const sessionStr = stringifySupabaseSession(session);
const sessionChunks = createChunks(key, sessionStr);
sessionChunks.forEach((sess) => {
this.setCookie(sess.name, sess.value);
});
}
removeItem(key) {
this._deleteSingleCookie(key);
this._deleteChunkedCookies(key);
}
_deleteSingleCookie(key) {
if (this.getCookie(key)) {
this.deleteCookie(key);
}
}
_deleteChunkedCookies(key, from = 0) {
for (let i = from; ; i++) {
const cookieName = `${key}.${i}`;
const value = this.getCookie(cookieName);
if (value === void 0) {
break;
}
this.deleteCookie(cookieName);
}
}
};
// src/browserCookieStorage.ts
var BrowserCookieAuthStorageAdapter = class extends CookieAuthStorageAdapter {
constructor(cookieOptions) {
super(cookieOptions);
}
getCookie(name) {
if (!isBrowser())
return null;
const cookies = (0, import_cookie2.parse)(document.cookie);
return cookies[name];
}
setCookie(name, value) {
if (!isBrowser())
return null;
document.cookie = (0, import_cookie2.serialize)(name, value, {
...this.cookieOptions,
httpOnly: false
});
}
deleteCookie(name) {
if (!isBrowser())
return null;
document.cookie = (0, import_cookie2.serialize)(name, "", {
...this.cookieOptions,
maxAge: 0,
httpOnly: false
});
}
};
// src/createClient.ts
import { createClient } from "@supabase/supabase-js";
function createSupabaseClient(supabaseUrl, supabaseKey, options) {
var _a;
const browser = isBrowser();
return createClient(supabaseUrl, supabaseKey, {
...options,
auth: {
flowType: "pkce",
autoRefreshToken: browser,
detectSessionInUrl: browser,
persistSession: true,
storage: options.auth.storage,
// fix this in supabase-js
...((_a = options.auth) == null ? void 0 : _a.storageKey) ? {
storageKey: options.auth.storageKey
} : {}
}
});
}
var export_parseCookies = import_cookie.parse;
var export_serializeCookie = import_cookie.serialize;
export {
BrowserCookieAuthStorageAdapter,
CookieAuthStorageAdapter,
DEFAULT_COOKIE_OPTIONS,
createSupabaseClient,
isBrowser,
export_parseCookies as parseCookies,
parseSupabaseCookie,
export_serializeCookie as serializeCookie,
stringifySupabaseSession
};
/*! Bundled license information:
cookie/index.js:
(*!
* cookie
* Copyright(c) 2012-2014 Roman Shtylman
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*)
*/
//# sourceMappingURL=index.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,52 @@
{
"name": "@supabase/auth-helpers-shared",
"version": "0.7.0",
"main": "dist/index.js",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"publishConfig": {
"access": "public"
},
"files": [
"dist"
],
"repository": {
"type": "git",
"url": "git+https://github.com/supabase/auth-helpers.git"
},
"keywords": [
"Supabase",
"Auth",
"Svelte Kit",
"Svelte"
],
"author": "Supabase",
"license": "MIT",
"bugs": {
"url": "https://github.com/supabase/auth-helpers/issues"
},
"homepage": "https://github.com/supabase/auth-helpers#readme",
"devDependencies": {
"@supabase/supabase-js": "2.42.0",
"@types/cookie": "^0.5.1",
"cookie": "^0.5.0",
"next": "^13.5.5",
"react": ">=17.0.2 <18.0.0 || >=18.0.0-0 <19.0.0",
"react-dom": "^17.0.2 || ^18.0.0-0",
"tsup": "^6.7.0",
"vitest": "^0.34.6",
"tsconfig": "0.1.1"
},
"dependencies": {
"jose": "^4.14.4"
},
"peerDependencies": {
"@supabase/supabase-js": "^2.39.8"
},
"scripts": {
"lint": "tsc",
"build": "tsup",
"test": "vitest run",
"test:watch": "vitest"
}
}

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, SignOutScope } 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?: SignOutScope): 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,EAEV,YAAY,EACb,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,SAAS,EAAe,MAAM,cAAc,CAAA;AAErD,MAAM,CAAC,OAAO,OAAO,cAAc;IACjC,+CAA+C;IAC/C,GAAG,EAAE,iBAAiB,CAAA;IAEtB,SAAS,CAAC,GAAG,EAAE,MAAM,CAAA;IACrB,SAAS,CAAC,OAAO,EAAE;QACjB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KACtB,CAAA;IACD,SAAS,CAAC,KAAK,EAAE,KAAK,CAAA;gBAEV,EACV,GAAQ,EACR,OAAY,EACZ,KAAK,GACN,EAAE;QACD,GAAG,EAAE,MAAM,CAAA;QACX,OAAO,CAAC,EAAE;YACR,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;SACtB,CAAA;QACD,KAAK,CAAC,EAAE,KAAK,CAAA;KACd;IAUD;;;;OAIG;IACG,OAAO,CACX,GAAG,EAAE,MAAM,EACX,KAAK,GAAE,YAAiC,GACvC,OAAO,CAAC;QAAE,IAAI,EAAE,IAAI,CAAC;QAAC,KAAK,EAAE,SAAS,GAAG,IAAI,CAAA;KAAE,CAAC;IAuBnD;;;;OAIG;IACG,iBAAiB,CACrB,KAAK,EAAE,MAAM,EACb,OAAO,GAAE;QACP,4HAA4H;QAC5H,IAAI,CAAC,EAAE,MAAM,CAAA;QAEb,wIAAwI;QACxI,UAAU,CAAC,EAAE,MAAM,CAAA;KACf,GACL,OAAO,CAAC,YAAY,CAAC;IAiBxB;;;;;;OAMG;IACG,YAAY,CAAC,MAAM,EAAE,kBAAkB,GAAG,OAAO,CAAC,oBAAoB,CAAC;IA8B7E;;;OAGG;IACG,UAAU,CAAC,UAAU,EAAE,mBAAmB,GAAG,OAAO,CAAC,YAAY,CAAC;IAgBxE;;;;;OAKG;IACG,SAAS,CACb,MAAM,CAAC,EAAE,UAAU,GAClB,OAAO,CACN;QAAE,IAAI,EAAE;YAAE,KAAK,EAAE,IAAI,EAAE,CAAC;YAAC,GAAG,EAAE,MAAM,CAAA;SAAE,GAAG,UAAU,CAAC;QAAC,KAAK,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;IAiBrD;;;;;;OAMG;IACG,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,mBAAmB,GAAG,OAAO,CAAC,YAAY,CAAC;IAkBzF;;;;;;;;OAQG;IACG,UAAU,CAAC,EAAE,EAAE,MAAM,EAAE,gBAAgB,UAAQ,GAAG,OAAO,CAAC,YAAY,CAAC;YAoB/D,YAAY;YA2BZ,aAAa;CAyB5B"}

View File

@@ -0,0 +1,278 @@
"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 types_1 = require("./lib/types");
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 = types_1.SIGN_OUT_SCOPES[0]) {
if (types_1.SIGN_OUT_SCOPES.indexOf(scope) < 0) {
throw new Error(`@supabase/auth-js: Parameter scope must be one of ${types_1.SIGN_OUT_SCOPES.join(', ')}`);
}
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) {
(0, helpers_1.validateUUID)(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) {
(0, helpers_1.validateUUID)(uid);
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) {
(0, helpers_1.validateUUID)(id);
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) {
(0, helpers_1.validateUUID)(params.userId);
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) {
(0, helpers_1.validateUUID)(params.userId);
(0, helpers_1.validateUUID)(params.id);
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,521 @@
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, User, UserAttributes, UserResponse, VerifyOtpParams, GoTrueMFAApi, ResendParams, AuthFlowType, LockFunc, UserIdentity, SignInAnonymouslyCredentials, JWK, JwtPayload, JwtHeader, Web3Credentials } 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 get jwks(): {
keys: JWK[];
};
protected set jwks(value: {
keys: JWK[];
});
protected get jwks_cached_at(): number;
protected set jwks_cached_at(value: number);
protected autoRefreshToken: boolean;
protected persistSession: boolean;
protected storage: SupportedStorage;
/**
* @experimental
*/
protected userStorage: SupportedStorage | null;
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>;
/**
* Signs in a user by verifying a message signed by the user's private key.
* Only Solana supported at this time, using the Sign in with Solana standard.
*/
signInWithWeb3(credentials: Web3Credentials): Promise<{
data: {
session: Session;
user: User;
};
error: null;
} | {
data: {
session: null;
user: null;
};
error: AuthError;
}>;
private signInWithSolana;
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;
/**
* Extracts the JWT claims present in the access token by first verifying the
* JWT against the server's JSON Web Key Set endpoint
* `/.well-known/jwks.json` which is often cached, resulting in significantly
* faster responses. Prefer this method over {@link #getUser} which always
* sends a request to the Auth server for each JWT.
*
* If the project is not using an asymmetric JWT signing key (like ECC or
* RSA) it always sends a request to the Auth server (similar to {@link
* #getUser}) to verify the JWT.
*
* @param jwt An optional specific JWT you wish to verify, not the one you
* can obtain from {@link #getSession}.
* @param options Various additional options that allow you to customize the
* behavior of this method.
*/
getClaims(jwt?: string, options?: {
/**
* @deprecated Please use options.jwks instead.
*/
keys?: JWK[];
/** If set to `true` the `exp` claim will not be validated against the current time. */
allowExpired?: boolean;
/** If set, this JSON Web Key Set is going to have precedence over the cached value available on the server. */
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

2371
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, processLock, } 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,EAC1B,WAAW,GACZ,MAAM,aAAa,CAAA"}

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

@@ -0,0 +1,36 @@
"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.processLock = 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; } });
Object.defineProperty(exports, "processLock", { enumerable: true, get: function () { return locks_1.processLock; } });
//# 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,qCAKoB;AAJlB,sGAAA,aAAa,OAAA;AACb,yHAAA,gCAAgC,OAAA;AAChC,sGAAA,SAAS,OAAiB;AAC1B,oGAAA,WAAW,OAAA"}

View File

@@ -0,0 +1,75 @@
/**
* 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;
export declare function bytesToBase64URL(bytes: Uint8Array): string;
//# 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;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,UAAU,UAcjD"}

View File

@@ -0,0 +1,270 @@
"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.bytesToBase64URL = 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;
function bytesToBase64URL(bytes) {
const result = [];
const state = { queue: 0, queuedBits: 0 };
const onChar = (char) => {
result.push(char);
};
bytes.forEach((byte) => byteToBase64URL(byte, state, onChar));
// always call with `null` after processing all bytes
byteToBase64URL(null, state, onChar);
return result.join('');
}
exports.bytesToBase64URL = bytesToBase64URL;
//# 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: number;
//# 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,QAAiB,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 = 10 * 60 * 1000; // 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,EAAE,GAAG,EAAE,GAAG,IAAI,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":"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"}

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":"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"}

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,66 @@
import { JwtHeader, JwtPayload, SupportedStorage, User } 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: 'HS256' | 'RS256' | 'ES256'): RsaHashedImportParams | EcKeyImportParams;
export declare function validateUUID(str: string): void;
export declare function userNotAvailableProxy(): User;
/**
* Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)).
* Note: Only works for JSON-safe data.
*/
export declare function deepClone<T>(obj: T): T;
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,IAAI,EAAE,MAAM,SAAS,CAAA;AAEvE,wBAAgB,SAAS,CAAC,SAAS,EAAE,MAAM,UAG1C;AAED,wBAAgB,IAAI,WAMnB;AAED,eAAO,MAAM,SAAS,eAAyE,CAAA;AAO/F;;GAEG;AACH,eAAO,MAAM,oBAAoB,eAmChC,CAAA;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM;;EAsBlD;AAED,aAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,eAAO,MAAM,YAAY,iBAAkB,KAAK,KAAG,KAWlD,CAAA;AAED,eAAO,MAAM,sBAAsB,kBAAmB,OAAO,8BAS5D,CAAA;AAGD,eAAO,MAAM,YAAY,YACd,gBAAgB,OACpB,MAAM,QACL,GAAG,KACR,QAAQ,IAAI,CAEd,CAAA;AAED,eAAO,MAAM,YAAY,YAAmB,gBAAgB,OAAO,MAAM,KAAG,QAAQ,OAAO,CAY1F,CAAA;AAED,eAAO,MAAM,eAAe,YAAmB,gBAAgB,OAAO,MAAM,KAAG,QAAQ,IAAI,CAE1F,CAAA;AAED;;;;GAIG;AACH,qBAAa,QAAQ,CAAC,CAAC,GAAG,GAAG;IAC3B,OAAc,kBAAkB,EAAE,kBAAkB,CAAU;IAE9D,SAAgB,OAAO,EAAG,WAAW,CAAC,CAAC,CAAC,CAAA;IAExC,SAAgB,OAAO,EAAG,CAAC,KAAK,CAAC,EAAE,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,KAAK,IAAI,CAAA;IAE9D,SAAgB,MAAM,EAAG,CAAC,MAAM,CAAC,EAAE,GAAG,KAAK,GAAG,CAAA;;CAW/C;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG;IACxC,MAAM,EAAE,SAAS,CAAA;IACjB,OAAO,EAAE,UAAU,CAAA;IACnB,SAAS,EAAE,UAAU,CAAA;IACrB,GAAG,EAAE;QACH,MAAM,EAAE,MAAM,CAAA;QACd,OAAO,EAAE,MAAM,CAAA;KAChB,CAAA;CACF,CAwBA;AAED;;GAEG;AACH,wBAAsB,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,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,CAC1B,GAAG,EAAE,OAAO,GAAG,OAAO,GAAG,OAAO,GAC/B,qBAAqB,GAAG,iBAAiB,CAgB3C;AAID,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,QAIvC;AAED,wBAAgB,qBAAqB,IAAI,IAAI,CAoC5C;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAEtC"}

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

@@ -0,0 +1,378 @@
"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.deepClone = exports.userNotAvailableProxy = exports.validateUUID = 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;
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
function validateUUID(str) {
if (!UUID_REGEX.test(str)) {
throw new Error('@supabase/auth-js: Expected parameter to be UUID but is not');
}
}
exports.validateUUID = validateUUID;
function userNotAvailableProxy() {
const proxyTarget = {};
return new Proxy(proxyTarget, {
get: (target, prop) => {
if (prop === '__isUserNotAvailableProxy') {
return true;
}
// Preventative check for common problematic symbols during cloning/inspection
// These symbols might be accessed by structuredClone or other internal mechanisms.
if (typeof prop === 'symbol') {
const sProp = prop.toString();
if (sProp === 'Symbol(Symbol.toPrimitive)' ||
sProp === 'Symbol(Symbol.toStringTag)' ||
sProp === 'Symbol(util.inspect.custom)') {
// Node.js util.inspect
return undefined;
}
}
throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${prop}" property of the session object is not supported. Please use getUser() instead.`);
},
set: (_target, prop) => {
throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`);
},
deleteProperty: (_target, prop) => {
throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`);
},
});
}
exports.userNotAvailableProxy = userNotAvailableProxy;
/**
* Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)).
* Note: Only works for JSON-safe data.
*/
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
exports.deepClone = deepClone;
//# sourceMappingURL=helpers.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
import { SupportedStorage } from './types';
/**
* 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":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAE1C;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,GAAE;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;CAAO,GAAG,gBAAgB,CAcjG"}

View File

@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.memoryLocalStorageAdapter = void 0;
/**
* 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":";;;AAEA;;;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":"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"}

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"}

View File

@@ -0,0 +1,160 @@
/**
* A namespaced identifier in the format `${namespace}:${reference}`.
*
* Used by {@link IdentifierArray} and {@link IdentifierRecord}.
*
* @group Identifier
*/
export declare type IdentifierString = `${string}:${string}`;
/**
* A read-only array of namespaced identifiers in the format `${namespace}:${reference}`.
*
* Used by {@link Wallet.chains | Wallet::chains}, {@link WalletAccount.chains | WalletAccount::chains}, and
* {@link WalletAccount.features | WalletAccount::features}.
*
* @group Identifier
*/
export declare type IdentifierArray = readonly IdentifierString[];
/**
* Version of the Wallet Standard implemented by a {@link Wallet}.
*
* Used by {@link Wallet.version | Wallet::version}.
*
* Note that this is _NOT_ a version of the Wallet, but a version of the Wallet Standard itself that the Wallet
* supports.
*
* This may be used by the app to determine compatibility and feature detect.
*
* @group Wallet
*/
export declare type WalletVersion = '1.0.0';
/**
* A data URI containing a base64-encoded SVG, WebP, PNG, or GIF image.
*
* Used by {@link Wallet.icon | Wallet::icon} and {@link WalletAccount.icon | WalletAccount::icon}.
*
* @group Wallet
*/
export declare type WalletIcon = `data:image/${'svg+xml' | 'webp' | 'png' | 'gif'};base64,${string}`;
/**
* Interface of a **WalletAccount**, also referred to as an **Account**.
*
* An account is a _read-only data object_ that is provided from the Wallet to the app, authorizing the app to use it.
*
* The app can use an account to display and query information from a chain.
*
* The app can also act using an account by passing it to {@link Wallet.features | features} of the Wallet.
*
* Wallets may use or extend {@link "@wallet-standard/wallet".ReadonlyWalletAccount} which implements this interface.
*
* @group Wallet
*/
export interface WalletAccount {
/** Address of the account, corresponding with a public key. */
readonly address: string;
/** Public key of the account, corresponding with a secret key to use. */
readonly publicKey: Uint8Array;
/**
* Chains supported by the account.
*
* This must be a subset of the {@link Wallet.chains | chains} of the Wallet.
*/
readonly chains: IdentifierArray;
/**
* Feature names supported by the account.
*
* This must be a subset of the names of {@link Wallet.features | features} of the Wallet.
*/
readonly features: IdentifierArray;
/** Optional user-friendly descriptive label or name for the account. This may be displayed by the app. */
readonly label?: string;
/** Optional user-friendly icon for the account. This may be displayed by the app. */
readonly icon?: WalletIcon;
}
/** Input for signing in. */
export interface SolanaSignInInput {
/**
* Optional EIP-4361 Domain.
* If not provided, the wallet must determine the Domain to include in the message.
*/
readonly domain?: string;
/**
* Optional EIP-4361 Address.
* If not provided, the wallet must determine the Address to include in the message.
*/
readonly address?: string;
/**
* Optional EIP-4361 Statement.
* If not provided, the wallet must not include Statement in the message.
*/
readonly statement?: string;
/**
* Optional EIP-4361 URI.
* If not provided, the wallet must not include URI in the message.
*/
readonly uri?: string;
/**
* Optional EIP-4361 Version.
* If not provided, the wallet must not include Version in the message.
*/
readonly version?: string;
/**
* Optional EIP-4361 Chain ID.
* If not provided, the wallet must not include Chain ID in the message.
*/
readonly chainId?: string;
/**
* Optional EIP-4361 Nonce.
* If not provided, the wallet must not include Nonce in the message.
*/
readonly nonce?: string;
/**
* Optional EIP-4361 Issued At.
* If not provided, the wallet must not include Issued At in the message.
*/
readonly issuedAt?: string;
/**
* Optional EIP-4361 Expiration Time.
* If not provided, the wallet must not include Expiration Time in the message.
*/
readonly expirationTime?: string;
/**
* Optional EIP-4361 Not Before.
* If not provided, the wallet must not include Not Before in the message.
*/
readonly notBefore?: string;
/**
* Optional EIP-4361 Request ID.
* If not provided, the wallet must not include Request ID in the message.
*/
readonly requestId?: string;
/**
* Optional EIP-4361 Resources.
* If not provided, the wallet must not include Resources in the message.
*/
readonly resources?: readonly string[];
}
/** Output of signing in. */
export interface SolanaSignInOutput {
/**
* Account that was signed in.
* The address of the account may be different from the provided input Address.
*/
readonly account: WalletAccount;
/**
* Message bytes that were signed.
* The wallet may prefix or otherwise modify the message before signing it.
*/
readonly signedMessage: Uint8Array;
/**
* Message signature produced.
* If the signature type is provided, the signature must be Ed25519.
*/
readonly signature: Uint8Array;
/**
* Optional type of the message signature produced.
* If not provided, the signature must be Ed25519.
*/
readonly signatureType?: 'ed25519';
}
//# sourceMappingURL=solana.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"solana.d.ts","sourceRoot":"","sources":["../../../src/lib/solana.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AACH,oBAAY,gBAAgB,GAAG,GAAG,MAAM,IAAI,MAAM,EAAE,CAAA;AAEpD;;;;;;;GAOG;AACH,oBAAY,eAAe,GAAG,SAAS,gBAAgB,EAAE,CAAA;AAEzD;;;;;;;;;;;GAWG;AACH,oBAAY,aAAa,GAAG,OAAO,CAAA;AAEnC;;;;;;GAMG;AACH,oBAAY,UAAU,GAAG,cAAc,SAAS,GAAG,MAAM,GAAG,KAAK,GAAG,KAAK,WAAW,MAAM,EAAE,CAAA;AAE5F;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,aAAa;IAC5B,+DAA+D;IAC/D,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IAExB,yEAAyE;IACzE,QAAQ,CAAC,SAAS,EAAE,UAAU,CAAA;IAE9B;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAA;IAEhC;;;;OAIG;IACH,QAAQ,CAAC,QAAQ,EAAE,eAAe,CAAA;IAElC,0GAA0G;IAC1G,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;IAEvB,qFAAqF;IACrF,QAAQ,CAAC,IAAI,CAAC,EAAE,UAAU,CAAA;CAC3B;AAED,4BAA4B;AAC5B,MAAM,WAAW,iBAAiB;IAChC;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAA;IAExB;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;IAEzB;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAA;IAE3B;;;OAGG;IACH,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAA;IAErB;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;IAEzB;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;IAEzB;;;OAGG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;IAEvB;;;OAGG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;IAE1B;;;OAGG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAA;IAEhC;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAA;IAE3B;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAA;IAE3B;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;CACvC;AAED,4BAA4B;AAC5B,MAAM,WAAW,kBAAkB;IACjC;;;OAGG;IACH,QAAQ,CAAC,OAAO,EAAE,aAAa,CAAA;IAE/B;;;OAGG;IACH,QAAQ,CAAC,aAAa,EAAE,UAAU,CAAA;IAElC;;;OAGG;IACH,QAAQ,CAAC,SAAS,EAAE,UAAU,CAAA;IAE9B;;;OAGG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,SAAS,CAAA;CACnC"}

View File

@@ -0,0 +1,4 @@
"use strict";
// types copied over from @solana/wallet-standard-features and @wallet-standard/base so this library doesn't depend on them
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=solana.js.map

View File

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

1088
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,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SIGN_OUT_SCOPES = void 0;
exports.SIGN_OUT_SCOPES = ['global', 'local', 'others'];
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":";;;AA+wCa,QAAA,eAAe,GAAG,CAAC,QAAQ,EAAE,OAAO,EAAE,QAAQ,CAAU,CAAA"}

View File

@@ -0,0 +1,2 @@
export declare const version = "2.71.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.71.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"}

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