vue-3-supabase
Version:
Simple Vue 3 wrap for Supabase.js Client (v2) build with Vitejs
5,198 lines • 179 kB
JavaScript
import { inject } from "vue";
function _mergeNamespaces(n, m) {
m.forEach(function(e) {
e && typeof e !== "string" && !Array.isArray(e) && Object.keys(e).forEach(function(k) {
if (k !== "default" && !(k in n)) {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function() {
return e[k];
}
});
}
});
});
return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { value: "Module" }));
}
var __awaiter$d = globalThis && globalThis.__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());
});
};
const resolveFetch$3 = (customFetch) => {
let _fetch;
if (customFetch) {
_fetch = customFetch;
} else if (typeof fetch === "undefined") {
_fetch = (...args) => __awaiter$d(void 0, void 0, void 0, function* () {
return yield (yield Promise.resolve().then(function() {
return browserPonyfill;
})).fetch(...args);
});
} else {
_fetch = fetch;
}
return (...args) => _fetch(...args);
};
class FunctionsError extends Error {
constructor(message, name2 = "FunctionsError", context) {
super(message);
super.name = name2;
this.context = context;
}
}
class FunctionsFetchError extends FunctionsError {
constructor(context) {
super("Failed to send a request to the Edge Function", "FunctionsFetchError", context);
}
}
class FunctionsRelayError extends FunctionsError {
constructor(context) {
super("Relay Error invoking the Edge Function", "FunctionsRelayError", context);
}
}
class FunctionsHttpError extends FunctionsError {
constructor(context) {
super("Edge Function returned a non-2xx status code", "FunctionsHttpError", context);
}
}
var __awaiter$c = globalThis && globalThis.__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());
});
};
class FunctionsClient {
constructor(url, { headers = {}, customFetch } = {}) {
this.url = url;
this.headers = headers;
this.fetch = resolveFetch$3(customFetch);
}
setAuth(token) {
this.headers.Authorization = `Bearer ${token}`;
}
invoke(functionName, options = {}) {
var _a;
return __awaiter$c(this, void 0, void 0, function* () {
try {
const { headers, method, body: functionArgs } = options;
let _headers = {};
let body;
if (functionArgs && (headers && !Object.prototype.hasOwnProperty.call(headers, "Content-Type") || !headers)) {
if (typeof Blob !== "undefined" && functionArgs instanceof Blob || functionArgs instanceof ArrayBuffer) {
_headers["Content-Type"] = "application/octet-stream";
body = functionArgs;
} else if (typeof functionArgs === "string") {
_headers["Content-Type"] = "text/plain";
body = functionArgs;
} else if (typeof FormData !== "undefined" && functionArgs instanceof FormData) {
body = functionArgs;
} else {
_headers["Content-Type"] = "application/json";
body = JSON.stringify(functionArgs);
}
}
const response = yield this.fetch(`${this.url}/${functionName}`, {
method: method || "POST",
headers: Object.assign(Object.assign(Object.assign({}, _headers), this.headers), headers),
body
}).catch((fetchError) => {
throw new FunctionsFetchError(fetchError);
});
const isRelayError = response.headers.get("x-relay-error");
if (isRelayError && isRelayError === "true") {
throw new FunctionsRelayError(response);
}
if (!response.ok) {
throw new FunctionsHttpError(response);
}
let responseType = ((_a = response.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "text/plain").split(";")[0].trim();
let data;
if (responseType === "application/json") {
data = yield response.json();
} else if (responseType === "application/octet-stream") {
data = yield response.blob();
} else if (responseType === "multipart/form-data") {
data = yield response.formData();
} else {
data = yield response.text();
}
return { data, error: null };
} catch (error) {
return { data: null, error };
}
});
}
}
var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
function getDefaultExportFromCjs(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
var browserPonyfill$1 = { exports: {} };
(function(module, exports) {
var global2 = typeof self !== "undefined" ? self : commonjsGlobal;
var __self__ = function() {
function F() {
this.fetch = false;
this.DOMException = global2.DOMException;
}
F.prototype = global2;
return new F();
}();
(function(self2) {
(function(exports2) {
var support = {
searchParams: "URLSearchParams" in self2,
iterable: "Symbol" in self2 && "iterator" in Symbol,
blob: "FileReader" in self2 && "Blob" in self2 && function() {
try {
new Blob();
return true;
} catch (e) {
return false;
}
}(),
formData: "FormData" in self2,
arrayBuffer: "ArrayBuffer" in self2
};
function isDataView(obj) {
return obj && DataView.prototype.isPrototypeOf(obj);
}
if (support.arrayBuffer) {
var viewClasses = [
"[object Int8Array]",
"[object Uint8Array]",
"[object Uint8ClampedArray]",
"[object Int16Array]",
"[object Uint16Array]",
"[object Int32Array]",
"[object Uint32Array]",
"[object Float32Array]",
"[object Float64Array]"
];
var isArrayBufferView = ArrayBuffer.isView || function(obj) {
return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1;
};
}
function normalizeName(name2) {
if (typeof name2 !== "string") {
name2 = String(name2);
}
if (/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(name2)) {
throw new TypeError("Invalid character in header field name");
}
return name2.toLowerCase();
}
function normalizeValue(value) {
if (typeof value !== "string") {
value = String(value);
}
return value;
}
function iteratorFor(items) {
var iterator = {
next: function() {
var value = items.shift();
return { done: value === void 0, value };
}
};
if (support.iterable) {
iterator[Symbol.iterator] = function() {
return iterator;
};
}
return iterator;
}
function Headers2(headers) {
this.map = {};
if (headers instanceof Headers2) {
headers.forEach(function(value, name2) {
this.append(name2, value);
}, this);
} else if (Array.isArray(headers)) {
headers.forEach(function(header) {
this.append(header[0], header[1]);
}, this);
} else if (headers) {
Object.getOwnPropertyNames(headers).forEach(function(name2) {
this.append(name2, headers[name2]);
}, this);
}
}
Headers2.prototype.append = function(name2, value) {
name2 = normalizeName(name2);
value = normalizeValue(value);
var oldValue = this.map[name2];
this.map[name2] = oldValue ? oldValue + ", " + value : value;
};
Headers2.prototype["delete"] = function(name2) {
delete this.map[normalizeName(name2)];
};
Headers2.prototype.get = function(name2) {
name2 = normalizeName(name2);
return this.has(name2) ? this.map[name2] : null;
};
Headers2.prototype.has = function(name2) {
return this.map.hasOwnProperty(normalizeName(name2));
};
Headers2.prototype.set = function(name2, value) {
this.map[normalizeName(name2)] = normalizeValue(value);
};
Headers2.prototype.forEach = function(callback, thisArg) {
for (var name2 in this.map) {
if (this.map.hasOwnProperty(name2)) {
callback.call(thisArg, this.map[name2], name2, this);
}
}
};
Headers2.prototype.keys = function() {
var items = [];
this.forEach(function(value, name2) {
items.push(name2);
});
return iteratorFor(items);
};
Headers2.prototype.values = function() {
var items = [];
this.forEach(function(value) {
items.push(value);
});
return iteratorFor(items);
};
Headers2.prototype.entries = function() {
var items = [];
this.forEach(function(value, name2) {
items.push([name2, value]);
});
return iteratorFor(items);
};
if (support.iterable) {
Headers2.prototype[Symbol.iterator] = Headers2.prototype.entries;
}
function consumed(body) {
if (body.bodyUsed) {
return Promise.reject(new TypeError("Already read"));
}
body.bodyUsed = true;
}
function fileReaderReady(reader) {
return new Promise(function(resolve, reject) {
reader.onload = function() {
resolve(reader.result);
};
reader.onerror = function() {
reject(reader.error);
};
});
}
function readBlobAsArrayBuffer(blob) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
reader.readAsArrayBuffer(blob);
return promise;
}
function readBlobAsText(blob) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
reader.readAsText(blob);
return promise;
}
function readArrayBufferAsText(buf) {
var view = new Uint8Array(buf);
var chars = new Array(view.length);
for (var i = 0; i < view.length; i++) {
chars[i] = String.fromCharCode(view[i]);
}
return chars.join("");
}
function bufferClone(buf) {
if (buf.slice) {
return buf.slice(0);
} else {
var view = new Uint8Array(buf.byteLength);
view.set(new Uint8Array(buf));
return view.buffer;
}
}
function Body() {
this.bodyUsed = false;
this._initBody = function(body) {
this._bodyInit = body;
if (!body) {
this._bodyText = "";
} else if (typeof body === "string") {
this._bodyText = body;
} else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
this._bodyBlob = body;
} else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
this._bodyFormData = body;
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this._bodyText = body.toString();
} else if (support.arrayBuffer && support.blob && isDataView(body)) {
this._bodyArrayBuffer = bufferClone(body.buffer);
this._bodyInit = new Blob([this._bodyArrayBuffer]);
} else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
this._bodyArrayBuffer = bufferClone(body);
} else {
this._bodyText = body = Object.prototype.toString.call(body);
}
if (!this.headers.get("content-type")) {
if (typeof body === "string") {
this.headers.set("content-type", "text/plain;charset=UTF-8");
} else if (this._bodyBlob && this._bodyBlob.type) {
this.headers.set("content-type", this._bodyBlob.type);
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this.headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
}
}
};
if (support.blob) {
this.blob = function() {
var rejected = consumed(this);
if (rejected) {
return rejected;
}
if (this._bodyBlob) {
return Promise.resolve(this._bodyBlob);
} else if (this._bodyArrayBuffer) {
return Promise.resolve(new Blob([this._bodyArrayBuffer]));
} else if (this._bodyFormData) {
throw new Error("could not read FormData body as blob");
} else {
return Promise.resolve(new Blob([this._bodyText]));
}
};
this.arrayBuffer = function() {
if (this._bodyArrayBuffer) {
return consumed(this) || Promise.resolve(this._bodyArrayBuffer);
} else {
return this.blob().then(readBlobAsArrayBuffer);
}
};
}
this.text = function() {
var rejected = consumed(this);
if (rejected) {
return rejected;
}
if (this._bodyBlob) {
return readBlobAsText(this._bodyBlob);
} else if (this._bodyArrayBuffer) {
return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer));
} else if (this._bodyFormData) {
throw new Error("could not read FormData body as text");
} else {
return Promise.resolve(this._bodyText);
}
};
if (support.formData) {
this.formData = function() {
return this.text().then(decode);
};
}
this.json = function() {
return this.text().then(JSON.parse);
};
return this;
}
var methods = ["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"];
function normalizeMethod(method) {
var upcased = method.toUpperCase();
return methods.indexOf(upcased) > -1 ? upcased : method;
}
function Request(input, options) {
options = options || {};
var body = options.body;
if (input instanceof Request) {
if (input.bodyUsed) {
throw new TypeError("Already read");
}
this.url = input.url;
this.credentials = input.credentials;
if (!options.headers) {
this.headers = new Headers2(input.headers);
}
this.method = input.method;
this.mode = input.mode;
this.signal = input.signal;
if (!body && input._bodyInit != null) {
body = input._bodyInit;
input.bodyUsed = true;
}
} else {
this.url = String(input);
}
this.credentials = options.credentials || this.credentials || "same-origin";
if (options.headers || !this.headers) {
this.headers = new Headers2(options.headers);
}
this.method = normalizeMethod(options.method || this.method || "GET");
this.mode = options.mode || this.mode || null;
this.signal = options.signal || this.signal;
this.referrer = null;
if ((this.method === "GET" || this.method === "HEAD") && body) {
throw new TypeError("Body not allowed for GET or HEAD requests");
}
this._initBody(body);
}
Request.prototype.clone = function() {
return new Request(this, { body: this._bodyInit });
};
function decode(body) {
var form = new FormData();
body.trim().split("&").forEach(function(bytes) {
if (bytes) {
var split = bytes.split("=");
var name2 = split.shift().replace(/\+/g, " ");
var value = split.join("=").replace(/\+/g, " ");
form.append(decodeURIComponent(name2), decodeURIComponent(value));
}
});
return form;
}
function parseHeaders(rawHeaders) {
var headers = new Headers2();
var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, " ");
preProcessedHeaders.split(/\r?\n/).forEach(function(line) {
var parts = line.split(":");
var key = parts.shift().trim();
if (key) {
var value = parts.join(":").trim();
headers.append(key, value);
}
});
return headers;
}
Body.call(Request.prototype);
function Response2(bodyInit, options) {
if (!options) {
options = {};
}
this.type = "default";
this.status = options.status === void 0 ? 200 : options.status;
this.ok = this.status >= 200 && this.status < 300;
this.statusText = "statusText" in options ? options.statusText : "OK";
this.headers = new Headers2(options.headers);
this.url = options.url || "";
this._initBody(bodyInit);
}
Body.call(Response2.prototype);
Response2.prototype.clone = function() {
return new Response2(this._bodyInit, {
status: this.status,
statusText: this.statusText,
headers: new Headers2(this.headers),
url: this.url
});
};
Response2.error = function() {
var response = new Response2(null, { status: 0, statusText: "" });
response.type = "error";
return response;
};
var redirectStatuses = [301, 302, 303, 307, 308];
Response2.redirect = function(url, status) {
if (redirectStatuses.indexOf(status) === -1) {
throw new RangeError("Invalid status code");
}
return new Response2(null, { status, headers: { location: url } });
};
exports2.DOMException = self2.DOMException;
try {
new exports2.DOMException();
} catch (err) {
exports2.DOMException = function(message, name2) {
this.message = message;
this.name = name2;
var error = Error(message);
this.stack = error.stack;
};
exports2.DOMException.prototype = Object.create(Error.prototype);
exports2.DOMException.prototype.constructor = exports2.DOMException;
}
function fetch2(input, init) {
return new Promise(function(resolve, reject) {
var request = new Request(input, init);
if (request.signal && request.signal.aborted) {
return reject(new exports2.DOMException("Aborted", "AbortError"));
}
var xhr = new XMLHttpRequest();
function abortXhr() {
xhr.abort();
}
xhr.onload = function() {
var options = {
status: xhr.status,
statusText: xhr.statusText,
headers: parseHeaders(xhr.getAllResponseHeaders() || "")
};
options.url = "responseURL" in xhr ? xhr.responseURL : options.headers.get("X-Request-URL");
var body = "response" in xhr ? xhr.response : xhr.responseText;
resolve(new Response2(body, options));
};
xhr.onerror = function() {
reject(new TypeError("Network request failed"));
};
xhr.ontimeout = function() {
reject(new TypeError("Network request failed"));
};
xhr.onabort = function() {
reject(new exports2.DOMException("Aborted", "AbortError"));
};
xhr.open(request.method, request.url, true);
if (request.credentials === "include") {
xhr.withCredentials = true;
} else if (request.credentials === "omit") {
xhr.withCredentials = false;
}
if ("responseType" in xhr && support.blob) {
xhr.responseType = "blob";
}
request.headers.forEach(function(value, name2) {
xhr.setRequestHeader(name2, value);
});
if (request.signal) {
request.signal.addEventListener("abort", abortXhr);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
request.signal.removeEventListener("abort", abortXhr);
}
};
}
xhr.send(typeof request._bodyInit === "undefined" ? null : request._bodyInit);
});
}
fetch2.polyfill = true;
if (!self2.fetch) {
self2.fetch = fetch2;
self2.Headers = Headers2;
self2.Request = Request;
self2.Response = Response2;
}
exports2.Headers = Headers2;
exports2.Request = Request;
exports2.Response = Response2;
exports2.fetch = fetch2;
Object.defineProperty(exports2, "__esModule", { value: true });
return exports2;
})({});
})(__self__);
__self__.fetch.ponyfill = true;
delete __self__.fetch.polyfill;
var ctx = __self__;
exports = ctx.fetch;
exports.default = ctx.fetch;
exports.fetch = ctx.fetch;
exports.Headers = ctx.Headers;
exports.Request = ctx.Request;
exports.Response = ctx.Response;
module.exports = exports;
})(browserPonyfill$1, browserPonyfill$1.exports);
var crossFetch = /* @__PURE__ */ getDefaultExportFromCjs(browserPonyfill$1.exports);
var browserPonyfill = /* @__PURE__ */ _mergeNamespaces({
__proto__: null,
"default": crossFetch
}, [browserPonyfill$1.exports]);
class PostgrestBuilder {
constructor(builder) {
this.shouldThrowOnError = false;
this.method = builder.method;
this.url = builder.url;
this.headers = builder.headers;
this.schema = builder.schema;
this.body = builder.body;
this.shouldThrowOnError = builder.shouldThrowOnError;
this.signal = builder.signal;
this.allowEmpty = builder.allowEmpty;
if (builder.fetch) {
this.fetch = builder.fetch;
} else if (typeof fetch === "undefined") {
this.fetch = crossFetch;
} else {
this.fetch = fetch;
}
}
throwOnError() {
this.shouldThrowOnError = true;
return this;
}
then(onfulfilled, onrejected) {
if (this.schema === void 0)
;
else if (["GET", "HEAD"].includes(this.method)) {
this.headers["Accept-Profile"] = this.schema;
} else {
this.headers["Content-Profile"] = this.schema;
}
if (this.method !== "GET" && this.method !== "HEAD") {
this.headers["Content-Type"] = "application/json";
}
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 (res2) => {
var _a, _b, _c;
let error = null;
let data = null;
let count = null;
let status = res2.status;
let statusText = res2.statusText;
if (res2.ok) {
if (this.method !== "HEAD") {
const body = await res2.text();
if (body === "")
;
else if (this.headers["Accept"] === "text/csv") {
data = body;
} else if (this.headers["Accept"] && this.headers["Accept"].includes("application/vnd.pgrst.plan+text")) {
data = body;
} else {
data = JSON.parse(body);
}
}
const countHeader = (_a = this.headers["Prefer"]) === null || _a === void 0 ? void 0 : _a.match(/count=(exact|planned|estimated)/);
const contentRange = (_b = res2.headers.get("content-range")) === null || _b === void 0 ? void 0 : _b.split("/");
if (countHeader && contentRange && contentRange.length > 1) {
count = parseInt(contentRange[1]);
}
} else {
const body = await res2.text();
try {
error = JSON.parse(body);
if (Array.isArray(error) && res2.status === 404) {
data = [];
error = null;
status = 200;
statusText = "OK";
}
} catch (_d) {
if (res2.status === 404 && body === "") {
status = 204;
statusText = "No Content";
} else {
error = {
message: body
};
}
}
if (error && this.allowEmpty && ((_c = error === null || error === void 0 ? void 0 : error.details) === null || _c === void 0 ? void 0 : _c.includes("Results contain 0 rows"))) {
error = null;
status = 200;
statusText = "OK";
}
if (error && this.shouldThrowOnError) {
throw error;
}
}
const postgrestResponse = {
error,
data,
count,
status,
statusText
};
return postgrestResponse;
});
if (!this.shouldThrowOnError) {
res = res.catch((fetchError) => ({
error: {
message: `FetchError: ${fetchError.message}`,
details: "",
hint: "",
code: fetchError.code || ""
},
data: null,
count: null,
status: 0,
statusText: ""
}));
}
return res.then(onfulfilled, onrejected);
}
}
class PostgrestTransformBuilder extends PostgrestBuilder {
select(columns) {
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 (this.headers["Prefer"]) {
this.headers["Prefer"] += ",";
}
this.headers["Prefer"] += "return=representation";
return this;
}
order(column, { ascending = true, nullsFirst, foreignTable } = {}) {
const key = foreignTable ? `${foreignTable}.order` : "order";
const existingOrder = this.url.searchParams.get(key);
this.url.searchParams.set(key, `${existingOrder ? `${existingOrder},` : ""}${column}.${ascending ? "asc" : "desc"}${nullsFirst === void 0 ? "" : nullsFirst ? ".nullsfirst" : ".nullslast"}`);
return this;
}
limit(count, { foreignTable } = {}) {
const key = typeof foreignTable === "undefined" ? "limit" : `${foreignTable}.limit`;
this.url.searchParams.set(key, `${count}`);
return this;
}
range(from, to, { foreignTable } = {}) {
const keyOffset = typeof foreignTable === "undefined" ? "offset" : `${foreignTable}.offset`;
const keyLimit = typeof foreignTable === "undefined" ? "limit" : `${foreignTable}.limit`;
this.url.searchParams.set(keyOffset, `${from}`);
this.url.searchParams.set(keyLimit, `${to - from + 1}`);
return this;
}
abortSignal(signal) {
this.signal = signal;
return this;
}
single() {
this.headers["Accept"] = "application/vnd.pgrst.object+json";
return this;
}
maybeSingle() {
this.headers["Accept"] = "application/vnd.pgrst.object+json";
this.allowEmpty = true;
return this;
}
csv() {
this.headers["Accept"] = "text/csv";
return this;
}
geojson() {
this.headers["Accept"] = "application/geo+json";
return this;
}
explain({ analyze = false, verbose = false, settings = false, buffers = false, wal = false, format = "text" } = {}) {
const options = [
analyze ? "analyze" : null,
verbose ? "verbose" : null,
settings ? "settings" : null,
buffers ? "buffers" : null,
wal ? "wal" : null
].filter(Boolean).join("|");
const forMediatype = this.headers["Accept"];
this.headers["Accept"] = `application/vnd.pgrst.plan+${format}; for="${forMediatype}"; options=${options};`;
if (format === "json")
return this;
else
return this;
}
rollback() {
var _a;
if (((_a = this.headers["Prefer"]) !== null && _a !== void 0 ? _a : "").trim().length > 0) {
this.headers["Prefer"] += ",tx=rollback";
} else {
this.headers["Prefer"] = "tx=rollback";
}
return this;
}
returns() {
return this;
}
}
class PostgrestFilterBuilder extends PostgrestTransformBuilder {
eq(column, value) {
this.url.searchParams.append(column, `eq.${value}`);
return this;
}
neq(column, value) {
this.url.searchParams.append(column, `neq.${value}`);
return this;
}
gt(column, value) {
this.url.searchParams.append(column, `gt.${value}`);
return this;
}
gte(column, value) {
this.url.searchParams.append(column, `gte.${value}`);
return this;
}
lt(column, value) {
this.url.searchParams.append(column, `lt.${value}`);
return this;
}
lte(column, value) {
this.url.searchParams.append(column, `lte.${value}`);
return this;
}
like(column, pattern) {
this.url.searchParams.append(column, `like.${pattern}`);
return this;
}
ilike(column, pattern) {
this.url.searchParams.append(column, `ilike.${pattern}`);
return this;
}
is(column, value) {
this.url.searchParams.append(column, `is.${value}`);
return this;
}
in(column, values) {
const cleanedValues = values.map((s) => {
if (typeof s === "string" && new RegExp("[,()]").test(s))
return `"${s}"`;
else
return `${s}`;
}).join(",");
this.url.searchParams.append(column, `in.(${cleanedValues})`);
return this;
}
contains(column, value) {
if (typeof value === "string") {
this.url.searchParams.append(column, `cs.${value}`);
} else if (Array.isArray(value)) {
this.url.searchParams.append(column, `cs.{${value.join(",")}}`);
} else {
this.url.searchParams.append(column, `cs.${JSON.stringify(value)}`);
}
return this;
}
containedBy(column, value) {
if (typeof value === "string") {
this.url.searchParams.append(column, `cd.${value}`);
} else if (Array.isArray(value)) {
this.url.searchParams.append(column, `cd.{${value.join(",")}}`);
} else {
this.url.searchParams.append(column, `cd.${JSON.stringify(value)}`);
}
return this;
}
rangeGt(column, range) {
this.url.searchParams.append(column, `sr.${range}`);
return this;
}
rangeGte(column, range) {
this.url.searchParams.append(column, `nxl.${range}`);
return this;
}
rangeLt(column, range) {
this.url.searchParams.append(column, `sl.${range}`);
return this;
}
rangeLte(column, range) {
this.url.searchParams.append(column, `nxr.${range}`);
return this;
}
rangeAdjacent(column, range) {
this.url.searchParams.append(column, `adj.${range}`);
return this;
}
overlaps(column, value) {
if (typeof value === "string") {
this.url.searchParams.append(column, `ov.${value}`);
} else {
this.url.searchParams.append(column, `ov.{${value.join(",")}}`);
}
return this;
}
textSearch(column, query, { config: config2, type } = {}) {
let typePart = "";
if (type === "plain") {
typePart = "pl";
} else if (type === "phrase") {
typePart = "ph";
} else if (type === "websearch") {
typePart = "w";
}
const configPart = config2 === void 0 ? "" : `(${config2})`;
this.url.searchParams.append(column, `${typePart}fts${configPart}.${query}`);
return this;
}
match(query) {
Object.entries(query).forEach(([column, value]) => {
this.url.searchParams.append(column, `eq.${value}`);
});
return this;
}
not(column, operator, value) {
this.url.searchParams.append(column, `not.${operator}.${value}`);
return this;
}
or(filters, { foreignTable } = {}) {
const key = foreignTable ? `${foreignTable}.or` : "or";
this.url.searchParams.append(key, `(${filters})`);
return this;
}
filter(column, operator, value) {
this.url.searchParams.append(column, `${operator}.${value}`);
return this;
}
}
class PostgrestQueryBuilder {
constructor(url, { headers = {}, schema, fetch: fetch2 }) {
this.url = url;
this.headers = headers;
this.schema = schema;
this.fetch = fetch2;
}
select(columns, { head = false, count } = {}) {
const method = head ? "HEAD" : "GET";
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["Prefer"] = `count=${count}`;
}
return new PostgrestFilterBuilder({
method,
url: this.url,
headers: this.headers,
schema: this.schema,
fetch: this.fetch,
allowEmpty: false
});
}
insert(values, { count } = {}) {
const method = "POST";
const prefersHeaders = [];
const body = values;
if (count) {
prefersHeaders.push(`count=${count}`);
}
if (this.headers["Prefer"]) {
prefersHeaders.unshift(this.headers["Prefer"]);
}
this.headers["Prefer"] = prefersHeaders.join(",");
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({
method,
url: this.url,
headers: this.headers,
schema: this.schema,
body,
fetch: this.fetch,
allowEmpty: false
});
}
upsert(values, { onConflict, ignoreDuplicates = false, count } = {}) {
const method = "POST";
const prefersHeaders = [`resolution=${ignoreDuplicates ? "ignore" : "merge"}-duplicates`];
if (onConflict !== void 0)
this.url.searchParams.set("on_conflict", onConflict);
const body = values;
if (count) {
prefersHeaders.push(`count=${count}`);
}
if (this.headers["Prefer"]) {
prefersHeaders.unshift(this.headers["Prefer"]);
}
this.headers["Prefer"] = prefersHeaders.join(",");
return new PostgrestFilterBuilder({
method,
url: this.url,
headers: this.headers,
schema: this.schema,
body,
fetch: this.fetch,
allowEmpty: false
});
}
update(values, { count } = {}) {
const method = "PATCH";
const prefersHeaders = [];
const body = values;
if (count) {
prefersHeaders.push(`count=${count}`);
}
if (this.headers["Prefer"]) {
prefersHeaders.unshift(this.headers["Prefer"]);
}
this.headers["Prefer"] = prefersHeaders.join(",");
return new PostgrestFilterBuilder({
method,
url: this.url,
headers: this.headers,
schema: this.schema,
body,
fetch: this.fetch,
allowEmpty: false
});
}
delete({ count } = {}) {
const method = "DELETE";
const prefersHeaders = [];
if (count) {
prefersHeaders.push(`count=${count}`);
}
if (this.headers["Prefer"]) {
prefersHeaders.unshift(this.headers["Prefer"]);
}
this.headers["Prefer"] = prefersHeaders.join(",");
return new PostgrestFilterBuilder({
method,
url: this.url,
headers: this.headers,
schema: this.schema,
fetch: this.fetch,
allowEmpty: false
});
}
}
const version$6 = "1.5.0";
const DEFAULT_HEADERS$4 = { "X-Client-Info": `postgrest-js/${version$6}` };
class PostgrestClient {
constructor(url, { headers = {}, schema, fetch: fetch2 } = {}) {
this.url = url;
this.headers = Object.assign(Object.assign({}, DEFAULT_HEADERS$4), headers);
this.schema = schema;
this.fetch = fetch2;
}
from(relation) {
const url = new URL(`${this.url}/${relation}`);
return new PostgrestQueryBuilder(url, {
headers: Object.assign({}, this.headers),
schema: this.schema,
fetch: this.fetch
});
}
rpc(fn, args = {}, { head = false, count } = {}) {
let method;
const url = new URL(`${this.url}/rpc/${fn}`);
let body;
if (head) {
method = "HEAD";
Object.entries(args).forEach(([name2, value]) => {
url.searchParams.append(name2, `${value}`);
});
} else {
method = "POST";
body = args;
}
const headers = Object.assign({}, this.headers);
if (count) {
headers["Prefer"] = `count=${count}`;
}
return new PostgrestFilterBuilder({
method,
url,
headers,
schema: this.schema,
body,
fetch: this.fetch,
allowEmpty: false
});
}
}
const _args = [
[
"websocket@1.0.34",
"/Users/Dido/Desktop/Test/vue-3-supabase"
]
];
const _from = "websocket@1.0.34";
const _id = "websocket@1.0.34";
const _inBundle = false;
const _integrity = "sha512-PRDso2sGwF6kM75QykIesBijKSVceR6jL2G8NGYyq2XrItNC2P5/qL5XeR056GhA+Ly7JMFvJb9I312mJfmqnQ==";
const _location = "/websocket";
const _phantomChildren = {};
const _requested = {
type: "version",
registry: true,
raw: "websocket@1.0.34",
name: "websocket",
escapedName: "websocket",
rawSpec: "1.0.34",
saveSpec: null,
fetchSpec: "1.0.34"
};
const _requiredBy = [
"/@supabase/realtime-js"
];
const _resolved = "https://registry.npmjs.org/websocket/-/websocket-1.0.34.tgz";
const _spec = "1.0.34";
const _where = "/Users/Dido/Desktop/Test/vue-3-supabase";
const author = {
name: "Brian McKelvey",
email: "theturtle32@gmail.com",
url: "https://github.com/theturtle32"
};
const browser$1 = "lib/browser.js";
const bugs = {
url: "https://github.com/theturtle32/WebSocket-Node/issues"
};
const config = {
verbose: false
};
const contributors = [
{
name: "I\xF1aki Baz Castillo",
email: "ibc@aliax.net",
url: "http://dev.sipdoc.net"
}
];
const dependencies = {
bufferutil: "^4.0.1",
debug: "^2.2.0",
"es5-ext": "^0.10.50",
"typedarray-to-buffer": "^3.1.5",
"utf-8-validate": "^5.0.2",
yaeti: "^0.0.6"
};
const description = "Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.";
const devDependencies = {
"buffer-equal": "^1.0.0",
gulp: "^4.0.2",
"gulp-jshint": "^2.0.4",
jshint: "^2.0.0",
"jshint-stylish": "^2.2.1",
tape: "^4.9.1"
};
const directories = {
lib: "./lib"
};
const engines = {
node: ">=4.0.0"
};
const homepage = "https://github.com/theturtle32/WebSocket-Node";
const keywords = [
"websocket",
"websockets",
"socket",
"networking",
"comet",
"push",
"RFC-6455",
"realtime",
"server",
"client"
];
const license = "Apache-2.0";
const main$1 = "index";
const name = "websocket";
const repository = {
type: "git",
url: "git+https://github.com/theturtle32/WebSocket-Node.git"
};
const scripts = {
gulp: "gulp",
test: "tape test/unit/*.js"
};
const version$5 = "1.0.34";
var require$$0 = {
_args,
_from,
_id,
_inBundle,
_integrity,
_location,
_phantomChildren,
_requested,
_requiredBy,
_resolved,
_spec,
_where,
author,
browser: browser$1,
bugs,
config,
contributors,
dependencies,
description,
devDependencies,
directories,
engines,
homepage,
keywords,
license,
main: main$1,
name,
repository,
scripts,
version: version$5
};
var version$4 = require$$0.version;
var _globalThis;
if (typeof globalThis === "object") {
_globalThis = globalThis;
} else {
try {
_globalThis = require("es5-ext/global");
} catch (error) {
} finally {
if (!_globalThis && typeof window !== "undefined") {
_globalThis = window;
}
if (!_globalThis) {
throw new Error("Could not determine global this");
}
}
}
var NativeWebSocket = _globalThis.WebSocket || _globalThis.MozWebSocket;
var websocket_version = version$4;
function W3CWebSocket(uri, protocols) {
var native_instance;
if (protocols) {
native_instance = new NativeWebSocket(uri, protocols);
} else {
native_instance = new NativeWebSocket(uri);
}
return native_instance;
}
if (NativeWebSocket) {
["CONNECTING", "OPEN", "CLOSING", "CLOSED"].forEach(function(prop) {
Object.defineProperty(W3CWebSocket, prop, {
get: function() {
return NativeWebSocket[prop];
}
});
});
}
var browser = {
"w3cwebsocket": NativeWebSocket ? W3CWebSocket : null,
"version": websocket_version
};
const version$3 = "2.7.2";
const DEFAULT_HEADERS$3 = { "X-Client-Info": `realtime-js/${version$3}` };
const VSN = "1.0.0";
const DEFAULT_TIMEOUT = 1e4;
const WS_CLOSE_NORMAL = 1e3;
var SOCKET_STATES;
(function(SOCKET_STATES2) {
SOCKET_STATES2[SOCKET_STATES2["connecting"] = 0] = "connecting";
SOCKET_STATES2[SOCKET_STATES2["open"] = 1] = "open";
SOCKET_STATES2[SOCKET_STATES2["closing"] = 2] = "closing";
SOCKET_STATES2[SOCKET_STATES2["closed"] = 3] = "closed";
})(SOCKET_STATES || (SOCKET_STATES = {}));
var CHANNEL_STATES;
(function(CHANNEL_STATES2) {
CHANNEL_STATES2["closed"] = "closed";
CHANNEL_STATES2["errored"] = "errored";
CHANNEL_STATES2["joined"] = "joined";
CHANNEL_STATES2["joining"] = "joining";
CHANNEL_STATES2["leaving"] = "leaving";
})(CHANNEL_STATES || (CHANNEL_STATES = {}));
var CHANNEL_EVENTS;
(function(CHANNEL_EVENTS2) {
CHANNEL_EVENTS2["close"] = "phx_close";
CHANNEL_EVENTS2["error"] = "phx_error";
CHANNEL_EVENTS2["join"] = "phx_join";
CHANNEL_EVENTS2["reply"] = "phx_reply";
CHANNEL_EVENTS2["leave"] = "phx_leave";
CHANNEL_EVENTS2["access_token"] = "access_token";
})(CHANNEL_EVENTS || (CHANNEL_EVENTS = {}));
var TRANSPORTS;
(function(TRANSPORTS2) {
TRANSPORTS2["websocket"] = "websocket";
})(TRANSPORTS || (TRANSPORTS = {}));
var CONNECTION_STATE;
(function(CONNECTION_STATE2) {
CONNECTION_STATE2["Connecting"] = "connecting";
CONNECTION_STATE2["Open"] = "open";
CONNECTION_STATE2["Closing"] = "closing";
CONNECTION_STATE2["Closed"] = "closed";
})(CONNECTION_STATE || (CONNECTION_STATE = {}));
class Timer {
constructor(callback, timerCalc) {
this.callback = callback;
this.timerCalc = timerCalc;
this.timer = void 0;
this.tries = 0;
this.callback = callback;
this.timerCalc = timerCalc;
}
reset() {
this.tries = 0;
clearTimeout(this.timer);
}
scheduleTimeout() {
clearTimeout(this.timer);
this.timer = setTimeout(() => {
this.tries = this.tries + 1;
this.callback();
}, this.timerCalc(this.tries + 1));
}
}
class Serializer {
constructor() {
this.HEADER_LENGTH = 1;
}
decode(rawPayload, callback) {
if (rawPayload.constructor === ArrayBuffer) {
return callback(this._binaryDecode(rawPayload));
}
if (typeof rawPayload === "string") {
return callback(JSON.parse(rawPayload));
}
return callback({});
}
_binaryDecode(buffer) {
const view = new DataView(buffer);
const decoder = new TextDecoder();
return this._decodeBroadcast(buffer, view, decoder);
}
_decodeBroadcast(buffer, view, decoder) {
const topicSize = view.getUint8(1);
const eventSize = view.getUint8(2);
let offset = this.HEADER_LENGTH + 2;
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, event, payload: data };
}
}
class Push {
constructor(channel, event, payload = {}, timeout = DEFAULT_TIMEOUT) {
this.channel = channel;
this.event = event;
this.payload = payload;
this.timeout = timeout;
this.sent = false;
this.timeoutTimer = void 0;
this.ref = "";
this.receivedResp = null;
this.recHooks = [];
this.refEvent = null;
this.rateLimited = false;
}
resend(timeout) {
this.timeout = timeout;
this._cancelRefEvent();
this.ref = "";
this.refEvent = null;
this.receivedResp = null;
this.sent = false;
this.send();
}
send() {
if (this._hasReceived("timeout")) {
return;
}
this.startTimeout();
this.sent = true;
const status = this.channel.socket.push({
topic: this.channel.topic,
event: this.event,
payload: this.payload,
ref: this.ref,
join_ref: this.channel._joinRef()
});
if (status === "rate limited") {
this.rateLimited = true;
}
}
updatePayload(payload) {
this.payload = Object.assign(Object.assign({}, this.payload), payload);
}
receive(status, callback) {
var _a;
if (this._hasReceived(status)) {
callback((_a = this.receivedResp) === null || _a === void 0 ? void 0 : _a.response);
}
this.recHooks.push({ status, callback });
return this;
}
startTimeout() {
if (this.timeoutTimer) {
return;
}
this.ref = this.channel.socket._makeRef();
this.refEvent = this.channel._replyEventName(this.ref);
const callback = (payload) => {
this._cancelRefEvent();
this._cancelTimeout();
this.receivedResp = payload;
this._matchReceive(payload);
};
this.channel._on(this.refEvent, {}, callback);
this.timeoutTimer = setTimeout(() => {
this.trigger("timeout", {});
}, this.timeout);
}
trigger(status, response) {
if (this.refEvent)
this.channel._trigger(this.refEvent, { status, response });
}
destroy() {
this._cancelRefEvent();
this._cancelTimeout();
}
_cancelRefEvent() {
if (!this.refEvent) {
return;
}
this.channel._off(this.refEvent, {});
}
_cancelTimeout() {
clearTimeout(this.timeoutTimer);
this.timeoutTimer = void 0;
}
_matchReceive({ status, response }) {
this.recHooks.filter((h) => h.status === status).forEach((h) => h.callback(response));
}
_hasReceived(status) {
return this.receivedResp && this.receivedResp.status === status;
}
}
var REALTIME_PRESENCE_LISTEN_EVENTS;
(function(REALTIME_PRESENCE_LISTEN_EVENTS2) {
REALTIME_PRESENCE_LISTEN_EVENTS2["SYNC"] = "sync";
REALTIME_PRESENCE_LISTEN_EVENTS2["JOIN"] = "join";
REALTIME_PRESENCE_LISTEN_EVENTS2["LEAVE"] = "leave";
})(REALTIME_PRESENCE_LISTEN_EVENTS || (REALTIME_PRESENCE_LISTEN_EVENTS = {}));
class RealtimePresence {
constructor(channel, opts) {
this.channel = channel;
this.state = {};
this.pendingDiffs = [];
this.joinRef = null;
this.caller = {
onJoin: () => {
},
onLeave: () => {
},
onSync: () => {
}
};
const events = (opts === null || opts === void 0 ? void 0 : opts.events) || {
state: "presence_state",
diff: "presence_diff"
};
this.channel._on(events.state, {}, (newState) => {
const { onJoin, onLeave, onSync } = this.caller;
this.joinRef = this.channel._joinRef();
this.state = RealtimePresence.syncState(this.state, newState, onJoin, onLeave);
this.pendingDiffs.forEach((diff) => {
this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave);
});
this.pendingDiffs = [];
onSync();
});
this.channel._on(events.diff, {}, (diff) => {
const { onJoin, onLeave, onSync } = this.caller;
if (this.inPendingSyncState()) {
this.pendingDiffs.push(diff);
} else {
this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave);
onSync();
}
});
this.onJoin((key, currentPresences, newPresences) => {
this.channel._trigger("presence", {
event: "join",
key,
currentPresences,
newPresences
});
});
this.onLeave((key, currentPresences, leftPresences) => {
this.channel._trigger("presence", {
event: "leave",
key,
currentPresences,
leftPresences
});
});
this.onSync(() => {
this.channel._trigger("presence", { event: "sync" });
});
}
static syncState(currentState, newState, onJoin, onLeave) {
const state = this.cloneDeep(currentState);
const transformedState = this.transformState(newState);
const joins = {};
const leaves = {};
this.map(state, (key, presences) => {
if (!transformedState[key]) {
leaves[key] = presences;
}
});
this.map(transformedState, (key, newPresences) => {
const currentPresences = state[key];
if (currentPresences) {
const newPresenceRefs = newPresences.map((m) => m.presence_ref);
const curPresenceRefs = currentPresences.map((m) => m.presence_ref);
const joinedPresences = newPresences.filter((m) => curPresenceRefs.indexOf(m.presence_ref) < 0);
const leftPresences = currentPresences.filter((m) => newPresenceRefs.indexOf(m.presence_ref) < 0);
if (joinedPresences.length > 0) {
joins[key] = joinedPresences;
}
if (leftPresences.length > 0) {
leaves[key] = leftPresences;
}
} else {
joins[key] = newPresences;
}
});
return this.syncDiff(state, { joins, leaves }, onJoin, onLeave);
}
static syncDiff(state, diff, onJoin, onLeave) {
const { joins, leaves } = {
joins: this.transformState(diff.joins),
leaves: this.transformState(diff.leaves)
};
if (!onJoin) {
onJoin = () => {
};
}
if (!onLeave) {
onLeave = () => {
};
}
this.map(joins, (key, newPresences) => {
var _a;
const currentPresences = (_a = state[key]) !== null && _a !== void 0 ? _a : [];
state[key] = this.cloneDeep(newPresences);
if (currentPresences.length > 0) {
const joinedPresenceRefs = state[key].map((m) => m.presence_ref);
const curPresences = currentPresences.filter((m) => joinedPresenceRefs.indexOf(m.presence_ref) < 0);
state[key].unshift(...curPresences);
}
onJoin(key, currentPresences, newPresences);
});
this.map(leaves, (key, leftPresences) => {
let currentPresences = state[key];
if (!currentPresences)
return;
const presenceRefsToRemove = leftPresences.map((m) => m.presence_ref);
currentPresences = currentPresences.filter((m) => presenceRefsToRemove.indexOf(m.presence_ref) < 0);
state[key] = currentPresences;
onLeave(key, currentPresences, leftPresences);
if (currentPresences.length === 0)
delete state[key];
});
return state;
}
static map(obj, func) {
return Object.getOwnPropertyNames(obj).map((key) => func(key, obj[key]));
}
static transformState(state) {
state = this.cloneDeep(state);
return Object.getOwnPropertyNames(state).reduce((newState, key) => {
const presences = state[key];
if ("metas" in presences) {
newState[key] = presences.metas.map((presence) => {
presence["presence_ref"] = presence["phx_ref"];
delete presence["phx_ref"];
delete presence["phx_ref_prev"];
return presence;
});
} else {
newState[key] = presences;
}
return newState;
}, {});
}
static cloneDeep(obj) {
return JSON.parse(JSON.stringify(obj));
}
onJoin(callback) {
this.caller.onJoin = callback;
}
onLeave(callback) {
this.caller.onLeave = callback;
}
onSync(callback) {
this.caller.onSync = callback;
}
inPendingSyncState() {
return !this.joinRef || this.joinRef !== this.channel._joinRef();
}
}
var PostgresTypes;
(function(PostgresTypes2) {
PostgresTypes2["abstime"] = "abstime";
PostgresTypes2["bool"] = "bool";
PostgresTypes2["date"] = "date";
PostgresTypes2["daterange"] = "daterange";
PostgresTypes2["float4"] = "float4";
PostgresTypes2["float8"] = "float8";
PostgresTypes2["int2"] = "int2";
PostgresTypes2["int4"] = "int4";
PostgresTypes2["int4range"] = "int4range";
PostgresTypes2["int8"] = "int8";
PostgresTypes2["int8range"] = "int8range";
PostgresTypes2["json"] = "json";
PostgresTypes2["jsonb"] = "jsonb";
PostgresTypes2["money"] = "money";
PostgresTypes2["numeric"] = "numeric";
PostgresTypes2["oid"] = "oid";
PostgresTypes2["reltime"] = "reltime";
PostgresTypes2["text"] = "text";
PostgresTypes2["time"] = "time";
PostgresTypes2["timestamp"] = "timestamp";
PostgresTypes2["timestamptz"] = "timestamptz";
PostgresTypes2["timetz"] = "timetz";
PostgresTypes2["tsrange"] = "tsrange";
PostgresTypes2["tstzrange"] = "tstzrange";
})(PostgresTypes || (PostgresTypes = {}));
const convertChangeData = (columns, record, options = {}) => {
var _a;
const skipTypes = (_a = options.skipTypes) !== null && _a !== void 0 ? _a : [];
return Object.keys(record).reduce((acc, rec_key) => {
acc[rec_key] = convertColumn(rec_key, columns, record, skipTypes);
return acc;
}, {});
};
const convertColumn = (columnName, columns, record, skipTypes) => {
const column = columns.find((x) => x.name === columnName);
const colType = column === null || column === void 0 ? void 0 : column.type;
const value = record[columnName];
if (colType && !skipTypes.includes(colType)) {
return convertCell(colType, value);
}
return noop$1(value);
};
const convertCell = (type, value) => {
if (type.charAt(0) === "_") {
const dataType = type.slice(1, type.length);
return toArray(value, dataType);
}
switch (type) {
case PostgresTypes.bool:
return toBoolean(value);
case PostgresTypes.float4:
case PostgresTypes.float8:
case PostgresTypes.int2:
case PostgresTypes.int4:
case PostgresTypes.int8:
case PostgresTypes.numeric:
case PostgresTypes.oid:
return toNumber(value);
case PostgresTypes.json:
case PostgresTypes.jsonb:
return toJson(value);
case PostgresTypes.timestamp:
return toTimestampString(value);
case PostgresTypes.abstime:
case PostgresTypes.date:
case PostgresTypes.daterange:
case PostgresTypes.int4range:
case PostgresTypes.int8range:
case PostgresTypes.money:
case PostgresTypes.reltime:
case PostgresTypes.text:
case PostgresTypes.time:
case PostgresTypes.timestamptz:
case PostgresTypes.timetz:
case PostgresTypes.tsrange:
case PostgresTypes.tstzrange:
return noop$1(value);
default:
return noop$1(value);
}
};
const noop$1 = (value) => {
return value;
};
const toBoolean = (value) => {
switch (value) {
case "t":
return true;
case "f":
return false;
default:
return value;
}
};
const toNumber = (value) => {
if (typeof value === "string") {
const parsedValue = parseFloat(value);
if (!Number.isNaN(parsedValue)) {
return parsedValue;
}
}
return value;
};
const toJson = (value) => {
if (typeof value === "string") {
try {
return JSON.parse(value);
} catch (error) {
console.log(`JSON parse error: ${error}`);
return value;
}
}
return value;
};
const toArray = (value, type) => {
if (typeof value !== "string") {
return value;
}
const lastIdx = value.length - 1;
const closeBrace = value[lastIdx];
const openBrace = value[0];
if (openBrace === "{" && closeBrace === "}") {
let arr;
const valTrim = value.slice(1, lastIdx);
try {
arr = JSON.parse("[" + valTrim + "]");
} catch (_) {
arr = valTrim ? valTrim.split(",") : [];
}
return arr.map((val) => convertCell(type, val));
}
return value;
};
const toTimestampString = (value) => {
if (typeof value === "string") {
return value.replace(" ", "T");
}
return value;
};
var __awaiter$b = globalThis && globalThis.__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());
});
};
var REALTIME_POSTGRES_CHANGES_LISTEN_EVENT;
(function(REALTIME_POSTGRES_CHANGES_LISTEN_EVENT2) {
REALTIME_POSTGRES_CHANGES_LISTEN_EVENT2["ALL"] = "*";
REALTIME_POSTGRES_CHANGES_LISTEN_EVENT2["INSERT"] = "INSERT";
REALTIME_POSTGRES_CHANGES_LISTEN_EVENT2["UPDATE"] = "UPDATE";
REALTIME_POSTGRES_CHANGES_LISTEN_EVENT2["DELETE"] = "DELETE";
})(REALTIME_POSTGRES_CHANGES_LISTEN_EVENT || (REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = {}));
var REALTIME_LISTEN_TYPES;
(function(REALTIME_LISTEN_TYPES2) {
REALTIME_LISTEN_TYPES2["BROADCAST"] = "broadcast";
REALTIME_LISTEN_TYPES2["PRESENCE"] = "presence";
REALTIME_LISTEN_TYPES2["POSTGRES_CHANGES"] = "postgres_changes";
})(REALTIME_LISTEN_TYPES || (REALTIME_LISTEN_TYPES = {}));
var REALTIME_SUBSCRIBE_STATES;
(function(REALTIME_SUBSCRIBE_STATES2) {
REALTIME_SUBSCRIBE_STATES2["SUBSCRIBED"] = "SUBSCRIBED";
REALTIME_SUBSCRIBE_STATES2["TIMED_OUT"] = "TIMED_OUT";
REALTIME_SUBSCRIBE_STATES2["CLOSED"] = "CLOSED";
REALTIME_SUBSCRIBE_STATES2["CHANNEL_ERROR"] = "CHANNEL_ERROR";
})(REALTIME_SUBSCRIBE_STATES || (REALTIME_SUBSCRIBE_STATES = {}));
class RealtimeChannel {
constructor(topic, params = { config: {} }, socket) {
this.topic = topic;
this.params = params;
this.socket = socket;
this.bindings = {};
this.state = CHANNEL_STATES.closed;
this.joinedOnce = false;
this.pushBuffer = [];
this.params.config = Object.assign({
broadcast: { ack: false, self: false },
presence: { key: "" }
}, params.config);
this.timeout = this.socket.timeout;
this.joinPush = new Push(this, CHANNEL_EVENTS.join, this.params, this.timeout);
this.rejoinTimer = new Timer(() => this._rejoinUntilConnected(), this.socket.reconnectAfterMs);
this.joinPush.receive("ok", () => {
this.state = CHANNEL_STATES.joined;
this.rejoinTimer.reset();
this.pushBuffer.forEach((pushEvent) => pushEvent.send());
this.pushBuffer = [];
});
this._onClose(() => {
this.rejoinTimer.reset();
this.socket.log("channel", `close ${this.topic} ${this._joinRef()}`);
this.state = CHANNEL_STATES.closed;
this.socket._remove(this);
});
this._onError((reason) => {
if (this._isLeaving() || this._isClosed()) {
return;
}
this.socket.log("channel", `error ${this.topic}`, reason);
this.state = CHANNEL_STATES.errored;
this.rejoinTimer.scheduleTimeout();
});
this.joinPush.receive("timeout", () => {
if (!this._isJoining()) {
return;
}
this.socket.log("channel", `timeout ${this.topic}`, this.joinPush.timeout);
this.state = CHANNEL_STATES.errored;
this.rejoinTimer.scheduleTimeout();
});
this._on(CHANNEL_EVENTS.reply, {}, (payload, ref) => {
this._trigger(this._replyEventName(ref), payload);
});
this.presence = new RealtimePresence(this);
}
subscribe(callback, timeout = this.timeout) {
var _a, _b;
if (this.joinedOnce) {
throw `tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance`;
} else {
const { config: { broadcast, presence } } = this.params;
this._onError((e) => callback && callback("CHANNEL_ERROR", e));
this._onClose(() => callback && callback("CLOSED"));
const accessTokenPayload = {};
const config2 = {
broadcast,
presence,
postgres_changes: (_b = (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.map((r) => r.filter)) !== null && _b !== void 0 ? _b : []
};
if (this.socket.accessToken) {
accessTokenPayload.access_token = this.socket.accessToken;
}
this.updateJoinPayload(Object.assign({ config: config2 }, accessTokenPayload));
this.joinedOnce = true;
this._rejoin(timeout);
this.joinPush.receive("ok", ({ postgres_changes: serverPostgresFilters }) => {
var _a2;
this.socket.accessToken && this.socket.setAuth(this.socket.accessToken);
if (serverPostgresFilters === void 0) {
callback && callback("SUBSCRIBED");
return;
} else {
const clientPostgresBindings = this.bindings.postgres_changes;
const bindingsLen = (_a2 = clientPostgresBindings === null || clientPostgresBindings === void 0 ? void 0 : clientPostgresBindings.length) !== null && _a2 !== void 0 ? _a2 : 0;
const newPostgresBindings = [];
for (let i = 0; i < bindingsLen; i++) {
const clientPostgresBinding = clientPostgresBindings[i];
const { filter: { event, schema, table, filter } } = clientPostgresBinding;
const serverPostgresFilter = serverPostgresFilters && serverPostgresFilters[i];
if (serverPostgresFilter && serverPostgresFilter.event === event && serverPostgresFilter.schema === schema && serverPostgresFilter.table === table && serverPostgresFilter.filter === filter) {
newPostgresBindings.push(Object.assign(Object.assign({}, clientPostgresBinding), { id: serverPostgresFilter.id }));
} else {
this.unsubscribe();
callback && callback("CHANNEL_ERROR", new Error("mismatch between server and client bindings for postgres changes"));
return;
}
}
this.bindings.postgres_changes = newPostgresBindings;
callback && callback("SUBSCRIBED");
return;
}
}).receive("error", (error) => {
callback && callback("CHANNEL_ERROR", new Error(JSON.stringify(Object.values(error).join(", ") || "error")));
return;
}).receive("timeout", () => {
callback && callback("TIMED_OUT");
return;
});
}
return this;
}
presenceState() {
return this.presence.state;
}
track(payload, opts = {}) {
return __awaiter$b(this, void 0, void 0, function* () {
return yield this.send({
type: "presence",
event: "track",
payload
}, opts.timeout || this.timeout);
});
}
untrack(opts = {}) {
return __awaiter$b(this, void 0, void 0, function* () {
return yield this.send({
type: "presence",
event: "untrack"
}, opts);
});
}
on(type, filter, callback) {
return this._on(type, filter, callback);
}
send(payload, opts = {}) {
return new Promise((resolve) => {
var _a, _b, _c;
const push = this._push(payload.type, payload, opts.timeout || this.timeout);
if (push.rateLimited) {
resolve("rate limited");
}
if (payload.type === "broadcast" && !((_c = (_b = (_a = this.params) === null || _a === void 0 ? void 0 : _a.config) === null || _b === void 0 ? void 0 : _b.broadcast) === null || _c === void 0 ? void 0 : _c.ack)) {
resolve("ok");
}
push.receive("ok", () => resolve("ok"));
push.receive("timeout", () => resolve("timed out"));
});
}
updateJoinPayload(payload) {
this.joinPush.updatePayload(payload);
}
unsubscribe(timeout = this.timeout) {
this.state = CHANNEL_STATES.leaving;
const onClose = () => {
this.socket.log("channel", `leave ${this.topic}`);
this._trigger(CHANNEL_EVENTS.close, "leave", this._joinRef());
};
this.rejoinTimer.reset();
this.joinPush.destroy();
return new Promise((resolve) => {
const leavePush = new Push(this, CHANNEL_EVENTS.leave, {}, timeout);
leavePush.receive("ok", () => {
onClose();
resolve("ok");
}).receive("timeout", () => {
onClose();
resolve("timed out");
}).receive("error", () => {
resolve("error");
});
leavePush.send();
if (!this._canPush()) {
leavePush.trigger("ok", {});
}
});
}
_push(event, payload, timeout = this.timeout) {
if (!this.joinedOnce) {
throw `tried to push '${event}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;
}
let pushEvent = new Push(this, event, payload, timeout);
if (this._canPush()) {
pushEvent.send();
} else {
pushEvent.startTimeout();
this.pushBuffer.push(pushEvent);
}
return pushEvent;
}
_onMessage(_event, payload, _ref) {
return payload;
}
_isMember(topic) {
return this.topic === topic;
}
_joinRef() {
return this.joinPush.ref;
}
_trigger(type, payload, ref) {
var _a, _b;
const typeLower = type.toLocaleLowerCase();
const { close, error, leave, join } = CHANNEL_EVENTS;
const events = [close, error, leave, join];
if (ref && events.indexOf(typeLower) >= 0 && ref !== this._joinRef()) {
return;
}
let handledPayload = this._onMessage(typeLower, payload, ref);
if (payload && !handledPayload) {
throw "channel onMessage callbacks must return the payload, modified or unmodified";
}
if (["insert", "update", "delete"].includes(typeLower)) {
(_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.filter((bind) => {
var _a2, _b2, _c;
return ((_a2 = bind.filter) === null || _a2 === void 0 ? void 0 : _a2.event) === "*" || ((_c = (_b2 = bind.filter) === null || _b2 === void 0 ? void 0 : _b2.event) === null || _c === void 0 ? void 0 : _c.toLocaleLowerCase()) === typeLower;
}).map((bind) => bind.callback(handledPayload, ref));
} else {
(_b = this.bindings[typeLower]) === null || _b === void 0 ? void 0 : _b.filter((bind) => {
var _a2, _b2, _c, _d, _e, _f;
if (["broadcast", "presence", "postgres_changes"].includes(typeLower)) {
if ("id" in bind) {
const bindId = bind.id;
const bindEvent = (_a2 = bind.filter) === null || _a2 === void 0 ? void 0 : _a2.event;
return bindId && ((_b2 = payload.ids) === null || _b2 === void 0 ? void 0 : _b2.includes(bindId)) && (bindEvent === "*" || (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());
}
} else {
return bind.type.toLocaleLowerCase() === typeLower;
}
}).map((bind) => {
if (typeof handledPayload === "object" && "ids" in handledPayload) {
const postgresChanges = handledPayload.data;
const { schema, table, commit_timestamp, type: type2, errors } = postgresChanges;
const enrichedPayload = {
schema,
table,
commit_timestamp,
eventType: type2,
new: {},
old: {},
errors
};
handledPayload = Object.assign(Object.assign({}, enrichedPayload), this._getPayloadRecords(postgresChanges));
}
bind.callback(handledPayload, ref);
});
}
}
_isClosed() {
return this.state === CHANNEL_STATES.closed;
}
_isJoined() {
return this.state === CHANNEL_STATES.joined;
}
_isJoining() {
return this.state === CHANNEL_STATES.joining;
}
_isLeaving() {
return this.state === CHANNEL_STATES.leaving;
}
_replyEventName(ref) {
return `chan_reply_${ref}`;
}
_on(type, filter, callback) {
const typeLower = type.toLocaleLowerCase();
const binding = {
type: typeLower,
filter,
callback
};
if (this.bindings[typeLower]) {
this.bindings[typeLower].push(binding);
} else {
this.bindings[typeLower] = [binding];
}
return this;
}
_off(type, filter) {
const typeLower = type.toLocaleLowerCase();
this.bindings[typeLower] = this.bindings[typeLower].filter((bind) => {
var _a;
return !(((_a = bind.type) === null || _a === void 0 ? void 0 : _a.toLocaleLowerCase()) === typeLower && RealtimeChannel.isEqual(bind.filter, filter));
});
return this;
}
static isEqual(obj1, obj2) {
if (Object.keys(obj1).length !== Object.keys(obj2).length) {
return false;
}
for (const k in obj1) {
if (obj1[k] !== obj2[k]) {
return false;
}
}
return true;
}
_rejoinUntilConnected() {
this.rejoinTimer.scheduleTimeout();
if (this.socket.isConnected()) {
this._rejoin();
}
}
_onClose(callback) {
this._on(CHANNEL_EVENTS.close, {}, callback);
}
_onError(callback) {
this._on(CHANNEL_EVENTS.error, {}, (reason) => callback(reason));
}
_canPush() {
return this.socket.isConnected() && this._isJoined();
}
_rejoin(timeout = this.timeout) {
if (this._isLeaving()) {
return;
}
this.socket._leaveOpenTopic(this.topic);
this.state = CHANNEL_STATES.joining;
this.joinPush.resend(timeout);
}
_getPayloadRecords(payload) {
const records = {
new: {},
old: {}
};
if (payload.type === "INSERT" || payload.type === "UPDATE") {
records.new = convertChangeData(payload.columns, payload.record);
}
if (payload.type === "UPDATE" || payload.type === "DELETE") {
records.old = convertChangeData(payload.columns, payload.old_record);
}
return records;
}
}
var __awaiter$a = globalThis && globalThis.__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());
});
};
const noop = () => {
};
class RealtimeClient {
constructor(endPoint, options) {
var _a;
this.accessToken = null;
this.channels = [];
this.endPoint = "";
this.headers = DEFAULT_HEADERS$3;
this.params = {};
this.timeout = DEFAULT_TIMEOUT;
this.transport = browser.w3cwebsocket;
this.heartbeatIntervalMs = 3e4;
this.heartbeatTimer = void 0;
this.pendingHeartbeatRef = null;
this.ref = 0;
this.logger = noop;
this.conn = null;
this.sendBuffer = [];
this.serializer = new Serializer();
this.stateChangeCallbacks = {
open: [],
close: [],
error: [],
message: []
};
this.eventsPerSecondLimitMs = 100;
this.inThrottle = false;
this.endPoint = `${endPoint}/${TRANSPORTS.websocket}`;
if (options === null || options === void 0 ? void 0 : options.params)
this.params = options.params;
if (options === null || options === void 0 ? void 0 : options.headers)
this.headers = Object.assign(Object.assign({}, this.headers), options.headers);
if (options === null || options === void 0 ? void 0 : options.timeout)
this.timeout = options.timeout;
if (options === null || options === void 0 ? void 0 : options.logger)
this.logger = options.logger;
if (options === null || options === void 0 ? void 0 : options.transport)
this.transport = options.transport;
if (options === null || options === void 0 ? void 0 : options.heartbeatIntervalMs)
this.heartbeatIntervalMs = options.heartbeatIntervalMs;
const eventsPerSecond = (_a = options === null || options === void 0 ? void 0 : options.params) === null || _a === void 0 ? void 0 : _a.eventsPerSecond;
if (eventsPerSecond)
this.eventsPerSecondLimitMs = Math.floor(1e3 / eventsPerSecond);
this.reconnectAfterMs = (options === null || options === void 0 ? void 0 : options.reconnectAfterMs) ? options.reconnectAfterMs : (tries) => {
return [1e3, 2e3, 5e3, 1e4][tries - 1] || 1e4;
};
this.encode = (options === null || options === void 0 ? void 0 : options.encode) ? options.encode : (payload, callback) => {
return callback(JSON.stringify(payload));
};
this.decode = (options === null || options === void 0 ? void 0 : options.decode) ? options.decode : this.serializer.decode.bind(this.serializer);
this.reconnectTimer = new Timer(() => __awaiter$a(this, void 0, void 0, function* () {
this.disconnect();
this.connect();
}), this.reconnectAfterMs);
}
connect() {
if (this.conn) {
return;
}
this.conn = new this.transport(this._endPointURL(), [], null, this.headers);
if (this.conn) {
this.conn.binaryType = "arraybuffer";
this.conn.onopen = () => this._onConnOpen();
this.conn.onerror = (error) => this._onConnError(error);
this.conn.onmessage = (event) => this._onConnMessage(event);
this.conn.onclose = (event) => this._onConnClose(event);
}
}
disconnect(code, reason) {
if (this.conn) {
this.conn.onclose = function() {
};
if (code) {
this.conn.close(code, reason !== null && reason !== void 0 ? reason : "");
} else {
this.conn.close();
}
this.conn = null;
this.heartbeatTimer && clearInterval(this.heartbeatTimer);
this.reconnectTimer.reset();
}
}
getChannels() {
return this.channels;
}
removeChannel(channel) {
return __awaiter$a(this, void 0, void 0, function* () {
const status = yield channel.unsubscribe();
if (this.channels.length === 0) {
this.disconnect();
}
return status;
});
}
removeAllChannels() {
return __awaiter$a(this, void 0, void 0, function* () {
const values_1 = yield Promise.all(this.channels.map((channel) => channel.unsubscribe()));
this.disconnect();
return values_1;
});
}
log(kind, msg, data) {
this.logger(kind, msg, data);
}
connectionState() {
switch (this.conn && this.conn.readyState) {
case SOCKET_STATES.connecting:
return CONNECTION_STATE.Connecting;
case SOCKET_STATES.open:
return CONNECTION_STATE.Open;
case SOCKET_STATES.closing:
return CONNECTION_STATE.Closing;
default:
return CONNECTION_STATE.Closed;
}
}
isConnected() {
return this.connectionState() === CONNECTION_STATE.Open;
}
channel(topic, params = { config: {} }) {
if (!this.isConnected()) {
this.connect();
}
const chan = new RealtimeChannel(`realtime:${topic}`, params, this);
this.channels.push(chan);
return chan;
}
push(data) {
const { topic, event, payload, ref } = data;
let callback = () => {
this.encode(data, (result) => {
var _a;
(_a = this.conn) === null || _a === void 0 ? void 0 : _a.send(result);
});
};
this.log("push", `${topic} ${event} (${ref})`, payload);
if (this.isConnected()) {
if (["broadcast", "presence", "postgres_changes"].includes(event)) {
const isThrottled = this._throttle(callback)();
if (isThrottled) {
return "rate limited";
}
} else {
callback();
}
} else {
this.sendBuffer.push(callback);
}
}
setAuth(token) {
this.accessToken = token;
this.channels.forEach((channel) => {
token && channel.updateJoinPayload({ access_token: token });
if (channel.joinedOnce && channel._isJoined()) {
channel._push(CHANNEL_EVENTS.access_token, { access_token: token });
}
});
}
_makeRef() {
let newRef = this.ref + 1;
if (newRef === this.ref) {
this.ref = 0;
} else {
this.ref = newRef;
}
return this.ref.toString();
}
_leaveOpenTopic(topic) {
let dupChannel = this.channels.find((c) => c.topic === topic && (c._isJoined() || c._isJoining()));
if (dupChannel) {
this.log("transport", `leaving duplicate topic "${topic}"`);
dupChannel.unsubscribe();
}
}
_remove(channel) {
this.channels = this.channels.filter((c) => c._joinRef() !== channel._joinRef());
}
_endPointURL() {
return this._appendParams(this.endPoint, Object.assign({}, this.params, { vsn: VSN }));
}
_onConnMessage(rawMessage) {
this.decode(rawMessage.data, (msg) => {
let { topic, event, payload, ref } = msg;
if (ref && ref === this.pendingHeartbeatRef || event === (payload === null || payload === void 0 ? void 0 : payload.type)) {
this.pendingHeartbeatRef = null;
}
this.log("receive", `${payload.status || ""} ${topic} ${event} ${ref && "(" + ref + ")" || ""}`, payload);
this.channels.filter((channel) => channel._isMember(topic)).forEach((channel) => channel._trigger(event, payload, ref));
this.stateChangeCallbacks.message.forEach((callback) => callback(msg));
});
}
_onConnOpen() {
this.log("transport", `connected to ${this._endPointURL()}`);
this._flushSendBuffer();
this.reconnectTimer.reset();
this.heartbeatTimer && clearInterval(this.heartbeatTimer);
this.heartbeatTimer = setInterval(() => this._sendHeartbeat(), this.heartbeatIntervalMs);
this.stateChangeCallbacks.open.forEach((callback) => callback());
}
_onConnClose(event) {
this.log("transport", "close", event);
this._triggerChanError();
this.heartbeatTimer && clearInterval(this.heartbeatTimer);
this.reconnectTimer.scheduleTimeout();
this.stateChangeCallbacks.close.forEach((callback) => callback(event));
}
_onConnError(error) {
this.log("transport", error.message);
this._triggerChanError();
this.stateChangeCallbacks.error.forEach((callback) => callback(error));
}
_triggerChanError() {
this.channels.forEach((channel) => channel._trigger(CHANNEL_EVENTS.error));
}
_appendParams(url, params) {
if (Object.keys(params).length === 0) {
return url;
}
const prefix = url.match(/\?/) ? "&" : "?";
const query = new URLSearchParams(params);
return `${url}${prefix}${query}`;
}
_flushSendBuffer() {
if (this.isConnected() && this.sendBuffer.length > 0) {
this.sendBuffer.forEach((callback) => callback());
this.sendBuffer = [];
}
}
_sendHeartbeat() {
var _a;
if (!this.isConnected()) {
return;
}
if (this.pendingHeartbeatRef) {
this.pendingHeartbeatRef = null;
this.log("transport", "heartbeat timeout. Attempting to re-establish connection");
(_a = this.conn) === null || _a === void 0 ? void 0 : _a.close(WS_CLOSE_NORMAL, "hearbeat timeout");
return;
}
this.pendingHeartbeatRef = this._makeRef();
this.push({
topic: "phoenix",
event: "heartbeat",
payload: {},
ref: this.pendingHeartbeatRef
});
this.setAuth(this.accessToken);
}
_throttle(callback, eventsPerSecondLimitMs = this.eventsPerSecondLimitMs) {
return () => {
if (this.inThrottle)
return true;
callback();
if (eventsPerSecondLimitMs > 0) {
this.inThrottle = true;
setTimeout(() => {
this.inThrottle = false;
}, eventsPerSecondLimitMs);
}
return false;
};
}
}
class StorageError extends Error {
constructor(message) {
super(message);
this.__isStorageError = true;
this.name = "StorageError";
}
}
function isStorageError(error) {
return typeof error === "object" && error !== null && "__isStorageError" in error;
}
class StorageApiError extends StorageError {
constructor(message, status) {
super(message);
this.name = "StorageApiError";
this.status = status;
}
toJSON() {
return {
name: this.name,
message: this.message,
status: this.status
};
}
}
class StorageUnknownError extends StorageError {
constructor(message, originalError) {
super(message);
this.name = "StorageUnknownError";
this.originalError = originalError;
}
}
var __awaiter$9 = globalThis && globalThis.__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());
});
};
const resolveFetch$2 = (customFetch) => {
let _fetch;
if (customFetch) {
_fetch = customFetch;
} else if (typeof fetch === "undefined") {
_fetch = (...args) => __awaiter$9(void 0, void 0, void 0, function* () {
return yield (yield Promise.resolve().then(function() {
return browserPonyfill;
})).fetch(...args);
});
} else {
_fetch = fetch;
}
return (...args) => _fetch(...args);
};
const resolveResponse = () => __awaiter$9(void 0, void 0, void 0, function* () {
if (typeof Response === "undefined") {
return (yield Promise.resolve().then(function() {
return browserPonyfill;
})).Response;
}
return Response;
});
var __awaiter$8 = globalThis && globalThis.__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());
});
};
const _getErrorMessage$1 = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err);
const handleError$1 = (error, reject) => __awaiter$8(void 0, void 0, void 0, function* () {
const Res = yield resolveResponse();
if (error instanceof Res) {
error.json().then((err) => {
reject(new StorageApiError(_getErrorMessage$1(err), error.status || 500));
}).catch((err) => {
reject(new StorageUnknownError(_getErrorMessage$1(err), err));
});
} else {
reject(new StorageUnknownError(_getErrorMessage$1(error), error));
}
});
const _getRequestParams$1 = (method, options, parameters, body) => {
const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} };
if (method === "GET") {
return params;
}
params.headers = Object.assign({ "Content-Type": "application/json" }, options === null || options === void 0 ? void 0 : options.headers);
params.body = JSON.stringify(body);
return Object.assign(Object.assign({}, params), parameters);
};
function _handleRequest$1(fetcher, method, url, options, parameters, body) {
return __awaiter$8(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
fetcher(url, _getRequestParams$1(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$1(error, reject));
});
});
}
function get(fetcher, url, options, parameters) {
return __awaiter$8(this, void 0, void 0, function* () {
return _handleRequest$1(fetcher, "GET", url, options, parameters);
});
}
function post(fetcher, url, body, options, parameters) {
return __awaiter$8(this, void 0, void 0, function* () {
return _handleRequest$1(fetcher, "POST", url, options, parameters, body);
});
}
function put(fetcher, url, body, options, parameters) {
return __awaiter$8(this, void 0, void 0, function* () {
return _handleRequest$1(fetcher, "PUT", url, options, parameters, body);
});
}
function remove(fetcher, url, body, options, parameters) {
return __awaiter$8(this, void 0, void 0, function* () {
return _handleRequest$1(fetcher, "DELETE", url, options, parameters, body);
});
}
var __awaiter$7 = globalThis && globalThis.__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());
});
};
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, fetch2) {
this.url = url;
this.headers = headers;
this.bucketId = bucketId;
this.fetch = resolveFetch$2(fetch2);
}
uploadOrUpdate(method, path, fileBody, fileOptions) {
return __awaiter$7(this, void 0, void 0, function* () {
try {
let body;
const options = Object.assign(Object.assign({}, DEFAULT_FILE_OPTIONS), fileOptions);
const headers = Object.assign(Object.assign({}, this.headers), method === "POST" && { "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 cleanPath = this._removeEmptyFolders(path);
const _path = this._getFinalPath(cleanPath);
const res = yield this.fetch(`${this.url}/object/${_path}`, Object.assign({ method, body, headers }, (options === null || options === void 0 ? void 0 : options.duplex) ? { duplex: options.duplex } : {}));
if (res.ok) {
return {
data: { path: cleanPath },
error: null
};
} else {
const error = yield res.json();
return { data: null, error };
}
} catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
upload(path, fileBody, fileOptions) {
return __awaiter$7(this, void 0, void 0, function* () {
return this.uploadOrUpdate("POST", path, fileBody, fileOptions);
});
}
uploadToSignedUrl(path, token, fileBody, fileOptions) {
return __awaiter$7(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 res = yield this.fetch(url.toString(), {
method: "PUT",
body,
headers
});
if (res.ok) {
return {
data: { path: cleanPath },
error: null
};
} else {
const error = yield res.json();
return { data: null, error };
}
} catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
createSignedUploadUrl(path) {
return __awaiter$7(this, void 0, void 0, function* () {
try {
let _path = this._getFinalPath(path);
const data = yield post(this.fetch, `${this.url}/object/upload/sign/${_path}`, {}, { headers: this.headers });
const url = new URL(this.url + data.url);
const token = url.searchParams.get("token");
if (!token) {
throw new StorageError("No token returned by API");
}
return { data: { signedUrl: url.toString(), path, token }, error: null };
} catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
update(path, fileBody, fileOptions) {
return __awaiter$7(this, void 0, void 0, function* () {
return this.uploadOrUpdate("PUT", path, fileBody, fileOptions);
});
}
move(fromPath, toPath) {
return __awaiter$7(this, void 0, void 0, function* () {
try {
const data = yield post(this.fetch, `${this.url}/object/move`, { bucketId: this.bucketId, sourceKey: fromPath, destinationKey: toPath }, { headers: this.headers });
return { data, error: null };
} catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
copy(fromPath, toPath) {
return __awaiter$7(this, void 0, void 0, function* () {
try {
const data = yield post(this.fetch, `${this.url}/object/copy`, { bucketId: this.bucketId, sourceKey: fromPath, destinationKey: toPath }, { headers: this.headers });
return { data: { path: data.Key }, error: null };
} catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
createSignedUrl(path, expiresIn, options) {
return __awaiter$7(this, void 0, void 0, function* () {
try {
let _path = this._getFinalPath(path);
let data = yield 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 (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
createSignedUrls(paths, expiresIn, options) {
return __awaiter$7(this, void 0, void 0, function* () {
try {
const data = yield 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 (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
download(path, options) {
return __awaiter$7(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 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 (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
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}`) }
};
}
remove(paths) {
return __awaiter$7(this, void 0, void 0, function* () {
try {
const data = yield remove(this.fetch, `${this.url}/object/${this.bucketId}`, { prefixes: paths }, { headers: this.headers });
return { data, error: null };
} catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
list(path, options, parameters) {
return __awaiter$7(this, void 0, void 0, function* () {
try {
const body = Object.assign(Object.assign(Object.assign({}, DEFAULT_SEARCH_OPTIONS), options), { prefix: path || "" });
const data = yield post(this.fetch, `${this.url}/object/list/${this.bucketId}`, body, { headers: this.headers }, parameters);
return { data, error: null };
} catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
_getFinalPath(path) {
return `${this.bucketId}/${path}`;
}
_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("&");
}
}
const version$2 = "2.5.1";
const DEFAULT_HEADERS$2 = { "X-Client-Info": `storage-js/${version$2}` };
var __awaiter$6 = globalThis && globalThis.__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());
});
};
class StorageBucketApi {
constructor(url, headers = {}, fetch2) {
this.url = url;
this.headers = Object.assign(Object.assign({}, DEFAULT_HEADERS$2), headers);
this.fetch = resolveFetch$2(fetch2);
}
listBuckets() {
return __awaiter$6(this, void 0, void 0, function* () {
try {
const data = yield get(this.fetch, `${this.url}/bucket`, { headers: this.headers });
return { data, error: null };
} catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
getBucket(id) {
return __awaiter$6(this, void 0, void 0, function* () {
try {
const data = yield get(this.fetch, `${this.url}/bucket/${id}`, { headers: this.headers });
return { data, error: null };
} catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
createBucket(id, options = {
public: false
}) {
return __awaiter$6(this, void 0, void 0, function* () {
try {
const data = yield post(this.fetch, `${this.url}/bucket`, {
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 (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
updateBucket(id, options) {
return __awaiter$6(this, void 0, void 0, function* () {
try {
const data = yield 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 (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
emptyBucket(id) {
return __awaiter$6(this, void 0, void 0, function* () {
try {
const data = yield post(this.fetch, `${this.url}/bucket/${id}/empty`, {}, { headers: this.headers });
return { data, error: null };
} catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
deleteBucket(id) {
return __awaiter$6(this, void 0, void 0, function* () {
try {
const data = yield remove(this.fetch, `${this.url}/bucket/${id}`, {}, { headers: this.headers });
return { data, error: null };
} catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
}
class StorageClient extends StorageBucketApi {
constructor(url, headers = {}, fetch2) {
super(url, headers, fetch2);
}
from(id) {
return new StorageFileApi(this.url, this.headers, id, this.fetch);
}
}
const version$1 = "2.20.0";
const DEFAULT_HEADERS$1 = { "X-Client-Info": `supabase-js/${version$1}` };
var __awaiter$5 = globalThis && globalThis.__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());
});
};
const resolveFetch$1 = (customFetch) => {
let _fetch;
if (customFetch) {
_fetch = customFetch;
} else if (typeof fetch === "undefined") {
_fetch = crossFetch;
} else {
_fetch = fetch;
}
return (...args) => _fetch(...args);
};
const resolveHeadersConstructor = () => {
if (typeof Headers === "undefined") {
return browserPonyfill$1.exports.Headers;
}
return Headers;
};
const fetchWithAuth = (supabaseKey, getAccessToken, customFetch) => {
const fetch2 = resolveFetch$1(customFetch);
const HeadersConstructor = resolveHeadersConstructor();
return (input, init) => __awaiter$5(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 fetch2(input, Object.assign(Object.assign({}, init), { headers }));
});
};
function stripTrailingSlash(url) {
return url.replace(/\/$/, "");
}
function applySettingDefaults(options, defaults) {
const { db: dbOptions, auth: authOptions, realtime: realtimeOptions, global: globalOptions } = options;
const { db: DEFAULT_DB_OPTIONS2, auth: DEFAULT_AUTH_OPTIONS2, realtime: DEFAULT_REALTIME_OPTIONS2, global: DEFAULT_GLOBAL_OPTIONS2 } = defaults;
return {
db: Object.assign(Object.assign({}, DEFAULT_DB_OPTIONS2), dbOptions),
auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS2), authOptions),
realtime: Object.assign(Object.assign({}, DEFAULT_REALTIME_OPTIONS2), realtimeOptions),
global: Object.assign(Object.assign({}, DEFAULT_GLOBAL_OPTIONS2), globalOptions)
};
}
var __awaiter$4 = globalThis && globalThis.__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());
});
};
function expiresAt(expiresIn) {
const timeNow = Math.round(Date.now() / 1e3);
return timeNow + expiresIn;
}
function uuid() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
return v.toString(16);
});
}
const isBrowser = () => typeof document !== "undefined";
const localStorageWriteTests = {
tested: false,
writable: false
};
const supportsLocalStorage = () => {
if (!isBrowser()) {
return false;
}
try {
if (typeof globalThis.localStorage !== "object") {
return false;
}
} catch (e) {
return false;
}
if (localStorageWriteTests.tested) {
return localStorageWriteTests.writable;
}
const randomKey = `lswt-${Math.random()}${Math.random()}`;
try {
globalThis.localStorage.setItem(randomKey, randomKey);
globalThis.localStorage.removeItem(randomKey);
localStorageWriteTests.tested = true;
localStorageWriteTests.writable = true;
} catch (e) {
localStorageWriteTests.tested = true;
localStorageWriteTests.writable = false;
}
return localStorageWriteTests.writable;
};
function getParameterByName(name2, url) {
var _a;
if (!url)
url = ((_a = window === null || window === void 0 ? void 0 : window.location) === null || _a === void 0 ? void 0 : _a.href) || "";
name2 = name2.replace(/[\[\]]/g, "\\$&");
const regex = new RegExp("[?&#]" + name2 + "(=([^&#]*)|&|#|$)"), results = regex.exec(url);
if (!results)
return null;
if (!results[2])
return "";
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
const resolveFetch = (customFetch) => {
let _fetch;
if (customFetch) {
_fetch = customFetch;
} else if (typeof fetch === "undefined") {
_fetch = (...args) => __awaiter$4(void 0, void 0, void 0, function* () {
return yield (yield Promise.resolve().then(function() {
return browserPonyfill;
})).fetch(...args);
});
} else {
_fetch = fetch;
}
return (...args) => _fetch(...args);
};
const looksLikeFetchResponse = (maybeResponse) => {
return typeof maybeResponse === "object" && maybeResponse !== null && "status" in maybeResponse && "ok" in maybeResponse && "json" in maybeResponse && typeof maybeResponse.json === "function";
};
const setItemAsync = (storage, key, data) => __awaiter$4(void 0, void 0, void 0, function* () {
yield storage.setItem(key, JSON.stringify(data));
});
const getItemAsync = (storage, key) => __awaiter$4(void 0, void 0, void 0, function* () {
const value = yield storage.getItem(key);
if (!value) {
return null;
}
try {
return JSON.parse(value);
} catch (_a) {
return value;
}
});
const removeItemAsync = (storage, key) => __awaiter$4(void 0, void 0, void 0, function* () {
yield storage.removeItem(key);
});
function decodeBase64URL(value) {
const key = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
let base64 = "";
let chr1, chr2, chr3;
let enc1, enc2, enc3, enc4;
let i = 0;
value = value.replace("-", "+").replace("_", "/");
while (i < value.length) {
enc1 = key.indexOf(value.charAt(i++));
enc2 = key.indexOf(value.charAt(i++));
enc3 = key.indexOf(value.charAt(i++));
enc4 = key.indexOf(value.charAt(i++));
chr1 = enc1 << 2 | enc2 >> 4;
chr2 = (enc2 & 15) << 4 | enc3 >> 2;
chr3 = (enc3 & 3) << 6 | enc4;
base64 = base64 + String.fromCharCode(chr1);
if (enc3 != 64 && chr2 != 0) {
base64 = base64 + String.fromCharCode(chr2);
}
if (enc4 != 64 && chr3 != 0) {
base64 = base64 + String.fromCharCode(chr3);
}
}
return base64;
}
class Deferred {
constructor() {
this.promise = new Deferred.promiseConstructor((res, rej) => {
this.resolve = res;
this.reject = rej;
});
}
}
Deferred.promiseConstructor = Promise;
function decodeJWTPayload(token) {
const base64UrlRegex = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i;
const parts = token.split(".");
if (parts.length !== 3) {
throw new Error("JWT is not valid: not a JWT structure");
}
if (!base64UrlRegex.test(parts[1])) {
throw new Error("JWT is not valid: payload is not in base64url format");
}
const base64Url = parts[1];
return JSON.parse(decodeBase64URL(base64Url));
}
function sleep(time) {
return new Promise((accept) => {
setTimeout(() => accept(null), time);
});
}
function retryable(fn, isRetryable) {
const promise = new Promise((accept, reject) => {
(() => __awaiter$4(this, void 0, void 0, function* () {
for (let attempt = 0; attempt < Infinity; attempt++) {
try {
const result = yield fn(attempt);
if (!isRetryable(attempt, null, result)) {
accept(result);
return;
}
} catch (e) {
if (!isRetryable(attempt, e)) {
reject(e);
return;
}
}
}
}))();
});
return promise;
}
function dec2hex(dec) {
return ("0" + dec.toString(16)).substr(-2);
}
function generatePKCEVerifier() {
const verifierLength = 56;
const array = new Uint32Array(verifierLength);
if (typeof crypto === "undefined") {
throw new Error("PKCE is not supported on devices without WebCrypto API support, please add polyfills");
}
crypto.getRandomValues(array);
return Array.from(array, dec2hex).join("");
}
function sha256(randomString) {
return __awaiter$4(this, void 0, void 0, function* () {
const encoder = new TextEncoder();
const encodedData = encoder.encode(randomString);
if (typeof crypto === "undefined") {
throw new Error("PKCE is not supported on devices without WebCrypto API support, please add polyfills");
}
const hash = yield crypto.subtle.digest("SHA-256", encodedData);
const bytes = new Uint8Array(hash);
return Array.from(bytes).map((c) => String.fromCharCode(c)).join("");
});
}
function base64urlencode(str) {
return btoa(str).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function generatePKCEChallenge(verifier) {
return __awaiter$4(this, void 0, void 0, function* () {
const hashed = yield sha256(verifier);
return base64urlencode(hashed);
});
}
class AuthError extends Error {
constructor(message, status) {
super(message);
this.__isAuthError = true;
this.name = "AuthError";
this.status = status;
}
}
function isAuthError(error) {
return typeof error === "object" && error !== null && "__isAuthError" in error;
}
class AuthApiError extends AuthError {
constructor(message, status) {
super(message, status);
this.name = "AuthApiError";
this.status = status;
}
toJSON() {
return {
name: this.name,
message: this.message,
status: this.status
};
}
}
function isAuthApiError(error) {
return isAuthError(error) && error.name === "AuthApiError";
}
class AuthUnknownError extends AuthError {
constructor(message, originalError) {
super(message);
this.name = "AuthUnknownError";
this.originalError = originalError;
}
}
class CustomAuthError extends AuthError {
constructor(message, name2, status) {
super(message);
this.name = name2;
this.status = status;
}
toJSON() {
return {
name: this.name,
message: this.message,
status: this.status
};
}
}
class AuthSessionMissingError extends CustomAuthError {
constructor() {
super("Auth session missing!", "AuthSessionMissingError", 400);
}
}
class AuthInvalidCredentialsError extends CustomAuthError {
constructor(message) {
super(message, "AuthInvalidCredentialsError", 400);
}
}
class AuthImplicitGrantRedirectError extends CustomAuthError {
constructor(message, details = null) {
super(message, "AuthImplicitGrantRedirectError", 500);
this.details = null;
this.details = details;
}
toJSON() {
return {
name: this.name,
message: this.message,
status: this.status,
details: this.details
};
}
}
class AuthPKCEGrantCodeExchangeError extends CustomAuthError {
constructor(message, details = null) {
super(message, "AuthPKCEGrantCodeExchangeError", 500);
this.details = null;
this.details = details;
}
toJSON() {
return {
name: this.name,
message: this.message,
status: this.status,
details: this.details
};
}
}
class AuthRetryableFetchError extends CustomAuthError {
constructor(message, status) {
super(message, "AuthRetryableFetchError", status);
}
}
var __awaiter$3 = globalThis && globalThis.__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());
});
};
var __rest$1 = globalThis && globalThis.__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;
};
const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err);
const handleError = (error, reject) => __awaiter$3(void 0, void 0, void 0, function* () {
const NETWORK_ERROR_CODES = [502, 503, 504];
if (!looksLikeFetchResponse(error)) {
reject(new AuthRetryableFetchError(_getErrorMessage(error), 0));
} else if (NETWORK_ERROR_CODES.includes(error.status)) {
reject(new AuthRetryableFetchError(_getErrorMessage(error), error.status));
} else {
error.json().then((err) => {
reject(new AuthApiError(_getErrorMessage(err), error.status || 500));
}).catch((e) => {
reject(new AuthUnknownError(_getErrorMessage(e), e));
});
}
});
const _getRequestParams = (method, options, parameters, body) => {
const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} };
if (method === "GET") {
return params;
}
params.headers = Object.assign({ "Content-Type": "application/json;charset=UTF-8" }, options === null || options === void 0 ? void 0 : options.headers);
params.body = JSON.stringify(body);
return Object.assign(Object.assign({}, params), parameters);
};
function _request(fetcher, method, url, options) {
var _a;
return __awaiter$3(this, void 0, void 0, function* () {
const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers);
if (options === null || options === void 0 ? void 0 : options.jwt) {
headers["Authorization"] = `Bearer ${options.jwt}`;
}
const qs = (_a = options === null || options === void 0 ? void 0 : options.query) !== null && _a !== void 0 ? _a : {};
if (options === null || options === void 0 ? void 0 : options.redirectTo) {
qs["redirect_to"] = options.redirectTo;
}
const queryString = Object.keys(qs).length ? "?" + new URLSearchParams(qs).toString() : "";
const data = yield _handleRequest(fetcher, method, url + queryString, { headers, noResolveJson: options === null || options === void 0 ? void 0 : options.noResolveJson }, {}, options === null || options === void 0 ? void 0 : options.body);
return (options === null || options === void 0 ? void 0 : options.xform) ? options === null || options === void 0 ? void 0 : options.xform(data) : { data: Object.assign({}, data), error: null };
});
}
function _handleRequest(fetcher, method, url, options, parameters, body) {
return __awaiter$3(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));
});
});
}
function _sessionResponse(data) {
var _a;
let session = null;
if (hasSession(data)) {
session = Object.assign({}, data);
session.expires_at = expiresAt(data.expires_in);
}
const user = (_a = data.user) !== null && _a !== void 0 ? _a : data;
return { data: { session, user }, error: null };
}
function _userResponse(data) {
var _a;
const user = (_a = data.user) !== null && _a !== void 0 ? _a : data;
return { data: { user }, error: null };
}
function _ssoResponse(data) {
return { data, error: null };
}
function _generateLinkResponse(data) {
const { action_link, email_otp, hashed_token, redirect_to, verification_type } = data, rest = __rest$1(data, ["action_link", "email_otp", "hashed_token", "redirect_to", "verification_type"]);
const properties = {
action_link,
email_otp,
hashed_token,
redirect_to,
verification_type
};
const user = Object.assign({}, rest);
return {
data: {
properties,
user
},
error: null
};
}
function _noResolveJsonResponse(data) {
return data;
}
function hasSession(data) {
return data.access_token && data.refresh_token && data.expires_in;
}
var __awaiter$2 = globalThis && globalThis.__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());
});
};
var __rest = globalThis && globalThis.__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;
};
class GoTrueAdminApi {
constructor({ url = "", headers = {}, fetch: fetch2 }) {
this.url = url;
this.headers = headers;
this.fetch = resolveFetch(fetch2);
this.mfa = {
listFactors: this._listFactors.bind(this),
deleteFactor: this._deleteFactor.bind(this)
};
}
signOut(jwt) {
return __awaiter$2(this, void 0, void 0, function* () {
try {
yield _request(this.fetch, "POST", `${this.url}/logout`, {
headers: this.headers,
jwt,
noResolveJson: true
});
return { data: null, error: null };
} catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
});
}
inviteUserByEmail(email, options = {}) {
return __awaiter$2(this, void 0, void 0, function* () {
try {
return yield _request(this.fetch, "POST", `${this.url}/invite`, {
body: { email, data: options.data },
headers: this.headers,
redirectTo: options.redirectTo,
xform: _userResponse
});
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
});
}
generateLink(params) {
return __awaiter$2(this, void 0, void 0, function* () {
try {
const { options } = params, rest = __rest(params, ["options"]);
const body = Object.assign(Object.assign({}, rest), options);
if ("newEmail" in rest) {
body.new_email = rest === null || rest === void 0 ? void 0 : rest.newEmail;
delete body["newEmail"];
}
return yield _request(this.fetch, "POST", `${this.url}/admin/generate_link`, {
body,
headers: this.headers,
xform: _generateLinkResponse,
redirectTo: options === null || options === void 0 ? void 0 : options.redirectTo
});
} catch (error) {
if (isAuthError(error)) {
return {
data: {
properties: null,
user: null
},
error
};
}
throw error;
}
});
}
createUser(attributes) {
return __awaiter$2(this, void 0, void 0, function* () {
try {
return yield _request(this.fetch, "POST", `${this.url}/admin/users`, {
body: attributes,
headers: this.headers,
xform: _userResponse
});
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
});
}
listUsers(params) {
var _a, _b, _c, _d, _e, _f, _g;
return __awaiter$2(this, void 0, void 0, function* () {
try {
const pagination = { nextPage: null, lastPage: 0, total: 0 };
const response = yield _request(this.fetch, "GET", `${this.url}/admin/users`, {
headers: this.headers,
noResolveJson: true,
query: {
page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : "",
per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ""
},
xform: _noResolveJsonResponse
});
if (response.error)
throw response.error;
const users = yield response.json();
const total = (_e = response.headers.get("x-total-count")) !== null && _e !== void 0 ? _e : 0;
const links = (_g = (_f = response.headers.get("link")) === null || _f === void 0 ? void 0 : _f.split(",")) !== null && _g !== void 0 ? _g : [];
if (links.length > 0) {
links.forEach((link) => {
const page = parseInt(link.split(";")[0].split("=")[1].substring(0, 1));
const rel = JSON.parse(link.split(";")[1].split("=")[1]);
pagination[`${rel}Page`] = page;
});
pagination.total = parseInt(total);
}
return { data: Object.assign(Object.assign({}, users), pagination), error: null };
} catch (error) {
if (isAuthError(error)) {
return { data: { users: [] }, error };
}
throw error;
}
});
}
getUserById(uid) {
return __awaiter$2(this, void 0, void 0, function* () {
try {
return yield _request(this.fetch, "GET", `${this.url}/admin/users/${uid}`, {
headers: this.headers,
xform: _userResponse
});
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
});
}
updateUserById(uid, attributes) {
return __awaiter$2(this, void 0, void 0, function* () {
try {
return yield _request(this.fetch, "PUT", `${this.url}/admin/users/${uid}`, {
body: attributes,
headers: this.headers,
xform: _userResponse
});
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
});
}
deleteUser(id, shouldSoftDelete = false) {
return __awaiter$2(this, void 0, void 0, function* () {
try {
return yield _request(this.fetch, "DELETE", `${this.url}/admin/users/${id}`, {
headers: this.headers,
body: {
should_soft_delete: shouldSoftDelete
},
xform: _userResponse
});
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
});
}
_listFactors(params) {
return __awaiter$2(this, void 0, void 0, function* () {
try {
const { data, error } = yield _request(this.fetch, "GET", `${this.url}/admin/users/${params.userId}/factors`, {
headers: this.headers,
xform: (factors) => {
return { data: { factors }, error: null };
}
});
return { data, error };
} catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
});
}
_deleteFactor(params) {
return __awaiter$2(this, void 0, void 0, function* () {
try {
const data = yield _request(this.fetch, "DELETE", `${this.url}/admin/users/${params.userId}/factors/${params.id}`, {
headers: this.headers
});
return { data, error: null };
} catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
});
}
}
const version = "2.22.1";
const GOTRUE_URL = "http://localhost:9999";
const STORAGE_KEY = "supabase.auth.token";
const DEFAULT_HEADERS = { "X-Client-Info": `gotrue-js/${version}` };
const EXPIRY_MARGIN = 10;
const localStorageAdapter = {
getItem: (key) => {
if (!supportsLocalStorage()) {
return null;
}
return globalThis.localStorage.getItem(key);
},
setItem: (key, value) => {
if (!supportsLocalStorage()) {
return;
}
globalThis.localStorage.setItem(key, value);
},
removeItem: (key) => {
if (!supportsLocalStorage()) {
return;
}
globalThis.localStorage.removeItem(key);
}
};
function polyfillGlobalThis() {
if (typeof globalThis === "object")
return;
try {
Object.defineProperty(Object.prototype, "__magic__", {
get: function() {
return this;
},
configurable: true
});
__magic__.globalThis = __magic__;
delete Object.prototype.__magic__;
} catch (e) {
if (typeof self !== "undefined") {
self.globalThis = self;
}
}
}
var __awaiter$1 = globalThis && globalThis.__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());
});
};
polyfillGlobalThis();
const DEFAULT_OPTIONS = {
url: GOTRUE_URL,
storageKey: STORAGE_KEY,
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true,
headers: DEFAULT_HEADERS,
flowType: "implicit"
};
const AUTO_REFRESH_TICK_DURATION = 10 * 1e3;
const AUTO_REFRESH_TICK_THRESHOLD = 3;
class GoTrueClient {
constructor(options) {
var _a;
this.stateChangeEmitters = /* @__PURE__ */ new Map();
this.autoRefreshTicker = null;
this.visibilityChangedCallback = null;
this.refreshingDeferred = null;
this.initializePromise = null;
this.detectSessionInUrl = true;
this.broadcastChannel = null;
const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options);
this.inMemorySession = null;
this.storageKey = settings.storageKey;
this.autoRefreshToken = settings.autoRefreshToken;
this.persistSession = settings.persistSession;
this.storage = settings.storage || localStorageAdapter;
this.admin = new GoTrueAdminApi({
url: settings.url,
headers: settings.headers,
fetch: settings.fetch
});
this.url = settings.url;
this.headers = settings.headers;
this.fetch = resolveFetch(settings.fetch);
this.detectSessionInUrl = settings.detectSessionInUrl;
this.flowType = settings.flowType;
this.mfa = {
verify: this._verify.bind(this),
enroll: this._enroll.bind(this),
unenroll: this._unenroll.bind(this),
challenge: this._challenge.bind(this),
listFactors: this._listFactors.bind(this),
challengeAndVerify: this._challengeAndVerify.bind(this),
getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this)
};
if (isBrowser() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) {
try {
this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey);
} catch (e) {
console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available", e);
}
(_a = this.broadcastChannel) === null || _a === void 0 ? void 0 : _a.addEventListener("message", (event) => {
this._notifyAllSubscribers(event.data.event, event.data.session, false);
});
}
this.initialize();
}
initialize() {
if (!this.initializePromise) {
this.initializePromise = this._initialize();
}
return this.initializePromise;
}
_initialize() {
return __awaiter$1(this, void 0, void 0, function* () {
if (this.initializePromise) {
return this.initializePromise;
}
try {
const isPKCEFlow = yield this._isPKCEFlow();
if (this.detectSessionInUrl && this._isImplicitGrantFlow() || isPKCEFlow) {
const { data, error } = yield this._getSessionFromUrl(isPKCEFlow);
if (error) {
yield this._removeSession();
return { error };
}
const { session, redirectType } = data;
yield this._saveSession(session);
setTimeout(() => {
if (redirectType === "recovery") {
this._notifyAllSubscribers("PASSWORD_RECOVERY", session);
} else {
this._notifyAllSubscribers("SIGNED_IN", session);
}
}, 0);
return { error: null };
}
yield this._recoverAndRefresh();
return { error: null };
} catch (error) {
if (isAuthError(error)) {
return { error };
}
return {
error: new AuthUnknownError("Unexpected error during initialization", error)
};
} finally {
yield this._handleVisibilityChange();
}
});
}
signUp(credentials) {
var _a, _b, _c;
return __awaiter$1(this, void 0, void 0, function* () {
try {
yield this._removeSession();
let res;
if ("email" in credentials) {
const { email, password, options } = credentials;
res = yield _request(this.fetch, "POST", `${this.url}/signup`, {
headers: this.headers,
redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo,
body: {
email,
password,
data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {},
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }
},
xform: _sessionResponse
});
} else if ("phone" in credentials) {
const { phone, password, options } = credentials;
res = yield _request(this.fetch, "POST", `${this.url}/signup`, {
headers: this.headers,
body: {
phone,
password,
data: (_b = options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : {},
channel: (_c = options === null || options === void 0 ? void 0 : options.channel) !== null && _c !== void 0 ? _c : "sms",
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }
},
xform: _sessionResponse
});
} else {
throw new AuthInvalidCredentialsError("You must provide either an email or phone number and a password");
}
const { data, error } = res;
if (error || !data) {
return { data: { user: null, session: null }, error };
}
const session = data.session;
const user = data.user;
if (data.session) {
yield this._saveSession(data.session);
this._notifyAllSubscribers("SIGNED_IN", session);
}
return { data: { user, session }, error: null };
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error };
}
throw error;
}
});
}
signInWithPassword(credentials) {
return __awaiter$1(this, void 0, void 0, function* () {
try {
yield this._removeSession();
let res;
if ("email" in credentials) {
const { email, password, options } = credentials;
res = yield _request(this.fetch, "POST", `${this.url}/token?grant_type=password`, {
headers: this.headers,
body: {
email,
password,
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }
},
xform: _sessionResponse
});
} else if ("phone" in credentials) {
const { phone, password, options } = credentials;
res = yield _request(this.fetch, "POST", `${this.url}/token?grant_type=password`, {
headers: this.headers,
body: {
phone,
password,
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }
},
xform: _sessionResponse
});
} else {
throw new AuthInvalidCredentialsError("You must provide either an email or phone number and a password");
}
const { data, error } = res;
if (error || !data)
return { data: { user: null, session: null }, error };
if (data.session) {
yield this._saveSession(data.session);
this._notifyAllSubscribers("SIGNED_IN", data.session);
}
return { data, error };
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error };
}
throw error;
}
});
}
signInWithOAuth(credentials) {
var _a, _b, _c, _d;
return __awaiter$1(this, void 0, void 0, function* () {
yield this._removeSession();
return yield this._handleProviderSignIn(credentials.provider, {
redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo,
scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes,
queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams,
skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect
});
});
}
exchangeCodeForSession(authCode) {
return __awaiter$1(this, void 0, void 0, function* () {
const codeVerifier = yield getItemAsync(this.storage, `${this.storageKey}-code-verifier`);
const { data, error } = yield _request(this.fetch, "POST", `${this.url}/token?grant_type=pkce`, {
headers: this.headers,
body: {
auth_code: authCode,
code_verifier: codeVerifier
},
xform: _sessionResponse
});
yield removeItemAsync(this.storage, `${this.storageKey}-code-verifier`);
if (error || !data)
return { data: { user: null, session: null }, error };
if (data.session) {
yield this._saveSession(data.session);
this._notifyAllSubscribers("SIGNED_IN", data.session);
}
return { data, error };
});
}
signInWithIdToken(credentials) {
return __awaiter$1(this, void 0, void 0, function* () {
yield this._removeSession();
try {
const { options, provider, token, nonce } = credentials;
const res = yield _request(this.fetch, "POST", `${this.url}/token?grant_type=id_token`, {
headers: this.headers,
body: {
provider,
id_token: token,
nonce,
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }
},
xform: _sessionResponse
});
const { data, error } = res;
if (error || !data)
return { data: { user: null, session: null }, error };
if (data.session) {
yield this._saveSession(data.session);
this._notifyAllSubscribers("SIGNED_IN", data.session);
}
return { data, error };
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error };
}
throw error;
}
});
}
signInWithOtp(credentials) {
var _a, _b, _c, _d, _e;
return __awaiter$1(this, void 0, void 0, function* () {
try {
yield this._removeSession();
if ("email" in credentials) {
const { email, options } = credentials;
let codeChallenge = null;
if (this.flowType === "pkce") {
const codeVerifier = generatePKCEVerifier();
yield setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier);
codeChallenge = yield generatePKCEChallenge(codeVerifier);
}
const { error } = yield _request(this.fetch, "POST", `${this.url}/otp`, {
headers: this.headers,
body: {
email,
data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {},
create_user: (_b = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _b !== void 0 ? _b : true,
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
code_challenge: codeChallenge,
code_challenge_method: codeChallenge ? "s256" : null
},
redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo
});
return { data: { user: null, session: null }, error };
}
if ("phone" in credentials) {
const { phone, options } = credentials;
const { error } = yield _request(this.fetch, "POST", `${this.url}/otp`, {
headers: this.headers,
body: {
phone,
data: (_c = options === null || options === void 0 ? void 0 : options.data) !== null && _c !== void 0 ? _c : {},
create_user: (_d = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _d !== void 0 ? _d : true,
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
channel: (_e = options === null || options === void 0 ? void 0 : options.channel) !== null && _e !== void 0 ? _e : "sms"
}
});
return { data: { user: null, session: null }, error };
}
throw new AuthInvalidCredentialsError("You must provide either an email or phone number.");
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error };
}
throw error;
}
});
}
verifyOtp(params) {
var _a, _b;
return __awaiter$1(this, void 0, void 0, function* () {
try {
yield this._removeSession();
const { data, error } = yield _request(this.fetch, "POST", `${this.url}/verify`, {
headers: this.headers,
body: Object.assign(Object.assign({}, params), { gotrue_meta_security: { captcha_token: (_a = params.options) === null || _a === void 0 ? void 0 : _a.captchaToken } }),
redirectTo: (_b = params.options) === null || _b === void 0 ? void 0 : _b.redirectTo,
xform: _sessionResponse
});
if (error) {
throw error;
}
if (!data) {
throw new Error("An error occurred on token verification.");
}
const session = data.session;
const user = data.user;
if (session === null || session === void 0 ? void 0 : session.access_token) {
yield this._saveSession(session);
this._notifyAllSubscribers("SIGNED_IN", session);
}
return { data: { user, session }, error: null };
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error };
}
throw error;
}
});
}
signInWithSSO(params) {
var _a, _b, _c;
return __awaiter$1(this, void 0, void 0, function* () {
try {
yield this._removeSession();
return yield _request(this.fetch, "POST", `${this.url}/sso`, {
body: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, "providerId" in params ? { provider_id: params.providerId } : null), "domain" in params ? { domain: params.domain } : null), { redirect_to: (_b = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo) !== null && _b !== void 0 ? _b : void 0 }), ((_c = params === null || params === void 0 ? void 0 : params.options) === null || _c === void 0 ? void 0 : _c.captchaToken) ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } } : null), { skip_http_redirect: true }),
headers: this.headers,
xform: _ssoResponse
});
} catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
});
}
getSession() {
return __awaiter$1(this, void 0, void 0, function* () {
yield this.initializePromise;
let currentSession = null;
if (this.persistSession) {
const maybeSession = yield getItemAsync(this.storage, this.storageKey);
if (maybeSession !== null) {
if (this._isValidSession(maybeSession)) {
currentSession = maybeSession;
} else {
yield this._removeSession();
}
}
} else {
currentSession = this.inMemorySession;
}
if (!currentSession) {
return { data: { session: null }, error: null };
}
const hasExpired = currentSession.expires_at ? currentSession.expires_at <= Date.now() / 1e3 : false;
if (!hasExpired) {
return { data: { session: currentSession }, error: null };
}
const { session, error } = yield this._callRefreshToken(currentSession.refresh_token);
if (error) {
return { data: { session: null }, error };
}
return { data: { session }, error: null };
});
}
getUser(jwt) {
var _a, _b;
return __awaiter$1(this, void 0, void 0, function* () {
try {
if (!jwt) {
const { data, error } = yield this.getSession();
if (error) {
throw error;
}
jwt = (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : void 0;
}
return yield _request(this.fetch, "GET", `${this.url}/user`, {
headers: this.headers,
jwt,
xform: _userResponse
});
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
});
}
updateUser(attributes, options = {}) {
return __awaiter$1(this, void 0, void 0, function* () {
try {
const { data: sessionData, error: sessionError } = yield this.getSession();
if (sessionError) {
throw sessionError;
}
if (!sessionData.session) {
throw new AuthSessionMissingError();
}
const session = sessionData.session;
const { data, error: userError } = yield _request(this.fetch, "PUT", `${this.url}/user`, {
headers: this.headers,
redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo,
body: attributes,
jwt: session.access_token,
xform: _userResponse
});
if (userError)
throw userError;
session.user = data.user;
yield this._saveSession(session);
this._notifyAllSubscribers("USER_UPDATED", session);
return { data: { user: session.user }, error: null };
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
});
}
_decodeJWT(jwt) {
return decodeJWTPayload(jwt);
}
setSession(currentSession) {
return __awaiter$1(this, void 0, void 0, function* () {
try {
if (!currentSession.access_token || !currentSession.refresh_token) {
throw new AuthSessionMissingError();
}
const timeNow = Date.now() / 1e3;
let expiresAt2 = timeNow;
let hasExpired = true;
let session = null;
const payload = decodeJWTPayload(currentSession.access_token);
if (payload.exp) {
expiresAt2 = payload.exp;
hasExpired = expiresAt2 <= timeNow;
}
if (hasExpired) {
const { session: refreshedSession, error } = yield this._callRefreshToken(currentSession.refresh_token);
if (error) {
return { data: { user: null, session: null }, error };
}
if (!refreshedSession) {
return { data: { user: null, session: null }, error: null };
}
session = refreshedSession;
} else {
const { data, error } = yield this.getUser(currentSession.access_token);
if (error) {
throw error;
}
session = {
access_token: currentSession.access_token,
refresh_token: currentSession.refresh_token,
user: data.user,
token_type: "bearer",
expires_in: expiresAt2 - timeNow,
expires_at: expiresAt2
};
yield this._saveSession(session);
this._notifyAllSubscribers("SIGNED_IN", session);
}
return { data: { user: session.user, session }, error: null };
} catch (error) {
if (isAuthError(error)) {
return { data: { session: null, user: null }, error };
}
throw error;
}
});
}
refreshSession(currentSession) {
var _a;
return __awaiter$1(this, void 0, void 0, function* () {
try {
if (!currentSession) {
const { data, error: error2 } = yield this.getSession();
if (error2) {
throw error2;
}
currentSession = (_a = data.session) !== null && _a !== void 0 ? _a : void 0;
}
if (!(currentSession === null || currentSession === void 0 ? void 0 : currentSession.refresh_token)) {
throw new AuthSessionMissingError();
}
const { session, error } = yield this._callRefreshToken(currentSession.refresh_token);
if (error) {
return { data: { user: null, session: null }, error };
}
if (!session) {
return { data: { user: null, session: null }, error: null };
}
return { data: { user: session.user, session }, error: null };
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error };
}
throw error;
}
});
}
_getSessionFromUrl(isPKCEFlow) {
return __awaiter$1(this, void 0, void 0, function* () {
try {
if (!isBrowser())
throw new AuthImplicitGrantRedirectError("No browser detected.");
if (this.flowType === "implicit" && !this._isImplicitGrantFlow()) {
throw new AuthImplicitGrantRedirectError("Not a valid implicit grant flow url.");
} else if (this.flowType == "pkce" && !isPKCEFlow) {
throw new AuthPKCEGrantCodeExchangeError("Not a valid PKCE flow url.");
}
if (isPKCEFlow) {
const authCode = getParameterByName("code");
if (!authCode)
throw new AuthPKCEGrantCodeExchangeError("No code detected.");
const { data: data2, error: error2 } = yield this.exchangeCodeForSession(authCode);
if (error2)
throw error2;
if (!data2.session)
throw new AuthPKCEGrantCodeExchangeError("No session detected.");
return { data: { session: data2.session, redirectType: null }, error: null };
}
const error_description = getParameterByName("error_description");
if (error_description) {
const error_code = getParameterByName("error_code");
if (!error_code)
throw new AuthImplicitGrantRedirectError("No error_code detected.");
const error2 = getParameterByName("error");
if (!error2)
throw new AuthImplicitGrantRedirectError("No error detected.");
throw new AuthImplicitGrantRedirectError(error_description, { error: error2, code: error_code });
}
const provider_token = getParameterByName("provider_token");
const provider_refresh_token = getParameterByName("provider_refresh_token");
const access_token = getParameterByName("access_token");
if (!access_token)
throw new AuthImplicitGrantRedirectError("No access_token detected.");
const expires_in = getParameterByName("expires_in");
if (!expires_in)
throw new AuthImplicitGrantRedirectError("No expires_in detected.");
const refresh_token = getParameterByName("refresh_token");
if (!refresh_token)
throw new AuthImplicitGrantRedirectError("No refresh_token detected.");
const token_type = getParameterByName("token_type");
if (!token_type)
throw new AuthImplicitGrantRedirectError("No token_type detected.");
const timeNow = Math.round(Date.now() / 1e3);
const expires_at = timeNow + parseInt(expires_in);
const { data, error } = yield this.getUser(access_token);
if (error)
throw error;
const user = data.user;
const session = {
provider_token,
provider_refresh_token,
access_token,
expires_in: parseInt(expires_in),
expires_at,
refresh_token,
token_type,
user
};
const redirectType = getParameterByName("type");
window.location.hash = "";
return { data: { session, redirectType }, error: null };
} catch (error) {
if (isAuthError(error)) {
return { data: { session: null, redirectType: null }, error };
}
throw error;
}
});
}
_isImplicitGrantFlow() {
return isBrowser() && (Boolean(getParameterByName("access_token")) || Boolean(getParameterByName("error_description")));
}
_isPKCEFlow() {
return __awaiter$1(this, void 0, void 0, function* () {
const currentStorageContent = yield getItemAsync(this.storage, `${this.storageKey}-code-verifier`);
return isBrowser() && Boolean(getParameterByName("code")) && Boolean(currentStorageContent);
});
}
signOut() {
var _a;
return __awaiter$1(this, void 0, void 0, function* () {
const { data, error: sessionError } = yield this.getSession();
if (sessionError) {
return { error: sessionError };
}
const accessToken = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token;
if (accessToken) {
const { error } = yield this.admin.signOut(accessToken);
if (error) {
if (!(isAuthApiError(error) && (error.status === 404 || error.status === 401))) {
return { error };
}
}
}
yield this._removeSession();
this._notifyAllSubscribers("SIGNED_OUT", null);
return { error: null };
});
}
onAuthStateChange(callback) {
const id = uuid();
const subscription = {
id,
callback,
unsubscribe: () => {
this.stateChangeEmitters.delete(id);
}
};
this.stateChangeEmitters.set(id, subscription);
this.emitInitialSession(id);
return { data: { subscription } };
}
emitInitialSession(id) {
var _a, _b;
return __awaiter$1(this, void 0, void 0, function* () {
try {
const { data: { session }, error } = yield this.getSession();
if (error)
throw error;
(_a = this.stateChangeEmitters.get(id)) === null || _a === void 0 ? void 0 : _a.callback("INITIAL_SESSION", session);
} catch (err) {
(_b = this.stateChangeEmitters.get(id)) === null || _b === void 0 ? void 0 : _b.callback("INITIAL_SESSION", null);
console.error(err);
}
});
}
resetPasswordForEmail(email, options = {}) {
return __awaiter$1(this, void 0, void 0, function* () {
let codeChallenge = null;
if (this.flowType === "pkce") {
const codeVerifier = generatePKCEVerifier();
yield setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier);
codeChallenge = yield generatePKCEChallenge(codeVerifier);
}
try {
return yield _request(this.fetch, "POST", `${this.url}/recover`, {
body: {
email,
code_challenge: codeChallenge,
code_challenge_method: codeChallenge ? "s256" : null,
gotrue_meta_security: { captcha_token: options.captchaToken }
},
headers: this.headers,
redirectTo: options.redirectTo
});
} catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
});
}
_refreshAccessToken(refreshToken) {
return __awaiter$1(this, void 0, void 0, function* () {
try {
const startedAt = Date.now();
return yield retryable((attempt) => __awaiter$1(this, void 0, void 0, function* () {
yield sleep(attempt * 200);
return yield _request(this.fetch, "POST", `${this.url}/token?grant_type=refresh_token`, {
body: { refresh_token: refreshToken },
headers: this.headers,
xform: _sessionResponse
});
}), (attempt, _, result) => result && result.error && result.error instanceof AuthRetryableFetchError && Date.now() + (attempt + 1) * 200 - startedAt < AUTO_REFRESH_TICK_DURATION);
} catch (error) {
if (isAuthError(error)) {
return { data: { session: null, user: null }, error };
}
throw error;
}
});
}
_isValidSession(maybeSession) {
const isValidSession = typeof maybeSession === "object" && maybeSession !== null && "access_token" in maybeSession && "refresh_token" in maybeSession && "expires_at" in maybeSession;
return isValidSession;
}
_handleProviderSignIn(provider, options) {
return __awaiter$1(this, void 0, void 0, function* () {
const url = yield this._getUrlForProvider(provider, {
redirectTo: options.redirectTo,
scopes: options.scopes,
queryParams: options.queryParams
});
if (isBrowser() && !options.skipBrowserRedirect) {
window.location.assign(url);
}
return { data: { provider, url }, error: null };
});
}
_recoverAndRefresh() {
var _a;
return __awaiter$1(this, void 0, void 0, function* () {
try {
const currentSession = yield getItemAsync(this.storage, this.storageKey);
if (!this._isValidSession(currentSession)) {
if (currentSession !== null) {
yield this._removeSession();
}
return;
}
const timeNow = Math.round(Date.now() / 1e3);
if (((_a = currentSession.expires_at) !== null && _a !== void 0 ? _a : Infinity) < timeNow + EXPIRY_MARGIN) {
if (this.autoRefreshToken && currentSession.refresh_token) {
const { error } = yield this._callRefreshToken(currentSession.refresh_token);
if (error) {
console.log(error.message);
yield this._removeSession();
}
} else {
yield this._removeSession();
}
} else {
if (this.persistSession) {
yield this._saveSession(currentSession);
}
this._notifyAllSubscribers("SIGNED_IN", currentSession);
}
} catch (err) {
console.error(err);
return;
}
});
}
_callRefreshToken(refreshToken) {
var _a, _b;
return __awaiter$1(this, void 0, void 0, function* () {
if (this.refreshingDeferred) {
return this.refreshingDeferred.promise;
}
try {
this.refreshingDeferred = new Deferred();
if (!refreshToken) {
throw new AuthSessionMissingError();
}
const { data, error } = yield this._refreshAccessToken(refreshToken);
if (error)
throw error;
if (!data.session)
throw new AuthSessionMissingError();
yield this._saveSession(data.session);
this._notifyAllSubscribers("TOKEN_REFRESHED", data.session);
const result = { session: data.session, error: null };
this.refreshingDeferred.resolve(result);
return result;
} catch (error) {
if (isAuthError(error)) {
const result = { session: null, error };
(_a = this.refreshingDeferred) === null || _a === void 0 ? void 0 : _a.resolve(result);
return result;
}
(_b = this.refreshingDeferred) === null || _b === void 0 ? void 0 : _b.reject(error);
throw error;
} finally {
this.refreshingDeferred = null;
}
});
}
_notifyAllSubscribers(event, session, broadcast = true) {
if (this.broadcastChannel && broadcast) {
this.broadcastChannel.postMessage({ event, session });
}
this.stateChangeEmitters.forEach((x) => x.callback(event, session));
}
_saveSession(session) {
return __awaiter$1(this, void 0, void 0, function* () {
if (!this.persistSession) {
this.inMemorySession = session;
}
if (this.persistSession && session.expires_at) {
yield this._persistSession(session);
}
});
}
_persistSession(currentSession) {
return setItemAsync(this.storage, this.storageKey, currentSession);
}
_removeSession() {
return __awaiter$1(this, void 0, void 0, function* () {
if (this.persistSession) {
yield removeItemAsync(this.storage, this.storageKey);
} else {
this.inMemorySession = null;
}
});
}
_removeVisibilityChangedCallback() {
const callback = this.visibilityChangedCallback;
this.visibilityChangedCallback = null;
try {
if (callback && isBrowser() && (window === null || window === void 0 ? void 0 : window.removeEventListener)) {
window.removeEventListener("visibilitychange", callback);
}
} catch (e) {
console.error("removing visibilitychange callback failed", e);
}
}
_startAutoRefresh() {
return __awaiter$1(this, void 0, void 0, function* () {
yield this._stopAutoRefresh();
const ticker = setInterval(() => this._autoRefreshTokenTick(), AUTO_REFRESH_TICK_DURATION);
this.autoRefreshTicker = ticker;
if (ticker && typeof ticker === "object" && typeof ticker.unref === "function") {
ticker.unref();
} else if (typeof Deno !== "undefined" && typeof Deno.unrefTimer === "function") {
Deno.unrefTimer(ticker);
}
yield this._autoRefreshTokenTick();
});
}
_stopAutoRefresh() {
return __awaiter$1(this, void 0, void 0, function* () {
const ticker = this.autoRefreshTicker;
this.autoRefreshTicker = null;
if (ticker) {
clearInterval(ticker);
}
});
}
startAutoRefresh() {
return __awaiter$1(this, void 0, void 0, function* () {
this._removeVisibilityChangedCallback();
yield this._startAutoRefresh();
});
}
stopAutoRefresh() {
return __awaiter$1(this, void 0, void 0, function* () {
this._removeVisibilityChangedCallback();
yield this._stopAutoRefresh();
});
}
_autoRefreshTokenTick() {
return __awaiter$1(this, void 0, void 0, function* () {
const now = Date.now();
try {
const { data: { session } } = yield this.getSession();
if (!session || !session.refresh_token || !session.expires_at) {
return;
}
const expiresInTicks = Math.floor((session.expires_at * 1e3 - now) / AUTO_REFRESH_TICK_DURATION);
if (expiresInTicks < AUTO_REFRESH_TICK_THRESHOLD) {
yield this._callRefreshToken(session.refresh_token);
}
} catch (e) {
console.error("Auto refresh tick failed with error. This is likely a transient error.", e);
}
});
}
_handleVisibilityChange() {
return __awaiter$1(this, void 0, void 0, function* () {
if (!isBrowser() || !(window === null || window === void 0 ? void 0 : window.addEventListener)) {
if (this.autoRefreshToken) {
this.startAutoRefresh();
}
return false;
}
try {
this.visibilityChangedCallback = () => __awaiter$1(this, void 0, void 0, function* () {
return yield this._onVisibilityChanged(false);
});
window === null || window === void 0 ? void 0 : window.addEventListener("visibilitychange", this.visibilityChangedCallback);
yield this._onVisibilityChanged(true);
} catch (error) {
console.error("_handleVisibilityChange", error);
}
});
}
_onVisibilityChanged(isInitial) {
return __awaiter$1(this, void 0, void 0, function* () {
if (document.visibilityState === "visible") {
if (!isInitial) {
yield this.initializePromise;
yield this._recoverAndRefresh();
}
if (this.autoRefreshToken) {
this._startAutoRefresh();
}
} else if (document.visibilityState === "hidden") {
if (this.autoRefreshToken) {
this._stopAutoRefresh();
}
}
});
}
_getUrlForProvider(provider, options) {
return __awaiter$1(this, void 0, void 0, function* () {
const urlParams = [`provider=${encodeURIComponent(provider)}`];
if (options === null || options === void 0 ? void 0 : options.redirectTo) {
urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`);
}
if (options === null || options === void 0 ? void 0 : options.scopes) {
urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`);
}
if (this.flowType === "pkce") {
const codeVerifier = generatePKCEVerifier();
yield setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier);
const codeChallenge = yield generatePKCEChallenge(codeVerifier);
const flowParams = new URLSearchParams({
code_challenge: `${encodeURIComponent(codeChallenge)}`,
code_challenge_method: `${encodeURIComponent("s256")}`
});
urlParams.push(flowParams.toString());
}
if (options === null || options === void 0 ? void 0 : options.queryParams) {
const query = new URLSearchParams(options.queryParams);
urlParams.push(query.toString());
}
return `${this.url}/authorize?${urlParams.join("&")}`;
});
}
_unenroll(params) {
var _a;
return __awaiter$1(this, void 0, void 0, function* () {
try {
const { data: sessionData, error: sessionError } = yield this.getSession();
if (sessionError) {
return { data: null, error: sessionError };
}
return yield _request(this.fetch, "DELETE", `${this.url}/factors/${params.factorId}`, {
headers: this.headers,
jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token
});
} catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
});
}
_enroll(params) {
var _a, _b;
return __awaiter$1(this, void 0, void 0, function* () {
try {
const { data: sessionData, error: sessionError } = yield this.getSession();
if (sessionError) {
return { data: null, error: sessionError };
}
const { data, error } = yield _request(this.fetch, "POST", `${this.url}/factors`, {
body: {
friendly_name: params.friendlyName,
factor_type: params.factorType,
issuer: params.issuer
},
headers: this.headers,
jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token
});
if (error) {
return { data: null, error };
}
if ((_b = data === null || data === void 0 ? void 0 : data.totp) === null || _b === void 0 ? void 0 : _b.qr_code) {
data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}`;
}
return { data, error: null };
} catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
});
}
_verify(params) {
var _a;
return __awaiter$1(this, void 0, void 0, function* () {
try {
const { data: sessionData, error: sessionError } = yield this.getSession();
if (sessionError) {
return { data: null, error: sessionError };
}
const { data, error } = yield _request(this.fetch, "POST", `${this.url}/factors/${params.factorId}/verify`, {
body: { code: params.code, challenge_id: params.challengeId },
headers: this.headers,
jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token
});
if (error) {
return { data: null, error };
}
yield this._saveSession(Object.assign({ expires_at: Math.round(Date.now() / 1e3) + data.expires_in }, data));
this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED", data);
return { data, error };
} catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
});
}
_challenge(params) {
var _a;
return __awaiter$1(this, void 0, void 0, function* () {
try {
const { data: sessionData, error: sessionError } = yield this.getSession();
if (sessionError) {
return { data: null, error: sessionError };
}
return yield _request(this.fetch, "POST", `${this.url}/factors/${params.factorId}/challenge`, {
headers: this.headers,
jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token
});
} catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
});
}
_challengeAndVerify(params) {
return __awaiter$1(this, void 0, void 0, function* () {
const { data: challengeData, error: challengeError } = yield this._challenge({
factorId: params.factorId
});
if (challengeError) {
return { data: null, error: challengeError };
}
return yield this._verify({
factorId: params.factorId,
challengeId: challengeData.id,
code: params.code
});
});
}
_listFactors() {
return __awaiter$1(this, void 0, void 0, function* () {
const { data: { user }, error: userError } = yield this.getUser();
if (userError) {
return { data: null, error: userError };
}
const factors = (user === null || user === void 0 ? void 0 : user.factors) || [];
const totp = factors.filter((factor) => factor.factor_type === "totp" && factor.status === "verified");
return {
data: {
all: factors,
totp
},
error: null
};
});
}
_getAuthenticatorAssuranceLevel() {
var _a, _b;
return __awaiter$1(this, void 0, void 0, function* () {
const { data: { session }, error: sessionError } = yield this.getSession();
if (sessionError) {
return { data: null, error: sessionError };
}
if (!session) {
return {
data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] },
error: null
};
}
const payload = this._decodeJWT(session.access_token);
let currentLevel = null;
if (payload.aal) {
currentLevel = payload.aal;
}
let nextLevel = currentLevel;
const verifiedFactors = (_b = (_a = session.user.factors) === null || _a === void 0 ? void 0 : _a.filter((factor) => factor.status === "verified")) !== null && _b !== void 0 ? _b : [];
if (verifiedFactors.length > 0) {
nextLevel = "aal2";
}
const currentAuthenticationMethods = payload.amr || [];
return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null };
});
}
}
class SupabaseAuthClient extends GoTrueClient {
constructor(options) {
super(options);
}
}
var __awaiter = globalThis && globalThis.__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());
});
};
const DEFAULT_GLOBAL_OPTIONS = {
headers: DEFAULT_HEADERS$1
};
const DEFAULT_DB_OPTIONS = {
schema: "public"
};
const DEFAULT_AUTH_OPTIONS = {
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true,
flowType: "implicit"
};
const DEFAULT_REALTIME_OPTIONS = {};
class SupabaseClient {
constructor(supabaseUrl, supabaseKey, options) {
var _a, _b, _c, _d, _e, _f, _g, _h;
this.supabaseUrl = supabaseUrl;
this.supabaseKey = supabaseKey;
if (!supabaseUrl)
throw new Error("supabaseUrl is required.");
if (!supabaseKey)
throw new Error("supabaseKey is required.");
const _supabaseUrl = stripTrailingSlash(supabaseUrl);
this.realtimeUrl = `${_supabaseUrl}/realtime/v1`.replace(/^http/i, "ws");
this.authUrl = `${_supabaseUrl}/auth/v1`;
this.storageUrl = `${_supabaseUrl}/storage/v1`;
const isPlatform = _supabaseUrl.match(/(supabase\.co)|(supabase\.in)/);
if (isPlatform) {
const urlParts = _supabaseUrl.split(".");
this.functionsUrl = `${urlParts[0]}.functions.${urlParts[1]}.${urlParts[2]}`;
} else {
this.functionsUrl = `${_supabaseUrl}/functions/v1`;
}
const defaultStorageKey = `sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`;
const DEFAULTS = {
db: DEFAULT_DB_OPTIONS,
realtime: DEFAULT_REALTIME_OPTIONS,
auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS), { storageKey: defaultStorageKey }),
global: DEFAULT_GLOBAL_OPTIONS
};
const settings = applySettingDefaults(options !== null && options !== void 0 ? options : {}, DEFAULTS);
this.storageKey = (_b = (_a = settings.auth) === null || _a === void 0 ? void 0 : _a.storageKey) !== null && _b !== void 0 ? _b : "";
this.headers = (_d = (_c = settings.global) === null || _c === void 0 ? void 0 : _c.headers) !== null && _d !== void 0 ? _d : {};
this.auth = this._initSupabaseAuthClient((_e = settings.auth) !== null && _e !== void 0 ? _e : {}, this.headers, (_f = settings.global) === null || _f === void 0 ? void 0 : _f.fetch);
this.fetch = fetchWithAuth(supabaseKey, this._getAccessToken.bind(this), (_g = settings.global) === null || _g === void 0 ? void 0 : _g.fetch);
this.realtime = this._initRealtimeClient(Object.assign({ headers: this.headers }, settings.realtime));
this.rest = new PostgrestClient(`${_supabaseUrl}/rest/v1`, {
headers: this.headers,
schema: (_h = settings.db) === null || _h === void 0 ? void 0 : _h.schema,
fetch: this.fetch
});
this._listenForAuthEvents();
}
get functions() {
return new FunctionsClient(this.functionsUrl, {
headers: this.headers,
customFetch: this.fetch
});
}
get storage() {
return new StorageClient(this.storageUrl, this.headers, this.fetch);
}
from(relation) {
return this.rest.from(relation);
}
rpc(fn, args = {}, options) {
return this.rest.rpc(fn, args, options);
}
channel(name2, opts = { config: {} }) {
return this.realtime.channel(name2, opts);
}
getChannels() {
return this.realtime.getChannels();
}
removeChannel(channel) {
return this.realtime.removeChannel(channel);
}
removeAllChannels() {
return this.realtime.removeAllChannels();
}
_getAccessToken() {
var _a, _b;
return __awaiter(this, void 0, void 0, function* () {
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 : null;
});
}
_initSupabaseAuthClient({ autoRefreshToken, persistSession, detectSessionInUrl, storage, storageKey, flowType }, headers, fetch2) {
const authHeaders = {
Authorization: `Bearer ${this.supabaseKey}`,
apikey: `${this.supabaseKey}`
};
return new SupabaseAuthClient({
url: this.authUrl,
headers: Object.assign(Object.assign({}, authHeaders), headers),
storageKey,
autoRefreshToken,
persistSession,
detectSessionInUrl,
storage,
flowType,
fetch: fetch2
});
}
_initRealtimeClient(options) {
return new RealtimeClient(this.realtimeUrl, 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, session === null || session === void 0 ? void 0 : session.access_token, "CLIENT");
});
return data;
}
_handleTokenChanged(event, token, source) {
if ((event === "TOKEN_REFRESHED" || event === "SIGNED_IN") && this.changedAccessToken !== token) {
this.realtime.setAuth(token !== null && token !== void 0 ? token : null);
this.changedAccessToken = token;
} else if (event === "SIGNED_OUT") {
this.realtime.setAuth(this.supabaseKey);
if (source == "STORAGE")
this.auth.signOut();
this.changedAccessToken = void 0;
}
}
}
const createClient = (supabaseUrl, supabaseKey, options) => {
return new SupabaseClient(supabaseUrl, supabaseKey, options);
};
const supabaseInjectionKey = Symbol();
const useSupabase = () => inject(supabaseInjectionKey);
var main = {
install: function(app, params) {
const { supabaseUrl, supabaseKey, options = {} } = params;
const supabase = createClient(supabaseUrl, supabaseKey, options);
app.config.globalProperties.$supabase = supabase;
app.provide(supabaseInjectionKey, supabase);
}
};
export { main as default, useSupabase };