wip:milestone 0 fixes
Some checks failed
CI/CD Pipeline / unit-tests (push) Failing after 1m16s
CI/CD Pipeline / integration-tests (push) Failing after 2m32s
CI/CD Pipeline / lint (push) Successful in 5m22s
CI/CD Pipeline / e2e-tests (push) Has been skipped
CI/CD Pipeline / build (push) Has been skipped

This commit is contained in:
2026-03-15 12:35:42 +02:00
parent 6708cf28a7
commit cffdf8af86
61266 changed files with 4511646 additions and 1938 deletions

View File

@@ -0,0 +1,85 @@
//#region src/cors.ts
/**
* Canonical CORS configuration for Supabase Edge Functions
*
* This module exports CORS headers that stay synchronized with the Supabase SDK.
* When new headers are added to the SDK, they are automatically included here,
* preventing CORS errors in Edge Functions.
*
* @example Basic usage
* ```typescript
* import { corsHeaders } from '@supabase/supabase-js/cors'
*
* Deno.serve(async (req) => {
* if (req.method === 'OPTIONS') {
* return new Response('ok', { headers: corsHeaders })
* }
*
* return new Response(
* JSON.stringify({ data: 'Hello' }),
* { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
* )
* })
* ```
*
* @module cors
*/
/**
* All custom headers sent by the Supabase SDK.
* These headers need to be included in CORS configuration to prevent preflight failures.
*
* Headers:
* - authorization: Bearer token for authentication
* - x-client-info: Library version information
* - apikey: Project API key
* - content-type: Standard HTTP content type
*/
const SUPABASE_HEADERS = [
"authorization",
"x-client-info",
"apikey",
"content-type"
].join(", ");
/**
* All HTTP methods used by the Supabase SDK
*/
const SUPABASE_METHODS = [
"GET",
"POST",
"PUT",
"PATCH",
"DELETE",
"OPTIONS"
].join(", ");
/**
* Default CORS headers for Supabase Edge Functions.
*
* Includes all headers sent by Supabase client libraries and allows all standard HTTP methods.
* Use this for simple CORS configurations with wildcard origin.
*
* @example
* ```typescript
* import { corsHeaders } from '@supabase/supabase-js/cors'
*
* Deno.serve(async (req) => {
* if (req.method === 'OPTIONS') {
* return new Response('ok', { headers: corsHeaders })
* }
*
* return new Response(
* JSON.stringify({ data: 'Hello' }),
* { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
* )
* })
* ```
*/
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": SUPABASE_HEADERS,
"Access-Control-Allow-Methods": SUPABASE_METHODS
};
//#endregion
exports.corsHeaders = corsHeaders;
//# sourceMappingURL=cors.cjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"cors.cjs","names":["corsHeaders: CorsHeaders"],"sources":["../src/cors.ts"],"sourcesContent":["/**\n * Canonical CORS configuration for Supabase Edge Functions\n *\n * This module exports CORS headers that stay synchronized with the Supabase SDK.\n * When new headers are added to the SDK, they are automatically included here,\n * preventing CORS errors in Edge Functions.\n *\n * @example Basic usage\n * ```typescript\n * import { corsHeaders } from '@supabase/supabase-js/cors'\n *\n * Deno.serve(async (req) => {\n * if (req.method === 'OPTIONS') {\n * return new Response('ok', { headers: corsHeaders })\n * }\n *\n * return new Response(\n * JSON.stringify({ data: 'Hello' }),\n * { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }\n * )\n * })\n * ```\n *\n * @module cors\n */\n\n/**\n * All custom headers sent by the Supabase SDK.\n * These headers need to be included in CORS configuration to prevent preflight failures.\n *\n * Headers:\n * - authorization: Bearer token for authentication\n * - x-client-info: Library version information\n * - apikey: Project API key\n * - content-type: Standard HTTP content type\n */\nconst SUPABASE_HEADERS = ['authorization', 'x-client-info', 'apikey', 'content-type'].join(', ')\n\n/**\n * All HTTP methods used by the Supabase SDK\n */\nconst SUPABASE_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'].join(', ')\n\n/**\n * Type representing CORS headers as a record of header names to values\n */\nexport type CorsHeaders = Record<string, string>\n\n/**\n * Default CORS headers for Supabase Edge Functions.\n *\n * Includes all headers sent by Supabase client libraries and allows all standard HTTP methods.\n * Use this for simple CORS configurations with wildcard origin.\n *\n * @example\n * ```typescript\n * import { corsHeaders } from '@supabase/supabase-js/cors'\n *\n * Deno.serve(async (req) => {\n * if (req.method === 'OPTIONS') {\n * return new Response('ok', { headers: corsHeaders })\n * }\n *\n * return new Response(\n * JSON.stringify({ data: 'Hello' }),\n * { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }\n * )\n * })\n * ```\n */\nexport const corsHeaders: CorsHeaders = {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Headers': SUPABASE_HEADERS,\n 'Access-Control-Allow-Methods': SUPABASE_METHODS,\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,mBAAmB;CAAC;CAAiB;CAAiB;CAAU;CAAe,CAAC,KAAK,KAAK;;;;AAKhG,MAAM,mBAAmB;CAAC;CAAO;CAAQ;CAAO;CAAS;CAAU;CAAU,CAAC,KAAK,KAAK;;;;;;;;;;;;;;;;;;;;;;;AA6BxF,MAAaA,cAA2B;CACtC,+BAA+B;CAC/B,gCAAgC;CAChC,gCAAgC;CACjC"}

View File

@@ -0,0 +1,56 @@
//#region src/cors.d.ts
/**
* Canonical CORS configuration for Supabase Edge Functions
*
* This module exports CORS headers that stay synchronized with the Supabase SDK.
* When new headers are added to the SDK, they are automatically included here,
* preventing CORS errors in Edge Functions.
*
* @example Basic usage
* ```typescript
* import { corsHeaders } from '@supabase/supabase-js/cors'
*
* Deno.serve(async (req) => {
* if (req.method === 'OPTIONS') {
* return new Response('ok', { headers: corsHeaders })
* }
*
* return new Response(
* JSON.stringify({ data: 'Hello' }),
* { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
* )
* })
* ```
*
* @module cors
*/
/**
* Type representing CORS headers as a record of header names to values
*/
type CorsHeaders = Record<string, string>;
/**
* Default CORS headers for Supabase Edge Functions.
*
* Includes all headers sent by Supabase client libraries and allows all standard HTTP methods.
* Use this for simple CORS configurations with wildcard origin.
*
* @example
* ```typescript
* import { corsHeaders } from '@supabase/supabase-js/cors'
*
* Deno.serve(async (req) => {
* if (req.method === 'OPTIONS') {
* return new Response('ok', { headers: corsHeaders })
* }
*
* return new Response(
* JSON.stringify({ data: 'Hello' }),
* { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
* )
* })
* ```
*/
declare const corsHeaders: CorsHeaders;
//#endregion
export { CorsHeaders, corsHeaders };
//# sourceMappingURL=cors.d.cts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"cors.d.cts","names":[],"sources":["../src/cors.ts"],"sourcesContent":[],"mappings":";;AA8CA;AAwBA;;;;;;;;;;;;;;;;;;;;;;;;;;KAxBY,WAAA,GAAc;;;;;;;;;;;;;;;;;;;;;;;cAwBb,aAAa"}

View File

@@ -0,0 +1,56 @@
//#region src/cors.d.ts
/**
* Canonical CORS configuration for Supabase Edge Functions
*
* This module exports CORS headers that stay synchronized with the Supabase SDK.
* When new headers are added to the SDK, they are automatically included here,
* preventing CORS errors in Edge Functions.
*
* @example Basic usage
* ```typescript
* import { corsHeaders } from '@supabase/supabase-js/cors'
*
* Deno.serve(async (req) => {
* if (req.method === 'OPTIONS') {
* return new Response('ok', { headers: corsHeaders })
* }
*
* return new Response(
* JSON.stringify({ data: 'Hello' }),
* { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
* )
* })
* ```
*
* @module cors
*/
/**
* Type representing CORS headers as a record of header names to values
*/
type CorsHeaders = Record<string, string>;
/**
* Default CORS headers for Supabase Edge Functions.
*
* Includes all headers sent by Supabase client libraries and allows all standard HTTP methods.
* Use this for simple CORS configurations with wildcard origin.
*
* @example
* ```typescript
* import { corsHeaders } from '@supabase/supabase-js/cors'
*
* Deno.serve(async (req) => {
* if (req.method === 'OPTIONS') {
* return new Response('ok', { headers: corsHeaders })
* }
*
* return new Response(
* JSON.stringify({ data: 'Hello' }),
* { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
* )
* })
* ```
*/
declare const corsHeaders: CorsHeaders;
//#endregion
export { CorsHeaders, corsHeaders };
//# sourceMappingURL=cors.d.mts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"cors.d.mts","names":[],"sources":["../src/cors.ts"],"sourcesContent":[],"mappings":";;AA8CA;AAwBA;;;;;;;;;;;;;;;;;;;;;;;;;;KAxBY,WAAA,GAAc;;;;;;;;;;;;;;;;;;;;;;;cAwBb,aAAa"}

View File

@@ -0,0 +1,84 @@
//#region src/cors.ts
/**
* Canonical CORS configuration for Supabase Edge Functions
*
* This module exports CORS headers that stay synchronized with the Supabase SDK.
* When new headers are added to the SDK, they are automatically included here,
* preventing CORS errors in Edge Functions.
*
* @example Basic usage
* ```typescript
* import { corsHeaders } from '@supabase/supabase-js/cors'
*
* Deno.serve(async (req) => {
* if (req.method === 'OPTIONS') {
* return new Response('ok', { headers: corsHeaders })
* }
*
* return new Response(
* JSON.stringify({ data: 'Hello' }),
* { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
* )
* })
* ```
*
* @module cors
*/
/**
* All custom headers sent by the Supabase SDK.
* These headers need to be included in CORS configuration to prevent preflight failures.
*
* Headers:
* - authorization: Bearer token for authentication
* - x-client-info: Library version information
* - apikey: Project API key
* - content-type: Standard HTTP content type
*/
const SUPABASE_HEADERS = [
"authorization",
"x-client-info",
"apikey",
"content-type"
].join(", ");
/**
* All HTTP methods used by the Supabase SDK
*/
const SUPABASE_METHODS = [
"GET",
"POST",
"PUT",
"PATCH",
"DELETE",
"OPTIONS"
].join(", ");
/**
* Default CORS headers for Supabase Edge Functions.
*
* Includes all headers sent by Supabase client libraries and allows all standard HTTP methods.
* Use this for simple CORS configurations with wildcard origin.
*
* @example
* ```typescript
* import { corsHeaders } from '@supabase/supabase-js/cors'
*
* Deno.serve(async (req) => {
* if (req.method === 'OPTIONS') {
* return new Response('ok', { headers: corsHeaders })
* }
*
* return new Response(
* JSON.stringify({ data: 'Hello' }),
* { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
* )
* })
* ```
*/
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": SUPABASE_HEADERS,
"Access-Control-Allow-Methods": SUPABASE_METHODS
};
//#endregion
export { corsHeaders };
//# sourceMappingURL=cors.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"cors.mjs","names":["corsHeaders: CorsHeaders"],"sources":["../src/cors.ts"],"sourcesContent":["/**\n * Canonical CORS configuration for Supabase Edge Functions\n *\n * This module exports CORS headers that stay synchronized with the Supabase SDK.\n * When new headers are added to the SDK, they are automatically included here,\n * preventing CORS errors in Edge Functions.\n *\n * @example Basic usage\n * ```typescript\n * import { corsHeaders } from '@supabase/supabase-js/cors'\n *\n * Deno.serve(async (req) => {\n * if (req.method === 'OPTIONS') {\n * return new Response('ok', { headers: corsHeaders })\n * }\n *\n * return new Response(\n * JSON.stringify({ data: 'Hello' }),\n * { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }\n * )\n * })\n * ```\n *\n * @module cors\n */\n\n/**\n * All custom headers sent by the Supabase SDK.\n * These headers need to be included in CORS configuration to prevent preflight failures.\n *\n * Headers:\n * - authorization: Bearer token for authentication\n * - x-client-info: Library version information\n * - apikey: Project API key\n * - content-type: Standard HTTP content type\n */\nconst SUPABASE_HEADERS = ['authorization', 'x-client-info', 'apikey', 'content-type'].join(', ')\n\n/**\n * All HTTP methods used by the Supabase SDK\n */\nconst SUPABASE_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'].join(', ')\n\n/**\n * Type representing CORS headers as a record of header names to values\n */\nexport type CorsHeaders = Record<string, string>\n\n/**\n * Default CORS headers for Supabase Edge Functions.\n *\n * Includes all headers sent by Supabase client libraries and allows all standard HTTP methods.\n * Use this for simple CORS configurations with wildcard origin.\n *\n * @example\n * ```typescript\n * import { corsHeaders } from '@supabase/supabase-js/cors'\n *\n * Deno.serve(async (req) => {\n * if (req.method === 'OPTIONS') {\n * return new Response('ok', { headers: corsHeaders })\n * }\n *\n * return new Response(\n * JSON.stringify({ data: 'Hello' }),\n * { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }\n * )\n * })\n * ```\n */\nexport const corsHeaders: CorsHeaders = {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Headers': SUPABASE_HEADERS,\n 'Access-Control-Allow-Methods': SUPABASE_METHODS,\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,mBAAmB;CAAC;CAAiB;CAAiB;CAAU;CAAe,CAAC,KAAK,KAAK;;;;AAKhG,MAAM,mBAAmB;CAAC;CAAO;CAAQ;CAAO;CAAS;CAAU;CAAU,CAAC,KAAK,KAAK;;;;;;;;;;;;;;;;;;;;;;;AA6BxF,MAAaA,cAA2B;CACtC,+BAA+B;CAC/B,gCAAgC;CAChC,gCAAgC;CACjC"}

View File

@@ -0,0 +1,622 @@
let __supabase_functions_js = require("@supabase/functions-js");
let __supabase_postgrest_js = require("@supabase/postgrest-js");
let __supabase_realtime_js = require("@supabase/realtime-js");
let __supabase_storage_js = require("@supabase/storage-js");
let __supabase_auth_js = require("@supabase/auth-js");
//#region src/lib/version.ts
const version = "2.99.1";
//#endregion
//#region src/lib/constants.ts
let JS_ENV = "";
if (typeof Deno !== "undefined") JS_ENV = "deno";
else if (typeof document !== "undefined") JS_ENV = "web";
else if (typeof navigator !== "undefined" && navigator.product === "ReactNative") JS_ENV = "react-native";
else JS_ENV = "node";
const DEFAULT_HEADERS = { "X-Client-Info": `supabase-js-${JS_ENV}/${version}` };
const DEFAULT_GLOBAL_OPTIONS = { headers: DEFAULT_HEADERS };
const DEFAULT_DB_OPTIONS = { schema: "public" };
const DEFAULT_AUTH_OPTIONS = {
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true,
flowType: "implicit"
};
const DEFAULT_REALTIME_OPTIONS = {};
//#endregion
//#region \0@oxc-project+runtime@0.101.0/helpers/typeof.js
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$1) {
return typeof o$1;
} : function(o$1) {
return o$1 && "function" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1;
}, _typeof(o);
}
//#endregion
//#region \0@oxc-project+runtime@0.101.0/helpers/toPrimitive.js
function toPrimitive(t, r) {
if ("object" != _typeof(t) || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r || "default");
if ("object" != _typeof(i)) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
//#endregion
//#region \0@oxc-project+runtime@0.101.0/helpers/toPropertyKey.js
function toPropertyKey(t) {
var i = toPrimitive(t, "string");
return "symbol" == _typeof(i) ? i : i + "";
}
//#endregion
//#region \0@oxc-project+runtime@0.101.0/helpers/defineProperty.js
function _defineProperty(e, r, t) {
return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
value: t,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[r] = t, e;
}
//#endregion
//#region \0@oxc-project+runtime@0.101.0/helpers/objectSpread2.js
function ownKeys(e, r) {
var t = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var o = Object.getOwnPropertySymbols(e);
r && (o = o.filter(function(r$1) {
return Object.getOwnPropertyDescriptor(e, r$1).enumerable;
})), t.push.apply(t, o);
}
return t;
}
function _objectSpread2(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys(Object(t), !0).forEach(function(r$1) {
_defineProperty(e, r$1, t[r$1]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r$1) {
Object.defineProperty(e, r$1, Object.getOwnPropertyDescriptor(t, r$1));
});
}
return e;
}
//#endregion
//#region src/lib/fetch.ts
const resolveFetch = (customFetch) => {
if (customFetch) return (...args) => customFetch(...args);
return (...args) => fetch(...args);
};
const resolveHeadersConstructor = () => {
return Headers;
};
const fetchWithAuth = (supabaseKey, getAccessToken, customFetch) => {
const fetch$1 = resolveFetch(customFetch);
const HeadersConstructor = resolveHeadersConstructor();
return async (input, init) => {
var _await$getAccessToken;
const accessToken = (_await$getAccessToken = await getAccessToken()) !== null && _await$getAccessToken !== void 0 ? _await$getAccessToken : supabaseKey;
let headers = new HeadersConstructor(init === null || init === void 0 ? void 0 : init.headers);
if (!headers.has("apikey")) headers.set("apikey", supabaseKey);
if (!headers.has("Authorization")) headers.set("Authorization", `Bearer ${accessToken}`);
return fetch$1(input, _objectSpread2(_objectSpread2({}, init), {}, { headers }));
};
};
//#endregion
//#region src/lib/helpers.ts
function ensureTrailingSlash(url) {
return url.endsWith("/") ? url : url + "/";
}
function applySettingDefaults(options, defaults) {
var _DEFAULT_GLOBAL_OPTIO, _globalOptions$header;
const { db: dbOptions, auth: authOptions, realtime: realtimeOptions, global: globalOptions } = options;
const { db: DEFAULT_DB_OPTIONS$1, auth: DEFAULT_AUTH_OPTIONS$1, realtime: DEFAULT_REALTIME_OPTIONS$1, global: DEFAULT_GLOBAL_OPTIONS$1 } = defaults;
const result = {
db: _objectSpread2(_objectSpread2({}, DEFAULT_DB_OPTIONS$1), dbOptions),
auth: _objectSpread2(_objectSpread2({}, DEFAULT_AUTH_OPTIONS$1), authOptions),
realtime: _objectSpread2(_objectSpread2({}, DEFAULT_REALTIME_OPTIONS$1), realtimeOptions),
storage: {},
global: _objectSpread2(_objectSpread2(_objectSpread2({}, DEFAULT_GLOBAL_OPTIONS$1), globalOptions), {}, { headers: _objectSpread2(_objectSpread2({}, (_DEFAULT_GLOBAL_OPTIO = DEFAULT_GLOBAL_OPTIONS$1 === null || DEFAULT_GLOBAL_OPTIONS$1 === void 0 ? void 0 : DEFAULT_GLOBAL_OPTIONS$1.headers) !== null && _DEFAULT_GLOBAL_OPTIO !== void 0 ? _DEFAULT_GLOBAL_OPTIO : {}), (_globalOptions$header = globalOptions === null || globalOptions === void 0 ? void 0 : globalOptions.headers) !== null && _globalOptions$header !== void 0 ? _globalOptions$header : {}) }),
accessToken: async () => ""
};
if (options.accessToken) result.accessToken = options.accessToken;
else delete result.accessToken;
return result;
}
/**
* Validates a Supabase client URL
*
* @param {string} supabaseUrl - The Supabase client URL string.
* @returns {URL} - The validated base URL.
* @throws {Error}
*/
function validateSupabaseUrl(supabaseUrl) {
const trimmedUrl = supabaseUrl === null || supabaseUrl === void 0 ? void 0 : supabaseUrl.trim();
if (!trimmedUrl) throw new Error("supabaseUrl is required.");
if (!trimmedUrl.match(/^https?:\/\//i)) throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");
try {
return new URL(ensureTrailingSlash(trimmedUrl));
} catch (_unused) {
throw Error("Invalid supabaseUrl: Provided URL is malformed.");
}
}
//#endregion
//#region src/lib/SupabaseAuthClient.ts
var SupabaseAuthClient = class extends __supabase_auth_js.AuthClient {
constructor(options) {
super(options);
}
};
//#endregion
//#region src/SupabaseClient.ts
/**
* Supabase Client.
*
* An isomorphic Javascript client for interacting with Postgres.
*/
var SupabaseClient = class {
/**
* Create a new client for use in the browser.
*
* @category Initializing
*
* @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard.
* @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard.
* @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase.
* @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring.
* @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage.
* @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user.
* @param options.realtime Options passed along to realtime-js constructor.
* @param options.storage Options passed along to the storage-js constructor.
* @param options.global.fetch A custom fetch implementation.
* @param options.global.headers Any additional headers to send with each network request.
*
* @example Creating a client
* ```js
* import { createClient } from '@supabase/supabase-js'
*
* // Create a single supabase client for interacting with your database
* const supabase = createClient('https://xyzcompany.supabase.co', 'publishable-or-anon-key')
* ```
*
* @example With a custom domain
* ```js
* import { createClient } from '@supabase/supabase-js'
*
* // Use a custom domain as the supabase URL
* const supabase = createClient('https://my-custom-domain.com', 'publishable-or-anon-key')
* ```
*
* @example With additional parameters
* ```js
* import { createClient } from '@supabase/supabase-js'
*
* const options = {
* db: {
* schema: 'public',
* },
* auth: {
* autoRefreshToken: true,
* persistSession: true,
* detectSessionInUrl: true
* },
* global: {
* headers: { 'x-my-custom-header': 'my-app-name' },
* },
* }
* const supabase = createClient("https://xyzcompany.supabase.co", "publishable-or-anon-key", options)
* ```
*
* @exampleDescription With custom schemas
* By default the API server points to the `public` schema. You can enable other database schemas within the Dashboard.
* Go to [Settings > API > Exposed schemas](/dashboard/project/_/settings/api) and add the schema which you want to expose to the API.
*
* Note: each client connection can only access a single schema, so the code above can access the `other_schema` schema but cannot access the `public` schema.
*
* @example With custom schemas
* ```js
* import { createClient } from '@supabase/supabase-js'
*
* const supabase = createClient('https://xyzcompany.supabase.co', 'publishable-or-anon-key', {
* // Provide a custom schema. Defaults to "public".
* db: { schema: 'other_schema' }
* })
* ```
*
* @exampleDescription Custom fetch implementation
* `supabase-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).
*
* @example Custom fetch implementation
* ```js
* import { createClient } from '@supabase/supabase-js'
*
* const supabase = createClient('https://xyzcompany.supabase.co', 'publishable-or-anon-key', {
* global: { fetch: fetch.bind(globalThis) }
* })
* ```
*
* @exampleDescription React Native options with AsyncStorage
* For React Native we recommend using `AsyncStorage` as the storage implementation for Supabase Auth.
*
* @example React Native options with AsyncStorage
* ```js
* import 'react-native-url-polyfill/auto'
* import { createClient } from '@supabase/supabase-js'
* import AsyncStorage from "@react-native-async-storage/async-storage";
*
* const supabase = createClient("https://xyzcompany.supabase.co", "publishable-or-anon-key", {
* auth: {
* storage: AsyncStorage,
* autoRefreshToken: true,
* persistSession: true,
* detectSessionInUrl: false,
* },
* });
* ```
*
* @exampleDescription React Native options with Expo SecureStore
* If you wish to encrypt the user's session information, you can use `aes-js` and store the encryption key in Expo SecureStore.
* The `aes-js` library, a reputable JavaScript-only implementation of the AES encryption algorithm in CTR mode.
* A new 256-bit encryption key is generated using the `react-native-get-random-values` library.
* This key is stored inside Expo's SecureStore, while the value is encrypted and placed inside AsyncStorage.
*
* Please make sure that:
* - You keep the `expo-secure-store`, `aes-js` and `react-native-get-random-values` libraries up-to-date.
* - Choose the correct [`SecureStoreOptions`](https://docs.expo.dev/versions/latest/sdk/securestore/#securestoreoptions) for your app's needs.
* E.g. [`SecureStore.WHEN_UNLOCKED`](https://docs.expo.dev/versions/latest/sdk/securestore/#securestorewhen_unlocked) regulates when the data can be accessed.
* - Carefully consider optimizations or other modifications to the above example, as those can lead to introducing subtle security vulnerabilities.
*
* @example React Native options with Expo SecureStore
* ```ts
* import 'react-native-url-polyfill/auto'
* import { createClient } from '@supabase/supabase-js'
* import AsyncStorage from '@react-native-async-storage/async-storage';
* import * as SecureStore from 'expo-secure-store';
* import * as aesjs from 'aes-js';
* import 'react-native-get-random-values';
*
* // As Expo's SecureStore does not support values larger than 2048
* // bytes, an AES-256 key is generated and stored in SecureStore, while
* // it is used to encrypt/decrypt values stored in AsyncStorage.
* class LargeSecureStore {
* private async _encrypt(key: string, value: string) {
* const encryptionKey = crypto.getRandomValues(new Uint8Array(256 / 8));
*
* const cipher = new aesjs.ModeOfOperation.ctr(encryptionKey, new aesjs.Counter(1));
* const encryptedBytes = cipher.encrypt(aesjs.utils.utf8.toBytes(value));
*
* await SecureStore.setItemAsync(key, aesjs.utils.hex.fromBytes(encryptionKey));
*
* return aesjs.utils.hex.fromBytes(encryptedBytes);
* }
*
* private async _decrypt(key: string, value: string) {
* const encryptionKeyHex = await SecureStore.getItemAsync(key);
* if (!encryptionKeyHex) {
* return encryptionKeyHex;
* }
*
* const cipher = new aesjs.ModeOfOperation.ctr(aesjs.utils.hex.toBytes(encryptionKeyHex), new aesjs.Counter(1));
* const decryptedBytes = cipher.decrypt(aesjs.utils.hex.toBytes(value));
*
* return aesjs.utils.utf8.fromBytes(decryptedBytes);
* }
*
* async getItem(key: string) {
* const encrypted = await AsyncStorage.getItem(key);
* if (!encrypted) { return encrypted; }
*
* return await this._decrypt(key, encrypted);
* }
*
* async removeItem(key: string) {
* await AsyncStorage.removeItem(key);
* await SecureStore.deleteItemAsync(key);
* }
*
* async setItem(key: string, value: string) {
* const encrypted = await this._encrypt(key, value);
*
* await AsyncStorage.setItem(key, encrypted);
* }
* }
*
* const supabase = createClient("https://xyzcompany.supabase.co", "publishable-or-anon-key", {
* auth: {
* storage: new LargeSecureStore(),
* autoRefreshToken: true,
* persistSession: true,
* detectSessionInUrl: false,
* },
* });
* ```
*
* @example With a database query
* ```ts
* import { createClient } from '@supabase/supabase-js'
*
* const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key')
*
* const { data } = await supabase.from('profiles').select('*')
* ```
*/
constructor(supabaseUrl, supabaseKey, options) {
var _settings$auth$storag, _settings$global$head;
this.supabaseUrl = supabaseUrl;
this.supabaseKey = supabaseKey;
const baseUrl = validateSupabaseUrl(supabaseUrl);
if (!supabaseKey) throw new Error("supabaseKey is required.");
this.realtimeUrl = new URL("realtime/v1", baseUrl);
this.realtimeUrl.protocol = this.realtimeUrl.protocol.replace("http", "ws");
this.authUrl = new URL("auth/v1", baseUrl);
this.storageUrl = new URL("storage/v1", baseUrl);
this.functionsUrl = new URL("functions/v1", baseUrl);
const defaultStorageKey = `sb-${baseUrl.hostname.split(".")[0]}-auth-token`;
const DEFAULTS = {
db: DEFAULT_DB_OPTIONS,
realtime: DEFAULT_REALTIME_OPTIONS,
auth: _objectSpread2(_objectSpread2({}, DEFAULT_AUTH_OPTIONS), {}, { storageKey: defaultStorageKey }),
global: DEFAULT_GLOBAL_OPTIONS
};
const settings = applySettingDefaults(options !== null && options !== void 0 ? options : {}, DEFAULTS);
this.storageKey = (_settings$auth$storag = settings.auth.storageKey) !== null && _settings$auth$storag !== void 0 ? _settings$auth$storag : "";
this.headers = (_settings$global$head = settings.global.headers) !== null && _settings$global$head !== void 0 ? _settings$global$head : {};
if (!settings.accessToken) {
var _settings$auth;
this.auth = this._initSupabaseAuthClient((_settings$auth = settings.auth) !== null && _settings$auth !== void 0 ? _settings$auth : {}, this.headers, settings.global.fetch);
} else {
this.accessToken = settings.accessToken;
this.auth = new Proxy({}, { get: (_, prop) => {
throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(prop)} is not possible`);
} });
}
this.fetch = fetchWithAuth(supabaseKey, this._getAccessToken.bind(this), settings.global.fetch);
this.realtime = this._initRealtimeClient(_objectSpread2({
headers: this.headers,
accessToken: this._getAccessToken.bind(this)
}, settings.realtime));
if (this.accessToken) Promise.resolve(this.accessToken()).then((token) => this.realtime.setAuth(token)).catch((e) => console.warn("Failed to set initial Realtime auth token:", e));
this.rest = new __supabase_postgrest_js.PostgrestClient(new URL("rest/v1", baseUrl).href, {
headers: this.headers,
schema: settings.db.schema,
fetch: this.fetch,
timeout: settings.db.timeout,
urlLengthLimit: settings.db.urlLengthLimit
});
this.storage = new __supabase_storage_js.StorageClient(this.storageUrl.href, this.headers, this.fetch, options === null || options === void 0 ? void 0 : options.storage);
if (!settings.accessToken) this._listenForAuthEvents();
}
/**
* Supabase Functions allows you to deploy and invoke edge functions.
*/
get functions() {
return new __supabase_functions_js.FunctionsClient(this.functionsUrl.href, {
headers: this.headers,
customFetch: this.fetch
});
}
/**
* Perform a query on a table or a view.
*
* @param relation - The table or view name to query
*/
from(relation) {
return this.rest.from(relation);
}
/**
* Select a schema to query or perform an function (rpc) call.
*
* The schema needs to be on the list of exposed schemas inside Supabase.
*
* @param schema - The schema to query
*/
schema(schema) {
return this.rest.schema(schema);
}
/**
* Perform a function call.
*
* @param fn - The function name to call
* @param args - The arguments to pass to the function call
* @param options - Named parameters
* @param options.head - When set to `true`, `data` will not be returned.
* Useful if you only need the count.
* @param options.get - When set to `true`, the function will be called with
* read-only access mode.
* @param options.count - Count algorithm to use to count rows returned by the
* function. Only applicable for [set-returning
* functions](https://www.postgresql.org/docs/current/functions-srf.html).
*
* `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the
* hood.
*
* `"planned"`: Approximated but fast count algorithm. Uses the Postgres
* statistics under the hood.
*
* `"estimated"`: Uses exact count for low numbers and planned count for high
* numbers.
*/
rpc(fn, args = {}, options = {
head: false,
get: false,
count: void 0
}) {
return this.rest.rpc(fn, args, options);
}
/**
* Creates a Realtime channel with Broadcast, Presence, and Postgres Changes.
*
* @param {string} name - The name of the Realtime channel.
* @param {Object} opts - The options to pass to the Realtime channel.
*
*/
channel(name, opts = { config: {} }) {
return this.realtime.channel(name, opts);
}
/**
* Returns all Realtime channels.
*/
getChannels() {
return this.realtime.getChannels();
}
/**
* Unsubscribes and removes Realtime channel from Realtime client.
*
* @param {RealtimeChannel} channel - The name of the Realtime channel.
*
*/
removeChannel(channel) {
return this.realtime.removeChannel(channel);
}
/**
* Unsubscribes and removes all Realtime channels from Realtime client.
*/
removeAllChannels() {
return this.realtime.removeAllChannels();
}
async _getAccessToken() {
var _this = this;
var _data$session$access_, _data$session;
if (_this.accessToken) return await _this.accessToken();
const { data } = await _this.auth.getSession();
return (_data$session$access_ = (_data$session = data.session) === null || _data$session === void 0 ? void 0 : _data$session.access_token) !== null && _data$session$access_ !== void 0 ? _data$session$access_ : _this.supabaseKey;
}
_initSupabaseAuthClient({ autoRefreshToken, persistSession, detectSessionInUrl, storage, userStorage, storageKey, flowType, lock, debug, throwOnError }, headers, fetch$1) {
const authHeaders = {
Authorization: `Bearer ${this.supabaseKey}`,
apikey: `${this.supabaseKey}`
};
return new SupabaseAuthClient({
url: this.authUrl.href,
headers: _objectSpread2(_objectSpread2({}, authHeaders), headers),
storageKey,
autoRefreshToken,
persistSession,
detectSessionInUrl,
storage,
userStorage,
flowType,
lock,
debug,
throwOnError,
fetch: fetch$1,
hasCustomAuthorizationHeader: Object.keys(this.headers).some((key) => key.toLowerCase() === "authorization")
});
}
_initRealtimeClient(options) {
return new __supabase_realtime_js.RealtimeClient(this.realtimeUrl.href, _objectSpread2(_objectSpread2({}, options), {}, { params: _objectSpread2(_objectSpread2({}, { apikey: this.supabaseKey }), options === null || options === void 0 ? void 0 : options.params) }));
}
_listenForAuthEvents() {
return this.auth.onAuthStateChange((event, session) => {
this._handleTokenChanged(event, "CLIENT", session === null || session === void 0 ? void 0 : session.access_token);
});
}
_handleTokenChanged(event, source, token) {
if ((event === "TOKEN_REFRESHED" || event === "SIGNED_IN") && this.changedAccessToken !== token) {
this.changedAccessToken = token;
this.realtime.setAuth(token);
} else if (event === "SIGNED_OUT") {
this.realtime.setAuth();
if (source == "STORAGE") this.auth.signOut();
this.changedAccessToken = void 0;
}
}
};
//#endregion
//#region src/index.ts
/**
* Creates a new Supabase Client.
*
* @example
* ```ts
* import { createClient } from '@supabase/supabase-js'
*
* const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key')
* const { data, error } = await supabase.from('profiles').select('*')
* ```
*/
const createClient = (supabaseUrl, supabaseKey, options) => {
return new SupabaseClient(supabaseUrl, supabaseKey, options);
};
function shouldShowDeprecationWarning() {
if (typeof window !== "undefined") return false;
const _process = globalThis["process"];
if (!_process) return false;
const processVersion = _process["version"];
if (processVersion === void 0 || processVersion === null) return false;
const versionMatch = processVersion.match(/^v(\d+)\./);
if (!versionMatch) return false;
return parseInt(versionMatch[1], 10) <= 18;
}
if (shouldShowDeprecationWarning()) console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");
//#endregion
Object.defineProperty(exports, 'FunctionRegion', {
enumerable: true,
get: function () {
return __supabase_functions_js.FunctionRegion;
}
});
Object.defineProperty(exports, 'FunctionsError', {
enumerable: true,
get: function () {
return __supabase_functions_js.FunctionsError;
}
});
Object.defineProperty(exports, 'FunctionsFetchError', {
enumerable: true,
get: function () {
return __supabase_functions_js.FunctionsFetchError;
}
});
Object.defineProperty(exports, 'FunctionsHttpError', {
enumerable: true,
get: function () {
return __supabase_functions_js.FunctionsHttpError;
}
});
Object.defineProperty(exports, 'FunctionsRelayError', {
enumerable: true,
get: function () {
return __supabase_functions_js.FunctionsRelayError;
}
});
Object.defineProperty(exports, 'PostgrestError', {
enumerable: true,
get: function () {
return __supabase_postgrest_js.PostgrestError;
}
});
exports.SupabaseClient = SupabaseClient;
exports.createClient = createClient;
Object.keys(__supabase_auth_js).forEach(function (k) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
enumerable: true,
get: function () { return __supabase_auth_js[k]; }
});
});
Object.keys(__supabase_realtime_js).forEach(function (k) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
enumerable: true,
get: function () { return __supabase_realtime_js[k]; }
});
});
//# sourceMappingURL=index.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,564 @@
import { FunctionInvokeOptions, FunctionRegion, FunctionsClient, FunctionsError, FunctionsFetchError, FunctionsHttpError, FunctionsRelayError } from "@supabase/functions-js";
import { PostgrestClient, PostgrestError, PostgrestError as PostgrestError$1, PostgrestFilterBuilder, PostgrestMaybeSingleResponse, PostgrestQueryBuilder, PostgrestResponse, PostgrestSingleResponse } from "@supabase/postgrest-js";
import { RealtimeChannel, RealtimeChannelOptions, RealtimeClient, RealtimeClientOptions } from "@supabase/realtime-js";
import { StorageClient, StorageClientOptions } from "@supabase/storage-js";
import { AuthClient, GoTrueClientOptions, Session as AuthSession, User as AuthUser } from "@supabase/auth-js";
export * from "@supabase/realtime-js";
export * from "@supabase/auth-js";
//#region src/lib/rest/types/common/common.d.ts
type GenericRelationship = {
foreignKeyName: string;
columns: string[];
isOneToOne?: boolean;
referencedRelation: string;
referencedColumns: string[];
};
type GenericTable = {
Row: Record<string, unknown>;
Insert: Record<string, unknown>;
Update: Record<string, unknown>;
Relationships: GenericRelationship[];
};
type GenericUpdatableView = {
Row: Record<string, unknown>;
Insert: Record<string, unknown>;
Update: Record<string, unknown>;
Relationships: GenericRelationship[];
};
type GenericNonUpdatableView = {
Row: Record<string, unknown>;
Relationships: GenericRelationship[];
};
type GenericView = GenericUpdatableView | GenericNonUpdatableView;
type GenericSetofOption = {
isSetofReturn?: boolean | undefined;
isOneToOne?: boolean | undefined;
isNotNullable?: boolean | undefined;
to: string;
from: string;
};
type GenericFunction = {
Args: Record<string, unknown> | never;
Returns: unknown;
SetofOptions?: GenericSetofOption;
};
type GenericSchema = {
Tables: Record<string, GenericTable>;
Views: Record<string, GenericView>;
Functions: Record<string, GenericFunction>;
};
//#endregion
//#region src/lib/types.d.ts
interface SupabaseAuthClientOptions extends GoTrueClientOptions {}
type Fetch = typeof fetch;
type SupabaseClientOptions<SchemaName> = {
/**
* The Postgres schema which your tables belong to. Must be on the list of exposed schemas in Supabase. Defaults to `public`.
*/
db?: {
schema?: SchemaName;
/**
* Optional timeout in milliseconds for PostgREST requests.
* When set, requests will automatically abort after this duration to prevent indefinite hangs.
*
* @example
* ```ts
* const supabase = createClient(url, key, {
* db: { timeout: 30000 } // 30 second timeout
* })
* ```
*/
timeout?: number;
/**
* Maximum URL length in characters before warnings/errors are triggered.
* Defaults to 8000 characters. Used to provide helpful hints when URLs
* exceed server limits.
*
* @example
* ```ts
* const supabase = createClient(url, key, {
* db: { urlLengthLimit: 10000 } // Custom limit
* })
* ```
*/
urlLengthLimit?: number;
};
auth?: {
/**
* Automatically refreshes the token for logged-in users. Defaults to true.
*/
autoRefreshToken?: boolean;
/**
* Optional key name used for storing tokens in local storage.
*/
storageKey?: string;
/**
* Whether to persist a logged-in session to storage. Defaults to true.
*/
persistSession?: boolean;
/**
* Detect a session from the URL. Used for OAuth login callbacks. Defaults to true.
*
* Can be set to a function to provide custom logic for determining if a URL contains
* a Supabase auth callback. The function receives the current URL and parsed parameters,
* and should return true if the URL should be processed as a Supabase auth callback.
*
* This is useful when your app uses other OAuth providers (e.g., Facebook Login) that
* also return access_token in the URL fragment, which would otherwise be incorrectly
* intercepted by Supabase Auth.
*
* @example
* ```ts
* detectSessionInUrl: (url, params) => {
* // Ignore Facebook OAuth redirects
* if (url.pathname === '/facebook/redirect') return false
* // Use default detection for other URLs
* return Boolean(params.access_token || params.error_description)
* }
* ```
*/
detectSessionInUrl?: boolean | ((url: URL, params: {
[parameter: string]: string;
}) => boolean);
/**
* A storage provider. Used to store the logged-in session.
*/
storage?: SupabaseAuthClientOptions['storage'];
/**
* A storage provider to store the user profile separately from the session.
* Useful when you need to store the session information in cookies,
* without bloating the data with the redundant user object.
*
* @experimental
*/
userStorage?: SupabaseAuthClientOptions['userStorage'];
/**
* OAuth flow to use - defaults to implicit flow. PKCE is recommended for mobile and server-side applications.
*/
flowType?: SupabaseAuthClientOptions['flowType'];
/**
* If debug messages for authentication client are emitted. Can be used to inspect the behavior of the library.
*/
debug?: SupabaseAuthClientOptions['debug'];
/**
* Provide your own locking mechanism based on the environment. By default no locking is done at this time.
*
* @experimental
*/
lock?: SupabaseAuthClientOptions['lock'];
/**
* If there is an error with the query, throwOnError will reject the promise by
* throwing the error instead of returning it as part of a successful response.
*/
throwOnError?: SupabaseAuthClientOptions['throwOnError'];
};
/**
* Options passed to the realtime-js instance
*/
realtime?: RealtimeClientOptions;
storage?: StorageClientOptions;
global?: {
/**
* A custom `fetch` implementation.
*/
fetch?: Fetch;
/**
* Optional headers for initializing the client.
*/
headers?: Record<string, string>;
};
/**
* Optional function for using a third-party authentication system with
* Supabase. The function should return an access token or ID token (JWT) by
* obtaining it from the third-party auth SDK. Note that this
* function may be called concurrently and many times. Use memoization and
* locking techniques if this is not supported by the SDKs.
*
* When set, the `auth` namespace of the Supabase client cannot be used.
* Create another client if you wish to use Supabase Auth and third-party
* authentications concurrently in the same application.
*/
accessToken?: () => Promise<string | null>;
};
/**
* Helper types for query results.
*/
type QueryResult<T> = T extends PromiseLike<infer U> ? U : never;
type QueryData<T> = T extends PromiseLike<{
data: infer U;
}> ? Exclude<U, null> : never;
type QueryError = PostgrestError$1;
/**
* Strips internal Supabase metadata from Database types.
* Useful for libraries defining generic constraints on Database types.
*
* @example
* ```typescript
* type CleanDB = DatabaseWithoutInternals<Database>
* ```
*/
type DatabaseWithoutInternals<DB> = Omit<DB, '__InternalSupabase'>;
//#endregion
//#region src/lib/SupabaseAuthClient.d.ts
declare class SupabaseAuthClient extends AuthClient {
constructor(options: SupabaseAuthClientOptions);
}
//#endregion
//#region src/lib/rest/types/common/rpc.d.ts
type IsMatchingArgs<FnArgs extends GenericFunction['Args'], PassedArgs extends GenericFunction['Args']> = [FnArgs] extends [Record<PropertyKey, never>] ? PassedArgs extends Record<PropertyKey, never> ? true : false : keyof PassedArgs extends keyof FnArgs ? PassedArgs extends FnArgs ? true : false : false;
type MatchingFunctionArgs<Fn$1 extends GenericFunction, Args extends GenericFunction['Args']> = Fn$1 extends {
Args: infer A extends GenericFunction['Args'];
} ? IsMatchingArgs<A, Args> extends true ? Fn$1 : never : false;
type FindMatchingFunctionByArgs<FnUnion, Args extends GenericFunction['Args']> = FnUnion extends infer Fn extends GenericFunction ? MatchingFunctionArgs<Fn, Args> : false;
type TablesAndViews<Schema extends GenericSchema> = Schema['Tables'] & Exclude<Schema['Views'], ''>;
type UnionToIntersection<U$1> = (U$1 extends any ? (k: U$1) => void : never) extends ((k: infer I) => void) ? I : never;
type LastOf<T> = UnionToIntersection<T extends any ? () => T : never> extends (() => infer R) ? R : never;
type IsAny<T> = 0 extends 1 & T ? true : false;
type ExactMatch<T, S> = [T] extends [S] ? ([S] extends [T] ? true : false) : false;
type ExtractExactFunction<Fns, Args> = Fns extends infer F ? F extends GenericFunction ? ExactMatch<F['Args'], Args> extends true ? F : never : never : never;
type IsNever<T> = [T] extends [never] ? true : false;
type RpcFunctionNotFound<FnName> = {
Row: any;
Result: {
error: true;
} & "Couldn't infer function definition matching provided arguments";
RelationName: FnName;
Relationships: null;
};
type CrossSchemaError<TableRef extends string> = {
error: true;
} & `Function returns SETOF from a different schema ('${TableRef}'). Use .overrideTypes<YourReturnType>() to specify the return type explicitly.`;
type GetRpcFunctionFilterBuilderByArgs<Schema extends GenericSchema, FnName extends string & keyof Schema['Functions'], Args> = {
0: Schema['Functions'][FnName];
1: IsAny<Schema> extends true ? any : IsNever<Args> extends true ? IsNever<ExtractExactFunction<Schema['Functions'][FnName], Args>> extends true ? LastOf<Schema['Functions'][FnName]> : ExtractExactFunction<Schema['Functions'][FnName], Args> : Args extends Record<PropertyKey, never> ? LastOf<Schema['Functions'][FnName]> : Args extends GenericFunction['Args'] ? IsNever<LastOf<FindMatchingFunctionByArgs<Schema['Functions'][FnName], Args>>> extends true ? LastOf<Schema['Functions'][FnName]> : LastOf<FindMatchingFunctionByArgs<Schema['Functions'][FnName], Args>> : ExtractExactFunction<Schema['Functions'][FnName], Args> extends GenericFunction ? ExtractExactFunction<Schema['Functions'][FnName], Args> : any;
}[1] extends infer Fn ? IsAny<Fn> extends true ? {
Row: any;
Result: any;
RelationName: FnName;
Relationships: null;
} : Fn extends GenericFunction ? {
Row: Fn['SetofOptions'] extends GenericSetofOption ? Fn['SetofOptions']['to'] extends keyof TablesAndViews<Schema> ? TablesAndViews<Schema>[Fn['SetofOptions']['to']]['Row'] : Fn['Returns'] extends any[] ? Fn['Returns'][number] extends Record<string, unknown> ? Fn['Returns'][number] : CrossSchemaError<Fn['SetofOptions']['to'] & string> : Fn['Returns'] extends Record<string, unknown> ? Fn['Returns'] : CrossSchemaError<Fn['SetofOptions']['to'] & string> : Fn['Returns'] extends any[] ? Fn['Returns'][number] extends Record<string, unknown> ? Fn['Returns'][number] : never : Fn['Returns'] extends Record<string, unknown> ? Fn['Returns'] : never;
Result: Fn['SetofOptions'] extends GenericSetofOption ? Fn['SetofOptions']['isSetofReturn'] extends true ? Fn['SetofOptions']['isOneToOne'] extends true ? Fn['Returns'][] : Fn['Returns'] : Fn['Returns'] : Fn['Returns'];
RelationName: Fn['SetofOptions'] extends GenericSetofOption ? Fn['SetofOptions']['to'] : FnName;
Relationships: Fn['SetofOptions'] extends GenericSetofOption ? Fn['SetofOptions']['to'] extends keyof Schema['Tables'] ? Schema['Tables'][Fn['SetofOptions']['to']]['Relationships'] : Fn['SetofOptions']['to'] extends keyof Schema['Views'] ? Schema['Views'][Fn['SetofOptions']['to']]['Relationships'] : null : null;
} : Fn extends false ? RpcFunctionNotFound<FnName> : RpcFunctionNotFound<FnName> : RpcFunctionNotFound<FnName>;
//#endregion
//#region src/SupabaseClient.d.ts
/**
* Supabase Client.
*
* An isomorphic Javascript client for interacting with Postgres.
*/
declare class SupabaseClient<Database = any, SchemaNameOrClientOptions extends (string & keyof Omit<Database, '__InternalSupabase'>) | {
PostgrestVersion: string;
} = ('public' extends keyof Omit<Database, '__InternalSupabase'> ? 'public' : string & keyof Omit<Database, '__InternalSupabase'>), SchemaName extends string & keyof Omit<Database, '__InternalSupabase'> = (SchemaNameOrClientOptions extends string & keyof Omit<Database, '__InternalSupabase'> ? SchemaNameOrClientOptions : 'public' extends keyof Omit<Database, '__InternalSupabase'> ? 'public' : string & keyof Omit<Omit<Database, '__InternalSupabase'>, '__InternalSupabase'>), Schema extends (Omit<Database, '__InternalSupabase'>[SchemaName] extends GenericSchema ? Omit<Database, '__InternalSupabase'>[SchemaName] : never) = (Omit<Database, '__InternalSupabase'>[SchemaName] extends GenericSchema ? Omit<Database, '__InternalSupabase'>[SchemaName] : never), ClientOptions extends {
PostgrestVersion: string;
} = (SchemaNameOrClientOptions extends string & keyof Omit<Database, '__InternalSupabase'> ? Database extends {
__InternalSupabase: {
PostgrestVersion: string;
};
} ? Database['__InternalSupabase'] : {
PostgrestVersion: '12';
} : SchemaNameOrClientOptions extends {
PostgrestVersion: string;
} ? SchemaNameOrClientOptions : never)> {
protected supabaseUrl: string;
protected supabaseKey: string;
/**
* Supabase Auth allows you to create and manage user sessions for access to data that is secured by access policies.
*/
auth: SupabaseAuthClient;
realtime: RealtimeClient;
/**
* Supabase Storage allows you to manage user-generated content, such as photos or videos.
*/
storage: StorageClient;
protected realtimeUrl: URL;
protected authUrl: URL;
protected storageUrl: URL;
protected functionsUrl: URL;
protected rest: PostgrestClient<Database, ClientOptions, SchemaName>;
protected storageKey: string;
protected fetch?: Fetch;
protected changedAccessToken?: string;
protected accessToken?: () => Promise<string | null>;
protected headers: Record<string, string>;
/**
* Create a new client for use in the browser.
*
* @category Initializing
*
* @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard.
* @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard.
* @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase.
* @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring.
* @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage.
* @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user.
* @param options.realtime Options passed along to realtime-js constructor.
* @param options.storage Options passed along to the storage-js constructor.
* @param options.global.fetch A custom fetch implementation.
* @param options.global.headers Any additional headers to send with each network request.
*
* @example Creating a client
* ```js
* import { createClient } from '@supabase/supabase-js'
*
* // Create a single supabase client for interacting with your database
* const supabase = createClient('https://xyzcompany.supabase.co', 'publishable-or-anon-key')
* ```
*
* @example With a custom domain
* ```js
* import { createClient } from '@supabase/supabase-js'
*
* // Use a custom domain as the supabase URL
* const supabase = createClient('https://my-custom-domain.com', 'publishable-or-anon-key')
* ```
*
* @example With additional parameters
* ```js
* import { createClient } from '@supabase/supabase-js'
*
* const options = {
* db: {
* schema: 'public',
* },
* auth: {
* autoRefreshToken: true,
* persistSession: true,
* detectSessionInUrl: true
* },
* global: {
* headers: { 'x-my-custom-header': 'my-app-name' },
* },
* }
* const supabase = createClient("https://xyzcompany.supabase.co", "publishable-or-anon-key", options)
* ```
*
* @exampleDescription With custom schemas
* By default the API server points to the `public` schema. You can enable other database schemas within the Dashboard.
* Go to [Settings > API > Exposed schemas](/dashboard/project/_/settings/api) and add the schema which you want to expose to the API.
*
* Note: each client connection can only access a single schema, so the code above can access the `other_schema` schema but cannot access the `public` schema.
*
* @example With custom schemas
* ```js
* import { createClient } from '@supabase/supabase-js'
*
* const supabase = createClient('https://xyzcompany.supabase.co', 'publishable-or-anon-key', {
* // Provide a custom schema. Defaults to "public".
* db: { schema: 'other_schema' }
* })
* ```
*
* @exampleDescription Custom fetch implementation
* `supabase-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).
*
* @example Custom fetch implementation
* ```js
* import { createClient } from '@supabase/supabase-js'
*
* const supabase = createClient('https://xyzcompany.supabase.co', 'publishable-or-anon-key', {
* global: { fetch: fetch.bind(globalThis) }
* })
* ```
*
* @exampleDescription React Native options with AsyncStorage
* For React Native we recommend using `AsyncStorage` as the storage implementation for Supabase Auth.
*
* @example React Native options with AsyncStorage
* ```js
* import 'react-native-url-polyfill/auto'
* import { createClient } from '@supabase/supabase-js'
* import AsyncStorage from "@react-native-async-storage/async-storage";
*
* const supabase = createClient("https://xyzcompany.supabase.co", "publishable-or-anon-key", {
* auth: {
* storage: AsyncStorage,
* autoRefreshToken: true,
* persistSession: true,
* detectSessionInUrl: false,
* },
* });
* ```
*
* @exampleDescription React Native options with Expo SecureStore
* If you wish to encrypt the user's session information, you can use `aes-js` and store the encryption key in Expo SecureStore.
* The `aes-js` library, a reputable JavaScript-only implementation of the AES encryption algorithm in CTR mode.
* A new 256-bit encryption key is generated using the `react-native-get-random-values` library.
* This key is stored inside Expo's SecureStore, while the value is encrypted and placed inside AsyncStorage.
*
* Please make sure that:
* - You keep the `expo-secure-store`, `aes-js` and `react-native-get-random-values` libraries up-to-date.
* - Choose the correct [`SecureStoreOptions`](https://docs.expo.dev/versions/latest/sdk/securestore/#securestoreoptions) for your app's needs.
* E.g. [`SecureStore.WHEN_UNLOCKED`](https://docs.expo.dev/versions/latest/sdk/securestore/#securestorewhen_unlocked) regulates when the data can be accessed.
* - Carefully consider optimizations or other modifications to the above example, as those can lead to introducing subtle security vulnerabilities.
*
* @example React Native options with Expo SecureStore
* ```ts
* import 'react-native-url-polyfill/auto'
* import { createClient } from '@supabase/supabase-js'
* import AsyncStorage from '@react-native-async-storage/async-storage';
* import * as SecureStore from 'expo-secure-store';
* import * as aesjs from 'aes-js';
* import 'react-native-get-random-values';
*
* // As Expo's SecureStore does not support values larger than 2048
* // bytes, an AES-256 key is generated and stored in SecureStore, while
* // it is used to encrypt/decrypt values stored in AsyncStorage.
* class LargeSecureStore {
* private async _encrypt(key: string, value: string) {
* const encryptionKey = crypto.getRandomValues(new Uint8Array(256 / 8));
*
* const cipher = new aesjs.ModeOfOperation.ctr(encryptionKey, new aesjs.Counter(1));
* const encryptedBytes = cipher.encrypt(aesjs.utils.utf8.toBytes(value));
*
* await SecureStore.setItemAsync(key, aesjs.utils.hex.fromBytes(encryptionKey));
*
* return aesjs.utils.hex.fromBytes(encryptedBytes);
* }
*
* private async _decrypt(key: string, value: string) {
* const encryptionKeyHex = await SecureStore.getItemAsync(key);
* if (!encryptionKeyHex) {
* return encryptionKeyHex;
* }
*
* const cipher = new aesjs.ModeOfOperation.ctr(aesjs.utils.hex.toBytes(encryptionKeyHex), new aesjs.Counter(1));
* const decryptedBytes = cipher.decrypt(aesjs.utils.hex.toBytes(value));
*
* return aesjs.utils.utf8.fromBytes(decryptedBytes);
* }
*
* async getItem(key: string) {
* const encrypted = await AsyncStorage.getItem(key);
* if (!encrypted) { return encrypted; }
*
* return await this._decrypt(key, encrypted);
* }
*
* async removeItem(key: string) {
* await AsyncStorage.removeItem(key);
* await SecureStore.deleteItemAsync(key);
* }
*
* async setItem(key: string, value: string) {
* const encrypted = await this._encrypt(key, value);
*
* await AsyncStorage.setItem(key, encrypted);
* }
* }
*
* const supabase = createClient("https://xyzcompany.supabase.co", "publishable-or-anon-key", {
* auth: {
* storage: new LargeSecureStore(),
* autoRefreshToken: true,
* persistSession: true,
* detectSessionInUrl: false,
* },
* });
* ```
*
* @example With a database query
* ```ts
* import { createClient } from '@supabase/supabase-js'
*
* const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key')
*
* const { data } = await supabase.from('profiles').select('*')
* ```
*/
constructor(supabaseUrl: string, supabaseKey: string, options?: SupabaseClientOptions<SchemaName>);
/**
* Supabase Functions allows you to deploy and invoke edge functions.
*/
get functions(): FunctionsClient;
from<TableName extends string & keyof Schema['Tables'], Table extends Schema['Tables'][TableName]>(relation: TableName): PostgrestQueryBuilder<ClientOptions, Schema, Table, TableName>;
from<ViewName extends string & keyof Schema['Views'], View extends Schema['Views'][ViewName]>(relation: ViewName): PostgrestQueryBuilder<ClientOptions, Schema, View, ViewName>;
/**
* Select a schema to query or perform an function (rpc) call.
*
* The schema needs to be on the list of exposed schemas inside Supabase.
*
* @param schema - The schema to query
*/
schema<DynamicSchema extends string & keyof Omit<Database, '__InternalSupabase'>>(schema: DynamicSchema): PostgrestClient<Database, ClientOptions, DynamicSchema, Database[DynamicSchema] extends GenericSchema ? Database[DynamicSchema] : any>;
/**
* Perform a function call.
*
* @param fn - The function name to call
* @param args - The arguments to pass to the function call
* @param options - Named parameters
* @param options.head - When set to `true`, `data` will not be returned.
* Useful if you only need the count.
* @param options.get - When set to `true`, the function will be called with
* read-only access mode.
* @param options.count - Count algorithm to use to count rows returned by the
* function. Only applicable for [set-returning
* functions](https://www.postgresql.org/docs/current/functions-srf.html).
*
* `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the
* hood.
*
* `"planned"`: Approximated but fast count algorithm. Uses the Postgres
* statistics under the hood.
*
* `"estimated"`: Uses exact count for low numbers and planned count for high
* numbers.
*/
rpc<FnName extends string & keyof Schema['Functions'], Args extends Schema['Functions'][FnName]['Args'] = never, FilterBuilder extends GetRpcFunctionFilterBuilderByArgs<Schema, FnName, Args> = GetRpcFunctionFilterBuilderByArgs<Schema, FnName, Args>>(fn: FnName, args?: Args, options?: {
head?: boolean;
get?: boolean;
count?: 'exact' | 'planned' | 'estimated';
}): PostgrestFilterBuilder<ClientOptions, Schema, FilterBuilder['Row'], FilterBuilder['Result'], FilterBuilder['RelationName'], FilterBuilder['Relationships'], 'RPC'>;
/**
* Creates a Realtime channel with Broadcast, Presence, and Postgres Changes.
*
* @param {string} name - The name of the Realtime channel.
* @param {Object} opts - The options to pass to the Realtime channel.
*
*/
channel(name: string, opts?: RealtimeChannelOptions): RealtimeChannel;
/**
* Returns all Realtime channels.
*/
getChannels(): RealtimeChannel[];
/**
* Unsubscribes and removes Realtime channel from Realtime client.
*
* @param {RealtimeChannel} channel - The name of the Realtime channel.
*
*/
removeChannel(channel: RealtimeChannel): Promise<'ok' | 'timed out' | 'error'>;
/**
* Unsubscribes and removes all Realtime channels from Realtime client.
*/
removeAllChannels(): Promise<('ok' | 'timed out' | 'error')[]>;
private _getAccessToken;
private _initSupabaseAuthClient;
private _initRealtimeClient;
private _listenForAuthEvents;
private _handleTokenChanged;
}
//#endregion
//#region src/index.d.ts
/**
* Creates a new Supabase Client.
*
* @example
* ```ts
* import { createClient } from '@supabase/supabase-js'
*
* const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key')
* const { data, error } = await supabase.from('profiles').select('*')
* ```
*/
declare const createClient: <Database = any, SchemaNameOrClientOptions extends (string & keyof Omit<Database, "__InternalSupabase">) | {
PostgrestVersion: string;
} = ("public" extends keyof Omit<Database, "__InternalSupabase"> ? "public" : string & keyof Omit<Database, "__InternalSupabase">), SchemaName extends string & keyof Omit<Database, "__InternalSupabase"> = (SchemaNameOrClientOptions extends string & keyof Omit<Database, "__InternalSupabase"> ? SchemaNameOrClientOptions : "public" extends keyof Omit<Database, "__InternalSupabase"> ? "public" : string & keyof Omit<Omit<Database, "__InternalSupabase">, "__InternalSupabase">)>(supabaseUrl: string, supabaseKey: string, options?: SupabaseClientOptions<SchemaName>) => SupabaseClient<Database, SchemaNameOrClientOptions, SchemaName>;
//#endregion
export { type AuthSession, type AuthUser, type DatabaseWithoutInternals, type FunctionInvokeOptions, FunctionRegion, FunctionsError, FunctionsFetchError, FunctionsHttpError, FunctionsRelayError, PostgrestError, type PostgrestMaybeSingleResponse, type PostgrestResponse, type PostgrestSingleResponse, type QueryData, type QueryError, type QueryResult, SupabaseClient, type SupabaseClientOptions, createClient };
//# sourceMappingURL=index.d.cts.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,564 @@
import { FunctionInvokeOptions, FunctionRegion, FunctionsClient, FunctionsError, FunctionsFetchError, FunctionsHttpError, FunctionsRelayError } from "@supabase/functions-js";
import { PostgrestClient, PostgrestError, PostgrestError as PostgrestError$1, PostgrestFilterBuilder, PostgrestMaybeSingleResponse, PostgrestQueryBuilder, PostgrestResponse, PostgrestSingleResponse } from "@supabase/postgrest-js";
import { RealtimeChannel, RealtimeChannelOptions, RealtimeClient, RealtimeClientOptions } from "@supabase/realtime-js";
import { StorageClient, StorageClientOptions } from "@supabase/storage-js";
import { AuthClient, GoTrueClientOptions, Session as AuthSession, User as AuthUser } from "@supabase/auth-js";
export * from "@supabase/realtime-js";
export * from "@supabase/auth-js";
//#region src/lib/rest/types/common/common.d.ts
type GenericRelationship = {
foreignKeyName: string;
columns: string[];
isOneToOne?: boolean;
referencedRelation: string;
referencedColumns: string[];
};
type GenericTable = {
Row: Record<string, unknown>;
Insert: Record<string, unknown>;
Update: Record<string, unknown>;
Relationships: GenericRelationship[];
};
type GenericUpdatableView = {
Row: Record<string, unknown>;
Insert: Record<string, unknown>;
Update: Record<string, unknown>;
Relationships: GenericRelationship[];
};
type GenericNonUpdatableView = {
Row: Record<string, unknown>;
Relationships: GenericRelationship[];
};
type GenericView = GenericUpdatableView | GenericNonUpdatableView;
type GenericSetofOption = {
isSetofReturn?: boolean | undefined;
isOneToOne?: boolean | undefined;
isNotNullable?: boolean | undefined;
to: string;
from: string;
};
type GenericFunction = {
Args: Record<string, unknown> | never;
Returns: unknown;
SetofOptions?: GenericSetofOption;
};
type GenericSchema = {
Tables: Record<string, GenericTable>;
Views: Record<string, GenericView>;
Functions: Record<string, GenericFunction>;
};
//#endregion
//#region src/lib/types.d.ts
interface SupabaseAuthClientOptions extends GoTrueClientOptions {}
type Fetch = typeof fetch;
type SupabaseClientOptions<SchemaName> = {
/**
* The Postgres schema which your tables belong to. Must be on the list of exposed schemas in Supabase. Defaults to `public`.
*/
db?: {
schema?: SchemaName;
/**
* Optional timeout in milliseconds for PostgREST requests.
* When set, requests will automatically abort after this duration to prevent indefinite hangs.
*
* @example
* ```ts
* const supabase = createClient(url, key, {
* db: { timeout: 30000 } // 30 second timeout
* })
* ```
*/
timeout?: number;
/**
* Maximum URL length in characters before warnings/errors are triggered.
* Defaults to 8000 characters. Used to provide helpful hints when URLs
* exceed server limits.
*
* @example
* ```ts
* const supabase = createClient(url, key, {
* db: { urlLengthLimit: 10000 } // Custom limit
* })
* ```
*/
urlLengthLimit?: number;
};
auth?: {
/**
* Automatically refreshes the token for logged-in users. Defaults to true.
*/
autoRefreshToken?: boolean;
/**
* Optional key name used for storing tokens in local storage.
*/
storageKey?: string;
/**
* Whether to persist a logged-in session to storage. Defaults to true.
*/
persistSession?: boolean;
/**
* Detect a session from the URL. Used for OAuth login callbacks. Defaults to true.
*
* Can be set to a function to provide custom logic for determining if a URL contains
* a Supabase auth callback. The function receives the current URL and parsed parameters,
* and should return true if the URL should be processed as a Supabase auth callback.
*
* This is useful when your app uses other OAuth providers (e.g., Facebook Login) that
* also return access_token in the URL fragment, which would otherwise be incorrectly
* intercepted by Supabase Auth.
*
* @example
* ```ts
* detectSessionInUrl: (url, params) => {
* // Ignore Facebook OAuth redirects
* if (url.pathname === '/facebook/redirect') return false
* // Use default detection for other URLs
* return Boolean(params.access_token || params.error_description)
* }
* ```
*/
detectSessionInUrl?: boolean | ((url: URL, params: {
[parameter: string]: string;
}) => boolean);
/**
* A storage provider. Used to store the logged-in session.
*/
storage?: SupabaseAuthClientOptions['storage'];
/**
* A storage provider to store the user profile separately from the session.
* Useful when you need to store the session information in cookies,
* without bloating the data with the redundant user object.
*
* @experimental
*/
userStorage?: SupabaseAuthClientOptions['userStorage'];
/**
* OAuth flow to use - defaults to implicit flow. PKCE is recommended for mobile and server-side applications.
*/
flowType?: SupabaseAuthClientOptions['flowType'];
/**
* If debug messages for authentication client are emitted. Can be used to inspect the behavior of the library.
*/
debug?: SupabaseAuthClientOptions['debug'];
/**
* Provide your own locking mechanism based on the environment. By default no locking is done at this time.
*
* @experimental
*/
lock?: SupabaseAuthClientOptions['lock'];
/**
* If there is an error with the query, throwOnError will reject the promise by
* throwing the error instead of returning it as part of a successful response.
*/
throwOnError?: SupabaseAuthClientOptions['throwOnError'];
};
/**
* Options passed to the realtime-js instance
*/
realtime?: RealtimeClientOptions;
storage?: StorageClientOptions;
global?: {
/**
* A custom `fetch` implementation.
*/
fetch?: Fetch;
/**
* Optional headers for initializing the client.
*/
headers?: Record<string, string>;
};
/**
* Optional function for using a third-party authentication system with
* Supabase. The function should return an access token or ID token (JWT) by
* obtaining it from the third-party auth SDK. Note that this
* function may be called concurrently and many times. Use memoization and
* locking techniques if this is not supported by the SDKs.
*
* When set, the `auth` namespace of the Supabase client cannot be used.
* Create another client if you wish to use Supabase Auth and third-party
* authentications concurrently in the same application.
*/
accessToken?: () => Promise<string | null>;
};
/**
* Helper types for query results.
*/
type QueryResult<T> = T extends PromiseLike<infer U> ? U : never;
type QueryData<T> = T extends PromiseLike<{
data: infer U;
}> ? Exclude<U, null> : never;
type QueryError = PostgrestError$1;
/**
* Strips internal Supabase metadata from Database types.
* Useful for libraries defining generic constraints on Database types.
*
* @example
* ```typescript
* type CleanDB = DatabaseWithoutInternals<Database>
* ```
*/
type DatabaseWithoutInternals<DB> = Omit<DB, '__InternalSupabase'>;
//#endregion
//#region src/lib/SupabaseAuthClient.d.ts
declare class SupabaseAuthClient extends AuthClient {
constructor(options: SupabaseAuthClientOptions);
}
//#endregion
//#region src/lib/rest/types/common/rpc.d.ts
type IsMatchingArgs<FnArgs extends GenericFunction['Args'], PassedArgs extends GenericFunction['Args']> = [FnArgs] extends [Record<PropertyKey, never>] ? PassedArgs extends Record<PropertyKey, never> ? true : false : keyof PassedArgs extends keyof FnArgs ? PassedArgs extends FnArgs ? true : false : false;
type MatchingFunctionArgs<Fn$1 extends GenericFunction, Args extends GenericFunction['Args']> = Fn$1 extends {
Args: infer A extends GenericFunction['Args'];
} ? IsMatchingArgs<A, Args> extends true ? Fn$1 : never : false;
type FindMatchingFunctionByArgs<FnUnion, Args extends GenericFunction['Args']> = FnUnion extends infer Fn extends GenericFunction ? MatchingFunctionArgs<Fn, Args> : false;
type TablesAndViews<Schema extends GenericSchema> = Schema['Tables'] & Exclude<Schema['Views'], ''>;
type UnionToIntersection<U$1> = (U$1 extends any ? (k: U$1) => void : never) extends ((k: infer I) => void) ? I : never;
type LastOf<T> = UnionToIntersection<T extends any ? () => T : never> extends (() => infer R) ? R : never;
type IsAny<T> = 0 extends 1 & T ? true : false;
type ExactMatch<T, S> = [T] extends [S] ? ([S] extends [T] ? true : false) : false;
type ExtractExactFunction<Fns, Args> = Fns extends infer F ? F extends GenericFunction ? ExactMatch<F['Args'], Args> extends true ? F : never : never : never;
type IsNever<T> = [T] extends [never] ? true : false;
type RpcFunctionNotFound<FnName> = {
Row: any;
Result: {
error: true;
} & "Couldn't infer function definition matching provided arguments";
RelationName: FnName;
Relationships: null;
};
type CrossSchemaError<TableRef extends string> = {
error: true;
} & `Function returns SETOF from a different schema ('${TableRef}'). Use .overrideTypes<YourReturnType>() to specify the return type explicitly.`;
type GetRpcFunctionFilterBuilderByArgs<Schema extends GenericSchema, FnName extends string & keyof Schema['Functions'], Args> = {
0: Schema['Functions'][FnName];
1: IsAny<Schema> extends true ? any : IsNever<Args> extends true ? IsNever<ExtractExactFunction<Schema['Functions'][FnName], Args>> extends true ? LastOf<Schema['Functions'][FnName]> : ExtractExactFunction<Schema['Functions'][FnName], Args> : Args extends Record<PropertyKey, never> ? LastOf<Schema['Functions'][FnName]> : Args extends GenericFunction['Args'] ? IsNever<LastOf<FindMatchingFunctionByArgs<Schema['Functions'][FnName], Args>>> extends true ? LastOf<Schema['Functions'][FnName]> : LastOf<FindMatchingFunctionByArgs<Schema['Functions'][FnName], Args>> : ExtractExactFunction<Schema['Functions'][FnName], Args> extends GenericFunction ? ExtractExactFunction<Schema['Functions'][FnName], Args> : any;
}[1] extends infer Fn ? IsAny<Fn> extends true ? {
Row: any;
Result: any;
RelationName: FnName;
Relationships: null;
} : Fn extends GenericFunction ? {
Row: Fn['SetofOptions'] extends GenericSetofOption ? Fn['SetofOptions']['to'] extends keyof TablesAndViews<Schema> ? TablesAndViews<Schema>[Fn['SetofOptions']['to']]['Row'] : Fn['Returns'] extends any[] ? Fn['Returns'][number] extends Record<string, unknown> ? Fn['Returns'][number] : CrossSchemaError<Fn['SetofOptions']['to'] & string> : Fn['Returns'] extends Record<string, unknown> ? Fn['Returns'] : CrossSchemaError<Fn['SetofOptions']['to'] & string> : Fn['Returns'] extends any[] ? Fn['Returns'][number] extends Record<string, unknown> ? Fn['Returns'][number] : never : Fn['Returns'] extends Record<string, unknown> ? Fn['Returns'] : never;
Result: Fn['SetofOptions'] extends GenericSetofOption ? Fn['SetofOptions']['isSetofReturn'] extends true ? Fn['SetofOptions']['isOneToOne'] extends true ? Fn['Returns'][] : Fn['Returns'] : Fn['Returns'] : Fn['Returns'];
RelationName: Fn['SetofOptions'] extends GenericSetofOption ? Fn['SetofOptions']['to'] : FnName;
Relationships: Fn['SetofOptions'] extends GenericSetofOption ? Fn['SetofOptions']['to'] extends keyof Schema['Tables'] ? Schema['Tables'][Fn['SetofOptions']['to']]['Relationships'] : Fn['SetofOptions']['to'] extends keyof Schema['Views'] ? Schema['Views'][Fn['SetofOptions']['to']]['Relationships'] : null : null;
} : Fn extends false ? RpcFunctionNotFound<FnName> : RpcFunctionNotFound<FnName> : RpcFunctionNotFound<FnName>;
//#endregion
//#region src/SupabaseClient.d.ts
/**
* Supabase Client.
*
* An isomorphic Javascript client for interacting with Postgres.
*/
declare class SupabaseClient<Database = any, SchemaNameOrClientOptions extends (string & keyof Omit<Database, '__InternalSupabase'>) | {
PostgrestVersion: string;
} = ('public' extends keyof Omit<Database, '__InternalSupabase'> ? 'public' : string & keyof Omit<Database, '__InternalSupabase'>), SchemaName extends string & keyof Omit<Database, '__InternalSupabase'> = (SchemaNameOrClientOptions extends string & keyof Omit<Database, '__InternalSupabase'> ? SchemaNameOrClientOptions : 'public' extends keyof Omit<Database, '__InternalSupabase'> ? 'public' : string & keyof Omit<Omit<Database, '__InternalSupabase'>, '__InternalSupabase'>), Schema extends (Omit<Database, '__InternalSupabase'>[SchemaName] extends GenericSchema ? Omit<Database, '__InternalSupabase'>[SchemaName] : never) = (Omit<Database, '__InternalSupabase'>[SchemaName] extends GenericSchema ? Omit<Database, '__InternalSupabase'>[SchemaName] : never), ClientOptions extends {
PostgrestVersion: string;
} = (SchemaNameOrClientOptions extends string & keyof Omit<Database, '__InternalSupabase'> ? Database extends {
__InternalSupabase: {
PostgrestVersion: string;
};
} ? Database['__InternalSupabase'] : {
PostgrestVersion: '12';
} : SchemaNameOrClientOptions extends {
PostgrestVersion: string;
} ? SchemaNameOrClientOptions : never)> {
protected supabaseUrl: string;
protected supabaseKey: string;
/**
* Supabase Auth allows you to create and manage user sessions for access to data that is secured by access policies.
*/
auth: SupabaseAuthClient;
realtime: RealtimeClient;
/**
* Supabase Storage allows you to manage user-generated content, such as photos or videos.
*/
storage: StorageClient;
protected realtimeUrl: URL;
protected authUrl: URL;
protected storageUrl: URL;
protected functionsUrl: URL;
protected rest: PostgrestClient<Database, ClientOptions, SchemaName>;
protected storageKey: string;
protected fetch?: Fetch;
protected changedAccessToken?: string;
protected accessToken?: () => Promise<string | null>;
protected headers: Record<string, string>;
/**
* Create a new client for use in the browser.
*
* @category Initializing
*
* @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard.
* @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard.
* @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase.
* @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring.
* @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage.
* @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user.
* @param options.realtime Options passed along to realtime-js constructor.
* @param options.storage Options passed along to the storage-js constructor.
* @param options.global.fetch A custom fetch implementation.
* @param options.global.headers Any additional headers to send with each network request.
*
* @example Creating a client
* ```js
* import { createClient } from '@supabase/supabase-js'
*
* // Create a single supabase client for interacting with your database
* const supabase = createClient('https://xyzcompany.supabase.co', 'publishable-or-anon-key')
* ```
*
* @example With a custom domain
* ```js
* import { createClient } from '@supabase/supabase-js'
*
* // Use a custom domain as the supabase URL
* const supabase = createClient('https://my-custom-domain.com', 'publishable-or-anon-key')
* ```
*
* @example With additional parameters
* ```js
* import { createClient } from '@supabase/supabase-js'
*
* const options = {
* db: {
* schema: 'public',
* },
* auth: {
* autoRefreshToken: true,
* persistSession: true,
* detectSessionInUrl: true
* },
* global: {
* headers: { 'x-my-custom-header': 'my-app-name' },
* },
* }
* const supabase = createClient("https://xyzcompany.supabase.co", "publishable-or-anon-key", options)
* ```
*
* @exampleDescription With custom schemas
* By default the API server points to the `public` schema. You can enable other database schemas within the Dashboard.
* Go to [Settings > API > Exposed schemas](/dashboard/project/_/settings/api) and add the schema which you want to expose to the API.
*
* Note: each client connection can only access a single schema, so the code above can access the `other_schema` schema but cannot access the `public` schema.
*
* @example With custom schemas
* ```js
* import { createClient } from '@supabase/supabase-js'
*
* const supabase = createClient('https://xyzcompany.supabase.co', 'publishable-or-anon-key', {
* // Provide a custom schema. Defaults to "public".
* db: { schema: 'other_schema' }
* })
* ```
*
* @exampleDescription Custom fetch implementation
* `supabase-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).
*
* @example Custom fetch implementation
* ```js
* import { createClient } from '@supabase/supabase-js'
*
* const supabase = createClient('https://xyzcompany.supabase.co', 'publishable-or-anon-key', {
* global: { fetch: fetch.bind(globalThis) }
* })
* ```
*
* @exampleDescription React Native options with AsyncStorage
* For React Native we recommend using `AsyncStorage` as the storage implementation for Supabase Auth.
*
* @example React Native options with AsyncStorage
* ```js
* import 'react-native-url-polyfill/auto'
* import { createClient } from '@supabase/supabase-js'
* import AsyncStorage from "@react-native-async-storage/async-storage";
*
* const supabase = createClient("https://xyzcompany.supabase.co", "publishable-or-anon-key", {
* auth: {
* storage: AsyncStorage,
* autoRefreshToken: true,
* persistSession: true,
* detectSessionInUrl: false,
* },
* });
* ```
*
* @exampleDescription React Native options with Expo SecureStore
* If you wish to encrypt the user's session information, you can use `aes-js` and store the encryption key in Expo SecureStore.
* The `aes-js` library, a reputable JavaScript-only implementation of the AES encryption algorithm in CTR mode.
* A new 256-bit encryption key is generated using the `react-native-get-random-values` library.
* This key is stored inside Expo's SecureStore, while the value is encrypted and placed inside AsyncStorage.
*
* Please make sure that:
* - You keep the `expo-secure-store`, `aes-js` and `react-native-get-random-values` libraries up-to-date.
* - Choose the correct [`SecureStoreOptions`](https://docs.expo.dev/versions/latest/sdk/securestore/#securestoreoptions) for your app's needs.
* E.g. [`SecureStore.WHEN_UNLOCKED`](https://docs.expo.dev/versions/latest/sdk/securestore/#securestorewhen_unlocked) regulates when the data can be accessed.
* - Carefully consider optimizations or other modifications to the above example, as those can lead to introducing subtle security vulnerabilities.
*
* @example React Native options with Expo SecureStore
* ```ts
* import 'react-native-url-polyfill/auto'
* import { createClient } from '@supabase/supabase-js'
* import AsyncStorage from '@react-native-async-storage/async-storage';
* import * as SecureStore from 'expo-secure-store';
* import * as aesjs from 'aes-js';
* import 'react-native-get-random-values';
*
* // As Expo's SecureStore does not support values larger than 2048
* // bytes, an AES-256 key is generated and stored in SecureStore, while
* // it is used to encrypt/decrypt values stored in AsyncStorage.
* class LargeSecureStore {
* private async _encrypt(key: string, value: string) {
* const encryptionKey = crypto.getRandomValues(new Uint8Array(256 / 8));
*
* const cipher = new aesjs.ModeOfOperation.ctr(encryptionKey, new aesjs.Counter(1));
* const encryptedBytes = cipher.encrypt(aesjs.utils.utf8.toBytes(value));
*
* await SecureStore.setItemAsync(key, aesjs.utils.hex.fromBytes(encryptionKey));
*
* return aesjs.utils.hex.fromBytes(encryptedBytes);
* }
*
* private async _decrypt(key: string, value: string) {
* const encryptionKeyHex = await SecureStore.getItemAsync(key);
* if (!encryptionKeyHex) {
* return encryptionKeyHex;
* }
*
* const cipher = new aesjs.ModeOfOperation.ctr(aesjs.utils.hex.toBytes(encryptionKeyHex), new aesjs.Counter(1));
* const decryptedBytes = cipher.decrypt(aesjs.utils.hex.toBytes(value));
*
* return aesjs.utils.utf8.fromBytes(decryptedBytes);
* }
*
* async getItem(key: string) {
* const encrypted = await AsyncStorage.getItem(key);
* if (!encrypted) { return encrypted; }
*
* return await this._decrypt(key, encrypted);
* }
*
* async removeItem(key: string) {
* await AsyncStorage.removeItem(key);
* await SecureStore.deleteItemAsync(key);
* }
*
* async setItem(key: string, value: string) {
* const encrypted = await this._encrypt(key, value);
*
* await AsyncStorage.setItem(key, encrypted);
* }
* }
*
* const supabase = createClient("https://xyzcompany.supabase.co", "publishable-or-anon-key", {
* auth: {
* storage: new LargeSecureStore(),
* autoRefreshToken: true,
* persistSession: true,
* detectSessionInUrl: false,
* },
* });
* ```
*
* @example With a database query
* ```ts
* import { createClient } from '@supabase/supabase-js'
*
* const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key')
*
* const { data } = await supabase.from('profiles').select('*')
* ```
*/
constructor(supabaseUrl: string, supabaseKey: string, options?: SupabaseClientOptions<SchemaName>);
/**
* Supabase Functions allows you to deploy and invoke edge functions.
*/
get functions(): FunctionsClient;
from<TableName extends string & keyof Schema['Tables'], Table extends Schema['Tables'][TableName]>(relation: TableName): PostgrestQueryBuilder<ClientOptions, Schema, Table, TableName>;
from<ViewName extends string & keyof Schema['Views'], View extends Schema['Views'][ViewName]>(relation: ViewName): PostgrestQueryBuilder<ClientOptions, Schema, View, ViewName>;
/**
* Select a schema to query or perform an function (rpc) call.
*
* The schema needs to be on the list of exposed schemas inside Supabase.
*
* @param schema - The schema to query
*/
schema<DynamicSchema extends string & keyof Omit<Database, '__InternalSupabase'>>(schema: DynamicSchema): PostgrestClient<Database, ClientOptions, DynamicSchema, Database[DynamicSchema] extends GenericSchema ? Database[DynamicSchema] : any>;
/**
* Perform a function call.
*
* @param fn - The function name to call
* @param args - The arguments to pass to the function call
* @param options - Named parameters
* @param options.head - When set to `true`, `data` will not be returned.
* Useful if you only need the count.
* @param options.get - When set to `true`, the function will be called with
* read-only access mode.
* @param options.count - Count algorithm to use to count rows returned by the
* function. Only applicable for [set-returning
* functions](https://www.postgresql.org/docs/current/functions-srf.html).
*
* `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the
* hood.
*
* `"planned"`: Approximated but fast count algorithm. Uses the Postgres
* statistics under the hood.
*
* `"estimated"`: Uses exact count for low numbers and planned count for high
* numbers.
*/
rpc<FnName extends string & keyof Schema['Functions'], Args extends Schema['Functions'][FnName]['Args'] = never, FilterBuilder extends GetRpcFunctionFilterBuilderByArgs<Schema, FnName, Args> = GetRpcFunctionFilterBuilderByArgs<Schema, FnName, Args>>(fn: FnName, args?: Args, options?: {
head?: boolean;
get?: boolean;
count?: 'exact' | 'planned' | 'estimated';
}): PostgrestFilterBuilder<ClientOptions, Schema, FilterBuilder['Row'], FilterBuilder['Result'], FilterBuilder['RelationName'], FilterBuilder['Relationships'], 'RPC'>;
/**
* Creates a Realtime channel with Broadcast, Presence, and Postgres Changes.
*
* @param {string} name - The name of the Realtime channel.
* @param {Object} opts - The options to pass to the Realtime channel.
*
*/
channel(name: string, opts?: RealtimeChannelOptions): RealtimeChannel;
/**
* Returns all Realtime channels.
*/
getChannels(): RealtimeChannel[];
/**
* Unsubscribes and removes Realtime channel from Realtime client.
*
* @param {RealtimeChannel} channel - The name of the Realtime channel.
*
*/
removeChannel(channel: RealtimeChannel): Promise<'ok' | 'timed out' | 'error'>;
/**
* Unsubscribes and removes all Realtime channels from Realtime client.
*/
removeAllChannels(): Promise<('ok' | 'timed out' | 'error')[]>;
private _getAccessToken;
private _initSupabaseAuthClient;
private _initRealtimeClient;
private _listenForAuthEvents;
private _handleTokenChanged;
}
//#endregion
//#region src/index.d.ts
/**
* Creates a new Supabase Client.
*
* @example
* ```ts
* import { createClient } from '@supabase/supabase-js'
*
* const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key')
* const { data, error } = await supabase.from('profiles').select('*')
* ```
*/
declare const createClient: <Database = any, SchemaNameOrClientOptions extends (string & keyof Omit<Database, "__InternalSupabase">) | {
PostgrestVersion: string;
} = ("public" extends keyof Omit<Database, "__InternalSupabase"> ? "public" : string & keyof Omit<Database, "__InternalSupabase">), SchemaName extends string & keyof Omit<Database, "__InternalSupabase"> = (SchemaNameOrClientOptions extends string & keyof Omit<Database, "__InternalSupabase"> ? SchemaNameOrClientOptions : "public" extends keyof Omit<Database, "__InternalSupabase"> ? "public" : string & keyof Omit<Omit<Database, "__InternalSupabase">, "__InternalSupabase">)>(supabaseUrl: string, supabaseKey: string, options?: SupabaseClientOptions<SchemaName>) => SupabaseClient<Database, SchemaNameOrClientOptions, SchemaName>;
//#endregion
export { type AuthSession, type AuthUser, type DatabaseWithoutInternals, type FunctionInvokeOptions, FunctionRegion, FunctionsError, FunctionsFetchError, FunctionsHttpError, FunctionsRelayError, PostgrestError, type PostgrestMaybeSingleResponse, type PostgrestResponse, type PostgrestSingleResponse, type QueryData, type QueryError, type QueryResult, SupabaseClient, type SupabaseClientOptions, createClient };
//# sourceMappingURL=index.d.mts.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,575 @@
import { FunctionRegion, FunctionsClient, FunctionsError, FunctionsFetchError, FunctionsHttpError, FunctionsRelayError } from "@supabase/functions-js";
import { PostgrestClient, PostgrestError } from "@supabase/postgrest-js";
import { RealtimeClient } from "@supabase/realtime-js";
import { StorageClient } from "@supabase/storage-js";
import { AuthClient } from "@supabase/auth-js";
export * from "@supabase/realtime-js"
export * from "@supabase/auth-js"
//#region src/lib/version.ts
const version = "2.99.1";
//#endregion
//#region src/lib/constants.ts
let JS_ENV = "";
if (typeof Deno !== "undefined") JS_ENV = "deno";
else if (typeof document !== "undefined") JS_ENV = "web";
else if (typeof navigator !== "undefined" && navigator.product === "ReactNative") JS_ENV = "react-native";
else JS_ENV = "node";
const DEFAULT_HEADERS = { "X-Client-Info": `supabase-js-${JS_ENV}/${version}` };
const DEFAULT_GLOBAL_OPTIONS = { headers: DEFAULT_HEADERS };
const DEFAULT_DB_OPTIONS = { schema: "public" };
const DEFAULT_AUTH_OPTIONS = {
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true,
flowType: "implicit"
};
const DEFAULT_REALTIME_OPTIONS = {};
//#endregion
//#region \0@oxc-project+runtime@0.101.0/helpers/typeof.js
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$1) {
return typeof o$1;
} : function(o$1) {
return o$1 && "function" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1;
}, _typeof(o);
}
//#endregion
//#region \0@oxc-project+runtime@0.101.0/helpers/toPrimitive.js
function toPrimitive(t, r) {
if ("object" != _typeof(t) || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r || "default");
if ("object" != _typeof(i)) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
//#endregion
//#region \0@oxc-project+runtime@0.101.0/helpers/toPropertyKey.js
function toPropertyKey(t) {
var i = toPrimitive(t, "string");
return "symbol" == _typeof(i) ? i : i + "";
}
//#endregion
//#region \0@oxc-project+runtime@0.101.0/helpers/defineProperty.js
function _defineProperty(e, r, t) {
return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
value: t,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[r] = t, e;
}
//#endregion
//#region \0@oxc-project+runtime@0.101.0/helpers/objectSpread2.js
function ownKeys(e, r) {
var t = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var o = Object.getOwnPropertySymbols(e);
r && (o = o.filter(function(r$1) {
return Object.getOwnPropertyDescriptor(e, r$1).enumerable;
})), t.push.apply(t, o);
}
return t;
}
function _objectSpread2(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys(Object(t), !0).forEach(function(r$1) {
_defineProperty(e, r$1, t[r$1]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r$1) {
Object.defineProperty(e, r$1, Object.getOwnPropertyDescriptor(t, r$1));
});
}
return e;
}
//#endregion
//#region src/lib/fetch.ts
const resolveFetch = (customFetch) => {
if (customFetch) return (...args) => customFetch(...args);
return (...args) => fetch(...args);
};
const resolveHeadersConstructor = () => {
return Headers;
};
const fetchWithAuth = (supabaseKey, getAccessToken, customFetch) => {
const fetch$1 = resolveFetch(customFetch);
const HeadersConstructor = resolveHeadersConstructor();
return async (input, init) => {
var _await$getAccessToken;
const accessToken = (_await$getAccessToken = await getAccessToken()) !== null && _await$getAccessToken !== void 0 ? _await$getAccessToken : supabaseKey;
let headers = new HeadersConstructor(init === null || init === void 0 ? void 0 : init.headers);
if (!headers.has("apikey")) headers.set("apikey", supabaseKey);
if (!headers.has("Authorization")) headers.set("Authorization", `Bearer ${accessToken}`);
return fetch$1(input, _objectSpread2(_objectSpread2({}, init), {}, { headers }));
};
};
//#endregion
//#region src/lib/helpers.ts
function ensureTrailingSlash(url) {
return url.endsWith("/") ? url : url + "/";
}
function applySettingDefaults(options, defaults) {
var _DEFAULT_GLOBAL_OPTIO, _globalOptions$header;
const { db: dbOptions, auth: authOptions, realtime: realtimeOptions, global: globalOptions } = options;
const { db: DEFAULT_DB_OPTIONS$1, auth: DEFAULT_AUTH_OPTIONS$1, realtime: DEFAULT_REALTIME_OPTIONS$1, global: DEFAULT_GLOBAL_OPTIONS$1 } = defaults;
const result = {
db: _objectSpread2(_objectSpread2({}, DEFAULT_DB_OPTIONS$1), dbOptions),
auth: _objectSpread2(_objectSpread2({}, DEFAULT_AUTH_OPTIONS$1), authOptions),
realtime: _objectSpread2(_objectSpread2({}, DEFAULT_REALTIME_OPTIONS$1), realtimeOptions),
storage: {},
global: _objectSpread2(_objectSpread2(_objectSpread2({}, DEFAULT_GLOBAL_OPTIONS$1), globalOptions), {}, { headers: _objectSpread2(_objectSpread2({}, (_DEFAULT_GLOBAL_OPTIO = DEFAULT_GLOBAL_OPTIONS$1 === null || DEFAULT_GLOBAL_OPTIONS$1 === void 0 ? void 0 : DEFAULT_GLOBAL_OPTIONS$1.headers) !== null && _DEFAULT_GLOBAL_OPTIO !== void 0 ? _DEFAULT_GLOBAL_OPTIO : {}), (_globalOptions$header = globalOptions === null || globalOptions === void 0 ? void 0 : globalOptions.headers) !== null && _globalOptions$header !== void 0 ? _globalOptions$header : {}) }),
accessToken: async () => ""
};
if (options.accessToken) result.accessToken = options.accessToken;
else delete result.accessToken;
return result;
}
/**
* Validates a Supabase client URL
*
* @param {string} supabaseUrl - The Supabase client URL string.
* @returns {URL} - The validated base URL.
* @throws {Error}
*/
function validateSupabaseUrl(supabaseUrl) {
const trimmedUrl = supabaseUrl === null || supabaseUrl === void 0 ? void 0 : supabaseUrl.trim();
if (!trimmedUrl) throw new Error("supabaseUrl is required.");
if (!trimmedUrl.match(/^https?:\/\//i)) throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");
try {
return new URL(ensureTrailingSlash(trimmedUrl));
} catch (_unused) {
throw Error("Invalid supabaseUrl: Provided URL is malformed.");
}
}
//#endregion
//#region src/lib/SupabaseAuthClient.ts
var SupabaseAuthClient = class extends AuthClient {
constructor(options) {
super(options);
}
};
//#endregion
//#region src/SupabaseClient.ts
/**
* Supabase Client.
*
* An isomorphic Javascript client for interacting with Postgres.
*/
var SupabaseClient = class {
/**
* Create a new client for use in the browser.
*
* @category Initializing
*
* @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard.
* @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard.
* @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase.
* @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring.
* @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage.
* @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user.
* @param options.realtime Options passed along to realtime-js constructor.
* @param options.storage Options passed along to the storage-js constructor.
* @param options.global.fetch A custom fetch implementation.
* @param options.global.headers Any additional headers to send with each network request.
*
* @example Creating a client
* ```js
* import { createClient } from '@supabase/supabase-js'
*
* // Create a single supabase client for interacting with your database
* const supabase = createClient('https://xyzcompany.supabase.co', 'publishable-or-anon-key')
* ```
*
* @example With a custom domain
* ```js
* import { createClient } from '@supabase/supabase-js'
*
* // Use a custom domain as the supabase URL
* const supabase = createClient('https://my-custom-domain.com', 'publishable-or-anon-key')
* ```
*
* @example With additional parameters
* ```js
* import { createClient } from '@supabase/supabase-js'
*
* const options = {
* db: {
* schema: 'public',
* },
* auth: {
* autoRefreshToken: true,
* persistSession: true,
* detectSessionInUrl: true
* },
* global: {
* headers: { 'x-my-custom-header': 'my-app-name' },
* },
* }
* const supabase = createClient("https://xyzcompany.supabase.co", "publishable-or-anon-key", options)
* ```
*
* @exampleDescription With custom schemas
* By default the API server points to the `public` schema. You can enable other database schemas within the Dashboard.
* Go to [Settings > API > Exposed schemas](/dashboard/project/_/settings/api) and add the schema which you want to expose to the API.
*
* Note: each client connection can only access a single schema, so the code above can access the `other_schema` schema but cannot access the `public` schema.
*
* @example With custom schemas
* ```js
* import { createClient } from '@supabase/supabase-js'
*
* const supabase = createClient('https://xyzcompany.supabase.co', 'publishable-or-anon-key', {
* // Provide a custom schema. Defaults to "public".
* db: { schema: 'other_schema' }
* })
* ```
*
* @exampleDescription Custom fetch implementation
* `supabase-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).
*
* @example Custom fetch implementation
* ```js
* import { createClient } from '@supabase/supabase-js'
*
* const supabase = createClient('https://xyzcompany.supabase.co', 'publishable-or-anon-key', {
* global: { fetch: fetch.bind(globalThis) }
* })
* ```
*
* @exampleDescription React Native options with AsyncStorage
* For React Native we recommend using `AsyncStorage` as the storage implementation for Supabase Auth.
*
* @example React Native options with AsyncStorage
* ```js
* import 'react-native-url-polyfill/auto'
* import { createClient } from '@supabase/supabase-js'
* import AsyncStorage from "@react-native-async-storage/async-storage";
*
* const supabase = createClient("https://xyzcompany.supabase.co", "publishable-or-anon-key", {
* auth: {
* storage: AsyncStorage,
* autoRefreshToken: true,
* persistSession: true,
* detectSessionInUrl: false,
* },
* });
* ```
*
* @exampleDescription React Native options with Expo SecureStore
* If you wish to encrypt the user's session information, you can use `aes-js` and store the encryption key in Expo SecureStore.
* The `aes-js` library, a reputable JavaScript-only implementation of the AES encryption algorithm in CTR mode.
* A new 256-bit encryption key is generated using the `react-native-get-random-values` library.
* This key is stored inside Expo's SecureStore, while the value is encrypted and placed inside AsyncStorage.
*
* Please make sure that:
* - You keep the `expo-secure-store`, `aes-js` and `react-native-get-random-values` libraries up-to-date.
* - Choose the correct [`SecureStoreOptions`](https://docs.expo.dev/versions/latest/sdk/securestore/#securestoreoptions) for your app's needs.
* E.g. [`SecureStore.WHEN_UNLOCKED`](https://docs.expo.dev/versions/latest/sdk/securestore/#securestorewhen_unlocked) regulates when the data can be accessed.
* - Carefully consider optimizations or other modifications to the above example, as those can lead to introducing subtle security vulnerabilities.
*
* @example React Native options with Expo SecureStore
* ```ts
* import 'react-native-url-polyfill/auto'
* import { createClient } from '@supabase/supabase-js'
* import AsyncStorage from '@react-native-async-storage/async-storage';
* import * as SecureStore from 'expo-secure-store';
* import * as aesjs from 'aes-js';
* import 'react-native-get-random-values';
*
* // As Expo's SecureStore does not support values larger than 2048
* // bytes, an AES-256 key is generated and stored in SecureStore, while
* // it is used to encrypt/decrypt values stored in AsyncStorage.
* class LargeSecureStore {
* private async _encrypt(key: string, value: string) {
* const encryptionKey = crypto.getRandomValues(new Uint8Array(256 / 8));
*
* const cipher = new aesjs.ModeOfOperation.ctr(encryptionKey, new aesjs.Counter(1));
* const encryptedBytes = cipher.encrypt(aesjs.utils.utf8.toBytes(value));
*
* await SecureStore.setItemAsync(key, aesjs.utils.hex.fromBytes(encryptionKey));
*
* return aesjs.utils.hex.fromBytes(encryptedBytes);
* }
*
* private async _decrypt(key: string, value: string) {
* const encryptionKeyHex = await SecureStore.getItemAsync(key);
* if (!encryptionKeyHex) {
* return encryptionKeyHex;
* }
*
* const cipher = new aesjs.ModeOfOperation.ctr(aesjs.utils.hex.toBytes(encryptionKeyHex), new aesjs.Counter(1));
* const decryptedBytes = cipher.decrypt(aesjs.utils.hex.toBytes(value));
*
* return aesjs.utils.utf8.fromBytes(decryptedBytes);
* }
*
* async getItem(key: string) {
* const encrypted = await AsyncStorage.getItem(key);
* if (!encrypted) { return encrypted; }
*
* return await this._decrypt(key, encrypted);
* }
*
* async removeItem(key: string) {
* await AsyncStorage.removeItem(key);
* await SecureStore.deleteItemAsync(key);
* }
*
* async setItem(key: string, value: string) {
* const encrypted = await this._encrypt(key, value);
*
* await AsyncStorage.setItem(key, encrypted);
* }
* }
*
* const supabase = createClient("https://xyzcompany.supabase.co", "publishable-or-anon-key", {
* auth: {
* storage: new LargeSecureStore(),
* autoRefreshToken: true,
* persistSession: true,
* detectSessionInUrl: false,
* },
* });
* ```
*
* @example With a database query
* ```ts
* import { createClient } from '@supabase/supabase-js'
*
* const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key')
*
* const { data } = await supabase.from('profiles').select('*')
* ```
*/
constructor(supabaseUrl, supabaseKey, options) {
var _settings$auth$storag, _settings$global$head;
this.supabaseUrl = supabaseUrl;
this.supabaseKey = supabaseKey;
const baseUrl = validateSupabaseUrl(supabaseUrl);
if (!supabaseKey) throw new Error("supabaseKey is required.");
this.realtimeUrl = new URL("realtime/v1", baseUrl);
this.realtimeUrl.protocol = this.realtimeUrl.protocol.replace("http", "ws");
this.authUrl = new URL("auth/v1", baseUrl);
this.storageUrl = new URL("storage/v1", baseUrl);
this.functionsUrl = new URL("functions/v1", baseUrl);
const defaultStorageKey = `sb-${baseUrl.hostname.split(".")[0]}-auth-token`;
const DEFAULTS = {
db: DEFAULT_DB_OPTIONS,
realtime: DEFAULT_REALTIME_OPTIONS,
auth: _objectSpread2(_objectSpread2({}, DEFAULT_AUTH_OPTIONS), {}, { storageKey: defaultStorageKey }),
global: DEFAULT_GLOBAL_OPTIONS
};
const settings = applySettingDefaults(options !== null && options !== void 0 ? options : {}, DEFAULTS);
this.storageKey = (_settings$auth$storag = settings.auth.storageKey) !== null && _settings$auth$storag !== void 0 ? _settings$auth$storag : "";
this.headers = (_settings$global$head = settings.global.headers) !== null && _settings$global$head !== void 0 ? _settings$global$head : {};
if (!settings.accessToken) {
var _settings$auth;
this.auth = this._initSupabaseAuthClient((_settings$auth = settings.auth) !== null && _settings$auth !== void 0 ? _settings$auth : {}, this.headers, settings.global.fetch);
} else {
this.accessToken = settings.accessToken;
this.auth = new Proxy({}, { get: (_, prop) => {
throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(prop)} is not possible`);
} });
}
this.fetch = fetchWithAuth(supabaseKey, this._getAccessToken.bind(this), settings.global.fetch);
this.realtime = this._initRealtimeClient(_objectSpread2({
headers: this.headers,
accessToken: this._getAccessToken.bind(this)
}, settings.realtime));
if (this.accessToken) Promise.resolve(this.accessToken()).then((token) => this.realtime.setAuth(token)).catch((e) => console.warn("Failed to set initial Realtime auth token:", e));
this.rest = new PostgrestClient(new URL("rest/v1", baseUrl).href, {
headers: this.headers,
schema: settings.db.schema,
fetch: this.fetch,
timeout: settings.db.timeout,
urlLengthLimit: settings.db.urlLengthLimit
});
this.storage = new StorageClient(this.storageUrl.href, this.headers, this.fetch, options === null || options === void 0 ? void 0 : options.storage);
if (!settings.accessToken) this._listenForAuthEvents();
}
/**
* Supabase Functions allows you to deploy and invoke edge functions.
*/
get functions() {
return new FunctionsClient(this.functionsUrl.href, {
headers: this.headers,
customFetch: this.fetch
});
}
/**
* Perform a query on a table or a view.
*
* @param relation - The table or view name to query
*/
from(relation) {
return this.rest.from(relation);
}
/**
* Select a schema to query or perform an function (rpc) call.
*
* The schema needs to be on the list of exposed schemas inside Supabase.
*
* @param schema - The schema to query
*/
schema(schema) {
return this.rest.schema(schema);
}
/**
* Perform a function call.
*
* @param fn - The function name to call
* @param args - The arguments to pass to the function call
* @param options - Named parameters
* @param options.head - When set to `true`, `data` will not be returned.
* Useful if you only need the count.
* @param options.get - When set to `true`, the function will be called with
* read-only access mode.
* @param options.count - Count algorithm to use to count rows returned by the
* function. Only applicable for [set-returning
* functions](https://www.postgresql.org/docs/current/functions-srf.html).
*
* `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the
* hood.
*
* `"planned"`: Approximated but fast count algorithm. Uses the Postgres
* statistics under the hood.
*
* `"estimated"`: Uses exact count for low numbers and planned count for high
* numbers.
*/
rpc(fn, args = {}, options = {
head: false,
get: false,
count: void 0
}) {
return this.rest.rpc(fn, args, options);
}
/**
* Creates a Realtime channel with Broadcast, Presence, and Postgres Changes.
*
* @param {string} name - The name of the Realtime channel.
* @param {Object} opts - The options to pass to the Realtime channel.
*
*/
channel(name, opts = { config: {} }) {
return this.realtime.channel(name, opts);
}
/**
* Returns all Realtime channels.
*/
getChannels() {
return this.realtime.getChannels();
}
/**
* Unsubscribes and removes Realtime channel from Realtime client.
*
* @param {RealtimeChannel} channel - The name of the Realtime channel.
*
*/
removeChannel(channel) {
return this.realtime.removeChannel(channel);
}
/**
* Unsubscribes and removes all Realtime channels from Realtime client.
*/
removeAllChannels() {
return this.realtime.removeAllChannels();
}
async _getAccessToken() {
var _this = this;
var _data$session$access_, _data$session;
if (_this.accessToken) return await _this.accessToken();
const { data } = await _this.auth.getSession();
return (_data$session$access_ = (_data$session = data.session) === null || _data$session === void 0 ? void 0 : _data$session.access_token) !== null && _data$session$access_ !== void 0 ? _data$session$access_ : _this.supabaseKey;
}
_initSupabaseAuthClient({ autoRefreshToken, persistSession, detectSessionInUrl, storage, userStorage, storageKey, flowType, lock, debug, throwOnError }, headers, fetch$1) {
const authHeaders = {
Authorization: `Bearer ${this.supabaseKey}`,
apikey: `${this.supabaseKey}`
};
return new SupabaseAuthClient({
url: this.authUrl.href,
headers: _objectSpread2(_objectSpread2({}, authHeaders), headers),
storageKey,
autoRefreshToken,
persistSession,
detectSessionInUrl,
storage,
userStorage,
flowType,
lock,
debug,
throwOnError,
fetch: fetch$1,
hasCustomAuthorizationHeader: Object.keys(this.headers).some((key) => key.toLowerCase() === "authorization")
});
}
_initRealtimeClient(options) {
return new RealtimeClient(this.realtimeUrl.href, _objectSpread2(_objectSpread2({}, options), {}, { params: _objectSpread2(_objectSpread2({}, { apikey: this.supabaseKey }), options === null || options === void 0 ? void 0 : options.params) }));
}
_listenForAuthEvents() {
return this.auth.onAuthStateChange((event, session) => {
this._handleTokenChanged(event, "CLIENT", session === null || session === void 0 ? void 0 : session.access_token);
});
}
_handleTokenChanged(event, source, token) {
if ((event === "TOKEN_REFRESHED" || event === "SIGNED_IN") && this.changedAccessToken !== token) {
this.changedAccessToken = token;
this.realtime.setAuth(token);
} else if (event === "SIGNED_OUT") {
this.realtime.setAuth();
if (source == "STORAGE") this.auth.signOut();
this.changedAccessToken = void 0;
}
}
};
//#endregion
//#region src/index.ts
/**
* Creates a new Supabase Client.
*
* @example
* ```ts
* import { createClient } from '@supabase/supabase-js'
*
* const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key')
* const { data, error } = await supabase.from('profiles').select('*')
* ```
*/
const createClient = (supabaseUrl, supabaseKey, options) => {
return new SupabaseClient(supabaseUrl, supabaseKey, options);
};
function shouldShowDeprecationWarning() {
if (typeof window !== "undefined") return false;
const _process = globalThis["process"];
if (!_process) return false;
const processVersion = _process["version"];
if (processVersion === void 0 || processVersion === null) return false;
const versionMatch = processVersion.match(/^v(\d+)\./);
if (!versionMatch) return false;
return parseInt(versionMatch[1], 10) <= 18;
}
if (shouldShowDeprecationWarning()) console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");
//#endregion
export { FunctionRegion, FunctionsError, FunctionsFetchError, FunctionsHttpError, FunctionsRelayError, PostgrestError, SupabaseClient, createClient };
//# sourceMappingURL=index.mjs.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long