fix price and modular
This commit is contained in:
+2
-4
@@ -1,9 +1,7 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const GoTrueAdminApi_1 = __importDefault(require("./GoTrueAdminApi"));
|
||||
const tslib_1 = require("tslib");
|
||||
const GoTrueAdminApi_1 = tslib_1.__importDefault(require("./GoTrueAdminApi"));
|
||||
const AuthAdminApi = GoTrueAdminApi_1.default;
|
||||
exports.default = AuthAdminApi;
|
||||
//# sourceMappingURL=AuthAdminApi.js.map
|
||||
+2
-4
@@ -1,9 +1,7 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const GoTrueClient_1 = __importDefault(require("./GoTrueClient"));
|
||||
const tslib_1 = require("tslib");
|
||||
const GoTrueClient_1 = tslib_1.__importDefault(require("./GoTrueClient"));
|
||||
const AuthClient = GoTrueClient_1.default;
|
||||
exports.default = AuthClient;
|
||||
//# sourceMappingURL=AuthClient.js.map
|
||||
+176
-13
@@ -1,21 +1,24 @@
|
||||
"use strict";
|
||||
var __rest = (this && this.__rest) || function (s, e) {
|
||||
var t = {};
|
||||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
||||
t[p] = s[p];
|
||||
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
||||
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
||||
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
||||
t[p[i]] = s[p[i]];
|
||||
}
|
||||
return t;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const tslib_1 = require("tslib");
|
||||
const fetch_1 = require("./lib/fetch");
|
||||
const helpers_1 = require("./lib/helpers");
|
||||
const types_1 = require("./lib/types");
|
||||
const errors_1 = require("./lib/errors");
|
||||
class GoTrueAdminApi {
|
||||
/**
|
||||
* Creates an admin API client that can be used to manage users and OAuth clients.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { GoTrueAdminApi } from '@supabase/auth-js'
|
||||
*
|
||||
* const admin = new GoTrueAdminApi({
|
||||
* url: 'https://xyzcompany.supabase.co/auth/v1',
|
||||
* headers: { Authorization: `Bearer ${process.env.SUPABASE_SERVICE_ROLE_KEY}` },
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
constructor({ url = '', headers = {}, fetch, }) {
|
||||
this.url = url;
|
||||
this.headers = headers;
|
||||
@@ -24,6 +27,14 @@ class GoTrueAdminApi {
|
||||
listFactors: this._listFactors.bind(this),
|
||||
deleteFactor: this._deleteFactor.bind(this),
|
||||
};
|
||||
this.oauth = {
|
||||
listClients: this._listOAuthClients.bind(this),
|
||||
createClient: this._createOAuthClient.bind(this),
|
||||
getClient: this._getOAuthClient.bind(this),
|
||||
updateClient: this._updateOAuthClient.bind(this),
|
||||
deleteClient: this._deleteOAuthClient.bind(this),
|
||||
regenerateClientSecret: this._regenerateOAuthClientSecret.bind(this),
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Removes a logged-in session.
|
||||
@@ -79,7 +90,7 @@ class GoTrueAdminApi {
|
||||
*/
|
||||
async generateLink(params) {
|
||||
try {
|
||||
const { options } = params, rest = __rest(params, ["options"]);
|
||||
const { options } = params, rest = tslib_1.__rest(params, ["options"]);
|
||||
const body = Object.assign(Object.assign({}, rest), options);
|
||||
if ('newEmail' in rest) {
|
||||
// replace newEmail with new_email in request body
|
||||
@@ -190,7 +201,7 @@ class GoTrueAdminApi {
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Updates the user data.
|
||||
* Updates the user data. Changes are applied directly without confirmation flows.
|
||||
*
|
||||
* @param attributes The data you want to update.
|
||||
*
|
||||
@@ -273,6 +284,158 @@ class GoTrueAdminApi {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Lists all OAuth clients with optional pagination.
|
||||
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
async _listOAuthClients(params) {
|
||||
var _a, _b, _c, _d, _e, _f, _g;
|
||||
try {
|
||||
const pagination = { nextPage: null, lastPage: 0, total: 0 };
|
||||
const response = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/oauth/clients`, {
|
||||
headers: this.headers,
|
||||
noResolveJson: true,
|
||||
query: {
|
||||
page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '',
|
||||
per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '',
|
||||
},
|
||||
xform: fetch_1._noResolveJsonResponse,
|
||||
});
|
||||
if (response.error)
|
||||
throw response.error;
|
||||
const clients = await response.json();
|
||||
const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0;
|
||||
const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : [];
|
||||
if (links.length > 0) {
|
||||
links.forEach((link) => {
|
||||
const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1));
|
||||
const rel = JSON.parse(link.split(';')[1].split('=')[1]);
|
||||
pagination[`${rel}Page`] = page;
|
||||
});
|
||||
pagination.total = parseInt(total);
|
||||
}
|
||||
return { data: Object.assign(Object.assign({}, clients), pagination), error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: { clients: [] }, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Creates a new OAuth client.
|
||||
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
async _createOAuthClient(params) {
|
||||
try {
|
||||
return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/oauth/clients`, {
|
||||
body: params,
|
||||
headers: this.headers,
|
||||
xform: (client) => {
|
||||
return { data: client, error: null };
|
||||
},
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Gets details of a specific OAuth client.
|
||||
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
async _getOAuthClient(clientId) {
|
||||
try {
|
||||
return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/oauth/clients/${clientId}`, {
|
||||
headers: this.headers,
|
||||
xform: (client) => {
|
||||
return { data: client, error: null };
|
||||
},
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Updates an existing OAuth client.
|
||||
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
async _updateOAuthClient(clientId, params) {
|
||||
try {
|
||||
return await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/admin/oauth/clients/${clientId}`, {
|
||||
body: params,
|
||||
headers: this.headers,
|
||||
xform: (client) => {
|
||||
return { data: client, error: null };
|
||||
},
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Deletes an OAuth client.
|
||||
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
async _deleteOAuthClient(clientId) {
|
||||
try {
|
||||
await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/oauth/clients/${clientId}`, {
|
||||
headers: this.headers,
|
||||
noResolveJson: true,
|
||||
});
|
||||
return { data: null, error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Regenerates the secret for an OAuth client.
|
||||
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
async _regenerateOAuthClientSecret(clientId) {
|
||||
try {
|
||||
return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/oauth/clients/${clientId}/regenerate_secret`, {
|
||||
headers: this.headers,
|
||||
xform: (client) => {
|
||||
return { data: client, error: null };
|
||||
},
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.default = GoTrueAdminApi;
|
||||
//# sourceMappingURL=GoTrueAdminApi.js.map
|
||||
+705
-220
File diff suppressed because it is too large
Load Diff
+7
-23
@@ -1,33 +1,17 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.processLock = exports.lockInternals = exports.NavigatorLockAcquireTimeoutError = exports.navigatorLock = exports.AuthClient = exports.AuthAdminApi = exports.GoTrueClient = exports.GoTrueAdminApi = void 0;
|
||||
const GoTrueAdminApi_1 = __importDefault(require("./GoTrueAdminApi"));
|
||||
const tslib_1 = require("tslib");
|
||||
const GoTrueAdminApi_1 = tslib_1.__importDefault(require("./GoTrueAdminApi"));
|
||||
exports.GoTrueAdminApi = GoTrueAdminApi_1.default;
|
||||
const GoTrueClient_1 = __importDefault(require("./GoTrueClient"));
|
||||
const GoTrueClient_1 = tslib_1.__importDefault(require("./GoTrueClient"));
|
||||
exports.GoTrueClient = GoTrueClient_1.default;
|
||||
const AuthAdminApi_1 = __importDefault(require("./AuthAdminApi"));
|
||||
const AuthAdminApi_1 = tslib_1.__importDefault(require("./AuthAdminApi"));
|
||||
exports.AuthAdminApi = AuthAdminApi_1.default;
|
||||
const AuthClient_1 = __importDefault(require("./AuthClient"));
|
||||
const AuthClient_1 = tslib_1.__importDefault(require("./AuthClient"));
|
||||
exports.AuthClient = AuthClient_1.default;
|
||||
__exportStar(require("./lib/types"), exports);
|
||||
__exportStar(require("./lib/errors"), exports);
|
||||
tslib_1.__exportStar(require("./lib/types"), exports);
|
||||
tslib_1.__exportStar(require("./lib/errors"), exports);
|
||||
var locks_1 = require("./lib/locks");
|
||||
Object.defineProperty(exports, "navigatorLock", { enumerable: true, get: function () { return locks_1.navigatorLock; } });
|
||||
Object.defineProperty(exports, "NavigatorLockAcquireTimeoutError", { enumerable: true, get: function () { return locks_1.NavigatorLockAcquireTimeoutError; } });
|
||||
|
||||
+10
-11
@@ -5,7 +5,16 @@
|
||||
* that repo!
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.bytesToBase64URL = exports.stringToUint8Array = exports.base64UrlToUint8Array = exports.stringFromUTF8 = exports.stringToUTF8 = exports.codepointToUTF8 = exports.stringFromBase64URL = exports.stringToBase64URL = exports.byteFromBase64URL = exports.byteToBase64URL = void 0;
|
||||
exports.byteToBase64URL = byteToBase64URL;
|
||||
exports.byteFromBase64URL = byteFromBase64URL;
|
||||
exports.stringToBase64URL = stringToBase64URL;
|
||||
exports.stringFromBase64URL = stringFromBase64URL;
|
||||
exports.codepointToUTF8 = codepointToUTF8;
|
||||
exports.stringToUTF8 = stringToUTF8;
|
||||
exports.stringFromUTF8 = stringFromUTF8;
|
||||
exports.base64UrlToUint8Array = base64UrlToUint8Array;
|
||||
exports.stringToUint8Array = stringToUint8Array;
|
||||
exports.bytesToBase64URL = bytesToBase64URL;
|
||||
/**
|
||||
* An array of characters that encode 6 bits into a Base64-URL alphabet
|
||||
* character.
|
||||
@@ -60,7 +69,6 @@ function byteToBase64URL(byte, state, emit) {
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.byteToBase64URL = byteToBase64URL;
|
||||
/**
|
||||
* Converts a String char code (extracted using `string.charCodeAt(position)`) to a sequence of Base64-URL characters.
|
||||
*
|
||||
@@ -87,7 +95,6 @@ function byteFromBase64URL(charCode, state, emit) {
|
||||
throw new Error(`Invalid Base64-URL character "${String.fromCharCode(charCode)}"`);
|
||||
}
|
||||
}
|
||||
exports.byteFromBase64URL = byteFromBase64URL;
|
||||
/**
|
||||
* Converts a JavaScript string (which may include any valid character) into a
|
||||
* Base64-URL encoded string. The string is first encoded in UTF-8 which is
|
||||
@@ -107,7 +114,6 @@ function stringToBase64URL(str) {
|
||||
byteToBase64URL(null, state, emitter);
|
||||
return base64.join('');
|
||||
}
|
||||
exports.stringToBase64URL = stringToBase64URL;
|
||||
/**
|
||||
* Converts a Base64-URL encoded string into a JavaScript string. It is assumed
|
||||
* that the underlying string has been encoded as UTF-8.
|
||||
@@ -132,7 +138,6 @@ function stringFromBase64URL(str) {
|
||||
}
|
||||
return conv.join('');
|
||||
}
|
||||
exports.stringFromBase64URL = stringFromBase64URL;
|
||||
/**
|
||||
* Converts a Unicode codepoint to a multi-byte UTF-8 sequence.
|
||||
*
|
||||
@@ -164,7 +169,6 @@ function codepointToUTF8(codepoint, emit) {
|
||||
}
|
||||
throw new Error(`Unrecognized Unicode codepoint: ${codepoint.toString(16)}`);
|
||||
}
|
||||
exports.codepointToUTF8 = codepointToUTF8;
|
||||
/**
|
||||
* Converts a JavaScript string to a sequence of UTF-8 bytes.
|
||||
*
|
||||
@@ -186,7 +190,6 @@ function stringToUTF8(str, emit) {
|
||||
codepointToUTF8(codepoint, emit);
|
||||
}
|
||||
}
|
||||
exports.stringToUTF8 = stringToUTF8;
|
||||
/**
|
||||
* Converts a UTF-8 byte to a Unicode codepoint.
|
||||
*
|
||||
@@ -233,7 +236,6 @@ function stringFromUTF8(byte, state, emit) {
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.stringFromUTF8 = stringFromUTF8;
|
||||
/**
|
||||
* Helper functions to convert different types of strings to Uint8Array
|
||||
*/
|
||||
@@ -248,13 +250,11 @@ function base64UrlToUint8Array(str) {
|
||||
}
|
||||
return new Uint8Array(result);
|
||||
}
|
||||
exports.base64UrlToUint8Array = base64UrlToUint8Array;
|
||||
function stringToUint8Array(str) {
|
||||
const result = [];
|
||||
stringToUTF8(str, (byte) => result.push(byte));
|
||||
return new Uint8Array(result);
|
||||
}
|
||||
exports.stringToUint8Array = stringToUint8Array;
|
||||
function bytesToBase64URL(bytes) {
|
||||
const result = [];
|
||||
const state = { queue: 0, queuedBits: 0 };
|
||||
@@ -266,5 +266,4 @@ function bytesToBase64URL(bytes) {
|
||||
byteToBase64URL(null, state, onChar);
|
||||
return result.join('');
|
||||
}
|
||||
exports.bytesToBase64URL = bytesToBase64URL;
|
||||
//# sourceMappingURL=base64url.js.map
|
||||
+159
-7
@@ -1,6 +1,23 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.AuthInvalidJwtError = exports.isAuthWeakPasswordError = exports.AuthWeakPasswordError = exports.isAuthRetryableFetchError = exports.AuthRetryableFetchError = exports.AuthPKCEGrantCodeExchangeError = exports.isAuthImplicitGrantRedirectError = exports.AuthImplicitGrantRedirectError = exports.AuthInvalidCredentialsError = exports.AuthInvalidTokenResponseError = exports.isAuthSessionMissingError = exports.AuthSessionMissingError = exports.CustomAuthError = exports.AuthUnknownError = exports.isAuthApiError = exports.AuthApiError = exports.isAuthError = exports.AuthError = void 0;
|
||||
exports.AuthInvalidJwtError = exports.AuthWeakPasswordError = exports.AuthRetryableFetchError = exports.AuthPKCECodeVerifierMissingError = exports.AuthPKCEGrantCodeExchangeError = exports.AuthImplicitGrantRedirectError = exports.AuthInvalidCredentialsError = exports.AuthInvalidTokenResponseError = exports.AuthSessionMissingError = exports.CustomAuthError = exports.AuthUnknownError = exports.AuthApiError = exports.AuthError = void 0;
|
||||
exports.isAuthError = isAuthError;
|
||||
exports.isAuthApiError = isAuthApiError;
|
||||
exports.isAuthSessionMissingError = isAuthSessionMissingError;
|
||||
exports.isAuthImplicitGrantRedirectError = isAuthImplicitGrantRedirectError;
|
||||
exports.isAuthPKCECodeVerifierMissingError = isAuthPKCECodeVerifierMissingError;
|
||||
exports.isAuthRetryableFetchError = isAuthRetryableFetchError;
|
||||
exports.isAuthWeakPasswordError = isAuthWeakPasswordError;
|
||||
/**
|
||||
* Base error thrown by Supabase Auth helpers.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { AuthError } from '@supabase/auth-js'
|
||||
*
|
||||
* throw new AuthError('Unexpected auth error', 500, 'unexpected')
|
||||
* ```
|
||||
*/
|
||||
class AuthError extends Error {
|
||||
constructor(message, status, code) {
|
||||
super(message);
|
||||
@@ -14,7 +31,16 @@ exports.AuthError = AuthError;
|
||||
function isAuthError(error) {
|
||||
return typeof error === 'object' && error !== null && '__isAuthError' in error;
|
||||
}
|
||||
exports.isAuthError = isAuthError;
|
||||
/**
|
||||
* Error returned directly from the GoTrue REST API.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { AuthApiError } from '@supabase/auth-js'
|
||||
*
|
||||
* throw new AuthApiError('Invalid credentials', 400, 'invalid_credentials')
|
||||
* ```
|
||||
*/
|
||||
class AuthApiError extends AuthError {
|
||||
constructor(message, status, code) {
|
||||
super(message, status, code);
|
||||
@@ -27,7 +53,20 @@ exports.AuthApiError = AuthApiError;
|
||||
function isAuthApiError(error) {
|
||||
return isAuthError(error) && error.name === 'AuthApiError';
|
||||
}
|
||||
exports.isAuthApiError = isAuthApiError;
|
||||
/**
|
||||
* Wraps non-standard errors so callers can inspect the root cause.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { AuthUnknownError } from '@supabase/auth-js'
|
||||
*
|
||||
* try {
|
||||
* await someAuthCall()
|
||||
* } catch (err) {
|
||||
* throw new AuthUnknownError('Auth failed', err)
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
class AuthUnknownError extends AuthError {
|
||||
constructor(message, originalError) {
|
||||
super(message);
|
||||
@@ -36,6 +75,16 @@ class AuthUnknownError extends AuthError {
|
||||
}
|
||||
}
|
||||
exports.AuthUnknownError = AuthUnknownError;
|
||||
/**
|
||||
* Flexible error class used to create named auth errors at runtime.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { CustomAuthError } from '@supabase/auth-js'
|
||||
*
|
||||
* throw new CustomAuthError('My custom auth error', 'MyAuthError', 400, 'custom_code')
|
||||
* ```
|
||||
*/
|
||||
class CustomAuthError extends AuthError {
|
||||
constructor(message, name, status, code) {
|
||||
super(message, status, code);
|
||||
@@ -44,6 +93,16 @@ class CustomAuthError extends AuthError {
|
||||
}
|
||||
}
|
||||
exports.CustomAuthError = CustomAuthError;
|
||||
/**
|
||||
* Error thrown when an operation requires a session but none is present.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { AuthSessionMissingError } from '@supabase/auth-js'
|
||||
*
|
||||
* throw new AuthSessionMissingError()
|
||||
* ```
|
||||
*/
|
||||
class AuthSessionMissingError extends CustomAuthError {
|
||||
constructor() {
|
||||
super('Auth session missing!', 'AuthSessionMissingError', 400, undefined);
|
||||
@@ -53,19 +112,51 @@ exports.AuthSessionMissingError = AuthSessionMissingError;
|
||||
function isAuthSessionMissingError(error) {
|
||||
return isAuthError(error) && error.name === 'AuthSessionMissingError';
|
||||
}
|
||||
exports.isAuthSessionMissingError = isAuthSessionMissingError;
|
||||
/**
|
||||
* Error thrown when the token response is malformed.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { AuthInvalidTokenResponseError } from '@supabase/auth-js'
|
||||
*
|
||||
* throw new AuthInvalidTokenResponseError()
|
||||
* ```
|
||||
*/
|
||||
class AuthInvalidTokenResponseError extends CustomAuthError {
|
||||
constructor() {
|
||||
super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500, undefined);
|
||||
}
|
||||
}
|
||||
exports.AuthInvalidTokenResponseError = AuthInvalidTokenResponseError;
|
||||
/**
|
||||
* Error thrown when email/password credentials are invalid.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { AuthInvalidCredentialsError } from '@supabase/auth-js'
|
||||
*
|
||||
* throw new AuthInvalidCredentialsError('Email or password is incorrect')
|
||||
* ```
|
||||
*/
|
||||
class AuthInvalidCredentialsError extends CustomAuthError {
|
||||
constructor(message) {
|
||||
super(message, 'AuthInvalidCredentialsError', 400, undefined);
|
||||
}
|
||||
}
|
||||
exports.AuthInvalidCredentialsError = AuthInvalidCredentialsError;
|
||||
/**
|
||||
* Error thrown when implicit grant redirects contain an error.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { AuthImplicitGrantRedirectError } from '@supabase/auth-js'
|
||||
*
|
||||
* throw new AuthImplicitGrantRedirectError('OAuth redirect failed', {
|
||||
* error: 'access_denied',
|
||||
* code: 'oauth_error',
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
class AuthImplicitGrantRedirectError extends CustomAuthError {
|
||||
constructor(message, details = null) {
|
||||
super(message, 'AuthImplicitGrantRedirectError', 500, undefined);
|
||||
@@ -85,7 +176,16 @@ exports.AuthImplicitGrantRedirectError = AuthImplicitGrantRedirectError;
|
||||
function isAuthImplicitGrantRedirectError(error) {
|
||||
return isAuthError(error) && error.name === 'AuthImplicitGrantRedirectError';
|
||||
}
|
||||
exports.isAuthImplicitGrantRedirectError = isAuthImplicitGrantRedirectError;
|
||||
/**
|
||||
* Error thrown during PKCE code exchanges.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { AuthPKCEGrantCodeExchangeError } from '@supabase/auth-js'
|
||||
*
|
||||
* throw new AuthPKCEGrantCodeExchangeError('PKCE exchange failed')
|
||||
* ```
|
||||
*/
|
||||
class AuthPKCEGrantCodeExchangeError extends CustomAuthError {
|
||||
constructor(message, details = null) {
|
||||
super(message, 'AuthPKCEGrantCodeExchangeError', 500, undefined);
|
||||
@@ -102,6 +202,40 @@ class AuthPKCEGrantCodeExchangeError extends CustomAuthError {
|
||||
}
|
||||
}
|
||||
exports.AuthPKCEGrantCodeExchangeError = AuthPKCEGrantCodeExchangeError;
|
||||
/**
|
||||
* Error thrown when the PKCE code verifier is not found in storage.
|
||||
* This typically happens when the auth flow was initiated in a different
|
||||
* browser, device, or the storage was cleared.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { AuthPKCECodeVerifierMissingError } from '@supabase/auth-js'
|
||||
*
|
||||
* throw new AuthPKCECodeVerifierMissingError()
|
||||
* ```
|
||||
*/
|
||||
class AuthPKCECodeVerifierMissingError extends CustomAuthError {
|
||||
constructor() {
|
||||
super('PKCE code verifier not found in storage. ' +
|
||||
'This can happen if the auth flow was initiated in a different browser or device, ' +
|
||||
'or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), ' +
|
||||
'use @supabase/ssr on both the server and client to store the code verifier in cookies.', 'AuthPKCECodeVerifierMissingError', 400, 'pkce_code_verifier_not_found');
|
||||
}
|
||||
}
|
||||
exports.AuthPKCECodeVerifierMissingError = AuthPKCECodeVerifierMissingError;
|
||||
function isAuthPKCECodeVerifierMissingError(error) {
|
||||
return isAuthError(error) && error.name === 'AuthPKCECodeVerifierMissingError';
|
||||
}
|
||||
/**
|
||||
* Error thrown when a transient fetch issue occurs.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { AuthRetryableFetchError } from '@supabase/auth-js'
|
||||
*
|
||||
* throw new AuthRetryableFetchError('Service temporarily unavailable', 503)
|
||||
* ```
|
||||
*/
|
||||
class AuthRetryableFetchError extends CustomAuthError {
|
||||
constructor(message, status) {
|
||||
super(message, 'AuthRetryableFetchError', status, undefined);
|
||||
@@ -111,12 +245,21 @@ exports.AuthRetryableFetchError = AuthRetryableFetchError;
|
||||
function isAuthRetryableFetchError(error) {
|
||||
return isAuthError(error) && error.name === 'AuthRetryableFetchError';
|
||||
}
|
||||
exports.isAuthRetryableFetchError = isAuthRetryableFetchError;
|
||||
/**
|
||||
* This error is thrown on certain methods when the password used is deemed
|
||||
* weak. Inspect the reasons to identify what password strength rules are
|
||||
* inadequate.
|
||||
*/
|
||||
/**
|
||||
* Error thrown when a supplied password is considered weak.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { AuthWeakPasswordError } from '@supabase/auth-js'
|
||||
*
|
||||
* throw new AuthWeakPasswordError('Password too short', 400, ['min_length'])
|
||||
* ```
|
||||
*/
|
||||
class AuthWeakPasswordError extends CustomAuthError {
|
||||
constructor(message, status, reasons) {
|
||||
super(message, 'AuthWeakPasswordError', status, 'weak_password');
|
||||
@@ -127,7 +270,16 @@ exports.AuthWeakPasswordError = AuthWeakPasswordError;
|
||||
function isAuthWeakPasswordError(error) {
|
||||
return isAuthError(error) && error.name === 'AuthWeakPasswordError';
|
||||
}
|
||||
exports.isAuthWeakPasswordError = isAuthWeakPasswordError;
|
||||
/**
|
||||
* Error thrown when a JWT cannot be verified or parsed.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { AuthInvalidJwtError } from '@supabase/auth-js'
|
||||
*
|
||||
* throw new AuthInvalidJwtError('Token signature is invalid')
|
||||
* ```
|
||||
*/
|
||||
class AuthInvalidJwtError extends CustomAuthError {
|
||||
constructor(message) {
|
||||
super(message, 'AuthInvalidJwtError', 400, 'invalid_jwt');
|
||||
|
||||
+10
-21
@@ -1,17 +1,14 @@
|
||||
"use strict";
|
||||
var __rest = (this && this.__rest) || function (s, e) {
|
||||
var t = {};
|
||||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
||||
t[p] = s[p];
|
||||
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
||||
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
||||
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
||||
t[p[i]] = s[p[i]];
|
||||
}
|
||||
return t;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports._noResolveJsonResponse = exports._generateLinkResponse = exports._ssoResponse = exports._userResponse = exports._sessionResponsePassword = exports._sessionResponse = exports._request = exports.handleError = void 0;
|
||||
exports.handleError = handleError;
|
||||
exports._request = _request;
|
||||
exports._sessionResponse = _sessionResponse;
|
||||
exports._sessionResponsePassword = _sessionResponsePassword;
|
||||
exports._userResponse = _userResponse;
|
||||
exports._ssoResponse = _ssoResponse;
|
||||
exports._generateLinkResponse = _generateLinkResponse;
|
||||
exports._noResolveJsonResponse = _noResolveJsonResponse;
|
||||
const tslib_1 = require("tslib");
|
||||
const constants_1 = require("./constants");
|
||||
const helpers_1 = require("./helpers");
|
||||
const errors_1 = require("./errors");
|
||||
@@ -68,7 +65,6 @@ async function handleError(error) {
|
||||
}
|
||||
throw new errors_1.AuthApiError(_getErrorMessage(data), error.status || 500, errorCode);
|
||||
}
|
||||
exports.handleError = handleError;
|
||||
const _getRequestParams = (method, options, parameters, body) => {
|
||||
const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} };
|
||||
if (method === 'GET') {
|
||||
@@ -98,7 +94,6 @@ async function _request(fetcher, method, url, options) {
|
||||
}, {}, options === null || options === void 0 ? void 0 : options.body);
|
||||
return (options === null || options === void 0 ? void 0 : options.xform) ? options === null || options === void 0 ? void 0 : options.xform(data) : { data: Object.assign({}, data), error: null };
|
||||
}
|
||||
exports._request = _request;
|
||||
async function _handleRequest(fetcher, method, url, options, parameters, body) {
|
||||
const requestParams = _getRequestParams(method, options, parameters, body);
|
||||
let result;
|
||||
@@ -135,7 +130,6 @@ function _sessionResponse(data) {
|
||||
const user = (_a = data.user) !== null && _a !== void 0 ? _a : data;
|
||||
return { data: { session, user }, error: null };
|
||||
}
|
||||
exports._sessionResponse = _sessionResponse;
|
||||
function _sessionResponsePassword(data) {
|
||||
const response = _sessionResponse(data);
|
||||
if (!response.error &&
|
||||
@@ -150,19 +144,16 @@ function _sessionResponsePassword(data) {
|
||||
}
|
||||
return response;
|
||||
}
|
||||
exports._sessionResponsePassword = _sessionResponsePassword;
|
||||
function _userResponse(data) {
|
||||
var _a;
|
||||
const user = (_a = data.user) !== null && _a !== void 0 ? _a : data;
|
||||
return { data: { user }, error: null };
|
||||
}
|
||||
exports._userResponse = _userResponse;
|
||||
function _ssoResponse(data) {
|
||||
return { data, error: null };
|
||||
}
|
||||
exports._ssoResponse = _ssoResponse;
|
||||
function _generateLinkResponse(data) {
|
||||
const { action_link, email_otp, hashed_token, redirect_to, verification_type } = data, rest = __rest(data, ["action_link", "email_otp", "hashed_token", "redirect_to", "verification_type"]);
|
||||
const { action_link, email_otp, hashed_token, redirect_to, verification_type } = data, rest = tslib_1.__rest(data, ["action_link", "email_otp", "hashed_token", "redirect_to", "verification_type"]);
|
||||
const properties = {
|
||||
action_link,
|
||||
email_otp,
|
||||
@@ -179,11 +170,9 @@ function _generateLinkResponse(data) {
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
exports._generateLinkResponse = _generateLinkResponse;
|
||||
function _noResolveJsonResponse(data) {
|
||||
return data;
|
||||
}
|
||||
exports._noResolveJsonResponse = _noResolveJsonResponse;
|
||||
/**
|
||||
* hasSession checks if the response object contains a valid session
|
||||
* @param data A response object
|
||||
|
||||
+70
-53
@@ -1,29 +1,22 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.deepClone = exports.userNotAvailableProxy = exports.validateUUID = exports.getAlgorithm = exports.validateExp = exports.parseResponseAPIVersion = exports.getCodeChallengeAndMethod = exports.generatePKCEChallenge = exports.generatePKCEVerifier = exports.retryable = exports.sleep = exports.decodeJWT = exports.Deferred = exports.removeItemAsync = exports.getItemAsync = exports.setItemAsync = exports.looksLikeFetchResponse = exports.resolveFetch = exports.parseParametersFromURL = exports.supportsLocalStorage = exports.isBrowser = exports.uuid = exports.expiresAt = void 0;
|
||||
exports.Deferred = exports.removeItemAsync = exports.getItemAsync = exports.setItemAsync = exports.looksLikeFetchResponse = exports.resolveFetch = exports.supportsLocalStorage = exports.isBrowser = void 0;
|
||||
exports.expiresAt = expiresAt;
|
||||
exports.generateCallbackId = generateCallbackId;
|
||||
exports.parseParametersFromURL = parseParametersFromURL;
|
||||
exports.decodeJWT = decodeJWT;
|
||||
exports.sleep = sleep;
|
||||
exports.retryable = retryable;
|
||||
exports.generatePKCEVerifier = generatePKCEVerifier;
|
||||
exports.generatePKCEChallenge = generatePKCEChallenge;
|
||||
exports.getCodeChallengeAndMethod = getCodeChallengeAndMethod;
|
||||
exports.parseResponseAPIVersion = parseResponseAPIVersion;
|
||||
exports.validateExp = validateExp;
|
||||
exports.getAlgorithm = getAlgorithm;
|
||||
exports.validateUUID = validateUUID;
|
||||
exports.userNotAvailableProxy = userNotAvailableProxy;
|
||||
exports.insecureUserWarningProxy = insecureUserWarningProxy;
|
||||
exports.deepClone = deepClone;
|
||||
const constants_1 = require("./constants");
|
||||
const errors_1 = require("./errors");
|
||||
const base64url_1 = require("./base64url");
|
||||
@@ -31,14 +24,22 @@ function expiresAt(expiresIn) {
|
||||
const timeNow = Math.round(Date.now() / 1000);
|
||||
return timeNow + expiresIn;
|
||||
}
|
||||
exports.expiresAt = expiresAt;
|
||||
function uuid() {
|
||||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
|
||||
const r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8;
|
||||
return v.toString(16);
|
||||
});
|
||||
/**
|
||||
* Generates a unique identifier for internal callback subscriptions.
|
||||
*
|
||||
* This function uses JavaScript Symbols to create guaranteed-unique identifiers
|
||||
* for auth state change callbacks. Symbols are ideal for this use case because:
|
||||
* - They are guaranteed unique by the JavaScript runtime
|
||||
* - They work in all environments (browser, SSR, Node.js)
|
||||
* - They avoid issues with Next.js 16 deterministic rendering requirements
|
||||
* - They are perfect for internal, non-serializable identifiers
|
||||
*
|
||||
* Note: This function is only used for internal subscription management,
|
||||
* not for security-critical operations like session tokens.
|
||||
*/
|
||||
function generateCallbackId() {
|
||||
return Symbol('auth-callback');
|
||||
}
|
||||
exports.uuid = uuid;
|
||||
const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined';
|
||||
exports.isBrowser = isBrowser;
|
||||
const localStorageWriteTests = {
|
||||
@@ -103,19 +104,11 @@ function parseParametersFromURL(href) {
|
||||
});
|
||||
return result;
|
||||
}
|
||||
exports.parseParametersFromURL = parseParametersFromURL;
|
||||
const resolveFetch = (customFetch) => {
|
||||
let _fetch;
|
||||
if (customFetch) {
|
||||
_fetch = customFetch;
|
||||
return (...args) => customFetch(...args);
|
||||
}
|
||||
else if (typeof fetch === 'undefined') {
|
||||
_fetch = (...args) => Promise.resolve().then(() => __importStar(require('@supabase/node-fetch'))).then(({ default: fetch }) => fetch(...args));
|
||||
}
|
||||
else {
|
||||
_fetch = fetch;
|
||||
}
|
||||
return (...args) => _fetch(...args);
|
||||
return (...args) => fetch(...args);
|
||||
};
|
||||
exports.resolveFetch = resolveFetch;
|
||||
const looksLikeFetchResponse = (maybeResponse) => {
|
||||
@@ -191,7 +184,6 @@ function decodeJWT(token) {
|
||||
};
|
||||
return data;
|
||||
}
|
||||
exports.decodeJWT = decodeJWT;
|
||||
/**
|
||||
* Creates a promise that resolves to null after some time.
|
||||
*/
|
||||
@@ -200,7 +192,6 @@ async function sleep(time) {
|
||||
setTimeout(() => accept(null), time);
|
||||
});
|
||||
}
|
||||
exports.sleep = sleep;
|
||||
/**
|
||||
* Converts the provided async function into a retryable function. Each result
|
||||
* or thrown error is sent to the isRetryable function which should return true
|
||||
@@ -230,7 +221,6 @@ function retryable(fn, isRetryable) {
|
||||
});
|
||||
return promise;
|
||||
}
|
||||
exports.retryable = retryable;
|
||||
function dec2hex(dec) {
|
||||
return ('0' + dec.toString(16)).substr(-2);
|
||||
}
|
||||
@@ -250,7 +240,6 @@ function generatePKCEVerifier() {
|
||||
crypto.getRandomValues(array);
|
||||
return Array.from(array, dec2hex).join('');
|
||||
}
|
||||
exports.generatePKCEVerifier = generatePKCEVerifier;
|
||||
async function sha256(randomString) {
|
||||
const encoder = new TextEncoder();
|
||||
const encodedData = encoder.encode(randomString);
|
||||
@@ -271,7 +260,6 @@ async function generatePKCEChallenge(verifier) {
|
||||
const hashed = await sha256(verifier);
|
||||
return btoa(hashed).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
}
|
||||
exports.generatePKCEChallenge = generatePKCEChallenge;
|
||||
async function getCodeChallengeAndMethod(storage, storageKey, isPasswordRecovery = false) {
|
||||
const codeVerifier = generatePKCEVerifier();
|
||||
let storedCodeVerifier = codeVerifier;
|
||||
@@ -283,7 +271,6 @@ async function getCodeChallengeAndMethod(storage, storageKey, isPasswordRecovery
|
||||
const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256';
|
||||
return [codeChallenge, codeChallengeMethod];
|
||||
}
|
||||
exports.getCodeChallengeAndMethod = getCodeChallengeAndMethod;
|
||||
/** Parses the API version which is 2YYY-MM-DD. */
|
||||
const API_VERSION_REGEX = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;
|
||||
function parseResponseAPIVersion(response) {
|
||||
@@ -302,7 +289,6 @@ function parseResponseAPIVersion(response) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
exports.parseResponseAPIVersion = parseResponseAPIVersion;
|
||||
function validateExp(exp) {
|
||||
if (!exp) {
|
||||
throw new Error('Missing exp claim');
|
||||
@@ -312,7 +298,6 @@ function validateExp(exp) {
|
||||
throw new Error('JWT has expired');
|
||||
}
|
||||
}
|
||||
exports.validateExp = validateExp;
|
||||
function getAlgorithm(alg) {
|
||||
switch (alg) {
|
||||
case 'RS256':
|
||||
@@ -330,14 +315,12 @@ function getAlgorithm(alg) {
|
||||
throw new Error('Invalid alg claim');
|
||||
}
|
||||
}
|
||||
exports.getAlgorithm = getAlgorithm;
|
||||
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
||||
function validateUUID(str) {
|
||||
if (!UUID_REGEX.test(str)) {
|
||||
throw new Error('@supabase/auth-js: Expected parameter to be UUID but is not');
|
||||
}
|
||||
}
|
||||
exports.validateUUID = validateUUID;
|
||||
function userNotAvailableProxy() {
|
||||
const proxyTarget = {};
|
||||
return new Proxy(proxyTarget, {
|
||||
@@ -366,7 +349,42 @@ function userNotAvailableProxy() {
|
||||
},
|
||||
});
|
||||
}
|
||||
exports.userNotAvailableProxy = userNotAvailableProxy;
|
||||
/**
|
||||
* Creates a proxy around a user object that warns when properties are accessed on the server.
|
||||
* This is used to alert developers that using user data from getSession() on the server is insecure.
|
||||
*
|
||||
* @param user The actual user object to wrap
|
||||
* @param suppressWarningRef An object with a 'value' property that controls warning suppression
|
||||
* @returns A proxied user object that warns on property access
|
||||
*/
|
||||
function insecureUserWarningProxy(user, suppressWarningRef) {
|
||||
return new Proxy(user, {
|
||||
get: (target, prop, receiver) => {
|
||||
// Allow internal checks without warning
|
||||
if (prop === '__isInsecureUserWarningProxy') {
|
||||
return true;
|
||||
}
|
||||
// Preventative check for common problematic symbols during cloning/inspection
|
||||
// These symbols might be accessed by structuredClone or other internal mechanisms
|
||||
if (typeof prop === 'symbol') {
|
||||
const sProp = prop.toString();
|
||||
if (sProp === 'Symbol(Symbol.toPrimitive)' ||
|
||||
sProp === 'Symbol(Symbol.toStringTag)' ||
|
||||
sProp === 'Symbol(util.inspect.custom)' ||
|
||||
sProp === 'Symbol(nodejs.util.inspect.custom)') {
|
||||
// Return the actual value for these symbols to allow proper inspection
|
||||
return Reflect.get(target, prop, receiver);
|
||||
}
|
||||
}
|
||||
// Emit warning on first property access
|
||||
if (!suppressWarningRef.value && typeof prop === 'string') {
|
||||
console.warn('Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.');
|
||||
suppressWarningRef.value = true;
|
||||
}
|
||||
return Reflect.get(target, prop, receiver);
|
||||
},
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)).
|
||||
* Note: Only works for JSON-safe data.
|
||||
@@ -374,5 +392,4 @@ exports.userNotAvailableProxy = userNotAvailableProxy;
|
||||
function deepClone(obj) {
|
||||
return JSON.parse(JSON.stringify(obj));
|
||||
}
|
||||
exports.deepClone = deepClone;
|
||||
//# sourceMappingURL=helpers.js.map
|
||||
+1
-2
@@ -1,6 +1,6 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.memoryLocalStorageAdapter = void 0;
|
||||
exports.memoryLocalStorageAdapter = memoryLocalStorageAdapter;
|
||||
/**
|
||||
* Returns a localStorage-like object that stores the key-value pairs in
|
||||
* memory.
|
||||
@@ -18,5 +18,4 @@ function memoryLocalStorageAdapter(store = {}) {
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.memoryLocalStorageAdapter = memoryLocalStorageAdapter;
|
||||
//# sourceMappingURL=local-storage.js.map
|
||||
+50
-4
@@ -1,6 +1,8 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.processLock = exports.navigatorLock = exports.ProcessLockAcquireTimeoutError = exports.NavigatorLockAcquireTimeoutError = exports.LockAcquireTimeoutError = exports.internals = void 0;
|
||||
exports.ProcessLockAcquireTimeoutError = exports.NavigatorLockAcquireTimeoutError = exports.LockAcquireTimeoutError = exports.internals = void 0;
|
||||
exports.navigatorLock = navigatorLock;
|
||||
exports.processLock = processLock;
|
||||
const helpers_1 = require("./helpers");
|
||||
/**
|
||||
* @experimental
|
||||
@@ -18,6 +20,17 @@ exports.internals = {
|
||||
* An error thrown when a lock cannot be acquired after some amount of time.
|
||||
*
|
||||
* Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { LockAcquireTimeoutError } from '@supabase/auth-js'
|
||||
*
|
||||
* class CustomLockError extends LockAcquireTimeoutError {
|
||||
* constructor() {
|
||||
* super('Lock timed out')
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
class LockAcquireTimeoutError extends Error {
|
||||
constructor(message) {
|
||||
@@ -26,9 +39,29 @@ class LockAcquireTimeoutError extends Error {
|
||||
}
|
||||
}
|
||||
exports.LockAcquireTimeoutError = LockAcquireTimeoutError;
|
||||
/**
|
||||
* Error thrown when the browser Navigator Lock API fails to acquire a lock.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { NavigatorLockAcquireTimeoutError } from '@supabase/auth-js'
|
||||
*
|
||||
* throw new NavigatorLockAcquireTimeoutError('Lock timed out')
|
||||
* ```
|
||||
*/
|
||||
class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError {
|
||||
}
|
||||
exports.NavigatorLockAcquireTimeoutError = NavigatorLockAcquireTimeoutError;
|
||||
/**
|
||||
* Error thrown when the process-level lock helper cannot acquire a lock.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { ProcessLockAcquireTimeoutError } from '@supabase/auth-js'
|
||||
*
|
||||
* throw new ProcessLockAcquireTimeoutError('Lock timed out')
|
||||
* ```
|
||||
*/
|
||||
class ProcessLockAcquireTimeoutError extends LockAcquireTimeoutError {
|
||||
}
|
||||
exports.ProcessLockAcquireTimeoutError = ProcessLockAcquireTimeoutError;
|
||||
@@ -56,6 +89,12 @@ exports.ProcessLockAcquireTimeoutError = ProcessLockAcquireTimeoutError;
|
||||
* will time out after so many milliseconds. An error is
|
||||
* a timeout if it has `isAcquireTimeout` set to true.
|
||||
* @param fn The operation to run once the lock is acquired.
|
||||
* @example
|
||||
* ```ts
|
||||
* await navigatorLock('sync-user', 1000, async () => {
|
||||
* await refreshSession()
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
async function navigatorLock(name, acquireTimeout, fn) {
|
||||
if (exports.internals.debug) {
|
||||
@@ -127,7 +166,6 @@ async function navigatorLock(name, acquireTimeout, fn) {
|
||||
}
|
||||
}));
|
||||
}
|
||||
exports.navigatorLock = navigatorLock;
|
||||
const PROCESS_LOCKS = {};
|
||||
/**
|
||||
* Implements a global exclusive lock that works only in the current process.
|
||||
@@ -142,6 +180,12 @@ const PROCESS_LOCKS = {};
|
||||
* will time out after so many milliseconds. An error is
|
||||
* a timeout if it has `isAcquireTimeout` set to true.
|
||||
* @param fn The operation to run once the lock is acquired.
|
||||
* @example
|
||||
* ```ts
|
||||
* await processLock('migrate', 5000, async () => {
|
||||
* await runMigration()
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
async function processLock(name, acquireTimeout, fn) {
|
||||
var _a;
|
||||
@@ -154,7 +198,10 @@ async function processLock(name, acquireTimeout, fn) {
|
||||
acquireTimeout >= 0
|
||||
? new Promise((_, reject) => {
|
||||
setTimeout(() => {
|
||||
reject(new ProcessLockAcquireTimeoutError(`Acquring process lock with name "${name}" timed out`));
|
||||
console.warn(`@supabase/gotrue-js: Lock "${name}" acquisition timed out after ${acquireTimeout}ms. ` +
|
||||
'This may be caused by another operation holding the lock. ' +
|
||||
'Consider increasing lockAcquireTimeout or checking for stuck operations.');
|
||||
reject(new ProcessLockAcquireTimeoutError(`Acquiring process lock with name "${name}" timed out`));
|
||||
}, acquireTimeout);
|
||||
})
|
||||
: null,
|
||||
@@ -183,5 +230,4 @@ async function processLock(name, acquireTimeout, fn) {
|
||||
// error or with an acquire timeout error
|
||||
return await currentOperation;
|
||||
}
|
||||
exports.processLock = processLock;
|
||||
//# sourceMappingURL=locks.js.map
|
||||
+1
-2
@@ -1,6 +1,6 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.polyfillGlobalThis = void 0;
|
||||
exports.polyfillGlobalThis = polyfillGlobalThis;
|
||||
/**
|
||||
* https://mathiasbynens.be/notes/globalthis
|
||||
*/
|
||||
@@ -26,5 +26,4 @@ function polyfillGlobalThis() {
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.polyfillGlobalThis = polyfillGlobalThis;
|
||||
//# sourceMappingURL=polyfills.js.map
|
||||
+18
@@ -1,5 +1,23 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SIGN_OUT_SCOPES = void 0;
|
||||
const WeakPasswordReasons = ['length', 'characters', 'pwned'];
|
||||
const AMRMethods = [
|
||||
'password',
|
||||
'otp',
|
||||
'oauth',
|
||||
'totp',
|
||||
'mfa/totp',
|
||||
'mfa/phone',
|
||||
'mfa/webauthn',
|
||||
'anonymous',
|
||||
'sso/saml',
|
||||
'magiclink',
|
||||
'web3',
|
||||
'oauth_provider/authorization_code',
|
||||
];
|
||||
const FactorTypes = ['totp', 'phone', 'webauthn'];
|
||||
const FactorVerificationStatuses = ['verified', 'unverified'];
|
||||
const MFATOTPChannels = ['sms', 'whatsapp'];
|
||||
exports.SIGN_OUT_SCOPES = ['global', 'local', 'others'];
|
||||
//# sourceMappingURL=types.js.map
|
||||
+7
-1
@@ -1,5 +1,11 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.version = void 0;
|
||||
exports.version = '2.71.1';
|
||||
// Generated automatically during releases by scripts/update-version-files.ts
|
||||
// This file provides runtime access to the package version for:
|
||||
// - HTTP request headers (e.g., X-Client-Info header for API requests)
|
||||
// - Debugging and support (identifying which version is running)
|
||||
// - Telemetry and logging (version reporting in errors/analytics)
|
||||
// - Ensuring build artifacts match the published package version
|
||||
exports.version = '2.93.3';
|
||||
//# sourceMappingURL=version.js.map
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
"use strict";
|
||||
// types and functions copied over from viem so this library doesn't depend on it
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getAddress = getAddress;
|
||||
exports.fromHex = fromHex;
|
||||
exports.toHex = toHex;
|
||||
exports.createSiweMessage = createSiweMessage;
|
||||
function getAddress(address) {
|
||||
if (!/^0x[a-fA-F0-9]{40}$/.test(address)) {
|
||||
throw new Error(`@supabase/auth-js: Address "${address}" is invalid.`);
|
||||
}
|
||||
return address.toLowerCase();
|
||||
}
|
||||
function fromHex(hex) {
|
||||
return parseInt(hex, 16);
|
||||
}
|
||||
function toHex(value) {
|
||||
const bytes = new TextEncoder().encode(value);
|
||||
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
|
||||
return ('0x' + hex);
|
||||
}
|
||||
/**
|
||||
* Creates EIP-4361 formatted message.
|
||||
*/
|
||||
function createSiweMessage(parameters) {
|
||||
var _a;
|
||||
const { chainId, domain, expirationTime, issuedAt = new Date(), nonce, notBefore, requestId, resources, scheme, uri, version, } = parameters;
|
||||
// Validate fields
|
||||
{
|
||||
if (!Number.isInteger(chainId))
|
||||
throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${chainId}`);
|
||||
if (!domain)
|
||||
throw new Error(`@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.`);
|
||||
if (nonce && nonce.length < 8)
|
||||
throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${nonce}`);
|
||||
if (!uri)
|
||||
throw new Error(`@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.`);
|
||||
if (version !== '1')
|
||||
throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${version}`);
|
||||
if ((_a = parameters.statement) === null || _a === void 0 ? void 0 : _a.includes('\n'))
|
||||
throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${parameters.statement}`);
|
||||
}
|
||||
// Construct message
|
||||
const address = getAddress(parameters.address);
|
||||
const origin = scheme ? `${scheme}://${domain}` : domain;
|
||||
const statement = parameters.statement ? `${parameters.statement}\n` : '';
|
||||
const prefix = `${origin} wants you to sign in with your Ethereum account:\n${address}\n\n${statement}`;
|
||||
let suffix = `URI: ${uri}\nVersion: ${version}\nChain ID: ${chainId}${nonce ? `\nNonce: ${nonce}` : ''}\nIssued At: ${issuedAt.toISOString()}`;
|
||||
if (expirationTime)
|
||||
suffix += `\nExpiration Time: ${expirationTime.toISOString()}`;
|
||||
if (notBefore)
|
||||
suffix += `\nNot Before: ${notBefore.toISOString()}`;
|
||||
if (requestId)
|
||||
suffix += `\nRequest ID: ${requestId}`;
|
||||
if (resources) {
|
||||
let content = '\nResources:';
|
||||
for (const resource of resources) {
|
||||
if (!resource || typeof resource !== 'string')
|
||||
throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${resource}`);
|
||||
content += `\n- ${resource}`;
|
||||
}
|
||||
suffix += content;
|
||||
}
|
||||
return `${prefix}\n${suffix}`;
|
||||
}
|
||||
//# sourceMappingURL=ethereum.js.map
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
"use strict";
|
||||
/* eslint-disable @typescript-eslint/ban-ts-comment */
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.WebAuthnUnknownError = exports.WebAuthnError = void 0;
|
||||
exports.isWebAuthnError = isWebAuthnError;
|
||||
exports.identifyRegistrationError = identifyRegistrationError;
|
||||
exports.identifyAuthenticationError = identifyAuthenticationError;
|
||||
const webauthn_1 = require("./webauthn");
|
||||
/**
|
||||
* A custom Error used to return a more nuanced error detailing _why_ one of the eight documented
|
||||
* errors in the spec was raised after calling `navigator.credentials.create()` or
|
||||
* `navigator.credentials.get()`:
|
||||
*
|
||||
* - `AbortError`
|
||||
* - `ConstraintError`
|
||||
* - `InvalidStateError`
|
||||
* - `NotAllowedError`
|
||||
* - `NotSupportedError`
|
||||
* - `SecurityError`
|
||||
* - `TypeError`
|
||||
* - `UnknownError`
|
||||
*
|
||||
* Error messages were determined through investigation of the spec to determine under which
|
||||
* scenarios a given error would be raised.
|
||||
*/
|
||||
class WebAuthnError extends Error {
|
||||
constructor({ message, code, cause, name, }) {
|
||||
var _a;
|
||||
// @ts-ignore: help Rollup understand that `cause` is okay to set
|
||||
super(message, { cause });
|
||||
this.__isWebAuthnError = true;
|
||||
this.name = (_a = name !== null && name !== void 0 ? name : (cause instanceof Error ? cause.name : undefined)) !== null && _a !== void 0 ? _a : 'Unknown Error';
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
exports.WebAuthnError = WebAuthnError;
|
||||
/**
|
||||
* Error class for unknown WebAuthn errors.
|
||||
* Wraps unexpected errors that don't match known WebAuthn error conditions.
|
||||
*/
|
||||
class WebAuthnUnknownError extends WebAuthnError {
|
||||
constructor(message, originalError) {
|
||||
super({
|
||||
code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',
|
||||
cause: originalError,
|
||||
message,
|
||||
});
|
||||
this.name = 'WebAuthnUnknownError';
|
||||
this.originalError = originalError;
|
||||
}
|
||||
}
|
||||
exports.WebAuthnUnknownError = WebAuthnUnknownError;
|
||||
/**
|
||||
* Type guard to check if an error is a WebAuthnError.
|
||||
* @param {unknown} error - The error to check
|
||||
* @returns {boolean} True if the error is a WebAuthnError
|
||||
*/
|
||||
function isWebAuthnError(error) {
|
||||
return typeof error === 'object' && error !== null && '__isWebAuthnError' in error;
|
||||
}
|
||||
/**
|
||||
* Attempt to intuit _why_ an error was raised after calling `navigator.credentials.create()`.
|
||||
* Maps browser errors to specific WebAuthn error codes for better debugging.
|
||||
* @param {Object} params - Error identification parameters
|
||||
* @param {Error} params.error - The error thrown by the browser
|
||||
* @param {CredentialCreationOptions} params.options - The options passed to credentials.create()
|
||||
* @returns {WebAuthnError} A WebAuthnError with a specific error code
|
||||
* @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential}
|
||||
*/
|
||||
function identifyRegistrationError({ error, options, }) {
|
||||
var _a, _b, _c;
|
||||
const { publicKey } = options;
|
||||
if (!publicKey) {
|
||||
throw Error('options was missing required publicKey property');
|
||||
}
|
||||
if (error.name === 'AbortError') {
|
||||
if (options.signal instanceof AbortSignal) {
|
||||
// https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16)
|
||||
return new WebAuthnError({
|
||||
message: 'Registration ceremony was sent an abort signal',
|
||||
code: 'ERROR_CEREMONY_ABORTED',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (error.name === 'ConstraintError') {
|
||||
if (((_a = publicKey.authenticatorSelection) === null || _a === void 0 ? void 0 : _a.requireResidentKey) === true) {
|
||||
// https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 4)
|
||||
return new WebAuthnError({
|
||||
message: 'Discoverable credentials were required but no available authenticator supported it',
|
||||
code: 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
else if (
|
||||
// @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024
|
||||
options.mediation === 'conditional' &&
|
||||
((_b = publicKey.authenticatorSelection) === null || _b === void 0 ? void 0 : _b.userVerification) === 'required') {
|
||||
// https://w3c.github.io/webauthn/#sctn-createCredential (Step 22.4)
|
||||
return new WebAuthnError({
|
||||
message: 'User verification was required during automatic registration but it could not be performed',
|
||||
code: 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
else if (((_c = publicKey.authenticatorSelection) === null || _c === void 0 ? void 0 : _c.userVerification) === 'required') {
|
||||
// https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 5)
|
||||
return new WebAuthnError({
|
||||
message: 'User verification was required but no available authenticator supported it',
|
||||
code: 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (error.name === 'InvalidStateError') {
|
||||
// https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 20)
|
||||
// https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 3)
|
||||
return new WebAuthnError({
|
||||
message: 'The authenticator was previously registered',
|
||||
code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
else if (error.name === 'NotAllowedError') {
|
||||
/**
|
||||
* Pass the error directly through. Platforms are overloading this error beyond what the spec
|
||||
* defines and we don't want to overwrite potentially useful error messages.
|
||||
*/
|
||||
return new WebAuthnError({
|
||||
message: error.message,
|
||||
code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
else if (error.name === 'NotSupportedError') {
|
||||
const validPubKeyCredParams = publicKey.pubKeyCredParams.filter((param) => param.type === 'public-key');
|
||||
if (validPubKeyCredParams.length === 0) {
|
||||
// https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 10)
|
||||
return new WebAuthnError({
|
||||
message: 'No entry in pubKeyCredParams was of type "public-key"',
|
||||
code: 'ERROR_MALFORMED_PUBKEYCREDPARAMS',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
// https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 2)
|
||||
return new WebAuthnError({
|
||||
message: 'No available authenticator supported any of the specified pubKeyCredParams algorithms',
|
||||
code: 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
else if (error.name === 'SecurityError') {
|
||||
const effectiveDomain = window.location.hostname;
|
||||
if (!(0, webauthn_1.isValidDomain)(effectiveDomain)) {
|
||||
// https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 7)
|
||||
return new WebAuthnError({
|
||||
message: `${window.location.hostname} is an invalid domain`,
|
||||
code: 'ERROR_INVALID_DOMAIN',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
else if (publicKey.rp.id !== effectiveDomain) {
|
||||
// https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 8)
|
||||
return new WebAuthnError({
|
||||
message: `The RP ID "${publicKey.rp.id}" is invalid for this domain`,
|
||||
code: 'ERROR_INVALID_RP_ID',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (error.name === 'TypeError') {
|
||||
if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) {
|
||||
// https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 5)
|
||||
return new WebAuthnError({
|
||||
message: 'User ID was not between 1 and 64 characters',
|
||||
code: 'ERROR_INVALID_USER_ID_LENGTH',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (error.name === 'UnknownError') {
|
||||
// https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 1)
|
||||
// https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 8)
|
||||
return new WebAuthnError({
|
||||
message: 'The authenticator was unable to process the specified options, or could not create a new credential',
|
||||
code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
return new WebAuthnError({
|
||||
message: 'a Non-Webauthn related error has occurred',
|
||||
code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Attempt to intuit _why_ an error was raised after calling `navigator.credentials.get()`.
|
||||
* Maps browser errors to specific WebAuthn error codes for better debugging.
|
||||
* @param {Object} params - Error identification parameters
|
||||
* @param {Error} params.error - The error thrown by the browser
|
||||
* @param {CredentialRequestOptions} params.options - The options passed to credentials.get()
|
||||
* @returns {WebAuthnError} A WebAuthnError with a specific error code
|
||||
* @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion}
|
||||
*/
|
||||
function identifyAuthenticationError({ error, options, }) {
|
||||
const { publicKey } = options;
|
||||
if (!publicKey) {
|
||||
throw Error('options was missing required publicKey property');
|
||||
}
|
||||
if (error.name === 'AbortError') {
|
||||
if (options.signal instanceof AbortSignal) {
|
||||
// https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16)
|
||||
return new WebAuthnError({
|
||||
message: 'Authentication ceremony was sent an abort signal',
|
||||
code: 'ERROR_CEREMONY_ABORTED',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (error.name === 'NotAllowedError') {
|
||||
/**
|
||||
* Pass the error directly through. Platforms are overloading this error beyond what the spec
|
||||
* defines and we don't want to overwrite potentially useful error messages.
|
||||
*/
|
||||
return new WebAuthnError({
|
||||
message: error.message,
|
||||
code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
else if (error.name === 'SecurityError') {
|
||||
const effectiveDomain = window.location.hostname;
|
||||
if (!(0, webauthn_1.isValidDomain)(effectiveDomain)) {
|
||||
// https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 5)
|
||||
return new WebAuthnError({
|
||||
message: `${window.location.hostname} is an invalid domain`,
|
||||
code: 'ERROR_INVALID_DOMAIN',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
else if (publicKey.rpId !== effectiveDomain) {
|
||||
// https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 6)
|
||||
return new WebAuthnError({
|
||||
message: `The RP ID "${publicKey.rpId}" is invalid for this domain`,
|
||||
code: 'ERROR_INVALID_RP_ID',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (error.name === 'UnknownError') {
|
||||
// https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 1)
|
||||
// https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 12)
|
||||
return new WebAuthnError({
|
||||
message: 'The authenticator was unable to process the specified options, or could not create a new assertion signature',
|
||||
code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
return new WebAuthnError({
|
||||
message: 'a Non-Webauthn related error has occurred',
|
||||
code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
//# sourceMappingURL=webauthn.errors.js.map
|
||||
+706
@@ -0,0 +1,706 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.WebAuthnApi = exports.DEFAULT_REQUEST_OPTIONS = exports.DEFAULT_CREATION_OPTIONS = exports.webAuthnAbortService = exports.WebAuthnAbortService = exports.identifyAuthenticationError = exports.identifyRegistrationError = exports.isWebAuthnError = exports.WebAuthnError = void 0;
|
||||
exports.deserializeCredentialCreationOptions = deserializeCredentialCreationOptions;
|
||||
exports.deserializeCredentialRequestOptions = deserializeCredentialRequestOptions;
|
||||
exports.serializeCredentialCreationResponse = serializeCredentialCreationResponse;
|
||||
exports.serializeCredentialRequestResponse = serializeCredentialRequestResponse;
|
||||
exports.isValidDomain = isValidDomain;
|
||||
exports.createCredential = createCredential;
|
||||
exports.getCredential = getCredential;
|
||||
exports.mergeCredentialCreationOptions = mergeCredentialCreationOptions;
|
||||
exports.mergeCredentialRequestOptions = mergeCredentialRequestOptions;
|
||||
const tslib_1 = require("tslib");
|
||||
const base64url_1 = require("./base64url");
|
||||
const errors_1 = require("./errors");
|
||||
const helpers_1 = require("./helpers");
|
||||
const webauthn_errors_1 = require("./webauthn.errors");
|
||||
Object.defineProperty(exports, "identifyAuthenticationError", { enumerable: true, get: function () { return webauthn_errors_1.identifyAuthenticationError; } });
|
||||
Object.defineProperty(exports, "identifyRegistrationError", { enumerable: true, get: function () { return webauthn_errors_1.identifyRegistrationError; } });
|
||||
Object.defineProperty(exports, "isWebAuthnError", { enumerable: true, get: function () { return webauthn_errors_1.isWebAuthnError; } });
|
||||
Object.defineProperty(exports, "WebAuthnError", { enumerable: true, get: function () { return webauthn_errors_1.WebAuthnError; } });
|
||||
/**
|
||||
* WebAuthn abort service to manage ceremony cancellation.
|
||||
* Ensures only one WebAuthn ceremony is active at a time to prevent "operation already in progress" errors.
|
||||
*
|
||||
* @experimental This class is experimental and may change in future releases
|
||||
* @see {@link https://w3c.github.io/webauthn/#sctn-automation-webdriver-capability W3C WebAuthn Spec - Aborting Ceremonies}
|
||||
*/
|
||||
class WebAuthnAbortService {
|
||||
/**
|
||||
* Create an abort signal for a new WebAuthn operation.
|
||||
* Automatically cancels any existing operation.
|
||||
*
|
||||
* @returns {AbortSignal} Signal to pass to navigator.credentials.create() or .get()
|
||||
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal MDN - AbortSignal}
|
||||
*/
|
||||
createNewAbortSignal() {
|
||||
// Abort any existing calls to navigator.credentials.create() or navigator.credentials.get()
|
||||
if (this.controller) {
|
||||
const abortError = new Error('Cancelling existing WebAuthn API call for new one');
|
||||
abortError.name = 'AbortError';
|
||||
this.controller.abort(abortError);
|
||||
}
|
||||
const newController = new AbortController();
|
||||
this.controller = newController;
|
||||
return newController.signal;
|
||||
}
|
||||
/**
|
||||
* Manually cancel the current WebAuthn operation.
|
||||
* Useful for cleaning up when user cancels or navigates away.
|
||||
*
|
||||
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort MDN - AbortController.abort}
|
||||
*/
|
||||
cancelCeremony() {
|
||||
if (this.controller) {
|
||||
const abortError = new Error('Manually cancelling existing WebAuthn API call');
|
||||
abortError.name = 'AbortError';
|
||||
this.controller.abort(abortError);
|
||||
this.controller = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.WebAuthnAbortService = WebAuthnAbortService;
|
||||
/**
|
||||
* Singleton instance to ensure only one WebAuthn ceremony is active at a time.
|
||||
* This prevents "operation already in progress" errors when retrying WebAuthn operations.
|
||||
*
|
||||
* @experimental This instance is experimental and may change in future releases
|
||||
*/
|
||||
exports.webAuthnAbortService = new WebAuthnAbortService();
|
||||
/**
|
||||
* Convert base64url encoded strings in WebAuthn credential creation options to ArrayBuffers
|
||||
* as required by the WebAuthn browser API.
|
||||
* Supports both native WebAuthn Level 3 parseCreationOptionsFromJSON and manual fallback.
|
||||
*
|
||||
* @param {ServerCredentialCreationOptions} options - JSON options from server with base64url encoded fields
|
||||
* @returns {PublicKeyCredentialCreationOptionsFuture} Options ready for navigator.credentials.create()
|
||||
* @see {@link https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON W3C WebAuthn Spec - parseCreationOptionsFromJSON}
|
||||
*/
|
||||
function deserializeCredentialCreationOptions(options) {
|
||||
if (!options) {
|
||||
throw new Error('Credential creation options are required');
|
||||
}
|
||||
// Check if the native parseCreationOptionsFromJSON method is available
|
||||
if (typeof PublicKeyCredential !== 'undefined' &&
|
||||
'parseCreationOptionsFromJSON' in PublicKeyCredential &&
|
||||
typeof PublicKeyCredential
|
||||
.parseCreationOptionsFromJSON === 'function') {
|
||||
// Use the native WebAuthn Level 3 method
|
||||
return PublicKeyCredential.parseCreationOptionsFromJSON(
|
||||
/** we assert the options here as typescript still doesn't know about future webauthn types */
|
||||
options);
|
||||
}
|
||||
// Fallback to manual parsing for browsers that don't support the native method
|
||||
// Destructure to separate fields that need transformation
|
||||
const { challenge: challengeStr, user: userOpts, excludeCredentials } = options, restOptions = tslib_1.__rest(options
|
||||
// Convert challenge from base64url to ArrayBuffer
|
||||
, ["challenge", "user", "excludeCredentials"]);
|
||||
// Convert challenge from base64url to ArrayBuffer
|
||||
const challenge = (0, base64url_1.base64UrlToUint8Array)(challengeStr).buffer;
|
||||
// Convert user.id from base64url to ArrayBuffer
|
||||
const user = Object.assign(Object.assign({}, userOpts), { id: (0, base64url_1.base64UrlToUint8Array)(userOpts.id).buffer });
|
||||
// Build the result object
|
||||
const result = Object.assign(Object.assign({}, restOptions), { challenge,
|
||||
user });
|
||||
// Only add excludeCredentials if it exists
|
||||
if (excludeCredentials && excludeCredentials.length > 0) {
|
||||
result.excludeCredentials = new Array(excludeCredentials.length);
|
||||
for (let i = 0; i < excludeCredentials.length; i++) {
|
||||
const cred = excludeCredentials[i];
|
||||
result.excludeCredentials[i] = Object.assign(Object.assign({}, cred), { id: (0, base64url_1.base64UrlToUint8Array)(cred.id).buffer, type: cred.type || 'public-key',
|
||||
// Cast transports to handle future transport types like "cable"
|
||||
transports: cred.transports });
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Convert base64url encoded strings in WebAuthn credential request options to ArrayBuffers
|
||||
* as required by the WebAuthn browser API.
|
||||
* Supports both native WebAuthn Level 3 parseRequestOptionsFromJSON and manual fallback.
|
||||
*
|
||||
* @param {ServerCredentialRequestOptions} options - JSON options from server with base64url encoded fields
|
||||
* @returns {PublicKeyCredentialRequestOptionsFuture} Options ready for navigator.credentials.get()
|
||||
* @see {@link https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON W3C WebAuthn Spec - parseRequestOptionsFromJSON}
|
||||
*/
|
||||
function deserializeCredentialRequestOptions(options) {
|
||||
if (!options) {
|
||||
throw new Error('Credential request options are required');
|
||||
}
|
||||
// Check if the native parseRequestOptionsFromJSON method is available
|
||||
if (typeof PublicKeyCredential !== 'undefined' &&
|
||||
'parseRequestOptionsFromJSON' in PublicKeyCredential &&
|
||||
typeof PublicKeyCredential
|
||||
.parseRequestOptionsFromJSON === 'function') {
|
||||
// Use the native WebAuthn Level 3 method
|
||||
return PublicKeyCredential.parseRequestOptionsFromJSON(options);
|
||||
}
|
||||
// Fallback to manual parsing for browsers that don't support the native method
|
||||
// Destructure to separate fields that need transformation
|
||||
const { challenge: challengeStr, allowCredentials } = options, restOptions = tslib_1.__rest(options
|
||||
// Convert challenge from base64url to ArrayBuffer
|
||||
, ["challenge", "allowCredentials"]);
|
||||
// Convert challenge from base64url to ArrayBuffer
|
||||
const challenge = (0, base64url_1.base64UrlToUint8Array)(challengeStr).buffer;
|
||||
// Build the result object
|
||||
const result = Object.assign(Object.assign({}, restOptions), { challenge });
|
||||
// Only add allowCredentials if it exists
|
||||
if (allowCredentials && allowCredentials.length > 0) {
|
||||
result.allowCredentials = new Array(allowCredentials.length);
|
||||
for (let i = 0; i < allowCredentials.length; i++) {
|
||||
const cred = allowCredentials[i];
|
||||
result.allowCredentials[i] = Object.assign(Object.assign({}, cred), { id: (0, base64url_1.base64UrlToUint8Array)(cred.id).buffer, type: cred.type || 'public-key',
|
||||
// Cast transports to handle future transport types like "cable"
|
||||
transports: cred.transports });
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Convert a registration/enrollment credential response to server format.
|
||||
* Serializes binary fields to base64url for JSON transmission.
|
||||
* Supports both native WebAuthn Level 3 toJSON and manual fallback.
|
||||
*
|
||||
* @param {RegistrationCredential} credential - Credential from navigator.credentials.create()
|
||||
* @returns {RegistrationResponseJSON} JSON-serializable credential for server
|
||||
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON}
|
||||
*/
|
||||
function serializeCredentialCreationResponse(credential) {
|
||||
var _a;
|
||||
// Check if the credential instance has the toJSON method
|
||||
if ('toJSON' in credential && typeof credential.toJSON === 'function') {
|
||||
// Use the native WebAuthn Level 3 method
|
||||
return credential.toJSON();
|
||||
}
|
||||
const credentialWithAttachment = credential;
|
||||
return {
|
||||
id: credential.id,
|
||||
rawId: credential.id,
|
||||
response: {
|
||||
attestationObject: (0, base64url_1.bytesToBase64URL)(new Uint8Array(credential.response.attestationObject)),
|
||||
clientDataJSON: (0, base64url_1.bytesToBase64URL)(new Uint8Array(credential.response.clientDataJSON)),
|
||||
},
|
||||
type: 'public-key',
|
||||
clientExtensionResults: credential.getClientExtensionResults(),
|
||||
// Convert null to undefined and cast to AuthenticatorAttachment type
|
||||
authenticatorAttachment: ((_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined),
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Convert an authentication/verification credential response to server format.
|
||||
* Serializes binary fields to base64url for JSON transmission.
|
||||
* Supports both native WebAuthn Level 3 toJSON and manual fallback.
|
||||
*
|
||||
* @param {AuthenticationCredential} credential - Credential from navigator.credentials.get()
|
||||
* @returns {AuthenticationResponseJSON} JSON-serializable credential for server
|
||||
* @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON}
|
||||
*/
|
||||
function serializeCredentialRequestResponse(credential) {
|
||||
var _a;
|
||||
// Check if the credential instance has the toJSON method
|
||||
if ('toJSON' in credential && typeof credential.toJSON === 'function') {
|
||||
// Use the native WebAuthn Level 3 method
|
||||
return credential.toJSON();
|
||||
}
|
||||
// Fallback to manual conversion for browsers that don't support toJSON
|
||||
// Access authenticatorAttachment via type assertion to handle TypeScript version differences
|
||||
// @simplewebauthn/types includes this property but base TypeScript 4.7.4 doesn't
|
||||
const credentialWithAttachment = credential;
|
||||
const clientExtensionResults = credential.getClientExtensionResults();
|
||||
const assertionResponse = credential.response;
|
||||
return {
|
||||
id: credential.id,
|
||||
rawId: credential.id, // W3C spec expects rawId to match id for JSON format
|
||||
response: {
|
||||
authenticatorData: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.authenticatorData)),
|
||||
clientDataJSON: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.clientDataJSON)),
|
||||
signature: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.signature)),
|
||||
userHandle: assertionResponse.userHandle
|
||||
? (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.userHandle))
|
||||
: undefined,
|
||||
},
|
||||
type: 'public-key',
|
||||
clientExtensionResults,
|
||||
// Convert null to undefined and cast to AuthenticatorAttachment type
|
||||
authenticatorAttachment: ((_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined),
|
||||
};
|
||||
}
|
||||
/**
|
||||
* A simple test to determine if a hostname is a properly-formatted domain name.
|
||||
* Considers localhost valid for development environments.
|
||||
*
|
||||
* A "valid domain" is defined here: https://url.spec.whatwg.org/#valid-domain
|
||||
*
|
||||
* Regex sourced from here:
|
||||
* https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html
|
||||
*
|
||||
* @param {string} hostname - The hostname to validate
|
||||
* @returns {boolean} True if valid domain or localhost
|
||||
* @see {@link https://url.spec.whatwg.org/#valid-domain WHATWG URL Spec - Valid Domain}
|
||||
*/
|
||||
function isValidDomain(hostname) {
|
||||
return (
|
||||
// Consider localhost valid as well since it's okay wrt Secure Contexts
|
||||
hostname === 'localhost' || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname));
|
||||
}
|
||||
/**
|
||||
* Determine if the browser is capable of WebAuthn.
|
||||
* Checks for necessary Web APIs: PublicKeyCredential and Credential Management.
|
||||
*
|
||||
* @returns {boolean} True if browser supports WebAuthn
|
||||
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential#browser_compatibility MDN - PublicKeyCredential Browser Compatibility}
|
||||
*/
|
||||
function browserSupportsWebAuthn() {
|
||||
var _a, _b;
|
||||
return !!((0, helpers_1.isBrowser)() &&
|
||||
'PublicKeyCredential' in window &&
|
||||
window.PublicKeyCredential &&
|
||||
'credentials' in navigator &&
|
||||
typeof ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _a === void 0 ? void 0 : _a.create) === 'function' &&
|
||||
typeof ((_b = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _b === void 0 ? void 0 : _b.get) === 'function');
|
||||
}
|
||||
/**
|
||||
* Create a WebAuthn credential using the browser's credentials API.
|
||||
* Wraps navigator.credentials.create() with error handling.
|
||||
*
|
||||
* @param {CredentialCreationOptions} options - Options including publicKey parameters
|
||||
* @returns {Promise<RequestResult<RegistrationCredential, WebAuthnError>>} Created credential or error
|
||||
* @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential}
|
||||
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create MDN - credentials.create}
|
||||
*/
|
||||
async function createCredential(options) {
|
||||
try {
|
||||
const response = await navigator.credentials.create(
|
||||
/** we assert the type here until typescript types are updated */
|
||||
options);
|
||||
if (!response) {
|
||||
return {
|
||||
data: null,
|
||||
error: new webauthn_errors_1.WebAuthnUnknownError('Empty credential response', response),
|
||||
};
|
||||
}
|
||||
if (!(response instanceof PublicKeyCredential)) {
|
||||
return {
|
||||
data: null,
|
||||
error: new webauthn_errors_1.WebAuthnUnknownError('Browser returned unexpected credential type', response),
|
||||
};
|
||||
}
|
||||
return { data: response, error: null };
|
||||
}
|
||||
catch (err) {
|
||||
return {
|
||||
data: null,
|
||||
error: (0, webauthn_errors_1.identifyRegistrationError)({
|
||||
error: err,
|
||||
options,
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Get a WebAuthn credential using the browser's credentials API.
|
||||
* Wraps navigator.credentials.get() with error handling.
|
||||
*
|
||||
* @param {CredentialRequestOptions} options - Options including publicKey parameters
|
||||
* @returns {Promise<RequestResult<AuthenticationCredential, WebAuthnError>>} Retrieved credential or error
|
||||
* @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion}
|
||||
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get MDN - credentials.get}
|
||||
*/
|
||||
async function getCredential(options) {
|
||||
try {
|
||||
const response = await navigator.credentials.get(
|
||||
/** we assert the type here until typescript types are updated */
|
||||
options);
|
||||
if (!response) {
|
||||
return {
|
||||
data: null,
|
||||
error: new webauthn_errors_1.WebAuthnUnknownError('Empty credential response', response),
|
||||
};
|
||||
}
|
||||
if (!(response instanceof PublicKeyCredential)) {
|
||||
return {
|
||||
data: null,
|
||||
error: new webauthn_errors_1.WebAuthnUnknownError('Browser returned unexpected credential type', response),
|
||||
};
|
||||
}
|
||||
return { data: response, error: null };
|
||||
}
|
||||
catch (err) {
|
||||
return {
|
||||
data: null,
|
||||
error: (0, webauthn_errors_1.identifyAuthenticationError)({
|
||||
error: err,
|
||||
options,
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
exports.DEFAULT_CREATION_OPTIONS = {
|
||||
hints: ['security-key'],
|
||||
authenticatorSelection: {
|
||||
authenticatorAttachment: 'cross-platform',
|
||||
requireResidentKey: false,
|
||||
/** set to preferred because older yubikeys don't have PIN/Biometric */
|
||||
userVerification: 'preferred',
|
||||
residentKey: 'discouraged',
|
||||
},
|
||||
attestation: 'direct',
|
||||
};
|
||||
exports.DEFAULT_REQUEST_OPTIONS = {
|
||||
/** set to preferred because older yubikeys don't have PIN/Biometric */
|
||||
userVerification: 'preferred',
|
||||
hints: ['security-key'],
|
||||
attestation: 'direct',
|
||||
};
|
||||
function deepMerge(...sources) {
|
||||
const isObject = (val) => val !== null && typeof val === 'object' && !Array.isArray(val);
|
||||
const isArrayBufferLike = (val) => val instanceof ArrayBuffer || ArrayBuffer.isView(val);
|
||||
const result = {};
|
||||
for (const source of sources) {
|
||||
if (!source)
|
||||
continue;
|
||||
for (const key in source) {
|
||||
const value = source[key];
|
||||
if (value === undefined)
|
||||
continue;
|
||||
if (Array.isArray(value)) {
|
||||
// preserve array reference, including unions like AuthenticatorTransport[]
|
||||
result[key] = value;
|
||||
}
|
||||
else if (isArrayBufferLike(value)) {
|
||||
result[key] = value;
|
||||
}
|
||||
else if (isObject(value)) {
|
||||
const existing = result[key];
|
||||
if (isObject(existing)) {
|
||||
result[key] = deepMerge(existing, value);
|
||||
}
|
||||
else {
|
||||
result[key] = deepMerge(value);
|
||||
}
|
||||
}
|
||||
else {
|
||||
result[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Merges WebAuthn credential creation options with overrides.
|
||||
* Sets sensible defaults for authenticator selection and extensions.
|
||||
*
|
||||
* @param {PublicKeyCredentialCreationOptionsFuture} baseOptions - The base options from the server
|
||||
* @param {PublicKeyCredentialCreationOptionsFuture} overrides - Optional overrides to apply
|
||||
* @param {string} friendlyName - Optional friendly name for the credential
|
||||
* @returns {PublicKeyCredentialCreationOptionsFuture} Merged credential creation options
|
||||
* @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorselectioncriteria W3C WebAuthn Spec - AuthenticatorSelectionCriteria}
|
||||
*/
|
||||
function mergeCredentialCreationOptions(baseOptions, overrides) {
|
||||
return deepMerge(exports.DEFAULT_CREATION_OPTIONS, baseOptions, overrides || {});
|
||||
}
|
||||
/**
|
||||
* Merges WebAuthn credential request options with overrides.
|
||||
* Sets sensible defaults for user verification and hints.
|
||||
*
|
||||
* @param {PublicKeyCredentialRequestOptionsFuture} baseOptions - The base options from the server
|
||||
* @param {PublicKeyCredentialRequestOptionsFuture} overrides - Optional overrides to apply
|
||||
* @returns {PublicKeyCredentialRequestOptionsFuture} Merged credential request options
|
||||
* @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions W3C WebAuthn Spec - PublicKeyCredentialRequestOptions}
|
||||
*/
|
||||
function mergeCredentialRequestOptions(baseOptions, overrides) {
|
||||
return deepMerge(exports.DEFAULT_REQUEST_OPTIONS, baseOptions, overrides || {});
|
||||
}
|
||||
/**
|
||||
* WebAuthn API wrapper for Supabase Auth.
|
||||
* Provides methods for enrolling, challenging, verifying, authenticating, and registering WebAuthn credentials.
|
||||
*
|
||||
* @experimental This API is experimental and may change in future releases
|
||||
* @see {@link https://w3c.github.io/webauthn/ W3C WebAuthn Specification}
|
||||
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API MDN - Web Authentication API}
|
||||
*/
|
||||
class WebAuthnApi {
|
||||
constructor(client) {
|
||||
this.client = client;
|
||||
// Bind all methods so they can be destructured
|
||||
this.enroll = this._enroll.bind(this);
|
||||
this.challenge = this._challenge.bind(this);
|
||||
this.verify = this._verify.bind(this);
|
||||
this.authenticate = this._authenticate.bind(this);
|
||||
this.register = this._register.bind(this);
|
||||
}
|
||||
/**
|
||||
* Enroll a new WebAuthn factor.
|
||||
* Creates an unverified WebAuthn factor that must be verified with a credential.
|
||||
*
|
||||
* @experimental This method is experimental and may change in future releases
|
||||
* @param {Omit<MFAEnrollWebauthnParams, 'factorType'>} params - Enrollment parameters (friendlyName required)
|
||||
* @returns {Promise<AuthMFAEnrollWebauthnResponse>} Enrolled factor details or error
|
||||
* @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential}
|
||||
*/
|
||||
async _enroll(params) {
|
||||
return this.client.mfa.enroll(Object.assign(Object.assign({}, params), { factorType: 'webauthn' }));
|
||||
}
|
||||
/**
|
||||
* Challenge for WebAuthn credential creation or authentication.
|
||||
* Combines server challenge with browser credential operations.
|
||||
* Handles both registration (create) and authentication (request) flows.
|
||||
*
|
||||
* @experimental This method is experimental and may change in future releases
|
||||
* @param {MFAChallengeWebauthnParams & { friendlyName?: string; signal?: AbortSignal }} params - Challenge parameters including factorId
|
||||
* @param {Object} overrides - Allows you to override the parameters passed to navigator.credentials
|
||||
* @param {PublicKeyCredentialCreationOptionsFuture} overrides.create - Override options for credential creation
|
||||
* @param {PublicKeyCredentialRequestOptionsFuture} overrides.request - Override options for credential request
|
||||
* @returns {Promise<RequestResult>} Challenge response with credential or error
|
||||
* @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation}
|
||||
* @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying Assertion}
|
||||
*/
|
||||
async _challenge({ factorId, webauthn, friendlyName, signal, }, overrides) {
|
||||
var _a;
|
||||
try {
|
||||
// Get challenge from server using the client's MFA methods
|
||||
const { data: challengeResponse, error: challengeError } = await this.client.mfa.challenge({
|
||||
factorId,
|
||||
webauthn,
|
||||
});
|
||||
if (!challengeResponse) {
|
||||
return { data: null, error: challengeError };
|
||||
}
|
||||
const abortSignal = signal !== null && signal !== void 0 ? signal : exports.webAuthnAbortService.createNewAbortSignal();
|
||||
/** webauthn will fail if either of the name/displayname are blank */
|
||||
if (challengeResponse.webauthn.type === 'create') {
|
||||
const { user } = challengeResponse.webauthn.credential_options.publicKey;
|
||||
if (!user.name) {
|
||||
// Preserve original format: use friendlyName if provided, otherwise fetch fallback
|
||||
// This maintains backward compatibility with the ${user.id}:${name} format
|
||||
const nameToUse = friendlyName;
|
||||
if (!nameToUse) {
|
||||
// Only fetch user data if friendlyName is not provided (bug fix for null friendlyName)
|
||||
const currentUser = await this.client.getUser();
|
||||
const userData = currentUser.data.user;
|
||||
const fallbackName = ((_a = userData === null || userData === void 0 ? void 0 : userData.user_metadata) === null || _a === void 0 ? void 0 : _a.name) || (userData === null || userData === void 0 ? void 0 : userData.email) || (userData === null || userData === void 0 ? void 0 : userData.id) || 'User';
|
||||
user.name = `${user.id}:${fallbackName}`;
|
||||
}
|
||||
else {
|
||||
user.name = `${user.id}:${nameToUse}`;
|
||||
}
|
||||
}
|
||||
if (!user.displayName) {
|
||||
user.displayName = user.name;
|
||||
}
|
||||
}
|
||||
switch (challengeResponse.webauthn.type) {
|
||||
case 'create': {
|
||||
const options = mergeCredentialCreationOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.create);
|
||||
const { data, error } = await createCredential({
|
||||
publicKey: options,
|
||||
signal: abortSignal,
|
||||
});
|
||||
if (data) {
|
||||
return {
|
||||
data: {
|
||||
factorId,
|
||||
challengeId: challengeResponse.id,
|
||||
webauthn: {
|
||||
type: challengeResponse.webauthn.type,
|
||||
credential_response: data,
|
||||
},
|
||||
},
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
return { data: null, error };
|
||||
}
|
||||
case 'request': {
|
||||
const options = mergeCredentialRequestOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.request);
|
||||
const { data, error } = await getCredential(Object.assign(Object.assign({}, challengeResponse.webauthn.credential_options), { publicKey: options, signal: abortSignal }));
|
||||
if (data) {
|
||||
return {
|
||||
data: {
|
||||
factorId,
|
||||
challengeId: challengeResponse.id,
|
||||
webauthn: {
|
||||
type: challengeResponse.webauthn.type,
|
||||
credential_response: data,
|
||||
},
|
||||
},
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
return { data: null, error };
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
return {
|
||||
data: null,
|
||||
error: new errors_1.AuthUnknownError('Unexpected error in challenge', error),
|
||||
};
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Verify a WebAuthn credential with the server.
|
||||
* Completes the WebAuthn ceremony by sending the credential to the server for verification.
|
||||
*
|
||||
* @experimental This method is experimental and may change in future releases
|
||||
* @param {Object} params - Verification parameters
|
||||
* @param {string} params.challengeId - ID of the challenge being verified
|
||||
* @param {string} params.factorId - ID of the WebAuthn factor
|
||||
* @param {MFAVerifyWebauthnParams<T>['webauthn']} params.webauthn - WebAuthn credential response
|
||||
* @returns {Promise<AuthMFAVerifyResponse>} Verification result with session or error
|
||||
* @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion}
|
||||
* */
|
||||
async _verify({ challengeId, factorId, webauthn, }) {
|
||||
return this.client.mfa.verify({
|
||||
factorId,
|
||||
challengeId,
|
||||
webauthn: webauthn,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Complete WebAuthn authentication flow.
|
||||
* Performs challenge and verification in a single operation for existing credentials.
|
||||
*
|
||||
* @experimental This method is experimental and may change in future releases
|
||||
* @param {Object} params - Authentication parameters
|
||||
* @param {string} params.factorId - ID of the WebAuthn factor to authenticate with
|
||||
* @param {Object} params.webauthn - WebAuthn configuration
|
||||
* @param {string} params.webauthn.rpId - Relying Party ID (defaults to current hostname)
|
||||
* @param {string[]} params.webauthn.rpOrigins - Allowed origins (defaults to current origin)
|
||||
* @param {AbortSignal} params.webauthn.signal - Optional abort signal
|
||||
* @param {PublicKeyCredentialRequestOptionsFuture} overrides - Override options for navigator.credentials.get
|
||||
* @returns {Promise<RequestResult<AuthMFAVerifyResponseData, WebAuthnError | AuthError>>} Authentication result
|
||||
* @see {@link https://w3c.github.io/webauthn/#sctn-authentication W3C WebAuthn Spec - Authentication Ceremony}
|
||||
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions}
|
||||
*/
|
||||
async _authenticate({ factorId, webauthn: { rpId = typeof window !== 'undefined' ? window.location.hostname : undefined, rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined, signal, } = {}, }, overrides) {
|
||||
if (!rpId) {
|
||||
return {
|
||||
data: null,
|
||||
error: new errors_1.AuthError('rpId is required for WebAuthn authentication'),
|
||||
};
|
||||
}
|
||||
try {
|
||||
if (!browserSupportsWebAuthn()) {
|
||||
return {
|
||||
data: null,
|
||||
error: new errors_1.AuthUnknownError('Browser does not support WebAuthn', null),
|
||||
};
|
||||
}
|
||||
// Get challenge and credential
|
||||
const { data: challengeResponse, error: challengeError } = await this.challenge({
|
||||
factorId,
|
||||
webauthn: { rpId, rpOrigins },
|
||||
signal,
|
||||
}, { request: overrides });
|
||||
if (!challengeResponse) {
|
||||
return { data: null, error: challengeError };
|
||||
}
|
||||
const { webauthn } = challengeResponse;
|
||||
// Verify credential
|
||||
return this._verify({
|
||||
factorId,
|
||||
challengeId: challengeResponse.challengeId,
|
||||
webauthn: {
|
||||
type: webauthn.type,
|
||||
rpId,
|
||||
rpOrigins,
|
||||
credential_response: webauthn.credential_response,
|
||||
},
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
return {
|
||||
data: null,
|
||||
error: new errors_1.AuthUnknownError('Unexpected error in authenticate', error),
|
||||
};
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Complete WebAuthn registration flow.
|
||||
* Performs enrollment, challenge, and verification in a single operation for new credentials.
|
||||
*
|
||||
* @experimental This method is experimental and may change in future releases
|
||||
* @param {Object} params - Registration parameters
|
||||
* @param {string} params.friendlyName - User-friendly name for the credential
|
||||
* @param {string} params.rpId - Relying Party ID (defaults to current hostname)
|
||||
* @param {string[]} params.rpOrigins - Allowed origins (defaults to current origin)
|
||||
* @param {AbortSignal} params.signal - Optional abort signal
|
||||
* @param {PublicKeyCredentialCreationOptionsFuture} overrides - Override options for navigator.credentials.create
|
||||
* @returns {Promise<RequestResult<AuthMFAVerifyResponseData, WebAuthnError | AuthError>>} Registration result
|
||||
* @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registration Ceremony}
|
||||
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions}
|
||||
*/
|
||||
async _register({ friendlyName, webauthn: { rpId = typeof window !== 'undefined' ? window.location.hostname : undefined, rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined, signal, } = {}, }, overrides) {
|
||||
if (!rpId) {
|
||||
return {
|
||||
data: null,
|
||||
error: new errors_1.AuthError('rpId is required for WebAuthn registration'),
|
||||
};
|
||||
}
|
||||
try {
|
||||
if (!browserSupportsWebAuthn()) {
|
||||
return {
|
||||
data: null,
|
||||
error: new errors_1.AuthUnknownError('Browser does not support WebAuthn', null),
|
||||
};
|
||||
}
|
||||
// Enroll factor
|
||||
const { data: factor, error: enrollError } = await this._enroll({
|
||||
friendlyName,
|
||||
});
|
||||
if (!factor) {
|
||||
await this.client.mfa
|
||||
.listFactors()
|
||||
.then((factors) => {
|
||||
var _a;
|
||||
return (_a = factors.data) === null || _a === void 0 ? void 0 : _a.all.find((v) => v.factor_type === 'webauthn' &&
|
||||
v.friendly_name === friendlyName &&
|
||||
v.status !== 'unverified');
|
||||
})
|
||||
.then((factor) => (factor ? this.client.mfa.unenroll({ factorId: factor === null || factor === void 0 ? void 0 : factor.id }) : void 0));
|
||||
return { data: null, error: enrollError };
|
||||
}
|
||||
// Get challenge and create credential
|
||||
const { data: challengeResponse, error: challengeError } = await this._challenge({
|
||||
factorId: factor.id,
|
||||
friendlyName: factor.friendly_name,
|
||||
webauthn: { rpId, rpOrigins },
|
||||
signal,
|
||||
}, {
|
||||
create: overrides,
|
||||
});
|
||||
if (!challengeResponse) {
|
||||
return { data: null, error: challengeError };
|
||||
}
|
||||
return this._verify({
|
||||
factorId: factor.id,
|
||||
challengeId: challengeResponse.challengeId,
|
||||
webauthn: {
|
||||
rpId,
|
||||
rpOrigins,
|
||||
type: challengeResponse.webauthn.type,
|
||||
credential_response: challengeResponse.webauthn.credential_response,
|
||||
},
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
return {
|
||||
data: null,
|
||||
error: new errors_1.AuthUnknownError('Unexpected error in register', error),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.WebAuthnApi = WebAuthnApi;
|
||||
//# sourceMappingURL=webauthn.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../../.nitro/tslib@2.8.1
|
||||
+15
-40
@@ -1,16 +1,16 @@
|
||||
{
|
||||
"name": "@supabase/auth-js",
|
||||
"version": "2.71.1",
|
||||
"version": "2.93.3",
|
||||
"private": false,
|
||||
"description": "Official client library for Supabase Auth",
|
||||
"description": "Official SDK for Supabase Auth",
|
||||
"keywords": [
|
||||
"auth",
|
||||
"supabase",
|
||||
"auth",
|
||||
"authentication"
|
||||
],
|
||||
"homepage": "https://github.com/supabase/auth-js",
|
||||
"bugs": "https://github.com/supabase/auth-js/issues",
|
||||
"homepage": "https://github.com/supabase/supabase-js/tree/master/packages/core/auth-js",
|
||||
"bugs": "https://github.com/supabase/supabase-js/issues",
|
||||
"license": "MIT",
|
||||
"author": "Supabase",
|
||||
"files": [
|
||||
@@ -20,50 +20,25 @@
|
||||
"main": "dist/main/index.js",
|
||||
"module": "dist/module/index.js",
|
||||
"types": "dist/module/index.d.ts",
|
||||
"repository": "github:supabase/auth-js",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/supabase/supabase-js.git",
|
||||
"directory": "packages/core/auth-js"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rimraf dist docs",
|
||||
"coverage": "echo \"run npm test\"",
|
||||
"format": "prettier --write \"{src,test}/**/*.ts\"",
|
||||
"build": "genversion src/lib/version.ts --es6 && run-s clean format build:* && run-s lint",
|
||||
"build": "npm run build:main && npm run build:module",
|
||||
"build:main": "tsc -p tsconfig.json",
|
||||
"build:module": "tsc -p tsconfig.module.json",
|
||||
"lint": "eslint ./src/**/* test/**/*.test.ts",
|
||||
"test": "run-s test:clean test:infra test:suite test:clean",
|
||||
"test:suite": "npm --prefix ./test run test",
|
||||
"test:infra": "cd infra && docker compose down && docker compose pull && docker compose up -d && sleep 30",
|
||||
"test:clean": "cd infra && docker compose down",
|
||||
"docs": "typedoc src/index.ts --out docs/v2 --excludePrivate --excludeProtected",
|
||||
"docs:json": "typedoc --json docs/v2/spec.json --excludeExternals --excludePrivate --excludeProtected src/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@supabase/node-fetch": "^2.6.14"
|
||||
"tslib": "2.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/faker": "^5.1.6",
|
||||
"@types/jest": "^28.1.6",
|
||||
"@types/jsonwebtoken": "^8.5.6",
|
||||
"@types/node": "^18.16.19",
|
||||
"@types/node-fetch": "^2.6.4",
|
||||
"@typescript-eslint/eslint-plugin": "^5.30.7",
|
||||
"@typescript-eslint/parser": "^5.30.7",
|
||||
"eslint": "^8.20.0",
|
||||
"eslint-config-prettier": "^8.5.0",
|
||||
"eslint-config-standard": "^17.0.0",
|
||||
"eslint-plugin-import": "^2.26.0",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
"eslint-plugin-promise": "^6.0.0",
|
||||
"faker": "^5.3.1",
|
||||
"genversion": "^3.1.1",
|
||||
"jest": "^28.1.3",
|
||||
"jest-mock-server": "^0.1.0",
|
||||
"jsonwebtoken": "^9.0.0",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"prettier": "2.7.1",
|
||||
"rimraf": "^3.0.2",
|
||||
"semantic-release-plugin-update-version-in-files": "^1.1.0",
|
||||
"ts-jest": "^28.0.7",
|
||||
"typedoc": "^0.22.16",
|
||||
"typescript": "^4.7.4"
|
||||
"prettier": "^2.8.8"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
}
|
||||
+69
-14
@@ -1,18 +1,26 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.FunctionsClient = void 0;
|
||||
const tslib_1 = require("tslib");
|
||||
const helper_1 = require("./helper");
|
||||
const types_1 = require("./types");
|
||||
/**
|
||||
* Client for invoking Supabase Edge Functions.
|
||||
*/
|
||||
class FunctionsClient {
|
||||
/**
|
||||
* Creates a new Functions client bound to an Edge Functions URL.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { FunctionsClient, FunctionRegion } from '@supabase/functions-js'
|
||||
*
|
||||
* const functions = new FunctionsClient('https://xyzcompany.supabase.co/functions/v1', {
|
||||
* headers: { apikey: 'public-anon-key' },
|
||||
* region: FunctionRegion.UsEast1,
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
constructor(url, { headers = {}, customFetch, region = types_1.FunctionRegion.Any, } = {}) {
|
||||
this.url = url;
|
||||
this.headers = headers;
|
||||
@@ -22,6 +30,10 @@ class FunctionsClient {
|
||||
/**
|
||||
* Updates the authorization header
|
||||
* @param token - the new jwt token sent in the authorisation header
|
||||
* @example
|
||||
* ```ts
|
||||
* functions.setAuth(session.access_token)
|
||||
* ```
|
||||
*/
|
||||
setAuth(token) {
|
||||
this.headers.Authorization = `Bearer ${token}`;
|
||||
@@ -30,12 +42,20 @@ class FunctionsClient {
|
||||
* Invokes a function
|
||||
* @param functionName - The name of the Function to invoke.
|
||||
* @param options - Options for invoking the Function.
|
||||
* @example
|
||||
* ```ts
|
||||
* const { data, error } = await functions.invoke('hello-world', {
|
||||
* body: { name: 'Ada' },
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
invoke(functionName, options = {}) {
|
||||
var _a;
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
invoke(functionName_1) {
|
||||
return tslib_1.__awaiter(this, arguments, void 0, function* (functionName, options = {}) {
|
||||
var _a;
|
||||
let timeoutId;
|
||||
let timeoutController;
|
||||
try {
|
||||
const { headers, method, body: functionArgs } = options;
|
||||
const { headers, method, body: functionArgs, signal, timeout } = options;
|
||||
let _headers = {};
|
||||
let { region } = options;
|
||||
if (!region) {
|
||||
@@ -73,6 +93,33 @@ class FunctionsClient {
|
||||
body = JSON.stringify(functionArgs);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (functionArgs &&
|
||||
typeof functionArgs !== 'string' &&
|
||||
!(typeof Blob !== 'undefined' && functionArgs instanceof Blob) &&
|
||||
!(functionArgs instanceof ArrayBuffer) &&
|
||||
!(typeof FormData !== 'undefined' && functionArgs instanceof FormData)) {
|
||||
body = JSON.stringify(functionArgs);
|
||||
}
|
||||
else {
|
||||
body = functionArgs;
|
||||
}
|
||||
}
|
||||
// Handle timeout by creating an AbortController
|
||||
let effectiveSignal = signal;
|
||||
if (timeout) {
|
||||
timeoutController = new AbortController();
|
||||
timeoutId = setTimeout(() => timeoutController.abort(), timeout);
|
||||
// If user provided their own signal, we need to respect both
|
||||
if (signal) {
|
||||
effectiveSignal = timeoutController.signal;
|
||||
// If the user's signal is aborted, abort our timeout controller too
|
||||
signal.addEventListener('abort', () => timeoutController.abort());
|
||||
}
|
||||
else {
|
||||
effectiveSignal = timeoutController.signal;
|
||||
}
|
||||
}
|
||||
const response = yield this.fetch(url.toString(), {
|
||||
method: method || 'POST',
|
||||
// headers priority is (high to low):
|
||||
@@ -81,6 +128,7 @@ class FunctionsClient {
|
||||
// 3. default Content-Type header
|
||||
headers: Object.assign(Object.assign(Object.assign({}, _headers), this.headers), headers),
|
||||
body,
|
||||
signal: effectiveSignal,
|
||||
}).catch((fetchError) => {
|
||||
throw new types_1.FunctionsFetchError(fetchError);
|
||||
});
|
||||
@@ -96,7 +144,8 @@ class FunctionsClient {
|
||||
if (responseType === 'application/json') {
|
||||
data = yield response.json();
|
||||
}
|
||||
else if (responseType === 'application/octet-stream') {
|
||||
else if (responseType === 'application/octet-stream' ||
|
||||
responseType === 'application/pdf') {
|
||||
data = yield response.blob();
|
||||
}
|
||||
else if (responseType === 'text/event-stream') {
|
||||
@@ -120,6 +169,12 @@ class FunctionsClient {
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
finally {
|
||||
// Clear the timeout if it was set
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+2
-32
@@ -1,41 +1,11 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.resolveFetch = void 0;
|
||||
const resolveFetch = (customFetch) => {
|
||||
let _fetch;
|
||||
if (customFetch) {
|
||||
_fetch = customFetch;
|
||||
return (...args) => customFetch(...args);
|
||||
}
|
||||
else if (typeof fetch === 'undefined') {
|
||||
_fetch = (...args) => Promise.resolve().then(() => __importStar(require('@supabase/node-fetch'))).then(({ default: fetch }) => fetch(...args));
|
||||
}
|
||||
else {
|
||||
_fetch = fetch;
|
||||
}
|
||||
return (...args) => _fetch(...args);
|
||||
return (...args) => fetch(...args);
|
||||
};
|
||||
exports.resolveFetch = resolveFetch;
|
||||
//# sourceMappingURL=helper.js.map
|
||||
+43
-1
@@ -1,6 +1,18 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.FunctionRegion = exports.FunctionsHttpError = exports.FunctionsRelayError = exports.FunctionsFetchError = exports.FunctionsError = void 0;
|
||||
/**
|
||||
* Base error for Supabase Edge Function invocations.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { FunctionsError } from '@supabase/functions-js'
|
||||
*
|
||||
* throw new FunctionsError('Unexpected error invoking function', 'FunctionsError', {
|
||||
* requestId: 'abc123',
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
class FunctionsError extends Error {
|
||||
constructor(message, name = 'FunctionsError', context) {
|
||||
super(message);
|
||||
@@ -9,18 +21,48 @@ class FunctionsError extends Error {
|
||||
}
|
||||
}
|
||||
exports.FunctionsError = FunctionsError;
|
||||
/**
|
||||
* Error thrown when the network request to an Edge Function fails.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { FunctionsFetchError } from '@supabase/functions-js'
|
||||
*
|
||||
* throw new FunctionsFetchError({ requestId: 'abc123' })
|
||||
* ```
|
||||
*/
|
||||
class FunctionsFetchError extends FunctionsError {
|
||||
constructor(context) {
|
||||
super('Failed to send a request to the Edge Function', 'FunctionsFetchError', context);
|
||||
}
|
||||
}
|
||||
exports.FunctionsFetchError = FunctionsFetchError;
|
||||
/**
|
||||
* Error thrown when the Supabase relay cannot reach the Edge Function.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { FunctionsRelayError } from '@supabase/functions-js'
|
||||
*
|
||||
* throw new FunctionsRelayError({ region: 'us-east-1' })
|
||||
* ```
|
||||
*/
|
||||
class FunctionsRelayError extends FunctionsError {
|
||||
constructor(context) {
|
||||
super('Relay Error invoking the Edge Function', 'FunctionsRelayError', context);
|
||||
}
|
||||
}
|
||||
exports.FunctionsRelayError = FunctionsRelayError;
|
||||
/**
|
||||
* Error thrown when the Edge Function returns a non-2xx status code.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { FunctionsHttpError } from '@supabase/functions-js'
|
||||
*
|
||||
* throw new FunctionsHttpError({ status: 500 })
|
||||
* ```
|
||||
*/
|
||||
class FunctionsHttpError extends FunctionsError {
|
||||
constructor(context) {
|
||||
super('Edge Function returned a non-2xx status code', 'FunctionsHttpError', context);
|
||||
@@ -45,5 +87,5 @@ var FunctionRegion;
|
||||
FunctionRegion["UsEast1"] = "us-east-1";
|
||||
FunctionRegion["UsWest1"] = "us-west-1";
|
||||
FunctionRegion["UsWest2"] = "us-west-2";
|
||||
})(FunctionRegion = exports.FunctionRegion || (exports.FunctionRegion = {}));
|
||||
})(FunctionRegion || (exports.FunctionRegion = FunctionRegion = {}));
|
||||
//# sourceMappingURL=types.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../../.nitro/tslib@2.8.1
|
||||
+14
-27
@@ -1,25 +1,24 @@
|
||||
{
|
||||
"name": "@supabase/functions-js",
|
||||
"version": "2.4.5",
|
||||
"description": "JS Client library to interact with Supabase Functions.",
|
||||
"version": "2.93.3",
|
||||
"description": "JS SDK to interact with Supabase Functions.",
|
||||
"main": "dist/main/index.js",
|
||||
"module": "dist/module/index.js",
|
||||
"types": "dist/module/index.d.ts",
|
||||
"sideEffects": false,
|
||||
"scripts": {
|
||||
"clean": "rimraf dist docs/v2",
|
||||
"format": "prettier --write \"{src,test}/**/*.ts\"",
|
||||
"build": "run-s clean format build:*",
|
||||
"build": "npm run build:main && npm run build:module",
|
||||
"build:main": "tsc -p tsconfig.json",
|
||||
"build:module": "tsc -p tsconfig.module.json",
|
||||
"docs": "typedoc src/index.ts --out docs/v2",
|
||||
"docs:json": "typedoc --json docs/v2/spec.json --excludeExternals src/index.ts",
|
||||
"test": "jest",
|
||||
"test:coverage": "jest --coverage"
|
||||
"test:ci": "jest --coverage"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/supabase/functions-js.git"
|
||||
"url": "https://github.com/supabase/supabase-js.git",
|
||||
"directory": "packages/core/functions-js"
|
||||
},
|
||||
"keywords": [
|
||||
"functions",
|
||||
@@ -32,34 +31,22 @@
|
||||
],
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/supabase/functions-js/issues"
|
||||
"url": "https://github.com/supabase/supabase-js/issues"
|
||||
},
|
||||
"homepage": "https://github.com/supabase/functions-js#readme",
|
||||
"homepage": "https://github.com/supabase/supabase-js/tree/master/packages/core/functions-js",
|
||||
"dependencies": {
|
||||
"@supabase/node-fetch": "^2.6.14"
|
||||
"tslib": "2.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sebbo2002/semantic-release-jsr": "^1.0.0",
|
||||
"@types/jest": "^28.1.0",
|
||||
"@types/jsonwebtoken": "^8.5.8",
|
||||
"@types/node": "^18.7.0",
|
||||
"genversion": "^3.0.2",
|
||||
"jest": "^28.1.0",
|
||||
"jsonwebtoken": "^9.0.0",
|
||||
"bs-logger": "^0.2.6",
|
||||
"nanoid": "^3.3.1",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"openai": "^4.52.5",
|
||||
"prettier": "^2.6.0",
|
||||
"rimraf": "^3.0.2",
|
||||
"semantic-release-plugin-update-version-in-files": "^1.1.0",
|
||||
"testcontainers": "^8.5.1",
|
||||
"ts-jest": "^28.0.0",
|
||||
"ts-node": "^10.9.0",
|
||||
"ts-test-decorators": "^0.0.6",
|
||||
"typedoc": "^0.22.13",
|
||||
"typescript": "^4.6.2"
|
||||
"testcontainers": "^8.5.1"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
}
|
||||
-1787
File diff suppressed because it is too large
Load Diff
-80
@@ -1,80 +0,0 @@
|
||||
{
|
||||
"name": "@supabase/node-fetch",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"version": "2.6.15",
|
||||
"description": "A light-weight module that brings window.fetch to node.js",
|
||||
"main": "lib/index.js",
|
||||
"browser": "./browser.js",
|
||||
"files": [
|
||||
"lib/index.js",
|
||||
"lib/index.mjs",
|
||||
"lib/index.es.js",
|
||||
"browser.js"
|
||||
],
|
||||
"engines": {
|
||||
"node": "4.x || >=6.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "cross-env BABEL_ENV=rollup rollup -c",
|
||||
"prepare": "npm run build",
|
||||
"test": "cross-env BABEL_ENV=test mocha --require babel-register --throw-deprecation test/test.js",
|
||||
"report": "cross-env BABEL_ENV=coverage nyc --reporter lcov --reporter text mocha -R spec test/test.js",
|
||||
"coverage": "cross-env BABEL_ENV=coverage nyc --reporter json --reporter text mocha -R spec test/test.js && codecov -f coverage/coverage-final.json"
|
||||
},
|
||||
"repository": "supabase/node-fetch",
|
||||
"keywords": [
|
||||
"fetch",
|
||||
"http",
|
||||
"promise"
|
||||
],
|
||||
"author": "David Frank",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/supabase/node-fetch/issues"
|
||||
},
|
||||
"homepage": "https://github.com/supabase/node-fetch",
|
||||
"dependencies": {
|
||||
"whatwg-url": "^5.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ungap/url-search-params": "^0.1.2",
|
||||
"abort-controller": "^1.1.0",
|
||||
"abortcontroller-polyfill": "^1.3.0",
|
||||
"babel-core": "^6.26.3",
|
||||
"babel-plugin-istanbul": "^4.1.6",
|
||||
"babel-plugin-transform-async-generator-functions": "^6.24.1",
|
||||
"babel-polyfill": "^6.26.0",
|
||||
"babel-preset-env": "1.4.0",
|
||||
"babel-register": "^6.16.3",
|
||||
"chai": "^3.5.0",
|
||||
"chai-as-promised": "^7.1.1",
|
||||
"chai-iterator": "^1.1.1",
|
||||
"chai-string": "~1.3.0",
|
||||
"codecov": "3.3.0",
|
||||
"cross-env": "^5.2.0",
|
||||
"form-data": "^2.3.3",
|
||||
"is-builtin-module": "^1.0.0",
|
||||
"mocha": "^5.0.0",
|
||||
"nyc": "11.9.0",
|
||||
"parted": "^0.1.1",
|
||||
"promise": "^8.0.3",
|
||||
"resumer": "0.0.0",
|
||||
"rollup": "^0.63.4",
|
||||
"rollup-plugin-babel": "^3.0.7",
|
||||
"string-to-arraybuffer": "^1.0.2",
|
||||
"teeny-request": "3.7.0"
|
||||
},
|
||||
"release": {
|
||||
"branches": [
|
||||
"+([0-9]).x",
|
||||
"main",
|
||||
"next",
|
||||
{
|
||||
"name": "beta",
|
||||
"prerelease": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
-222
@@ -1,222 +0,0 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
// @ts-ignore
|
||||
const node_fetch_1 = __importDefault(require("@supabase/node-fetch"));
|
||||
const PostgrestError_1 = __importDefault(require("./PostgrestError"));
|
||||
class PostgrestBuilder {
|
||||
constructor(builder) {
|
||||
var _a, _b;
|
||||
this.shouldThrowOnError = false;
|
||||
this.method = builder.method;
|
||||
this.url = builder.url;
|
||||
this.headers = new Headers(builder.headers);
|
||||
this.schema = builder.schema;
|
||||
this.body = builder.body;
|
||||
this.shouldThrowOnError = (_a = builder.shouldThrowOnError) !== null && _a !== void 0 ? _a : false;
|
||||
this.signal = builder.signal;
|
||||
this.isMaybeSingle = (_b = builder.isMaybeSingle) !== null && _b !== void 0 ? _b : false;
|
||||
if (builder.fetch) {
|
||||
this.fetch = builder.fetch;
|
||||
}
|
||||
else if (typeof fetch === 'undefined') {
|
||||
this.fetch = node_fetch_1.default;
|
||||
}
|
||||
else {
|
||||
this.fetch = fetch;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* If there's an error with the query, throwOnError will reject the promise by
|
||||
* throwing the error instead of returning it as part of a successful response.
|
||||
*
|
||||
* {@link https://github.com/supabase/supabase-js/issues/92}
|
||||
*/
|
||||
throwOnError() {
|
||||
this.shouldThrowOnError = true;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Set an HTTP header for the request.
|
||||
*/
|
||||
setHeader(name, value) {
|
||||
this.headers = new Headers(this.headers);
|
||||
this.headers.set(name, value);
|
||||
return this;
|
||||
}
|
||||
then(onfulfilled, onrejected) {
|
||||
// https://postgrest.org/en/stable/api.html#switching-schemas
|
||||
if (this.schema === undefined) {
|
||||
// skip
|
||||
}
|
||||
else if (['GET', 'HEAD'].includes(this.method)) {
|
||||
this.headers.set('Accept-Profile', this.schema);
|
||||
}
|
||||
else {
|
||||
this.headers.set('Content-Profile', this.schema);
|
||||
}
|
||||
if (this.method !== 'GET' && this.method !== 'HEAD') {
|
||||
this.headers.set('Content-Type', 'application/json');
|
||||
}
|
||||
// NOTE: Invoke w/o `this` to avoid illegal invocation error.
|
||||
// https://github.com/supabase/postgrest-js/pull/247
|
||||
const _fetch = this.fetch;
|
||||
let res = _fetch(this.url.toString(), {
|
||||
method: this.method,
|
||||
headers: this.headers,
|
||||
body: JSON.stringify(this.body),
|
||||
signal: this.signal,
|
||||
}).then(async (res) => {
|
||||
var _a, _b, _c, _d;
|
||||
let error = null;
|
||||
let data = null;
|
||||
let count = null;
|
||||
let status = res.status;
|
||||
let statusText = res.statusText;
|
||||
if (res.ok) {
|
||||
if (this.method !== 'HEAD') {
|
||||
const body = await res.text();
|
||||
if (body === '') {
|
||||
// Prefer: return=minimal
|
||||
}
|
||||
else if (this.headers.get('Accept') === 'text/csv') {
|
||||
data = body;
|
||||
}
|
||||
else if (this.headers.get('Accept') &&
|
||||
((_a = this.headers.get('Accept')) === null || _a === void 0 ? void 0 : _a.includes('application/vnd.pgrst.plan+text'))) {
|
||||
data = body;
|
||||
}
|
||||
else {
|
||||
data = JSON.parse(body);
|
||||
}
|
||||
}
|
||||
const countHeader = (_b = this.headers.get('Prefer')) === null || _b === void 0 ? void 0 : _b.match(/count=(exact|planned|estimated)/);
|
||||
const contentRange = (_c = res.headers.get('content-range')) === null || _c === void 0 ? void 0 : _c.split('/');
|
||||
if (countHeader && contentRange && contentRange.length > 1) {
|
||||
count = parseInt(contentRange[1]);
|
||||
}
|
||||
// Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361
|
||||
// Issue persists e.g. for `.insert([...]).select().maybeSingle()`
|
||||
if (this.isMaybeSingle && this.method === 'GET' && Array.isArray(data)) {
|
||||
if (data.length > 1) {
|
||||
error = {
|
||||
// https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553
|
||||
code: 'PGRST116',
|
||||
details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`,
|
||||
hint: null,
|
||||
message: 'JSON object requested, multiple (or no) rows returned',
|
||||
};
|
||||
data = null;
|
||||
count = null;
|
||||
status = 406;
|
||||
statusText = 'Not Acceptable';
|
||||
}
|
||||
else if (data.length === 1) {
|
||||
data = data[0];
|
||||
}
|
||||
else {
|
||||
data = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
const body = await res.text();
|
||||
try {
|
||||
error = JSON.parse(body);
|
||||
// Workaround for https://github.com/supabase/postgrest-js/issues/295
|
||||
if (Array.isArray(error) && res.status === 404) {
|
||||
data = [];
|
||||
error = null;
|
||||
status = 200;
|
||||
statusText = 'OK';
|
||||
}
|
||||
}
|
||||
catch (_e) {
|
||||
// Workaround for https://github.com/supabase/postgrest-js/issues/295
|
||||
if (res.status === 404 && body === '') {
|
||||
status = 204;
|
||||
statusText = 'No Content';
|
||||
}
|
||||
else {
|
||||
error = {
|
||||
message: body,
|
||||
};
|
||||
}
|
||||
}
|
||||
if (error && this.isMaybeSingle && ((_d = error === null || error === void 0 ? void 0 : error.details) === null || _d === void 0 ? void 0 : _d.includes('0 rows'))) {
|
||||
error = null;
|
||||
status = 200;
|
||||
statusText = 'OK';
|
||||
}
|
||||
if (error && this.shouldThrowOnError) {
|
||||
throw new PostgrestError_1.default(error);
|
||||
}
|
||||
}
|
||||
const postgrestResponse = {
|
||||
error,
|
||||
data,
|
||||
count,
|
||||
status,
|
||||
statusText,
|
||||
};
|
||||
return postgrestResponse;
|
||||
});
|
||||
if (!this.shouldThrowOnError) {
|
||||
res = res.catch((fetchError) => {
|
||||
var _a, _b, _c;
|
||||
return ({
|
||||
error: {
|
||||
message: `${(_a = fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) !== null && _a !== void 0 ? _a : 'FetchError'}: ${fetchError === null || fetchError === void 0 ? void 0 : fetchError.message}`,
|
||||
details: `${(_b = fetchError === null || fetchError === void 0 ? void 0 : fetchError.stack) !== null && _b !== void 0 ? _b : ''}`,
|
||||
hint: '',
|
||||
code: `${(_c = fetchError === null || fetchError === void 0 ? void 0 : fetchError.code) !== null && _c !== void 0 ? _c : ''}`,
|
||||
},
|
||||
data: null,
|
||||
count: null,
|
||||
status: 0,
|
||||
statusText: '',
|
||||
});
|
||||
});
|
||||
}
|
||||
return res.then(onfulfilled, onrejected);
|
||||
}
|
||||
/**
|
||||
* Override the type of the returned `data`.
|
||||
*
|
||||
* @typeParam NewResult - The new result type to override with
|
||||
* @deprecated Use overrideTypes<yourType, { merge: false }>() method at the end of your call chain instead
|
||||
*/
|
||||
returns() {
|
||||
/* istanbul ignore next */
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Override the type of the returned `data` field in the response.
|
||||
*
|
||||
* @typeParam NewResult - The new type to cast the response data to
|
||||
* @typeParam Options - Optional type configuration (defaults to { merge: true })
|
||||
* @typeParam Options.merge - When true, merges the new type with existing return type. When false, replaces the existing types entirely (defaults to true)
|
||||
* @example
|
||||
* ```typescript
|
||||
* // Merge with existing types (default behavior)
|
||||
* const query = supabase
|
||||
* .from('users')
|
||||
* .select()
|
||||
* .overrideTypes<{ custom_field: string }>()
|
||||
*
|
||||
* // Replace existing types completely
|
||||
* const replaceQuery = supabase
|
||||
* .from('users')
|
||||
* .select()
|
||||
* .overrideTypes<{ id: number; name: string }, { merge: false }>()
|
||||
* ```
|
||||
* @returns A PostgrestBuilder instance with the new type
|
||||
*/
|
||||
overrideTypes() {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
exports.default = PostgrestBuilder;
|
||||
//# sourceMappingURL=PostgrestBuilder.js.map
|
||||
-121
@@ -1,121 +0,0 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const PostgrestQueryBuilder_1 = __importDefault(require("./PostgrestQueryBuilder"));
|
||||
const PostgrestFilterBuilder_1 = __importDefault(require("./PostgrestFilterBuilder"));
|
||||
/**
|
||||
* PostgREST client.
|
||||
*
|
||||
* @typeParam Database - Types for the schema from the [type
|
||||
* generator](https://supabase.com/docs/reference/javascript/next/typescript-support)
|
||||
*
|
||||
* @typeParam SchemaName - Postgres schema to switch to. Must be a string
|
||||
* literal, the same one passed to the constructor. If the schema is not
|
||||
* `"public"`, this must be supplied manually.
|
||||
*/
|
||||
class PostgrestClient {
|
||||
// TODO: Add back shouldThrowOnError once we figure out the typings
|
||||
/**
|
||||
* Creates a PostgREST client.
|
||||
*
|
||||
* @param url - URL of the PostgREST endpoint
|
||||
* @param options - Named parameters
|
||||
* @param options.headers - Custom headers
|
||||
* @param options.schema - Postgres schema to switch to
|
||||
* @param options.fetch - Custom fetch
|
||||
*/
|
||||
constructor(url, { headers = {}, schema, fetch, } = {}) {
|
||||
this.url = url;
|
||||
this.headers = new Headers(headers);
|
||||
this.schemaName = schema;
|
||||
this.fetch = fetch;
|
||||
}
|
||||
/**
|
||||
* Perform a query on a table or a view.
|
||||
*
|
||||
* @param relation - The table or view name to query
|
||||
*/
|
||||
from(relation) {
|
||||
const url = new URL(`${this.url}/${relation}`);
|
||||
return new PostgrestQueryBuilder_1.default(url, {
|
||||
headers: new Headers(this.headers),
|
||||
schema: this.schemaName,
|
||||
fetch: this.fetch,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* 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 new PostgrestClient(this.url, {
|
||||
headers: this.headers,
|
||||
schema,
|
||||
fetch: this.fetch,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* 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 = {}, { head = false, get = false, count, } = {}) {
|
||||
var _a;
|
||||
let method;
|
||||
const url = new URL(`${this.url}/rpc/${fn}`);
|
||||
let body;
|
||||
if (head || get) {
|
||||
method = head ? 'HEAD' : 'GET';
|
||||
Object.entries(args)
|
||||
// params with undefined value needs to be filtered out, otherwise it'll
|
||||
// show up as `?param=undefined`
|
||||
.filter(([_, value]) => value !== undefined)
|
||||
// array values need special syntax
|
||||
.map(([name, value]) => [name, Array.isArray(value) ? `{${value.join(',')}}` : `${value}`])
|
||||
.forEach(([name, value]) => {
|
||||
url.searchParams.append(name, value);
|
||||
});
|
||||
}
|
||||
else {
|
||||
method = 'POST';
|
||||
body = args;
|
||||
}
|
||||
const headers = new Headers(this.headers);
|
||||
if (count) {
|
||||
headers.set('Prefer', `count=${count}`);
|
||||
}
|
||||
return new PostgrestFilterBuilder_1.default({
|
||||
method,
|
||||
url,
|
||||
headers,
|
||||
schema: this.schemaName,
|
||||
body,
|
||||
fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch,
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.default = PostgrestClient;
|
||||
//# sourceMappingURL=PostgrestClient.js.map
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
/**
|
||||
* Error format
|
||||
*
|
||||
* {@link https://postgrest.org/en/stable/api.html?highlight=options#errors-and-http-status-codes}
|
||||
*/
|
||||
class PostgrestError extends Error {
|
||||
constructor(context) {
|
||||
super(context.message);
|
||||
this.name = 'PostgrestError';
|
||||
this.details = context.details;
|
||||
this.hint = context.hint;
|
||||
this.code = context.code;
|
||||
}
|
||||
}
|
||||
exports.default = PostgrestError;
|
||||
//# sourceMappingURL=PostgrestError.js.map
|
||||
Generated
Vendored
-381
@@ -1,381 +0,0 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const PostgrestTransformBuilder_1 = __importDefault(require("./PostgrestTransformBuilder"));
|
||||
class PostgrestFilterBuilder extends PostgrestTransformBuilder_1.default {
|
||||
/**
|
||||
* Match only rows where `column` is equal to `value`.
|
||||
*
|
||||
* To check if the value of `column` is NULL, you should use `.is()` instead.
|
||||
*
|
||||
* @param column - The column to filter on
|
||||
* @param value - The value to filter with
|
||||
*/
|
||||
eq(column, value) {
|
||||
this.url.searchParams.append(column, `eq.${value}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Match only rows where `column` is not equal to `value`.
|
||||
*
|
||||
* @param column - The column to filter on
|
||||
* @param value - The value to filter with
|
||||
*/
|
||||
neq(column, value) {
|
||||
this.url.searchParams.append(column, `neq.${value}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Match only rows where `column` is greater than `value`.
|
||||
*
|
||||
* @param column - The column to filter on
|
||||
* @param value - The value to filter with
|
||||
*/
|
||||
gt(column, value) {
|
||||
this.url.searchParams.append(column, `gt.${value}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Match only rows where `column` is greater than or equal to `value`.
|
||||
*
|
||||
* @param column - The column to filter on
|
||||
* @param value - The value to filter with
|
||||
*/
|
||||
gte(column, value) {
|
||||
this.url.searchParams.append(column, `gte.${value}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Match only rows where `column` is less than `value`.
|
||||
*
|
||||
* @param column - The column to filter on
|
||||
* @param value - The value to filter with
|
||||
*/
|
||||
lt(column, value) {
|
||||
this.url.searchParams.append(column, `lt.${value}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Match only rows where `column` is less than or equal to `value`.
|
||||
*
|
||||
* @param column - The column to filter on
|
||||
* @param value - The value to filter with
|
||||
*/
|
||||
lte(column, value) {
|
||||
this.url.searchParams.append(column, `lte.${value}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Match only rows where `column` matches `pattern` case-sensitively.
|
||||
*
|
||||
* @param column - The column to filter on
|
||||
* @param pattern - The pattern to match with
|
||||
*/
|
||||
like(column, pattern) {
|
||||
this.url.searchParams.append(column, `like.${pattern}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Match only rows where `column` matches all of `patterns` case-sensitively.
|
||||
*
|
||||
* @param column - The column to filter on
|
||||
* @param patterns - The patterns to match with
|
||||
*/
|
||||
likeAllOf(column, patterns) {
|
||||
this.url.searchParams.append(column, `like(all).{${patterns.join(',')}}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Match only rows where `column` matches any of `patterns` case-sensitively.
|
||||
*
|
||||
* @param column - The column to filter on
|
||||
* @param patterns - The patterns to match with
|
||||
*/
|
||||
likeAnyOf(column, patterns) {
|
||||
this.url.searchParams.append(column, `like(any).{${patterns.join(',')}}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Match only rows where `column` matches `pattern` case-insensitively.
|
||||
*
|
||||
* @param column - The column to filter on
|
||||
* @param pattern - The pattern to match with
|
||||
*/
|
||||
ilike(column, pattern) {
|
||||
this.url.searchParams.append(column, `ilike.${pattern}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Match only rows where `column` matches all of `patterns` case-insensitively.
|
||||
*
|
||||
* @param column - The column to filter on
|
||||
* @param patterns - The patterns to match with
|
||||
*/
|
||||
ilikeAllOf(column, patterns) {
|
||||
this.url.searchParams.append(column, `ilike(all).{${patterns.join(',')}}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Match only rows where `column` matches any of `patterns` case-insensitively.
|
||||
*
|
||||
* @param column - The column to filter on
|
||||
* @param patterns - The patterns to match with
|
||||
*/
|
||||
ilikeAnyOf(column, patterns) {
|
||||
this.url.searchParams.append(column, `ilike(any).{${patterns.join(',')}}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Match only rows where `column` IS `value`.
|
||||
*
|
||||
* For non-boolean columns, this is only relevant for checking if the value of
|
||||
* `column` is NULL by setting `value` to `null`.
|
||||
*
|
||||
* For boolean columns, you can also set `value` to `true` or `false` and it
|
||||
* will behave the same way as `.eq()`.
|
||||
*
|
||||
* @param column - The column to filter on
|
||||
* @param value - The value to filter with
|
||||
*/
|
||||
is(column, value) {
|
||||
this.url.searchParams.append(column, `is.${value}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Match only rows where `column` is included in the `values` array.
|
||||
*
|
||||
* @param column - The column to filter on
|
||||
* @param values - The values array to filter with
|
||||
*/
|
||||
in(column, values) {
|
||||
const cleanedValues = Array.from(new Set(values))
|
||||
.map((s) => {
|
||||
// handle postgrest reserved characters
|
||||
// https://postgrest.org/en/v7.0.0/api.html#reserved-characters
|
||||
if (typeof s === 'string' && new RegExp('[,()]').test(s))
|
||||
return `"${s}"`;
|
||||
else
|
||||
return `${s}`;
|
||||
})
|
||||
.join(',');
|
||||
this.url.searchParams.append(column, `in.(${cleanedValues})`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Only relevant for jsonb, array, and range columns. Match only rows where
|
||||
* `column` contains every element appearing in `value`.
|
||||
*
|
||||
* @param column - The jsonb, array, or range column to filter on
|
||||
* @param value - The jsonb, array, or range value to filter with
|
||||
*/
|
||||
contains(column, value) {
|
||||
if (typeof value === 'string') {
|
||||
// range types can be inclusive '[', ']' or exclusive '(', ')' so just
|
||||
// keep it simple and accept a string
|
||||
this.url.searchParams.append(column, `cs.${value}`);
|
||||
}
|
||||
else if (Array.isArray(value)) {
|
||||
// array
|
||||
this.url.searchParams.append(column, `cs.{${value.join(',')}}`);
|
||||
}
|
||||
else {
|
||||
// json
|
||||
this.url.searchParams.append(column, `cs.${JSON.stringify(value)}`);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Only relevant for jsonb, array, and range columns. Match only rows where
|
||||
* every element appearing in `column` is contained by `value`.
|
||||
*
|
||||
* @param column - The jsonb, array, or range column to filter on
|
||||
* @param value - The jsonb, array, or range value to filter with
|
||||
*/
|
||||
containedBy(column, value) {
|
||||
if (typeof value === 'string') {
|
||||
// range
|
||||
this.url.searchParams.append(column, `cd.${value}`);
|
||||
}
|
||||
else if (Array.isArray(value)) {
|
||||
// array
|
||||
this.url.searchParams.append(column, `cd.{${value.join(',')}}`);
|
||||
}
|
||||
else {
|
||||
// json
|
||||
this.url.searchParams.append(column, `cd.${JSON.stringify(value)}`);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Only relevant for range columns. Match only rows where every element in
|
||||
* `column` is greater than any element in `range`.
|
||||
*
|
||||
* @param column - The range column to filter on
|
||||
* @param range - The range to filter with
|
||||
*/
|
||||
rangeGt(column, range) {
|
||||
this.url.searchParams.append(column, `sr.${range}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Only relevant for range columns. Match only rows where every element in
|
||||
* `column` is either contained in `range` or greater than any element in
|
||||
* `range`.
|
||||
*
|
||||
* @param column - The range column to filter on
|
||||
* @param range - The range to filter with
|
||||
*/
|
||||
rangeGte(column, range) {
|
||||
this.url.searchParams.append(column, `nxl.${range}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Only relevant for range columns. Match only rows where every element in
|
||||
* `column` is less than any element in `range`.
|
||||
*
|
||||
* @param column - The range column to filter on
|
||||
* @param range - The range to filter with
|
||||
*/
|
||||
rangeLt(column, range) {
|
||||
this.url.searchParams.append(column, `sl.${range}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Only relevant for range columns. Match only rows where every element in
|
||||
* `column` is either contained in `range` or less than any element in
|
||||
* `range`.
|
||||
*
|
||||
* @param column - The range column to filter on
|
||||
* @param range - The range to filter with
|
||||
*/
|
||||
rangeLte(column, range) {
|
||||
this.url.searchParams.append(column, `nxr.${range}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Only relevant for range columns. Match only rows where `column` is
|
||||
* mutually exclusive to `range` and there can be no element between the two
|
||||
* ranges.
|
||||
*
|
||||
* @param column - The range column to filter on
|
||||
* @param range - The range to filter with
|
||||
*/
|
||||
rangeAdjacent(column, range) {
|
||||
this.url.searchParams.append(column, `adj.${range}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Only relevant for array and range columns. Match only rows where
|
||||
* `column` and `value` have an element in common.
|
||||
*
|
||||
* @param column - The array or range column to filter on
|
||||
* @param value - The array or range value to filter with
|
||||
*/
|
||||
overlaps(column, value) {
|
||||
if (typeof value === 'string') {
|
||||
// range
|
||||
this.url.searchParams.append(column, `ov.${value}`);
|
||||
}
|
||||
else {
|
||||
// array
|
||||
this.url.searchParams.append(column, `ov.{${value.join(',')}}`);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Only relevant for text and tsvector columns. Match only rows where
|
||||
* `column` matches the query string in `query`.
|
||||
*
|
||||
* @param column - The text or tsvector column to filter on
|
||||
* @param query - The query text to match with
|
||||
* @param options - Named parameters
|
||||
* @param options.config - The text search configuration to use
|
||||
* @param options.type - Change how the `query` text is interpreted
|
||||
*/
|
||||
textSearch(column, query, { config, type } = {}) {
|
||||
let typePart = '';
|
||||
if (type === 'plain') {
|
||||
typePart = 'pl';
|
||||
}
|
||||
else if (type === 'phrase') {
|
||||
typePart = 'ph';
|
||||
}
|
||||
else if (type === 'websearch') {
|
||||
typePart = 'w';
|
||||
}
|
||||
const configPart = config === undefined ? '' : `(${config})`;
|
||||
this.url.searchParams.append(column, `${typePart}fts${configPart}.${query}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Match only rows where each column in `query` keys is equal to its
|
||||
* associated value. Shorthand for multiple `.eq()`s.
|
||||
*
|
||||
* @param query - The object to filter with, with column names as keys mapped
|
||||
* to their filter values
|
||||
*/
|
||||
match(query) {
|
||||
Object.entries(query).forEach(([column, value]) => {
|
||||
this.url.searchParams.append(column, `eq.${value}`);
|
||||
});
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Match only rows which doesn't satisfy the filter.
|
||||
*
|
||||
* Unlike most filters, `opearator` and `value` are used as-is and need to
|
||||
* follow [PostgREST
|
||||
* syntax](https://postgrest.org/en/stable/api.html#operators). You also need
|
||||
* to make sure they are properly sanitized.
|
||||
*
|
||||
* @param column - The column to filter on
|
||||
* @param operator - The operator to be negated to filter with, following
|
||||
* PostgREST syntax
|
||||
* @param value - The value to filter with, following PostgREST syntax
|
||||
*/
|
||||
not(column, operator, value) {
|
||||
this.url.searchParams.append(column, `not.${operator}.${value}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Match only rows which satisfy at least one of the filters.
|
||||
*
|
||||
* Unlike most filters, `filters` is used as-is and needs to follow [PostgREST
|
||||
* syntax](https://postgrest.org/en/stable/api.html#operators). You also need
|
||||
* to make sure it's properly sanitized.
|
||||
*
|
||||
* It's currently not possible to do an `.or()` filter across multiple tables.
|
||||
*
|
||||
* @param filters - The filters to use, following PostgREST syntax
|
||||
* @param options - Named parameters
|
||||
* @param options.referencedTable - Set this to filter on referenced tables
|
||||
* instead of the parent table
|
||||
* @param options.foreignTable - Deprecated, use `referencedTable` instead
|
||||
*/
|
||||
or(filters, { foreignTable, referencedTable = foreignTable, } = {}) {
|
||||
const key = referencedTable ? `${referencedTable}.or` : 'or';
|
||||
this.url.searchParams.append(key, `(${filters})`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Match only rows which satisfy the filter. This is an escape hatch - you
|
||||
* should use the specific filter methods wherever possible.
|
||||
*
|
||||
* Unlike most filters, `opearator` and `value` are used as-is and need to
|
||||
* follow [PostgREST
|
||||
* syntax](https://postgrest.org/en/stable/api.html#operators). You also need
|
||||
* to make sure they are properly sanitized.
|
||||
*
|
||||
* @param column - The column to filter on
|
||||
* @param operator - The operator to filter with, following PostgREST syntax
|
||||
* @param value - The value to filter with, following PostgREST syntax
|
||||
*/
|
||||
filter(column, operator, value) {
|
||||
this.url.searchParams.append(column, `${operator}.${value}`);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
exports.default = PostgrestFilterBuilder;
|
||||
//# sourceMappingURL=PostgrestFilterBuilder.js.map
|
||||
Generated
Vendored
-251
@@ -1,251 +0,0 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const PostgrestFilterBuilder_1 = __importDefault(require("./PostgrestFilterBuilder"));
|
||||
class PostgrestQueryBuilder {
|
||||
constructor(url, { headers = {}, schema, fetch, }) {
|
||||
this.url = url;
|
||||
this.headers = new Headers(headers);
|
||||
this.schema = schema;
|
||||
this.fetch = fetch;
|
||||
}
|
||||
/**
|
||||
* Perform a SELECT query on the table or view.
|
||||
*
|
||||
* @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName`
|
||||
*
|
||||
* @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.count - Count algorithm to use to count rows in the table or view.
|
||||
*
|
||||
* `"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.
|
||||
*/
|
||||
select(columns, { head = false, count, } = {}) {
|
||||
const method = head ? 'HEAD' : 'GET';
|
||||
// Remove whitespaces except when quoted
|
||||
let quoted = false;
|
||||
const cleanedColumns = (columns !== null && columns !== void 0 ? columns : '*')
|
||||
.split('')
|
||||
.map((c) => {
|
||||
if (/\s/.test(c) && !quoted) {
|
||||
return '';
|
||||
}
|
||||
if (c === '"') {
|
||||
quoted = !quoted;
|
||||
}
|
||||
return c;
|
||||
})
|
||||
.join('');
|
||||
this.url.searchParams.set('select', cleanedColumns);
|
||||
if (count) {
|
||||
this.headers.append('Prefer', `count=${count}`);
|
||||
}
|
||||
return new PostgrestFilterBuilder_1.default({
|
||||
method,
|
||||
url: this.url,
|
||||
headers: this.headers,
|
||||
schema: this.schema,
|
||||
fetch: this.fetch,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Perform an INSERT into the table or view.
|
||||
*
|
||||
* By default, inserted rows are not returned. To return it, chain the call
|
||||
* with `.select()`.
|
||||
*
|
||||
* @param values - The values to insert. Pass an object to insert a single row
|
||||
* or an array to insert multiple rows.
|
||||
*
|
||||
* @param options - Named parameters
|
||||
*
|
||||
* @param options.count - Count algorithm to use to count inserted rows.
|
||||
*
|
||||
* `"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.
|
||||
*
|
||||
* @param options.defaultToNull - Make missing fields default to `null`.
|
||||
* Otherwise, use the default value for the column. Only applies for bulk
|
||||
* inserts.
|
||||
*/
|
||||
insert(values, { count, defaultToNull = true, } = {}) {
|
||||
var _a;
|
||||
const method = 'POST';
|
||||
if (count) {
|
||||
this.headers.append('Prefer', `count=${count}`);
|
||||
}
|
||||
if (!defaultToNull) {
|
||||
this.headers.append('Prefer', `missing=default`);
|
||||
}
|
||||
if (Array.isArray(values)) {
|
||||
const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []);
|
||||
if (columns.length > 0) {
|
||||
const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`);
|
||||
this.url.searchParams.set('columns', uniqueColumns.join(','));
|
||||
}
|
||||
}
|
||||
return new PostgrestFilterBuilder_1.default({
|
||||
method,
|
||||
url: this.url,
|
||||
headers: this.headers,
|
||||
schema: this.schema,
|
||||
body: values,
|
||||
fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Perform an UPSERT on the table or view. Depending on the column(s) passed
|
||||
* to `onConflict`, `.upsert()` allows you to perform the equivalent of
|
||||
* `.insert()` if a row with the corresponding `onConflict` columns doesn't
|
||||
* exist, or if it does exist, perform an alternative action depending on
|
||||
* `ignoreDuplicates`.
|
||||
*
|
||||
* By default, upserted rows are not returned. To return it, chain the call
|
||||
* with `.select()`.
|
||||
*
|
||||
* @param values - The values to upsert with. Pass an object to upsert a
|
||||
* single row or an array to upsert multiple rows.
|
||||
*
|
||||
* @param options - Named parameters
|
||||
*
|
||||
* @param options.onConflict - Comma-separated UNIQUE column(s) to specify how
|
||||
* duplicate rows are determined. Two rows are duplicates if all the
|
||||
* `onConflict` columns are equal.
|
||||
*
|
||||
* @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If
|
||||
* `false`, duplicate rows are merged with existing rows.
|
||||
*
|
||||
* @param options.count - Count algorithm to use to count upserted rows.
|
||||
*
|
||||
* `"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.
|
||||
*
|
||||
* @param options.defaultToNull - Make missing fields default to `null`.
|
||||
* Otherwise, use the default value for the column. This only applies when
|
||||
* inserting new rows, not when merging with existing rows under
|
||||
* `ignoreDuplicates: false`. This also only applies when doing bulk upserts.
|
||||
*/
|
||||
upsert(values, { onConflict, ignoreDuplicates = false, count, defaultToNull = true, } = {}) {
|
||||
var _a;
|
||||
const method = 'POST';
|
||||
this.headers.append('Prefer', `resolution=${ignoreDuplicates ? 'ignore' : 'merge'}-duplicates`);
|
||||
if (onConflict !== undefined)
|
||||
this.url.searchParams.set('on_conflict', onConflict);
|
||||
if (count) {
|
||||
this.headers.append('Prefer', `count=${count}`);
|
||||
}
|
||||
if (!defaultToNull) {
|
||||
this.headers.append('Prefer', 'missing=default');
|
||||
}
|
||||
if (Array.isArray(values)) {
|
||||
const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []);
|
||||
if (columns.length > 0) {
|
||||
const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`);
|
||||
this.url.searchParams.set('columns', uniqueColumns.join(','));
|
||||
}
|
||||
}
|
||||
return new PostgrestFilterBuilder_1.default({
|
||||
method,
|
||||
url: this.url,
|
||||
headers: this.headers,
|
||||
schema: this.schema,
|
||||
body: values,
|
||||
fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Perform an UPDATE on the table or view.
|
||||
*
|
||||
* By default, updated rows are not returned. To return it, chain the call
|
||||
* with `.select()` after filters.
|
||||
*
|
||||
* @param values - The values to update with
|
||||
*
|
||||
* @param options - Named parameters
|
||||
*
|
||||
* @param options.count - Count algorithm to use to count updated rows.
|
||||
*
|
||||
* `"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.
|
||||
*/
|
||||
update(values, { count, } = {}) {
|
||||
var _a;
|
||||
const method = 'PATCH';
|
||||
if (count) {
|
||||
this.headers.append('Prefer', `count=${count}`);
|
||||
}
|
||||
return new PostgrestFilterBuilder_1.default({
|
||||
method,
|
||||
url: this.url,
|
||||
headers: this.headers,
|
||||
schema: this.schema,
|
||||
body: values,
|
||||
fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Perform a DELETE on the table or view.
|
||||
*
|
||||
* By default, deleted rows are not returned. To return it, chain the call
|
||||
* with `.select()` after filters.
|
||||
*
|
||||
* @param options - Named parameters
|
||||
*
|
||||
* @param options.count - Count algorithm to use to count deleted rows.
|
||||
*
|
||||
* `"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.
|
||||
*/
|
||||
delete({ count, } = {}) {
|
||||
var _a;
|
||||
const method = 'DELETE';
|
||||
if (count) {
|
||||
this.headers.append('Prefer', `count=${count}`);
|
||||
}
|
||||
return new PostgrestFilterBuilder_1.default({
|
||||
method,
|
||||
url: this.url,
|
||||
headers: this.headers,
|
||||
schema: this.schema,
|
||||
fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch,
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.default = PostgrestQueryBuilder;
|
||||
//# sourceMappingURL=PostgrestQueryBuilder.js.map
|
||||
Generated
Vendored
-226
@@ -1,226 +0,0 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const PostgrestBuilder_1 = __importDefault(require("./PostgrestBuilder"));
|
||||
class PostgrestTransformBuilder extends PostgrestBuilder_1.default {
|
||||
/**
|
||||
* Perform a SELECT on the query result.
|
||||
*
|
||||
* By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not
|
||||
* return modified rows. By calling this method, modified rows are returned in
|
||||
* `data`.
|
||||
*
|
||||
* @param columns - The columns to retrieve, separated by commas
|
||||
*/
|
||||
select(columns) {
|
||||
// Remove whitespaces except when quoted
|
||||
let quoted = false;
|
||||
const cleanedColumns = (columns !== null && columns !== void 0 ? columns : '*')
|
||||
.split('')
|
||||
.map((c) => {
|
||||
if (/\s/.test(c) && !quoted) {
|
||||
return '';
|
||||
}
|
||||
if (c === '"') {
|
||||
quoted = !quoted;
|
||||
}
|
||||
return c;
|
||||
})
|
||||
.join('');
|
||||
this.url.searchParams.set('select', cleanedColumns);
|
||||
this.headers.append('Prefer', 'return=representation');
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Order the query result by `column`.
|
||||
*
|
||||
* You can call this method multiple times to order by multiple columns.
|
||||
*
|
||||
* You can order referenced tables, but it only affects the ordering of the
|
||||
* parent table if you use `!inner` in the query.
|
||||
*
|
||||
* @param column - The column to order by
|
||||
* @param options - Named parameters
|
||||
* @param options.ascending - If `true`, the result will be in ascending order
|
||||
* @param options.nullsFirst - If `true`, `null`s appear first. If `false`,
|
||||
* `null`s appear last.
|
||||
* @param options.referencedTable - Set this to order a referenced table by
|
||||
* its columns
|
||||
* @param options.foreignTable - Deprecated, use `options.referencedTable`
|
||||
* instead
|
||||
*/
|
||||
order(column, { ascending = true, nullsFirst, foreignTable, referencedTable = foreignTable, } = {}) {
|
||||
const key = referencedTable ? `${referencedTable}.order` : 'order';
|
||||
const existingOrder = this.url.searchParams.get(key);
|
||||
this.url.searchParams.set(key, `${existingOrder ? `${existingOrder},` : ''}${column}.${ascending ? 'asc' : 'desc'}${nullsFirst === undefined ? '' : nullsFirst ? '.nullsfirst' : '.nullslast'}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Limit the query result by `count`.
|
||||
*
|
||||
* @param count - The maximum number of rows to return
|
||||
* @param options - Named parameters
|
||||
* @param options.referencedTable - Set this to limit rows of referenced
|
||||
* tables instead of the parent table
|
||||
* @param options.foreignTable - Deprecated, use `options.referencedTable`
|
||||
* instead
|
||||
*/
|
||||
limit(count, { foreignTable, referencedTable = foreignTable, } = {}) {
|
||||
const key = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`;
|
||||
this.url.searchParams.set(key, `${count}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Limit the query result by starting at an offset `from` and ending at the offset `to`.
|
||||
* Only records within this range are returned.
|
||||
* This respects the query order and if there is no order clause the range could behave unexpectedly.
|
||||
* The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third
|
||||
* and fourth rows of the query.
|
||||
*
|
||||
* @param from - The starting index from which to limit the result
|
||||
* @param to - The last index to which to limit the result
|
||||
* @param options - Named parameters
|
||||
* @param options.referencedTable - Set this to limit rows of referenced
|
||||
* tables instead of the parent table
|
||||
* @param options.foreignTable - Deprecated, use `options.referencedTable`
|
||||
* instead
|
||||
*/
|
||||
range(from, to, { foreignTable, referencedTable = foreignTable, } = {}) {
|
||||
const keyOffset = typeof referencedTable === 'undefined' ? 'offset' : `${referencedTable}.offset`;
|
||||
const keyLimit = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`;
|
||||
this.url.searchParams.set(keyOffset, `${from}`);
|
||||
// Range is inclusive, so add 1
|
||||
this.url.searchParams.set(keyLimit, `${to - from + 1}`);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Set the AbortSignal for the fetch request.
|
||||
*
|
||||
* @param signal - The AbortSignal to use for the fetch request
|
||||
*/
|
||||
abortSignal(signal) {
|
||||
this.signal = signal;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Return `data` as a single object instead of an array of objects.
|
||||
*
|
||||
* Query result must be one row (e.g. using `.limit(1)`), otherwise this
|
||||
* returns an error.
|
||||
*/
|
||||
single() {
|
||||
this.headers.set('Accept', 'application/vnd.pgrst.object+json');
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Return `data` as a single object instead of an array of objects.
|
||||
*
|
||||
* Query result must be zero or one row (e.g. using `.limit(1)`), otherwise
|
||||
* this returns an error.
|
||||
*/
|
||||
maybeSingle() {
|
||||
// Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361
|
||||
// Issue persists e.g. for `.insert([...]).select().maybeSingle()`
|
||||
if (this.method === 'GET') {
|
||||
this.headers.set('Accept', 'application/json');
|
||||
}
|
||||
else {
|
||||
this.headers.set('Accept', 'application/vnd.pgrst.object+json');
|
||||
}
|
||||
this.isMaybeSingle = true;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Return `data` as a string in CSV format.
|
||||
*/
|
||||
csv() {
|
||||
this.headers.set('Accept', 'text/csv');
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Return `data` as an object in [GeoJSON](https://geojson.org) format.
|
||||
*/
|
||||
geojson() {
|
||||
this.headers.set('Accept', 'application/geo+json');
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Return `data` as the EXPLAIN plan for the query.
|
||||
*
|
||||
* You need to enable the
|
||||
* [db_plan_enabled](https://supabase.com/docs/guides/database/debugging-performance#enabling-explain)
|
||||
* setting before using this method.
|
||||
*
|
||||
* @param options - Named parameters
|
||||
*
|
||||
* @param options.analyze - If `true`, the query will be executed and the
|
||||
* actual run time will be returned
|
||||
*
|
||||
* @param options.verbose - If `true`, the query identifier will be returned
|
||||
* and `data` will include the output columns of the query
|
||||
*
|
||||
* @param options.settings - If `true`, include information on configuration
|
||||
* parameters that affect query planning
|
||||
*
|
||||
* @param options.buffers - If `true`, include information on buffer usage
|
||||
*
|
||||
* @param options.wal - If `true`, include information on WAL record generation
|
||||
*
|
||||
* @param options.format - The format of the output, can be `"text"` (default)
|
||||
* or `"json"`
|
||||
*/
|
||||
explain({ analyze = false, verbose = false, settings = false, buffers = false, wal = false, format = 'text', } = {}) {
|
||||
var _a;
|
||||
const options = [
|
||||
analyze ? 'analyze' : null,
|
||||
verbose ? 'verbose' : null,
|
||||
settings ? 'settings' : null,
|
||||
buffers ? 'buffers' : null,
|
||||
wal ? 'wal' : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('|');
|
||||
// An Accept header can carry multiple media types but postgrest-js always sends one
|
||||
const forMediatype = (_a = this.headers.get('Accept')) !== null && _a !== void 0 ? _a : 'application/json';
|
||||
this.headers.set('Accept', `application/vnd.pgrst.plan+${format}; for="${forMediatype}"; options=${options};`);
|
||||
if (format === 'json') {
|
||||
return this;
|
||||
}
|
||||
else {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Rollback the query.
|
||||
*
|
||||
* `data` will still be returned, but the query is not committed.
|
||||
*/
|
||||
rollback() {
|
||||
this.headers.append('Prefer', 'tx=rollback');
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Override the type of the returned `data`.
|
||||
*
|
||||
* @typeParam NewResult - The new result type to override with
|
||||
* @deprecated Use overrideTypes<yourType, { merge: false }>() method at the end of your call chain instead
|
||||
*/
|
||||
returns() {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Set the maximum number of rows that can be affected by the query.
|
||||
* Only available in PostgREST v13+ and only works with PATCH and DELETE methods.
|
||||
*
|
||||
* @param value - The maximum number of rows that can be affected
|
||||
*/
|
||||
maxAffected(value) {
|
||||
this.headers.append('Prefer', 'handling=strict');
|
||||
this.headers.append('Prefer', `max-affected=${value}`);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
exports.default = PostgrestTransformBuilder;
|
||||
//# sourceMappingURL=PostgrestTransformBuilder.js.map
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.PostgrestError = exports.PostgrestBuilder = exports.PostgrestTransformBuilder = exports.PostgrestFilterBuilder = exports.PostgrestQueryBuilder = exports.PostgrestClient = void 0;
|
||||
// Always update wrapper.mjs when updating this file.
|
||||
const PostgrestClient_1 = __importDefault(require("./PostgrestClient"));
|
||||
exports.PostgrestClient = PostgrestClient_1.default;
|
||||
const PostgrestQueryBuilder_1 = __importDefault(require("./PostgrestQueryBuilder"));
|
||||
exports.PostgrestQueryBuilder = PostgrestQueryBuilder_1.default;
|
||||
const PostgrestFilterBuilder_1 = __importDefault(require("./PostgrestFilterBuilder"));
|
||||
exports.PostgrestFilterBuilder = PostgrestFilterBuilder_1.default;
|
||||
const PostgrestTransformBuilder_1 = __importDefault(require("./PostgrestTransformBuilder"));
|
||||
exports.PostgrestTransformBuilder = PostgrestTransformBuilder_1.default;
|
||||
const PostgrestBuilder_1 = __importDefault(require("./PostgrestBuilder"));
|
||||
exports.PostgrestBuilder = PostgrestBuilder_1.default;
|
||||
const PostgrestError_1 = __importDefault(require("./PostgrestError"));
|
||||
exports.PostgrestError = PostgrestError_1.default;
|
||||
exports.default = {
|
||||
PostgrestClient: PostgrestClient_1.default,
|
||||
PostgrestQueryBuilder: PostgrestQueryBuilder_1.default,
|
||||
PostgrestFilterBuilder: PostgrestFilterBuilder_1.default,
|
||||
PostgrestTransformBuilder: PostgrestTransformBuilder_1.default,
|
||||
PostgrestBuilder: PostgrestBuilder_1.default,
|
||||
PostgrestError: PostgrestError_1.default,
|
||||
};
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1253
File diff suppressed because it is too large
Load Diff
+39
-44
@@ -1,74 +1,69 @@
|
||||
{
|
||||
"name": "@supabase/postgrest-js",
|
||||
"version": "1.21.3",
|
||||
"version": "2.93.3",
|
||||
"description": "Isomorphic PostgREST client",
|
||||
"keywords": [
|
||||
"postgrest",
|
||||
"supabase"
|
||||
],
|
||||
"homepage": "https://github.com/supabase/postgrest-js",
|
||||
"bugs": "https://github.com/supabase/postgrest-js/issues",
|
||||
"homepage": "https://github.com/supabase/supabase-js/tree/master/packages/core/postgrest-js",
|
||||
"bugs": "https://github.com/supabase/supabase-js/issues",
|
||||
"license": "MIT",
|
||||
"author": "Supabase",
|
||||
"files": [
|
||||
"dist",
|
||||
"src"
|
||||
],
|
||||
"main": "dist/cjs/index.js",
|
||||
"module": "dist/esm/wrapper.mjs",
|
||||
"main": "dist/index.cjs",
|
||||
"module": "dist/index.mjs",
|
||||
"types": "dist/index.d.cts",
|
||||
"exports": {
|
||||
"import": {
|
||||
"types": "./dist/cjs/index.d.ts",
|
||||
"default": "./dist/esm/wrapper.mjs"
|
||||
".": {
|
||||
"import": {
|
||||
"types": "./dist/index.d.mts",
|
||||
"default": "./dist/index.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/index.d.cts",
|
||||
"default": "./dist/index.cjs"
|
||||
}
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/cjs/index.d.ts",
|
||||
"default": "./dist/cjs/index.js"
|
||||
}
|
||||
"./dist/*": "./dist/*",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/supabase/supabase-js.git",
|
||||
"directory": "packages/core/postgrest-js"
|
||||
},
|
||||
"types": "./dist/cjs/index.d.ts",
|
||||
"repository": "supabase/postgrest-js",
|
||||
"scripts": {
|
||||
"clean": "rimraf dist docs/v2",
|
||||
"format": "prettier --write \"{src,test}/**/*.ts\" wrapper.mjs",
|
||||
"format:check": "prettier --check \"{src,test}/**/*.ts\"",
|
||||
"build": "run-s clean format build:*",
|
||||
"build:cjs": "tsc -p tsconfig.json",
|
||||
"build:esm": "cpy wrapper.mjs dist/esm/",
|
||||
"build": "tsdown",
|
||||
"build:watch": "tsdown --watch",
|
||||
"format": "node scripts/format.js",
|
||||
"format:check": "node scripts/format.js check",
|
||||
"docs": "typedoc src/index.ts --out docs/v2",
|
||||
"docs:json": "typedoc --json docs/v2/spec.json --excludeExternals src/index.ts",
|
||||
"test": "run-s format:check test:types db:clean db:run test:generated-types test:run db:clean && node test/smoke.cjs && node test/smoke.mjs",
|
||||
"test:run": "jest --runInBand --coverage",
|
||||
"test:generated-types": "run-s db:generate-test-types && git diff --exit-code test/types.generated.ts || (echo '❌ Generated types are not up to date. Run npm run db:generate-test-types.' && exit 1)",
|
||||
"test:update": "run-s db:clean db:run db:generate-test-types && jest --runInBand --updateSnapshot && run-s db:clean",
|
||||
"test:types": "run-s build && tsd --files 'test/**/*.test*.ts'",
|
||||
"test:run": "jest --runInBand --coverage -u",
|
||||
"test:smoke": "node test/smoke.cjs && node test/smoke.mjs",
|
||||
"test:types": "tstyche",
|
||||
"test:types:ci": "tstyche --target '4.7,5.5,latest'",
|
||||
"test:types:watch": "chokidar 'src/**/*.ts' 'test/**/*.ts' -c 'npm run test:types'",
|
||||
"type-check": "tsc --noEmit --project tsconfig.json",
|
||||
"type-check:test": "tsc --noEmit --project tsconfig.test.json",
|
||||
"db:clean": "cd test/db && docker compose down --volumes",
|
||||
"db:run": "cd test/db && docker compose up --detach && wait-for-localhost 3000",
|
||||
"db:generate-test-types": "cd test/db && docker compose up --detach && wait-for-localhost 8080 && curl --location 'http://0.0.0.0:8080/generators/typescript?included_schemas=public,personal&detect_one_to_one_relationships=true' > ../types.generated.ts && node ../scripts/update-json-type.js && prettier --write ../types.generated.ts"
|
||||
"type-check:test": "tsc --noEmit --project tsconfig.test.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"@supabase/node-fetch": "^2.6.14"
|
||||
"tslib": "2.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^27.5.1",
|
||||
"chokidar-cli": "^3.0.0",
|
||||
"cpy-cli": "^5.0.0",
|
||||
"jest": "^28.1.0",
|
||||
"node-abort-controller": "^3.0.1",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"prettier": "^2.6.2",
|
||||
"rimraf": "^3.0.2",
|
||||
"semantic-release-plugin-update-version-in-files": "^1.1.0",
|
||||
"ts-expect": "^1.3.0",
|
||||
"ts-jest": "^28.0.3",
|
||||
"tsd": "^0.31.2",
|
||||
"tstyche": "^4.3.0",
|
||||
"type-fest": "^4.32.0",
|
||||
"typedoc": "^0.22.16",
|
||||
"typescript": "^4.5.5",
|
||||
"wait-for-localhost-cli": "^3.0.0",
|
||||
"zod": "^3.25.76"
|
||||
"wait-for-localhost-cli": "^4.0.0",
|
||||
"zod": "^3.25.76",
|
||||
"prettier": "^2.6.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
}
|
||||
+128
-64
@@ -1,47 +1,12 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || (function () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.REALTIME_CHANNEL_STATES = exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_LISTEN_TYPES = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = void 0;
|
||||
const tslib_1 = require("tslib");
|
||||
const constants_1 = require("./lib/constants");
|
||||
const push_1 = __importDefault(require("./lib/push"));
|
||||
const timer_1 = __importDefault(require("./lib/timer"));
|
||||
const RealtimePresence_1 = __importDefault(require("./RealtimePresence"));
|
||||
const Transformers = __importStar(require("./lib/transformers"));
|
||||
const push_1 = tslib_1.__importDefault(require("./lib/push"));
|
||||
const timer_1 = tslib_1.__importDefault(require("./lib/timer"));
|
||||
const RealtimePresence_1 = tslib_1.__importDefault(require("./RealtimePresence"));
|
||||
const Transformers = tslib_1.__importStar(require("./lib/transformers"));
|
||||
const transformers_1 = require("./lib/transformers");
|
||||
var REALTIME_POSTGRES_CHANGES_LISTEN_EVENT;
|
||||
(function (REALTIME_POSTGRES_CHANGES_LISTEN_EVENT) {
|
||||
@@ -71,9 +36,26 @@ exports.REALTIME_CHANNEL_STATES = constants_1.CHANNEL_STATES;
|
||||
* and send and receive messages.
|
||||
*/
|
||||
class RealtimeChannel {
|
||||
/**
|
||||
* Creates a channel that can broadcast messages, sync presence, and listen to Postgres changes.
|
||||
*
|
||||
* The topic determines which realtime stream you are subscribing to. Config options let you
|
||||
* enable acknowledgement for broadcasts, presence tracking, or private channels.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import RealtimeClient from '@supabase/realtime-js'
|
||||
*
|
||||
* const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', {
|
||||
* params: { apikey: 'public-anon-key' },
|
||||
* })
|
||||
* const channel = new RealtimeChannel('realtime:public:messages', { config: {} }, client)
|
||||
* ```
|
||||
*/
|
||||
constructor(
|
||||
/** Topic name can be any string. */
|
||||
topic, params = { config: {} }, socket) {
|
||||
var _a, _b;
|
||||
this.topic = topic;
|
||||
this.params = params;
|
||||
this.socket = socket;
|
||||
@@ -132,18 +114,22 @@ class RealtimeChannel {
|
||||
this.presence = new RealtimePresence_1.default(this);
|
||||
this.broadcastEndpointURL = (0, transformers_1.httpEndpointURL)(this.socket.endPoint);
|
||||
this.private = this.params.config.private || false;
|
||||
if (!this.private && ((_b = (_a = this.params.config) === null || _a === void 0 ? void 0 : _a.broadcast) === null || _b === void 0 ? void 0 : _b.replay)) {
|
||||
throw `tried to use replay on public channel '${this.topic}'. It must be a private channel.`;
|
||||
}
|
||||
}
|
||||
/** Subscribe registers your client with the server */
|
||||
subscribe(callback, timeout = this.timeout) {
|
||||
var _a, _b;
|
||||
var _a, _b, _c;
|
||||
if (!this.socket.isConnected()) {
|
||||
this.socket.connect();
|
||||
}
|
||||
if (this.state == constants_1.CHANNEL_STATES.closed) {
|
||||
const { config: { broadcast, presence, private: isPrivate }, } = this.params;
|
||||
const postgres_changes = (_b = (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.map((r) => r.filter)) !== null && _b !== void 0 ? _b : [];
|
||||
const presence_enabled = !!this.bindings[REALTIME_LISTEN_TYPES.PRESENCE] &&
|
||||
this.bindings[REALTIME_LISTEN_TYPES.PRESENCE].length > 0;
|
||||
const presence_enabled = (!!this.bindings[REALTIME_LISTEN_TYPES.PRESENCE] &&
|
||||
this.bindings[REALTIME_LISTEN_TYPES.PRESENCE].length > 0) ||
|
||||
((_c = this.params.config.presence) === null || _c === void 0 ? void 0 : _c.enabled) === true;
|
||||
const accessTokenPayload = {};
|
||||
const config = {
|
||||
broadcast,
|
||||
@@ -162,7 +148,10 @@ class RealtimeChannel {
|
||||
this.joinPush
|
||||
.receive('ok', async ({ postgres_changes }) => {
|
||||
var _a;
|
||||
this.socket.setAuth();
|
||||
// Only refresh auth if using callback-based tokens
|
||||
if (!this.socket._isManualToken()) {
|
||||
this.socket.setAuth();
|
||||
}
|
||||
if (postgres_changes === undefined) {
|
||||
callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED);
|
||||
return;
|
||||
@@ -177,9 +166,9 @@ class RealtimeChannel {
|
||||
const serverPostgresFilter = postgres_changes && postgres_changes[i];
|
||||
if (serverPostgresFilter &&
|
||||
serverPostgresFilter.event === event &&
|
||||
serverPostgresFilter.schema === schema &&
|
||||
serverPostgresFilter.table === table &&
|
||||
serverPostgresFilter.filter === filter) {
|
||||
RealtimeChannel.isFilterValueEqual(serverPostgresFilter.schema, schema) &&
|
||||
RealtimeChannel.isFilterValueEqual(serverPostgresFilter.table, table) &&
|
||||
RealtimeChannel.isFilterValueEqual(serverPostgresFilter.filter, filter)) {
|
||||
newPostgresBindings.push(Object.assign(Object.assign({}, clientPostgresBinding), { id: serverPostgresFilter.id }));
|
||||
}
|
||||
else {
|
||||
@@ -206,9 +195,19 @@ class RealtimeChannel {
|
||||
}
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Returns the current presence state for this channel.
|
||||
*
|
||||
* The shape is a map keyed by presence key (for example a user id) where each entry contains the
|
||||
* tracked metadata for that user.
|
||||
*/
|
||||
presenceState() {
|
||||
return this.presence.state;
|
||||
}
|
||||
/**
|
||||
* Sends the supplied payload to the presence tracker so other subscribers can see that this
|
||||
* client is online. Use `untrack` to stop broadcasting presence for the same key.
|
||||
*/
|
||||
async track(payload, opts = {}) {
|
||||
return await this.send({
|
||||
type: 'presence',
|
||||
@@ -216,6 +215,9 @@ class RealtimeChannel {
|
||||
payload,
|
||||
}, opts.timeout || this.timeout);
|
||||
}
|
||||
/**
|
||||
* Removes the current presence state for this client.
|
||||
*/
|
||||
async untrack(opts = {}) {
|
||||
return await this.send({
|
||||
type: 'presence',
|
||||
@@ -223,13 +225,61 @@ class RealtimeChannel {
|
||||
}, opts);
|
||||
}
|
||||
on(type, filter, callback) {
|
||||
if (this.state === constants_1.CHANNEL_STATES.joined &&
|
||||
type === REALTIME_LISTEN_TYPES.PRESENCE) {
|
||||
if (this.state === constants_1.CHANNEL_STATES.joined && type === REALTIME_LISTEN_TYPES.PRESENCE) {
|
||||
this.socket.log('channel', `resubscribe to ${this.topic} due to change in presence callbacks on joined channel`);
|
||||
this.unsubscribe().then(() => this.subscribe());
|
||||
this.unsubscribe().then(async () => await this.subscribe());
|
||||
}
|
||||
return this._on(type, filter, callback);
|
||||
}
|
||||
/**
|
||||
* Sends a broadcast message explicitly via REST API.
|
||||
*
|
||||
* This method always uses the REST API endpoint regardless of WebSocket connection state.
|
||||
* Useful when you want to guarantee REST delivery or when gradually migrating from implicit REST fallback.
|
||||
*
|
||||
* @param event The name of the broadcast event
|
||||
* @param payload Payload to be sent (required)
|
||||
* @param opts Options including timeout
|
||||
* @returns Promise resolving to object with success status, and error details if failed
|
||||
*/
|
||||
async httpSend(event, payload, opts = {}) {
|
||||
var _a;
|
||||
if (payload === undefined || payload === null) {
|
||||
return Promise.reject('Payload is required for httpSend()');
|
||||
}
|
||||
const headers = {
|
||||
apikey: this.socket.apiKey ? this.socket.apiKey : '',
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
if (this.socket.accessTokenValue) {
|
||||
headers['Authorization'] = `Bearer ${this.socket.accessTokenValue}`;
|
||||
}
|
||||
const options = {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
messages: [
|
||||
{
|
||||
topic: this.subTopic,
|
||||
event,
|
||||
payload: payload,
|
||||
private: this.private,
|
||||
},
|
||||
],
|
||||
}),
|
||||
};
|
||||
const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a = opts.timeout) !== null && _a !== void 0 ? _a : this.timeout);
|
||||
if (response.status === 202) {
|
||||
return { success: true };
|
||||
}
|
||||
let errorMessage = response.statusText;
|
||||
try {
|
||||
const errorBody = await response.json();
|
||||
errorMessage = errorBody.error || errorBody.message || errorMessage;
|
||||
}
|
||||
catch (_b) { }
|
||||
return Promise.reject(new Error(errorMessage));
|
||||
}
|
||||
/**
|
||||
* Sends a message into the channel.
|
||||
*
|
||||
@@ -242,17 +292,20 @@ class RealtimeChannel {
|
||||
async send(args, opts = {}) {
|
||||
var _a, _b;
|
||||
if (!this._canPush() && args.type === 'broadcast') {
|
||||
console.warn('Realtime send() is automatically falling back to REST API. ' +
|
||||
'This behavior will be deprecated in the future. ' +
|
||||
'Please use httpSend() explicitly for REST delivery.');
|
||||
const { event, payload: endpoint_payload } = args;
|
||||
const authorization = this.socket.accessTokenValue
|
||||
? `Bearer ${this.socket.accessTokenValue}`
|
||||
: '';
|
||||
const headers = {
|
||||
apikey: this.socket.apiKey ? this.socket.apiKey : '',
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
if (this.socket.accessTokenValue) {
|
||||
headers['Authorization'] = `Bearer ${this.socket.accessTokenValue}`;
|
||||
}
|
||||
const options = {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: authorization,
|
||||
apikey: this.socket.apiKey ? this.socket.apiKey : '',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
messages: [
|
||||
{
|
||||
@@ -291,6 +344,10 @@ class RealtimeChannel {
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Updates the payload that will be sent the next time the channel joins (reconnects).
|
||||
* Useful for rotating access tokens or updating config without re-creating the channel.
|
||||
*/
|
||||
updateJoinPayload(payload) {
|
||||
this.joinPush.updatePayload(payload);
|
||||
}
|
||||
@@ -416,8 +473,7 @@ class RealtimeChannel {
|
||||
if (['insert', 'update', 'delete'].includes(typeLower)) {
|
||||
(_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.filter((bind) => {
|
||||
var _a, _b, _c;
|
||||
return (((_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event) === '*' ||
|
||||
((_c = (_b = bind.filter) === null || _b === void 0 ? void 0 : _b.event) === null || _c === void 0 ? void 0 : _c.toLocaleLowerCase()) === typeLower);
|
||||
return ((_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event) === '*' || ((_c = (_b = bind.filter) === null || _b === void 0 ? void 0 : _b.event) === null || _c === void 0 ? void 0 : _c.toLocaleLowerCase()) === typeLower;
|
||||
}).map((bind) => bind.callback(handledPayload, ref));
|
||||
}
|
||||
else {
|
||||
@@ -430,13 +486,11 @@ class RealtimeChannel {
|
||||
return (bindId &&
|
||||
((_b = payload.ids) === null || _b === void 0 ? void 0 : _b.includes(bindId)) &&
|
||||
(bindEvent === '*' ||
|
||||
(bindEvent === null || bindEvent === void 0 ? void 0 : bindEvent.toLocaleLowerCase()) ===
|
||||
((_c = payload.data) === null || _c === void 0 ? void 0 : _c.type.toLocaleLowerCase())));
|
||||
(bindEvent === null || bindEvent === void 0 ? void 0 : bindEvent.toLocaleLowerCase()) === ((_c = payload.data) === null || _c === void 0 ? void 0 : _c.type.toLocaleLowerCase())));
|
||||
}
|
||||
else {
|
||||
const bindEvent = (_e = (_d = bind === null || bind === void 0 ? void 0 : bind.filter) === null || _d === void 0 ? void 0 : _d.event) === null || _e === void 0 ? void 0 : _e.toLocaleLowerCase();
|
||||
return (bindEvent === '*' ||
|
||||
bindEvent === ((_f = payload === null || payload === void 0 ? void 0 : payload.event) === null || _f === void 0 ? void 0 : _f.toLocaleLowerCase()));
|
||||
return bindEvent === '*' || bindEvent === ((_f = payload === null || payload === void 0 ? void 0 : payload.event) === null || _f === void 0 ? void 0 : _f.toLocaleLowerCase());
|
||||
}
|
||||
}
|
||||
else {
|
||||
@@ -521,6 +575,16 @@ class RealtimeChannel {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Compares two optional filter values for equality.
|
||||
* Treats undefined, null, and empty string as equivalent empty values.
|
||||
* @internal
|
||||
*/
|
||||
static isFilterValueEqual(serverValue, clientValue) {
|
||||
const normalizedServer = serverValue !== null && serverValue !== void 0 ? serverValue : undefined;
|
||||
const normalizedClient = clientValue !== null && clientValue !== void 0 ? clientValue : undefined;
|
||||
return normalizedServer === normalizedClient;
|
||||
}
|
||||
/** @internal */
|
||||
_rejoinUntilConnected() {
|
||||
this.rejoinTimer.scheduleTimeout();
|
||||
|
||||
+190
-85
@@ -1,47 +1,12 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || (function () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const websocket_factory_1 = __importDefault(require("./lib/websocket-factory"));
|
||||
const tslib_1 = require("tslib");
|
||||
const websocket_factory_1 = tslib_1.__importDefault(require("./lib/websocket-factory"));
|
||||
const constants_1 = require("./lib/constants");
|
||||
const serializer_1 = __importDefault(require("./lib/serializer"));
|
||||
const timer_1 = __importDefault(require("./lib/timer"));
|
||||
const serializer_1 = tslib_1.__importDefault(require("./lib/serializer"));
|
||||
const timer_1 = tslib_1.__importDefault(require("./lib/timer"));
|
||||
const transformers_1 = require("./lib/transformers");
|
||||
const RealtimeChannel_1 = __importDefault(require("./RealtimeChannel"));
|
||||
const RealtimeChannel_1 = tslib_1.__importDefault(require("./RealtimeChannel"));
|
||||
const noop = () => { };
|
||||
// Connection-related constants
|
||||
const CONNECTION_TIMEOUTS = {
|
||||
@@ -68,6 +33,7 @@ class RealtimeClient {
|
||||
* @param options.params The optional params to pass when connecting.
|
||||
* @param options.headers Deprecated: headers cannot be set on websocket connections and this option will be removed in the future.
|
||||
* @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message.
|
||||
* @param options.heartbeatCallback The optional function to handle heartbeat status and latency.
|
||||
* @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) }
|
||||
* @param options.logLevel Sets the log level for Realtime
|
||||
* @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload))
|
||||
@@ -75,11 +41,22 @@ class RealtimeClient {
|
||||
* @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off.
|
||||
* @param options.worker Use Web Worker to set a side flow. Defaults to false.
|
||||
* @param options.workerUrl The URL of the worker script. Defaults to https://realtime.supabase.com/worker.js that includes a heartbeat event call to keep the connection alive.
|
||||
* @param options.vsn The protocol version to use when connecting. Supported versions are "1.0.0" and "2.0.0". Defaults to "2.0.0".
|
||||
* @example
|
||||
* ```ts
|
||||
* import RealtimeClient from '@supabase/realtime-js'
|
||||
*
|
||||
* const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', {
|
||||
* params: { apikey: 'public-anon-key' },
|
||||
* })
|
||||
* client.connect()
|
||||
* ```
|
||||
*/
|
||||
constructor(endPoint, options) {
|
||||
var _a;
|
||||
this.accessTokenValue = null;
|
||||
this.apiKey = null;
|
||||
this._manuallySetToken = false;
|
||||
this.channels = new Array();
|
||||
this.endPoint = '';
|
||||
this.httpEndpoint = '';
|
||||
@@ -94,6 +71,7 @@ class RealtimeClient {
|
||||
this.heartbeatCallback = noop;
|
||||
this.ref = 0;
|
||||
this.reconnectTimer = null;
|
||||
this.vsn = constants_1.DEFAULT_VSN;
|
||||
this.logger = noop;
|
||||
this.conn = null;
|
||||
this.sendBuffer = [];
|
||||
@@ -108,28 +86,17 @@ class RealtimeClient {
|
||||
this._connectionState = 'disconnected';
|
||||
this._wasManualDisconnect = false;
|
||||
this._authPromise = null;
|
||||
this._heartbeatSentAt = null;
|
||||
/**
|
||||
* Use either custom fetch, if provided, or default fetch to make HTTP requests
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
this._resolveFetch = (customFetch) => {
|
||||
let _fetch;
|
||||
if (customFetch) {
|
||||
_fetch = customFetch;
|
||||
return (...args) => customFetch(...args);
|
||||
}
|
||||
else if (typeof fetch === 'undefined') {
|
||||
// Node.js environment without native fetch
|
||||
_fetch = (...args) => Promise.resolve(`${'@supabase/node-fetch'}`).then(s => __importStar(require(s))).then(({ default: fetch }) => fetch(...args))
|
||||
.catch((error) => {
|
||||
throw new Error(`Failed to load @supabase/node-fetch: ${error.message}. ` +
|
||||
`This is required for HTTP requests in Node.js environments without native fetch.`);
|
||||
});
|
||||
}
|
||||
else {
|
||||
_fetch = fetch;
|
||||
}
|
||||
return (...args) => _fetch(...args);
|
||||
return (...args) => fetch(...args);
|
||||
};
|
||||
// Validate required parameters
|
||||
if (!((_a = options === null || options === void 0 ? void 0 : options.params) === null || _a === void 0 ? void 0 : _a.apikey)) {
|
||||
@@ -154,7 +121,12 @@ class RealtimeClient {
|
||||
return;
|
||||
}
|
||||
this._setConnectionState('connecting');
|
||||
this._setAuthSafely('connect');
|
||||
// Trigger auth if needed and not already in progress
|
||||
// This ensures auth is called for standalone RealtimeClient usage
|
||||
// while avoiding race conditions with SupabaseClient's immediate setAuth call
|
||||
if (this.accessToken && !this._authPromise) {
|
||||
this._setAuthSafely('connect');
|
||||
}
|
||||
// Establish WebSocket connection
|
||||
if (this.transport) {
|
||||
// Use custom transport if provided
|
||||
@@ -191,7 +163,7 @@ class RealtimeClient {
|
||||
* @returns string The URL of the websocket.
|
||||
*/
|
||||
endpointURL() {
|
||||
return this._appendParams(this.endPoint, Object.assign({}, this.params, { vsn: constants_1.VSN }));
|
||||
return this._appendParams(this.endPoint, Object.assign({}, this.params, { vsn: this.vsn }));
|
||||
}
|
||||
/**
|
||||
* Disconnects the socket.
|
||||
@@ -213,12 +185,14 @@ class RealtimeClient {
|
||||
clearTimeout(fallbackTimer);
|
||||
this._setConnectionState('disconnected');
|
||||
};
|
||||
// Close the WebSocket connection
|
||||
if (code) {
|
||||
this.conn.close(code, reason !== null && reason !== void 0 ? reason : '');
|
||||
}
|
||||
else {
|
||||
this.conn.close();
|
||||
// Close the WebSocket connection if close method exists
|
||||
if (typeof this.conn.close === 'function') {
|
||||
if (code) {
|
||||
this.conn.close(code, reason !== null && reason !== void 0 ? reason : '');
|
||||
}
|
||||
else {
|
||||
this.conn.close();
|
||||
}
|
||||
}
|
||||
this._teardownConnection();
|
||||
}
|
||||
@@ -293,6 +267,13 @@ class RealtimeClient {
|
||||
isDisconnecting() {
|
||||
return this._connectionState === 'disconnecting';
|
||||
}
|
||||
/**
|
||||
* Creates (or reuses) a {@link RealtimeChannel} for the provided topic.
|
||||
*
|
||||
* Topics are automatically prefixed with `realtime:` to match the Realtime service.
|
||||
* If a channel with the same topic already exists it will be returned instead of creating
|
||||
* a duplicate connection.
|
||||
*/
|
||||
channel(topic, params = { config: {} }) {
|
||||
const realtimeTopic = `realtime:${topic}`;
|
||||
const exists = this.getChannels().find((c) => c.topic === realtimeTopic);
|
||||
@@ -333,7 +314,18 @@ class RealtimeClient {
|
||||
*
|
||||
* On callback used, it will set the value of the token internal to the client.
|
||||
*
|
||||
* When a token is explicitly provided, it will be preserved across channel operations
|
||||
* (including removeChannel and resubscribe). The `accessToken` callback will not be
|
||||
* invoked until `setAuth()` is called without arguments.
|
||||
*
|
||||
* @param token A JWT string to override the token set on the client.
|
||||
*
|
||||
* @example
|
||||
* // Use a manual token (preserved across resubscribes, ignores accessToken callback)
|
||||
* client.realtime.setAuth('my-custom-jwt')
|
||||
*
|
||||
* // Switch back to using the accessToken callback
|
||||
* client.realtime.setAuth()
|
||||
*/
|
||||
async setAuth(token = null) {
|
||||
this._authPromise = this._performAuth(token);
|
||||
@@ -344,20 +336,39 @@ class RealtimeClient {
|
||||
this._authPromise = null;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Returns true if the current access token was explicitly set via setAuth(token),
|
||||
* false if it was obtained via the accessToken callback.
|
||||
* @internal
|
||||
*/
|
||||
_isManualToken() {
|
||||
return this._manuallySetToken;
|
||||
}
|
||||
/**
|
||||
* Sends a heartbeat message if the socket is connected.
|
||||
*/
|
||||
async sendHeartbeat() {
|
||||
var _a;
|
||||
if (!this.isConnected()) {
|
||||
this.heartbeatCallback('disconnected');
|
||||
try {
|
||||
this.heartbeatCallback('disconnected');
|
||||
}
|
||||
catch (e) {
|
||||
this.log('error', 'error in heartbeat callback', e);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Handle heartbeat timeout and force reconnection if needed
|
||||
if (this.pendingHeartbeatRef) {
|
||||
this.pendingHeartbeatRef = null;
|
||||
this._heartbeatSentAt = null;
|
||||
this.log('transport', 'heartbeat timeout. Attempting to re-establish connection');
|
||||
this.heartbeatCallback('timeout');
|
||||
try {
|
||||
this.heartbeatCallback('timeout');
|
||||
}
|
||||
catch (e) {
|
||||
this.log('error', 'error in heartbeat callback', e);
|
||||
}
|
||||
// Force reconnection after heartbeat timeout
|
||||
this._wasManualDisconnect = false;
|
||||
(_a = this.conn) === null || _a === void 0 ? void 0 : _a.close(constants_1.WS_CLOSE_NORMAL, 'heartbeat timeout');
|
||||
@@ -370,6 +381,7 @@ class RealtimeClient {
|
||||
return;
|
||||
}
|
||||
// Send heartbeat message to server
|
||||
this._heartbeatSentAt = Date.now();
|
||||
this.pendingHeartbeatRef = this._makeRef();
|
||||
this.push({
|
||||
topic: 'phoenix',
|
||||
@@ -377,9 +389,18 @@ class RealtimeClient {
|
||||
payload: {},
|
||||
ref: this.pendingHeartbeatRef,
|
||||
});
|
||||
this.heartbeatCallback('sent');
|
||||
try {
|
||||
this.heartbeatCallback('sent');
|
||||
}
|
||||
catch (e) {
|
||||
this.log('error', 'error in heartbeat callback', e);
|
||||
}
|
||||
this._setAuthSafely('heartbeat');
|
||||
}
|
||||
/**
|
||||
* Sets a callback that receives lifecycle events for internal heartbeat messages.
|
||||
* Useful for instrumenting connection health (e.g. sent/ok/timeout/disconnected).
|
||||
*/
|
||||
onHeartbeat(callback) {
|
||||
this.heartbeatCallback = callback;
|
||||
}
|
||||
@@ -433,11 +454,18 @@ class RealtimeClient {
|
||||
_onConnMessage(rawMessage) {
|
||||
this.decode(rawMessage.data, (msg) => {
|
||||
// Handle heartbeat responses
|
||||
if (msg.topic === 'phoenix' && msg.event === 'phx_reply') {
|
||||
this.heartbeatCallback(msg.payload.status === 'ok' ? 'ok' : 'error');
|
||||
}
|
||||
// Handle pending heartbeat reference cleanup
|
||||
if (msg.ref && msg.ref === this.pendingHeartbeatRef) {
|
||||
if (msg.topic === 'phoenix' &&
|
||||
msg.event === 'phx_reply' &&
|
||||
msg.ref &&
|
||||
msg.ref === this.pendingHeartbeatRef) {
|
||||
const latency = this._heartbeatSentAt ? Date.now() - this._heartbeatSentAt : undefined;
|
||||
try {
|
||||
this.heartbeatCallback(msg.payload.status === 'ok' ? 'ok' : 'error', latency);
|
||||
}
|
||||
catch (e) {
|
||||
this.log('error', 'error in heartbeat callback', e);
|
||||
}
|
||||
this._heartbeatSentAt = null;
|
||||
this.pendingHeartbeatRef = null;
|
||||
}
|
||||
// Log incoming message
|
||||
@@ -490,6 +518,9 @@ class RealtimeClient {
|
||||
this.conn.onerror = (error) => this._onConnError(error);
|
||||
this.conn.onmessage = (event) => this._onConnMessage(event);
|
||||
this.conn.onclose = (event) => this._onConnClose(event);
|
||||
if (this.conn.readyState === constants_1.SOCKET_STATES.open) {
|
||||
this._onConnOpen();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Teardown connection and cleanup resources
|
||||
@@ -497,6 +528,15 @@ class RealtimeClient {
|
||||
*/
|
||||
_teardownConnection() {
|
||||
if (this.conn) {
|
||||
if (this.conn.readyState === constants_1.SOCKET_STATES.open ||
|
||||
this.conn.readyState === constants_1.SOCKET_STATES.connecting) {
|
||||
try {
|
||||
this.conn.close();
|
||||
}
|
||||
catch (e) {
|
||||
this.log('error', 'Error closing connection', e);
|
||||
}
|
||||
}
|
||||
this.conn.onopen = null;
|
||||
this.conn.onerror = null;
|
||||
this.conn.onmessage = null;
|
||||
@@ -504,13 +544,26 @@ class RealtimeClient {
|
||||
this.conn = null;
|
||||
}
|
||||
this._clearAllTimers();
|
||||
this._terminateWorker();
|
||||
this.channels.forEach((channel) => channel.teardown());
|
||||
}
|
||||
/** @internal */
|
||||
_onConnOpen() {
|
||||
this._setConnectionState('connected');
|
||||
this.log('transport', `connected to ${this.endpointURL()}`);
|
||||
this.flushSendBuffer();
|
||||
// Wait for any pending auth operations before flushing send buffer
|
||||
// This ensures channel join messages include the correct access token
|
||||
const authPromise = this._authPromise ||
|
||||
(this.accessToken && !this.accessTokenValue ? this.setAuth() : Promise.resolve());
|
||||
authPromise
|
||||
.then(() => {
|
||||
this.flushSendBuffer();
|
||||
})
|
||||
.catch((e) => {
|
||||
this.log('error', 'error waiting for auth on connect', e);
|
||||
// Proceed anyway to avoid hanging connections
|
||||
this.flushSendBuffer();
|
||||
});
|
||||
this._clearTimer('reconnect');
|
||||
if (!this.worker) {
|
||||
this._startHeartbeat();
|
||||
@@ -539,7 +592,7 @@ class RealtimeClient {
|
||||
this.workerRef = new Worker(objectUrl);
|
||||
this.workerRef.onerror = (error) => {
|
||||
this.log('worker', 'worker error', error.message);
|
||||
this.workerRef.terminate();
|
||||
this._terminateWorker();
|
||||
};
|
||||
this.workerRef.onmessage = (event) => {
|
||||
if (event.data.event === 'keepAlive') {
|
||||
@@ -551,6 +604,17 @@ class RealtimeClient {
|
||||
interval: this.heartbeatIntervalMs,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Terminate the Web Worker and clear the reference
|
||||
* @internal
|
||||
*/
|
||||
_terminateWorker() {
|
||||
if (this.workerRef) {
|
||||
this.log('worker', 'terminating worker');
|
||||
this.workerRef.terminate();
|
||||
this.workerRef = undefined;
|
||||
}
|
||||
}
|
||||
/** @internal */
|
||||
_onConnClose(event) {
|
||||
var _a;
|
||||
@@ -570,6 +634,12 @@ class RealtimeClient {
|
||||
this.log('transport', `${error}`);
|
||||
this._triggerChanError();
|
||||
this._triggerStateCallbacks('error', error);
|
||||
try {
|
||||
this.heartbeatCallback('error');
|
||||
}
|
||||
catch (e) {
|
||||
this.log('error', 'error in heartbeat callback', e);
|
||||
}
|
||||
}
|
||||
/** @internal */
|
||||
_triggerChanError() {
|
||||
@@ -614,16 +684,34 @@ class RealtimeClient {
|
||||
*/
|
||||
async _performAuth(token = null) {
|
||||
let tokenToSend;
|
||||
let isManualToken = false;
|
||||
if (token) {
|
||||
tokenToSend = token;
|
||||
// Track if this is a manually-provided token
|
||||
isManualToken = true;
|
||||
}
|
||||
else if (this.accessToken) {
|
||||
// Always call the accessToken callback to get fresh token
|
||||
tokenToSend = await this.accessToken();
|
||||
// Call the accessToken callback to get fresh token
|
||||
try {
|
||||
tokenToSend = await this.accessToken();
|
||||
}
|
||||
catch (e) {
|
||||
this.log('error', 'Error fetching access token from callback', e);
|
||||
// Fall back to cached value if callback fails
|
||||
tokenToSend = this.accessTokenValue;
|
||||
}
|
||||
}
|
||||
else {
|
||||
tokenToSend = this.accessTokenValue;
|
||||
}
|
||||
// Track whether this token was manually set or fetched via callback
|
||||
if (isManualToken) {
|
||||
this._manuallySetToken = true;
|
||||
}
|
||||
else if (this.accessToken) {
|
||||
// If we used the callback, clear the manual flag
|
||||
this._manuallySetToken = false;
|
||||
}
|
||||
if (this.accessTokenValue != tokenToSend) {
|
||||
this.accessTokenValue = tokenToSend;
|
||||
this.channels.forEach((channel) => {
|
||||
@@ -654,9 +742,12 @@ class RealtimeClient {
|
||||
* @internal
|
||||
*/
|
||||
_setAuthSafely(context = 'general') {
|
||||
this.setAuth().catch((e) => {
|
||||
this.log('error', `error setting auth in ${context}`, e);
|
||||
});
|
||||
// Only refresh auth if using callback-based tokens
|
||||
if (!this._isManualToken()) {
|
||||
this.setAuth().catch((e) => {
|
||||
this.log('error', `Error setting auth in ${context}`, e);
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Trigger state change callbacks with proper error handling
|
||||
@@ -696,7 +787,7 @@ class RealtimeClient {
|
||||
* @internal
|
||||
*/
|
||||
_initializeOptions(options) {
|
||||
var _a, _b, _c, _d, _e, _f, _g, _h;
|
||||
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
|
||||
// Set defaults
|
||||
this.transport = (_a = options === null || options === void 0 ? void 0 : options.transport) !== null && _a !== void 0 ? _a : null;
|
||||
this.timeout = (_b = options === null || options === void 0 ? void 0 : options.timeout) !== null && _b !== void 0 ? _b : constants_1.DEFAULT_TIMEOUT;
|
||||
@@ -704,6 +795,8 @@ class RealtimeClient {
|
||||
(_c = options === null || options === void 0 ? void 0 : options.heartbeatIntervalMs) !== null && _c !== void 0 ? _c : CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL;
|
||||
this.worker = (_d = options === null || options === void 0 ? void 0 : options.worker) !== null && _d !== void 0 ? _d : false;
|
||||
this.accessToken = (_e = options === null || options === void 0 ? void 0 : options.accessToken) !== null && _e !== void 0 ? _e : null;
|
||||
this.heartbeatCallback = (_f = options === null || options === void 0 ? void 0 : options.heartbeatCallback) !== null && _f !== void 0 ? _f : noop;
|
||||
this.vsn = (_g = options === null || options === void 0 ? void 0 : options.vsn) !== null && _g !== void 0 ? _g : constants_1.DEFAULT_VSN;
|
||||
// Handle special cases
|
||||
if (options === null || options === void 0 ? void 0 : options.params)
|
||||
this.params = options.params;
|
||||
@@ -715,15 +808,27 @@ class RealtimeClient {
|
||||
}
|
||||
// Set up functions with defaults
|
||||
this.reconnectAfterMs =
|
||||
(_f = options === null || options === void 0 ? void 0 : options.reconnectAfterMs) !== null && _f !== void 0 ? _f : ((tries) => {
|
||||
(_h = options === null || options === void 0 ? void 0 : options.reconnectAfterMs) !== null && _h !== void 0 ? _h : ((tries) => {
|
||||
return RECONNECT_INTERVALS[tries - 1] || DEFAULT_RECONNECT_FALLBACK;
|
||||
});
|
||||
this.encode =
|
||||
(_g = options === null || options === void 0 ? void 0 : options.encode) !== null && _g !== void 0 ? _g : ((payload, callback) => {
|
||||
return callback(JSON.stringify(payload));
|
||||
});
|
||||
this.decode =
|
||||
(_h = options === null || options === void 0 ? void 0 : options.decode) !== null && _h !== void 0 ? _h : this.serializer.decode.bind(this.serializer);
|
||||
switch (this.vsn) {
|
||||
case constants_1.VSN_1_0_0:
|
||||
this.encode =
|
||||
(_j = options === null || options === void 0 ? void 0 : options.encode) !== null && _j !== void 0 ? _j : ((payload, callback) => {
|
||||
return callback(JSON.stringify(payload));
|
||||
});
|
||||
this.decode =
|
||||
(_k = options === null || options === void 0 ? void 0 : options.decode) !== null && _k !== void 0 ? _k : ((payload, callback) => {
|
||||
return callback(JSON.parse(payload));
|
||||
});
|
||||
break;
|
||||
case constants_1.VSN_2_0_0:
|
||||
this.encode = (_l = options === null || options === void 0 ? void 0 : options.encode) !== null && _l !== void 0 ? _l : this.serializer.encode.bind(this.serializer);
|
||||
this.decode = (_m = options === null || options === void 0 ? void 0 : options.decode) !== null && _m !== void 0 ? _m : this.serializer.decode.bind(this.serializer);
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Unsupported serializer version: ${this.vsn}`);
|
||||
}
|
||||
// Handle worker setup
|
||||
if (this.worker) {
|
||||
if (typeof window !== 'undefined' && !window.Worker) {
|
||||
|
||||
+12
-4
@@ -13,11 +13,19 @@ var REALTIME_PRESENCE_LISTEN_EVENTS;
|
||||
})(REALTIME_PRESENCE_LISTEN_EVENTS || (exports.REALTIME_PRESENCE_LISTEN_EVENTS = REALTIME_PRESENCE_LISTEN_EVENTS = {}));
|
||||
class RealtimePresence {
|
||||
/**
|
||||
* Initializes the Presence.
|
||||
* Creates a Presence helper that keeps the local presence state in sync with the server.
|
||||
*
|
||||
* @param channel - The RealtimeChannel
|
||||
* @param opts - The options,
|
||||
* for example `{events: {state: 'state', diff: 'diff'}}`
|
||||
* @param channel - The realtime channel to bind to.
|
||||
* @param opts - Optional custom event names, e.g. `{ events: { state: 'state', diff: 'diff' } }`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const presence = new RealtimePresence(channel)
|
||||
*
|
||||
* channel.on('presence', ({ event, key }) => {
|
||||
* console.log(`Presence ${event} on ${key}`)
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
constructor(channel, opts) {
|
||||
this.channel = channel;
|
||||
|
||||
+5
-40
@@ -1,53 +1,18 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || (function () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.WebSocketFactory = exports.REALTIME_CHANNEL_STATES = exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_PRESENCE_LISTEN_EVENTS = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = exports.REALTIME_LISTEN_TYPES = exports.RealtimeClient = exports.RealtimeChannel = exports.RealtimePresence = void 0;
|
||||
const RealtimeClient_1 = __importDefault(require("./RealtimeClient"));
|
||||
const tslib_1 = require("tslib");
|
||||
const RealtimeClient_1 = tslib_1.__importDefault(require("./RealtimeClient"));
|
||||
exports.RealtimeClient = RealtimeClient_1.default;
|
||||
const RealtimeChannel_1 = __importStar(require("./RealtimeChannel"));
|
||||
const RealtimeChannel_1 = tslib_1.__importStar(require("./RealtimeChannel"));
|
||||
exports.RealtimeChannel = RealtimeChannel_1.default;
|
||||
Object.defineProperty(exports, "REALTIME_LISTEN_TYPES", { enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_LISTEN_TYPES; } });
|
||||
Object.defineProperty(exports, "REALTIME_POSTGRES_CHANGES_LISTEN_EVENT", { enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT; } });
|
||||
Object.defineProperty(exports, "REALTIME_SUBSCRIBE_STATES", { enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_SUBSCRIBE_STATES; } });
|
||||
Object.defineProperty(exports, "REALTIME_CHANNEL_STATES", { enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_CHANNEL_STATES; } });
|
||||
const RealtimePresence_1 = __importStar(require("./RealtimePresence"));
|
||||
const RealtimePresence_1 = tslib_1.__importStar(require("./RealtimePresence"));
|
||||
exports.RealtimePresence = RealtimePresence_1.default;
|
||||
Object.defineProperty(exports, "REALTIME_PRESENCE_LISTEN_EVENTS", { enumerable: true, get: function () { return RealtimePresence_1.REALTIME_PRESENCE_LISTEN_EVENTS; } });
|
||||
const websocket_factory_1 = __importDefault(require("./lib/websocket-factory"));
|
||||
const websocket_factory_1 = tslib_1.__importDefault(require("./lib/websocket-factory"));
|
||||
exports.WebSocketFactory = websocket_factory_1.default;
|
||||
//# sourceMappingURL=index.js.map
|
||||
+4
-2
@@ -1,9 +1,11 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.CONNECTION_STATE = exports.TRANSPORTS = exports.CHANNEL_EVENTS = exports.CHANNEL_STATES = exports.SOCKET_STATES = exports.MAX_PUSH_BUFFER_SIZE = exports.WS_CLOSE_NORMAL = exports.DEFAULT_TIMEOUT = exports.VERSION = exports.VSN = exports.DEFAULT_VERSION = void 0;
|
||||
exports.CONNECTION_STATE = exports.TRANSPORTS = exports.CHANNEL_EVENTS = exports.CHANNEL_STATES = exports.SOCKET_STATES = exports.MAX_PUSH_BUFFER_SIZE = exports.WS_CLOSE_NORMAL = exports.DEFAULT_TIMEOUT = exports.VERSION = exports.DEFAULT_VSN = exports.VSN_2_0_0 = exports.VSN_1_0_0 = exports.DEFAULT_VERSION = void 0;
|
||||
const version_1 = require("./version");
|
||||
exports.DEFAULT_VERSION = `realtime-js/${version_1.version}`;
|
||||
exports.VSN = '1.0.0';
|
||||
exports.VSN_1_0_0 = '1.0.0';
|
||||
exports.VSN_2_0_0 = '2.0.0';
|
||||
exports.DEFAULT_VSN = exports.VSN_2_0_0;
|
||||
exports.VERSION = version_1.version;
|
||||
exports.DEFAULT_TIMEOUT = 10000;
|
||||
exports.WS_CLOSE_NORMAL = 1000;
|
||||
|
||||
+2
-4
@@ -91,10 +91,8 @@ class Push {
|
||||
clearTimeout(this.timeoutTimer);
|
||||
this.timeoutTimer = undefined;
|
||||
}
|
||||
_matchReceive({ status, response, }) {
|
||||
this.recHooks
|
||||
.filter((h) => h.status === status)
|
||||
.forEach((h) => h.callback(response));
|
||||
_matchReceive({ status, response }) {
|
||||
this.recHooks.filter((h) => h.status === status).forEach((h) => h.callback(response));
|
||||
}
|
||||
_hasReceived(status) {
|
||||
return this.receivedResp && this.receivedResp.status === status;
|
||||
|
||||
+133
-14
@@ -1,35 +1,154 @@
|
||||
"use strict";
|
||||
// This file draws heavily from https://github.com/phoenixframework/phoenix/commit/cf098e9cf7a44ee6479d31d911a97d3c7430c6fe
|
||||
// License: https://github.com/phoenixframework/phoenix/blob/master/LICENSE.md
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
class Serializer {
|
||||
constructor() {
|
||||
constructor(allowedMetadataKeys) {
|
||||
this.HEADER_LENGTH = 1;
|
||||
this.USER_BROADCAST_PUSH_META_LENGTH = 6;
|
||||
this.KINDS = { userBroadcastPush: 3, userBroadcast: 4 };
|
||||
this.BINARY_ENCODING = 0;
|
||||
this.JSON_ENCODING = 1;
|
||||
this.BROADCAST_EVENT = 'broadcast';
|
||||
this.allowedMetadataKeys = [];
|
||||
this.allowedMetadataKeys = allowedMetadataKeys !== null && allowedMetadataKeys !== void 0 ? allowedMetadataKeys : [];
|
||||
}
|
||||
encode(msg, callback) {
|
||||
if (msg.event === this.BROADCAST_EVENT &&
|
||||
!(msg.payload instanceof ArrayBuffer) &&
|
||||
typeof msg.payload.event === 'string') {
|
||||
return callback(this._binaryEncodeUserBroadcastPush(msg));
|
||||
}
|
||||
let payload = [msg.join_ref, msg.ref, msg.topic, msg.event, msg.payload];
|
||||
return callback(JSON.stringify(payload));
|
||||
}
|
||||
_binaryEncodeUserBroadcastPush(message) {
|
||||
var _a;
|
||||
if (this._isArrayBuffer((_a = message.payload) === null || _a === void 0 ? void 0 : _a.payload)) {
|
||||
return this._encodeBinaryUserBroadcastPush(message);
|
||||
}
|
||||
else {
|
||||
return this._encodeJsonUserBroadcastPush(message);
|
||||
}
|
||||
}
|
||||
_encodeBinaryUserBroadcastPush(message) {
|
||||
var _a, _b;
|
||||
const userPayload = (_b = (_a = message.payload) === null || _a === void 0 ? void 0 : _a.payload) !== null && _b !== void 0 ? _b : new ArrayBuffer(0);
|
||||
return this._encodeUserBroadcastPush(message, this.BINARY_ENCODING, userPayload);
|
||||
}
|
||||
_encodeJsonUserBroadcastPush(message) {
|
||||
var _a, _b;
|
||||
const userPayload = (_b = (_a = message.payload) === null || _a === void 0 ? void 0 : _a.payload) !== null && _b !== void 0 ? _b : {};
|
||||
const encoder = new TextEncoder();
|
||||
const encodedUserPayload = encoder.encode(JSON.stringify(userPayload)).buffer;
|
||||
return this._encodeUserBroadcastPush(message, this.JSON_ENCODING, encodedUserPayload);
|
||||
}
|
||||
_encodeUserBroadcastPush(message, encodingType, encodedPayload) {
|
||||
var _a, _b;
|
||||
const topic = message.topic;
|
||||
const ref = (_a = message.ref) !== null && _a !== void 0 ? _a : '';
|
||||
const joinRef = (_b = message.join_ref) !== null && _b !== void 0 ? _b : '';
|
||||
const userEvent = message.payload.event;
|
||||
// Filter metadata based on allowed keys
|
||||
const rest = this.allowedMetadataKeys
|
||||
? this._pick(message.payload, this.allowedMetadataKeys)
|
||||
: {};
|
||||
const metadata = Object.keys(rest).length === 0 ? '' : JSON.stringify(rest);
|
||||
// Validate lengths don't exceed uint8 max value (255)
|
||||
if (joinRef.length > 255) {
|
||||
throw new Error(`joinRef length ${joinRef.length} exceeds maximum of 255`);
|
||||
}
|
||||
if (ref.length > 255) {
|
||||
throw new Error(`ref length ${ref.length} exceeds maximum of 255`);
|
||||
}
|
||||
if (topic.length > 255) {
|
||||
throw new Error(`topic length ${topic.length} exceeds maximum of 255`);
|
||||
}
|
||||
if (userEvent.length > 255) {
|
||||
throw new Error(`userEvent length ${userEvent.length} exceeds maximum of 255`);
|
||||
}
|
||||
if (metadata.length > 255) {
|
||||
throw new Error(`metadata length ${metadata.length} exceeds maximum of 255`);
|
||||
}
|
||||
const metaLength = this.USER_BROADCAST_PUSH_META_LENGTH +
|
||||
joinRef.length +
|
||||
ref.length +
|
||||
topic.length +
|
||||
userEvent.length +
|
||||
metadata.length;
|
||||
const header = new ArrayBuffer(this.HEADER_LENGTH + metaLength);
|
||||
let view = new DataView(header);
|
||||
let offset = 0;
|
||||
view.setUint8(offset++, this.KINDS.userBroadcastPush); // kind
|
||||
view.setUint8(offset++, joinRef.length);
|
||||
view.setUint8(offset++, ref.length);
|
||||
view.setUint8(offset++, topic.length);
|
||||
view.setUint8(offset++, userEvent.length);
|
||||
view.setUint8(offset++, metadata.length);
|
||||
view.setUint8(offset++, encodingType);
|
||||
Array.from(joinRef, (char) => view.setUint8(offset++, char.charCodeAt(0)));
|
||||
Array.from(ref, (char) => view.setUint8(offset++, char.charCodeAt(0)));
|
||||
Array.from(topic, (char) => view.setUint8(offset++, char.charCodeAt(0)));
|
||||
Array.from(userEvent, (char) => view.setUint8(offset++, char.charCodeAt(0)));
|
||||
Array.from(metadata, (char) => view.setUint8(offset++, char.charCodeAt(0)));
|
||||
var combined = new Uint8Array(header.byteLength + encodedPayload.byteLength);
|
||||
combined.set(new Uint8Array(header), 0);
|
||||
combined.set(new Uint8Array(encodedPayload), header.byteLength);
|
||||
return combined.buffer;
|
||||
}
|
||||
decode(rawPayload, callback) {
|
||||
if (rawPayload.constructor === ArrayBuffer) {
|
||||
return callback(this._binaryDecode(rawPayload));
|
||||
if (this._isArrayBuffer(rawPayload)) {
|
||||
let result = this._binaryDecode(rawPayload);
|
||||
return callback(result);
|
||||
}
|
||||
if (typeof rawPayload === 'string') {
|
||||
return callback(JSON.parse(rawPayload));
|
||||
const jsonPayload = JSON.parse(rawPayload);
|
||||
const [join_ref, ref, topic, event, payload] = jsonPayload;
|
||||
return callback({ join_ref, ref, topic, event, payload });
|
||||
}
|
||||
return callback({});
|
||||
}
|
||||
_binaryDecode(buffer) {
|
||||
const view = new DataView(buffer);
|
||||
const kind = view.getUint8(0);
|
||||
const decoder = new TextDecoder();
|
||||
return this._decodeBroadcast(buffer, view, decoder);
|
||||
switch (kind) {
|
||||
case this.KINDS.userBroadcast:
|
||||
return this._decodeUserBroadcast(buffer, view, decoder);
|
||||
}
|
||||
}
|
||||
_decodeBroadcast(buffer, view, decoder) {
|
||||
_decodeUserBroadcast(buffer, view, decoder) {
|
||||
const topicSize = view.getUint8(1);
|
||||
const eventSize = view.getUint8(2);
|
||||
let offset = this.HEADER_LENGTH + 2;
|
||||
const userEventSize = view.getUint8(2);
|
||||
const metadataSize = view.getUint8(3);
|
||||
const payloadEncoding = view.getUint8(4);
|
||||
let offset = this.HEADER_LENGTH + 4;
|
||||
const topic = decoder.decode(buffer.slice(offset, offset + topicSize));
|
||||
offset = offset + topicSize;
|
||||
const event = decoder.decode(buffer.slice(offset, offset + eventSize));
|
||||
offset = offset + eventSize;
|
||||
const data = JSON.parse(decoder.decode(buffer.slice(offset, buffer.byteLength)));
|
||||
return { ref: null, topic: topic, event: event, payload: data };
|
||||
const userEvent = decoder.decode(buffer.slice(offset, offset + userEventSize));
|
||||
offset = offset + userEventSize;
|
||||
const metadata = decoder.decode(buffer.slice(offset, offset + metadataSize));
|
||||
offset = offset + metadataSize;
|
||||
const payload = buffer.slice(offset, buffer.byteLength);
|
||||
const parsedPayload = payloadEncoding === this.JSON_ENCODING ? JSON.parse(decoder.decode(payload)) : payload;
|
||||
const data = {
|
||||
type: this.BROADCAST_EVENT,
|
||||
event: userEvent,
|
||||
payload: parsedPayload,
|
||||
};
|
||||
// Metadata is optional and always JSON encoded
|
||||
if (metadataSize > 0) {
|
||||
data['meta'] = JSON.parse(metadata);
|
||||
}
|
||||
return { join_ref: null, ref: null, topic: topic, event: this.BROADCAST_EVENT, payload: data };
|
||||
}
|
||||
_isArrayBuffer(buffer) {
|
||||
var _a;
|
||||
return buffer instanceof ArrayBuffer || ((_a = buffer === null || buffer === void 0 ? void 0 : buffer.constructor) === null || _a === void 0 ? void 0 : _a.name) === 'ArrayBuffer';
|
||||
}
|
||||
_pick(obj, keys) {
|
||||
if (!obj || typeof obj !== 'object') {
|
||||
return {};
|
||||
}
|
||||
return Object.fromEntries(Object.entries(obj).filter(([key]) => keys.includes(key)));
|
||||
}
|
||||
}
|
||||
exports.default = Serializer;
|
||||
|
||||
+18
-6
@@ -48,6 +48,9 @@ var PostgresTypes;
|
||||
const convertChangeData = (columns, record, options = {}) => {
|
||||
var _a;
|
||||
const skipTypes = (_a = options.skipTypes) !== null && _a !== void 0 ? _a : [];
|
||||
if (!record) {
|
||||
return {};
|
||||
}
|
||||
return Object.keys(record).reduce((acc, rec_key) => {
|
||||
acc[rec_key] = (0, exports.convertColumn)(rec_key, columns, record, skipTypes);
|
||||
return acc;
|
||||
@@ -163,8 +166,7 @@ const toJson = (value) => {
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
}
|
||||
catch (error) {
|
||||
console.log(`JSON parse error: ${error}`);
|
||||
catch (_a) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -220,10 +222,20 @@ const toTimestampString = (value) => {
|
||||
};
|
||||
exports.toTimestampString = toTimestampString;
|
||||
const httpEndpointURL = (socketUrl) => {
|
||||
let url = socketUrl;
|
||||
url = url.replace(/^ws/i, 'http');
|
||||
url = url.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i, '');
|
||||
return url.replace(/\/+$/, '') + '/api/broadcast';
|
||||
const wsUrl = new URL(socketUrl);
|
||||
wsUrl.protocol = wsUrl.protocol.replace(/^ws/i, 'http');
|
||||
wsUrl.pathname = wsUrl.pathname
|
||||
.replace(/\/+$/, '') // remove all trailing slashes
|
||||
.replace(/\/socket\/websocket$/i, '') // remove the socket/websocket path
|
||||
.replace(/\/socket$/i, '') // remove the socket path
|
||||
.replace(/\/websocket$/i, ''); // remove the websocket path
|
||||
if (wsUrl.pathname === '' || wsUrl.pathname === '/') {
|
||||
wsUrl.pathname = '/api/broadcast';
|
||||
}
|
||||
else {
|
||||
wsUrl.pathname = wsUrl.pathname + '/api/broadcast';
|
||||
}
|
||||
return wsUrl.href;
|
||||
};
|
||||
exports.httpEndpointURL = httpEndpointURL;
|
||||
//# sourceMappingURL=transformers.js.map
|
||||
+7
-1
@@ -1,5 +1,11 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.version = void 0;
|
||||
exports.version = '2.15.1';
|
||||
// Generated automatically during releases by scripts/update-version-files.ts
|
||||
// This file provides runtime access to the package version for:
|
||||
// - HTTP request headers (e.g., X-Client-Info header for API requests)
|
||||
// - Debugging and support (identifying which version is running)
|
||||
// - Telemetry and logging (version reporting in errors/analytics)
|
||||
// - Ensuring build artifacts match the published package version
|
||||
exports.version = '2.93.3';
|
||||
//# sourceMappingURL=version.js.map
|
||||
Generated
Vendored
+62
-26
@@ -1,18 +1,23 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.WebSocketFactory = void 0;
|
||||
/**
|
||||
* Utilities for creating WebSocket instances across runtimes.
|
||||
*/
|
||||
class WebSocketFactory {
|
||||
/**
|
||||
* Static-only utility – prevent instantiation.
|
||||
*/
|
||||
constructor() { }
|
||||
static detectEnvironment() {
|
||||
var _a;
|
||||
if (typeof WebSocket !== 'undefined') {
|
||||
return { type: 'native', constructor: WebSocket };
|
||||
}
|
||||
if (typeof globalThis !== 'undefined' &&
|
||||
typeof globalThis.WebSocket !== 'undefined') {
|
||||
if (typeof globalThis !== 'undefined' && typeof globalThis.WebSocket !== 'undefined') {
|
||||
return { type: 'native', constructor: globalThis.WebSocket };
|
||||
}
|
||||
if (typeof global !== 'undefined' &&
|
||||
typeof global.WebSocket !== 'undefined') {
|
||||
if (typeof global !== 'undefined' && typeof global.WebSocket !== 'undefined') {
|
||||
return { type: 'native', constructor: global.WebSocket };
|
||||
}
|
||||
if (typeof globalThis !== 'undefined' &&
|
||||
@@ -25,39 +30,43 @@ class WebSocketFactory {
|
||||
};
|
||||
}
|
||||
if ((typeof globalThis !== 'undefined' && globalThis.EdgeRuntime) ||
|
||||
(typeof navigator !== 'undefined' &&
|
||||
((_a = navigator.userAgent) === null || _a === void 0 ? void 0 : _a.includes('Vercel-Edge')))) {
|
||||
(typeof navigator !== 'undefined' && ((_a = navigator.userAgent) === null || _a === void 0 ? void 0 : _a.includes('Vercel-Edge')))) {
|
||||
return {
|
||||
type: 'unsupported',
|
||||
error: 'Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.',
|
||||
workaround: 'Use serverless functions or a different deployment target for WebSocket functionality.',
|
||||
};
|
||||
}
|
||||
if (typeof process !== 'undefined' &&
|
||||
process.versions &&
|
||||
process.versions.node) {
|
||||
const nodeVersion = parseInt(process.versions.node.split('.')[0]);
|
||||
// Node.js 22+ should have native WebSocket
|
||||
if (nodeVersion >= 22) {
|
||||
// Check if native WebSocket is available (should be in Node.js 22+)
|
||||
if (typeof globalThis.WebSocket !== 'undefined') {
|
||||
return { type: 'native', constructor: globalThis.WebSocket };
|
||||
// Use dynamic property access to avoid Next.js Edge Runtime static analysis warnings
|
||||
const _process = globalThis['process'];
|
||||
if (_process) {
|
||||
const processVersions = _process['versions'];
|
||||
if (processVersions && processVersions['node']) {
|
||||
// Remove 'v' prefix if present and parse the major version
|
||||
const versionString = processVersions['node'];
|
||||
const nodeVersion = parseInt(versionString.replace(/^v/, '').split('.')[0]);
|
||||
// Node.js 22+ should have native WebSocket
|
||||
if (nodeVersion >= 22) {
|
||||
// Check if native WebSocket is available (should be in Node.js 22+)
|
||||
if (typeof globalThis.WebSocket !== 'undefined') {
|
||||
return { type: 'native', constructor: globalThis.WebSocket };
|
||||
}
|
||||
// If not available, user needs to provide it
|
||||
return {
|
||||
type: 'unsupported',
|
||||
error: `Node.js ${nodeVersion} detected but native WebSocket not found.`,
|
||||
workaround: 'Provide a WebSocket implementation via the transport option.',
|
||||
};
|
||||
}
|
||||
// If not available, user needs to provide it
|
||||
// Node.js < 22 doesn't have native WebSocket
|
||||
return {
|
||||
type: 'unsupported',
|
||||
error: `Node.js ${nodeVersion} detected but native WebSocket not found.`,
|
||||
workaround: 'Provide a WebSocket implementation via the transport option.',
|
||||
error: `Node.js ${nodeVersion} detected without native WebSocket support.`,
|
||||
workaround: 'For Node.js < 22, install "ws" package and provide it via the transport option:\n' +
|
||||
'import ws from "ws"\n' +
|
||||
'new RealtimeClient(url, { transport: ws })',
|
||||
};
|
||||
}
|
||||
// Node.js < 22 doesn't have native WebSocket
|
||||
return {
|
||||
type: 'unsupported',
|
||||
error: `Node.js ${nodeVersion} detected without native WebSocket support.`,
|
||||
workaround: 'For Node.js < 22, install "ws" package and provide it via the transport option:\n' +
|
||||
'import ws from "ws"\n' +
|
||||
'new RealtimeClient(url, { transport: ws })',
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: 'unsupported',
|
||||
@@ -65,6 +74,15 @@ class WebSocketFactory {
|
||||
workaround: "Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation.",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Returns the best available WebSocket constructor for the current runtime.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const WS = WebSocketFactory.getWebSocketConstructor()
|
||||
* const socket = new WS('wss://realtime.supabase.co/socket')
|
||||
* ```
|
||||
*/
|
||||
static getWebSocketConstructor() {
|
||||
const env = this.detectEnvironment();
|
||||
if (env.constructor) {
|
||||
@@ -76,10 +94,28 @@ class WebSocketFactory {
|
||||
}
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
/**
|
||||
* Creates a WebSocket using the detected constructor.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const socket = WebSocketFactory.createWebSocket('wss://realtime.supabase.co/socket')
|
||||
* ```
|
||||
*/
|
||||
static createWebSocket(url, protocols) {
|
||||
const WS = this.getWebSocketConstructor();
|
||||
return new WS(url, protocols);
|
||||
}
|
||||
/**
|
||||
* Detects whether the runtime can establish WebSocket connections.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* if (!WebSocketFactory.isWebSocketSupported()) {
|
||||
* console.warn('Falling back to long polling')
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
static isWebSocketSupported() {
|
||||
try {
|
||||
const env = this.detectEnvironment();
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../../.nitro/tslib@2.8.1
|
||||
+17
-22
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@supabase/realtime-js",
|
||||
"version": "2.15.1",
|
||||
"version": "2.93.3",
|
||||
"description": "Listen to realtime updates to your PostgreSQL database",
|
||||
"keywords": [
|
||||
"realtime",
|
||||
@@ -11,8 +11,8 @@
|
||||
"firebase",
|
||||
"supabase"
|
||||
],
|
||||
"homepage": "https://github.com/supabase/realtime-js",
|
||||
"bugs": "https://github.com/supabase/realtime-js/issues",
|
||||
"homepage": "https://github.com/supabase/supabase-js/tree/master/packages/core/realtime-js",
|
||||
"bugs": "https://github.com/supabase/supabase-js/issues",
|
||||
"files": [
|
||||
"dist",
|
||||
"src"
|
||||
@@ -20,46 +20,41 @@
|
||||
"main": "dist/main/index.js",
|
||||
"module": "dist/module/index.js",
|
||||
"types": "dist/module/index.d.ts",
|
||||
"repository": "https://github.com/supabase/realtime-js",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/supabase/supabase-js.git",
|
||||
"directory": "packages/core/realtime-js"
|
||||
},
|
||||
"author": "Supabase",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"clean": "rimraf dist docs/v2",
|
||||
"format": "prettier --write \"{src,test}/**/*.ts\"",
|
||||
"build": "run-s clean format build:*",
|
||||
"build": "npm run build:main && npm run build:module",
|
||||
"build:main": "tsc -p tsconfig.json",
|
||||
"build:module": "tsc -p tsconfig.module.json",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"coverage": "vitest run --coverage",
|
||||
"coverage:text": "vitest run --coverage.enabled true --coverage.reporter=text",
|
||||
"test:coverage": "vitest run --coverage.enabled true --coverage.reporter=text",
|
||||
"docs": "typedoc src/index.ts --out docs/v2",
|
||||
"docs:json": "typedoc --json docs/v2/spec.json --excludeExternals src/index.ts",
|
||||
"check-exports": "attw --pack .",
|
||||
"ci": "run-s test coverage"
|
||||
"test:ci": "vitest run --coverage"
|
||||
},
|
||||
"dependencies": {
|
||||
"@supabase/node-fetch": "^2.6.13",
|
||||
"@types/phoenix": "^1.6.6",
|
||||
"ws": "^8.18.2",
|
||||
"@types/ws": "^8.18.1"
|
||||
"@types/ws": "^8.18.1",
|
||||
"tslib": "2.8.1",
|
||||
"ws": "^8.18.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@arethetypeswrong/cli": "^0.16.4",
|
||||
"@vitest/coverage-v8": "^3.1.4",
|
||||
"eslint": "^9.27.0",
|
||||
"esm": "^3.2.25",
|
||||
"jsdom": "^16.7.0",
|
||||
"jsdom-global": "3.0.0",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"mock-socket": "^9.3.1",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"nyc": "^15.1.0",
|
||||
"prettier": "^2.8.8",
|
||||
"semantic-release-plugin-update-version-in-files": "^1.1.0",
|
||||
"typedoc": "^0.27.9",
|
||||
"typescript": "^5.8.3",
|
||||
"vitest": "^3.1.4",
|
||||
"web-worker": "1.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
}
|
||||
+2616
File diff suppressed because it is too large
Load Diff
-23
@@ -1,23 +0,0 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.StorageClient = void 0;
|
||||
const StorageFileApi_1 = __importDefault(require("./packages/StorageFileApi"));
|
||||
const StorageBucketApi_1 = __importDefault(require("./packages/StorageBucketApi"));
|
||||
class StorageClient extends StorageBucketApi_1.default {
|
||||
constructor(url, headers = {}, fetch, opts) {
|
||||
super(url, headers, fetch, opts);
|
||||
}
|
||||
/**
|
||||
* Perform file operation in a bucket.
|
||||
*
|
||||
* @param id The bucket id to operate on.
|
||||
*/
|
||||
from(id) {
|
||||
return new StorageFileApi_1.default(this.url, this.headers, id, this.fetch);
|
||||
}
|
||||
}
|
||||
exports.StorageClient = StorageClient;
|
||||
//# sourceMappingURL=StorageClient.js.map
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.StorageClient = void 0;
|
||||
var StorageClient_1 = require("./StorageClient");
|
||||
Object.defineProperty(exports, "StorageClient", { enumerable: true, get: function () { return StorageClient_1.StorageClient; } });
|
||||
__exportStar(require("./lib/types"), exports);
|
||||
__exportStar(require("./lib/errors"), exports);
|
||||
//# sourceMappingURL=index.js.map
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DEFAULT_HEADERS = void 0;
|
||||
const version_1 = require("./version");
|
||||
exports.DEFAULT_HEADERS = { 'X-Client-Info': `storage-js/${version_1.version}` };
|
||||
//# sourceMappingURL=constants.js.map
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.StorageUnknownError = exports.StorageApiError = exports.isStorageError = exports.StorageError = void 0;
|
||||
class StorageError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.__isStorageError = true;
|
||||
this.name = 'StorageError';
|
||||
}
|
||||
}
|
||||
exports.StorageError = StorageError;
|
||||
function isStorageError(error) {
|
||||
return typeof error === 'object' && error !== null && '__isStorageError' in error;
|
||||
}
|
||||
exports.isStorageError = isStorageError;
|
||||
class StorageApiError extends StorageError {
|
||||
constructor(message, status, statusCode) {
|
||||
super(message);
|
||||
this.name = 'StorageApiError';
|
||||
this.status = status;
|
||||
this.statusCode = statusCode;
|
||||
}
|
||||
toJSON() {
|
||||
return {
|
||||
name: this.name,
|
||||
message: this.message,
|
||||
status: this.status,
|
||||
statusCode: this.statusCode,
|
||||
};
|
||||
}
|
||||
}
|
||||
exports.StorageApiError = StorageApiError;
|
||||
class StorageUnknownError extends StorageError {
|
||||
constructor(message, originalError) {
|
||||
super(message);
|
||||
this.name = 'StorageUnknownError';
|
||||
this.originalError = originalError;
|
||||
}
|
||||
}
|
||||
exports.StorageUnknownError = StorageUnknownError;
|
||||
//# sourceMappingURL=errors.js.map
|
||||
-97
@@ -1,97 +0,0 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.remove = exports.head = exports.put = exports.post = exports.get = void 0;
|
||||
const errors_1 = require("./errors");
|
||||
const helpers_1 = require("./helpers");
|
||||
const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err);
|
||||
const handleError = (error, reject, options) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const Res = yield (0, helpers_1.resolveResponse)();
|
||||
if (error instanceof Res && !(options === null || options === void 0 ? void 0 : options.noResolveJson)) {
|
||||
error
|
||||
.json()
|
||||
.then((err) => {
|
||||
const status = error.status || 500;
|
||||
const statusCode = (err === null || err === void 0 ? void 0 : err.statusCode) || status + '';
|
||||
reject(new errors_1.StorageApiError(_getErrorMessage(err), status, statusCode));
|
||||
})
|
||||
.catch((err) => {
|
||||
reject(new errors_1.StorageUnknownError(_getErrorMessage(err), err));
|
||||
});
|
||||
}
|
||||
else {
|
||||
reject(new errors_1.StorageUnknownError(_getErrorMessage(error), error));
|
||||
}
|
||||
});
|
||||
const _getRequestParams = (method, options, parameters, body) => {
|
||||
const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} };
|
||||
if (method === 'GET' || !body) {
|
||||
return params;
|
||||
}
|
||||
if ((0, helpers_1.isPlainObject)(body)) {
|
||||
params.headers = Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers);
|
||||
params.body = JSON.stringify(body);
|
||||
}
|
||||
else {
|
||||
params.body = body;
|
||||
}
|
||||
if (options === null || options === void 0 ? void 0 : options.duplex) {
|
||||
params.duplex = options.duplex;
|
||||
}
|
||||
return Object.assign(Object.assign({}, params), parameters);
|
||||
};
|
||||
function _handleRequest(fetcher, method, url, options, parameters, body) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
return new Promise((resolve, reject) => {
|
||||
fetcher(url, _getRequestParams(method, options, parameters, body))
|
||||
.then((result) => {
|
||||
if (!result.ok)
|
||||
throw result;
|
||||
if (options === null || options === void 0 ? void 0 : options.noResolveJson)
|
||||
return result;
|
||||
return result.json();
|
||||
})
|
||||
.then((data) => resolve(data))
|
||||
.catch((error) => handleError(error, reject, options));
|
||||
});
|
||||
});
|
||||
}
|
||||
function get(fetcher, url, options, parameters) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
return _handleRequest(fetcher, 'GET', url, options, parameters);
|
||||
});
|
||||
}
|
||||
exports.get = get;
|
||||
function post(fetcher, url, body, options, parameters) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
return _handleRequest(fetcher, 'POST', url, options, parameters, body);
|
||||
});
|
||||
}
|
||||
exports.post = post;
|
||||
function put(fetcher, url, body, options, parameters) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
return _handleRequest(fetcher, 'PUT', url, options, parameters, body);
|
||||
});
|
||||
}
|
||||
exports.put = put;
|
||||
function head(fetcher, url, options, parameters) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
return _handleRequest(fetcher, 'HEAD', url, Object.assign(Object.assign({}, options), { noResolveJson: true }), parameters);
|
||||
});
|
||||
}
|
||||
exports.head = head;
|
||||
function remove(fetcher, url, body, options, parameters) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
return _handleRequest(fetcher, 'DELETE', url, options, parameters, body);
|
||||
});
|
||||
}
|
||||
exports.remove = remove;
|
||||
//# sourceMappingURL=fetch.js.map
|
||||
-90
@@ -1,90 +0,0 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isPlainObject = exports.recursiveToCamel = exports.resolveResponse = exports.resolveFetch = void 0;
|
||||
const resolveFetch = (customFetch) => {
|
||||
let _fetch;
|
||||
if (customFetch) {
|
||||
_fetch = customFetch;
|
||||
}
|
||||
else if (typeof fetch === 'undefined') {
|
||||
_fetch = (...args) => Promise.resolve().then(() => __importStar(require('@supabase/node-fetch'))).then(({ default: fetch }) => fetch(...args));
|
||||
}
|
||||
else {
|
||||
_fetch = fetch;
|
||||
}
|
||||
return (...args) => _fetch(...args);
|
||||
};
|
||||
exports.resolveFetch = resolveFetch;
|
||||
const resolveResponse = () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
if (typeof Response === 'undefined') {
|
||||
// @ts-ignore
|
||||
return (yield Promise.resolve().then(() => __importStar(require('@supabase/node-fetch')))).Response;
|
||||
}
|
||||
return Response;
|
||||
});
|
||||
exports.resolveResponse = resolveResponse;
|
||||
const recursiveToCamel = (item) => {
|
||||
if (Array.isArray(item)) {
|
||||
return item.map((el) => (0, exports.recursiveToCamel)(el));
|
||||
}
|
||||
else if (typeof item === 'function' || item !== Object(item)) {
|
||||
return item;
|
||||
}
|
||||
const result = {};
|
||||
Object.entries(item).forEach(([key, value]) => {
|
||||
const newKey = key.replace(/([-_][a-z])/gi, (c) => c.toUpperCase().replace(/[-_]/g, ''));
|
||||
result[newKey] = (0, exports.recursiveToCamel)(value);
|
||||
});
|
||||
return result;
|
||||
};
|
||||
exports.recursiveToCamel = recursiveToCamel;
|
||||
/**
|
||||
* Determine if input is a plain object
|
||||
* An object is plain if it's created by either {}, new Object(), or Object.create(null)
|
||||
* source: https://github.com/sindresorhus/is-plain-obj
|
||||
*/
|
||||
const isPlainObject = (value) => {
|
||||
if (typeof value !== 'object' || value === null) {
|
||||
return false;
|
||||
}
|
||||
const prototype = Object.getPrototypeOf(value);
|
||||
return ((prototype === null ||
|
||||
prototype === Object.prototype ||
|
||||
Object.getPrototypeOf(prototype) === null) &&
|
||||
!(Symbol.toStringTag in value) &&
|
||||
!(Symbol.iterator in value));
|
||||
};
|
||||
exports.isPlainObject = isPlainObject;
|
||||
//# sourceMappingURL=helpers.js.map
|
||||
-3
@@ -1,3 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
//# sourceMappingURL=types.js.map
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.version = void 0;
|
||||
// generated by genversion
|
||||
exports.version = '2.11.0';
|
||||
//# sourceMappingURL=version.js.map
|
||||
Generated
Vendored
-178
@@ -1,178 +0,0 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const constants_1 = require("../lib/constants");
|
||||
const errors_1 = require("../lib/errors");
|
||||
const fetch_1 = require("../lib/fetch");
|
||||
const helpers_1 = require("../lib/helpers");
|
||||
class StorageBucketApi {
|
||||
constructor(url, headers = {}, fetch, opts) {
|
||||
const baseUrl = new URL(url);
|
||||
// if legacy uri is used, replace with new storage host (disables request buffering to allow > 50GB uploads)
|
||||
// "project-ref.supabase.co" becomes "project-ref.storage.supabase.co"
|
||||
if (opts === null || opts === void 0 ? void 0 : opts.useNewHostname) {
|
||||
const isSupabaseHost = /supabase\.(co|in|red)$/.test(baseUrl.hostname);
|
||||
if (isSupabaseHost && !baseUrl.hostname.includes('storage.supabase.')) {
|
||||
baseUrl.hostname = baseUrl.hostname.replace('supabase.', 'storage.supabase.');
|
||||
}
|
||||
}
|
||||
this.url = baseUrl.href;
|
||||
this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers);
|
||||
this.fetch = (0, helpers_1.resolveFetch)(fetch);
|
||||
}
|
||||
/**
|
||||
* Retrieves the details of all Storage buckets within an existing project.
|
||||
*/
|
||||
listBuckets() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/bucket`, { headers: this.headers });
|
||||
return { data, error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isStorageError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Retrieves the details of an existing Storage bucket.
|
||||
*
|
||||
* @param id The unique identifier of the bucket you would like to retrieve.
|
||||
*/
|
||||
getBucket(id) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/bucket/${id}`, { headers: this.headers });
|
||||
return { data, error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isStorageError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Creates a new Storage bucket
|
||||
*
|
||||
* @param id A unique identifier for the bucket you are creating.
|
||||
* @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private.
|
||||
* @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket.
|
||||
* The global file size limit takes precedence over this value.
|
||||
* The default value is null, which doesn't set a per bucket file size limit.
|
||||
* @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload.
|
||||
* The default value is null, which allows files with all mime types to be uploaded.
|
||||
* Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png.
|
||||
* @returns newly created bucket id
|
||||
* @param options.type (private-beta) specifies the bucket type. see `BucketType` for more details.
|
||||
* - default bucket type is `STANDARD`
|
||||
*/
|
||||
createBucket(id, options = {
|
||||
public: false,
|
||||
}) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket`, {
|
||||
id,
|
||||
name: id,
|
||||
type: options.type,
|
||||
public: options.public,
|
||||
file_size_limit: options.fileSizeLimit,
|
||||
allowed_mime_types: options.allowedMimeTypes,
|
||||
}, { headers: this.headers });
|
||||
return { data, error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isStorageError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Updates a Storage bucket
|
||||
*
|
||||
* @param id A unique identifier for the bucket you are updating.
|
||||
* @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations.
|
||||
* @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket.
|
||||
* The global file size limit takes precedence over this value.
|
||||
* The default value is null, which doesn't set a per bucket file size limit.
|
||||
* @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload.
|
||||
* The default value is null, which allows files with all mime types to be uploaded.
|
||||
* Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png.
|
||||
*/
|
||||
updateBucket(id, options) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
const data = yield (0, fetch_1.put)(this.fetch, `${this.url}/bucket/${id}`, {
|
||||
id,
|
||||
name: id,
|
||||
public: options.public,
|
||||
file_size_limit: options.fileSizeLimit,
|
||||
allowed_mime_types: options.allowedMimeTypes,
|
||||
}, { headers: this.headers });
|
||||
return { data, error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isStorageError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Removes all objects inside a single bucket.
|
||||
*
|
||||
* @param id The unique identifier of the bucket you would like to empty.
|
||||
*/
|
||||
emptyBucket(id) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket/${id}/empty`, {}, { headers: this.headers });
|
||||
return { data, error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isStorageError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Deletes an existing bucket. A bucket can't be deleted with existing objects inside it.
|
||||
* You must first `empty()` the bucket.
|
||||
*
|
||||
* @param id The unique identifier of the bucket you would like to delete.
|
||||
*/
|
||||
deleteBucket(id) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/bucket/${id}`, {}, { headers: this.headers });
|
||||
return { data, error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isStorageError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.default = StorageBucketApi;
|
||||
//# sourceMappingURL=StorageBucketApi.js.map
|
||||
Generated
Vendored
-556
@@ -1,556 +0,0 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const errors_1 = require("../lib/errors");
|
||||
const fetch_1 = require("../lib/fetch");
|
||||
const helpers_1 = require("../lib/helpers");
|
||||
const DEFAULT_SEARCH_OPTIONS = {
|
||||
limit: 100,
|
||||
offset: 0,
|
||||
sortBy: {
|
||||
column: 'name',
|
||||
order: 'asc',
|
||||
},
|
||||
};
|
||||
const DEFAULT_FILE_OPTIONS = {
|
||||
cacheControl: '3600',
|
||||
contentType: 'text/plain;charset=UTF-8',
|
||||
upsert: false,
|
||||
};
|
||||
class StorageFileApi {
|
||||
constructor(url, headers = {}, bucketId, fetch) {
|
||||
this.url = url;
|
||||
this.headers = headers;
|
||||
this.bucketId = bucketId;
|
||||
this.fetch = (0, helpers_1.resolveFetch)(fetch);
|
||||
}
|
||||
/**
|
||||
* Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one.
|
||||
*
|
||||
* @param method HTTP method.
|
||||
* @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
|
||||
* @param fileBody The body of the file to be stored in the bucket.
|
||||
*/
|
||||
uploadOrUpdate(method, path, fileBody, fileOptions) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
let body;
|
||||
const options = Object.assign(Object.assign({}, DEFAULT_FILE_OPTIONS), fileOptions);
|
||||
let headers = Object.assign(Object.assign({}, this.headers), (method === 'POST' && { 'x-upsert': String(options.upsert) }));
|
||||
const metadata = options.metadata;
|
||||
if (typeof Blob !== 'undefined' && fileBody instanceof Blob) {
|
||||
body = new FormData();
|
||||
body.append('cacheControl', options.cacheControl);
|
||||
if (metadata) {
|
||||
body.append('metadata', this.encodeMetadata(metadata));
|
||||
}
|
||||
body.append('', fileBody);
|
||||
}
|
||||
else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) {
|
||||
body = fileBody;
|
||||
body.append('cacheControl', options.cacheControl);
|
||||
if (metadata) {
|
||||
body.append('metadata', this.encodeMetadata(metadata));
|
||||
}
|
||||
}
|
||||
else {
|
||||
body = fileBody;
|
||||
headers['cache-control'] = `max-age=${options.cacheControl}`;
|
||||
headers['content-type'] = options.contentType;
|
||||
if (metadata) {
|
||||
headers['x-metadata'] = this.toBase64(this.encodeMetadata(metadata));
|
||||
}
|
||||
}
|
||||
if (fileOptions === null || fileOptions === void 0 ? void 0 : fileOptions.headers) {
|
||||
headers = Object.assign(Object.assign({}, headers), fileOptions.headers);
|
||||
}
|
||||
const cleanPath = this._removeEmptyFolders(path);
|
||||
const _path = this._getFinalPath(cleanPath);
|
||||
const data = yield (method == 'PUT' ? fetch_1.put : fetch_1.post)(this.fetch, `${this.url}/object/${_path}`, body, Object.assign({ headers }, ((options === null || options === void 0 ? void 0 : options.duplex) ? { duplex: options.duplex } : {})));
|
||||
return {
|
||||
data: { path: cleanPath, id: data.Id, fullPath: data.Key },
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isStorageError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Uploads a file to an existing bucket.
|
||||
*
|
||||
* @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
|
||||
* @param fileBody The body of the file to be stored in the bucket.
|
||||
*/
|
||||
upload(path, fileBody, fileOptions) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
return this.uploadOrUpdate('POST', path, fileBody, fileOptions);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Upload a file with a token generated from `createSignedUploadUrl`.
|
||||
* @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
|
||||
* @param token The token generated from `createSignedUploadUrl`
|
||||
* @param fileBody The body of the file to be stored in the bucket.
|
||||
*/
|
||||
uploadToSignedUrl(path, token, fileBody, fileOptions) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const cleanPath = this._removeEmptyFolders(path);
|
||||
const _path = this._getFinalPath(cleanPath);
|
||||
const url = new URL(this.url + `/object/upload/sign/${_path}`);
|
||||
url.searchParams.set('token', token);
|
||||
try {
|
||||
let body;
|
||||
const options = Object.assign({ upsert: DEFAULT_FILE_OPTIONS.upsert }, fileOptions);
|
||||
const headers = Object.assign(Object.assign({}, this.headers), { 'x-upsert': String(options.upsert) });
|
||||
if (typeof Blob !== 'undefined' && fileBody instanceof Blob) {
|
||||
body = new FormData();
|
||||
body.append('cacheControl', options.cacheControl);
|
||||
body.append('', fileBody);
|
||||
}
|
||||
else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) {
|
||||
body = fileBody;
|
||||
body.append('cacheControl', options.cacheControl);
|
||||
}
|
||||
else {
|
||||
body = fileBody;
|
||||
headers['cache-control'] = `max-age=${options.cacheControl}`;
|
||||
headers['content-type'] = options.contentType;
|
||||
}
|
||||
const data = yield (0, fetch_1.put)(this.fetch, url.toString(), body, { headers });
|
||||
return {
|
||||
data: { path: cleanPath, fullPath: data.Key },
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isStorageError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Creates a signed upload URL.
|
||||
* Signed upload URLs can be used to upload files to the bucket without further authentication.
|
||||
* They are valid for 2 hours.
|
||||
* @param path The file path, including the current file name. For example `folder/image.png`.
|
||||
* @param options.upsert If set to true, allows the file to be overwritten if it already exists.
|
||||
*/
|
||||
createSignedUploadUrl(path, options) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
let _path = this._getFinalPath(path);
|
||||
const headers = Object.assign({}, this.headers);
|
||||
if (options === null || options === void 0 ? void 0 : options.upsert) {
|
||||
headers['x-upsert'] = 'true';
|
||||
}
|
||||
const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/upload/sign/${_path}`, {}, { headers });
|
||||
const url = new URL(this.url + data.url);
|
||||
const token = url.searchParams.get('token');
|
||||
if (!token) {
|
||||
throw new errors_1.StorageError('No token returned by API');
|
||||
}
|
||||
return { data: { signedUrl: url.toString(), path, token }, error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isStorageError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Replaces an existing file at the specified path with a new one.
|
||||
*
|
||||
* @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update.
|
||||
* @param fileBody The body of the file to be stored in the bucket.
|
||||
*/
|
||||
update(path, fileBody, fileOptions) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
return this.uploadOrUpdate('PUT', path, fileBody, fileOptions);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Moves an existing file to a new path in the same bucket.
|
||||
*
|
||||
* @param fromPath The original file path, including the current file name. For example `folder/image.png`.
|
||||
* @param toPath The new file path, including the new file name. For example `folder/image-new.png`.
|
||||
* @param options The destination options.
|
||||
*/
|
||||
move(fromPath, toPath, options) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/move`, {
|
||||
bucketId: this.bucketId,
|
||||
sourceKey: fromPath,
|
||||
destinationKey: toPath,
|
||||
destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket,
|
||||
}, { headers: this.headers });
|
||||
return { data, error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isStorageError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Copies an existing file to a new path in the same bucket.
|
||||
*
|
||||
* @param fromPath The original file path, including the current file name. For example `folder/image.png`.
|
||||
* @param toPath The new file path, including the new file name. For example `folder/image-copy.png`.
|
||||
* @param options The destination options.
|
||||
*/
|
||||
copy(fromPath, toPath, options) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/copy`, {
|
||||
bucketId: this.bucketId,
|
||||
sourceKey: fromPath,
|
||||
destinationKey: toPath,
|
||||
destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket,
|
||||
}, { headers: this.headers });
|
||||
return { data: { path: data.Key }, error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isStorageError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Creates a signed URL. Use a signed URL to share a file for a fixed amount of time.
|
||||
*
|
||||
* @param path The file path, including the current file name. For example `folder/image.png`.
|
||||
* @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute.
|
||||
* @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.
|
||||
* @param options.transform Transform the asset before serving it to the client.
|
||||
*/
|
||||
createSignedUrl(path, expiresIn, options) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
let _path = this._getFinalPath(path);
|
||||
let data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/sign/${_path}`, Object.assign({ expiresIn }, ((options === null || options === void 0 ? void 0 : options.transform) ? { transform: options.transform } : {})), { headers: this.headers });
|
||||
const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download)
|
||||
? `&download=${options.download === true ? '' : options.download}`
|
||||
: '';
|
||||
const signedUrl = encodeURI(`${this.url}${data.signedURL}${downloadQueryParam}`);
|
||||
data = { signedUrl };
|
||||
return { data, error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isStorageError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time.
|
||||
*
|
||||
* @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`.
|
||||
* @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute.
|
||||
* @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.
|
||||
*/
|
||||
createSignedUrls(paths, expiresIn, options) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/sign/${this.bucketId}`, { expiresIn, paths }, { headers: this.headers });
|
||||
const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download)
|
||||
? `&download=${options.download === true ? '' : options.download}`
|
||||
: '';
|
||||
return {
|
||||
data: data.map((datum) => (Object.assign(Object.assign({}, datum), { signedUrl: datum.signedURL
|
||||
? encodeURI(`${this.url}${datum.signedURL}${downloadQueryParam}`)
|
||||
: null }))),
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isStorageError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead.
|
||||
*
|
||||
* @param path The full path and file name of the file to be downloaded. For example `folder/image.png`.
|
||||
* @param options.transform Transform the asset before serving it to the client.
|
||||
*/
|
||||
download(path, options) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined';
|
||||
const renderPath = wantsTransformation ? 'render/image/authenticated' : 'object';
|
||||
const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {});
|
||||
const queryString = transformationQuery ? `?${transformationQuery}` : '';
|
||||
try {
|
||||
const _path = this._getFinalPath(path);
|
||||
const res = yield (0, fetch_1.get)(this.fetch, `${this.url}/${renderPath}/${_path}${queryString}`, {
|
||||
headers: this.headers,
|
||||
noResolveJson: true,
|
||||
});
|
||||
const data = yield res.blob();
|
||||
return { data, error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isStorageError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Retrieves the details of an existing file.
|
||||
* @param path
|
||||
*/
|
||||
info(path) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const _path = this._getFinalPath(path);
|
||||
try {
|
||||
const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/object/info/${_path}`, {
|
||||
headers: this.headers,
|
||||
});
|
||||
return { data: (0, helpers_1.recursiveToCamel)(data), error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isStorageError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Checks the existence of a file.
|
||||
* @param path
|
||||
*/
|
||||
exists(path) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const _path = this._getFinalPath(path);
|
||||
try {
|
||||
yield (0, fetch_1.head)(this.fetch, `${this.url}/object/${_path}`, {
|
||||
headers: this.headers,
|
||||
});
|
||||
return { data: true, error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isStorageError)(error) && error instanceof errors_1.StorageUnknownError) {
|
||||
const originalError = error.originalError;
|
||||
if ([400, 404].includes(originalError === null || originalError === void 0 ? void 0 : originalError.status)) {
|
||||
return { data: false, error };
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset.
|
||||
* This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset.
|
||||
*
|
||||
* @param path The path and name of the file to generate the public URL for. For example `folder/image.png`.
|
||||
* @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.
|
||||
* @param options.transform Transform the asset before serving it to the client.
|
||||
*/
|
||||
getPublicUrl(path, options) {
|
||||
const _path = this._getFinalPath(path);
|
||||
const _queryString = [];
|
||||
const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download)
|
||||
? `download=${options.download === true ? '' : options.download}`
|
||||
: '';
|
||||
if (downloadQueryParam !== '') {
|
||||
_queryString.push(downloadQueryParam);
|
||||
}
|
||||
const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined';
|
||||
const renderPath = wantsTransformation ? 'render/image' : 'object';
|
||||
const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {});
|
||||
if (transformationQuery !== '') {
|
||||
_queryString.push(transformationQuery);
|
||||
}
|
||||
let queryString = _queryString.join('&');
|
||||
if (queryString !== '') {
|
||||
queryString = `?${queryString}`;
|
||||
}
|
||||
return {
|
||||
data: { publicUrl: encodeURI(`${this.url}/${renderPath}/public/${_path}${queryString}`) },
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Deletes files within the same bucket
|
||||
*
|
||||
* @param paths An array of files to delete, including the path and file name. For example [`'folder/image.png'`].
|
||||
*/
|
||||
remove(paths) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/object/${this.bucketId}`, { prefixes: paths }, { headers: this.headers });
|
||||
return { data, error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isStorageError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Get file metadata
|
||||
* @param id the file id to retrieve metadata
|
||||
*/
|
||||
// async getMetadata(
|
||||
// id: string
|
||||
// ): Promise<
|
||||
// | {
|
||||
// data: Metadata
|
||||
// error: null
|
||||
// }
|
||||
// | {
|
||||
// data: null
|
||||
// error: StorageError
|
||||
// }
|
||||
// > {
|
||||
// try {
|
||||
// const data = await get(this.fetch, `${this.url}/metadata/${id}`, { headers: this.headers })
|
||||
// return { data, error: null }
|
||||
// } catch (error) {
|
||||
// if (isStorageError(error)) {
|
||||
// return { data: null, error }
|
||||
// }
|
||||
// throw error
|
||||
// }
|
||||
// }
|
||||
/**
|
||||
* Update file metadata
|
||||
* @param id the file id to update metadata
|
||||
* @param meta the new file metadata
|
||||
*/
|
||||
// async updateMetadata(
|
||||
// id: string,
|
||||
// meta: Metadata
|
||||
// ): Promise<
|
||||
// | {
|
||||
// data: Metadata
|
||||
// error: null
|
||||
// }
|
||||
// | {
|
||||
// data: null
|
||||
// error: StorageError
|
||||
// }
|
||||
// > {
|
||||
// try {
|
||||
// const data = await post(
|
||||
// this.fetch,
|
||||
// `${this.url}/metadata/${id}`,
|
||||
// { ...meta },
|
||||
// { headers: this.headers }
|
||||
// )
|
||||
// return { data, error: null }
|
||||
// } catch (error) {
|
||||
// if (isStorageError(error)) {
|
||||
// return { data: null, error }
|
||||
// }
|
||||
// throw error
|
||||
// }
|
||||
// }
|
||||
/**
|
||||
* Lists all the files within a bucket.
|
||||
* @param path The folder path.
|
||||
* @param options Search options including limit (defaults to 100), offset, sortBy, and search
|
||||
*/
|
||||
list(path, options, parameters) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
const body = Object.assign(Object.assign(Object.assign({}, DEFAULT_SEARCH_OPTIONS), options), { prefix: path || '' });
|
||||
const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/list/${this.bucketId}`, body, { headers: this.headers }, parameters);
|
||||
return { data, error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isStorageError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* @experimental this method signature might change in the future
|
||||
* @param options search options
|
||||
* @param parameters
|
||||
*/
|
||||
listV2(options, parameters) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
const body = Object.assign({}, options);
|
||||
const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/list-v2/${this.bucketId}`, body, { headers: this.headers }, parameters);
|
||||
return { data, error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isStorageError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
encodeMetadata(metadata) {
|
||||
return JSON.stringify(metadata);
|
||||
}
|
||||
toBase64(data) {
|
||||
if (typeof Buffer !== 'undefined') {
|
||||
return Buffer.from(data).toString('base64');
|
||||
}
|
||||
return btoa(data);
|
||||
}
|
||||
_getFinalPath(path) {
|
||||
return `${this.bucketId}/${path.replace(/^\/+/, '')}`;
|
||||
}
|
||||
_removeEmptyFolders(path) {
|
||||
return path.replace(/^\/|\/$/g, '').replace(/\/+/g, '/');
|
||||
}
|
||||
transformOptsToQueryString(transform) {
|
||||
const params = [];
|
||||
if (transform.width) {
|
||||
params.push(`width=${transform.width}`);
|
||||
}
|
||||
if (transform.height) {
|
||||
params.push(`height=${transform.height}`);
|
||||
}
|
||||
if (transform.resize) {
|
||||
params.push(`resize=${transform.resize}`);
|
||||
}
|
||||
if (transform.format) {
|
||||
params.push(`format=${transform.format}`);
|
||||
}
|
||||
if (transform.quality) {
|
||||
params.push(`quality=${transform.quality}`);
|
||||
}
|
||||
return params.join('&');
|
||||
}
|
||||
}
|
||||
exports.default = StorageFileApi;
|
||||
//# sourceMappingURL=StorageFileApi.js.map
|
||||
+33
-41
@@ -1,70 +1,62 @@
|
||||
{
|
||||
"name": "@supabase/storage-js",
|
||||
"version": "2.11.0",
|
||||
"version": "2.93.3",
|
||||
"description": "Isomorphic storage client for Supabase.",
|
||||
"keywords": [
|
||||
"javascript",
|
||||
"typescript",
|
||||
"supabase"
|
||||
],
|
||||
"homepage": "https://github.com/supabase/storage-js",
|
||||
"bugs": "https://github.com/supabase/storage-js/issues",
|
||||
"homepage": "https://github.com/supabase/supabase-js/tree/master/packages/core/storage-js",
|
||||
"bugs": "https://github.com/supabase/supabase-js/issues",
|
||||
"license": "MIT",
|
||||
"author": "Supabase",
|
||||
"files": [
|
||||
"dist",
|
||||
"src"
|
||||
],
|
||||
"main": "dist/main/index.js",
|
||||
"module": "dist/module/index.js",
|
||||
"types": "dist/module/index.d.ts",
|
||||
"main": "dist/index.cjs",
|
||||
"module": "dist/index.mjs",
|
||||
"types": "dist/index.d.cts",
|
||||
"exports": {
|
||||
".": {
|
||||
"import": {
|
||||
"types": "./dist/index.d.mts",
|
||||
"default": "./dist/index.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/index.d.cts",
|
||||
"default": "./dist/index.cjs"
|
||||
}
|
||||
},
|
||||
"./dist/*": "./dist/*",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"repository": "supabase/storage-js",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/supabase/supabase-js.git",
|
||||
"directory": "packages/core/storage-js"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rimraf dist docs/v2",
|
||||
"format": "prettier --write \"{src,test}/**/*.ts\"",
|
||||
"build": "genversion src/lib/version.ts --es6 && run-s clean format build:*",
|
||||
"build:main": "tsc -p tsconfig.json",
|
||||
"build:module": "tsc -p tsconfig.module.json",
|
||||
"build:umd": "webpack",
|
||||
"types-generate": "dts-gen -m '@supabase/storage-js' -s",
|
||||
"test": "run-s test:clean test:infra test:suite test:clean",
|
||||
"test:suite": "jest --runInBand --coverage",
|
||||
"test:infra": "cd infra && docker compose down && docker compose up -d --build && sleep 10",
|
||||
"test:clean": "cd infra && docker compose down --remove-orphans",
|
||||
"build": "tsdown",
|
||||
"build:watch": "tsdown --watch",
|
||||
"docs": "typedoc --entryPoints src/index.ts --out docs/v2 --entryPoints src/packages/* --excludePrivate --excludeProtected",
|
||||
"docs:json": "typedoc --json docs/v2/spec.json --entryPoints src/index.ts --entryPoints src/packages/* --excludePrivate --excludeExternals --excludeProtected"
|
||||
},
|
||||
"dependencies": {
|
||||
"@supabase/node-fetch": "^2.6.14"
|
||||
"iceberg-js": "^0.8.1",
|
||||
"tslib": "2.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^26.0.13",
|
||||
"form-data": "^4.0.0",
|
||||
"genversion": "^3.0.1",
|
||||
"husky": "^4.3.0",
|
||||
"jest": "^29.0.0",
|
||||
"jest-environment-jsdom": "^29.5.0",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"prettier": "^2.1.2",
|
||||
"pretty-quick": "^3.1.0",
|
||||
"rimraf": "^3.0.2",
|
||||
"semantic-release-plugin-update-version-in-files": "^1.1.0",
|
||||
"ts-jest": "^29.0.0",
|
||||
"ts-loader": "^9.4.2",
|
||||
"typedoc": "^0.22.16",
|
||||
"typescript": "^4.6.3",
|
||||
"webpack": "^5.75.0",
|
||||
"webpack-cli": "^5.0.1"
|
||||
},
|
||||
"husky": {
|
||||
"hooks": {
|
||||
"pre-commit": "pretty-quick --staged"
|
||||
}
|
||||
"form-data": "^4.0.0"
|
||||
},
|
||||
"jsdelivr": "dist/umd/supabase.js",
|
||||
"unpkg": "dist/umd/supabase.js",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
}
|
||||
+406
@@ -0,0 +1,406 @@
|
||||
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.93.3";
|
||||
|
||||
//#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.
|
||||
* @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
|
||||
* ```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
|
||||
});
|
||||
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
|
||||
-229
@@ -1,229 +0,0 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const functions_js_1 = require("@supabase/functions-js");
|
||||
const postgrest_js_1 = require("@supabase/postgrest-js");
|
||||
const realtime_js_1 = require("@supabase/realtime-js");
|
||||
const storage_js_1 = require("@supabase/storage-js");
|
||||
const constants_1 = require("./lib/constants");
|
||||
const fetch_1 = require("./lib/fetch");
|
||||
const helpers_1 = require("./lib/helpers");
|
||||
const SupabaseAuthClient_1 = require("./lib/SupabaseAuthClient");
|
||||
/**
|
||||
* Supabase Client.
|
||||
*
|
||||
* An isomorphic Javascript client for interacting with Postgres.
|
||||
*/
|
||||
class SupabaseClient {
|
||||
/**
|
||||
* Create a new client for use in the browser.
|
||||
* @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.
|
||||
*/
|
||||
constructor(supabaseUrl, supabaseKey, options) {
|
||||
var _a, _b, _c;
|
||||
this.supabaseUrl = supabaseUrl;
|
||||
this.supabaseKey = supabaseKey;
|
||||
if (!supabaseUrl)
|
||||
throw new Error('supabaseUrl is required.');
|
||||
if (!supabaseKey)
|
||||
throw new Error('supabaseKey is required.');
|
||||
const _supabaseUrl = (0, helpers_1.ensureTrailingSlash)(supabaseUrl);
|
||||
const baseUrl = new URL(_supabaseUrl);
|
||||
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);
|
||||
// default storage key uses the supabase project ref as a namespace
|
||||
const defaultStorageKey = `sb-${baseUrl.hostname.split('.')[0]}-auth-token`;
|
||||
const DEFAULTS = {
|
||||
db: constants_1.DEFAULT_DB_OPTIONS,
|
||||
realtime: constants_1.DEFAULT_REALTIME_OPTIONS,
|
||||
auth: Object.assign(Object.assign({}, constants_1.DEFAULT_AUTH_OPTIONS), { storageKey: defaultStorageKey }),
|
||||
global: constants_1.DEFAULT_GLOBAL_OPTIONS,
|
||||
};
|
||||
const settings = (0, helpers_1.applySettingDefaults)(options !== null && options !== void 0 ? options : {}, DEFAULTS);
|
||||
this.storageKey = (_a = settings.auth.storageKey) !== null && _a !== void 0 ? _a : '';
|
||||
this.headers = (_b = settings.global.headers) !== null && _b !== void 0 ? _b : {};
|
||||
if (!settings.accessToken) {
|
||||
this.auth = this._initSupabaseAuthClient((_c = settings.auth) !== null && _c !== void 0 ? _c : {}, 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 = (0, fetch_1.fetchWithAuth)(supabaseKey, this._getAccessToken.bind(this), settings.global.fetch);
|
||||
this.realtime = this._initRealtimeClient(Object.assign({ headers: this.headers, accessToken: this._getAccessToken.bind(this) }, settings.realtime));
|
||||
this.rest = new postgrest_js_1.PostgrestClient(new URL('rest/v1', baseUrl).href, {
|
||||
headers: this.headers,
|
||||
schema: settings.db.schema,
|
||||
fetch: this.fetch,
|
||||
});
|
||||
this.storage = new storage_js_1.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 functions_js_1.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);
|
||||
}
|
||||
// NOTE: signatures must be kept in sync with PostgrestClient.schema
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
// NOTE: signatures must be kept in sync with PostgrestClient.rpc
|
||||
/**
|
||||
* 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 = {}) {
|
||||
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();
|
||||
}
|
||||
_getAccessToken() {
|
||||
var _a, _b;
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
if (this.accessToken) {
|
||||
return yield this.accessToken();
|
||||
}
|
||||
const { data } = yield this.auth.getSession();
|
||||
return (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : this.supabaseKey;
|
||||
});
|
||||
}
|
||||
_initSupabaseAuthClient({ autoRefreshToken, persistSession, detectSessionInUrl, storage, storageKey, flowType, lock, debug, }, headers, fetch) {
|
||||
const authHeaders = {
|
||||
Authorization: `Bearer ${this.supabaseKey}`,
|
||||
apikey: `${this.supabaseKey}`,
|
||||
};
|
||||
return new SupabaseAuthClient_1.SupabaseAuthClient({
|
||||
url: this.authUrl.href,
|
||||
headers: Object.assign(Object.assign({}, authHeaders), headers),
|
||||
storageKey: storageKey,
|
||||
autoRefreshToken,
|
||||
persistSession,
|
||||
detectSessionInUrl,
|
||||
storage,
|
||||
flowType,
|
||||
lock,
|
||||
debug,
|
||||
fetch,
|
||||
// auth checks if there is a custom authorizaiton header using this flag
|
||||
// so it knows whether to return an error when getUser is called with no session
|
||||
hasCustomAuthorizationHeader: 'Authorization' in this.headers,
|
||||
});
|
||||
}
|
||||
_initRealtimeClient(options) {
|
||||
return new realtime_js_1.RealtimeClient(this.realtimeUrl.href, Object.assign(Object.assign({}, options), { params: Object.assign({ apikey: this.supabaseKey }, options === null || options === void 0 ? void 0 : options.params) }));
|
||||
}
|
||||
_listenForAuthEvents() {
|
||||
let data = this.auth.onAuthStateChange((event, session) => {
|
||||
this._handleTokenChanged(event, 'CLIENT', session === null || session === void 0 ? void 0 : session.access_token);
|
||||
});
|
||||
return data;
|
||||
}
|
||||
_handleTokenChanged(event, source, token) {
|
||||
if ((event === 'TOKEN_REFRESHED' || event === 'SIGNED_IN') &&
|
||||
this.changedAccessToken !== token) {
|
||||
this.changedAccessToken = token;
|
||||
}
|
||||
else if (event === 'SIGNED_OUT') {
|
||||
this.realtime.setAuth();
|
||||
if (source == 'STORAGE')
|
||||
this.auth.signOut();
|
||||
this.changedAccessToken = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.default = SupabaseClient;
|
||||
//# sourceMappingURL=SupabaseClient.js.map
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createClient = exports.SupabaseClient = exports.FunctionRegion = exports.FunctionsError = exports.FunctionsRelayError = exports.FunctionsFetchError = exports.FunctionsHttpError = exports.PostgrestError = void 0;
|
||||
const SupabaseClient_1 = __importDefault(require("./SupabaseClient"));
|
||||
__exportStar(require("@supabase/auth-js"), exports);
|
||||
var postgrest_js_1 = require("@supabase/postgrest-js");
|
||||
Object.defineProperty(exports, "PostgrestError", { enumerable: true, get: function () { return postgrest_js_1.PostgrestError; } });
|
||||
var functions_js_1 = require("@supabase/functions-js");
|
||||
Object.defineProperty(exports, "FunctionsHttpError", { enumerable: true, get: function () { return functions_js_1.FunctionsHttpError; } });
|
||||
Object.defineProperty(exports, "FunctionsFetchError", { enumerable: true, get: function () { return functions_js_1.FunctionsFetchError; } });
|
||||
Object.defineProperty(exports, "FunctionsRelayError", { enumerable: true, get: function () { return functions_js_1.FunctionsRelayError; } });
|
||||
Object.defineProperty(exports, "FunctionsError", { enumerable: true, get: function () { return functions_js_1.FunctionsError; } });
|
||||
Object.defineProperty(exports, "FunctionRegion", { enumerable: true, get: function () { return functions_js_1.FunctionRegion; } });
|
||||
__exportStar(require("@supabase/realtime-js"), exports);
|
||||
var SupabaseClient_2 = require("./SupabaseClient");
|
||||
Object.defineProperty(exports, "SupabaseClient", { enumerable: true, get: function () { return __importDefault(SupabaseClient_2).default; } });
|
||||
/**
|
||||
* Creates a new Supabase Client.
|
||||
*/
|
||||
const createClient = (supabaseUrl, supabaseKey, options) => {
|
||||
return new SupabaseClient_1.default(supabaseUrl, supabaseKey, options);
|
||||
};
|
||||
exports.createClient = createClient;
|
||||
// Check for Node.js <= 18 deprecation
|
||||
function shouldShowDeprecationWarning() {
|
||||
// Skip in browser environments
|
||||
if (typeof window !== 'undefined') {
|
||||
return false;
|
||||
}
|
||||
// Skip if process is not available (e.g., Edge Runtime)
|
||||
if (typeof process === 'undefined') {
|
||||
return false;
|
||||
}
|
||||
// Use dynamic property access to avoid Next.js Edge Runtime static analysis warnings
|
||||
const processVersion = process['version'];
|
||||
if (processVersion === undefined || processVersion === null) {
|
||||
return false;
|
||||
}
|
||||
const versionMatch = processVersion.match(/^v(\d+)\./);
|
||||
if (!versionMatch) {
|
||||
return false;
|
||||
}
|
||||
const majorVersion = parseInt(versionMatch[1], 10);
|
||||
return majorVersion <= 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`);
|
||||
}
|
||||
//# sourceMappingURL=index.js.map
|
||||
Generated
Vendored
-11
@@ -1,11 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SupabaseAuthClient = void 0;
|
||||
const auth_js_1 = require("@supabase/auth-js");
|
||||
class SupabaseAuthClient extends auth_js_1.AuthClient {
|
||||
constructor(options) {
|
||||
super(options);
|
||||
}
|
||||
}
|
||||
exports.SupabaseAuthClient = SupabaseAuthClient;
|
||||
//# sourceMappingURL=SupabaseAuthClient.js.map
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DEFAULT_REALTIME_OPTIONS = exports.DEFAULT_AUTH_OPTIONS = exports.DEFAULT_DB_OPTIONS = exports.DEFAULT_GLOBAL_OPTIONS = exports.DEFAULT_HEADERS = void 0;
|
||||
const version_1 = require("./version");
|
||||
let JS_ENV = '';
|
||||
// @ts-ignore
|
||||
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';
|
||||
}
|
||||
exports.DEFAULT_HEADERS = { 'X-Client-Info': `supabase-js-${JS_ENV}/${version_1.version}` };
|
||||
exports.DEFAULT_GLOBAL_OPTIONS = {
|
||||
headers: exports.DEFAULT_HEADERS,
|
||||
};
|
||||
exports.DEFAULT_DB_OPTIONS = {
|
||||
schema: 'public',
|
||||
};
|
||||
exports.DEFAULT_AUTH_OPTIONS = {
|
||||
autoRefreshToken: true,
|
||||
persistSession: true,
|
||||
detectSessionInUrl: true,
|
||||
flowType: 'implicit',
|
||||
};
|
||||
exports.DEFAULT_REALTIME_OPTIONS = {};
|
||||
//# sourceMappingURL=constants.js.map
|
||||
-76
@@ -1,76 +0,0 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.fetchWithAuth = exports.resolveHeadersConstructor = exports.resolveFetch = void 0;
|
||||
// @ts-ignore
|
||||
const node_fetch_1 = __importStar(require("@supabase/node-fetch"));
|
||||
const resolveFetch = (customFetch) => {
|
||||
let _fetch;
|
||||
if (customFetch) {
|
||||
_fetch = customFetch;
|
||||
}
|
||||
else if (typeof fetch === 'undefined') {
|
||||
_fetch = node_fetch_1.default;
|
||||
}
|
||||
else {
|
||||
_fetch = fetch;
|
||||
}
|
||||
return (...args) => _fetch(...args);
|
||||
};
|
||||
exports.resolveFetch = resolveFetch;
|
||||
const resolveHeadersConstructor = () => {
|
||||
if (typeof Headers === 'undefined') {
|
||||
return node_fetch_1.Headers;
|
||||
}
|
||||
return Headers;
|
||||
};
|
||||
exports.resolveHeadersConstructor = resolveHeadersConstructor;
|
||||
const fetchWithAuth = (supabaseKey, getAccessToken, customFetch) => {
|
||||
const fetch = (0, exports.resolveFetch)(customFetch);
|
||||
const HeadersConstructor = (0, exports.resolveHeadersConstructor)();
|
||||
return (input, init) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
var _a;
|
||||
const accessToken = (_a = (yield getAccessToken())) !== null && _a !== void 0 ? _a : 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(input, Object.assign(Object.assign({}, init), { headers }));
|
||||
});
|
||||
};
|
||||
exports.fetchWithAuth = fetchWithAuth;
|
||||
//# sourceMappingURL=fetch.js.map
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.applySettingDefaults = exports.isBrowser = exports.ensureTrailingSlash = exports.uuid = void 0;
|
||||
function uuid() {
|
||||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
|
||||
var r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8;
|
||||
return v.toString(16);
|
||||
});
|
||||
}
|
||||
exports.uuid = uuid;
|
||||
function ensureTrailingSlash(url) {
|
||||
return url.endsWith('/') ? url : url + '/';
|
||||
}
|
||||
exports.ensureTrailingSlash = ensureTrailingSlash;
|
||||
const isBrowser = () => typeof window !== 'undefined';
|
||||
exports.isBrowser = isBrowser;
|
||||
function applySettingDefaults(options, defaults) {
|
||||
var _a, _b;
|
||||
const { db: dbOptions, auth: authOptions, realtime: realtimeOptions, global: globalOptions, } = options;
|
||||
const { db: DEFAULT_DB_OPTIONS, auth: DEFAULT_AUTH_OPTIONS, realtime: DEFAULT_REALTIME_OPTIONS, global: DEFAULT_GLOBAL_OPTIONS, } = defaults;
|
||||
const result = {
|
||||
db: Object.assign(Object.assign({}, DEFAULT_DB_OPTIONS), dbOptions),
|
||||
auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS), authOptions),
|
||||
realtime: Object.assign(Object.assign({}, DEFAULT_REALTIME_OPTIONS), realtimeOptions),
|
||||
storage: {},
|
||||
global: Object.assign(Object.assign(Object.assign({}, DEFAULT_GLOBAL_OPTIONS), globalOptions), { headers: Object.assign(Object.assign({}, ((_a = DEFAULT_GLOBAL_OPTIONS === null || DEFAULT_GLOBAL_OPTIONS === void 0 ? void 0 : DEFAULT_GLOBAL_OPTIONS.headers) !== null && _a !== void 0 ? _a : {})), ((_b = globalOptions === null || globalOptions === void 0 ? void 0 : globalOptions.headers) !== null && _b !== void 0 ? _b : {})) }),
|
||||
accessToken: () => __awaiter(this, void 0, void 0, function* () { return ''; }),
|
||||
};
|
||||
if (options.accessToken) {
|
||||
result.accessToken = options.accessToken;
|
||||
}
|
||||
else {
|
||||
// hack around Required<>
|
||||
delete result.accessToken;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
exports.applySettingDefaults = applySettingDefaults;
|
||||
//# sourceMappingURL=helpers.js.map
|
||||
-5
@@ -1,5 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.version = void 0;
|
||||
exports.version = '2.56.0';
|
||||
//# sourceMappingURL=version.js.map
|
||||
+80
-57
@@ -1,13 +1,13 @@
|
||||
{
|
||||
"name": "@supabase/supabase-js",
|
||||
"version": "2.56.0",
|
||||
"description": "Isomorphic Javascript client for Supabase",
|
||||
"version": "2.93.3",
|
||||
"description": "Isomorphic Javascript SDK for Supabase",
|
||||
"keywords": [
|
||||
"javascript",
|
||||
"typescript",
|
||||
"supabase"
|
||||
],
|
||||
"homepage": "https://github.com/supabase/supabase-js",
|
||||
"homepage": "https://github.com/supabase/supabase-js/tree/master/packages/core/supabase-js",
|
||||
"bugs": "https://github.com/supabase/supabase-js/issues",
|
||||
"license": "MIT",
|
||||
"author": "Supabase",
|
||||
@@ -15,76 +15,99 @@
|
||||
"dist",
|
||||
"src"
|
||||
],
|
||||
"main": "dist/main/index.js",
|
||||
"module": "dist/module/index.js",
|
||||
"types": "dist/module/index.d.ts",
|
||||
"main": "dist/index.cjs",
|
||||
"module": "dist/index.mjs",
|
||||
"types": "dist/index.d.cts",
|
||||
"exports": {
|
||||
".": {
|
||||
"import": {
|
||||
"types": "./dist/index.d.mts",
|
||||
"default": "./dist/index.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/index.d.cts",
|
||||
"default": "./dist/index.cjs"
|
||||
}
|
||||
},
|
||||
"./dist/*": "./dist/*",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"repository": "supabase/supabase-js",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/supabase/supabase-js.git",
|
||||
"directory": "packages/core/supabase-js"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rimraf dist docs/v2",
|
||||
"format": "prettier --write \"{src,test}/**/*.ts\"",
|
||||
"build": "run-s clean format build:*",
|
||||
"build:main": "tsc -p tsconfig.json",
|
||||
"build:module": "tsc -p tsconfig.module.json",
|
||||
"build:umd": "webpack --env mode=production",
|
||||
"types-generate": "dts-gen -m '@supabase/supabase-js' -s",
|
||||
"test": "run-s test:types test:run",
|
||||
"test:all": "run-s test:types test:run test:integration test:integration:browser",
|
||||
"build": "tsdown",
|
||||
"build:watch": "tsdown --watch",
|
||||
"test": "npm run test:types && npm run test:run",
|
||||
"test:all": "npm run test:types && npm run test:run && npm run test:integration && npm run test:integration:browser",
|
||||
"test:run": "jest --runInBand --detectOpenHandles",
|
||||
"test:unit": "jest --runInBand --detectOpenHandles test/unit",
|
||||
"test:coverage": "jest --runInBand --coverage --testPathIgnorePatterns=\"test/integration|test/deno\"",
|
||||
"test:integration": "jest --runInBand --detectOpenHandles test/integration.test.ts",
|
||||
"test:integration:browser": "deno test --allow-all test/integration.browser.test.ts",
|
||||
"test:edge-functions": "deno test --allow-all --no-check test/deno/edge-functions-integration.test.ts",
|
||||
"test:edge-functions": "cd test/deno && npm run test:edge-functions",
|
||||
"test:deno": "cd test/deno && npm run test",
|
||||
"test:watch": "jest --watch --verbose false --silent false",
|
||||
"test:node:playwright": "cd test/integration/node-browser && npm install && cp ../../../dist/umd/supabase.js . && npm run test",
|
||||
"test:bun": "cd test/integration/bun && bun install && bun test",
|
||||
"test:types": "run-s build:module && tsd --files test/types/*.test-d.ts && jsr publish --dry-run",
|
||||
"docs": "typedoc --entryPoints src/index.ts --out docs/v2 --includes src/**/*.ts",
|
||||
"docs:json": "typedoc --entryPoints src/index.ts --includes src/**/*.ts --json docs/v2/spec.json --excludeExternals",
|
||||
"serve:coverage": "npm run test:coverage && serve test/coverage",
|
||||
"update:test-deps": "npm run build && npm pack && cp supabase-supabase-js-*.tgz test/integration/expo/supabase-supabase-js-0.0.0-automated.tgz && cp supabase-supabase-js-*.tgz test/integration/next/supabase-supabase-js-0.0.0-automated.tgz && cp supabase-supabase-js-*.tgz test/deno/supabase-supabase-js-0.0.0-automated.tgz && cp supabase-supabase-js-*.tgz test/integration/bun/supabase-supabase-js-0.0.0-automated.tgz && cd test/integration/expo && npm install && cd ../next && npm install --legacy-peer-deps && cd ../../deno && npm install && cd ../integration/bun && bun install",
|
||||
"update:test-deps:expo": "npm run build && npm pack && cp supabase-supabase-js-*.tgz test/integration/expo/supabase-supabase-js-0.0.0-automated.tgz && cd test/integration/expo && npm install",
|
||||
"update:test-deps:next": "npm run build && npm pack && cp supabase-supabase-js-*.tgz test/integration/next/supabase-supabase-js-0.0.0-automated.tgz && cd test/integration/next && npm install --legacy-peer-deps",
|
||||
"update:test-deps:deno": "npm run build && npm pack && cp supabase-supabase-js-*.tgz test/deno/supabase-supabase-js-0.0.0-automated.tgz && cd test/deno && npm install",
|
||||
"update:test-deps:bun": "npm run build && npm pack && cp supabase-supabase-js-*.tgz test/integration/bun/supabase-supabase-js-0.0.0-automated.tgz && cd test/integration/bun && bun install"
|
||||
"test:expo": "cd test/integration/expo && npm test",
|
||||
"test:next": "cd test/integration/next && npm test",
|
||||
"test:types": "tsd --files test/types/*.test-d.ts && jsr publish --dry-run --allow-dirty",
|
||||
"test:exports": "attw --pack .",
|
||||
"test:esm": "node test/module-resolution.test.mjs",
|
||||
"test:cjs": "node test/module-resolution.test.cjs",
|
||||
"test:module-resolution": "npm run test:exports && npm run test:esm && npm run test:cjs",
|
||||
"docs": "typedoc --entryPoints src/index.ts --out docs/v2",
|
||||
"docs:json": "typedoc --entryPoints src/index.ts --json docs/v2/spec.json --excludeExternals",
|
||||
"serve:coverage": "npx nx test:coverage supabase-js && npx --yes serve test/coverage",
|
||||
"update:test-deps": "npm run update:test-deps:expo && npm run update:test-deps:next && npm run update:test-deps:deno && npm run update:test-deps:bun",
|
||||
"update:test-deps:expo": "cd test/integration/expo && npm install",
|
||||
"update:test-deps:next": "cd test/integration/next && npm install",
|
||||
"update:test-deps:deno": "cd test/deno && npm install",
|
||||
"update:test-deps:bun": "cd test/integration/bun && bun install"
|
||||
},
|
||||
"dependencies": {
|
||||
"@supabase/auth-js": "2.71.1",
|
||||
"@supabase/functions-js": "2.4.5",
|
||||
"@supabase/node-fetch": "2.6.15",
|
||||
"@supabase/postgrest-js": "1.21.3",
|
||||
"@supabase/realtime-js": "2.15.1",
|
||||
"@supabase/storage-js": "^2.10.4"
|
||||
"@supabase/auth-js": "2.93.3",
|
||||
"@supabase/functions-js": "2.93.3",
|
||||
"@supabase/postgrest-js": "2.93.3",
|
||||
"@supabase/realtime-js": "2.93.3",
|
||||
"@supabase/storage-js": "2.93.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sebbo2002/semantic-release-jsr": "^1.0.0",
|
||||
"@solana/wallet-standard-features": "^1.3.0",
|
||||
"@types/jest": "^29.2.5",
|
||||
"husky": "^4.3.8",
|
||||
"jest": "^29.3.1",
|
||||
"jsr": "^0.13.5",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"prettier": "^2.5.1",
|
||||
"pretty-quick": "^3.1.3",
|
||||
"puppeteer": "^24.9.0",
|
||||
"rimraf": "^3.0.2",
|
||||
"semantic-release-plugin-update-version-in-files": "^1.1.0",
|
||||
"serve": "^14.2.1",
|
||||
"ts-jest": "^29.0.5",
|
||||
"ts-loader": "^8.0.11",
|
||||
"ts-node": "^10.9.1",
|
||||
"tsd": "^0.30.4",
|
||||
"typedoc": "^0.22.16",
|
||||
"typescript": "^4.5.5",
|
||||
"webpack": "^5.69.1",
|
||||
"webpack-cli": "^4.9.2"
|
||||
},
|
||||
"husky": {
|
||||
"hooks": {
|
||||
"pre-commit": "pretty-quick --staged"
|
||||
}
|
||||
"tsd": "^0.33.0"
|
||||
},
|
||||
"jsdelivr": "dist/umd/supabase.js",
|
||||
"unpkg": "dist/umd/supabase.js"
|
||||
"unpkg": "dist/umd/supabase.js",
|
||||
"nx": {
|
||||
"targets": {
|
||||
"test:integration:browser": {
|
||||
"dependsOn": [
|
||||
{
|
||||
"projects": [
|
||||
"storage-js"
|
||||
],
|
||||
"target": "build"
|
||||
}
|
||||
]
|
||||
},
|
||||
"test:edge-functions": {
|
||||
"dependsOn": [
|
||||
{
|
||||
"projects": [
|
||||
"storage-js"
|
||||
],
|
||||
"target": "build"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user