Files
SecondBrain/.obsidian/plugins/obsidian-transcription/main.js
T
2026-05-14 11:14:11 +03:00

10954 lines
390 KiB
JavaScript

/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __esm = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// node_modules/.pnpm/requires-port@1.0.0/node_modules/requires-port/index.js
var require_requires_port = __commonJS({
"node_modules/.pnpm/requires-port@1.0.0/node_modules/requires-port/index.js"(exports, module2) {
"use strict";
module2.exports = function required(port, protocol) {
protocol = protocol.split(":")[0];
port = +port;
if (!port)
return false;
switch (protocol) {
case "http":
case "ws":
return port !== 80;
case "https":
case "wss":
return port !== 443;
case "ftp":
return port !== 21;
case "gopher":
return port !== 70;
case "file":
return false;
}
return port !== 0;
};
}
});
// node_modules/.pnpm/querystringify@2.2.0/node_modules/querystringify/index.js
var require_querystringify = __commonJS({
"node_modules/.pnpm/querystringify@2.2.0/node_modules/querystringify/index.js"(exports) {
"use strict";
var has = Object.prototype.hasOwnProperty;
var undef;
function decode2(input) {
try {
return decodeURIComponent(input.replace(/\+/g, " "));
} catch (e2) {
return null;
}
}
function encode2(input) {
try {
return encodeURIComponent(input);
} catch (e2) {
return null;
}
}
function querystring(query) {
var parser = /([^=?#&]+)=?([^&]*)/g, result = {}, part;
while (part = parser.exec(query)) {
var key = decode2(part[1]), value = decode2(part[2]);
if (key === null || value === null || key in result)
continue;
result[key] = value;
}
return result;
}
function querystringify(obj, prefix) {
prefix = prefix || "";
var pairs = [], value, key;
if (typeof prefix !== "string")
prefix = "?";
for (key in obj) {
if (has.call(obj, key)) {
value = obj[key];
if (!value && (value === null || value === undef || isNaN(value))) {
value = "";
}
key = encode2(key);
value = encode2(value);
if (key === null || value === null)
continue;
pairs.push(key + "=" + value);
}
}
return pairs.length ? prefix + pairs.join("&") : "";
}
exports.stringify = querystringify;
exports.parse = querystring;
}
});
// node_modules/.pnpm/url-parse@1.5.10/node_modules/url-parse/index.js
var require_url_parse = __commonJS({
"node_modules/.pnpm/url-parse@1.5.10/node_modules/url-parse/index.js"(exports, module2) {
"use strict";
var required = require_requires_port();
var qs = require_querystringify();
var controlOrWhitespace = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;
var CRHTLF = /[\n\r\t]/g;
var slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//;
var port = /:\d+$/;
var protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i;
var windowsDriveLetter = /^[a-zA-Z]:/;
function trimLeft(str) {
return (str ? str : "").toString().replace(controlOrWhitespace, "");
}
var rules = [
["#", "hash"],
["?", "query"],
function sanitize(address, url) {
return isSpecial(url.protocol) ? address.replace(/\\/g, "/") : address;
},
["/", "pathname"],
["@", "auth", 1],
[NaN, "host", void 0, 1, 1],
[/:(\d*)$/, "port", void 0, 1],
[NaN, "hostname", void 0, 1, 1]
];
var ignore = { hash: 1, query: 1 };
function lolcation(loc) {
var globalVar;
if (typeof window !== "undefined")
globalVar = window;
else if (typeof global !== "undefined")
globalVar = global;
else if (typeof self !== "undefined")
globalVar = self;
else
globalVar = {};
var location = globalVar.location || {};
loc = loc || location;
var finaldestination = {}, type = typeof loc, key;
if (loc.protocol === "blob:") {
finaldestination = new Url(unescape(loc.pathname), {});
} else if (type === "string") {
finaldestination = new Url(loc, {});
for (key in ignore)
delete finaldestination[key];
} else if (type === "object") {
for (key in loc) {
if (key in ignore)
continue;
finaldestination[key] = loc[key];
}
if (finaldestination.slashes === void 0) {
finaldestination.slashes = slashes.test(loc.href);
}
}
return finaldestination;
}
function isSpecial(scheme) {
return scheme === "file:" || scheme === "ftp:" || scheme === "http:" || scheme === "https:" || scheme === "ws:" || scheme === "wss:";
}
function extractProtocol(address, location) {
address = trimLeft(address);
address = address.replace(CRHTLF, "");
location = location || {};
var match2 = protocolre.exec(address);
var protocol = match2[1] ? match2[1].toLowerCase() : "";
var forwardSlashes = !!match2[2];
var otherSlashes = !!match2[3];
var slashesCount = 0;
var rest;
if (forwardSlashes) {
if (otherSlashes) {
rest = match2[2] + match2[3] + match2[4];
slashesCount = match2[2].length + match2[3].length;
} else {
rest = match2[2] + match2[4];
slashesCount = match2[2].length;
}
} else {
if (otherSlashes) {
rest = match2[3] + match2[4];
slashesCount = match2[3].length;
} else {
rest = match2[4];
}
}
if (protocol === "file:") {
if (slashesCount >= 2) {
rest = rest.slice(2);
}
} else if (isSpecial(protocol)) {
rest = match2[4];
} else if (protocol) {
if (forwardSlashes) {
rest = rest.slice(2);
}
} else if (slashesCount >= 2 && isSpecial(location.protocol)) {
rest = match2[4];
}
return {
protocol,
slashes: forwardSlashes || isSpecial(protocol),
slashesCount,
rest
};
}
function resolve(relative, base) {
if (relative === "")
return base;
var path = (base || "/").split("/").slice(0, -1).concat(relative.split("/")), i2 = path.length, last = path[i2 - 1], unshift = false, up = 0;
while (i2--) {
if (path[i2] === ".") {
path.splice(i2, 1);
} else if (path[i2] === "..") {
path.splice(i2, 1);
up++;
} else if (up) {
if (i2 === 0)
unshift = true;
path.splice(i2, 1);
up--;
}
}
if (unshift)
path.unshift("");
if (last === "." || last === "..")
path.push("");
return path.join("/");
}
function Url(address, location, parser) {
address = trimLeft(address);
address = address.replace(CRHTLF, "");
if (!(this instanceof Url)) {
return new Url(address, location, parser);
}
var relative, extracted, parse, instruction, index, key, instructions = rules.slice(), type = typeof location, url = this, i2 = 0;
if (type !== "object" && type !== "string") {
parser = location;
location = null;
}
if (parser && typeof parser !== "function")
parser = qs.parse;
location = lolcation(location);
extracted = extractProtocol(address || "", location);
relative = !extracted.protocol && !extracted.slashes;
url.slashes = extracted.slashes || relative && location.slashes;
url.protocol = extracted.protocol || location.protocol || "";
address = extracted.rest;
if (extracted.protocol === "file:" && (extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) || !extracted.slashes && (extracted.protocol || extracted.slashesCount < 2 || !isSpecial(url.protocol))) {
instructions[3] = [/(.*)/, "pathname"];
}
for (; i2 < instructions.length; i2++) {
instruction = instructions[i2];
if (typeof instruction === "function") {
address = instruction(address, url);
continue;
}
parse = instruction[0];
key = instruction[1];
if (parse !== parse) {
url[key] = address;
} else if (typeof parse === "string") {
index = parse === "@" ? address.lastIndexOf(parse) : address.indexOf(parse);
if (~index) {
if (typeof instruction[2] === "number") {
url[key] = address.slice(0, index);
address = address.slice(index + instruction[2]);
} else {
url[key] = address.slice(index);
address = address.slice(0, index);
}
}
} else if (index = parse.exec(address)) {
url[key] = index[1];
address = address.slice(0, index.index);
}
url[key] = url[key] || (relative && instruction[3] ? location[key] || "" : "");
if (instruction[4])
url[key] = url[key].toLowerCase();
}
if (parser)
url.query = parser(url.query);
if (relative && location.slashes && url.pathname.charAt(0) !== "/" && (url.pathname !== "" || location.pathname !== "")) {
url.pathname = resolve(url.pathname, location.pathname);
}
if (url.pathname.charAt(0) !== "/" && isSpecial(url.protocol)) {
url.pathname = "/" + url.pathname;
}
if (!required(url.port, url.protocol)) {
url.host = url.hostname;
url.port = "";
}
url.username = url.password = "";
if (url.auth) {
index = url.auth.indexOf(":");
if (~index) {
url.username = url.auth.slice(0, index);
url.username = encodeURIComponent(decodeURIComponent(url.username));
url.password = url.auth.slice(index + 1);
url.password = encodeURIComponent(decodeURIComponent(url.password));
} else {
url.username = encodeURIComponent(decodeURIComponent(url.auth));
}
url.auth = url.password ? url.username + ":" + url.password : url.username;
}
url.origin = url.protocol !== "file:" && isSpecial(url.protocol) && url.host ? url.protocol + "//" + url.host : "null";
url.href = url.toString();
}
function set(part, value, fn) {
var url = this;
switch (part) {
case "query":
if (typeof value === "string" && value.length) {
value = (fn || qs.parse)(value);
}
url[part] = value;
break;
case "port":
url[part] = value;
if (!required(value, url.protocol)) {
url.host = url.hostname;
url[part] = "";
} else if (value) {
url.host = url.hostname + ":" + value;
}
break;
case "hostname":
url[part] = value;
if (url.port)
value += ":" + url.port;
url.host = value;
break;
case "host":
url[part] = value;
if (port.test(value)) {
value = value.split(":");
url.port = value.pop();
url.hostname = value.join(":");
} else {
url.hostname = value;
url.port = "";
}
break;
case "protocol":
url.protocol = value.toLowerCase();
url.slashes = !fn;
break;
case "pathname":
case "hash":
if (value) {
var char = part === "pathname" ? "/" : "#";
url[part] = value.charAt(0) !== char ? char + value : value;
} else {
url[part] = value;
}
break;
case "username":
case "password":
url[part] = encodeURIComponent(value);
break;
case "auth":
var index = value.indexOf(":");
if (~index) {
url.username = value.slice(0, index);
url.username = encodeURIComponent(decodeURIComponent(url.username));
url.password = value.slice(index + 1);
url.password = encodeURIComponent(decodeURIComponent(url.password));
} else {
url.username = encodeURIComponent(decodeURIComponent(value));
}
}
for (var i2 = 0; i2 < rules.length; i2++) {
var ins = rules[i2];
if (ins[4])
url[ins[1]] = url[ins[1]].toLowerCase();
}
url.auth = url.password ? url.username + ":" + url.password : url.username;
url.origin = url.protocol !== "file:" && isSpecial(url.protocol) && url.host ? url.protocol + "//" + url.host : "null";
url.href = url.toString();
return url;
}
function toString(stringify) {
if (!stringify || typeof stringify !== "function")
stringify = qs.stringify;
var query, url = this, host = url.host, protocol = url.protocol;
if (protocol && protocol.charAt(protocol.length - 1) !== ":")
protocol += ":";
var result = protocol + (url.protocol && url.slashes || isSpecial(url.protocol) ? "//" : "");
if (url.username) {
result += url.username;
if (url.password)
result += ":" + url.password;
result += "@";
} else if (url.password) {
result += ":" + url.password;
result += "@";
} else if (url.protocol !== "file:" && isSpecial(url.protocol) && !host && url.pathname !== "/") {
result += "@";
}
if (host[host.length - 1] === ":" || port.test(url.hostname) && !url.port) {
host += ":";
}
result += host + url.pathname;
query = typeof url.query === "object" ? stringify(url.query) : url.query;
if (query)
result += query.charAt(0) !== "?" ? "?" + query : query;
if (url.hash)
result += url.hash;
return result;
}
Url.prototype = { set, toString };
Url.extractProtocol = extractProtocol;
Url.location = lolcation;
Url.trimLeft = trimLeft;
Url.qs = qs;
module2.exports = Url;
}
});
// node_modules/.pnpm/@supabase+node-fetch@2.6.15/node_modules/@supabase/node-fetch/browser.js
var browser_exports2 = {};
__export(browser_exports2, {
Headers: () => Headers2,
Request: () => Request2,
Response: () => Response3,
default: () => browser_default,
fetch: () => fetch2
});
var getGlobal, globalObject, fetch2, browser_default, Headers2, Request2, Response3;
var init_browser = __esm({
"node_modules/.pnpm/@supabase+node-fetch@2.6.15/node_modules/@supabase/node-fetch/browser.js"() {
"use strict";
getGlobal = function() {
if (typeof self !== "undefined") {
return self;
}
if (typeof window !== "undefined") {
return window;
}
if (typeof global !== "undefined") {
return global;
}
throw new Error("unable to locate global object");
};
globalObject = getGlobal();
fetch2 = globalObject.fetch;
browser_default = globalObject.fetch.bind(globalObject);
Headers2 = globalObject.Headers;
Request2 = globalObject.Request;
Response3 = globalObject.Response;
}
});
// node_modules/.pnpm/ws@8.16.0/node_modules/ws/browser.js
var require_browser = __commonJS({
"node_modules/.pnpm/ws@8.16.0/node_modules/ws/browser.js"(exports, module2) {
"use strict";
module2.exports = function() {
throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object");
};
}
});
// src/main.ts
var main_exports = {};
__export(main_exports, {
Transcription: () => Transcription,
default: () => Transcription
});
module.exports = __toCommonJS(main_exports);
var import_obsidian4 = require("obsidian");
// src/settings.ts
var import_obsidian = require("obsidian");
var SWIFTINK_AUTH_CALLBACK = "https://swiftink.io/login/?callback=obsidian://swiftink_auth";
var SUPABASE_URL = "https://vcdeqgrsqaexpnogauly.supabase.co";
var SUPABASE_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZjZGVxZ3JzcWFleHBub2dhdWx5Iiwicm9sZSI6ImFub24iLCJpYXQiOjE2ODU2OTM4NDUsImV4cCI6MjAwMTI2OTg0NX0.BBxpvuejw_E-Q_g6SU6G6sGP_6r4KnrP-vHV2JZpAho";
var API_BASE = "https://api.swiftink.io";
var IS_SWIFTINK = "swiftink";
var DEFAULT_SETTINGS = {
timestamps: false,
timestampFormat: "auto",
timestampInterval: "0",
translate: false,
language: "auto",
verbosity: 1,
whisperASRUrls: "http://localhost:9000",
debug: false,
transcriptionEngine: "swiftink",
embedAdditionalFunctionality: true,
embedSummary: true,
embedOutline: true,
embedKeywords: true,
swiftink_access_token: null,
swiftink_refresh_token: null,
lineSpacing: "multi",
encode: true,
initialPrompt: "",
vadFilter: false,
wordTimestamps: false
};
var LANGUAGES = {
AFRIKAANS: "af",
ALBANIAN: "sq",
AMHARIC: "am",
ARABIC: "ar",
ARMENIAN: "hy",
ASSAMESE: "as",
AZERBAIJANI: "az",
BASHKIR: "ba",
BASQUE: "eu",
BELARUSIAN: "be",
BENGALI: "bn",
BOSNIAN: "bs",
BRETON: "br",
BULGARIAN: "bg",
BURMESE: "my",
CATALAN: "ca",
CHINESE: "zh",
CROATIAN: "hr",
CZECH: "cs",
DANISH: "da",
DUTCH: "nl",
ENGLISH: "en",
ESTONIAN: "et",
FAROESE: "fo",
FINNISH: "fi",
FRENCH: "fr",
GALICIAN: "gl",
GEORGIAN: "ka",
GERMAN: "de",
GREEK: "el",
GUJARATI: "gu",
HAITIAN: "ht",
HAUSA: "ha",
HEBREW: "he",
HINDI: "hi",
HUNGARIAN: "hu",
ICELANDIC: "is",
INDONESIAN: "id",
ITALIAN: "it",
JAPANESE: "ja",
JAVANESE: "jv",
KANNADA: "kn",
KAZAKH: "kk",
KOREAN: "ko",
LAO: "lo",
LATIN: "la",
LATVIAN: "lv",
LINGALA: "ln",
LITHUANIAN: "lt",
LUXEMBOURGISH: "lb",
MACEDONIAN: "mk",
MALAGASY: "mg",
MALAY: "ms",
MALAYALAM: "ml",
MALTESE: "mt",
MAORI: "mi",
MARATHI: "mr",
MONGOLIAN: "mn",
NEPALI: "ne",
NORWEGIAN: "nb",
OCCITAN: "oc",
PANJABI: "pa",
PERSIAN: "fa",
POLISH: "pl",
PORTUGUESE: "pt",
PUSHTO: "ps",
ROMANIAN: "ro",
RUSSIAN: "ru",
SANSKRIT: "sa",
SERBIAN: "sr",
SHONA: "sn",
SINDHI: "sd",
SINHALA: "si",
SLOVAK: "sk",
SLOVENIAN: "sl",
SOMALI: "so",
SPANISH: "es",
SUNDANESE: "su",
SWAHILI: "sw",
SWEDISH: "sv",
TAGALOG: "tl",
TAJIK: "tg",
TAMIL: "ta",
TATAR: "tt",
TELUGU: "te",
THAI: "th"
};
var TranscriptionSettingTab = class extends import_obsidian.PluginSettingTab {
constructor(app, plugin) {
super(app, plugin);
this.plugin = plugin;
}
display() {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl("h2", {
text: "Settings for Obsidian Transcription"
});
new import_obsidian.Setting(containerEl).setName("General Settings").setHeading();
new import_obsidian.Setting(containerEl).setName("Transcription engine").setDesc("The transcription engine to use").setTooltip("Swiftink is a free cloud based transcription engine (no local set up, additional AI features). Whisper ASR is a self-hosted local transcription engine that uses a Python app (requires local setup).").setClass("transcription-engine-setting").addDropdown((dropdown) => dropdown.addOption("swiftink", "Swiftink").addOption("whisper_asr", "Whisper ASR").setValue(this.plugin.settings.transcriptionEngine).onChange(async (value) => {
this.plugin.settings.transcriptionEngine = value;
await this.plugin.saveSettings();
this.updateSettingVisibility(".swiftink-settings", value === "swiftink");
this.updateSettingVisibility(".whisper-asr-settings", value === "whisper_asr");
this.updateSettingVisibility(".word-timestamps-setting", value === "whisper_asr" && this.plugin.settings.timestamps);
}));
new import_obsidian.Setting(containerEl).setName("Notice verbosity").setDesc("How granularly notices should be displayed").setTooltip("Verbose will display a notice for every event in the backend. Normal will display a notice for every major event, such as successful transcription or file upload. Silent will not display any notices.").addDropdown((dropdown) => dropdown.addOption("0", "Silent").addOption("1", "Normal").addOption("2", "Verbose").setValue(this.plugin.settings.verbosity.toString()).onChange(async (value) => {
this.plugin.settings.verbosity = parseInt(value);
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("Language").setDesc("The language to transcribe the audio in").setTooltip("Automatically detected if not specified").addDropdown((dropdown) => {
dropdown.addOption("auto", "Auto-detect");
for (const [key, value] of Object.entries(LANGUAGES)) {
dropdown.addOption(value, key.charAt(0).toUpperCase() + key.slice(1).toLowerCase());
}
dropdown.setValue(this.plugin.settings.language);
dropdown.onChange(async (value) => {
this.plugin.settings.language = value;
await this.plugin.saveSettings();
});
});
new import_obsidian.Setting(containerEl).setName("Line Spacing").setDesc("Which line spacing mode to use").setTooltip("Defaults to multi-line, as returned by the transcription engine").addDropdown((dropdown) => {
dropdown.addOption("multi", "Multi-line");
dropdown.addOption("single", "Single-line");
dropdown.setValue(this.plugin.settings.lineSpacing);
dropdown.onChange(async (value) => {
this.plugin.settings.lineSpacing = value;
await this.plugin.saveSettings();
});
});
new import_obsidian.Setting(containerEl).setName("Enable timestamps").setDesc("Add timestamps to the beginning of each line").addToggle((toggle) => toggle.setValue(this.plugin.settings.timestamps).onChange(async (value) => {
this.plugin.settings.timestamps = value;
await this.plugin.saveSettings();
this.updateSettingVisibility(".depends-on-timestamps", value);
this.updateSettingVisibility(".word-timestamps-setting", this.plugin.settings.transcriptionEngine === "whisper_asr" && value);
}));
new import_obsidian.Setting(containerEl).setName("Timestamp format").setDesc("Your choice of hours, minutes, and/or seconds in the timestamp. Auto uses the shortest possible format.").setClass("depends-on-timestamps").addDropdown((dropdown) => dropdown.addOption("auto", "Auto").addOption("HH:mm:ss", "HH:mm:ss").addOption("mm:ss", "mm:ss").addOption("ss", "ss").setValue(this.plugin.settings.timestampFormat).onChange(async (value) => {
this.plugin.settings.timestampFormat = value;
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("Timestamp interval").setDesc("The interval at which to add timestamps, in seconds.").setClass("depends-on-timestamps").addDropdown((dropdown) => dropdown.addOption("0", "Off").addOption("5", "5").addOption("10", "10").addOption("15", "15").addOption("20", "20").addOption("30", "30").addOption("60", "60").setValue(this.plugin.settings.timestampInterval).onChange(async (value) => {
this.plugin.settings.timestampInterval = value;
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("Swiftink Settings").setClass("swiftink-settings").setHeading();
new import_obsidian.Setting(containerEl).setClass("swiftink-settings").setName("Swiftink Account").addButton((bt) => {
bt.setButtonText("Sign in with Email");
bt.setClass("swiftink-unauthed-only");
bt.onClick(async () => {
window.open(SWIFTINK_AUTH_CALLBACK, "_blank");
});
}).addButton((bt) => {
bt.setButtonText("Sign in with Google");
bt.setClass("swiftink-unauthed-only");
bt.onClick(async () => {
this.plugin.supabase.auth.signInWithOAuth({
provider: "google",
options: { redirectTo: "obsidian://swiftink_auth" }
});
});
}).addButton((bt) => {
bt.setButtonText("Sign in with GitHub");
bt.setClass("swiftink-unauthed-only");
bt.onClick(async () => {
this.plugin.supabase.auth.signInWithOAuth({
provider: "github",
options: { redirectTo: "obsidian://swiftink_auth" }
});
});
}).addButton((bt) => {
bt.setButtonText("Log out");
bt.setClass("swiftink-authed-only");
bt.onClick(async () => {
await this.plugin.supabase.auth.signOut();
this.plugin.user = null;
this.plugin.settings.swiftink_access_token = null;
this.plugin.settings.swiftink_refresh_token = null;
await this.plugin.saveSettings();
this.updateSettingVisibility(".swiftink-unauthed-only", true);
this.updateSettingVisibility(".swiftink-authed-only", false);
new import_obsidian.Notice("Successfully logged out");
});
}).addButton((bt) => {
var _a;
bt.setButtonText(`Manage ${(_a = this.plugin.user) == null ? void 0 : _a.email}`);
bt.setClass("swiftink-authed-only");
bt.setClass("swiftink-manage-account-btn");
bt.onClick(() => {
window.open("https://swiftink.io/dashboard/account", "_blank");
});
});
new import_obsidian.Setting(containerEl).setName("Embed summary").setDesc("Embed the generated transcription summary in the note").setTooltip("This will only work if you have a Swiftink Pro account").setClass("swiftink-settings").addToggle((toggle) => toggle.setValue(this.plugin.settings.embedSummary).onChange(async (value) => {
this.plugin.settings.embedSummary = value;
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("Embed outline").setDesc("Embed the generated transcription outline in the note").setTooltip("This will only work if you have a Swiftink Pro account").setClass("swiftink-settings").addToggle((toggle) => toggle.setValue(this.plugin.settings.embedOutline).onChange(async (value) => {
this.plugin.settings.embedOutline = value;
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("Embed keywords").setDesc("Embed the extracted keywords in the note").setTooltip("This will only work if you have a Swiftink Pro account").setClass("swiftink-settings").addToggle((toggle) => toggle.setValue(this.plugin.settings.embedKeywords).onChange(async (value) => {
this.plugin.settings.embedKeywords = value;
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("Embed function link").setDesc("(Recommended) Include an embedded link to the transcript function modal in the transcribed note").setTooltip("If you disable this, you will not be able to import your additional transcript data or view the transcript on the Swiftink.io from within Obsidian.").setClass("swiftink-settings").addToggle((toggle) => toggle.setValue(this.plugin.settings.embedAdditionalFunctionality).onChange(async (value) => {
this.plugin.settings.embedAdditionalFunctionality = value;
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("Whisper ASR Settings").setClass("whisper-asr-settings").setHeading();
new import_obsidian.Setting(containerEl).setName("Whisper ASR URLs").setDesc("The URL of the Whisper ASR server: https://github.com/ahmetoner/whisper-asr-webservice. Provide multiple URLs separated by semi-colons in case one is offline or not accessible. Tried in order.").setClass("whisper-asr-settings").addText((text) => text.setPlaceholder(DEFAULT_SETTINGS.whisperASRUrls).setValue(this.plugin.settings.whisperASRUrls).onChange(async (value) => {
this.plugin.settings.whisperASRUrls = value;
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("Encode").setDesc("Encode audio first through ffmpeg").setClass("whisper-asr-settings").addToggle((toggle) => toggle.setValue(this.plugin.settings.encode).onChange(async (value) => {
this.plugin.settings.encode = value;
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("Initial prompt").setDesc("Model follows the style of the prompt, rather than any instructions contained within. 224 tokens max. More info at https://cookbook.openai.com/examples/whisper_prompting_guide").setClass("whisper-asr-settings").addTextArea((text) => text.setPlaceholder(DEFAULT_SETTINGS.initialPrompt).setValue(this.plugin.settings.initialPrompt).onChange(async (value) => {
this.plugin.settings.initialPrompt = value;
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("Word timestamps").setDesc("Include timestamps for each word, can get very verbose! Only works if timestamps are enabled.").setClass("word-timestamps-setting").addToggle((toggle) => toggle.setValue(this.plugin.settings.wordTimestamps).onChange(async (value) => {
this.plugin.settings.wordTimestamps = value;
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("VAD filter").setDesc("Filter out silence from the audio").setClass("whisper-asr-settings").addToggle((toggle) => toggle.setValue(this.plugin.settings.vadFilter).onChange(async (value) => {
this.plugin.settings.vadFilter = value;
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("Advanced Settings").setHeading();
new import_obsidian.Setting(containerEl).setName("Debug mode").setDesc("Enable debug mode to see more console logs").addToggle((toggle) => toggle.setValue(this.plugin.settings.debug).onChange(async (value) => {
this.plugin.settings.debug = value;
await this.plugin.saveSettings();
}));
containerEl.createEl("hr");
const logoLink = containerEl.createEl("a");
logoLink.href = "https://www.swiftink.io";
logoLink.style.display = "block";
logoLink.style.marginLeft = "auto";
logoLink.style.marginRight = "auto";
logoLink.style.width = "30%";
const logo = logoLink.createEl("img");
logo.src = "https://www.swiftink.io/assets/img/logos/swiftink.svg";
logo.alt = "Swiftink Logo";
logo.style.display = "block";
logo.style.width = "100%";
const name = containerEl.createEl("p");
name.classList.add("swiftink-settings");
name.innerHTML = "Swiftink.io";
name.style.textAlign = "center";
const help = containerEl.createEl("p");
help.classList.add("swiftink-settings");
help.innerHTML = "Questions? Please see our <a href='https://www.swiftink.io/docs'>Documentation</a> or email us at <a href='mailto:support@swiftnk.io'>support@swiftink.io</a> \u{1F642}";
help.style.textAlign = "center";
help.style.fontSize = "0.85em";
const disclaimer = containerEl.createEl("p");
disclaimer.classList.add("swiftink-settings");
disclaimer.innerHTML = "By proceeding you agree to our <a href='https://www.swiftink.io/terms'>Terms of Service</a> and <a href='https://www.swiftink.io/privacy'>Privacy Policy</a>.";
disclaimer.style.textAlign = "center";
disclaimer.style.fontSize = "0.85em";
this.updateSettingVisibility(".swiftink-settings", this.plugin.settings.transcriptionEngine === "swiftink");
this.updateSettingVisibility(".whisper-asr-settings", this.plugin.settings.transcriptionEngine === "whisper_asr");
this.updateSettingVisibility(".depends-on-timestamps", this.plugin.settings.timestamps);
this.updateSettingVisibility(".word-timestamps-setting", this.plugin.settings.transcriptionEngine === "whisper_asr" && this.plugin.settings.timestamps);
this.updateSettingVisibility(".swiftink-unauthed-only", this.plugin.user === null);
this.updateSettingVisibility(".swiftink-authed-only", this.plugin.user !== null);
}
updateSettingVisibility(classSelector, visible) {
const { containerEl } = this;
containerEl.findAll(classSelector).forEach((element) => {
element.style.display = visible ? "block" : "none";
});
}
};
// src/transcribe.ts
var import_obsidian3 = require("obsidian");
// node_modules/.pnpm/@babel+runtime@7.23.9/node_modules/@babel/runtime/helpers/esm/typeof.js
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(o2) {
return typeof o2;
} : function(o2) {
return o2 && typeof Symbol == "function" && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
}, _typeof(o);
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/_lib/toInteger/index.js
function toInteger(dirtyNumber) {
if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) {
return NaN;
}
var number = Number(dirtyNumber);
if (isNaN(number)) {
return number;
}
return number < 0 ? Math.ceil(number) : Math.floor(number);
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/_lib/requiredArgs/index.js
function requiredArgs(required, args) {
if (args.length < required) {
throw new TypeError(required + " argument" + (required > 1 ? "s" : "") + " required, but only " + args.length + " present");
}
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/toDate/index.js
function toDate(argument) {
requiredArgs(1, arguments);
var argStr = Object.prototype.toString.call(argument);
if (argument instanceof Date || _typeof(argument) === "object" && argStr === "[object Date]") {
return new Date(argument.getTime());
} else if (typeof argument === "number" || argStr === "[object Number]") {
return new Date(argument);
} else {
if ((typeof argument === "string" || argStr === "[object String]") && typeof console !== "undefined") {
console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments");
console.warn(new Error().stack);
}
return new Date(NaN);
}
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/addMilliseconds/index.js
function addMilliseconds(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var timestamp = toDate(dirtyDate).getTime();
var amount = toInteger(dirtyAmount);
return new Date(timestamp + amount);
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/_lib/defaultOptions/index.js
var defaultOptions = {};
function getDefaultOptions() {
return defaultOptions;
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js
function getTimezoneOffsetInMilliseconds(date) {
var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
utcDate.setUTCFullYear(date.getFullYear());
return date.getTime() - utcDate.getTime();
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/isDate/index.js
function isDate(value) {
requiredArgs(1, arguments);
return value instanceof Date || _typeof(value) === "object" && Object.prototype.toString.call(value) === "[object Date]";
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/isValid/index.js
function isValid(dirtyDate) {
requiredArgs(1, arguments);
if (!isDate(dirtyDate) && typeof dirtyDate !== "number") {
return false;
}
var date = toDate(dirtyDate);
return !isNaN(Number(date));
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/subMilliseconds/index.js
function subMilliseconds(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var amount = toInteger(dirtyAmount);
return addMilliseconds(dirtyDate, -amount);
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/_lib/getUTCDayOfYear/index.js
var MILLISECONDS_IN_DAY = 864e5;
function getUTCDayOfYear(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
var timestamp = date.getTime();
date.setUTCMonth(0, 1);
date.setUTCHours(0, 0, 0, 0);
var startOfYearTimestamp = date.getTime();
var difference = timestamp - startOfYearTimestamp;
return Math.floor(difference / MILLISECONDS_IN_DAY) + 1;
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/_lib/startOfUTCISOWeek/index.js
function startOfUTCISOWeek(dirtyDate) {
requiredArgs(1, arguments);
var weekStartsOn = 1;
var date = toDate(dirtyDate);
var day = date.getUTCDay();
var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
date.setUTCDate(date.getUTCDate() - diff);
date.setUTCHours(0, 0, 0, 0);
return date;
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/_lib/getUTCISOWeekYear/index.js
function getUTCISOWeekYear(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
var year = date.getUTCFullYear();
var fourthOfJanuaryOfNextYear = new Date(0);
fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4);
fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0);
var startOfNextYear = startOfUTCISOWeek(fourthOfJanuaryOfNextYear);
var fourthOfJanuaryOfThisYear = new Date(0);
fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4);
fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0);
var startOfThisYear = startOfUTCISOWeek(fourthOfJanuaryOfThisYear);
if (date.getTime() >= startOfNextYear.getTime()) {
return year + 1;
} else if (date.getTime() >= startOfThisYear.getTime()) {
return year;
} else {
return year - 1;
}
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/_lib/startOfUTCISOWeekYear/index.js
function startOfUTCISOWeekYear(dirtyDate) {
requiredArgs(1, arguments);
var year = getUTCISOWeekYear(dirtyDate);
var fourthOfJanuary = new Date(0);
fourthOfJanuary.setUTCFullYear(year, 0, 4);
fourthOfJanuary.setUTCHours(0, 0, 0, 0);
var date = startOfUTCISOWeek(fourthOfJanuary);
return date;
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/_lib/getUTCISOWeek/index.js
var MILLISECONDS_IN_WEEK = 6048e5;
function getUTCISOWeek(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime();
return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/_lib/startOfUTCWeek/index.js
function startOfUTCWeek(dirtyDate, options) {
var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
requiredArgs(1, arguments);
var defaultOptions4 = getDefaultOptions();
var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions4.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions4.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0);
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");
}
var date = toDate(dirtyDate);
var day = date.getUTCDay();
var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
date.setUTCDate(date.getUTCDate() - diff);
date.setUTCHours(0, 0, 0, 0);
return date;
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/_lib/getUTCWeekYear/index.js
function getUTCWeekYear(dirtyDate, options) {
var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
var year = date.getUTCFullYear();
var defaultOptions4 = getDefaultOptions();
var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions4.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions4.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1);
if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");
}
var firstWeekOfNextYear = new Date(0);
firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate);
firstWeekOfNextYear.setUTCHours(0, 0, 0, 0);
var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, options);
var firstWeekOfThisYear = new Date(0);
firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate);
firstWeekOfThisYear.setUTCHours(0, 0, 0, 0);
var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, options);
if (date.getTime() >= startOfNextYear.getTime()) {
return year + 1;
} else if (date.getTime() >= startOfThisYear.getTime()) {
return year;
} else {
return year - 1;
}
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/_lib/startOfUTCWeekYear/index.js
function startOfUTCWeekYear(dirtyDate, options) {
var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
requiredArgs(1, arguments);
var defaultOptions4 = getDefaultOptions();
var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions4.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions4.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1);
var year = getUTCWeekYear(dirtyDate, options);
var firstWeek = new Date(0);
firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate);
firstWeek.setUTCHours(0, 0, 0, 0);
var date = startOfUTCWeek(firstWeek, options);
return date;
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/_lib/getUTCWeek/index.js
var MILLISECONDS_IN_WEEK2 = 6048e5;
function getUTCWeek(dirtyDate, options) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
var diff = startOfUTCWeek(date, options).getTime() - startOfUTCWeekYear(date, options).getTime();
return Math.round(diff / MILLISECONDS_IN_WEEK2) + 1;
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/_lib/addLeadingZeros/index.js
function addLeadingZeros(number, targetLength) {
var sign = number < 0 ? "-" : "";
var output = Math.abs(number).toString();
while (output.length < targetLength) {
output = "0" + output;
}
return sign + output;
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/_lib/format/lightFormatters/index.js
var formatters = {
y: function y(date, token) {
var signedYear = date.getUTCFullYear();
var year = signedYear > 0 ? signedYear : 1 - signedYear;
return addLeadingZeros(token === "yy" ? year % 100 : year, token.length);
},
M: function M(date, token) {
var month = date.getUTCMonth();
return token === "M" ? String(month + 1) : addLeadingZeros(month + 1, 2);
},
d: function d(date, token) {
return addLeadingZeros(date.getUTCDate(), token.length);
},
a: function a(date, token) {
var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? "pm" : "am";
switch (token) {
case "a":
case "aa":
return dayPeriodEnumValue.toUpperCase();
case "aaa":
return dayPeriodEnumValue;
case "aaaaa":
return dayPeriodEnumValue[0];
case "aaaa":
default:
return dayPeriodEnumValue === "am" ? "a.m." : "p.m.";
}
},
h: function h(date, token) {
return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length);
},
H: function H(date, token) {
return addLeadingZeros(date.getUTCHours(), token.length);
},
m: function m(date, token) {
return addLeadingZeros(date.getUTCMinutes(), token.length);
},
s: function s(date, token) {
return addLeadingZeros(date.getUTCSeconds(), token.length);
},
S: function S(date, token) {
var numberOfDigits = token.length;
var milliseconds = date.getUTCMilliseconds();
var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3));
return addLeadingZeros(fractionalSeconds, token.length);
}
};
var lightFormatters_default = formatters;
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/_lib/format/formatters/index.js
var dayPeriodEnum = {
am: "am",
pm: "pm",
midnight: "midnight",
noon: "noon",
morning: "morning",
afternoon: "afternoon",
evening: "evening",
night: "night"
};
var formatters2 = {
G: function G(date, token, localize2) {
var era = date.getUTCFullYear() > 0 ? 1 : 0;
switch (token) {
case "G":
case "GG":
case "GGG":
return localize2.era(era, {
width: "abbreviated"
});
case "GGGGG":
return localize2.era(era, {
width: "narrow"
});
case "GGGG":
default:
return localize2.era(era, {
width: "wide"
});
}
},
y: function y2(date, token, localize2) {
if (token === "yo") {
var signedYear = date.getUTCFullYear();
var year = signedYear > 0 ? signedYear : 1 - signedYear;
return localize2.ordinalNumber(year, {
unit: "year"
});
}
return lightFormatters_default.y(date, token);
},
Y: function Y(date, token, localize2, options) {
var signedWeekYear = getUTCWeekYear(date, options);
var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear;
if (token === "YY") {
var twoDigitYear = weekYear % 100;
return addLeadingZeros(twoDigitYear, 2);
}
if (token === "Yo") {
return localize2.ordinalNumber(weekYear, {
unit: "year"
});
}
return addLeadingZeros(weekYear, token.length);
},
R: function R(date, token) {
var isoWeekYear = getUTCISOWeekYear(date);
return addLeadingZeros(isoWeekYear, token.length);
},
u: function u(date, token) {
var year = date.getUTCFullYear();
return addLeadingZeros(year, token.length);
},
Q: function Q(date, token, localize2) {
var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
switch (token) {
case "Q":
return String(quarter);
case "QQ":
return addLeadingZeros(quarter, 2);
case "Qo":
return localize2.ordinalNumber(quarter, {
unit: "quarter"
});
case "QQQ":
return localize2.quarter(quarter, {
width: "abbreviated",
context: "formatting"
});
case "QQQQQ":
return localize2.quarter(quarter, {
width: "narrow",
context: "formatting"
});
case "QQQQ":
default:
return localize2.quarter(quarter, {
width: "wide",
context: "formatting"
});
}
},
q: function q(date, token, localize2) {
var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
switch (token) {
case "q":
return String(quarter);
case "qq":
return addLeadingZeros(quarter, 2);
case "qo":
return localize2.ordinalNumber(quarter, {
unit: "quarter"
});
case "qqq":
return localize2.quarter(quarter, {
width: "abbreviated",
context: "standalone"
});
case "qqqqq":
return localize2.quarter(quarter, {
width: "narrow",
context: "standalone"
});
case "qqqq":
default:
return localize2.quarter(quarter, {
width: "wide",
context: "standalone"
});
}
},
M: function M2(date, token, localize2) {
var month = date.getUTCMonth();
switch (token) {
case "M":
case "MM":
return lightFormatters_default.M(date, token);
case "Mo":
return localize2.ordinalNumber(month + 1, {
unit: "month"
});
case "MMM":
return localize2.month(month, {
width: "abbreviated",
context: "formatting"
});
case "MMMMM":
return localize2.month(month, {
width: "narrow",
context: "formatting"
});
case "MMMM":
default:
return localize2.month(month, {
width: "wide",
context: "formatting"
});
}
},
L: function L(date, token, localize2) {
var month = date.getUTCMonth();
switch (token) {
case "L":
return String(month + 1);
case "LL":
return addLeadingZeros(month + 1, 2);
case "Lo":
return localize2.ordinalNumber(month + 1, {
unit: "month"
});
case "LLL":
return localize2.month(month, {
width: "abbreviated",
context: "standalone"
});
case "LLLLL":
return localize2.month(month, {
width: "narrow",
context: "standalone"
});
case "LLLL":
default:
return localize2.month(month, {
width: "wide",
context: "standalone"
});
}
},
w: function w(date, token, localize2, options) {
var week = getUTCWeek(date, options);
if (token === "wo") {
return localize2.ordinalNumber(week, {
unit: "week"
});
}
return addLeadingZeros(week, token.length);
},
I: function I(date, token, localize2) {
var isoWeek = getUTCISOWeek(date);
if (token === "Io") {
return localize2.ordinalNumber(isoWeek, {
unit: "week"
});
}
return addLeadingZeros(isoWeek, token.length);
},
d: function d2(date, token, localize2) {
if (token === "do") {
return localize2.ordinalNumber(date.getUTCDate(), {
unit: "date"
});
}
return lightFormatters_default.d(date, token);
},
D: function D(date, token, localize2) {
var dayOfYear = getUTCDayOfYear(date);
if (token === "Do") {
return localize2.ordinalNumber(dayOfYear, {
unit: "dayOfYear"
});
}
return addLeadingZeros(dayOfYear, token.length);
},
E: function E(date, token, localize2) {
var dayOfWeek = date.getUTCDay();
switch (token) {
case "E":
case "EE":
case "EEE":
return localize2.day(dayOfWeek, {
width: "abbreviated",
context: "formatting"
});
case "EEEEE":
return localize2.day(dayOfWeek, {
width: "narrow",
context: "formatting"
});
case "EEEEEE":
return localize2.day(dayOfWeek, {
width: "short",
context: "formatting"
});
case "EEEE":
default:
return localize2.day(dayOfWeek, {
width: "wide",
context: "formatting"
});
}
},
e: function e(date, token, localize2, options) {
var dayOfWeek = date.getUTCDay();
var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
switch (token) {
case "e":
return String(localDayOfWeek);
case "ee":
return addLeadingZeros(localDayOfWeek, 2);
case "eo":
return localize2.ordinalNumber(localDayOfWeek, {
unit: "day"
});
case "eee":
return localize2.day(dayOfWeek, {
width: "abbreviated",
context: "formatting"
});
case "eeeee":
return localize2.day(dayOfWeek, {
width: "narrow",
context: "formatting"
});
case "eeeeee":
return localize2.day(dayOfWeek, {
width: "short",
context: "formatting"
});
case "eeee":
default:
return localize2.day(dayOfWeek, {
width: "wide",
context: "formatting"
});
}
},
c: function c(date, token, localize2, options) {
var dayOfWeek = date.getUTCDay();
var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
switch (token) {
case "c":
return String(localDayOfWeek);
case "cc":
return addLeadingZeros(localDayOfWeek, token.length);
case "co":
return localize2.ordinalNumber(localDayOfWeek, {
unit: "day"
});
case "ccc":
return localize2.day(dayOfWeek, {
width: "abbreviated",
context: "standalone"
});
case "ccccc":
return localize2.day(dayOfWeek, {
width: "narrow",
context: "standalone"
});
case "cccccc":
return localize2.day(dayOfWeek, {
width: "short",
context: "standalone"
});
case "cccc":
default:
return localize2.day(dayOfWeek, {
width: "wide",
context: "standalone"
});
}
},
i: function i(date, token, localize2) {
var dayOfWeek = date.getUTCDay();
var isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;
switch (token) {
case "i":
return String(isoDayOfWeek);
case "ii":
return addLeadingZeros(isoDayOfWeek, token.length);
case "io":
return localize2.ordinalNumber(isoDayOfWeek, {
unit: "day"
});
case "iii":
return localize2.day(dayOfWeek, {
width: "abbreviated",
context: "formatting"
});
case "iiiii":
return localize2.day(dayOfWeek, {
width: "narrow",
context: "formatting"
});
case "iiiiii":
return localize2.day(dayOfWeek, {
width: "short",
context: "formatting"
});
case "iiii":
default:
return localize2.day(dayOfWeek, {
width: "wide",
context: "formatting"
});
}
},
a: function a2(date, token, localize2) {
var hours = date.getUTCHours();
var dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am";
switch (token) {
case "a":
case "aa":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "abbreviated",
context: "formatting"
});
case "aaa":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "abbreviated",
context: "formatting"
}).toLowerCase();
case "aaaaa":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "narrow",
context: "formatting"
});
case "aaaa":
default:
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "wide",
context: "formatting"
});
}
},
b: function b(date, token, localize2) {
var hours = date.getUTCHours();
var dayPeriodEnumValue;
if (hours === 12) {
dayPeriodEnumValue = dayPeriodEnum.noon;
} else if (hours === 0) {
dayPeriodEnumValue = dayPeriodEnum.midnight;
} else {
dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am";
}
switch (token) {
case "b":
case "bb":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "abbreviated",
context: "formatting"
});
case "bbb":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "abbreviated",
context: "formatting"
}).toLowerCase();
case "bbbbb":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "narrow",
context: "formatting"
});
case "bbbb":
default:
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "wide",
context: "formatting"
});
}
},
B: function B(date, token, localize2) {
var hours = date.getUTCHours();
var dayPeriodEnumValue;
if (hours >= 17) {
dayPeriodEnumValue = dayPeriodEnum.evening;
} else if (hours >= 12) {
dayPeriodEnumValue = dayPeriodEnum.afternoon;
} else if (hours >= 4) {
dayPeriodEnumValue = dayPeriodEnum.morning;
} else {
dayPeriodEnumValue = dayPeriodEnum.night;
}
switch (token) {
case "B":
case "BB":
case "BBB":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "abbreviated",
context: "formatting"
});
case "BBBBB":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "narrow",
context: "formatting"
});
case "BBBB":
default:
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "wide",
context: "formatting"
});
}
},
h: function h2(date, token, localize2) {
if (token === "ho") {
var hours = date.getUTCHours() % 12;
if (hours === 0)
hours = 12;
return localize2.ordinalNumber(hours, {
unit: "hour"
});
}
return lightFormatters_default.h(date, token);
},
H: function H2(date, token, localize2) {
if (token === "Ho") {
return localize2.ordinalNumber(date.getUTCHours(), {
unit: "hour"
});
}
return lightFormatters_default.H(date, token);
},
K: function K(date, token, localize2) {
var hours = date.getUTCHours() % 12;
if (token === "Ko") {
return localize2.ordinalNumber(hours, {
unit: "hour"
});
}
return addLeadingZeros(hours, token.length);
},
k: function k(date, token, localize2) {
var hours = date.getUTCHours();
if (hours === 0)
hours = 24;
if (token === "ko") {
return localize2.ordinalNumber(hours, {
unit: "hour"
});
}
return addLeadingZeros(hours, token.length);
},
m: function m2(date, token, localize2) {
if (token === "mo") {
return localize2.ordinalNumber(date.getUTCMinutes(), {
unit: "minute"
});
}
return lightFormatters_default.m(date, token);
},
s: function s2(date, token, localize2) {
if (token === "so") {
return localize2.ordinalNumber(date.getUTCSeconds(), {
unit: "second"
});
}
return lightFormatters_default.s(date, token);
},
S: function S2(date, token) {
return lightFormatters_default.S(date, token);
},
X: function X(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
if (timezoneOffset === 0) {
return "Z";
}
switch (token) {
case "X":
return formatTimezoneWithOptionalMinutes(timezoneOffset);
case "XXXX":
case "XX":
return formatTimezone(timezoneOffset);
case "XXXXX":
case "XXX":
default:
return formatTimezone(timezoneOffset, ":");
}
},
x: function x(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
switch (token) {
case "x":
return formatTimezoneWithOptionalMinutes(timezoneOffset);
case "xxxx":
case "xx":
return formatTimezone(timezoneOffset);
case "xxxxx":
case "xxx":
default:
return formatTimezone(timezoneOffset, ":");
}
},
O: function O(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
switch (token) {
case "O":
case "OO":
case "OOO":
return "GMT" + formatTimezoneShort(timezoneOffset, ":");
case "OOOO":
default:
return "GMT" + formatTimezone(timezoneOffset, ":");
}
},
z: function z(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
switch (token) {
case "z":
case "zz":
case "zzz":
return "GMT" + formatTimezoneShort(timezoneOffset, ":");
case "zzzz":
default:
return "GMT" + formatTimezone(timezoneOffset, ":");
}
},
t: function t(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timestamp = Math.floor(originalDate.getTime() / 1e3);
return addLeadingZeros(timestamp, token.length);
},
T: function T(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timestamp = originalDate.getTime();
return addLeadingZeros(timestamp, token.length);
}
};
function formatTimezoneShort(offset, dirtyDelimiter) {
var sign = offset > 0 ? "-" : "+";
var absOffset = Math.abs(offset);
var hours = Math.floor(absOffset / 60);
var minutes = absOffset % 60;
if (minutes === 0) {
return sign + String(hours);
}
var delimiter = dirtyDelimiter || "";
return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2);
}
function formatTimezoneWithOptionalMinutes(offset, dirtyDelimiter) {
if (offset % 60 === 0) {
var sign = offset > 0 ? "-" : "+";
return sign + addLeadingZeros(Math.abs(offset) / 60, 2);
}
return formatTimezone(offset, dirtyDelimiter);
}
function formatTimezone(offset, dirtyDelimiter) {
var delimiter = dirtyDelimiter || "";
var sign = offset > 0 ? "-" : "+";
var absOffset = Math.abs(offset);
var hours = addLeadingZeros(Math.floor(absOffset / 60), 2);
var minutes = addLeadingZeros(absOffset % 60, 2);
return sign + hours + delimiter + minutes;
}
var formatters_default = formatters2;
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/_lib/format/longFormatters/index.js
var dateLongFormatter = function dateLongFormatter2(pattern, formatLong2) {
switch (pattern) {
case "P":
return formatLong2.date({
width: "short"
});
case "PP":
return formatLong2.date({
width: "medium"
});
case "PPP":
return formatLong2.date({
width: "long"
});
case "PPPP":
default:
return formatLong2.date({
width: "full"
});
}
};
var timeLongFormatter = function timeLongFormatter2(pattern, formatLong2) {
switch (pattern) {
case "p":
return formatLong2.time({
width: "short"
});
case "pp":
return formatLong2.time({
width: "medium"
});
case "ppp":
return formatLong2.time({
width: "long"
});
case "pppp":
default:
return formatLong2.time({
width: "full"
});
}
};
var dateTimeLongFormatter = function dateTimeLongFormatter2(pattern, formatLong2) {
var matchResult = pattern.match(/(P+)(p+)?/) || [];
var datePattern = matchResult[1];
var timePattern = matchResult[2];
if (!timePattern) {
return dateLongFormatter(pattern, formatLong2);
}
var dateTimeFormat;
switch (datePattern) {
case "P":
dateTimeFormat = formatLong2.dateTime({
width: "short"
});
break;
case "PP":
dateTimeFormat = formatLong2.dateTime({
width: "medium"
});
break;
case "PPP":
dateTimeFormat = formatLong2.dateTime({
width: "long"
});
break;
case "PPPP":
default:
dateTimeFormat = formatLong2.dateTime({
width: "full"
});
break;
}
return dateTimeFormat.replace("{{date}}", dateLongFormatter(datePattern, formatLong2)).replace("{{time}}", timeLongFormatter(timePattern, formatLong2));
};
var longFormatters = {
p: timeLongFormatter,
P: dateTimeLongFormatter
};
var longFormatters_default = longFormatters;
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/_lib/protectedTokens/index.js
var protectedDayOfYearTokens = ["D", "DD"];
var protectedWeekYearTokens = ["YY", "YYYY"];
function isProtectedDayOfYearToken(token) {
return protectedDayOfYearTokens.indexOf(token) !== -1;
}
function isProtectedWeekYearToken(token) {
return protectedWeekYearTokens.indexOf(token) !== -1;
}
function throwProtectedError(token, format2, input) {
if (token === "YYYY") {
throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(format2, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
} else if (token === "YY") {
throw new RangeError("Use `yy` instead of `YY` (in `".concat(format2, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
} else if (token === "D") {
throw new RangeError("Use `d` instead of `D` (in `".concat(format2, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
} else if (token === "DD") {
throw new RangeError("Use `dd` instead of `DD` (in `".concat(format2, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
}
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/locale/en-US/_lib/formatDistance/index.js
var formatDistanceLocale = {
lessThanXSeconds: {
one: "less than a second",
other: "less than {{count}} seconds"
},
xSeconds: {
one: "1 second",
other: "{{count}} seconds"
},
halfAMinute: "half a minute",
lessThanXMinutes: {
one: "less than a minute",
other: "less than {{count}} minutes"
},
xMinutes: {
one: "1 minute",
other: "{{count}} minutes"
},
aboutXHours: {
one: "about 1 hour",
other: "about {{count}} hours"
},
xHours: {
one: "1 hour",
other: "{{count}} hours"
},
xDays: {
one: "1 day",
other: "{{count}} days"
},
aboutXWeeks: {
one: "about 1 week",
other: "about {{count}} weeks"
},
xWeeks: {
one: "1 week",
other: "{{count}} weeks"
},
aboutXMonths: {
one: "about 1 month",
other: "about {{count}} months"
},
xMonths: {
one: "1 month",
other: "{{count}} months"
},
aboutXYears: {
one: "about 1 year",
other: "about {{count}} years"
},
xYears: {
one: "1 year",
other: "{{count}} years"
},
overXYears: {
one: "over 1 year",
other: "over {{count}} years"
},
almostXYears: {
one: "almost 1 year",
other: "almost {{count}} years"
}
};
var formatDistance = function formatDistance2(token, count, options) {
var result;
var tokenValue = formatDistanceLocale[token];
if (typeof tokenValue === "string") {
result = tokenValue;
} else if (count === 1) {
result = tokenValue.one;
} else {
result = tokenValue.other.replace("{{count}}", count.toString());
}
if (options !== null && options !== void 0 && options.addSuffix) {
if (options.comparison && options.comparison > 0) {
return "in " + result;
} else {
return result + " ago";
}
}
return result;
};
var formatDistance_default = formatDistance;
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/locale/_lib/buildFormatLongFn/index.js
function buildFormatLongFn(args) {
return function() {
var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
var width = options.width ? String(options.width) : args.defaultWidth;
var format2 = args.formats[width] || args.formats[args.defaultWidth];
return format2;
};
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/locale/en-US/_lib/formatLong/index.js
var dateFormats = {
full: "EEEE, MMMM do, y",
long: "MMMM do, y",
medium: "MMM d, y",
short: "MM/dd/yyyy"
};
var timeFormats = {
full: "h:mm:ss a zzzz",
long: "h:mm:ss a z",
medium: "h:mm:ss a",
short: "h:mm a"
};
var dateTimeFormats = {
full: "{{date}} 'at' {{time}}",
long: "{{date}} 'at' {{time}}",
medium: "{{date}}, {{time}}",
short: "{{date}}, {{time}}"
};
var formatLong = {
date: buildFormatLongFn({
formats: dateFormats,
defaultWidth: "full"
}),
time: buildFormatLongFn({
formats: timeFormats,
defaultWidth: "full"
}),
dateTime: buildFormatLongFn({
formats: dateTimeFormats,
defaultWidth: "full"
})
};
var formatLong_default = formatLong;
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/locale/en-US/_lib/formatRelative/index.js
var formatRelativeLocale = {
lastWeek: "'last' eeee 'at' p",
yesterday: "'yesterday at' p",
today: "'today at' p",
tomorrow: "'tomorrow at' p",
nextWeek: "eeee 'at' p",
other: "P"
};
var formatRelative = function formatRelative2(token, _date, _baseDate, _options) {
return formatRelativeLocale[token];
};
var formatRelative_default = formatRelative;
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/locale/_lib/buildLocalizeFn/index.js
function buildLocalizeFn(args) {
return function(dirtyIndex, options) {
var context = options !== null && options !== void 0 && options.context ? String(options.context) : "standalone";
var valuesArray;
if (context === "formatting" && args.formattingValues) {
var defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
var width = options !== null && options !== void 0 && options.width ? String(options.width) : defaultWidth;
valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth];
} else {
var _defaultWidth = args.defaultWidth;
var _width = options !== null && options !== void 0 && options.width ? String(options.width) : args.defaultWidth;
valuesArray = args.values[_width] || args.values[_defaultWidth];
}
var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex;
return valuesArray[index];
};
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/locale/en-US/_lib/localize/index.js
var eraValues = {
narrow: ["B", "A"],
abbreviated: ["BC", "AD"],
wide: ["Before Christ", "Anno Domini"]
};
var quarterValues = {
narrow: ["1", "2", "3", "4"],
abbreviated: ["Q1", "Q2", "Q3", "Q4"],
wide: ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"]
};
var monthValues = {
narrow: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"],
abbreviated: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
wide: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
};
var dayValues = {
narrow: ["S", "M", "T", "W", "T", "F", "S"],
short: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
abbreviated: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
wide: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
};
var dayPeriodValues = {
narrow: {
am: "a",
pm: "p",
midnight: "mi",
noon: "n",
morning: "morning",
afternoon: "afternoon",
evening: "evening",
night: "night"
},
abbreviated: {
am: "AM",
pm: "PM",
midnight: "midnight",
noon: "noon",
morning: "morning",
afternoon: "afternoon",
evening: "evening",
night: "night"
},
wide: {
am: "a.m.",
pm: "p.m.",
midnight: "midnight",
noon: "noon",
morning: "morning",
afternoon: "afternoon",
evening: "evening",
night: "night"
}
};
var formattingDayPeriodValues = {
narrow: {
am: "a",
pm: "p",
midnight: "mi",
noon: "n",
morning: "in the morning",
afternoon: "in the afternoon",
evening: "in the evening",
night: "at night"
},
abbreviated: {
am: "AM",
pm: "PM",
midnight: "midnight",
noon: "noon",
morning: "in the morning",
afternoon: "in the afternoon",
evening: "in the evening",
night: "at night"
},
wide: {
am: "a.m.",
pm: "p.m.",
midnight: "midnight",
noon: "noon",
morning: "in the morning",
afternoon: "in the afternoon",
evening: "in the evening",
night: "at night"
}
};
var ordinalNumber = function ordinalNumber2(dirtyNumber, _options) {
var number = Number(dirtyNumber);
var rem100 = number % 100;
if (rem100 > 20 || rem100 < 10) {
switch (rem100 % 10) {
case 1:
return number + "st";
case 2:
return number + "nd";
case 3:
return number + "rd";
}
}
return number + "th";
};
var localize = {
ordinalNumber,
era: buildLocalizeFn({
values: eraValues,
defaultWidth: "wide"
}),
quarter: buildLocalizeFn({
values: quarterValues,
defaultWidth: "wide",
argumentCallback: function argumentCallback(quarter) {
return quarter - 1;
}
}),
month: buildLocalizeFn({
values: monthValues,
defaultWidth: "wide"
}),
day: buildLocalizeFn({
values: dayValues,
defaultWidth: "wide"
}),
dayPeriod: buildLocalizeFn({
values: dayPeriodValues,
defaultWidth: "wide",
formattingValues: formattingDayPeriodValues,
defaultFormattingWidth: "wide"
})
};
var localize_default = localize;
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/locale/_lib/buildMatchFn/index.js
function buildMatchFn(args) {
return function(string) {
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
var width = options.width;
var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
var matchResult = string.match(matchPattern);
if (!matchResult) {
return null;
}
var matchedString = matchResult[0];
var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
var key = Array.isArray(parsePatterns) ? findIndex(parsePatterns, function(pattern) {
return pattern.test(matchedString);
}) : findKey(parsePatterns, function(pattern) {
return pattern.test(matchedString);
});
var value;
value = args.valueCallback ? args.valueCallback(key) : key;
value = options.valueCallback ? options.valueCallback(value) : value;
var rest = string.slice(matchedString.length);
return {
value,
rest
};
};
}
function findKey(object, predicate) {
for (var key in object) {
if (object.hasOwnProperty(key) && predicate(object[key])) {
return key;
}
}
return void 0;
}
function findIndex(array, predicate) {
for (var key = 0; key < array.length; key++) {
if (predicate(array[key])) {
return key;
}
}
return void 0;
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/locale/_lib/buildMatchPatternFn/index.js
function buildMatchPatternFn(args) {
return function(string) {
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
var matchResult = string.match(args.matchPattern);
if (!matchResult)
return null;
var matchedString = matchResult[0];
var parseResult = string.match(args.parsePattern);
if (!parseResult)
return null;
var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0];
value = options.valueCallback ? options.valueCallback(value) : value;
var rest = string.slice(matchedString.length);
return {
value,
rest
};
};
}
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/locale/en-US/_lib/match/index.js
var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
var parseOrdinalNumberPattern = /\d+/i;
var matchEraPatterns = {
narrow: /^(b|a)/i,
abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
wide: /^(before christ|before common era|anno domini|common era)/i
};
var parseEraPatterns = {
any: [/^b/i, /^(a|c)/i]
};
var matchQuarterPatterns = {
narrow: /^[1234]/i,
abbreviated: /^q[1234]/i,
wide: /^[1234](th|st|nd|rd)? quarter/i
};
var parseQuarterPatterns = {
any: [/1/i, /2/i, /3/i, /4/i]
};
var matchMonthPatterns = {
narrow: /^[jfmasond]/i,
abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i
};
var parseMonthPatterns = {
narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i],
any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i]
};
var matchDayPatterns = {
narrow: /^[smtwf]/i,
short: /^(su|mo|tu|we|th|fr|sa)/i,
abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i
};
var parseDayPatterns = {
narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i]
};
var matchDayPeriodPatterns = {
narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i
};
var parseDayPeriodPatterns = {
any: {
am: /^a/i,
pm: /^p/i,
midnight: /^mi/i,
noon: /^no/i,
morning: /morning/i,
afternoon: /afternoon/i,
evening: /evening/i,
night: /night/i
}
};
var match = {
ordinalNumber: buildMatchPatternFn({
matchPattern: matchOrdinalNumberPattern,
parsePattern: parseOrdinalNumberPattern,
valueCallback: function valueCallback(value) {
return parseInt(value, 10);
}
}),
era: buildMatchFn({
matchPatterns: matchEraPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseEraPatterns,
defaultParseWidth: "any"
}),
quarter: buildMatchFn({
matchPatterns: matchQuarterPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseQuarterPatterns,
defaultParseWidth: "any",
valueCallback: function valueCallback2(index) {
return index + 1;
}
}),
month: buildMatchFn({
matchPatterns: matchMonthPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseMonthPatterns,
defaultParseWidth: "any"
}),
day: buildMatchFn({
matchPatterns: matchDayPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseDayPatterns,
defaultParseWidth: "any"
}),
dayPeriod: buildMatchFn({
matchPatterns: matchDayPeriodPatterns,
defaultMatchWidth: "any",
parsePatterns: parseDayPeriodPatterns,
defaultParseWidth: "any"
})
};
var match_default = match;
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/locale/en-US/index.js
var locale = {
code: "en-US",
formatDistance: formatDistance_default,
formatLong: formatLong_default,
formatRelative: formatRelative_default,
localize: localize_default,
match: match_default,
options: {
weekStartsOn: 0,
firstWeekContainsDate: 1
}
};
var en_US_default = locale;
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/_lib/defaultLocale/index.js
var defaultLocale_default = en_US_default;
// node_modules/.pnpm/date-fns@2.30.0/node_modules/date-fns/esm/format/index.js
var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
var escapedStringRegExp = /^'([^]*?)'?$/;
var doubleQuoteRegExp = /''/g;
var unescapedLatinCharacterRegExp = /[a-zA-Z]/;
function format(dirtyDate, dirtyFormatStr, options) {
var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4;
requiredArgs(2, arguments);
var formatStr = String(dirtyFormatStr);
var defaultOptions4 = getDefaultOptions();
var locale2 = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions4.locale) !== null && _ref !== void 0 ? _ref : defaultLocale_default;
var firstWeekContainsDate = toInteger((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions4.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions4.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1);
if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");
}
var weekStartsOn = toInteger((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions4.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions4.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0);
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");
}
if (!locale2.localize) {
throw new RangeError("locale must contain localize property");
}
if (!locale2.formatLong) {
throw new RangeError("locale must contain formatLong property");
}
var originalDate = toDate(dirtyDate);
if (!isValid(originalDate)) {
throw new RangeError("Invalid time value");
}
var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate);
var utcDate = subMilliseconds(originalDate, timezoneOffset);
var formatterOptions = {
firstWeekContainsDate,
weekStartsOn,
locale: locale2,
_originalDate: originalDate
};
var result = formatStr.match(longFormattingTokensRegExp).map(function(substring) {
var firstCharacter = substring[0];
if (firstCharacter === "p" || firstCharacter === "P") {
var longFormatter = longFormatters_default[firstCharacter];
return longFormatter(substring, locale2.formatLong);
}
return substring;
}).join("").match(formattingTokensRegExp).map(function(substring) {
if (substring === "''") {
return "'";
}
var firstCharacter = substring[0];
if (firstCharacter === "'") {
return cleanEscapedString(substring);
}
var formatter = formatters_default[firstCharacter];
if (formatter) {
if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(substring)) {
throwProtectedError(substring, dirtyFormatStr, String(dirtyDate));
}
if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(substring)) {
throwProtectedError(substring, dirtyFormatStr, String(dirtyDate));
}
return formatter(utcDate, substring, locale2.localize, formatterOptions);
}
if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
throw new RangeError("Format string contains an unescaped latin alphabet character `" + firstCharacter + "`");
}
return substring;
}).join("");
return result;
}
function cleanEscapedString(input) {
var matched = input.match(escapedStringRegExp);
if (!matched) {
return input;
}
return matched[1].replace(doubleQuoteRegExp, "'");
}
// src/utils.ts
var import_obsidian2 = require("obsidian");
var randomString = (length) => Array(length + 1).join((Math.random().toString(36) + "00000000000000000").slice(2, 18)).slice(0, length);
async function payloadGenerator(payload_data) {
const boundary_string = `Boundary${randomString(16)}`;
const boundary = `------${boundary_string}`;
const chunks = [];
for (const [key, value] of Object.entries(payload_data)) {
chunks.push(new TextEncoder().encode(`${boundary}\r
`));
if (typeof value === "string") {
chunks.push(new TextEncoder().encode(`Content-Disposition: form-data; name="${key}"\r
\r
`));
chunks.push(new TextEncoder().encode(`${value}\r
`));
} else if (value instanceof Blob) {
chunks.push(new TextEncoder().encode(`Content-Disposition: form-data; name="${key}"; filename="blob"\r
Content-Type: "application/octet-stream"\r
\r
`));
chunks.push(await (0, import_obsidian2.getBlobArrayBuffer)(value));
chunks.push(new TextEncoder().encode("\r\n"));
} else {
chunks.push(new Uint8Array(await new Response(value).arrayBuffer()));
chunks.push(new TextEncoder().encode("\r\n"));
}
}
await Promise.all(chunks);
chunks.push(new TextEncoder().encode(`${boundary}--\r
`));
return [await new Blob(chunks).arrayBuffer(), boundary_string];
}
function preprocessWhisperASRResponse(rawResponse) {
return {
language: rawResponse.language,
text: rawResponse.text,
segments: rawResponse.segments.map((segment) => {
const baseSegment = {
segmentIndex: segment[0],
seek: segment[1],
start: segment[2],
end: segment[3],
text: segment[4],
tokens: segment[5],
temperature: segment[6],
avg_logprob: segment[7],
compression_ratio: segment[8],
no_speech_prob: segment[9],
words: null
};
if (segment[10] !== null) {
baseSegment.words = segment[10].map((wordTimestamp) => ({
start: wordTimestamp[0],
end: wordTimestamp[1],
word: wordTimestamp[2],
probability: wordTimestamp[3]
}));
}
return baseSegment;
})
};
}
// node_modules/.pnpm/js-base64@3.7.6/node_modules/js-base64/base64.mjs
var version = "3.7.6";
var VERSION = version;
var _hasatob = typeof atob === "function";
var _hasbtoa = typeof btoa === "function";
var _hasBuffer = typeof Buffer === "function";
var _TD = typeof TextDecoder === "function" ? new TextDecoder() : void 0;
var _TE = typeof TextEncoder === "function" ? new TextEncoder() : void 0;
var b64ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var b64chs = Array.prototype.slice.call(b64ch);
var b64tab = ((a3) => {
let tab = {};
a3.forEach((c2, i2) => tab[c2] = i2);
return tab;
})(b64chs);
var b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
var _fromCC = String.fromCharCode.bind(String);
var _U8Afrom = typeof Uint8Array.from === "function" ? Uint8Array.from.bind(Uint8Array) : (it) => new Uint8Array(Array.prototype.slice.call(it, 0));
var _mkUriSafe = (src) => src.replace(/=/g, "").replace(/[+\/]/g, (m0) => m0 == "+" ? "-" : "_");
var _tidyB64 = (s3) => s3.replace(/[^A-Za-z0-9\+\/]/g, "");
var btoaPolyfill = (bin) => {
let u32, c0, c1, c2, asc = "";
const pad = bin.length % 3;
for (let i2 = 0; i2 < bin.length; ) {
if ((c0 = bin.charCodeAt(i2++)) > 255 || (c1 = bin.charCodeAt(i2++)) > 255 || (c2 = bin.charCodeAt(i2++)) > 255)
throw new TypeError("invalid character found");
u32 = c0 << 16 | c1 << 8 | c2;
asc += b64chs[u32 >> 18 & 63] + b64chs[u32 >> 12 & 63] + b64chs[u32 >> 6 & 63] + b64chs[u32 & 63];
}
return pad ? asc.slice(0, pad - 3) + "===".substring(pad) : asc;
};
var _btoa = _hasbtoa ? (bin) => btoa(bin) : _hasBuffer ? (bin) => Buffer.from(bin, "binary").toString("base64") : btoaPolyfill;
var _fromUint8Array = _hasBuffer ? (u8a) => Buffer.from(u8a).toString("base64") : (u8a) => {
const maxargs = 4096;
let strs = [];
for (let i2 = 0, l = u8a.length; i2 < l; i2 += maxargs) {
strs.push(_fromCC.apply(null, u8a.subarray(i2, i2 + maxargs)));
}
return _btoa(strs.join(""));
};
var fromUint8Array = (u8a, urlsafe = false) => urlsafe ? _mkUriSafe(_fromUint8Array(u8a)) : _fromUint8Array(u8a);
var cb_utob = (c2) => {
if (c2.length < 2) {
var cc = c2.charCodeAt(0);
return cc < 128 ? c2 : cc < 2048 ? _fromCC(192 | cc >>> 6) + _fromCC(128 | cc & 63) : _fromCC(224 | cc >>> 12 & 15) + _fromCC(128 | cc >>> 6 & 63) + _fromCC(128 | cc & 63);
} else {
var cc = 65536 + (c2.charCodeAt(0) - 55296) * 1024 + (c2.charCodeAt(1) - 56320);
return _fromCC(240 | cc >>> 18 & 7) + _fromCC(128 | cc >>> 12 & 63) + _fromCC(128 | cc >>> 6 & 63) + _fromCC(128 | cc & 63);
}
};
var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
var utob = (u2) => u2.replace(re_utob, cb_utob);
var _encode = _hasBuffer ? (s3) => Buffer.from(s3, "utf8").toString("base64") : _TE ? (s3) => _fromUint8Array(_TE.encode(s3)) : (s3) => _btoa(utob(s3));
var encode = (src, urlsafe = false) => urlsafe ? _mkUriSafe(_encode(src)) : _encode(src);
var encodeURI2 = (src) => encode(src, true);
var re_btou = /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g;
var cb_btou = (cccc) => {
switch (cccc.length) {
case 4:
var cp = (7 & cccc.charCodeAt(0)) << 18 | (63 & cccc.charCodeAt(1)) << 12 | (63 & cccc.charCodeAt(2)) << 6 | 63 & cccc.charCodeAt(3), offset = cp - 65536;
return _fromCC((offset >>> 10) + 55296) + _fromCC((offset & 1023) + 56320);
case 3:
return _fromCC((15 & cccc.charCodeAt(0)) << 12 | (63 & cccc.charCodeAt(1)) << 6 | 63 & cccc.charCodeAt(2));
default:
return _fromCC((31 & cccc.charCodeAt(0)) << 6 | 63 & cccc.charCodeAt(1));
}
};
var btou = (b2) => b2.replace(re_btou, cb_btou);
var atobPolyfill = (asc) => {
asc = asc.replace(/\s+/g, "");
if (!b64re.test(asc))
throw new TypeError("malformed base64.");
asc += "==".slice(2 - (asc.length & 3));
let u24, bin = "", r1, r2;
for (let i2 = 0; i2 < asc.length; ) {
u24 = b64tab[asc.charAt(i2++)] << 18 | b64tab[asc.charAt(i2++)] << 12 | (r1 = b64tab[asc.charAt(i2++)]) << 6 | (r2 = b64tab[asc.charAt(i2++)]);
bin += r1 === 64 ? _fromCC(u24 >> 16 & 255) : r2 === 64 ? _fromCC(u24 >> 16 & 255, u24 >> 8 & 255) : _fromCC(u24 >> 16 & 255, u24 >> 8 & 255, u24 & 255);
}
return bin;
};
var _atob = _hasatob ? (asc) => atob(_tidyB64(asc)) : _hasBuffer ? (asc) => Buffer.from(asc, "base64").toString("binary") : atobPolyfill;
var _toUint8Array = _hasBuffer ? (a3) => _U8Afrom(Buffer.from(a3, "base64")) : (a3) => _U8Afrom(_atob(a3).split("").map((c2) => c2.charCodeAt(0)));
var toUint8Array = (a3) => _toUint8Array(_unURI(a3));
var _decode = _hasBuffer ? (a3) => Buffer.from(a3, "base64").toString("utf8") : _TD ? (a3) => _TD.decode(_toUint8Array(a3)) : (a3) => btou(_atob(a3));
var _unURI = (a3) => _tidyB64(a3.replace(/[-_]/g, (m0) => m0 == "-" ? "+" : "/"));
var decode = (src) => _decode(_unURI(src));
var isValid2 = (src) => {
if (typeof src !== "string")
return false;
const s3 = src.replace(/\s+/g, "").replace(/={0,2}$/, "");
return !/[^\s0-9a-zA-Z\+/]/.test(s3) || !/[^\s0-9a-zA-Z\-_]/.test(s3);
};
var _noEnum = (v) => {
return {
value: v,
enumerable: false,
writable: true,
configurable: true
};
};
var extendString = function() {
const _add = (name, body) => Object.defineProperty(String.prototype, name, _noEnum(body));
_add("fromBase64", function() {
return decode(this);
});
_add("toBase64", function(urlsafe) {
return encode(this, urlsafe);
});
_add("toBase64URI", function() {
return encode(this, true);
});
_add("toBase64URL", function() {
return encode(this, true);
});
_add("toUint8Array", function() {
return toUint8Array(this);
});
};
var extendUint8Array = function() {
const _add = (name, body) => Object.defineProperty(Uint8Array.prototype, name, _noEnum(body));
_add("toBase64", function(urlsafe) {
return fromUint8Array(this, urlsafe);
});
_add("toBase64URI", function() {
return fromUint8Array(this, true);
});
_add("toBase64URL", function() {
return fromUint8Array(this, true);
});
};
var extendBuiltins = () => {
extendString();
extendUint8Array();
};
var gBase64 = {
version,
VERSION,
atob: _atob,
atobPolyfill,
btoa: _btoa,
btoaPolyfill,
fromBase64: decode,
toBase64: encode,
encode,
encodeURI: encodeURI2,
encodeURL: encodeURI2,
utob,
btou,
decode,
isValid: isValid2,
fromUint8Array,
toUint8Array,
extendString,
extendUint8Array,
extendBuiltins
};
// node_modules/.pnpm/tus-js-client@3.1.3/node_modules/tus-js-client/lib.esm/upload.js
var import_url_parse = __toESM(require_url_parse());
// node_modules/.pnpm/tus-js-client@3.1.3/node_modules/tus-js-client/lib.esm/error.js
function _typeof2(o) {
"@babel/helpers - typeof";
return _typeof2 = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(o2) {
return typeof o2;
} : function(o2) {
return o2 && typeof Symbol == "function" && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
}, _typeof2(o);
}
function _defineProperties(target, props) {
for (var i2 = 0; i2 < props.length; i2++) {
var descriptor = props[i2];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor)
descriptor.writable = true;
Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps)
_defineProperties(Constructor.prototype, protoProps);
if (staticProps)
_defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _toPropertyKey(arg) {
var key = _toPrimitive(arg, "string");
return _typeof2(key) === "symbol" ? key : String(key);
}
function _toPrimitive(input, hint) {
if (_typeof2(input) !== "object" || input === null)
return input;
var prim = input[Symbol.toPrimitive];
if (prim !== void 0) {
var res = prim.call(input, hint || "default");
if (_typeof2(res) !== "object")
return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
Object.defineProperty(subClass, "prototype", { writable: false });
if (superClass)
_setPrototypeOf(subClass, superClass);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived), result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _possibleConstructorReturn(self2, call) {
if (call && (_typeof2(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self2);
}
function _assertThisInitialized(self2) {
if (self2 === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self2;
}
function _wrapNativeSuper(Class) {
var _cache = typeof Map === "function" ? /* @__PURE__ */ new Map() : void 0;
_wrapNativeSuper = function _wrapNativeSuper2(Class2) {
if (Class2 === null || !_isNativeFunction(Class2))
return Class2;
if (typeof Class2 !== "function") {
throw new TypeError("Super expression must either be null or a function");
}
if (typeof _cache !== "undefined") {
if (_cache.has(Class2))
return _cache.get(Class2);
_cache.set(Class2, Wrapper);
}
function Wrapper() {
return _construct(Class2, arguments, _getPrototypeOf(this).constructor);
}
Wrapper.prototype = Object.create(Class2.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } });
return _setPrototypeOf(Wrapper, Class2);
};
return _wrapNativeSuper(Class);
}
function _construct(Parent, args, Class) {
if (_isNativeReflectConstruct()) {
_construct = Reflect.construct.bind();
} else {
_construct = function _construct2(Parent2, args2, Class2) {
var a3 = [null];
a3.push.apply(a3, args2);
var Constructor = Function.bind.apply(Parent2, a3);
var instance = new Constructor();
if (Class2)
_setPrototypeOf(instance, Class2.prototype);
return instance;
};
}
return _construct.apply(null, arguments);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct)
return false;
if (Reflect.construct.sham)
return false;
if (typeof Proxy === "function")
return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
}));
return true;
} catch (e2) {
return false;
}
}
function _isNativeFunction(fn) {
try {
return Function.toString.call(fn).indexOf("[native code]") !== -1;
} catch (e2) {
return typeof fn === "function";
}
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf3(o2, p2) {
o2.__proto__ = p2;
return o2;
};
return _setPrototypeOf(o, p);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf3(o2) {
return o2.__proto__ || Object.getPrototypeOf(o2);
};
return _getPrototypeOf(o);
}
var DetailedError = /* @__PURE__ */ function(_Error) {
_inherits(DetailedError2, _Error);
var _super = _createSuper(DetailedError2);
function DetailedError2(message) {
var _this;
var causingErr = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : null;
var req = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : null;
var res = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : null;
_classCallCheck(this, DetailedError2);
_this = _super.call(this, message);
_this.originalRequest = req;
_this.originalResponse = res;
_this.causingError = causingErr;
if (causingErr != null) {
message += ", caused by ".concat(causingErr.toString());
}
if (req != null) {
var requestId = req.getHeader("X-Request-ID") || "n/a";
var method = req.getMethod();
var url = req.getURL();
var status = res ? res.getStatus() : "n/a";
var body = res ? res.getBody() || "" : "n/a";
message += ", originated from request (method: ".concat(method, ", url: ").concat(url, ", response code: ").concat(status, ", response text: ").concat(body, ", request id: ").concat(requestId, ")");
}
_this.message = message;
return _this;
}
return _createClass(DetailedError2);
}(/* @__PURE__ */ _wrapNativeSuper(Error));
var error_default = DetailedError;
// node_modules/.pnpm/tus-js-client@3.1.3/node_modules/tus-js-client/lib.esm/logger.js
var isEnabled = false;
function log(msg) {
if (!isEnabled)
return;
console.log(msg);
}
// node_modules/.pnpm/tus-js-client@3.1.3/node_modules/tus-js-client/lib.esm/uuid.js
function uuid() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c2) {
var r = Math.random() * 16 | 0;
var v = c2 === "x" ? r : r & 3 | 8;
return v.toString(16);
});
}
// node_modules/.pnpm/tus-js-client@3.1.3/node_modules/tus-js-client/lib.esm/upload.js
function _regeneratorRuntime() {
"use strict";
_regeneratorRuntime = function _regeneratorRuntime3() {
return e2;
};
var t2, e2 = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function(t3, e3, r2) {
t3[e3] = r2.value;
}, i2 = typeof Symbol == "function" ? Symbol : {}, a3 = i2.iterator || "@@iterator", c2 = i2.asyncIterator || "@@asyncIterator", u2 = i2.toStringTag || "@@toStringTag";
function define(t3, e3, r2) {
return Object.defineProperty(t3, e3, { value: r2, enumerable: true, configurable: true, writable: true }), t3[e3];
}
try {
define({}, "");
} catch (t3) {
define = function define2(t4, e3, r2) {
return t4[e3] = r2;
};
}
function wrap(t3, e3, r2, n2) {
var i3 = e3 && e3.prototype instanceof Generator ? e3 : Generator, a4 = Object.create(i3.prototype), c3 = new Context(n2 || []);
return o(a4, "_invoke", { value: makeInvokeMethod(t3, r2, c3) }), a4;
}
function tryCatch(t3, e3, r2) {
try {
return { type: "normal", arg: t3.call(e3, r2) };
} catch (t4) {
return { type: "throw", arg: t4 };
}
}
e2.wrap = wrap;
var h3 = "suspendedStart", l = "suspendedYield", f = "executing", s3 = "completed", y3 = {};
function Generator() {
}
function GeneratorFunction() {
}
function GeneratorFunctionPrototype() {
}
var p = {};
define(p, a3, function() {
return this;
});
var d3 = Object.getPrototypeOf, v = d3 && d3(d3(values([])));
v && v !== r && n.call(v, a3) && (p = v);
var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
function defineIteratorMethods(t3) {
["next", "throw", "return"].forEach(function(e3) {
define(t3, e3, function(t4) {
return this._invoke(e3, t4);
});
});
}
function AsyncIterator(t3, e3) {
function invoke(r3, o2, i3, a4) {
var c3 = tryCatch(t3[r3], t3, o2);
if (c3.type !== "throw") {
var u3 = c3.arg, h4 = u3.value;
return h4 && _typeof3(h4) == "object" && n.call(h4, "__await") ? e3.resolve(h4.__await).then(function(t4) {
invoke("next", t4, i3, a4);
}, function(t4) {
invoke("throw", t4, i3, a4);
}) : e3.resolve(h4).then(function(t4) {
u3.value = t4, i3(u3);
}, function(t4) {
return invoke("throw", t4, i3, a4);
});
}
a4(c3.arg);
}
var r2;
o(this, "_invoke", { value: function value(t4, n2) {
function callInvokeWithMethodAndArg() {
return new e3(function(e4, r3) {
invoke(t4, n2, e4, r3);
});
}
return r2 = r2 ? r2.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
} });
}
function makeInvokeMethod(e3, r2, n2) {
var o2 = h3;
return function(i3, a4) {
if (o2 === f)
throw new Error("Generator is already running");
if (o2 === s3) {
if (i3 === "throw")
throw a4;
return { value: t2, done: true };
}
for (n2.method = i3, n2.arg = a4; ; ) {
var c3 = n2.delegate;
if (c3) {
var u3 = maybeInvokeDelegate(c3, n2);
if (u3) {
if (u3 === y3)
continue;
return u3;
}
}
if (n2.method === "next")
n2.sent = n2._sent = n2.arg;
else if (n2.method === "throw") {
if (o2 === h3)
throw o2 = s3, n2.arg;
n2.dispatchException(n2.arg);
} else
n2.method === "return" && n2.abrupt("return", n2.arg);
o2 = f;
var p2 = tryCatch(e3, r2, n2);
if (p2.type === "normal") {
if (o2 = n2.done ? s3 : l, p2.arg === y3)
continue;
return { value: p2.arg, done: n2.done };
}
p2.type === "throw" && (o2 = s3, n2.method = "throw", n2.arg = p2.arg);
}
};
}
function maybeInvokeDelegate(e3, r2) {
var n2 = r2.method, o2 = e3.iterator[n2];
if (o2 === t2)
return r2.delegate = null, n2 === "throw" && e3.iterator["return"] && (r2.method = "return", r2.arg = t2, maybeInvokeDelegate(e3, r2), r2.method === "throw") || n2 !== "return" && (r2.method = "throw", r2.arg = new TypeError("The iterator does not provide a '" + n2 + "' method")), y3;
var i3 = tryCatch(o2, e3.iterator, r2.arg);
if (i3.type === "throw")
return r2.method = "throw", r2.arg = i3.arg, r2.delegate = null, y3;
var a4 = i3.arg;
return a4 ? a4.done ? (r2[e3.resultName] = a4.value, r2.next = e3.nextLoc, r2.method !== "return" && (r2.method = "next", r2.arg = t2), r2.delegate = null, y3) : a4 : (r2.method = "throw", r2.arg = new TypeError("iterator result is not an object"), r2.delegate = null, y3);
}
function pushTryEntry(t3) {
var e3 = { tryLoc: t3[0] };
1 in t3 && (e3.catchLoc = t3[1]), 2 in t3 && (e3.finallyLoc = t3[2], e3.afterLoc = t3[3]), this.tryEntries.push(e3);
}
function resetTryEntry(t3) {
var e3 = t3.completion || {};
e3.type = "normal", delete e3.arg, t3.completion = e3;
}
function Context(t3) {
this.tryEntries = [{ tryLoc: "root" }], t3.forEach(pushTryEntry, this), this.reset(true);
}
function values(e3) {
if (e3 || e3 === "") {
var r2 = e3[a3];
if (r2)
return r2.call(e3);
if (typeof e3.next == "function")
return e3;
if (!isNaN(e3.length)) {
var o2 = -1, i3 = function next() {
for (; ++o2 < e3.length; )
if (n.call(e3, o2))
return next.value = e3[o2], next.done = false, next;
return next.value = t2, next.done = true, next;
};
return i3.next = i3;
}
}
throw new TypeError(_typeof3(e3) + " is not iterable");
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: true }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: true }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u2, "GeneratorFunction"), e2.isGeneratorFunction = function(t3) {
var e3 = typeof t3 == "function" && t3.constructor;
return !!e3 && (e3 === GeneratorFunction || (e3.displayName || e3.name) === "GeneratorFunction");
}, e2.mark = function(t3) {
return Object.setPrototypeOf ? Object.setPrototypeOf(t3, GeneratorFunctionPrototype) : (t3.__proto__ = GeneratorFunctionPrototype, define(t3, u2, "GeneratorFunction")), t3.prototype = Object.create(g), t3;
}, e2.awrap = function(t3) {
return { __await: t3 };
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c2, function() {
return this;
}), e2.AsyncIterator = AsyncIterator, e2.async = function(t3, r2, n2, o2, i3) {
i3 === void 0 && (i3 = Promise);
var a4 = new AsyncIterator(wrap(t3, r2, n2, o2), i3);
return e2.isGeneratorFunction(r2) ? a4 : a4.next().then(function(t4) {
return t4.done ? t4.value : a4.next();
});
}, defineIteratorMethods(g), define(g, u2, "Generator"), define(g, a3, function() {
return this;
}), define(g, "toString", function() {
return "[object Generator]";
}), e2.keys = function(t3) {
var e3 = Object(t3), r2 = [];
for (var n2 in e3)
r2.push(n2);
return r2.reverse(), function next() {
for (; r2.length; ) {
var t4 = r2.pop();
if (t4 in e3)
return next.value = t4, next.done = false, next;
}
return next.done = true, next;
};
}, e2.values = values, Context.prototype = { constructor: Context, reset: function reset(e3) {
if (this.prev = 0, this.next = 0, this.sent = this._sent = t2, this.done = false, this.delegate = null, this.method = "next", this.arg = t2, this.tryEntries.forEach(resetTryEntry), !e3)
for (var r2 in this)
r2.charAt(0) === "t" && n.call(this, r2) && !isNaN(+r2.slice(1)) && (this[r2] = t2);
}, stop: function stop() {
this.done = true;
var t3 = this.tryEntries[0].completion;
if (t3.type === "throw")
throw t3.arg;
return this.rval;
}, dispatchException: function dispatchException(e3) {
if (this.done)
throw e3;
var r2 = this;
function handle(n2, o3) {
return a4.type = "throw", a4.arg = e3, r2.next = n2, o3 && (r2.method = "next", r2.arg = t2), !!o3;
}
for (var o2 = this.tryEntries.length - 1; o2 >= 0; --o2) {
var i3 = this.tryEntries[o2], a4 = i3.completion;
if (i3.tryLoc === "root")
return handle("end");
if (i3.tryLoc <= this.prev) {
var c3 = n.call(i3, "catchLoc"), u3 = n.call(i3, "finallyLoc");
if (c3 && u3) {
if (this.prev < i3.catchLoc)
return handle(i3.catchLoc, true);
if (this.prev < i3.finallyLoc)
return handle(i3.finallyLoc);
} else if (c3) {
if (this.prev < i3.catchLoc)
return handle(i3.catchLoc, true);
} else {
if (!u3)
throw new Error("try statement without catch or finally");
if (this.prev < i3.finallyLoc)
return handle(i3.finallyLoc);
}
}
}
}, abrupt: function abrupt(t3, e3) {
for (var r2 = this.tryEntries.length - 1; r2 >= 0; --r2) {
var o2 = this.tryEntries[r2];
if (o2.tryLoc <= this.prev && n.call(o2, "finallyLoc") && this.prev < o2.finallyLoc) {
var i3 = o2;
break;
}
}
i3 && (t3 === "break" || t3 === "continue") && i3.tryLoc <= e3 && e3 <= i3.finallyLoc && (i3 = null);
var a4 = i3 ? i3.completion : {};
return a4.type = t3, a4.arg = e3, i3 ? (this.method = "next", this.next = i3.finallyLoc, y3) : this.complete(a4);
}, complete: function complete(t3, e3) {
if (t3.type === "throw")
throw t3.arg;
return t3.type === "break" || t3.type === "continue" ? this.next = t3.arg : t3.type === "return" ? (this.rval = this.arg = t3.arg, this.method = "return", this.next = "end") : t3.type === "normal" && e3 && (this.next = e3), y3;
}, finish: function finish(t3) {
for (var e3 = this.tryEntries.length - 1; e3 >= 0; --e3) {
var r2 = this.tryEntries[e3];
if (r2.finallyLoc === t3)
return this.complete(r2.completion, r2.afterLoc), resetTryEntry(r2), y3;
}
}, "catch": function _catch(t3) {
for (var e3 = this.tryEntries.length - 1; e3 >= 0; --e3) {
var r2 = this.tryEntries[e3];
if (r2.tryLoc === t3) {
var n2 = r2.completion;
if (n2.type === "throw") {
var o2 = n2.arg;
resetTryEntry(r2);
}
return o2;
}
}
throw new Error("illegal catch attempt");
}, delegateYield: function delegateYield(e3, r2, n2) {
return this.delegate = { iterator: values(e3), resultName: r2, nextLoc: n2 }, this.method === "next" && (this.arg = t2), y3;
} }, e2;
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function() {
var self2 = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self2, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(void 0);
});
};
}
function _slicedToArray(arr, i2) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i2) || _unsupportedIterableToArray(arr, i2) || _nonIterableRest();
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray(o, minLen) {
if (!o)
return;
if (typeof o === "string")
return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor)
n = o.constructor.name;
if (n === "Map" || n === "Set")
return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len2) {
if (len2 == null || len2 > arr.length)
len2 = arr.length;
for (var i2 = 0, arr2 = new Array(len2); i2 < len2; i2++)
arr2[i2] = arr[i2];
return arr2;
}
function _iterableToArrayLimit(r, l) {
var t2 = r == null ? null : typeof Symbol != "undefined" && r[Symbol.iterator] || r["@@iterator"];
if (t2 != null) {
var e2, n, i2, u2, a3 = [], f = true, o = false;
try {
if (i2 = (t2 = t2.call(r)).next, l === 0) {
if (Object(t2) !== t2)
return;
f = false;
} else
for (; !(f = (e2 = i2.call(t2)).done) && (a3.push(e2.value), a3.length !== l); f = true)
;
} catch (r2) {
o = true, n = r2;
} finally {
try {
if (!f && t2["return"] != null && (u2 = t2["return"](), Object(u2) !== u2))
return;
} finally {
if (o)
throw n;
}
}
return a3;
}
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr))
return arr;
}
function _typeof3(o) {
"@babel/helpers - typeof";
return _typeof3 = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(o2) {
return typeof o2;
} : function(o2) {
return o2 && typeof Symbol == "function" && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
}, _typeof3(o);
}
function ownKeys(e2, r) {
var t2 = Object.keys(e2);
if (Object.getOwnPropertySymbols) {
var o = Object.getOwnPropertySymbols(e2);
r && (o = o.filter(function(r2) {
return Object.getOwnPropertyDescriptor(e2, r2).enumerable;
})), t2.push.apply(t2, o);
}
return t2;
}
function _objectSpread(e2) {
for (var r = 1; r < arguments.length; r++) {
var t2 = arguments[r] != null ? arguments[r] : {};
r % 2 ? ownKeys(Object(t2), true).forEach(function(r2) {
_defineProperty(e2, r2, t2[r2]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e2, Object.getOwnPropertyDescriptors(t2)) : ownKeys(Object(t2)).forEach(function(r2) {
Object.defineProperty(e2, r2, Object.getOwnPropertyDescriptor(t2, r2));
});
}
return e2;
}
function _defineProperty(obj, key, value) {
key = _toPropertyKey2(key);
if (key in obj) {
Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
} else {
obj[key] = value;
}
return obj;
}
function _classCallCheck2(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties2(target, props) {
for (var i2 = 0; i2 < props.length; i2++) {
var descriptor = props[i2];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor)
descriptor.writable = true;
Object.defineProperty(target, _toPropertyKey2(descriptor.key), descriptor);
}
}
function _createClass2(Constructor, protoProps, staticProps) {
if (protoProps)
_defineProperties2(Constructor.prototype, protoProps);
if (staticProps)
_defineProperties2(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _toPropertyKey2(arg) {
var key = _toPrimitive2(arg, "string");
return _typeof3(key) === "symbol" ? key : String(key);
}
function _toPrimitive2(input, hint) {
if (_typeof3(input) !== "object" || input === null)
return input;
var prim = input[Symbol.toPrimitive];
if (prim !== void 0) {
var res = prim.call(input, hint || "default");
if (_typeof3(res) !== "object")
return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
var defaultOptions2 = {
endpoint: null,
uploadUrl: null,
metadata: {},
fingerprint: null,
uploadSize: null,
onProgress: null,
onChunkComplete: null,
onSuccess: null,
onError: null,
onUploadUrlAvailable: null,
overridePatchMethod: false,
headers: {},
addRequestId: false,
onBeforeRequest: null,
onAfterResponse: null,
onShouldRetry: defaultOnShouldRetry,
chunkSize: Infinity,
retryDelays: [0, 1e3, 3e3, 5e3],
parallelUploads: 1,
parallelUploadBoundaries: null,
storeFingerprintForResuming: true,
removeFingerprintOnSuccess: false,
uploadLengthDeferred: false,
uploadDataDuringCreation: false,
urlStorage: null,
fileReader: null,
httpStack: null
};
var BaseUpload = /* @__PURE__ */ function() {
function BaseUpload2(file, options) {
_classCallCheck2(this, BaseUpload2);
if ("resume" in options) {
console.log("tus: The `resume` option has been removed in tus-js-client v2. Please use the URL storage API instead.");
}
this.options = options;
this.options.chunkSize = Number(this.options.chunkSize);
this._urlStorage = this.options.urlStorage;
this.file = file;
this.url = null;
this._req = null;
this._fingerprint = null;
this._urlStorageKey = null;
this._offset = null;
this._aborted = false;
this._size = null;
this._source = null;
this._retryAttempt = 0;
this._retryTimeout = null;
this._offsetBeforeRetry = 0;
this._parallelUploads = null;
this._parallelUploadUrls = null;
}
_createClass2(BaseUpload2, [{
key: "findPreviousUploads",
value: function findPreviousUploads() {
var _this = this;
return this.options.fingerprint(this.file, this.options).then(function(fingerprint2) {
return _this._urlStorage.findUploadsByFingerprint(fingerprint2);
});
}
}, {
key: "resumeFromPreviousUpload",
value: function resumeFromPreviousUpload(previousUpload) {
this.url = previousUpload.uploadUrl || null;
this._parallelUploadUrls = previousUpload.parallelUploadUrls || null;
this._urlStorageKey = previousUpload.urlStorageKey;
}
}, {
key: "start",
value: function start() {
var _this2 = this;
var file = this.file;
if (!file) {
this._emitError(new Error("tus: no file or stream to upload provided"));
return;
}
if (!this.options.endpoint && !this.options.uploadUrl && !this.url) {
this._emitError(new Error("tus: neither an endpoint or an upload URL is provided"));
return;
}
var retryDelays = this.options.retryDelays;
if (retryDelays != null && Object.prototype.toString.call(retryDelays) !== "[object Array]") {
this._emitError(new Error("tus: the `retryDelays` option must either be an array or null"));
return;
}
if (this.options.parallelUploads > 1) {
for (var _i = 0, _arr = ["uploadUrl", "uploadSize", "uploadLengthDeferred"]; _i < _arr.length; _i++) {
var optionName = _arr[_i];
if (this.options[optionName]) {
this._emitError(new Error("tus: cannot use the ".concat(optionName, " option when parallelUploads is enabled")));
return;
}
}
}
if (this.options.parallelUploadBoundaries) {
if (this.options.parallelUploads <= 1) {
this._emitError(new Error("tus: cannot use the `parallelUploadBoundaries` option when `parallelUploads` is disabled"));
return;
}
if (this.options.parallelUploads !== this.options.parallelUploadBoundaries.length) {
this._emitError(new Error("tus: the `parallelUploadBoundaries` must have the same length as the value of `parallelUploads`"));
return;
}
}
this.options.fingerprint(file, this.options).then(function(fingerprint2) {
if (fingerprint2 == null) {
log("No fingerprint was calculated meaning that the upload cannot be stored in the URL storage.");
} else {
log("Calculated fingerprint: ".concat(fingerprint2));
}
_this2._fingerprint = fingerprint2;
if (_this2._source) {
return _this2._source;
}
return _this2.options.fileReader.openFile(file, _this2.options.chunkSize);
}).then(function(source) {
_this2._source = source;
if (_this2.options.uploadLengthDeferred) {
_this2._size = null;
} else if (_this2.options.uploadSize != null) {
_this2._size = Number(_this2.options.uploadSize);
if (Number.isNaN(_this2._size)) {
_this2._emitError(new Error("tus: cannot convert `uploadSize` option into a number"));
return;
}
} else {
_this2._size = _this2._source.size;
if (_this2._size == null) {
_this2._emitError(new Error("tus: cannot automatically derive upload's size from input. Specify it manually using the `uploadSize` option or use the `uploadLengthDeferred` option"));
return;
}
}
if (_this2.options.parallelUploads > 1 || _this2._parallelUploadUrls != null) {
_this2._startParallelUpload();
} else {
_this2._startSingleUpload();
}
})["catch"](function(err) {
_this2._emitError(err);
});
}
}, {
key: "_startParallelUpload",
value: function _startParallelUpload() {
var _this$options$paralle, _this3 = this;
var totalSize = this._size;
var totalProgress = 0;
this._parallelUploads = [];
var partCount = this._parallelUploadUrls != null ? this._parallelUploadUrls.length : this.options.parallelUploads;
var parts = (_this$options$paralle = this.options.parallelUploadBoundaries) !== null && _this$options$paralle !== void 0 ? _this$options$paralle : splitSizeIntoParts(this._source.size, partCount);
if (this._parallelUploadUrls) {
parts.forEach(function(part, index) {
part.uploadUrl = _this3._parallelUploadUrls[index] || null;
});
}
this._parallelUploadUrls = new Array(parts.length);
var uploads = parts.map(function(part, index) {
var lastPartProgress = 0;
return _this3._source.slice(part.start, part.end).then(function(_ref) {
var value = _ref.value;
return new Promise(function(resolve, reject) {
var options = _objectSpread(_objectSpread({}, _this3.options), {}, {
uploadUrl: part.uploadUrl || null,
storeFingerprintForResuming: false,
removeFingerprintOnSuccess: false,
parallelUploads: 1,
parallelUploadBoundaries: null,
metadata: {},
headers: _objectSpread(_objectSpread({}, _this3.options.headers), {}, {
"Upload-Concat": "partial"
}),
onSuccess: resolve,
onError: reject,
onProgress: function onProgress(newPartProgress) {
totalProgress = totalProgress - lastPartProgress + newPartProgress;
lastPartProgress = newPartProgress;
_this3._emitProgress(totalProgress, totalSize);
},
onUploadUrlAvailable: function onUploadUrlAvailable() {
_this3._parallelUploadUrls[index] = upload.url;
if (_this3._parallelUploadUrls.filter(function(u2) {
return Boolean(u2);
}).length === parts.length) {
_this3._saveUploadInUrlStorage();
}
}
});
var upload = new BaseUpload2(value, options);
upload.start();
_this3._parallelUploads.push(upload);
});
});
});
var req;
Promise.all(uploads).then(function() {
req = _this3._openRequest("POST", _this3.options.endpoint);
req.setHeader("Upload-Concat", "final;".concat(_this3._parallelUploadUrls.join(" ")));
var metadata = encodeMetadata(_this3.options.metadata);
if (metadata !== "") {
req.setHeader("Upload-Metadata", metadata);
}
return _this3._sendRequest(req, null);
}).then(function(res) {
if (!inStatusCategory(res.getStatus(), 200)) {
_this3._emitHttpError(req, res, "tus: unexpected response while creating upload");
return;
}
var location = res.getHeader("Location");
if (location == null) {
_this3._emitHttpError(req, res, "tus: invalid or missing Location header");
return;
}
_this3.url = resolveUrl(_this3.options.endpoint, location);
log("Created upload at ".concat(_this3.url));
_this3._emitSuccess();
})["catch"](function(err) {
_this3._emitError(err);
});
}
}, {
key: "_startSingleUpload",
value: function _startSingleUpload() {
this._aborted = false;
if (this.url != null) {
log("Resuming upload from previous URL: ".concat(this.url));
this._resumeUpload();
return;
}
if (this.options.uploadUrl != null) {
log("Resuming upload from provided URL: ".concat(this.options.uploadUrl));
this.url = this.options.uploadUrl;
this._resumeUpload();
return;
}
log("Creating a new upload");
this._createUpload();
}
}, {
key: "abort",
value: function abort(shouldTerminate) {
var _this4 = this;
if (this._parallelUploads != null) {
this._parallelUploads.forEach(function(upload) {
upload.abort(shouldTerminate);
});
}
if (this._req !== null) {
this._req.abort();
}
this._aborted = true;
if (this._retryTimeout != null) {
clearTimeout(this._retryTimeout);
this._retryTimeout = null;
}
if (!shouldTerminate || this.url == null) {
return Promise.resolve();
}
return BaseUpload2.terminate(this.url, this.options).then(function() {
return _this4._removeFromUrlStorage();
});
}
}, {
key: "_emitHttpError",
value: function _emitHttpError(req, res, message, causingErr) {
this._emitError(new error_default(message, causingErr, req, res));
}
}, {
key: "_emitError",
value: function _emitError(err) {
var _this5 = this;
if (this._aborted)
return;
if (this.options.retryDelays != null) {
var shouldResetDelays = this._offset != null && this._offset > this._offsetBeforeRetry;
if (shouldResetDelays) {
this._retryAttempt = 0;
}
if (shouldRetry(err, this._retryAttempt, this.options)) {
var delay = this.options.retryDelays[this._retryAttempt++];
this._offsetBeforeRetry = this._offset;
this._retryTimeout = setTimeout(function() {
_this5.start();
}, delay);
return;
}
}
if (typeof this.options.onError === "function") {
this.options.onError(err);
} else {
throw err;
}
}
}, {
key: "_emitSuccess",
value: function _emitSuccess() {
if (this.options.removeFingerprintOnSuccess) {
this._removeFromUrlStorage();
}
if (typeof this.options.onSuccess === "function") {
this.options.onSuccess();
}
}
}, {
key: "_emitProgress",
value: function _emitProgress(bytesSent, bytesTotal) {
if (typeof this.options.onProgress === "function") {
this.options.onProgress(bytesSent, bytesTotal);
}
}
}, {
key: "_emitChunkComplete",
value: function _emitChunkComplete(chunkSize, bytesAccepted, bytesTotal) {
if (typeof this.options.onChunkComplete === "function") {
this.options.onChunkComplete(chunkSize, bytesAccepted, bytesTotal);
}
}
}, {
key: "_createUpload",
value: function _createUpload() {
var _this6 = this;
if (!this.options.endpoint) {
this._emitError(new Error("tus: unable to create upload because no endpoint is provided"));
return;
}
var req = this._openRequest("POST", this.options.endpoint);
if (this.options.uploadLengthDeferred) {
req.setHeader("Upload-Defer-Length", 1);
} else {
req.setHeader("Upload-Length", this._size);
}
var metadata = encodeMetadata(this.options.metadata);
if (metadata !== "") {
req.setHeader("Upload-Metadata", metadata);
}
var promise;
if (this.options.uploadDataDuringCreation && !this.options.uploadLengthDeferred) {
this._offset = 0;
promise = this._addChunkToRequest(req);
} else {
promise = this._sendRequest(req, null);
}
promise.then(function(res) {
if (!inStatusCategory(res.getStatus(), 200)) {
_this6._emitHttpError(req, res, "tus: unexpected response while creating upload");
return;
}
var location = res.getHeader("Location");
if (location == null) {
_this6._emitHttpError(req, res, "tus: invalid or missing Location header");
return;
}
_this6.url = resolveUrl(_this6.options.endpoint, location);
log("Created upload at ".concat(_this6.url));
if (typeof _this6.options.onUploadUrlAvailable === "function") {
_this6.options.onUploadUrlAvailable();
}
if (_this6._size === 0) {
_this6._emitSuccess();
_this6._source.close();
return;
}
_this6._saveUploadInUrlStorage().then(function() {
if (_this6.options.uploadDataDuringCreation) {
_this6._handleUploadResponse(req, res);
} else {
_this6._offset = 0;
_this6._performUpload();
}
});
})["catch"](function(err) {
_this6._emitHttpError(req, null, "tus: failed to create upload", err);
});
}
}, {
key: "_resumeUpload",
value: function _resumeUpload() {
var _this7 = this;
var req = this._openRequest("HEAD", this.url);
var promise = this._sendRequest(req, null);
promise.then(function(res) {
var status = res.getStatus();
if (!inStatusCategory(status, 200)) {
if (status === 423) {
_this7._emitHttpError(req, res, "tus: upload is currently locked; retry later");
return;
}
if (inStatusCategory(status, 400)) {
_this7._removeFromUrlStorage();
}
if (!_this7.options.endpoint) {
_this7._emitHttpError(req, res, "tus: unable to resume upload (new upload cannot be created without an endpoint)");
return;
}
_this7.url = null;
_this7._createUpload();
return;
}
var offset = parseInt(res.getHeader("Upload-Offset"), 10);
if (Number.isNaN(offset)) {
_this7._emitHttpError(req, res, "tus: invalid or missing offset value");
return;
}
var length = parseInt(res.getHeader("Upload-Length"), 10);
if (Number.isNaN(length) && !_this7.options.uploadLengthDeferred) {
_this7._emitHttpError(req, res, "tus: invalid or missing length value");
return;
}
if (typeof _this7.options.onUploadUrlAvailable === "function") {
_this7.options.onUploadUrlAvailable();
}
_this7._saveUploadInUrlStorage().then(function() {
if (offset === length) {
_this7._emitProgress(length, length);
_this7._emitSuccess();
return;
}
_this7._offset = offset;
_this7._performUpload();
});
})["catch"](function(err) {
_this7._emitHttpError(req, null, "tus: failed to resume upload", err);
});
}
}, {
key: "_performUpload",
value: function _performUpload() {
var _this8 = this;
if (this._aborted) {
return;
}
var req;
if (this.options.overridePatchMethod) {
req = this._openRequest("POST", this.url);
req.setHeader("X-HTTP-Method-Override", "PATCH");
} else {
req = this._openRequest("PATCH", this.url);
}
req.setHeader("Upload-Offset", this._offset);
var promise = this._addChunkToRequest(req);
promise.then(function(res) {
if (!inStatusCategory(res.getStatus(), 200)) {
_this8._emitHttpError(req, res, "tus: unexpected response while uploading chunk");
return;
}
_this8._handleUploadResponse(req, res);
})["catch"](function(err) {
if (_this8._aborted) {
return;
}
_this8._emitHttpError(req, null, "tus: failed to upload chunk at offset ".concat(_this8._offset), err);
});
}
}, {
key: "_addChunkToRequest",
value: function _addChunkToRequest(req) {
var _this9 = this;
var start = this._offset;
var end = this._offset + this.options.chunkSize;
req.setProgressHandler(function(bytesSent) {
_this9._emitProgress(start + bytesSent, _this9._size);
});
req.setHeader("Content-Type", "application/offset+octet-stream");
if ((end === Infinity || end > this._size) && !this.options.uploadLengthDeferred) {
end = this._size;
}
return this._source.slice(start, end).then(function(_ref2) {
var value = _ref2.value, done = _ref2.done;
var valueSize = value && value.size ? value.size : 0;
if (_this9.options.uploadLengthDeferred && done) {
_this9._size = _this9._offset + valueSize;
req.setHeader("Upload-Length", _this9._size);
}
var newSize = _this9._offset + valueSize;
if (!_this9.options.uploadLengthDeferred && done && newSize !== _this9._size) {
return Promise.reject(new Error("upload was configured with a size of ".concat(_this9._size, " bytes, but the source is done after ").concat(newSize, " bytes")));
}
if (value === null) {
return _this9._sendRequest(req);
}
_this9._emitProgress(_this9._offset, _this9._size);
return _this9._sendRequest(req, value);
});
}
}, {
key: "_handleUploadResponse",
value: function _handleUploadResponse(req, res) {
var offset = parseInt(res.getHeader("Upload-Offset"), 10);
if (Number.isNaN(offset)) {
this._emitHttpError(req, res, "tus: invalid or missing offset value");
return;
}
this._emitProgress(offset, this._size);
this._emitChunkComplete(offset - this._offset, offset, this._size);
this._offset = offset;
if (offset === this._size) {
this._emitSuccess();
this._source.close();
return;
}
this._performUpload();
}
}, {
key: "_openRequest",
value: function _openRequest(method, url) {
var req = openRequest(method, url, this.options);
this._req = req;
return req;
}
}, {
key: "_removeFromUrlStorage",
value: function _removeFromUrlStorage() {
var _this10 = this;
if (!this._urlStorageKey)
return;
this._urlStorage.removeUpload(this._urlStorageKey)["catch"](function(err) {
_this10._emitError(err);
});
this._urlStorageKey = null;
}
}, {
key: "_saveUploadInUrlStorage",
value: function _saveUploadInUrlStorage() {
var _this11 = this;
if (!this.options.storeFingerprintForResuming || !this._fingerprint || this._urlStorageKey !== null) {
return Promise.resolve();
}
var storedUpload = {
size: this._size,
metadata: this.options.metadata,
creationTime: new Date().toString()
};
if (this._parallelUploads) {
storedUpload.parallelUploadUrls = this._parallelUploadUrls;
} else {
storedUpload.uploadUrl = this.url;
}
return this._urlStorage.addUpload(this._fingerprint, storedUpload).then(function(urlStorageKey) {
_this11._urlStorageKey = urlStorageKey;
});
}
}, {
key: "_sendRequest",
value: function _sendRequest(req) {
var body = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : null;
return sendRequest(req, body, this.options);
}
}], [{
key: "terminate",
value: function terminate(url) {
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
var req = openRequest("DELETE", url, options);
return sendRequest(req, null, options).then(function(res) {
if (res.getStatus() === 204) {
return;
}
throw new error_default("tus: unexpected response while terminating upload", null, req, res);
})["catch"](function(err) {
if (!(err instanceof error_default)) {
err = new error_default("tus: failed to terminate upload", err, req, null);
}
if (!shouldRetry(err, 0, options)) {
throw err;
}
var delay = options.retryDelays[0];
var remainingDelays = options.retryDelays.slice(1);
var newOptions = _objectSpread(_objectSpread({}, options), {}, {
retryDelays: remainingDelays
});
return new Promise(function(resolve) {
return setTimeout(resolve, delay);
}).then(function() {
return BaseUpload2.terminate(url, newOptions);
});
});
}
}]);
return BaseUpload2;
}();
function encodeMetadata(metadata) {
return Object.entries(metadata).map(function(_ref3) {
var _ref4 = _slicedToArray(_ref3, 2), key = _ref4[0], value = _ref4[1];
return "".concat(key, " ").concat(gBase64.encode(String(value)));
}).join(",");
}
function inStatusCategory(status, category) {
return status >= category && status < category + 100;
}
function openRequest(method, url, options) {
var req = options.httpStack.createRequest(method, url);
req.setHeader("Tus-Resumable", "1.0.0");
var headers = options.headers || {};
Object.entries(headers).forEach(function(_ref5) {
var _ref6 = _slicedToArray(_ref5, 2), name = _ref6[0], value = _ref6[1];
req.setHeader(name, value);
});
if (options.addRequestId) {
var requestId = uuid();
req.setHeader("X-Request-ID", requestId);
}
return req;
}
function sendRequest(_x, _x2, _x3) {
return _sendRequest2.apply(this, arguments);
}
function _sendRequest2() {
_sendRequest2 = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(function _callee(req, body, options) {
var res;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1)
switch (_context.prev = _context.next) {
case 0:
if (!(typeof options.onBeforeRequest === "function")) {
_context.next = 3;
break;
}
_context.next = 3;
return options.onBeforeRequest(req);
case 3:
_context.next = 5;
return req.send(body);
case 5:
res = _context.sent;
if (!(typeof options.onAfterResponse === "function")) {
_context.next = 9;
break;
}
_context.next = 9;
return options.onAfterResponse(req, res);
case 9:
return _context.abrupt("return", res);
case 10:
case "end":
return _context.stop();
}
}, _callee);
}));
return _sendRequest2.apply(this, arguments);
}
function isOnline() {
var online = true;
if (typeof window !== "undefined" && "navigator" in window && window.navigator.onLine === false) {
online = false;
}
return online;
}
function shouldRetry(err, retryAttempt, options) {
if (options.retryDelays == null || retryAttempt >= options.retryDelays.length || err.originalRequest == null) {
return false;
}
if (options && typeof options.onShouldRetry === "function") {
return options.onShouldRetry(err, retryAttempt, options);
}
return defaultOnShouldRetry(err);
}
function defaultOnShouldRetry(err) {
var status = err.originalResponse ? err.originalResponse.getStatus() : 0;
return (!inStatusCategory(status, 400) || status === 409 || status === 423) && isOnline();
}
function resolveUrl(origin, link) {
return new import_url_parse.default(link, origin).toString();
}
function splitSizeIntoParts(totalSize, partCount) {
var partSize = Math.floor(totalSize / partCount);
var parts = [];
for (var i2 = 0; i2 < partCount; i2++) {
parts.push({
start: partSize * i2,
end: partSize * (i2 + 1)
});
}
parts[partCount - 1].end = totalSize;
return parts;
}
BaseUpload.defaultOptions = defaultOptions2;
var upload_default = BaseUpload;
// node_modules/.pnpm/tus-js-client@3.1.3/node_modules/tus-js-client/lib.esm/noopUrlStorage.js
function _typeof4(o) {
"@babel/helpers - typeof";
return _typeof4 = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(o2) {
return typeof o2;
} : function(o2) {
return o2 && typeof Symbol == "function" && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
}, _typeof4(o);
}
function _classCallCheck3(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties3(target, props) {
for (var i2 = 0; i2 < props.length; i2++) {
var descriptor = props[i2];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor)
descriptor.writable = true;
Object.defineProperty(target, _toPropertyKey3(descriptor.key), descriptor);
}
}
function _createClass3(Constructor, protoProps, staticProps) {
if (protoProps)
_defineProperties3(Constructor.prototype, protoProps);
if (staticProps)
_defineProperties3(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _toPropertyKey3(arg) {
var key = _toPrimitive3(arg, "string");
return _typeof4(key) === "symbol" ? key : String(key);
}
function _toPrimitive3(input, hint) {
if (_typeof4(input) !== "object" || input === null)
return input;
var prim = input[Symbol.toPrimitive];
if (prim !== void 0) {
var res = prim.call(input, hint || "default");
if (_typeof4(res) !== "object")
return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
var NoopUrlStorage = /* @__PURE__ */ function() {
function NoopUrlStorage2() {
_classCallCheck3(this, NoopUrlStorage2);
}
_createClass3(NoopUrlStorage2, [{
key: "listAllUploads",
value: function listAllUploads() {
return Promise.resolve([]);
}
}, {
key: "findUploadsByFingerprint",
value: function findUploadsByFingerprint(fingerprint2) {
return Promise.resolve([]);
}
}, {
key: "removeUpload",
value: function removeUpload(urlStorageKey) {
return Promise.resolve();
}
}, {
key: "addUpload",
value: function addUpload(fingerprint2, upload) {
return Promise.resolve(null);
}
}]);
return NoopUrlStorage2;
}();
// node_modules/.pnpm/tus-js-client@3.1.3/node_modules/tus-js-client/lib.esm/browser/urlStorage.js
function _typeof5(o) {
"@babel/helpers - typeof";
return _typeof5 = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(o2) {
return typeof o2;
} : function(o2) {
return o2 && typeof Symbol == "function" && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
}, _typeof5(o);
}
function _classCallCheck4(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties4(target, props) {
for (var i2 = 0; i2 < props.length; i2++) {
var descriptor = props[i2];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor)
descriptor.writable = true;
Object.defineProperty(target, _toPropertyKey4(descriptor.key), descriptor);
}
}
function _createClass4(Constructor, protoProps, staticProps) {
if (protoProps)
_defineProperties4(Constructor.prototype, protoProps);
if (staticProps)
_defineProperties4(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _toPropertyKey4(arg) {
var key = _toPrimitive4(arg, "string");
return _typeof5(key) === "symbol" ? key : String(key);
}
function _toPrimitive4(input, hint) {
if (_typeof5(input) !== "object" || input === null)
return input;
var prim = input[Symbol.toPrimitive];
if (prim !== void 0) {
var res = prim.call(input, hint || "default");
if (_typeof5(res) !== "object")
return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
var hasStorage = false;
try {
hasStorage = "localStorage" in window;
key = "tusSupport";
originalValue = localStorage.getItem(key);
localStorage.setItem(key, originalValue);
if (originalValue === null)
localStorage.removeItem(key);
} catch (e2) {
if (e2.code === e2.SECURITY_ERR || e2.code === e2.QUOTA_EXCEEDED_ERR) {
hasStorage = false;
} else {
throw e2;
}
}
var key;
var originalValue;
var canStoreURLs = hasStorage;
var WebStorageUrlStorage = /* @__PURE__ */ function() {
function WebStorageUrlStorage2() {
_classCallCheck4(this, WebStorageUrlStorage2);
}
_createClass4(WebStorageUrlStorage2, [{
key: "findAllUploads",
value: function findAllUploads() {
var results = this._findEntries("tus::");
return Promise.resolve(results);
}
}, {
key: "findUploadsByFingerprint",
value: function findUploadsByFingerprint(fingerprint2) {
var results = this._findEntries("tus::".concat(fingerprint2, "::"));
return Promise.resolve(results);
}
}, {
key: "removeUpload",
value: function removeUpload(urlStorageKey) {
localStorage.removeItem(urlStorageKey);
return Promise.resolve();
}
}, {
key: "addUpload",
value: function addUpload(fingerprint2, upload) {
var id = Math.round(Math.random() * 1e12);
var key = "tus::".concat(fingerprint2, "::").concat(id);
localStorage.setItem(key, JSON.stringify(upload));
return Promise.resolve(key);
}
}, {
key: "_findEntries",
value: function _findEntries(prefix) {
var results = [];
for (var i2 = 0; i2 < localStorage.length; i2++) {
var _key = localStorage.key(i2);
if (_key.indexOf(prefix) !== 0)
continue;
try {
var upload = JSON.parse(localStorage.getItem(_key));
upload.urlStorageKey = _key;
results.push(upload);
} catch (e2) {
}
}
return results;
}
}]);
return WebStorageUrlStorage2;
}();
// node_modules/.pnpm/tus-js-client@3.1.3/node_modules/tus-js-client/lib.esm/browser/httpStack.js
function _typeof6(o) {
"@babel/helpers - typeof";
return _typeof6 = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(o2) {
return typeof o2;
} : function(o2) {
return o2 && typeof Symbol == "function" && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
}, _typeof6(o);
}
function _classCallCheck5(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties5(target, props) {
for (var i2 = 0; i2 < props.length; i2++) {
var descriptor = props[i2];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor)
descriptor.writable = true;
Object.defineProperty(target, _toPropertyKey5(descriptor.key), descriptor);
}
}
function _createClass5(Constructor, protoProps, staticProps) {
if (protoProps)
_defineProperties5(Constructor.prototype, protoProps);
if (staticProps)
_defineProperties5(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _toPropertyKey5(arg) {
var key = _toPrimitive5(arg, "string");
return _typeof6(key) === "symbol" ? key : String(key);
}
function _toPrimitive5(input, hint) {
if (_typeof6(input) !== "object" || input === null)
return input;
var prim = input[Symbol.toPrimitive];
if (prim !== void 0) {
var res = prim.call(input, hint || "default");
if (_typeof6(res) !== "object")
return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
var XHRHttpStack = /* @__PURE__ */ function() {
function XHRHttpStack2() {
_classCallCheck5(this, XHRHttpStack2);
}
_createClass5(XHRHttpStack2, [{
key: "createRequest",
value: function createRequest(method, url) {
return new Request(method, url);
}
}, {
key: "getName",
value: function getName() {
return "XHRHttpStack";
}
}]);
return XHRHttpStack2;
}();
var Request = /* @__PURE__ */ function() {
function Request3(method, url) {
_classCallCheck5(this, Request3);
this._xhr = new XMLHttpRequest();
this._xhr.open(method, url, true);
this._method = method;
this._url = url;
this._headers = {};
}
_createClass5(Request3, [{
key: "getMethod",
value: function getMethod() {
return this._method;
}
}, {
key: "getURL",
value: function getURL() {
return this._url;
}
}, {
key: "setHeader",
value: function setHeader(header, value) {
this._xhr.setRequestHeader(header, value);
this._headers[header] = value;
}
}, {
key: "getHeader",
value: function getHeader(header) {
return this._headers[header];
}
}, {
key: "setProgressHandler",
value: function setProgressHandler(progressHandler) {
if (!("upload" in this._xhr)) {
return;
}
this._xhr.upload.onprogress = function(e2) {
if (!e2.lengthComputable) {
return;
}
progressHandler(e2.loaded);
};
}
}, {
key: "send",
value: function send() {
var _this = this;
var body = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : null;
return new Promise(function(resolve, reject) {
_this._xhr.onload = function() {
resolve(new Response2(_this._xhr));
};
_this._xhr.onerror = function(err) {
reject(err);
};
_this._xhr.send(body);
});
}
}, {
key: "abort",
value: function abort() {
this._xhr.abort();
return Promise.resolve();
}
}, {
key: "getUnderlyingObject",
value: function getUnderlyingObject() {
return this._xhr;
}
}]);
return Request3;
}();
var Response2 = /* @__PURE__ */ function() {
function Response4(xhr) {
_classCallCheck5(this, Response4);
this._xhr = xhr;
}
_createClass5(Response4, [{
key: "getStatus",
value: function getStatus() {
return this._xhr.status;
}
}, {
key: "getHeader",
value: function getHeader(header) {
return this._xhr.getResponseHeader(header);
}
}, {
key: "getBody",
value: function getBody() {
return this._xhr.responseText;
}
}, {
key: "getUnderlyingObject",
value: function getUnderlyingObject() {
return this._xhr;
}
}]);
return Response4;
}();
// node_modules/.pnpm/tus-js-client@3.1.3/node_modules/tus-js-client/lib.esm/browser/isReactNative.js
var isReactNative = function isReactNative2() {
return typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
};
var isReactNative_default = isReactNative;
// node_modules/.pnpm/tus-js-client@3.1.3/node_modules/tus-js-client/lib.esm/browser/uriToBlob.js
function uriToBlob(uri) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.responseType = "blob";
xhr.onload = function() {
var blob = xhr.response;
resolve(blob);
};
xhr.onerror = function(err) {
reject(err);
};
xhr.open("GET", uri);
xhr.send();
});
}
// node_modules/.pnpm/tus-js-client@3.1.3/node_modules/tus-js-client/lib.esm/browser/sources/isCordova.js
var isCordova = function isCordova2() {
return typeof window !== "undefined" && (typeof window.PhoneGap !== "undefined" || typeof window.Cordova !== "undefined" || typeof window.cordova !== "undefined");
};
var isCordova_default = isCordova;
// node_modules/.pnpm/tus-js-client@3.1.3/node_modules/tus-js-client/lib.esm/browser/sources/readAsByteArray.js
function readAsByteArray(chunk) {
return new Promise(function(resolve, reject) {
var reader = new FileReader();
reader.onload = function() {
var value = new Uint8Array(reader.result);
resolve({
value
});
};
reader.onerror = function(err) {
reject(err);
};
reader.readAsArrayBuffer(chunk);
});
}
// node_modules/.pnpm/tus-js-client@3.1.3/node_modules/tus-js-client/lib.esm/browser/sources/FileSource.js
function _typeof7(o) {
"@babel/helpers - typeof";
return _typeof7 = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(o2) {
return typeof o2;
} : function(o2) {
return o2 && typeof Symbol == "function" && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
}, _typeof7(o);
}
function _classCallCheck6(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties6(target, props) {
for (var i2 = 0; i2 < props.length; i2++) {
var descriptor = props[i2];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor)
descriptor.writable = true;
Object.defineProperty(target, _toPropertyKey6(descriptor.key), descriptor);
}
}
function _createClass6(Constructor, protoProps, staticProps) {
if (protoProps)
_defineProperties6(Constructor.prototype, protoProps);
if (staticProps)
_defineProperties6(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _toPropertyKey6(arg) {
var key = _toPrimitive6(arg, "string");
return _typeof7(key) === "symbol" ? key : String(key);
}
function _toPrimitive6(input, hint) {
if (_typeof7(input) !== "object" || input === null)
return input;
var prim = input[Symbol.toPrimitive];
if (prim !== void 0) {
var res = prim.call(input, hint || "default");
if (_typeof7(res) !== "object")
return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
var FileSource = /* @__PURE__ */ function() {
function FileSource2(file) {
_classCallCheck6(this, FileSource2);
this._file = file;
this.size = file.size;
}
_createClass6(FileSource2, [{
key: "slice",
value: function slice(start, end) {
if (isCordova_default()) {
return readAsByteArray(this._file.slice(start, end));
}
var value = this._file.slice(start, end);
var done = end >= this.size;
return Promise.resolve({
value,
done
});
}
}, {
key: "close",
value: function close() {
}
}]);
return FileSource2;
}();
// node_modules/.pnpm/tus-js-client@3.1.3/node_modules/tus-js-client/lib.esm/browser/sources/StreamSource.js
function _typeof8(o) {
"@babel/helpers - typeof";
return _typeof8 = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(o2) {
return typeof o2;
} : function(o2) {
return o2 && typeof Symbol == "function" && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
}, _typeof8(o);
}
function _classCallCheck7(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties7(target, props) {
for (var i2 = 0; i2 < props.length; i2++) {
var descriptor = props[i2];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor)
descriptor.writable = true;
Object.defineProperty(target, _toPropertyKey7(descriptor.key), descriptor);
}
}
function _createClass7(Constructor, protoProps, staticProps) {
if (protoProps)
_defineProperties7(Constructor.prototype, protoProps);
if (staticProps)
_defineProperties7(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _toPropertyKey7(arg) {
var key = _toPrimitive7(arg, "string");
return _typeof8(key) === "symbol" ? key : String(key);
}
function _toPrimitive7(input, hint) {
if (_typeof8(input) !== "object" || input === null)
return input;
var prim = input[Symbol.toPrimitive];
if (prim !== void 0) {
var res = prim.call(input, hint || "default");
if (_typeof8(res) !== "object")
return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
function len(blobOrArray) {
if (blobOrArray === void 0)
return 0;
if (blobOrArray.size !== void 0)
return blobOrArray.size;
return blobOrArray.length;
}
function concat(a3, b2) {
if (a3.concat) {
return a3.concat(b2);
}
if (a3 instanceof Blob) {
return new Blob([a3, b2], {
type: a3.type
});
}
if (a3.set) {
var c2 = new a3.constructor(a3.length + b2.length);
c2.set(a3);
c2.set(b2, a3.length);
return c2;
}
throw new Error("Unknown data type");
}
var StreamSource = /* @__PURE__ */ function() {
function StreamSource2(reader) {
_classCallCheck7(this, StreamSource2);
this._buffer = void 0;
this._bufferOffset = 0;
this._reader = reader;
this._done = false;
}
_createClass7(StreamSource2, [{
key: "slice",
value: function slice(start, end) {
if (start < this._bufferOffset) {
return Promise.reject(new Error("Requested data is before the reader's current offset"));
}
return this._readUntilEnoughDataOrDone(start, end);
}
}, {
key: "_readUntilEnoughDataOrDone",
value: function _readUntilEnoughDataOrDone(start, end) {
var _this = this;
var hasEnoughData = end <= this._bufferOffset + len(this._buffer);
if (this._done || hasEnoughData) {
var value = this._getDataFromBuffer(start, end);
var done = value == null ? this._done : false;
return Promise.resolve({
value,
done
});
}
return this._reader.read().then(function(_ref) {
var value2 = _ref.value, done2 = _ref.done;
if (done2) {
_this._done = true;
} else if (_this._buffer === void 0) {
_this._buffer = value2;
} else {
_this._buffer = concat(_this._buffer, value2);
}
return _this._readUntilEnoughDataOrDone(start, end);
});
}
}, {
key: "_getDataFromBuffer",
value: function _getDataFromBuffer(start, end) {
if (start > this._bufferOffset) {
this._buffer = this._buffer.slice(start - this._bufferOffset);
this._bufferOffset = start;
}
var hasAllDataBeenRead = len(this._buffer) === 0;
if (this._done && hasAllDataBeenRead) {
return null;
}
return this._buffer.slice(0, end - start);
}
}, {
key: "close",
value: function close() {
if (this._reader.cancel) {
this._reader.cancel();
}
}
}]);
return StreamSource2;
}();
// node_modules/.pnpm/tus-js-client@3.1.3/node_modules/tus-js-client/lib.esm/browser/fileReader.js
function _typeof9(o) {
"@babel/helpers - typeof";
return _typeof9 = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(o2) {
return typeof o2;
} : function(o2) {
return o2 && typeof Symbol == "function" && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
}, _typeof9(o);
}
function _regeneratorRuntime2() {
"use strict";
_regeneratorRuntime2 = function _regeneratorRuntime3() {
return e2;
};
var t2, e2 = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function(t3, e3, r2) {
t3[e3] = r2.value;
}, i2 = typeof Symbol == "function" ? Symbol : {}, a3 = i2.iterator || "@@iterator", c2 = i2.asyncIterator || "@@asyncIterator", u2 = i2.toStringTag || "@@toStringTag";
function define(t3, e3, r2) {
return Object.defineProperty(t3, e3, { value: r2, enumerable: true, configurable: true, writable: true }), t3[e3];
}
try {
define({}, "");
} catch (t3) {
define = function define2(t4, e3, r2) {
return t4[e3] = r2;
};
}
function wrap(t3, e3, r2, n2) {
var i3 = e3 && e3.prototype instanceof Generator ? e3 : Generator, a4 = Object.create(i3.prototype), c3 = new Context(n2 || []);
return o(a4, "_invoke", { value: makeInvokeMethod(t3, r2, c3) }), a4;
}
function tryCatch(t3, e3, r2) {
try {
return { type: "normal", arg: t3.call(e3, r2) };
} catch (t4) {
return { type: "throw", arg: t4 };
}
}
e2.wrap = wrap;
var h3 = "suspendedStart", l = "suspendedYield", f = "executing", s3 = "completed", y3 = {};
function Generator() {
}
function GeneratorFunction() {
}
function GeneratorFunctionPrototype() {
}
var p = {};
define(p, a3, function() {
return this;
});
var d3 = Object.getPrototypeOf, v = d3 && d3(d3(values([])));
v && v !== r && n.call(v, a3) && (p = v);
var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
function defineIteratorMethods(t3) {
["next", "throw", "return"].forEach(function(e3) {
define(t3, e3, function(t4) {
return this._invoke(e3, t4);
});
});
}
function AsyncIterator(t3, e3) {
function invoke(r3, o2, i3, a4) {
var c3 = tryCatch(t3[r3], t3, o2);
if (c3.type !== "throw") {
var u3 = c3.arg, h4 = u3.value;
return h4 && _typeof9(h4) == "object" && n.call(h4, "__await") ? e3.resolve(h4.__await).then(function(t4) {
invoke("next", t4, i3, a4);
}, function(t4) {
invoke("throw", t4, i3, a4);
}) : e3.resolve(h4).then(function(t4) {
u3.value = t4, i3(u3);
}, function(t4) {
return invoke("throw", t4, i3, a4);
});
}
a4(c3.arg);
}
var r2;
o(this, "_invoke", { value: function value(t4, n2) {
function callInvokeWithMethodAndArg() {
return new e3(function(e4, r3) {
invoke(t4, n2, e4, r3);
});
}
return r2 = r2 ? r2.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
} });
}
function makeInvokeMethod(e3, r2, n2) {
var o2 = h3;
return function(i3, a4) {
if (o2 === f)
throw new Error("Generator is already running");
if (o2 === s3) {
if (i3 === "throw")
throw a4;
return { value: t2, done: true };
}
for (n2.method = i3, n2.arg = a4; ; ) {
var c3 = n2.delegate;
if (c3) {
var u3 = maybeInvokeDelegate(c3, n2);
if (u3) {
if (u3 === y3)
continue;
return u3;
}
}
if (n2.method === "next")
n2.sent = n2._sent = n2.arg;
else if (n2.method === "throw") {
if (o2 === h3)
throw o2 = s3, n2.arg;
n2.dispatchException(n2.arg);
} else
n2.method === "return" && n2.abrupt("return", n2.arg);
o2 = f;
var p2 = tryCatch(e3, r2, n2);
if (p2.type === "normal") {
if (o2 = n2.done ? s3 : l, p2.arg === y3)
continue;
return { value: p2.arg, done: n2.done };
}
p2.type === "throw" && (o2 = s3, n2.method = "throw", n2.arg = p2.arg);
}
};
}
function maybeInvokeDelegate(e3, r2) {
var n2 = r2.method, o2 = e3.iterator[n2];
if (o2 === t2)
return r2.delegate = null, n2 === "throw" && e3.iterator["return"] && (r2.method = "return", r2.arg = t2, maybeInvokeDelegate(e3, r2), r2.method === "throw") || n2 !== "return" && (r2.method = "throw", r2.arg = new TypeError("The iterator does not provide a '" + n2 + "' method")), y3;
var i3 = tryCatch(o2, e3.iterator, r2.arg);
if (i3.type === "throw")
return r2.method = "throw", r2.arg = i3.arg, r2.delegate = null, y3;
var a4 = i3.arg;
return a4 ? a4.done ? (r2[e3.resultName] = a4.value, r2.next = e3.nextLoc, r2.method !== "return" && (r2.method = "next", r2.arg = t2), r2.delegate = null, y3) : a4 : (r2.method = "throw", r2.arg = new TypeError("iterator result is not an object"), r2.delegate = null, y3);
}
function pushTryEntry(t3) {
var e3 = { tryLoc: t3[0] };
1 in t3 && (e3.catchLoc = t3[1]), 2 in t3 && (e3.finallyLoc = t3[2], e3.afterLoc = t3[3]), this.tryEntries.push(e3);
}
function resetTryEntry(t3) {
var e3 = t3.completion || {};
e3.type = "normal", delete e3.arg, t3.completion = e3;
}
function Context(t3) {
this.tryEntries = [{ tryLoc: "root" }], t3.forEach(pushTryEntry, this), this.reset(true);
}
function values(e3) {
if (e3 || e3 === "") {
var r2 = e3[a3];
if (r2)
return r2.call(e3);
if (typeof e3.next == "function")
return e3;
if (!isNaN(e3.length)) {
var o2 = -1, i3 = function next() {
for (; ++o2 < e3.length; )
if (n.call(e3, o2))
return next.value = e3[o2], next.done = false, next;
return next.value = t2, next.done = true, next;
};
return i3.next = i3;
}
}
throw new TypeError(_typeof9(e3) + " is not iterable");
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: true }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: true }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u2, "GeneratorFunction"), e2.isGeneratorFunction = function(t3) {
var e3 = typeof t3 == "function" && t3.constructor;
return !!e3 && (e3 === GeneratorFunction || (e3.displayName || e3.name) === "GeneratorFunction");
}, e2.mark = function(t3) {
return Object.setPrototypeOf ? Object.setPrototypeOf(t3, GeneratorFunctionPrototype) : (t3.__proto__ = GeneratorFunctionPrototype, define(t3, u2, "GeneratorFunction")), t3.prototype = Object.create(g), t3;
}, e2.awrap = function(t3) {
return { __await: t3 };
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c2, function() {
return this;
}), e2.AsyncIterator = AsyncIterator, e2.async = function(t3, r2, n2, o2, i3) {
i3 === void 0 && (i3 = Promise);
var a4 = new AsyncIterator(wrap(t3, r2, n2, o2), i3);
return e2.isGeneratorFunction(r2) ? a4 : a4.next().then(function(t4) {
return t4.done ? t4.value : a4.next();
});
}, defineIteratorMethods(g), define(g, u2, "Generator"), define(g, a3, function() {
return this;
}), define(g, "toString", function() {
return "[object Generator]";
}), e2.keys = function(t3) {
var e3 = Object(t3), r2 = [];
for (var n2 in e3)
r2.push(n2);
return r2.reverse(), function next() {
for (; r2.length; ) {
var t4 = r2.pop();
if (t4 in e3)
return next.value = t4, next.done = false, next;
}
return next.done = true, next;
};
}, e2.values = values, Context.prototype = { constructor: Context, reset: function reset(e3) {
if (this.prev = 0, this.next = 0, this.sent = this._sent = t2, this.done = false, this.delegate = null, this.method = "next", this.arg = t2, this.tryEntries.forEach(resetTryEntry), !e3)
for (var r2 in this)
r2.charAt(0) === "t" && n.call(this, r2) && !isNaN(+r2.slice(1)) && (this[r2] = t2);
}, stop: function stop() {
this.done = true;
var t3 = this.tryEntries[0].completion;
if (t3.type === "throw")
throw t3.arg;
return this.rval;
}, dispatchException: function dispatchException(e3) {
if (this.done)
throw e3;
var r2 = this;
function handle(n2, o3) {
return a4.type = "throw", a4.arg = e3, r2.next = n2, o3 && (r2.method = "next", r2.arg = t2), !!o3;
}
for (var o2 = this.tryEntries.length - 1; o2 >= 0; --o2) {
var i3 = this.tryEntries[o2], a4 = i3.completion;
if (i3.tryLoc === "root")
return handle("end");
if (i3.tryLoc <= this.prev) {
var c3 = n.call(i3, "catchLoc"), u3 = n.call(i3, "finallyLoc");
if (c3 && u3) {
if (this.prev < i3.catchLoc)
return handle(i3.catchLoc, true);
if (this.prev < i3.finallyLoc)
return handle(i3.finallyLoc);
} else if (c3) {
if (this.prev < i3.catchLoc)
return handle(i3.catchLoc, true);
} else {
if (!u3)
throw new Error("try statement without catch or finally");
if (this.prev < i3.finallyLoc)
return handle(i3.finallyLoc);
}
}
}
}, abrupt: function abrupt(t3, e3) {
for (var r2 = this.tryEntries.length - 1; r2 >= 0; --r2) {
var o2 = this.tryEntries[r2];
if (o2.tryLoc <= this.prev && n.call(o2, "finallyLoc") && this.prev < o2.finallyLoc) {
var i3 = o2;
break;
}
}
i3 && (t3 === "break" || t3 === "continue") && i3.tryLoc <= e3 && e3 <= i3.finallyLoc && (i3 = null);
var a4 = i3 ? i3.completion : {};
return a4.type = t3, a4.arg = e3, i3 ? (this.method = "next", this.next = i3.finallyLoc, y3) : this.complete(a4);
}, complete: function complete(t3, e3) {
if (t3.type === "throw")
throw t3.arg;
return t3.type === "break" || t3.type === "continue" ? this.next = t3.arg : t3.type === "return" ? (this.rval = this.arg = t3.arg, this.method = "return", this.next = "end") : t3.type === "normal" && e3 && (this.next = e3), y3;
}, finish: function finish(t3) {
for (var e3 = this.tryEntries.length - 1; e3 >= 0; --e3) {
var r2 = this.tryEntries[e3];
if (r2.finallyLoc === t3)
return this.complete(r2.completion, r2.afterLoc), resetTryEntry(r2), y3;
}
}, "catch": function _catch(t3) {
for (var e3 = this.tryEntries.length - 1; e3 >= 0; --e3) {
var r2 = this.tryEntries[e3];
if (r2.tryLoc === t3) {
var n2 = r2.completion;
if (n2.type === "throw") {
var o2 = n2.arg;
resetTryEntry(r2);
}
return o2;
}
}
throw new Error("illegal catch attempt");
}, delegateYield: function delegateYield(e3, r2, n2) {
return this.delegate = { iterator: values(e3), resultName: r2, nextLoc: n2 }, this.method === "next" && (this.arg = t2), y3;
} }, e2;
}
function asyncGeneratorStep2(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator2(fn) {
return function() {
var self2 = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self2, args);
function _next(value) {
asyncGeneratorStep2(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep2(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(void 0);
});
};
}
function _classCallCheck8(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties8(target, props) {
for (var i2 = 0; i2 < props.length; i2++) {
var descriptor = props[i2];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor)
descriptor.writable = true;
Object.defineProperty(target, _toPropertyKey8(descriptor.key), descriptor);
}
}
function _createClass8(Constructor, protoProps, staticProps) {
if (protoProps)
_defineProperties8(Constructor.prototype, protoProps);
if (staticProps)
_defineProperties8(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _toPropertyKey8(arg) {
var key = _toPrimitive8(arg, "string");
return _typeof9(key) === "symbol" ? key : String(key);
}
function _toPrimitive8(input, hint) {
if (_typeof9(input) !== "object" || input === null)
return input;
var prim = input[Symbol.toPrimitive];
if (prim !== void 0) {
var res = prim.call(input, hint || "default");
if (_typeof9(res) !== "object")
return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
var FileReader2 = /* @__PURE__ */ function() {
function FileReader3() {
_classCallCheck8(this, FileReader3);
}
_createClass8(FileReader3, [{
key: "openFile",
value: function() {
var _openFile = _asyncToGenerator2(/* @__PURE__ */ _regeneratorRuntime2().mark(function _callee(input, chunkSize) {
var blob;
return _regeneratorRuntime2().wrap(function _callee$(_context) {
while (1)
switch (_context.prev = _context.next) {
case 0:
if (!(isReactNative_default() && input && typeof input.uri !== "undefined")) {
_context.next = 11;
break;
}
_context.prev = 1;
_context.next = 4;
return uriToBlob(input.uri);
case 4:
blob = _context.sent;
return _context.abrupt("return", new FileSource(blob));
case 8:
_context.prev = 8;
_context.t0 = _context["catch"](1);
throw new Error("tus: cannot fetch `file.uri` as Blob, make sure the uri is correct and accessible. ".concat(_context.t0));
case 11:
if (!(typeof input.slice === "function" && typeof input.size !== "undefined")) {
_context.next = 13;
break;
}
return _context.abrupt("return", Promise.resolve(new FileSource(input)));
case 13:
if (!(typeof input.read === "function")) {
_context.next = 18;
break;
}
chunkSize = Number(chunkSize);
if (Number.isFinite(chunkSize)) {
_context.next = 17;
break;
}
return _context.abrupt("return", Promise.reject(new Error("cannot create source for stream without a finite value for the `chunkSize` option")));
case 17:
return _context.abrupt("return", Promise.resolve(new StreamSource(input, chunkSize)));
case 18:
return _context.abrupt("return", Promise.reject(new Error("source object may only be an instance of File, Blob, or Reader in this environment")));
case 19:
case "end":
return _context.stop();
}
}, _callee, null, [[1, 8]]);
}));
function openFile(_x, _x2) {
return _openFile.apply(this, arguments);
}
return openFile;
}()
}]);
return FileReader3;
}();
// node_modules/.pnpm/tus-js-client@3.1.3/node_modules/tus-js-client/lib.esm/browser/fileSignature.js
function fingerprint(file, options) {
if (isReactNative_default()) {
return Promise.resolve(reactNativeFingerprint(file, options));
}
return Promise.resolve(["tus-br", file.name, file.type, file.size, file.lastModified, options.endpoint].join("-"));
}
function reactNativeFingerprint(file, options) {
var exifHash = file.exif ? hashCode(JSON.stringify(file.exif)) : "noexif";
return ["tus-rn", file.name || "noname", file.size || "nosize", exifHash, options.endpoint].join("/");
}
function hashCode(str) {
var hash = 0;
if (str.length === 0) {
return hash;
}
for (var i2 = 0; i2 < str.length; i2++) {
var _char = str.charCodeAt(i2);
hash = (hash << 5) - hash + _char;
hash &= hash;
}
return hash;
}
// node_modules/.pnpm/tus-js-client@3.1.3/node_modules/tus-js-client/lib.esm/browser/index.js
function _typeof10(o) {
"@babel/helpers - typeof";
return _typeof10 = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(o2) {
return typeof o2;
} : function(o2) {
return o2 && typeof Symbol == "function" && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
}, _typeof10(o);
}
function _classCallCheck9(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties9(target, props) {
for (var i2 = 0; i2 < props.length; i2++) {
var descriptor = props[i2];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor)
descriptor.writable = true;
Object.defineProperty(target, _toPropertyKey9(descriptor.key), descriptor);
}
}
function _createClass9(Constructor, protoProps, staticProps) {
if (protoProps)
_defineProperties9(Constructor.prototype, protoProps);
if (staticProps)
_defineProperties9(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _inherits2(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
Object.defineProperty(subClass, "prototype", { writable: false });
if (superClass)
_setPrototypeOf2(subClass, superClass);
}
function _setPrototypeOf2(o, p) {
_setPrototypeOf2 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf3(o2, p2) {
o2.__proto__ = p2;
return o2;
};
return _setPrototypeOf2(o, p);
}
function _createSuper2(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct2();
return function _createSuperInternal() {
var Super = _getPrototypeOf2(Derived), result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf2(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn2(this, result);
};
}
function _possibleConstructorReturn2(self2, call) {
if (call && (_typeof10(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized2(self2);
}
function _assertThisInitialized2(self2) {
if (self2 === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self2;
}
function _isNativeReflectConstruct2() {
if (typeof Reflect === "undefined" || !Reflect.construct)
return false;
if (Reflect.construct.sham)
return false;
if (typeof Proxy === "function")
return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
}));
return true;
} catch (e2) {
return false;
}
}
function _getPrototypeOf2(o) {
_getPrototypeOf2 = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf3(o2) {
return o2.__proto__ || Object.getPrototypeOf(o2);
};
return _getPrototypeOf2(o);
}
function ownKeys2(e2, r) {
var t2 = Object.keys(e2);
if (Object.getOwnPropertySymbols) {
var o = Object.getOwnPropertySymbols(e2);
r && (o = o.filter(function(r2) {
return Object.getOwnPropertyDescriptor(e2, r2).enumerable;
})), t2.push.apply(t2, o);
}
return t2;
}
function _objectSpread2(e2) {
for (var r = 1; r < arguments.length; r++) {
var t2 = arguments[r] != null ? arguments[r] : {};
r % 2 ? ownKeys2(Object(t2), true).forEach(function(r2) {
_defineProperty2(e2, r2, t2[r2]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e2, Object.getOwnPropertyDescriptors(t2)) : ownKeys2(Object(t2)).forEach(function(r2) {
Object.defineProperty(e2, r2, Object.getOwnPropertyDescriptor(t2, r2));
});
}
return e2;
}
function _defineProperty2(obj, key, value) {
key = _toPropertyKey9(key);
if (key in obj) {
Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
} else {
obj[key] = value;
}
return obj;
}
function _toPropertyKey9(arg) {
var key = _toPrimitive9(arg, "string");
return _typeof10(key) === "symbol" ? key : String(key);
}
function _toPrimitive9(input, hint) {
if (_typeof10(input) !== "object" || input === null)
return input;
var prim = input[Symbol.toPrimitive];
if (prim !== void 0) {
var res = prim.call(input, hint || "default");
if (_typeof10(res) !== "object")
return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
var defaultOptions3 = _objectSpread2(_objectSpread2({}, upload_default.defaultOptions), {}, {
httpStack: new XHRHttpStack(),
fileReader: new FileReader2(),
urlStorage: canStoreURLs ? new WebStorageUrlStorage() : new NoopUrlStorage(),
fingerprint
});
var Upload = /* @__PURE__ */ function(_BaseUpload) {
_inherits2(Upload2, _BaseUpload);
var _super = _createSuper2(Upload2);
function Upload2() {
var file = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : null;
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
_classCallCheck9(this, Upload2);
options = _objectSpread2(_objectSpread2({}, defaultOptions3), options);
return _super.call(this, file, options);
}
_createClass9(Upload2, null, [{
key: "terminate",
value: function terminate(url) {
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
options = _objectSpread2(_objectSpread2({}, defaultOptions3), options);
return upload_default.terminate(url, options);
}
}]);
return Upload2;
}(upload_default);
var _window = window;
var XMLHttpRequest2 = _window.XMLHttpRequest;
var Blob2 = _window.Blob;
var isSupported = XMLHttpRequest2 && Blob2 && typeof Blob2.prototype.slice === "function";
// src/transcribe.ts
var MAX_TRIES = 100;
var TranscriptionEngine = class {
constructor(settings, vault, statusBar, supabase, app) {
this.transcription_engines = {
swiftink: this.getTranscriptionSwiftink,
whisper_asr: this.getTranscriptionWhisperASR
};
this.settings = settings;
this.vault = vault;
this.statusBar = statusBar;
this.supabase = supabase;
this.app = app;
}
segmentsToTimestampedString(segments, timestampFormat, interval = 0) {
let maxDuration = 0;
segments.forEach((segment) => {
maxDuration = Math.max(maxDuration, segment.end);
});
const autoFormat = maxDuration < 3600 ? "mm:ss" : "HH:mm:ss";
const renderSegments = (segments2) => segments2.reduce((transcription, segment) => {
let start = new Date(segment.start * 1e3);
let end = new Date(segment.end * 1e3);
start = new Date(start.getTime() + start.getTimezoneOffset() * 6e4);
end = new Date(end.getTime() + end.getTimezoneOffset() * 6e4);
const formatToUse = timestampFormat === "auto" ? autoFormat : timestampFormat;
const start_formatted = format(start, formatToUse);
const end_formatted = format(end, formatToUse);
const segment_string = `${start_formatted} - ${end_formatted}: ${segment.text.trim()}
`;
transcription += segment_string;
return transcription;
}, "");
if (interval > 0) {
const groupedSegments = {};
segments.forEach((segment) => {
const intervalStart = Math.floor(segment.start / interval) * interval;
if (!groupedSegments[intervalStart]) {
groupedSegments[intervalStart] = {
start: segment.start,
end: segment.end,
texts: [segment.text]
};
} else {
groupedSegments[intervalStart].end = Math.max(groupedSegments[intervalStart].end, segment.end);
groupedSegments[intervalStart].texts.push(segment.text);
}
});
const bucketedSegments = Object.values(groupedSegments).map((group) => ({
start: group.start,
end: group.end,
text: group.texts.join("").trim()
}));
return renderSegments(bucketedSegments);
} else {
return renderSegments(segments);
}
}
async getTranscription(file) {
if (this.settings.debug)
console.log(`Transcription engine: ${this.settings.transcriptionEngine}`);
const start = new Date();
this.transcriptionEngine = this.transcription_engines[this.settings.transcriptionEngine];
return this.transcriptionEngine(file).then((transcription) => {
if (this.settings.debug)
console.log(`Transcription: ${transcription}`);
if (this.settings.debug)
console.log(`Transcription took ${new Date().getTime() - start.getTime()} ms`);
return transcription;
});
}
async getTranscriptionWhisperASR(file) {
const payload_data = {};
payload_data["audio_file"] = new Blob([
await this.vault.readBinary(file)
]);
const [request_body, boundary_string] = await payloadGenerator(payload_data);
let args = "output=json";
args += `&word_timestamps=true`;
const { translate, encode: encode2, vadFilter, language, initialPrompt } = this.settings;
if (translate)
args += `&task=translate`;
if (encode2 !== DEFAULT_SETTINGS.encode)
args += `&encode=${encode2}`;
if (vadFilter !== DEFAULT_SETTINGS.vadFilter)
args += `&vad_filter=${vadFilter}`;
if (language !== DEFAULT_SETTINGS.language)
args += `&language=${language}`;
if (initialPrompt)
args += `&initial_prompt=${initialPrompt}`;
const urls = this.settings.whisperASRUrls.split(";").filter(Boolean);
for (const baseUrl of urls) {
const url = `${baseUrl}/asr?${args}`;
console.log("Trying URL:", url);
const options = {
method: "POST",
url,
contentType: `multipart/form-data; boundary=----${boundary_string}`,
body: request_body
};
console.log("Options:", options);
try {
const response = await (0, import_obsidian3.requestUrl)(options);
if (this.settings.debug)
console.log("Raw response:", response);
const preprocessed = Array.isArray(response.json.segments[0]) ? preprocessWhisperASRResponse(response.json) : response.json;
if (this.settings.debug)
console.log("Preprocessed response:", preprocessed);
const wordSegments = preprocessed.segments.reduce((acc, segment) => {
if (segment.words) {
acc.push(...segment.words.map((wordTimestamp) => ({
start: wordTimestamp.start,
end: wordTimestamp.end,
text: wordTimestamp.word
})));
}
return acc;
}, []);
if (this.settings.wordTimestamps) {
return this.segmentsToTimestampedString(wordSegments, this.settings.timestampFormat);
} else if (parseInt(this.settings.timestampInterval)) {
return this.segmentsToTimestampedString(wordSegments, this.settings.timestampFormat, parseInt(this.settings.timestampInterval));
} else if (this.settings.timestamps) {
const segments = preprocessed.segments.map((segment) => ({
start: segment.start,
end: segment.end,
text: segment.text
}));
return this.segmentsToTimestampedString(segments, this.settings.timestampFormat);
} else if (preprocessed.segments) {
return preprocessed.segments.map((segment) => segment.text).map((s3) => s3.trim()).join("\n");
} else {
return preprocessed.text;
}
} catch (error) {
if (this.settings.debug)
console.error("Error with URL:", url, error);
}
}
return Promise.reject("All Whisper ASR URLs failed");
}
async getTranscriptionSwiftink(file) {
const session = await this.supabase.auth.getSession().then((res) => {
return res.data;
});
if (session == null || session.session == null) {
return Promise.reject("No user session found. Please log in and try again.");
}
const token = session.session.access_token;
const id = session.session.user.id;
const fileStream = await this.vault.readBinary(file);
const filename = file.name.replace(/[^a-zA-Z0-9.]+/g, "-");
let uploadProgressNotice = null;
const uploadPromise = new Promise((resolve) => {
const upload = new Upload(new Blob([fileStream]), {
endpoint: `https://vcdeqgrsqaexpnogauly.supabase.co/storage/v1/upload/resumable`,
retryDelays: [0, 3e3, 5e3, 1e4, 2e4],
headers: {
authorization: `Bearer ${token}`,
"x-upsert": "true"
},
uploadDataDuringCreation: true,
metadata: {
bucketName: "swiftink-upload",
objectName: `${id}/${filename}`
},
chunkSize: 6 * 1024 * 1024,
onProgress: (bytesUploaded, bytesTotal) => {
const percentage = (bytesUploaded / bytesTotal * 100).toFixed(2);
const noticeMessage = `Uploading ${filename}: ${percentage}%`;
if (!uploadProgressNotice) {
uploadProgressNotice = new import_obsidian3.Notice(noticeMessage, 80 * 1e3);
} else {
uploadProgressNotice.setMessage(noticeMessage);
}
if (this.settings.debug) {
console.log(bytesUploaded, bytesTotal, percentage + "%");
}
},
onSuccess: () => {
if (this.settings.debug) {
console.log(`Successfully uploaded ${filename} to Swiftink`);
}
if (uploadProgressNotice) {
uploadProgressNotice.hide();
}
resolve(upload);
}
});
upload.start();
});
try {
await uploadPromise;
new import_obsidian3.Notice(`Successfully uploaded ${filename} to Swiftink`);
} catch (error) {
if (this.settings.debug) {
console.log("Failed to upload to Swiftink: ", error);
}
return Promise.reject(new import_obsidian3.Notice(`Failed to upload ${filename} to Swiftink`));
}
let transcriptionProgressNotice = null;
const fileUrl = `https://vcdeqgrsqaexpnogauly.supabase.co/storage/v1/object/public/swiftink-upload/${id}/${filename}`;
const url = `${API_BASE}/transcripts/`;
const headers = { Authorization: `Bearer ${token}` };
const body = {
name: filename,
url: fileUrl
};
if (this.settings.language != "auto")
body.language = this.settings.language;
if (this.settings.debug)
console.log(body);
const options = {
method: "POST",
url,
headers,
body: JSON.stringify(body)
};
let transcript_create_res;
try {
transcript_create_res = await (0, import_obsidian3.requestUrl)(options);
} catch (error) {
if (this.settings.debug)
console.log("Failed to create transcript: ", error);
return Promise.reject(error);
}
let transcript = transcript_create_res.json;
if (this.settings.debug)
console.log(transcript);
let completed_statuses = ["transcribed", "complete"];
if (this.settings.embedSummary || this.settings.embedOutline || this.settings.embedKeywords) {
completed_statuses = ["complete"];
}
return new Promise((resolve, reject) => {
let tries = 0;
const updateTranscriptionNotice = () => {
const noticeMessage = `Transcribing ${transcript.name}...`;
if (!transcriptionProgressNotice) {
transcriptionProgressNotice = new import_obsidian3.Notice(noticeMessage, 80 * 1e3);
} else {
transcriptionProgressNotice.setMessage(noticeMessage);
}
};
const poll = setInterval(async () => {
const options2 = {
method: "GET",
url: `${API_BASE}/transcripts/${transcript.id}`,
headers
};
const transcript_res = await (0, import_obsidian3.requestUrl)(options2);
transcript = transcript_res.json;
if (this.settings.debug)
console.log(transcript);
if (transcript.status && completed_statuses.includes(transcript.status)) {
clearInterval(poll);
if (transcriptionProgressNotice) {
transcriptionProgressNotice.hide();
}
new import_obsidian3.Notice(`Successfully transcribed ${filename} with Swiftink`);
resolve(this.formatSwiftinkResults(transcript));
} else if (transcript.status == "failed") {
if (this.settings.debug)
console.error("Swiftink failed to transcribe the file");
clearInterval(poll);
reject("Swiftink failed to transcribe the file");
} else if (transcript.status == "validation_failed") {
if (this.settings.debug)
console.error("Swiftink has detected an invalid file");
clearInterval(poll);
reject("Swiftink has detected an invalid file");
} else if (tries > MAX_TRIES) {
if (this.settings.debug)
console.error("Swiftink took too long to transcribe the file");
clearInterval(poll);
reject("Swiftink took too long to transcribe the file");
} else {
updateTranscriptionNotice();
}
tries++;
}, 3e3);
});
}
formatSwiftinkResults(transcript) {
let transcript_text = "## Transcript\n";
if (this.settings.timestamps)
transcript_text += this.segmentsToTimestampedString(transcript.text_segments, this.settings.timestampFormat);
else
transcript_text += transcript.text ? transcript.text : "";
if (transcript_text.slice(-1) !== "\n")
transcript_text += "\n";
if (this.settings.embedSummary && transcript.summary && transcript.summary !== "Insufficient information for a summary.")
transcript_text += `## Summary
${transcript.summary}`;
if (transcript_text.slice(-1) !== "\n")
transcript_text += "\n";
if (this.settings.embedOutline && transcript.heading_segments.length > 0)
transcript_text += `## Outline
${this.segmentsToTimestampedString(transcript.heading_segments, this.settings.timestampFormat)}`;
if (transcript_text.slice(-1) !== "\n")
transcript_text += "\n";
if (this.settings.embedKeywords && transcript.keywords.length > 0)
transcript_text += `## Keywords
${transcript.keywords.join(", ")}`;
if (transcript_text.slice(-1) !== "\n")
transcript_text += "\n";
if (this.settings.embedAdditionalFunctionality) {
transcript_text += `[...](obsidian://swiftink_transcript_functions?id=${transcript.id})`;
}
return transcript_text;
}
};
// src/status.ts
var StatusBar = class {
constructor(statusBarEl) {
this.messages = [];
this.statusBarEl = statusBarEl;
}
hasForcedMessage() {
return this.messages.some((message) => message.force);
}
setText(message) {
this.statusBarEl.setText(message.message);
}
clearText() {
this.statusBarEl.setText("");
}
displayMessage(message, timeout, force = false, kek_mode = false) {
if (this.messages[0] && this.messages[0].message === message)
return;
this.messages.push(new StatusBarMessage(`Transcribe: ${message.slice(0, 100)}`, timeout, force, kek_mode));
this.display();
}
display() {
if (this.hasForcedMessage()) {
const lastForced = this.messages.filter((message) => message.force).pop();
if (lastForced)
this.messages = [lastForced];
if (this.currentMessage !== lastForced) {
this.currentMessage = lastForced;
if (!this.currentMessage)
return;
this.currentMessage.timeShown = Date.now();
this.setText(this.currentMessage);
} else if (this.currentMessage == lastForced && this.currentMessage && this.currentMessage.messageTimedOut()) {
this.clearText();
}
} else {
if (this.currentMessage && this.currentMessage.messageTimedOut()) {
if (this.messages.length > 0) {
const currentMessage = this.messages.shift();
this.currentMessage = currentMessage;
if (this.currentMessage) {
this.setText(this.currentMessage);
this.currentMessage.timeShown = Date.now();
} else {
this.currentMessage = void 0;
this.clearText();
}
} else {
this.currentMessage = void 0;
this.clearText();
}
} else if (!this.currentMessage && this.messages.length > 0) {
const currentMessage = this.messages.shift();
this.currentMessage = currentMessage;
if (!this.currentMessage)
return;
this.setText(this.currentMessage);
this.currentMessage.timeShown = Date.now();
} else if (!this.currentMessage) {
this.clearText();
}
}
}
};
var StatusBarMessage = class {
constructor(message, timeout, force = false, kek_mode = false) {
this.messageAge = function() {
if (!this.timeShown)
return 0;
return Date.now() - this.timeShown;
};
this.messageTimedOut = function() {
return this.messageAge() >= this.timeout;
};
this.message = message;
this.timeout = timeout;
this.force = force;
this.kek_mode = kek_mode;
}
};
// node_modules/.pnpm/@supabase+functions-js@2.1.5/node_modules/@supabase/functions-js/dist/module/helper.js
var resolveFetch = (customFetch) => {
let _fetch;
if (customFetch) {
_fetch = customFetch;
} else if (typeof fetch === "undefined") {
_fetch = (...args) => Promise.resolve().then(() => (init_browser(), browser_exports2)).then(({ default: fetch3 }) => fetch3(...args));
} else {
_fetch = fetch;
}
return (...args) => _fetch(...args);
};
// node_modules/.pnpm/@supabase+functions-js@2.1.5/node_modules/@supabase/functions-js/dist/module/types.js
var FunctionsError = class extends Error {
constructor(message, name = "FunctionsError", context) {
super(message);
this.name = name;
this.context = context;
}
};
var FunctionsFetchError = class extends FunctionsError {
constructor(context) {
super("Failed to send a request to the Edge Function", "FunctionsFetchError", context);
}
};
var FunctionsRelayError = class extends FunctionsError {
constructor(context) {
super("Relay Error invoking the Edge Function", "FunctionsRelayError", context);
}
};
var FunctionsHttpError = class extends FunctionsError {
constructor(context) {
super("Edge Function returned a non-2xx status code", "FunctionsHttpError", context);
}
};
// node_modules/.pnpm/@supabase+functions-js@2.1.5/node_modules/@supabase/functions-js/dist/module/FunctionsClient.js
var __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 (e2) {
reject(e2);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e2) {
reject(e2);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var FunctionsClient = class {
constructor(url, { headers = {}, customFetch } = {}) {
this.url = url;
this.headers = headers;
this.fetch = resolveFetch(customFetch);
}
setAuth(token) {
this.headers.Authorization = `Bearer ${token}`;
}
invoke(functionName, options = {}) {
var _a;
return __awaiter(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 };
}
});
}
};
// node_modules/.pnpm/@supabase+postgrest-js@1.9.2/node_modules/@supabase/postgrest-js/dist/module/PostgrestBuilder.js
init_browser();
// node_modules/.pnpm/@supabase+postgrest-js@1.9.2/node_modules/@supabase/postgrest-js/dist/module/PostgrestError.js
var PostgrestError = class extends Error {
constructor(context) {
super(context.message);
this.name = "PostgrestError";
this.details = context.details;
this.hint = context.hint;
this.code = context.code;
}
};
// node_modules/.pnpm/@supabase+postgrest-js@1.9.2/node_modules/@supabase/postgrest-js/dist/module/PostgrestBuilder.js
var PostgrestBuilder = class {
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.isMaybeSingle = builder.isMaybeSingle;
if (builder.fetch) {
this.fetch = builder.fetch;
} else if (typeof fetch === "undefined") {
this.fetch = browser_default;
} 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]);
}
if (this.isMaybeSingle && this.method === "GET" && Array.isArray(data)) {
if (data.length > 1) {
error = {
code: "PGRST116",
details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`,
hint: null,
message: "JSON object requested, multiple (or no) rows returned"
};
data = null;
count = null;
status = 406;
statusText = "Not Acceptable";
} else if (data.length === 1) {
data = data[0];
} else {
data = null;
}
}
} else {
const body = await 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.isMaybeSingle && ((_c = error === null || error === void 0 ? void 0 : error.details) === null || _c === void 0 ? void 0 : _c.includes("0 rows"))) {
error = null;
status = 200;
statusText = "OK";
}
if (error && this.shouldThrowOnError) {
throw new PostgrestError(error);
}
}
const postgrestResponse = {
error,
data,
count,
status,
statusText
};
return postgrestResponse;
});
if (!this.shouldThrowOnError) {
res = res.catch((fetchError) => {
var _a, _b, _c;
return {
error: {
message: `${(_a = fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) !== null && _a !== void 0 ? _a : "FetchError"}: ${fetchError === null || fetchError === void 0 ? void 0 : fetchError.message}`,
details: `${(_b = fetchError === null || fetchError === void 0 ? void 0 : fetchError.stack) !== null && _b !== void 0 ? _b : ""}`,
hint: "",
code: `${(_c = fetchError === null || fetchError === void 0 ? void 0 : fetchError.code) !== null && _c !== void 0 ? _c : ""}`
},
data: null,
count: null,
status: 0,
statusText: ""
};
});
}
return res.then(onfulfilled, onrejected);
}
};
// node_modules/.pnpm/@supabase+postgrest-js@1.9.2/node_modules/@supabase/postgrest-js/dist/module/PostgrestTransformBuilder.js
var PostgrestTransformBuilder = class extends PostgrestBuilder {
select(columns) {
let quoted = false;
const cleanedColumns = (columns !== null && columns !== void 0 ? columns : "*").split("").map((c2) => {
if (/\s/.test(c2) && !quoted) {
return "";
}
if (c2 === '"') {
quoted = !quoted;
}
return c2;
}).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, referencedTable = foreignTable } = {}) {
const key = referencedTable ? `${referencedTable}.order` : "order";
const existingOrder = this.url.searchParams.get(key);
this.url.searchParams.set(key, `${existingOrder ? `${existingOrder},` : ""}${column}.${ascending ? "asc" : "desc"}${nullsFirst === void 0 ? "" : nullsFirst ? ".nullsfirst" : ".nullslast"}`);
return this;
}
limit(count, { foreignTable, referencedTable = foreignTable } = {}) {
const key = typeof referencedTable === "undefined" ? "limit" : `${referencedTable}.limit`;
this.url.searchParams.set(key, `${count}`);
return this;
}
range(from, to, { foreignTable, referencedTable = foreignTable } = {}) {
const keyOffset = typeof referencedTable === "undefined" ? "offset" : `${referencedTable}.offset`;
const keyLimit = typeof referencedTable === "undefined" ? "limit" : `${referencedTable}.limit`;
this.url.searchParams.set(keyOffset, `${from}`);
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() {
if (this.method === "GET") {
this.headers["Accept"] = "application/json";
} else {
this.headers["Accept"] = "application/vnd.pgrst.object+json";
}
this.isMaybeSingle = 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: format2 = "text" } = {}) {
var _a;
const options = [
analyze ? "analyze" : null,
verbose ? "verbose" : null,
settings ? "settings" : null,
buffers ? "buffers" : null,
wal ? "wal" : null
].filter(Boolean).join("|");
const forMediatype = (_a = this.headers["Accept"]) !== null && _a !== void 0 ? _a : "application/json";
this.headers["Accept"] = `application/vnd.pgrst.plan+${format2}; for="${forMediatype}"; options=${options};`;
if (format2 === "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;
}
};
// node_modules/.pnpm/@supabase+postgrest-js@1.9.2/node_modules/@supabase/postgrest-js/dist/module/PostgrestFilterBuilder.js
var PostgrestFilterBuilder = class 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;
}
likeAllOf(column, patterns) {
this.url.searchParams.append(column, `like(all).{${patterns.join(",")}}`);
return this;
}
likeAnyOf(column, patterns) {
this.url.searchParams.append(column, `like(any).{${patterns.join(",")}}`);
return this;
}
ilike(column, pattern) {
this.url.searchParams.append(column, `ilike.${pattern}`);
return this;
}
ilikeAllOf(column, patterns) {
this.url.searchParams.append(column, `ilike(all).{${patterns.join(",")}}`);
return this;
}
ilikeAnyOf(column, patterns) {
this.url.searchParams.append(column, `ilike(any).{${patterns.join(",")}}`);
return this;
}
is(column, value) {
this.url.searchParams.append(column, `is.${value}`);
return this;
}
in(column, values) {
const cleanedValues = values.map((s3) => {
if (typeof s3 === "string" && new RegExp("[,()]").test(s3))
return `"${s3}"`;
else
return `${s3}`;
}).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, type } = {}) {
let typePart = "";
if (type === "plain") {
typePart = "pl";
} else if (type === "phrase") {
typePart = "ph";
} else if (type === "websearch") {
typePart = "w";
}
const configPart = config === void 0 ? "" : `(${config})`;
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, referencedTable = foreignTable } = {}) {
const key = referencedTable ? `${referencedTable}.or` : "or";
this.url.searchParams.append(key, `(${filters})`);
return this;
}
filter(column, operator, value) {
this.url.searchParams.append(column, `${operator}.${value}`);
return this;
}
};
// node_modules/.pnpm/@supabase+postgrest-js@1.9.2/node_modules/@supabase/postgrest-js/dist/module/PostgrestQueryBuilder.js
var PostgrestQueryBuilder = class {
constructor(url, { headers = {}, schema, fetch: fetch3 }) {
this.url = url;
this.headers = headers;
this.schema = schema;
this.fetch = fetch3;
}
select(columns, { head = false, count } = {}) {
const method = head ? "HEAD" : "GET";
let quoted = false;
const cleanedColumns = (columns !== null && columns !== void 0 ? columns : "*").split("").map((c2) => {
if (/\s/.test(c2) && !quoted) {
return "";
}
if (c2 === '"') {
quoted = !quoted;
}
return c2;
}).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, defaultToNull = true } = {}) {
const method = "POST";
const prefersHeaders = [];
if (this.headers["Prefer"]) {
prefersHeaders.push(this.headers["Prefer"]);
}
if (count) {
prefersHeaders.push(`count=${count}`);
}
if (!defaultToNull) {
prefersHeaders.push("missing=default");
}
this.headers["Prefer"] = prefersHeaders.join(",");
if (Array.isArray(values)) {
const columns = values.reduce((acc, x2) => acc.concat(Object.keys(x2)), []);
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: values,
fetch: this.fetch,
allowEmpty: false
});
}
upsert(values, { onConflict, ignoreDuplicates = false, count, defaultToNull = true } = {}) {
const method = "POST";
const prefersHeaders = [`resolution=${ignoreDuplicates ? "ignore" : "merge"}-duplicates`];
if (onConflict !== void 0)
this.url.searchParams.set("on_conflict", onConflict);
if (this.headers["Prefer"]) {
prefersHeaders.push(this.headers["Prefer"]);
}
if (count) {
prefersHeaders.push(`count=${count}`);
}
if (!defaultToNull) {
prefersHeaders.push("missing=default");
}
this.headers["Prefer"] = prefersHeaders.join(",");
if (Array.isArray(values)) {
const columns = values.reduce((acc, x2) => acc.concat(Object.keys(x2)), []);
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: values,
fetch: this.fetch,
allowEmpty: false
});
}
update(values, { count } = {}) {
const method = "PATCH";
const prefersHeaders = [];
if (this.headers["Prefer"]) {
prefersHeaders.push(this.headers["Prefer"]);
}
if (count) {
prefersHeaders.push(`count=${count}`);
}
this.headers["Prefer"] = prefersHeaders.join(",");
return new PostgrestFilterBuilder({
method,
url: this.url,
headers: this.headers,
schema: this.schema,
body: values,
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
});
}
};
// node_modules/.pnpm/@supabase+postgrest-js@1.9.2/node_modules/@supabase/postgrest-js/dist/module/version.js
var version2 = "1.9.2";
// node_modules/.pnpm/@supabase+postgrest-js@1.9.2/node_modules/@supabase/postgrest-js/dist/module/constants.js
var DEFAULT_HEADERS = { "X-Client-Info": `postgrest-js/${version2}` };
// node_modules/.pnpm/@supabase+postgrest-js@1.9.2/node_modules/@supabase/postgrest-js/dist/module/PostgrestClient.js
var PostgrestClient = class {
constructor(url, { headers = {}, schema, fetch: fetch3 } = {}) {
this.url = url;
this.headers = Object.assign(Object.assign({}, DEFAULT_HEADERS), headers);
this.schemaName = schema;
this.fetch = fetch3;
}
from(relation) {
const url = new URL(`${this.url}/${relation}`);
return new PostgrestQueryBuilder(url, {
headers: Object.assign({}, this.headers),
schema: this.schemaName,
fetch: this.fetch
});
}
schema(schema) {
return new PostgrestClient(this.url, {
headers: this.headers,
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(([name, value]) => {
url.searchParams.append(name, `${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.schemaName,
body,
fetch: this.fetch,
allowEmpty: false
});
}
};
// node_modules/.pnpm/@supabase+realtime-js@2.9.3/node_modules/@supabase/realtime-js/dist/module/lib/version.js
var version3 = "2.9.3";
// node_modules/.pnpm/@supabase+realtime-js@2.9.3/node_modules/@supabase/realtime-js/dist/module/lib/constants.js
var DEFAULT_HEADERS2 = { "X-Client-Info": `realtime-js/${version3}` };
var VSN = "1.0.0";
var DEFAULT_TIMEOUT = 1e4;
var 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 = {}));
// node_modules/.pnpm/@supabase+realtime-js@2.9.3/node_modules/@supabase/realtime-js/dist/module/lib/timer.js
var Timer = class {
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));
}
};
// node_modules/.pnpm/@supabase+realtime-js@2.9.3/node_modules/@supabase/realtime-js/dist/module/lib/serializer.js
var Serializer = class {
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 };
}
};
// node_modules/.pnpm/@supabase+realtime-js@2.9.3/node_modules/@supabase/realtime-js/dist/module/lib/push.js
var Push = class {
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;
}
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;
this.channel.socket.push({
topic: this.channel.topic,
event: this.event,
payload: this.payload,
ref: this.ref,
join_ref: this.channel._joinRef()
});
}
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((h3) => h3.status === status).forEach((h3) => h3.callback(response));
}
_hasReceived(status) {
return this.receivedResp && this.receivedResp.status === status;
}
};
// node_modules/.pnpm/@supabase+realtime-js@2.9.3/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.js
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 = {}));
var RealtimePresence = class {
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((m3) => m3.presence_ref);
const curPresenceRefs = currentPresences.map((m3) => m3.presence_ref);
const joinedPresences = newPresences.filter((m3) => curPresenceRefs.indexOf(m3.presence_ref) < 0);
const leftPresences = currentPresences.filter((m3) => newPresenceRefs.indexOf(m3.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((m3) => m3.presence_ref);
const curPresences = currentPresences.filter((m3) => joinedPresenceRefs.indexOf(m3.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((m3) => m3.presence_ref);
currentPresences = currentPresences.filter((m3) => presenceRefsToRemove.indexOf(m3.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();
}
};
// node_modules/.pnpm/@supabase+realtime-js@2.9.3/node_modules/@supabase/realtime-js/dist/module/lib/transformers.js
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 = {}));
var 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;
}, {});
};
var convertColumn = (columnName, columns, record, skipTypes) => {
const column = columns.find((x2) => x2.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(value);
};
var 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(value);
default:
return noop(value);
}
};
var noop = (value) => {
return value;
};
var toBoolean = (value) => {
switch (value) {
case "t":
return true;
case "f":
return false;
default:
return value;
}
};
var toNumber = (value) => {
if (typeof value === "string") {
const parsedValue = parseFloat(value);
if (!Number.isNaN(parsedValue)) {
return parsedValue;
}
}
return value;
};
var toJson = (value) => {
if (typeof value === "string") {
try {
return JSON.parse(value);
} catch (error) {
console.log(`JSON parse error: ${error}`);
return value;
}
}
return value;
};
var 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;
};
var toTimestampString = (value) => {
if (typeof value === "string") {
return value.replace(" ", "T");
}
return value;
};
// node_modules/.pnpm/@supabase+realtime-js@2.9.3/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.js
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 = {}));
var RealtimeChannel = class {
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.subTopic = topic.replace(/^realtime:/i, "");
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);
this.broadcastEndpointURL = this._broadcastEndpointURL();
}
subscribe(callback, timeout = this.timeout) {
var _a, _b;
if (!this.socket.isConnected()) {
this.socket.connect();
}
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((e2) => callback && callback("CHANNEL_ERROR", e2));
this._onClose(() => callback && callback("CLOSED"));
const accessTokenPayload = {};
const config = {
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 }, 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 i2 = 0; i2 < bindingsLen; i2++) {
const clientPostgresBinding = clientPostgresBindings[i2];
const { filter: { event, schema, table, filter } } = clientPostgresBinding;
const serverPostgresFilter = serverPostgresFilters && serverPostgresFilters[i2];
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;
}
async track(payload, opts = {}) {
return await this.send({
type: "presence",
event: "track",
payload
}, opts.timeout || this.timeout);
}
async untrack(opts = {}) {
return await this.send({
type: "presence",
event: "untrack"
}, opts);
}
on(type, filter, callback) {
return this._on(type, filter, callback);
}
async send(args, opts = {}) {
var _a, _b;
if (!this._canPush() && args.type === "broadcast") {
const { event, payload: endpoint_payload } = args;
const options = {
method: "POST",
headers: {
apikey: (_a = this.socket.apiKey) !== null && _a !== void 0 ? _a : "",
"Content-Type": "application/json"
},
body: JSON.stringify({
messages: [
{ topic: this.subTopic, event, payload: endpoint_payload }
]
})
};
try {
const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_b = opts.timeout) !== null && _b !== void 0 ? _b : this.timeout);
if (response.ok) {
return "ok";
} else {
return "error";
}
} catch (error) {
if (error.name === "AbortError") {
return "timed out";
} else {
return "error";
}
}
} else {
return new Promise((resolve) => {
var _a2, _b2, _c;
const push = this._push(args.type, args, opts.timeout || this.timeout);
if (args.type === "broadcast" && !((_c = (_b2 = (_a2 = this.params) === null || _a2 === void 0 ? void 0 : _a2.config) === null || _b2 === void 0 ? void 0 : _b2.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", {});
}
});
}
_broadcastEndpointURL() {
let url = this.socket.endPoint;
url = url.replace(/^ws/i, "http");
url = url.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i, "");
return url.replace(/\/+$/, "") + "/api/broadcast";
}
async _fetchWithTimeout(url, options, timeout) {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
const response = await this.socket.fetch(url, Object.assign(Object.assign({}, options), { signal: controller.signal }));
clearTimeout(id);
return response;
}
_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 k2 in obj1) {
if (obj1[k2] !== obj2[k2]) {
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;
}
};
// node_modules/.pnpm/@supabase+realtime-js@2.9.3/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.js
var noop2 = () => {
};
var NATIVE_WEBSOCKET_AVAILABLE = typeof WebSocket !== "undefined";
var RealtimeClient = class {
constructor(endPoint, options) {
var _a;
this.accessToken = null;
this.apiKey = null;
this.channels = [];
this.endPoint = "";
this.headers = DEFAULT_HEADERS2;
this.params = {};
this.timeout = DEFAULT_TIMEOUT;
this.heartbeatIntervalMs = 3e4;
this.heartbeatTimer = void 0;
this.pendingHeartbeatRef = null;
this.ref = 0;
this.logger = noop2;
this.conn = null;
this.sendBuffer = [];
this.serializer = new Serializer();
this.stateChangeCallbacks = {
open: [],
close: [],
error: [],
message: []
};
this._resolveFetch = (customFetch) => {
let _fetch;
if (customFetch) {
_fetch = customFetch;
} else if (typeof fetch === "undefined") {
_fetch = (...args) => Promise.resolve().then(() => (init_browser(), browser_exports2)).then(({ default: fetch3 }) => fetch3(...args));
} else {
_fetch = fetch;
}
return (...args) => _fetch(...args);
};
this.endPoint = `${endPoint}/${TRANSPORTS.websocket}`;
if (options === null || options === void 0 ? void 0 : options.transport) {
this.transport = options.transport;
} else {
this.transport = null;
}
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.heartbeatIntervalMs)
this.heartbeatIntervalMs = options.heartbeatIntervalMs;
const accessToken = (_a = options === null || options === void 0 ? void 0 : options.params) === null || _a === void 0 ? void 0 : _a.apikey;
if (accessToken) {
this.accessToken = accessToken;
this.apiKey = accessToken;
}
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(async () => {
this.disconnect();
this.connect();
}, this.reconnectAfterMs);
this.fetch = this._resolveFetch(options === null || options === void 0 ? void 0 : options.fetch);
}
connect() {
if (this.conn) {
return;
}
if (this.transport) {
this.conn = new this.transport(this._endPointURL(), void 0, {
headers: this.headers
});
return;
}
if (NATIVE_WEBSOCKET_AVAILABLE) {
this.conn = new WebSocket(this._endPointURL());
this.setupConnection();
return;
}
this.conn = new WSWebSocketDummy(this._endPointURL(), void 0, {
close: () => {
this.conn = null;
}
});
Promise.resolve().then(() => __toESM(require_browser())).then(({ default: WS }) => {
this.conn = new WS(this._endPointURL(), void 0, {
headers: this.headers
});
this.setupConnection();
});
}
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;
}
async removeChannel(channel) {
const status = await channel.unsubscribe();
if (this.channels.length === 0) {
this.disconnect();
}
return status;
}
async removeAllChannels() {
const values_1 = await 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: {} }) {
const chan = new RealtimeChannel(`realtime:${topic}`, params, this);
this.channels.push(chan);
return chan;
}
push(data) {
const { topic, event, payload, ref } = data;
const 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()) {
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((c2) => c2.topic === topic && (c2._isJoined() || c2._isJoining()));
if (dupChannel) {
this.log("transport", `leaving duplicate topic "${topic}"`);
dupChannel.unsubscribe();
}
}
_remove(channel) {
this.channels = this.channels.filter((c2) => c2._joinRef() !== channel._joinRef());
}
setupConnection() {
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);
}
}
_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);
}
};
var WSWebSocketDummy = class {
constructor(address, _protocols, options) {
this.binaryType = "arraybuffer";
this.onclose = () => {
};
this.onerror = () => {
};
this.onmessage = () => {
};
this.onopen = () => {
};
this.readyState = SOCKET_STATES.connecting;
this.send = () => {
};
this.url = null;
this.url = address;
this.close = options.close;
}
};
// node_modules/.pnpm/@supabase+storage-js@2.5.5/node_modules/@supabase/storage-js/dist/module/lib/errors.js
var StorageError = class extends Error {
constructor(message) {
super(message);
this.__isStorageError = true;
this.name = "StorageError";
}
};
function isStorageError(error) {
return typeof error === "object" && error !== null && "__isStorageError" in error;
}
var StorageApiError = class extends StorageError {
constructor(message, status) {
super(message);
this.name = "StorageApiError";
this.status = status;
}
toJSON() {
return {
name: this.name,
message: this.message,
status: this.status
};
}
};
var StorageUnknownError = class extends StorageError {
constructor(message, originalError) {
super(message);
this.name = "StorageUnknownError";
this.originalError = originalError;
}
};
// node_modules/.pnpm/@supabase+storage-js@2.5.5/node_modules/@supabase/storage-js/dist/module/lib/helpers.js
var __awaiter2 = 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 (e2) {
reject(e2);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e2) {
reject(e2);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var resolveFetch2 = (customFetch) => {
let _fetch;
if (customFetch) {
_fetch = customFetch;
} else if (typeof fetch === "undefined") {
_fetch = (...args) => Promise.resolve().then(() => (init_browser(), browser_exports2)).then(({ default: fetch3 }) => fetch3(...args));
} else {
_fetch = fetch;
}
return (...args) => _fetch(...args);
};
var resolveResponse = () => __awaiter2(void 0, void 0, void 0, function* () {
if (typeof Response === "undefined") {
return (yield Promise.resolve().then(() => (init_browser(), browser_exports2))).Response;
}
return Response;
});
// node_modules/.pnpm/@supabase+storage-js@2.5.5/node_modules/@supabase/storage-js/dist/module/lib/fetch.js
var __awaiter3 = 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 (e2) {
reject(e2);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e2) {
reject(e2);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err);
var handleError = (error, reject) => __awaiter3(void 0, void 0, void 0, function* () {
const Res = yield resolveResponse();
if (error instanceof Res) {
error.json().then((err) => {
reject(new StorageApiError(_getErrorMessage(err), error.status || 500));
}).catch((err) => {
reject(new StorageUnknownError(_getErrorMessage(err), err));
});
} else {
reject(new StorageUnknownError(_getErrorMessage(error), error));
}
});
var _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" }, options === null || options === void 0 ? void 0 : options.headers);
params.body = JSON.stringify(body);
return Object.assign(Object.assign({}, params), parameters);
};
function _handleRequest(fetcher, method, url, options, parameters, body) {
return __awaiter3(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 get(fetcher, url, options, parameters) {
return __awaiter3(this, void 0, void 0, function* () {
return _handleRequest(fetcher, "GET", url, options, parameters);
});
}
function post(fetcher, url, body, options, parameters) {
return __awaiter3(this, void 0, void 0, function* () {
return _handleRequest(fetcher, "POST", url, options, parameters, body);
});
}
function put(fetcher, url, body, options, parameters) {
return __awaiter3(this, void 0, void 0, function* () {
return _handleRequest(fetcher, "PUT", url, options, parameters, body);
});
}
function remove(fetcher, url, body, options, parameters) {
return __awaiter3(this, void 0, void 0, function* () {
return _handleRequest(fetcher, "DELETE", url, options, parameters, body);
});
}
// node_modules/.pnpm/@supabase+storage-js@2.5.5/node_modules/@supabase/storage-js/dist/module/packages/StorageFileApi.js
var __awaiter4 = 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 (e2) {
reject(e2);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e2) {
reject(e2);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var DEFAULT_SEARCH_OPTIONS = {
limit: 100,
offset: 0,
sortBy: {
column: "name",
order: "asc"
}
};
var DEFAULT_FILE_OPTIONS = {
cacheControl: "3600",
contentType: "text/plain;charset=UTF-8",
upsert: false
};
var StorageFileApi = class {
constructor(url, headers = {}, bucketId, fetch3) {
this.url = url;
this.headers = headers;
this.bucketId = bucketId;
this.fetch = resolveFetch2(fetch3);
}
uploadOrUpdate(method, path, fileBody, fileOptions) {
return __awaiter4(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 } : {}));
const data = yield res.json();
if (res.ok) {
return {
data: { path: cleanPath, id: data.Id, fullPath: data.Key },
error: null
};
} else {
const error = data;
return { data: null, error };
}
} catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
upload(path, fileBody, fileOptions) {
return __awaiter4(this, void 0, void 0, function* () {
return this.uploadOrUpdate("POST", path, fileBody, fileOptions);
});
}
uploadToSignedUrl(path, token, fileBody, fileOptions) {
return __awaiter4(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
});
const data = yield res.json();
if (res.ok) {
return {
data: { path: cleanPath, fullPath: data.Key },
error: null
};
} else {
const error = data;
return { data: null, error };
}
} catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
createSignedUploadUrl(path) {
return __awaiter4(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 __awaiter4(this, void 0, void 0, function* () {
return this.uploadOrUpdate("PUT", path, fileBody, fileOptions);
});
}
move(fromPath, toPath) {
return __awaiter4(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 __awaiter4(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 __awaiter4(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 __awaiter4(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 __awaiter4(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 __awaiter4(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 __awaiter4(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("&");
}
};
// node_modules/.pnpm/@supabase+storage-js@2.5.5/node_modules/@supabase/storage-js/dist/module/lib/version.js
var version4 = "2.5.5";
// node_modules/.pnpm/@supabase+storage-js@2.5.5/node_modules/@supabase/storage-js/dist/module/lib/constants.js
var DEFAULT_HEADERS3 = { "X-Client-Info": `storage-js/${version4}` };
// node_modules/.pnpm/@supabase+storage-js@2.5.5/node_modules/@supabase/storage-js/dist/module/packages/StorageBucketApi.js
var __awaiter5 = 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 (e2) {
reject(e2);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e2) {
reject(e2);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var StorageBucketApi = class {
constructor(url, headers = {}, fetch3) {
this.url = url;
this.headers = Object.assign(Object.assign({}, DEFAULT_HEADERS3), headers);
this.fetch = resolveFetch2(fetch3);
}
listBuckets() {
return __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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;
}
});
}
};
// node_modules/.pnpm/@supabase+storage-js@2.5.5/node_modules/@supabase/storage-js/dist/module/StorageClient.js
var StorageClient = class extends StorageBucketApi {
constructor(url, headers = {}, fetch3) {
super(url, headers, fetch3);
}
from(id) {
return new StorageFileApi(this.url, this.headers, id, this.fetch);
}
};
// node_modules/.pnpm/@supabase+supabase-js@2.39.4/node_modules/@supabase/supabase-js/dist/module/lib/version.js
var version5 = "2.39.4";
// node_modules/.pnpm/@supabase+supabase-js@2.39.4/node_modules/@supabase/supabase-js/dist/module/lib/constants.js
var JS_ENV = "";
if (typeof Deno !== "undefined") {
JS_ENV = "deno";
} else if (typeof document !== "undefined") {
JS_ENV = "web";
} else if (typeof navigator !== "undefined" && navigator.product === "ReactNative") {
JS_ENV = "react-native";
} else {
JS_ENV = "node";
}
var DEFAULT_HEADERS4 = { "X-Client-Info": `supabase-js-${JS_ENV}/${version5}` };
var DEFAULT_GLOBAL_OPTIONS = {
headers: DEFAULT_HEADERS4
};
var DEFAULT_DB_OPTIONS = {
schema: "public"
};
var DEFAULT_AUTH_OPTIONS = {
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true,
flowType: "implicit"
};
var DEFAULT_REALTIME_OPTIONS = {};
// node_modules/.pnpm/@supabase+supabase-js@2.39.4/node_modules/@supabase/supabase-js/dist/module/lib/fetch.js
init_browser();
var __awaiter6 = 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 (e2) {
reject(e2);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e2) {
reject(e2);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var resolveFetch3 = (customFetch) => {
let _fetch;
if (customFetch) {
_fetch = customFetch;
} else if (typeof fetch === "undefined") {
_fetch = browser_default;
} else {
_fetch = fetch;
}
return (...args) => _fetch(...args);
};
var resolveHeadersConstructor = () => {
if (typeof Headers === "undefined") {
return Headers2;
}
return Headers;
};
var fetchWithAuth = (supabaseKey, getAccessToken, customFetch) => {
const fetch3 = resolveFetch3(customFetch);
const HeadersConstructor = resolveHeadersConstructor();
return (input, init) => __awaiter6(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 fetch3(input, Object.assign(Object.assign({}, init), { headers }));
});
};
// node_modules/.pnpm/@supabase+supabase-js@2.39.4/node_modules/@supabase/supabase-js/dist/module/lib/helpers.js
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)
};
}
// node_modules/.pnpm/@supabase+gotrue-js@2.62.2/node_modules/@supabase/gotrue-js/dist/module/lib/helpers.js
function expiresAt(expiresIn) {
const timeNow = Math.round(Date.now() / 1e3);
return timeNow + expiresIn;
}
function uuid2() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c2) {
const r = Math.random() * 16 | 0, v = c2 == "x" ? r : r & 3 | 8;
return v.toString(16);
});
}
var isBrowser = () => typeof document !== "undefined";
var localStorageWriteTests = {
tested: false,
writable: false
};
var supportsLocalStorage = () => {
if (!isBrowser()) {
return false;
}
try {
if (typeof globalThis.localStorage !== "object") {
return false;
}
} catch (e2) {
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 (e2) {
localStorageWriteTests.tested = true;
localStorageWriteTests.writable = false;
}
return localStorageWriteTests.writable;
};
function parseParametersFromURL(href) {
const result = {};
const url = new URL(href);
if (url.hash && url.hash[0] === "#") {
try {
const hashSearchParams = new URLSearchParams(url.hash.substring(1));
hashSearchParams.forEach((value, key) => {
result[key] = value;
});
} catch (e2) {
}
}
url.searchParams.forEach((value, key) => {
result[key] = value;
});
return result;
}
var resolveFetch4 = (customFetch) => {
let _fetch;
if (customFetch) {
_fetch = customFetch;
} else if (typeof fetch === "undefined") {
_fetch = (...args) => Promise.resolve().then(() => (init_browser(), browser_exports2)).then(({ default: fetch3 }) => fetch3(...args));
} else {
_fetch = fetch;
}
return (...args) => _fetch(...args);
};
var looksLikeFetchResponse = (maybeResponse) => {
return typeof maybeResponse === "object" && maybeResponse !== null && "status" in maybeResponse && "ok" in maybeResponse && "json" in maybeResponse && typeof maybeResponse.json === "function";
};
var setItemAsync = async (storage, key, data) => {
await storage.setItem(key, JSON.stringify(data));
};
var getItemAsync = async (storage, key) => {
const value = await storage.getItem(key);
if (!value) {
return null;
}
try {
return JSON.parse(value);
} catch (_a) {
return value;
}
};
var removeItemAsync = async (storage, key) => {
await storage.removeItem(key);
};
function decodeBase64URL(value) {
const key = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
let base64 = "";
let chr1, chr2, chr3;
let enc1, enc2, enc3, enc4;
let i2 = 0;
value = value.replace("-", "+").replace("_", "/");
while (i2 < value.length) {
enc1 = key.indexOf(value.charAt(i2++));
enc2 = key.indexOf(value.charAt(i2++));
enc3 = key.indexOf(value.charAt(i2++));
enc4 = key.indexOf(value.charAt(i2++));
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;
}
var Deferred = class {
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));
}
async function sleep(time) {
return await new Promise((accept) => {
setTimeout(() => accept(null), time);
});
}
function retryable(fn, isRetryable) {
const promise = new Promise((accept, reject) => {
;
(async () => {
for (let attempt = 0; attempt < Infinity; attempt++) {
try {
const result = await fn(attempt);
if (!isRetryable(attempt, null, result)) {
accept(result);
return;
}
} catch (e2) {
if (!isRetryable(attempt, e2)) {
reject(e2);
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") {
const charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
const charSetLen = charSet.length;
let verifier = "";
for (let i2 = 0; i2 < verifierLength; i2++) {
verifier += charSet.charAt(Math.floor(Math.random() * charSetLen));
}
return verifier;
}
crypto.getRandomValues(array);
return Array.from(array, dec2hex).join("");
}
async function sha256(randomString2) {
const encoder = new TextEncoder();
const encodedData = encoder.encode(randomString2);
const hash = await crypto.subtle.digest("SHA-256", encodedData);
const bytes = new Uint8Array(hash);
return Array.from(bytes).map((c2) => String.fromCharCode(c2)).join("");
}
function base64urlencode(str) {
return btoa(str).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
async function generatePKCEChallenge(verifier) {
const hasCryptoSupport = typeof crypto !== "undefined" && typeof crypto.subtle !== "undefined" && typeof TextEncoder !== "undefined";
if (!hasCryptoSupport) {
console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.");
return verifier;
}
const hashed = await sha256(verifier);
return base64urlencode(hashed);
}
// node_modules/.pnpm/@supabase+gotrue-js@2.62.2/node_modules/@supabase/gotrue-js/dist/module/lib/errors.js
var AuthError = class 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;
}
var AuthApiError = class 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";
}
var AuthUnknownError = class extends AuthError {
constructor(message, originalError) {
super(message);
this.name = "AuthUnknownError";
this.originalError = originalError;
}
};
var CustomAuthError = class extends AuthError {
constructor(message, name, status) {
super(message);
this.name = name;
this.status = status;
}
toJSON() {
return {
name: this.name,
message: this.message,
status: this.status
};
}
};
var AuthSessionMissingError = class extends CustomAuthError {
constructor() {
super("Auth session missing!", "AuthSessionMissingError", 400);
}
};
var AuthInvalidTokenResponseError = class extends CustomAuthError {
constructor() {
super("Auth session or user missing", "AuthInvalidTokenResponseError", 500);
}
};
var AuthInvalidCredentialsError = class extends CustomAuthError {
constructor(message) {
super(message, "AuthInvalidCredentialsError", 400);
}
};
var AuthImplicitGrantRedirectError = class 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
};
}
};
var AuthPKCEGrantCodeExchangeError = class 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
};
}
};
var AuthRetryableFetchError = class extends CustomAuthError {
constructor(message, status) {
super(message, "AuthRetryableFetchError", status);
}
};
function isAuthRetryableFetchError(error) {
return isAuthError(error) && error.name === "AuthRetryableFetchError";
}
var AuthWeakPasswordError = class extends CustomAuthError {
constructor(message, status, reasons) {
super(message, "AuthWeakPasswordError", status);
this.reasons = reasons;
}
};
// node_modules/.pnpm/@supabase+gotrue-js@2.62.2/node_modules/@supabase/gotrue-js/dist/module/lib/fetch.js
var __rest = function(s3, e2) {
var t2 = {};
for (var p in s3)
if (Object.prototype.hasOwnProperty.call(s3, p) && e2.indexOf(p) < 0)
t2[p] = s3[p];
if (s3 != null && typeof Object.getOwnPropertySymbols === "function")
for (var i2 = 0, p = Object.getOwnPropertySymbols(s3); i2 < p.length; i2++) {
if (e2.indexOf(p[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s3, p[i2]))
t2[p[i2]] = s3[p[i2]];
}
return t2;
};
var _getErrorMessage2 = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err);
var NETWORK_ERROR_CODES = [502, 503, 504];
async function handleError2(error) {
if (!looksLikeFetchResponse(error)) {
throw new AuthRetryableFetchError(_getErrorMessage2(error), 0);
}
if (NETWORK_ERROR_CODES.includes(error.status)) {
throw new AuthRetryableFetchError(_getErrorMessage2(error), error.status);
}
let data;
try {
data = await error.json();
} catch (e2) {
throw new AuthUnknownError(_getErrorMessage2(e2), e2);
}
if (typeof data === "object" && data && typeof data.weak_password === "object" && data.weak_password && Array.isArray(data.weak_password.reasons) && data.weak_password.reasons.length && data.weak_password.reasons.reduce((a3, i2) => a3 && typeof i2 === "string", true)) {
throw new AuthWeakPasswordError(_getErrorMessage2(data), error.status, data.weak_password.reasons);
}
throw new AuthApiError(_getErrorMessage2(data), error.status || 500);
}
var _getRequestParams2 = (method, options, parameters, body) => {
const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} };
if (method === "GET") {
return params;
}
params.headers = Object.assign({ "Content-Type": "application/json;charset=UTF-8" }, options === null || options === void 0 ? void 0 : options.headers);
params.body = JSON.stringify(body);
return Object.assign(Object.assign({}, params), parameters);
};
async function _request(fetcher, method, url, options) {
var _a;
const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers);
if (options === null || options === void 0 ? void 0 : options.jwt) {
headers["Authorization"] = `Bearer ${options.jwt}`;
}
const qs = (_a = options === null || options === void 0 ? void 0 : options.query) !== null && _a !== void 0 ? _a : {};
if (options === null || options === void 0 ? void 0 : options.redirectTo) {
qs["redirect_to"] = options.redirectTo;
}
const queryString = Object.keys(qs).length ? "?" + new URLSearchParams(qs).toString() : "";
const data = await _handleRequest2(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 };
}
async function _handleRequest2(fetcher, method, url, options, parameters, body) {
const requestParams = _getRequestParams2(method, options, parameters, body);
let result;
try {
result = await fetcher(url, requestParams);
} catch (e2) {
console.error(e2);
throw new AuthRetryableFetchError(_getErrorMessage2(e2), 0);
}
if (!result.ok) {
await handleError2(result);
}
if (options === null || options === void 0 ? void 0 : options.noResolveJson) {
return result;
}
try {
return await result.json();
} catch (e2) {
await handleError2(e2);
}
}
function _sessionResponse(data) {
var _a;
let session = null;
if (hasSession(data)) {
session = Object.assign({}, data);
if (!data.expires_at) {
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 _sessionResponsePassword(data) {
const response = _sessionResponse(data);
if (!response.error && data.weak_password && typeof data.weak_password === "object" && Array.isArray(data.weak_password.reasons) && data.weak_password.reasons.length && data.weak_password.message && typeof data.weak_password.message === "string" && data.weak_password.reasons.reduce((a3, i2) => a3 && typeof i2 === "string", true)) {
response.data.weak_password = data.weak_password;
}
return response;
}
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(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;
}
// node_modules/.pnpm/@supabase+gotrue-js@2.62.2/node_modules/@supabase/gotrue-js/dist/module/GoTrueAdminApi.js
var __rest2 = function(s3, e2) {
var t2 = {};
for (var p in s3)
if (Object.prototype.hasOwnProperty.call(s3, p) && e2.indexOf(p) < 0)
t2[p] = s3[p];
if (s3 != null && typeof Object.getOwnPropertySymbols === "function")
for (var i2 = 0, p = Object.getOwnPropertySymbols(s3); i2 < p.length; i2++) {
if (e2.indexOf(p[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s3, p[i2]))
t2[p[i2]] = s3[p[i2]];
}
return t2;
};
var GoTrueAdminApi = class {
constructor({ url = "", headers = {}, fetch: fetch3 }) {
this.url = url;
this.headers = headers;
this.fetch = resolveFetch4(fetch3);
this.mfa = {
listFactors: this._listFactors.bind(this),
deleteFactor: this._deleteFactor.bind(this)
};
}
async signOut(jwt, scope = "global") {
try {
await _request(this.fetch, "POST", `${this.url}/logout?scope=${scope}`, {
headers: this.headers,
jwt,
noResolveJson: true
});
return { data: null, error: null };
} catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
async inviteUserByEmail(email, options = {}) {
try {
return await _request(this.fetch, "POST", `${this.url}/invite`, {
body: { email, data: options.data },
headers: this.headers,
redirectTo: options.redirectTo,
xform: _userResponse
});
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
async generateLink(params) {
try {
const { options } = params, rest = __rest2(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 await _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;
}
}
async createUser(attributes) {
try {
return await _request(this.fetch, "POST", `${this.url}/admin/users`, {
body: attributes,
headers: this.headers,
xform: _userResponse
});
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
async listUsers(params) {
var _a, _b, _c, _d, _e, _f, _g;
try {
const pagination = { nextPage: null, lastPage: 0, total: 0 };
const response = await _request(this.fetch, "GET", `${this.url}/admin/users`, {
headers: this.headers,
noResolveJson: true,
query: {
page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : "",
per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ""
},
xform: _noResolveJsonResponse
});
if (response.error)
throw response.error;
const users = await response.json();
const total = (_e = response.headers.get("x-total-count")) !== null && _e !== void 0 ? _e : 0;
const links = (_g = (_f = response.headers.get("link")) === null || _f === void 0 ? void 0 : _f.split(",")) !== null && _g !== void 0 ? _g : [];
if (links.length > 0) {
links.forEach((link) => {
const page = parseInt(link.split(";")[0].split("=")[1].substring(0, 1));
const rel = JSON.parse(link.split(";")[1].split("=")[1]);
pagination[`${rel}Page`] = page;
});
pagination.total = parseInt(total);
}
return { data: Object.assign(Object.assign({}, users), pagination), error: null };
} catch (error) {
if (isAuthError(error)) {
return { data: { users: [] }, error };
}
throw error;
}
}
async getUserById(uid) {
try {
return await _request(this.fetch, "GET", `${this.url}/admin/users/${uid}`, {
headers: this.headers,
xform: _userResponse
});
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
async updateUserById(uid, attributes) {
try {
return await _request(this.fetch, "PUT", `${this.url}/admin/users/${uid}`, {
body: attributes,
headers: this.headers,
xform: _userResponse
});
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
async deleteUser(id, shouldSoftDelete = false) {
try {
return await _request(this.fetch, "DELETE", `${this.url}/admin/users/${id}`, {
headers: this.headers,
body: {
should_soft_delete: shouldSoftDelete
},
xform: _userResponse
});
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
async _listFactors(params) {
try {
const { data, error } = await _request(this.fetch, "GET", `${this.url}/admin/users/${params.userId}/factors`, {
headers: this.headers,
xform: (factors) => {
return { data: { factors }, error: null };
}
});
return { data, error };
} catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
async _deleteFactor(params) {
try {
const data = await _request(this.fetch, "DELETE", `${this.url}/admin/users/${params.userId}/factors/${params.id}`, {
headers: this.headers
});
return { data, error: null };
} catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
};
// node_modules/.pnpm/@supabase+gotrue-js@2.62.2/node_modules/@supabase/gotrue-js/dist/module/lib/version.js
var version6 = "0.0.0";
// node_modules/.pnpm/@supabase+gotrue-js@2.62.2/node_modules/@supabase/gotrue-js/dist/module/lib/constants.js
var GOTRUE_URL = "http://localhost:9999";
var STORAGE_KEY = "supabase.auth.token";
var DEFAULT_HEADERS5 = { "X-Client-Info": `gotrue-js/${version6}` };
var EXPIRY_MARGIN = 10;
// node_modules/.pnpm/@supabase+gotrue-js@2.62.2/node_modules/@supabase/gotrue-js/dist/module/lib/local-storage.js
var 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 memoryLocalStorageAdapter(store = {}) {
return {
getItem: (key) => {
return store[key] || null;
},
setItem: (key, value) => {
store[key] = value;
},
removeItem: (key) => {
delete store[key];
}
};
}
// node_modules/.pnpm/@supabase+gotrue-js@2.62.2/node_modules/@supabase/gotrue-js/dist/module/lib/polyfills.js
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 (e2) {
if (typeof self !== "undefined") {
self.globalThis = self;
}
}
}
// node_modules/.pnpm/@supabase+gotrue-js@2.62.2/node_modules/@supabase/gotrue-js/dist/module/lib/locks.js
var internals = {
debug: !!(globalThis && supportsLocalStorage() && globalThis.localStorage && globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug") === "true")
};
var LockAcquireTimeoutError = class extends Error {
constructor(message) {
super(message);
this.isAcquireTimeout = true;
}
};
var NavigatorLockAcquireTimeoutError = class extends LockAcquireTimeoutError {
};
async function navigatorLock(name, acquireTimeout, fn) {
if (internals.debug) {
console.log("@supabase/gotrue-js: navigatorLock: acquire lock", name, acquireTimeout);
}
const abortController = new globalThis.AbortController();
if (acquireTimeout > 0) {
setTimeout(() => {
abortController.abort();
if (internals.debug) {
console.log("@supabase/gotrue-js: navigatorLock acquire timed out", name);
}
}, acquireTimeout);
}
return await globalThis.navigator.locks.request(name, acquireTimeout === 0 ? {
mode: "exclusive",
ifAvailable: true
} : {
mode: "exclusive",
signal: abortController.signal
}, async (lock) => {
if (lock) {
if (internals.debug) {
console.log("@supabase/gotrue-js: navigatorLock: acquired", name, lock.name);
}
try {
return await fn();
} finally {
if (internals.debug) {
console.log("@supabase/gotrue-js: navigatorLock: released", name, lock.name);
}
}
} else {
if (acquireTimeout === 0) {
if (internals.debug) {
console.log("@supabase/gotrue-js: navigatorLock: not immediately available", name);
}
throw new NavigatorLockAcquireTimeoutError(`Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed`);
} else {
if (internals.debug) {
try {
const result = await globalThis.navigator.locks.query();
console.log("@supabase/gotrue-js: Navigator LockManager state", JSON.stringify(result, null, " "));
} catch (e2) {
console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state", e2);
}
}
console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request");
return await fn();
}
}
});
}
// node_modules/.pnpm/@supabase+gotrue-js@2.62.2/node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.js
polyfillGlobalThis();
var DEFAULT_OPTIONS = {
url: GOTRUE_URL,
storageKey: STORAGE_KEY,
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true,
headers: DEFAULT_HEADERS5,
flowType: "implicit",
debug: false
};
var AUTO_REFRESH_TICK_DURATION = 30 * 1e3;
var AUTO_REFRESH_TICK_THRESHOLD = 3;
async function lockNoOp(name, acquireTimeout, fn) {
return await fn();
}
var GoTrueClient = class {
constructor(options) {
var _a, _b;
this.memoryStorage = null;
this.stateChangeEmitters = /* @__PURE__ */ new Map();
this.autoRefreshTicker = null;
this.visibilityChangedCallback = null;
this.refreshingDeferred = null;
this.initializePromise = null;
this.detectSessionInUrl = true;
this.lockAcquired = false;
this.pendingInLock = [];
this.broadcastChannel = null;
this.logger = console.log;
this.instanceID = GoTrueClient.nextInstanceID;
GoTrueClient.nextInstanceID += 1;
if (this.instanceID > 0 && isBrowser()) {
console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");
}
const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options);
this.logDebugMessages = !!settings.debug;
if (typeof settings.debug === "function") {
this.logger = settings.debug;
}
this.persistSession = settings.persistSession;
this.storageKey = settings.storageKey;
this.autoRefreshToken = settings.autoRefreshToken;
this.admin = new GoTrueAdminApi({
url: settings.url,
headers: settings.headers,
fetch: settings.fetch
});
this.url = settings.url;
this.headers = settings.headers;
this.fetch = resolveFetch4(settings.fetch);
this.lock = settings.lock || lockNoOp;
this.detectSessionInUrl = settings.detectSessionInUrl;
this.flowType = settings.flowType;
if (settings.lock) {
this.lock = settings.lock;
} else if (isBrowser() && ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _a === void 0 ? void 0 : _a.locks)) {
this.lock = navigatorLock;
} else {
this.lock = lockNoOp;
}
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 (this.persistSession) {
if (settings.storage) {
this.storage = settings.storage;
} else {
if (supportsLocalStorage()) {
this.storage = localStorageAdapter;
} else {
this.memoryStorage = {};
this.storage = memoryLocalStorageAdapter(this.memoryStorage);
}
}
} else {
this.memoryStorage = {};
this.storage = memoryLocalStorageAdapter(this.memoryStorage);
}
if (isBrowser() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) {
try {
this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey);
} catch (e2) {
console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available", e2);
}
(_b = this.broadcastChannel) === null || _b === void 0 ? void 0 : _b.addEventListener("message", async (event) => {
this._debug("received broadcast notification from other tab or client", event);
await this._notifyAllSubscribers(event.data.event, event.data.session, false);
});
}
this.initialize();
}
_debug(...args) {
if (this.logDebugMessages) {
this.logger(`GoTrueClient@${this.instanceID} (${version6}) ${new Date().toISOString()}`, ...args);
}
return this;
}
async initialize() {
if (this.initializePromise) {
return await this.initializePromise;
}
this.initializePromise = (async () => {
return await this._acquireLock(-1, async () => {
return await this._initialize();
});
})();
return await this.initializePromise;
}
async _initialize() {
try {
const isPKCEFlow = isBrowser() ? await this._isPKCEFlow() : false;
this._debug("#_initialize()", "begin", "is PKCE flow", isPKCEFlow);
if (isPKCEFlow || this.detectSessionInUrl && this._isImplicitGrantFlow()) {
const { data, error } = await this._getSessionFromURL(isPKCEFlow);
if (error) {
this._debug("#_initialize()", "error detecting session from URL", error);
if ((error === null || error === void 0 ? void 0 : error.message) === "Identity is already linked" || (error === null || error === void 0 ? void 0 : error.message) === "Identity is already linked to another user") {
return { error };
}
await this._removeSession();
return { error };
}
const { session, redirectType } = data;
this._debug("#_initialize()", "detected session in URL", session, "redirect type", redirectType);
await this._saveSession(session);
setTimeout(async () => {
if (redirectType === "recovery") {
await this._notifyAllSubscribers("PASSWORD_RECOVERY", session);
} else {
await this._notifyAllSubscribers("SIGNED_IN", session);
}
}, 0);
return { error: null };
}
await this._recoverAndRefresh();
return { error: null };
} catch (error) {
if (isAuthError(error)) {
return { error };
}
return {
error: new AuthUnknownError("Unexpected error during initialization", error)
};
} finally {
await this._handleVisibilityChange();
this._debug("#_initialize()", "end");
}
}
async signUp(credentials) {
var _a, _b, _c;
try {
await this._removeSession();
let res;
if ("email" in credentials) {
const { email, password, options } = credentials;
let codeChallenge = null;
let codeChallengeMethod = null;
if (this.flowType === "pkce") {
const codeVerifier = generatePKCEVerifier();
await setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier);
codeChallenge = await generatePKCEChallenge(codeVerifier);
codeChallengeMethod = codeVerifier === codeChallenge ? "plain" : "s256";
}
res = await _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 },
code_challenge: codeChallenge,
code_challenge_method: codeChallengeMethod
},
xform: _sessionResponse
});
} else if ("phone" in credentials) {
const { phone, password, options } = credentials;
res = await _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) {
await this._saveSession(data.session);
await 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;
}
}
async signInWithPassword(credentials) {
try {
await this._removeSession();
let res;
if ("email" in credentials) {
const { email, password, options } = credentials;
res = await _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: _sessionResponsePassword
});
} else if ("phone" in credentials) {
const { phone, password, options } = credentials;
res = await _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: _sessionResponsePassword
});
} else {
throw new AuthInvalidCredentialsError("You must provide either an email or phone number and a password");
}
const { data, error } = res;
if (error) {
return { data: { user: null, session: null }, error };
} else if (!data || !data.session || !data.user) {
return { data: { user: null, session: null }, error: new AuthInvalidTokenResponseError() };
}
if (data.session) {
await this._saveSession(data.session);
await this._notifyAllSubscribers("SIGNED_IN", data.session);
}
return {
data: Object.assign({ user: data.user, session: data.session }, data.weak_password ? { weakPassword: data.weak_password } : null),
error
};
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error };
}
throw error;
}
}
async signInWithOAuth(credentials) {
var _a, _b, _c, _d;
await this._removeSession();
return await 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
});
}
async exchangeCodeForSession(authCode) {
await this.initializePromise;
return this._acquireLock(-1, async () => {
return this._exchangeCodeForSession(authCode);
});
}
async _exchangeCodeForSession(authCode) {
const storageItem = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`);
const [codeVerifier, redirectType] = (storageItem !== null && storageItem !== void 0 ? storageItem : "").split("/");
const { data, error } = await _request(this.fetch, "POST", `${this.url}/token?grant_type=pkce`, {
headers: this.headers,
body: {
auth_code: authCode,
code_verifier: codeVerifier
},
xform: _sessionResponse
});
await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`);
if (error) {
return { data: { user: null, session: null, redirectType: null }, error };
} else if (!data || !data.session || !data.user) {
return {
data: { user: null, session: null, redirectType: null },
error: new AuthInvalidTokenResponseError()
};
}
if (data.session) {
await this._saveSession(data.session);
await this._notifyAllSubscribers("SIGNED_IN", data.session);
}
return { data: Object.assign(Object.assign({}, data), { redirectType: redirectType !== null && redirectType !== void 0 ? redirectType : null }), error };
}
async signInWithIdToken(credentials) {
await this._removeSession();
try {
const { options, provider, token, access_token, nonce } = credentials;
const res = await _request(this.fetch, "POST", `${this.url}/token?grant_type=id_token`, {
headers: this.headers,
body: {
provider,
id_token: token,
access_token,
nonce,
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }
},
xform: _sessionResponse
});
const { data, error } = res;
if (error) {
return { data: { user: null, session: null }, error };
} else if (!data || !data.session || !data.user) {
return {
data: { user: null, session: null },
error: new AuthInvalidTokenResponseError()
};
}
if (data.session) {
await this._saveSession(data.session);
await this._notifyAllSubscribers("SIGNED_IN", data.session);
}
return { data, error };
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error };
}
throw error;
}
}
async signInWithOtp(credentials) {
var _a, _b, _c, _d, _e;
try {
await this._removeSession();
if ("email" in credentials) {
const { email, options } = credentials;
let codeChallenge = null;
let codeChallengeMethod = null;
if (this.flowType === "pkce") {
const codeVerifier = generatePKCEVerifier();
await setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier);
codeChallenge = await generatePKCEChallenge(codeVerifier);
codeChallengeMethod = codeVerifier === codeChallenge ? "plain" : "s256";
}
const { error } = await _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: codeChallengeMethod
},
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 { data, error } = await _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, messageId: data === null || data === void 0 ? void 0 : data.message_id }, 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;
}
}
async verifyOtp(params) {
var _a, _b;
try {
if (params.type !== "email_change" && params.type !== "phone_change") {
await this._removeSession();
}
let redirectTo = void 0;
let captchaToken = void 0;
if ("options" in params) {
redirectTo = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo;
captchaToken = (_b = params.options) === null || _b === void 0 ? void 0 : _b.captchaToken;
}
const { data, error } = await _request(this.fetch, "POST", `${this.url}/verify`, {
headers: this.headers,
body: Object.assign(Object.assign({}, params), { gotrue_meta_security: { captcha_token: captchaToken } }),
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) {
await this._saveSession(session);
await this._notifyAllSubscribers(params.type == "recovery" ? "PASSWORD_RECOVERY" : "SIGNED_IN", session);
}
return { data: { user, session }, error: null };
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error };
}
throw error;
}
}
async signInWithSSO(params) {
var _a, _b, _c;
try {
await this._removeSession();
let codeChallenge = null;
let codeChallengeMethod = null;
if (this.flowType === "pkce") {
const codeVerifier = generatePKCEVerifier();
await setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier);
codeChallenge = await generatePKCEChallenge(codeVerifier);
codeChallengeMethod = codeVerifier === codeChallenge ? "plain" : "s256";
}
return await _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, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }),
headers: this.headers,
xform: _ssoResponse
});
} catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
async reauthenticate() {
await this.initializePromise;
return await this._acquireLock(-1, async () => {
return await this._reauthenticate();
});
}
async _reauthenticate() {
try {
return await this._useSession(async (result) => {
const { data: { session }, error: sessionError } = result;
if (sessionError)
throw sessionError;
if (!session)
throw new AuthSessionMissingError();
const { error } = await _request(this.fetch, "GET", `${this.url}/reauthenticate`, {
headers: this.headers,
jwt: session.access_token
});
return { data: { user: null, session: null }, error };
});
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error };
}
throw error;
}
}
async resend(credentials) {
try {
if (credentials.type != "email_change" && credentials.type != "phone_change") {
await this._removeSession();
}
const endpoint = `${this.url}/resend`;
if ("email" in credentials) {
const { email, type, options } = credentials;
const { error } = await _request(this.fetch, "POST", endpoint, {
headers: this.headers,
body: {
email,
type,
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }
},
redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo
});
return { data: { user: null, session: null }, error };
} else if ("phone" in credentials) {
const { phone, type, options } = credentials;
const { data, error } = await _request(this.fetch, "POST", endpoint, {
headers: this.headers,
body: {
phone,
type,
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }
}
});
return { data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, error };
}
throw new AuthInvalidCredentialsError("You must provide either an email or phone number and a type");
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error };
}
throw error;
}
}
async getSession() {
await this.initializePromise;
return this._acquireLock(-1, async () => {
return this._useSession(async (result) => {
return result;
});
});
}
async _acquireLock(acquireTimeout, fn) {
this._debug("#_acquireLock", "begin", acquireTimeout);
try {
if (this.lockAcquired) {
const last = this.pendingInLock.length ? this.pendingInLock[this.pendingInLock.length - 1] : Promise.resolve();
const result = (async () => {
await last;
return await fn();
})();
this.pendingInLock.push((async () => {
try {
await result;
} catch (e2) {
}
})());
return result;
}
return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => {
this._debug("#_acquireLock", "lock acquired for storage key", this.storageKey);
try {
this.lockAcquired = true;
const result = fn();
this.pendingInLock.push((async () => {
try {
await result;
} catch (e2) {
}
})());
await result;
while (this.pendingInLock.length) {
const waitOn = [...this.pendingInLock];
await Promise.all(waitOn);
this.pendingInLock.splice(0, waitOn.length);
}
return await result;
} finally {
this._debug("#_acquireLock", "lock released for storage key", this.storageKey);
this.lockAcquired = false;
}
});
} finally {
this._debug("#_acquireLock", "end");
}
}
async _useSession(fn) {
this._debug("#_useSession", "begin");
try {
const result = await this.__loadSession();
return await fn(result);
} finally {
this._debug("#_useSession", "end");
}
}
async __loadSession() {
this._debug("#__loadSession()", "begin");
if (!this.lockAcquired) {
this._debug("#__loadSession()", "used outside of an acquired lock!", new Error().stack);
}
try {
let currentSession = null;
const maybeSession = await getItemAsync(this.storage, this.storageKey);
this._debug("#getSession()", "session from storage", maybeSession);
if (maybeSession !== null) {
if (this._isValidSession(maybeSession)) {
currentSession = maybeSession;
} else {
this._debug("#getSession()", "session from storage is not valid");
await this._removeSession();
}
}
if (!currentSession) {
return { data: { session: null }, error: null };
}
const hasExpired = currentSession.expires_at ? currentSession.expires_at <= Date.now() / 1e3 : false;
this._debug("#__loadSession()", `session has${hasExpired ? "" : " not"} expired`, "expires_at", currentSession.expires_at);
if (!hasExpired) {
return { data: { session: currentSession }, error: null };
}
const { session, error } = await this._callRefreshToken(currentSession.refresh_token);
if (error) {
return { data: { session: null }, error };
}
return { data: { session }, error: null };
} finally {
this._debug("#__loadSession()", "end");
}
}
async getUser(jwt) {
if (jwt) {
return await this._getUser(jwt);
}
await this.initializePromise;
return this._acquireLock(-1, async () => {
return await this._getUser();
});
}
async _getUser(jwt) {
try {
if (jwt) {
return await _request(this.fetch, "GET", `${this.url}/user`, {
headers: this.headers,
jwt,
xform: _userResponse
});
}
return await this._useSession(async (result) => {
var _a, _b;
const { data, error } = result;
if (error) {
throw error;
}
return await _request(this.fetch, "GET", `${this.url}/user`, {
headers: this.headers,
jwt: (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : void 0,
xform: _userResponse
});
});
} catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
async updateUser(attributes, options = {}) {
await this.initializePromise;
return await this._acquireLock(-1, async () => {
return await this._updateUser(attributes, options);
});
}
async _updateUser(attributes, options = {}) {
try {
return await this._useSession(async (result) => {
const { data: sessionData, error: sessionError } = result;
if (sessionError) {
throw sessionError;
}
if (!sessionData.session) {
throw new AuthSessionMissingError();
}
const session = sessionData.session;
let codeChallenge = null;
let codeChallengeMethod = null;
if (this.flowType === "pkce" && attributes.email != null) {
const codeVerifier = generatePKCEVerifier();
await setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier);
codeChallenge = await generatePKCEChallenge(codeVerifier);
codeChallengeMethod = codeVerifier === codeChallenge ? "plain" : "s256";
}
const { data, error: userError } = await _request(this.fetch, "PUT", `${this.url}/user`, {
headers: this.headers,
redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo,
body: Object.assign(Object.assign({}, attributes), { code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }),
jwt: session.access_token,
xform: _userResponse
});
if (userError)
throw userError;
session.user = data.user;
await this._saveSession(session);
await 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);
}
async setSession(currentSession) {
await this.initializePromise;
return await this._acquireLock(-1, async () => {
return await this._setSession(currentSession);
});
}
async _setSession(currentSession) {
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 } = await 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 } = await 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
};
await this._saveSession(session);
await 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;
}
}
async refreshSession(currentSession) {
await this.initializePromise;
return await this._acquireLock(-1, async () => {
return await this._refreshSession(currentSession);
});
}
async _refreshSession(currentSession) {
try {
return await this._useSession(async (result) => {
var _a;
if (!currentSession) {
const { data, error: error2 } = result;
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 } = await 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;
}
}
async _getSessionFromURL(isPKCEFlow) {
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.");
}
const params = parseParametersFromURL(window.location.href);
if (isPKCEFlow) {
if (!params.code)
throw new AuthPKCEGrantCodeExchangeError("No code detected.");
const { data: data2, error: error2 } = await this._exchangeCodeForSession(params.code);
if (error2)
throw error2;
const url = new URL(window.location.href);
url.searchParams.delete("code");
window.history.replaceState(window.history.state, "", url.toString());
return { data: { session: data2.session, redirectType: null }, error: null };
}
if (params.error || params.error_description || params.error_code) {
throw new AuthImplicitGrantRedirectError(params.error_description || "Error in URL with unspecified error_description", {
error: params.error || "unspecified_error",
code: params.error_code || "unspecified_code"
});
}
const { provider_token, provider_refresh_token, access_token, refresh_token, expires_in, expires_at, token_type } = params;
if (!access_token || !expires_in || !refresh_token || !token_type) {
throw new AuthImplicitGrantRedirectError("No session defined in URL");
}
const timeNow = Math.round(Date.now() / 1e3);
const expiresIn = parseInt(expires_in);
let expiresAt2 = timeNow + expiresIn;
if (expires_at) {
expiresAt2 = parseInt(expires_at);
}
const actuallyExpiresIn = expiresAt2 - timeNow;
if (actuallyExpiresIn * 1e3 <= AUTO_REFRESH_TICK_DURATION) {
console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${actuallyExpiresIn}s, should have been closer to ${expiresIn}s`);
}
const issuedAt = expiresAt2 - expiresIn;
if (timeNow - issuedAt >= 120) {
console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale", issuedAt, expiresAt2, timeNow);
} else if (timeNow - issuedAt < 0) {
console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew", issuedAt, expiresAt2, timeNow);
}
const { data, error } = await this._getUser(access_token);
if (error)
throw error;
const session = {
provider_token,
provider_refresh_token,
access_token,
expires_in: expiresIn,
expires_at: expiresAt2,
refresh_token,
token_type,
user: data.user
};
window.location.hash = "";
this._debug("#_getSessionFromURL()", "clearing window.location.hash");
return { data: { session, redirectType: params.type }, error: null };
} catch (error) {
if (isAuthError(error)) {
return { data: { session: null, redirectType: null }, error };
}
throw error;
}
}
_isImplicitGrantFlow() {
const params = parseParametersFromURL(window.location.href);
return !!(isBrowser() && (params.access_token || params.error_description));
}
async _isPKCEFlow() {
const params = parseParametersFromURL(window.location.href);
const currentStorageContent = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`);
return !!(params.code && currentStorageContent);
}
async signOut(options = { scope: "global" }) {
await this.initializePromise;
return await this._acquireLock(-1, async () => {
return await this._signOut(options);
});
}
async _signOut({ scope } = { scope: "global" }) {
return await this._useSession(async (result) => {
var _a;
const { data, error: sessionError } = result;
if (sessionError) {
return { error: sessionError };
}
const accessToken = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token;
if (accessToken) {
const { error } = await this.admin.signOut(accessToken, scope);
if (error) {
if (!(isAuthApiError(error) && (error.status === 404 || error.status === 401))) {
return { error };
}
}
}
if (scope !== "others") {
await this._removeSession();
await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`);
await this._notifyAllSubscribers("SIGNED_OUT", null);
}
return { error: null };
});
}
onAuthStateChange(callback) {
const id = uuid2();
const subscription = {
id,
callback,
unsubscribe: () => {
this._debug("#unsubscribe()", "state change callback with id removed", id);
this.stateChangeEmitters.delete(id);
}
};
this._debug("#onAuthStateChange()", "registered callback with id", id);
this.stateChangeEmitters.set(id, subscription);
(async () => {
await this.initializePromise;
await this._acquireLock(-1, async () => {
this._emitInitialSession(id);
});
})();
return { data: { subscription } };
}
async _emitInitialSession(id) {
return await this._useSession(async (result) => {
var _a, _b;
try {
const { data: { session }, error } = result;
if (error)
throw error;
await ((_a = this.stateChangeEmitters.get(id)) === null || _a === void 0 ? void 0 : _a.callback("INITIAL_SESSION", session));
this._debug("INITIAL_SESSION", "callback id", id, "session", session);
} catch (err) {
await ((_b = this.stateChangeEmitters.get(id)) === null || _b === void 0 ? void 0 : _b.callback("INITIAL_SESSION", null));
this._debug("INITIAL_SESSION", "callback id", id, "error", err);
console.error(err);
}
});
}
async resetPasswordForEmail(email, options = {}) {
let codeChallenge = null;
let codeChallengeMethod = null;
if (this.flowType === "pkce") {
const codeVerifier = generatePKCEVerifier();
await setItemAsync(this.storage, `${this.storageKey}-code-verifier`, `${codeVerifier}/PASSWORD_RECOVERY`);
codeChallenge = await generatePKCEChallenge(codeVerifier);
codeChallengeMethod = codeVerifier === codeChallenge ? "plain" : "s256";
}
try {
return await _request(this.fetch, "POST", `${this.url}/recover`, {
body: {
email,
code_challenge: codeChallenge,
code_challenge_method: codeChallengeMethod,
gotrue_meta_security: { captcha_token: options.captchaToken }
},
headers: this.headers,
redirectTo: options.redirectTo
});
} catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
async getUserIdentities() {
var _a;
try {
const { data, error } = await this.getUser();
if (error)
throw error;
return { data: { identities: (_a = data.user.identities) !== null && _a !== void 0 ? _a : [] }, error: null };
} catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
async linkIdentity(credentials) {
var _a;
try {
const { data, error } = await this._useSession(async (result) => {
var _a2, _b, _c, _d, _e;
const { data: data2, error: error2 } = result;
if (error2)
throw error2;
const url = await this._getUrlForProvider(`${this.url}/user/identities/authorize`, credentials.provider, {
redirectTo: (_a2 = credentials.options) === null || _a2 === void 0 ? void 0 : _a2.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: true
});
return await _request(this.fetch, "GET", url, {
headers: this.headers,
jwt: (_e = (_d = data2.session) === null || _d === void 0 ? void 0 : _d.access_token) !== null && _e !== void 0 ? _e : void 0
});
});
if (error)
throw error;
if (isBrowser() && !((_a = credentials.options) === null || _a === void 0 ? void 0 : _a.skipBrowserRedirect)) {
window.location.assign(data === null || data === void 0 ? void 0 : data.url);
}
return { data: { provider: credentials.provider, url: data === null || data === void 0 ? void 0 : data.url }, error: null };
} catch (error) {
if (isAuthError(error)) {
return { data: { provider: credentials.provider, url: null }, error };
}
throw error;
}
}
async unlinkIdentity(identity) {
try {
return await this._useSession(async (result) => {
var _a, _b;
const { data, error } = result;
if (error) {
throw error;
}
return await _request(this.fetch, "DELETE", `${this.url}/user/identities/${identity.identity_id}`, {
headers: this.headers,
jwt: (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : void 0
});
});
} catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
async _refreshAccessToken(refreshToken) {
const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)`;
this._debug(debugName, "begin");
try {
const startedAt = Date.now();
return await retryable(async (attempt) => {
await sleep(attempt * 200);
this._debug(debugName, "refreshing attempt", attempt);
return await _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 && isAuthRetryableFetchError(result.error) && Date.now() + (attempt + 1) * 200 - startedAt < AUTO_REFRESH_TICK_DURATION);
} catch (error) {
this._debug(debugName, "error", error);
if (isAuthError(error)) {
return { data: { session: null, user: null }, error };
}
throw error;
} finally {
this._debug(debugName, "end");
}
}
_isValidSession(maybeSession) {
const isValidSession = typeof maybeSession === "object" && maybeSession !== null && "access_token" in maybeSession && "refresh_token" in maybeSession && "expires_at" in maybeSession;
return isValidSession;
}
async _handleProviderSignIn(provider, options) {
const url = await this._getUrlForProvider(`${this.url}/authorize`, provider, {
redirectTo: options.redirectTo,
scopes: options.scopes,
queryParams: options.queryParams
});
this._debug("#_handleProviderSignIn()", "provider", provider, "options", options, "url", url);
if (isBrowser() && !options.skipBrowserRedirect) {
window.location.assign(url);
}
return { data: { provider, url }, error: null };
}
async _recoverAndRefresh() {
var _a;
const debugName = "#_recoverAndRefresh()";
this._debug(debugName, "begin");
try {
const currentSession = await getItemAsync(this.storage, this.storageKey);
this._debug(debugName, "session from storage", currentSession);
if (!this._isValidSession(currentSession)) {
this._debug(debugName, "session is not valid");
if (currentSession !== null) {
await this._removeSession();
}
return;
}
const timeNow = Math.round(Date.now() / 1e3);
const expiresWithMargin = ((_a = currentSession.expires_at) !== null && _a !== void 0 ? _a : Infinity) < timeNow + EXPIRY_MARGIN;
this._debug(debugName, `session has${expiresWithMargin ? "" : " not"} expired with margin of ${EXPIRY_MARGIN}s`);
if (expiresWithMargin) {
if (this.autoRefreshToken && currentSession.refresh_token) {
const { error } = await this._callRefreshToken(currentSession.refresh_token);
if (error) {
console.error(error);
if (!isAuthRetryableFetchError(error)) {
this._debug(debugName, "refresh failed with a non-retryable error, removing the session", error);
await this._removeSession();
}
}
}
} else {
await this._notifyAllSubscribers("SIGNED_IN", currentSession);
}
} catch (err) {
this._debug(debugName, "error", err);
console.error(err);
return;
} finally {
this._debug(debugName, "end");
}
}
async _callRefreshToken(refreshToken) {
var _a, _b;
if (!refreshToken) {
throw new AuthSessionMissingError();
}
if (this.refreshingDeferred) {
return this.refreshingDeferred.promise;
}
const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)`;
this._debug(debugName, "begin");
try {
this.refreshingDeferred = new Deferred();
const { data, error } = await this._refreshAccessToken(refreshToken);
if (error)
throw error;
if (!data.session)
throw new AuthSessionMissingError();
await this._saveSession(data.session);
await this._notifyAllSubscribers("TOKEN_REFRESHED", data.session);
const result = { session: data.session, error: null };
this.refreshingDeferred.resolve(result);
return result;
} catch (error) {
this._debug(debugName, "error", error);
if (isAuthError(error)) {
const result = { session: null, error };
if (!isAuthRetryableFetchError(error)) {
await this._removeSession();
await this._notifyAllSubscribers("SIGNED_OUT", null);
}
(_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;
this._debug(debugName, "end");
}
}
async _notifyAllSubscribers(event, session, broadcast = true) {
const debugName = `#_notifyAllSubscribers(${event})`;
this._debug(debugName, "begin", session, `broadcast = ${broadcast}`);
try {
if (this.broadcastChannel && broadcast) {
this.broadcastChannel.postMessage({ event, session });
}
const errors = [];
const promises = Array.from(this.stateChangeEmitters.values()).map(async (x2) => {
try {
await x2.callback(event, session);
} catch (e2) {
errors.push(e2);
}
});
await Promise.all(promises);
if (errors.length > 0) {
for (let i2 = 0; i2 < errors.length; i2 += 1) {
console.error(errors[i2]);
}
throw errors[0];
}
} finally {
this._debug(debugName, "end");
}
}
async _saveSession(session) {
this._debug("#_saveSession()", session);
await setItemAsync(this.storage, this.storageKey, session);
}
async _removeSession() {
this._debug("#_removeSession()");
await removeItemAsync(this.storage, this.storageKey);
}
_removeVisibilityChangedCallback() {
this._debug("#_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 (e2) {
console.error("removing visibilitychange callback failed", e2);
}
}
async _startAutoRefresh() {
await this._stopAutoRefresh();
this._debug("#_startAutoRefresh()");
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);
}
setTimeout(async () => {
await this.initializePromise;
await this._autoRefreshTokenTick();
}, 0);
}
async _stopAutoRefresh() {
this._debug("#_stopAutoRefresh()");
const ticker = this.autoRefreshTicker;
this.autoRefreshTicker = null;
if (ticker) {
clearInterval(ticker);
}
}
async startAutoRefresh() {
this._removeVisibilityChangedCallback();
await this._startAutoRefresh();
}
async stopAutoRefresh() {
this._removeVisibilityChangedCallback();
await this._stopAutoRefresh();
}
async _autoRefreshTokenTick() {
this._debug("#_autoRefreshTokenTick()", "begin");
try {
await this._acquireLock(0, async () => {
try {
const now = Date.now();
try {
return await this._useSession(async (result) => {
const { data: { session } } = result;
if (!session || !session.refresh_token || !session.expires_at) {
this._debug("#_autoRefreshTokenTick()", "no session");
return;
}
const expiresInTicks = Math.floor((session.expires_at * 1e3 - now) / AUTO_REFRESH_TICK_DURATION);
this._debug("#_autoRefreshTokenTick()", `access token expires in ${expiresInTicks} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks`);
if (expiresInTicks <= AUTO_REFRESH_TICK_THRESHOLD) {
await this._callRefreshToken(session.refresh_token);
}
});
} catch (e2) {
console.error("Auto refresh tick failed with error. This is likely a transient error.", e2);
}
} finally {
this._debug("#_autoRefreshTokenTick()", "end");
}
});
} catch (e2) {
if (e2.isAcquireTimeout || e2 instanceof LockAcquireTimeoutError) {
this._debug("auto refresh token tick lock not available");
} else {
throw e2;
}
}
}
async _handleVisibilityChange() {
this._debug("#_handleVisibilityChange()");
if (!isBrowser() || !(window === null || window === void 0 ? void 0 : window.addEventListener)) {
if (this.autoRefreshToken) {
this.startAutoRefresh();
}
return false;
}
try {
this.visibilityChangedCallback = async () => await this._onVisibilityChanged(false);
window === null || window === void 0 ? void 0 : window.addEventListener("visibilitychange", this.visibilityChangedCallback);
await this._onVisibilityChanged(true);
} catch (error) {
console.error("_handleVisibilityChange", error);
}
}
async _onVisibilityChanged(calledFromInitialize) {
const methodName = `#_onVisibilityChanged(${calledFromInitialize})`;
this._debug(methodName, "visibilityState", document.visibilityState);
if (document.visibilityState === "visible") {
if (this.autoRefreshToken) {
this._startAutoRefresh();
}
if (!calledFromInitialize) {
await this.initializePromise;
await this._acquireLock(-1, async () => {
if (document.visibilityState !== "visible") {
this._debug(methodName, "acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");
return;
}
await this._recoverAndRefresh();
});
}
} else if (document.visibilityState === "hidden") {
if (this.autoRefreshToken) {
this._stopAutoRefresh();
}
}
}
async _getUrlForProvider(url, provider, options) {
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();
await setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier);
const codeChallenge = await generatePKCEChallenge(codeVerifier);
const codeChallengeMethod = codeVerifier === codeChallenge ? "plain" : "s256";
this._debug("PKCE", "code verifier", `${codeVerifier.substring(0, 5)}...`, "code challenge", codeChallenge, "method", codeChallengeMethod);
const flowParams = new URLSearchParams({
code_challenge: `${encodeURIComponent(codeChallenge)}`,
code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}`
});
urlParams.push(flowParams.toString());
}
if (options === null || options === void 0 ? void 0 : options.queryParams) {
const query = new URLSearchParams(options.queryParams);
urlParams.push(query.toString());
}
if (options === null || options === void 0 ? void 0 : options.skipBrowserRedirect) {
urlParams.push(`skip_http_redirect=${options.skipBrowserRedirect}`);
}
return `${url}?${urlParams.join("&")}`;
}
async _unenroll(params) {
try {
return await this._useSession(async (result) => {
var _a;
const { data: sessionData, error: sessionError } = result;
if (sessionError) {
return { data: null, error: sessionError };
}
return await _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;
}
}
async _enroll(params) {
try {
return await this._useSession(async (result) => {
var _a, _b;
const { data: sessionData, error: sessionError } = result;
if (sessionError) {
return { data: null, error: sessionError };
}
const { data, error } = await _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;
}
}
async _verify(params) {
return this._acquireLock(-1, async () => {
try {
return await this._useSession(async (result) => {
var _a;
const { data: sessionData, error: sessionError } = result;
if (sessionError) {
return { data: null, error: sessionError };
}
const { data, error } = await _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 };
}
await this._saveSession(Object.assign({ expires_at: Math.round(Date.now() / 1e3) + data.expires_in }, data));
await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED", data);
return { data, error };
});
} catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
});
}
async _challenge(params) {
return this._acquireLock(-1, async () => {
try {
return await this._useSession(async (result) => {
var _a;
const { data: sessionData, error: sessionError } = result;
if (sessionError) {
return { data: null, error: sessionError };
}
return await _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;
}
});
}
async _challengeAndVerify(params) {
const { data: challengeData, error: challengeError } = await this._challenge({
factorId: params.factorId
});
if (challengeError) {
return { data: null, error: challengeError };
}
return await this._verify({
factorId: params.factorId,
challengeId: challengeData.id,
code: params.code
});
}
async _listFactors() {
const { data: { user }, error: userError } = await 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
};
}
async _getAuthenticatorAssuranceLevel() {
return this._acquireLock(-1, async () => {
return await this._useSession(async (result) => {
var _a, _b;
const { data: { session }, error: sessionError } = result;
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 };
});
});
}
};
GoTrueClient.nextInstanceID = 0;
// node_modules/.pnpm/@supabase+supabase-js@2.39.4/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.js
var SupabaseAuthClient = class extends GoTrueClient {
constructor(options) {
super(options);
}
};
// node_modules/.pnpm/@supabase+supabase-js@2.39.4/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.js
var __awaiter7 = 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 (e2) {
reject(e2);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e2) {
reject(e2);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var SupabaseClient = class {
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`;
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);
}
schema(schema) {
return this.rest.schema(schema);
}
rpc(fn, args = {}, options) {
return this.rest.rpc(fn, args, options);
}
channel(name, opts = { config: {} }) {
return this.realtime.channel(name, opts);
}
getChannels() {
return this.realtime.getChannels();
}
removeChannel(channel) {
return this.realtime.removeChannel(channel);
}
removeAllChannels() {
return this.realtime.removeAllChannels();
}
_getAccessToken() {
var _a, _b;
return __awaiter7(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, debug }, headers, fetch3) {
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,
debug,
fetch: fetch3
});
}
_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, "CLIENT", session === null || session === void 0 ? void 0 : session.access_token);
});
return data;
}
_handleTokenChanged(event, source, token) {
if ((event === "TOKEN_REFRESHED" || event === "SIGNED_IN") && this.changedAccessToken !== token) {
this.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;
}
}
};
// node_modules/.pnpm/@supabase+supabase-js@2.39.4/node_modules/@supabase/supabase-js/dist/module/index.js
var createClient = (supabaseUrl, supabaseKey, options) => {
return new SupabaseClient(supabaseUrl, supabaseKey, options);
};
// src/fileLink.ts
var FileLink = class {
constructor(attachementFolder, basePath) {
this.attachementFolder = attachementFolder;
this.basePath = basePath;
}
embedFile(file) {
console.log("attached file path: " + this.attachementFolder);
console.log("vault path: " + this.basePath);
console.log("file: " + file.name);
}
};
// src/main.ts
var _Transcription = class extends import_obsidian4.Plugin {
constructor(app, manifest) {
super(app, manifest);
this.pendingCommand = null;
this.ongoingTranscriptionTasks = [];
this.supabase = createClient(SUPABASE_URL, SUPABASE_KEY, {
auth: {
detectSessionInUrl: false,
autoRefreshToken: true,
persistSession: true
}
});
this.getTranscribeableFiles = async (file) => {
const filesLinked = Object.keys(this.app.metadataCache.resolvedLinks[file.path]);
const filesToTranscribe = [];
for (const linkedFilePath of filesLinked) {
const linkedFileExtension = linkedFilePath.split(".").pop();
if (linkedFileExtension === void 0 || !_Transcription.transcribeFileExtensions.includes(linkedFileExtension.toLowerCase())) {
if (this.settings.debug)
console.log("Skipping " + linkedFilePath + " because the file extension is not in the list of transcribeable file extensions");
continue;
}
const linkedFile = this.app.vault.getAbstractFileByPath(linkedFilePath);
if (linkedFile instanceof import_obsidian4.TFile)
filesToTranscribe.push(linkedFile);
else {
if (this.settings.debug)
console.log("Could not find file " + linkedFilePath);
continue;
}
}
return filesToTranscribe;
};
}
querySelectionOnAuthentication(authString, display) {
if (authString === ".swiftink-manage-account-btn") {
return document.querySelectorAll(authString).forEach((element) => {
var _a;
element.innerHTML = `Manage ${(_a = this.user) == null ? void 0 : _a.email}`;
});
} else {
return document.querySelectorAll(authString).forEach((element) => {
element.setAttribute("style", display);
});
}
}
async executePendingCommand(pendingCommand) {
try {
const session = await this.supabase.auth.getSession().then((res) => {
return res.data;
});
if (!session || !session.session) {
throw new Error("User not authenticated.");
}
if (pendingCommand == null ? void 0 : pendingCommand.file) {
const abortController = new AbortController();
const task = this.transcribeAndWrite(pendingCommand.parentFile, pendingCommand.file, abortController);
this.ongoingTranscriptionTasks.push({
task,
abortController
});
await task;
} else {
const filesToTranscribe = await this.getTranscribeableFiles(pendingCommand.parentFile);
for (const fileToTranscribe of filesToTranscribe) {
const abortController = new AbortController();
const task = this.transcribeAndWrite(pendingCommand.parentFile, fileToTranscribe, abortController);
this.ongoingTranscriptionTasks.push({ task, abortController });
await task;
}
}
} catch (error) {
console.error("Error during transcription process:", error);
}
}
async transcribeAndWrite(parent_file, file, abortController) {
var _a, _b;
try {
if (this.settings.debug)
console.log("Transcribing " + file.path);
const transcription = await this.transcriptionEngine.getTranscription(file);
let fileText = await this.app.vault.read(parent_file);
const fileLinkString = this.app.metadataCache.fileToLinktext(file, parent_file.path);
const fileLinkStringTagged = `[[${fileLinkString}]]`;
const startReplacementIndex = fileText.indexOf(fileLinkStringTagged) + fileLinkStringTagged.length;
if (this.settings.lineSpacing === "single") {
fileText = [
fileText.slice(0, startReplacementIndex),
`${transcription}`,
fileText.slice(startReplacementIndex)
].join(" ");
} else {
fileText = [
fileText.slice(0, startReplacementIndex),
`
${transcription}`,
fileText.slice(startReplacementIndex)
].join("");
}
if ((_a = abortController == null ? void 0 : abortController.signal) == null ? void 0 : _a.aborted) {
new import_obsidian4.Notice(`Transcription of ${file.name} cancelled!`, 5 * 1e3);
return;
}
await this.app.vault.modify(parent_file, fileText);
} catch (error) {
if ((_b = error == null ? void 0 : error.message) == null ? void 0 : _b.includes("402")) {
new import_obsidian4.Notice("You have exceeded the free tier.\nPlease upgrade to a paid plan at swiftink.io/pricing to continue transcribing files.\nThanks for using Swiftink!", 10 * 1e3);
} else {
if (this.settings.debug)
console.log(error);
new import_obsidian4.Notice(`Error transcribing file: ${error}`, 10 * 1e3);
}
} finally {
abortController = null;
}
}
onFileMenu(menu, file) {
var _a;
const parentFile = this.app.workspace.getActiveFile();
if (parentFile instanceof import_obsidian4.TFile && file instanceof import_obsidian4.TFile) {
const fileExtension = (_a = file.extension) == null ? void 0 : _a.toLowerCase();
if (fileExtension && _Transcription.transcribeFileExtensions.includes(fileExtension)) {
menu.addItem((item) => {
item.setTitle("Transcribe").setIcon("headphones").onClick(async () => {
if (this.user == null && this.settings.transcriptionEngine == IS_SWIFTINK) {
this.pendingCommand = {
file,
parentFile
};
window.open(SWIFTINK_AUTH_CALLBACK, "_blank");
}
const abortController = new AbortController();
const task = this.transcribeAndWrite(parentFile, file, abortController);
this.ongoingTranscriptionTasks.push({
task,
abortController
});
await task;
});
});
}
}
}
async onload() {
await this.loadSettings();
_Transcription.plugin = this;
console.log("Loading Obsidian Transcription");
if (this.settings.debug)
console.log("Debug mode enabled");
this.transcriptionEngine = new TranscriptionEngine(this.settings, this.app.vault, this.statusBar, this.supabase, this.app);
if (this.settings.transcriptionEngine == "swiftink") {
this.user = await this.supabase.auth.getUser().then((res) => {
return res.data.user || null;
});
if (this.user == null) {
if (this.settings.debug)
console.log("Trying to set access token and refresh token from settings");
if (this.settings.swiftink_access_token != null && this.settings.swiftink_refresh_token != null) {
await this.supabase.auth.setSession({
access_token: this.settings.swiftink_access_token,
refresh_token: this.settings.swiftink_refresh_token
});
this.user = await this.supabase.auth.getUser().then((res) => {
return res.data.user || null;
});
}
if (this.user == null) {
const noticeContent = document.createDocumentFragment();
const textNode = document.createTextNode("Transcription: You are signed out. Please ");
const signInLink = document.createElement("a");
signInLink.target = "_blank";
signInLink.textContent = "Sign In";
noticeContent.appendChild(textNode);
noticeContent.appendChild(signInLink);
const notice = new import_obsidian4.Notice(noticeContent, 16 * 1e3);
notice.noticeEl.addEventListener("click", () => {
window.open(SWIFTINK_AUTH_CALLBACK, "_blank");
});
}
}
}
if (!import_obsidian4.Platform.isMobileApp) {
this.statusBar = new StatusBar(this.addStatusBarItem());
this.registerInterval(window.setInterval(() => this.statusBar.display(), 1e3));
}
this.registerEvent(this.app.workspace.on("file-menu", this.onFileMenu.bind(this)));
this.addCommand({
id: "obsidian-transcription-add-file",
name: "Add File to Transcription",
editorCallback: async () => {
class FileSelectionModal extends import_obsidian4.Modal {
onOpen() {
const { contentEl } = this;
contentEl.createEl("h2", { text: "Select files:" });
const input = contentEl.createEl("input", {
type: "file",
attr: { multiple: "" }
});
contentEl.createEl("br");
contentEl.createEl("br");
const button = contentEl.createEl("button", { text: "Add file link" });
button.addEventListener("click", () => {
const fileList = input.files;
if (fileList) {
const files = Array.from(fileList);
let path = "";
for (const file of files) {
path = this.app.vault.getResourcePath(file).toString();
}
const basePath = this.app.vault.adapter.basePath;
const fe = new FileLink(path, basePath);
files.forEach((file) => {
fe.embedFile(file);
});
}
});
}
}
new FileSelectionModal(this.app).open();
}
});
this.addCommand({
id: "obsidian-transcription-stop",
name: "Stop Transcription",
editorCallback: async () => {
try {
if (this.ongoingTranscriptionTasks.length > 0) {
console.log("Stopping ongoing transcription...");
for (const { abortController, task } of this.ongoingTranscriptionTasks) {
abortController.abort();
await task.catch(() => {
});
}
this.ongoingTranscriptionTasks = [];
} else {
new import_obsidian4.Notice("No ongoing transcription to stop", 5 * 1e3);
}
} catch (error) {
console.error("Error stopping transcription:", error);
}
}
});
this.addCommand({
id: "obsidian-transcription-transcribe-all-in-view",
name: "Transcribe all files in view",
editorCallback: async (editor, view) => {
if (view.file === null)
return;
const filesToTranscribe = await this.getTranscribeableFiles(view.file);
const fileNames = filesToTranscribe.map((file) => file.name).join(", ");
new import_obsidian4.Notice(`Files Selected: ${fileNames}`, 5 * 1e3);
if (this.user == null && this.settings.transcriptionEngine == IS_SWIFTINK) {
this.pendingCommand = {
parentFile: view.file
};
window.open(SWIFTINK_AUTH_CALLBACK, "_blank");
} else {
for (const fileToTranscribe of filesToTranscribe) {
const abortController = new AbortController();
const task = this.transcribeAndWrite(view.file, fileToTranscribe, abortController);
this.ongoingTranscriptionTasks.push({ task, abortController });
await task;
}
}
}
});
this.addCommand({
id: "obsidian-transcription-transcribe-specific-file-in-view",
name: "Transcribe file in view",
editorCallback: async (editor, view) => {
if (view.file === null)
return;
const filesToTranscribe = await this.getTranscribeableFiles(view.file);
class FileSelectionModal extends import_obsidian4.FuzzySuggestModal {
constructor(app, transcriptionInstance) {
super(app);
this.transcriptionInstance = transcriptionInstance;
}
getItems() {
return filesToTranscribe;
}
getItemText(file) {
return file.name;
}
async onChooseItem(file) {
if (view.file === null)
return;
new import_obsidian4.Notice(`File Selected: ${file.name}`, 5 * 1e3);
if (this.transcriptionInstance.user == null && this.transcriptionInstance.settings.transcriptionEngine == IS_SWIFTINK) {
this.transcriptionInstance.pendingCommand = {
file,
parentFile: view.file
};
window.open(SWIFTINK_AUTH_CALLBACK, "_blank");
} else {
const abortController = new AbortController();
const task = this.transcriptionInstance.transcribeAndWrite(view.file, file, abortController);
this.transcriptionInstance.ongoingTranscriptionTasks.push({
task,
abortController
});
await task;
}
}
}
new FileSelectionModal(this.app, this).open();
}
});
this.app.workspace.on("quit", () => {
_Transcription.children.forEach((child) => {
child.kill();
});
});
this.addSettingTab(new TranscriptionSettingTab(this.app, this));
this.registerObsidianProtocolHandler("swiftink_auth", async (callback) => {
const params = new URLSearchParams(callback.hash);
const access_token = params.get("access_token");
const refresh_token = params.get("refresh_token");
if (!access_token || !refresh_token) {
new import_obsidian4.Notice("Transcription: Error authenticating with Swiftink.io");
return;
}
await this.supabase.auth.setSession({
access_token,
refresh_token
});
this.user = await this.supabase.auth.getUser().then((res) => {
return res.data.user || null;
});
new import_obsidian4.Notice("Successfully authenticated with Swiftink.io");
this.settings.swiftink_access_token = access_token;
this.settings.swiftink_refresh_token = refresh_token;
await this.saveSettings();
if (this.user == null) {
this.querySelectionOnAuthentication(".swiftink-unauthed-only", "display: block !important");
this.querySelectionOnAuthentication(".swiftink-authed-only", "display: none !important");
} else {
this.querySelectionOnAuthentication(".swiftink-unauthed-only", "display: none !important");
this.querySelectionOnAuthentication(".swiftink-authed-only", "display: block !important");
this.querySelectionOnAuthentication(".swiftink-manage-account-btn", "");
}
if (this.pendingCommand) {
await this.executePendingCommand(this.pendingCommand);
this.pendingCommand = null;
}
return;
});
this.registerObsidianProtocolHandler("swiftink_transcript_functions", async (callback) => {
const id = callback.id;
console.log(id);
const functions = [
"View on Swiftink.io"
];
class SwiftinkTranscriptFunctionsModal extends import_obsidian4.FuzzySuggestModal {
getItems() {
return functions;
}
getItemText(function_name) {
return function_name;
}
onChooseItem(function_name) {
if (function_name == "View on Swiftink.io") {
window.open("https://swiftink.io/dashboard/transcripts/" + id, "_blank");
}
}
}
new SwiftinkTranscriptFunctionsModal(this.app).open();
});
}
onunload() {
if (this.settings.debug)
console.log("Unloading Obsidian Transcription");
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
};
var Transcription = _Transcription;
Transcription.children = [];
Transcription.transcribeFileExtensions = [
"mp3",
"wav",
"webm",
"ogg",
"flac",
"m4a",
"aac",
"amr",
"opus",
"aiff",
"m3gp",
"mp4",
"m4v",
"mov",
"avi",
"wmv",
"flv",
"mpeg",
"mpg",
"mkv"
];
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
/* nosourcemap */