'update'
This commit is contained in:
commit
ef22d7449f
4614 files changed
+353848
No files matched your search
+87
@@ -0,0 +1,87 @@
|
||||
|
||||
|
||||
|
||||
# Server configuration
|
||||
PORT=3001
|
||||
|
||||
# Environment variables for Supabase configuration
|
||||
SUPABASE_URL=https://spobwqqaskuhcmyeklgk.supabase.co
|
||||
SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InNwb2J3cXFhc2t1aGNteWVrbGdrIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE4NzU1NDcsImV4cCI6MjA3NzQ1MTU0N30.oJevtZ5RykT0QkALQdoIKL6OQoTKkNHCCjGaK8I1-2I
|
||||
|
||||
|
||||
# -- WARNING: This schema is for context only and is not meant to be run.
|
||||
# -- Table order and constraints may not be valid for execution.
|
||||
|
||||
# CREATE TABLE public.categories (
|
||||
# category_id integer NOT NULL DEFAULT nextval('categories_category_id_seq'::regclass),
|
||||
# name character varying NOT NULL,
|
||||
# description text,
|
||||
# CONSTRAINT categories_pkey PRIMARY KEY (category_id)
|
||||
# );
|
||||
# CREATE TABLE public.inventory_logs (
|
||||
# log_id integer NOT NULL DEFAULT nextval('inventory_logs_log_id_seq'::regclass),
|
||||
# product_id integer,
|
||||
# user_id integer,
|
||||
# action character varying CHECK (action::text = ANY (ARRAY['add'::character varying, 'remove'::character varying, 'sale'::character varying, 'adjust'::character varying]::text[])),
|
||||
# quantity integer NOT NULL,
|
||||
# remarks text,
|
||||
# log_date timestamp without time zone DEFAULT now(),
|
||||
# CONSTRAINT inventory_logs_pkey PRIMARY KEY (log_id),
|
||||
# CONSTRAINT inventory_logs_product_id_fkey FOREIGN KEY (product_id) REFERENCES public.products(product_id),
|
||||
# CONSTRAINT inventory_logs_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(user_id)
|
||||
# );
|
||||
# CREATE TABLE public.products (
|
||||
# product_id integer NOT NULL DEFAULT nextval('products_product_id_seq'::regclass),
|
||||
# barcode character varying,
|
||||
# name character varying NOT NULL,
|
||||
# category_id integer,
|
||||
# price numeric NOT NULL,
|
||||
# cost numeric,
|
||||
# stock integer DEFAULT 0,
|
||||
# unit character varying DEFAULT 'pcs'::character varying,
|
||||
# created_at timestamp without time zone DEFAULT now(),
|
||||
# updated_at timestamp without time zone DEFAULT now(),
|
||||
# CONSTRAINT products_pkey PRIMARY KEY (product_id),
|
||||
# CONSTRAINT products_category_id_fkey FOREIGN KEY (category_id) REFERENCES public.categories(category_id)
|
||||
# );
|
||||
# CREATE TABLE public.sale_items (
|
||||
# sale_item_id integer NOT NULL DEFAULT nextval('sale_items_sale_item_id_seq'::regclass),
|
||||
# sale_id integer,
|
||||
# product_id integer,
|
||||
# quantity integer NOT NULL,
|
||||
# price numeric NOT NULL,
|
||||
# total numeric DEFAULT ((quantity)::numeric * price),
|
||||
# CONSTRAINT sale_items_pkey PRIMARY KEY (sale_item_id),
|
||||
# CONSTRAINT sale_items_sale_id_fkey FOREIGN KEY (sale_id) REFERENCES public.sales(sale_id),
|
||||
# CONSTRAINT sale_items_product_id_fkey FOREIGN KEY (product_id) REFERENCES public.products(product_id)
|
||||
# );
|
||||
# CREATE TABLE public.sales (
|
||||
# sale_id integer NOT NULL DEFAULT nextval('sales_sale_id_seq'::regclass),
|
||||
# user_id integer,
|
||||
# total_amount numeric NOT NULL,
|
||||
# payment_type character varying DEFAULT 'cash'::character varying CHECK (payment_type::text = ANY (ARRAY['cash'::character varying, 'gcash'::character varying, 'card'::character varying]::text[])),
|
||||
# amount_tendered numeric,
|
||||
# change_due numeric,
|
||||
# sale_date timestamp without time zone DEFAULT now(),
|
||||
# status character varying DEFAULT 'completed'::character varying CHECK (status::text = ANY (ARRAY['completed'::character varying, 'voided'::character varying, 'refunded'::character varying]::text[])),
|
||||
# CONSTRAINT sales_pkey PRIMARY KEY (sale_id),
|
||||
# CONSTRAINT sales_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(user_id)
|
||||
# );
|
||||
# CREATE TABLE public.settings (
|
||||
# setting_id integer NOT NULL DEFAULT nextval('settings_setting_id_seq'::regclass),
|
||||
# store_name character varying,
|
||||
# address character varying,
|
||||
# contact character varying,
|
||||
# tax_rate numeric DEFAULT 0.00,
|
||||
# CONSTRAINT settings_pkey PRIMARY KEY (setting_id)
|
||||
# );
|
||||
# CREATE TABLE public.users (
|
||||
# user_id integer NOT NULL DEFAULT nextval('users_user_id_seq'::regclass),
|
||||
# full_name character varying NOT NULL,
|
||||
# username character varying NOT NULL UNIQUE,
|
||||
# password text NOT NULL,
|
||||
# role character varying DEFAULT 'cashier'::character varying CHECK (role::text = ANY (ARRAY['admin'::character varying, 'cashier'::character varying]::text[])),
|
||||
# status character varying DEFAULT 'active'::character varying CHECK (status::text = ANY (ARRAY['active'::character varying, 'inactive'::character varying]::text[])),
|
||||
# created_at timestamp without time zone DEFAULT now(),
|
||||
# CONSTRAINT users_pkey PRIMARY KEY (user_id)
|
||||
# );
|
||||
@@ -0,0 +1,11 @@
|
||||
// server/config/supabaseClient.js
|
||||
import { createClient } from "@supabase/supabase-js";
|
||||
import dotenv from 'dotenv'
|
||||
|
||||
dotenv.config()
|
||||
|
||||
const supabaseUrl = process.env.SUPABASE_URL;
|
||||
const supabaseKey = process.env.SUPABASE_ANON_KEY;
|
||||
|
||||
const supabase = createClient(supabaseUrl, supabaseKey);
|
||||
export default supabase;
|
||||
@@ -0,0 +1,53 @@
|
||||
// server/controller/authController.js
|
||||
import bcrypt from "bcrypt";
|
||||
import supabase from "../config/supabaseClient.js";
|
||||
|
||||
export const login = async (req, res) => {
|
||||
const { username, password } = req.body;
|
||||
|
||||
try {
|
||||
// Fetch user by username
|
||||
const { data: user, error } = await supabase
|
||||
.from("users")
|
||||
.select("*")
|
||||
.eq("username", username)
|
||||
.single();
|
||||
|
||||
if (error || !user) {
|
||||
return res.status(400).json({ message: "User not found" });
|
||||
}
|
||||
|
||||
// Check if user is active
|
||||
if (user.status !== "active") {
|
||||
return res.status(403).json({ message: "User is not active" });
|
||||
}
|
||||
|
||||
// Check password - try bcrypt first, then plain text fallback
|
||||
let isValidPassword = false;
|
||||
|
||||
// Try bcrypt comparison first (for hashed passwords)
|
||||
if (user.password.startsWith('$2b$') || user.password.startsWith('$2a$')) {
|
||||
// This looks like a bcrypt hash
|
||||
isValidPassword = await bcrypt.compare(password, user.password);
|
||||
} else {
|
||||
// Plain text fallback (for your mock data)
|
||||
isValidPassword = (password === user.password);
|
||||
}
|
||||
|
||||
if (!isValidPassword) {
|
||||
return res.status(401).json({ message: "Invalid password" });
|
||||
}
|
||||
|
||||
// Success
|
||||
return res.status(200).json({
|
||||
user_id: user.user_id,
|
||||
username: user.username,
|
||||
full_name: user.full_name,
|
||||
role: user.role,
|
||||
status: user.status,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("Login error:", err);
|
||||
return res.status(500).json({ message: "Server error" });
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,17 @@
|
||||
import supabase from "../config/supabaseClient.js";
|
||||
|
||||
export const getCategories = async (req, res) => {
|
||||
try {
|
||||
const { data: categories, error } = await supabase
|
||||
.from('categories')
|
||||
.select('category_id, name')
|
||||
.order('name');
|
||||
|
||||
if (error) throw error;
|
||||
|
||||
res.json(categories);
|
||||
} catch (error) {
|
||||
console.error('Error fetching categories:', error);
|
||||
res.status(500).json({ error: 'Failed to fetch categories' });
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,68 @@
|
||||
import supabase from "../config/supabaseClient.js";
|
||||
|
||||
// Get all inventory logs
|
||||
export const getInventoryLogs = async (req, res) => {
|
||||
try {
|
||||
const { product_id } = req.query;
|
||||
let query = supabase
|
||||
.from('inventory_logs')
|
||||
.select(`*, products(name), users(full_name)`)
|
||||
.order('log_date', { ascending: false });
|
||||
|
||||
if (product_id) query = query.eq('product_id', product_id);
|
||||
|
||||
const { data, error } = await query;
|
||||
|
||||
if (error) throw error;
|
||||
|
||||
res.json(data);
|
||||
} catch (error) {
|
||||
console.error("Error fetching inventory logs:", error);
|
||||
res.status(500).json({ error: "Failed to fetch inventory logs" });
|
||||
}
|
||||
};
|
||||
|
||||
// Add a log (add, remove, adjust, sale)
|
||||
export const createInventoryLog = async (req, res) => {
|
||||
const { product_id, user_id, action, quantity, remarks } = req.body;
|
||||
|
||||
if (!product_id || !user_id || !action || !quantity) {
|
||||
return res.status(400).json({ error: "Missing required fields" });
|
||||
}
|
||||
|
||||
try {
|
||||
// Insert log
|
||||
const { data: log, error } = await supabase
|
||||
.from('inventory_logs')
|
||||
.insert([{ product_id, user_id, action, quantity, remarks }])
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) throw error;
|
||||
|
||||
// Update product stock
|
||||
// Add/subtract quantity depending on action
|
||||
const { data: product, error: fetchError } = await supabase
|
||||
.from('products')
|
||||
.select('stock')
|
||||
.eq('product_id', product_id)
|
||||
.single();
|
||||
if (fetchError) throw fetchError;
|
||||
|
||||
let newStock = product.stock;
|
||||
if (action === "add" || action === "adjust") newStock += quantity;
|
||||
else if (action === "remove" || action === "sale") newStock -= quantity;
|
||||
|
||||
const { error: updateError } = await supabase
|
||||
.from('products')
|
||||
.update({ stock: newStock })
|
||||
.eq('product_id', product_id);
|
||||
|
||||
if (updateError) throw updateError;
|
||||
|
||||
res.status(201).json(log);
|
||||
} catch (error) {
|
||||
console.error("Error creating inventory log:", error);
|
||||
res.status(500).json({ error: "Failed to create inventory log" });
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,80 @@
|
||||
import supabase from "../config/supabaseClient.js";
|
||||
|
||||
export const getProducts = async (req, res) => {
|
||||
try {
|
||||
const { search, category } = req.query;
|
||||
|
||||
let query = supabase
|
||||
.from('products')
|
||||
.select(`
|
||||
*,
|
||||
categories!inner (
|
||||
category_id,
|
||||
name
|
||||
)
|
||||
`);
|
||||
|
||||
// Add search filter if provided
|
||||
if (search) {
|
||||
query = query.or(`name.ilike.%${search}%,barcode.ilike.%${search}%`);
|
||||
}
|
||||
|
||||
// Add category filter if provided - filter by category name
|
||||
if (category && category !== 'all') {
|
||||
query = query.eq('categories.name', category);
|
||||
}
|
||||
|
||||
query = query.order('name');
|
||||
|
||||
const { data: products, error } = await query;
|
||||
|
||||
if (error) throw error;
|
||||
|
||||
// Transform the data to match frontend expectations
|
||||
const transformedProducts = products.map(product => ({
|
||||
...product,
|
||||
category: product.categories.name,
|
||||
category_id: product.categories.category_id
|
||||
}));
|
||||
|
||||
res.json(transformedProducts);
|
||||
} catch (error) {
|
||||
console.error('Error fetching products:', error);
|
||||
res.status(500).json({ error: 'Failed to fetch products' });
|
||||
}
|
||||
};
|
||||
|
||||
export const getProductByBarcode = async (req, res) => {
|
||||
const { barcode } = req.params;
|
||||
|
||||
try {
|
||||
const { data: product, error } = await supabase
|
||||
.from('products')
|
||||
.select(`
|
||||
*,
|
||||
categories (
|
||||
category_id,
|
||||
name
|
||||
)
|
||||
`)
|
||||
.eq('barcode', barcode)
|
||||
.single();
|
||||
|
||||
if (error) throw error;
|
||||
if (!product) {
|
||||
return res.status(404).json({ error: 'Product not found' });
|
||||
}
|
||||
|
||||
// Transform the data
|
||||
const transformedProduct = {
|
||||
...product,
|
||||
category: product.categories.name,
|
||||
category_id: product.categories.category_id
|
||||
};
|
||||
|
||||
res.json(transformedProduct);
|
||||
} catch (error) {
|
||||
console.error('Error fetching product by barcode:', error);
|
||||
res.status(500).json({ error: 'Failed to fetch product' });
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,243 @@
|
||||
// controllers/reportController.js
|
||||
import supabase from '../config/supabaseClient.js';
|
||||
|
||||
/** Build start/end Date objects for a given range */
|
||||
function getDateRange(range = 'month', options = {}) {
|
||||
const now = options.now ? new Date(options.now) : new Date();
|
||||
const year = options.year ? parseInt(options.year, 10) : now.getFullYear();
|
||||
|
||||
let start, end;
|
||||
|
||||
switch (range) {
|
||||
case 'today': {
|
||||
const d = options.date ? new Date(options.date) : now;
|
||||
start = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0);
|
||||
end = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'week': {
|
||||
// Last 7 days including today
|
||||
end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
|
||||
start = new Date(end);
|
||||
start.setDate(end.getDate() - 6);
|
||||
start.setHours(0, 0, 0);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'month': {
|
||||
const month = options.month ? parseInt(options.month, 10) - 1 : now.getMonth();
|
||||
start = new Date(year, month, 1, 0, 0, 0);
|
||||
end = new Date(year, month + 1, 0, 23, 59, 59);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'quarter': {
|
||||
const q = options.quarter ? parseInt(options.quarter, 10) : Math.floor(now.getMonth() / 3) + 1;
|
||||
const startMonth = (q - 1) * 3;
|
||||
start = new Date(year, startMonth, 1, 0, 0, 0);
|
||||
end = new Date(year, startMonth + 3, 0, 23, 59, 59);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'year':
|
||||
default: {
|
||||
start = new Date(year, 0, 1, 0, 0, 0);
|
||||
end = new Date(year, 11, 31, 23, 59, 59);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return { start, end }; // Return Date objects, not ISO strings
|
||||
}
|
||||
|
||||
/** Fetch sales between two dates */
|
||||
async function fetchSalesInRange(start, end) {
|
||||
// Convert to ISO for Supabase filtering (UTC)
|
||||
const { data, error } = await supabase
|
||||
.from('sales')
|
||||
.select(`
|
||||
sale_id,
|
||||
sale_date,
|
||||
total_amount,
|
||||
status,
|
||||
sale_items(
|
||||
sale_item_id,
|
||||
product_id,
|
||||
quantity,
|
||||
price
|
||||
)
|
||||
`)
|
||||
.gte('sale_date', start.toISOString())
|
||||
.lte('sale_date', end.toISOString());
|
||||
|
||||
if (error) throw error;
|
||||
return data || [];
|
||||
}
|
||||
|
||||
/** GET /api/reports/summary */
|
||||
async function getSummary(req, res) {
|
||||
try {
|
||||
const { range = 'month', year, month, quarter, date } = req.query;
|
||||
const dr = getDateRange(range, { year, month, quarter, date });
|
||||
|
||||
const sales = await fetchSalesInRange(dr.start, dr.end);
|
||||
|
||||
const completed = sales.filter(s => s.status === 'completed');
|
||||
const refunded = sales.filter(s => s.status === 'refunded');
|
||||
const voided = sales.filter(s => s.status === 'voided');
|
||||
|
||||
const total_orders = completed.length;
|
||||
const total_sales = completed.reduce((acc, s) => acc + (Number(s.total_amount) || 0), 0);
|
||||
const total_refunds = refunded.reduce((acc, s) => acc + (Number(s.total_amount) || 0), 0);
|
||||
|
||||
res.json({
|
||||
range,
|
||||
start: dr.start.toISOString(),
|
||||
end: dr.end.toISOString(),
|
||||
total_orders,
|
||||
total_sales: Number(total_sales.toFixed(2)),
|
||||
total_refunds: Number(total_refunds.toFixed(2)),
|
||||
breakdown: {
|
||||
completed: completed.length,
|
||||
refunded: refunded.length,
|
||||
voided: voided.length
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('getSummary error', err);
|
||||
res.status(500).json({ error: err.message || 'Internal server error' });
|
||||
}
|
||||
}
|
||||
|
||||
/** GET /api/reports/sales-trend */
|
||||
async function getSalesTrend(req, res) {
|
||||
try {
|
||||
const { range = 'year', year, month } = req.query;
|
||||
|
||||
if (range === 'year') {
|
||||
const useYear = year ? parseInt(year, 10) : new Date().getFullYear();
|
||||
const dr = getDateRange('year', { year: useYear });
|
||||
const sales = await fetchSalesInRange(dr.start, dr.end);
|
||||
|
||||
const months = Array.from({ length: 12 }, (_, i) => ({
|
||||
monthIndex: i,
|
||||
label: new Date(useYear, i, 1).toLocaleString('en-US', { month: 'short' }),
|
||||
total: 0
|
||||
}));
|
||||
|
||||
sales.forEach(s => {
|
||||
if (s.status !== 'completed') return;
|
||||
const m = new Date(s.sale_date).getMonth();
|
||||
months[m].total += Number(s.total_amount) || 0;
|
||||
});
|
||||
|
||||
res.json({ range: 'year', year: useYear, data: months.map(m => ({ label: m.label, total: Number(m.total.toFixed(2)) })) });
|
||||
return;
|
||||
}
|
||||
|
||||
if (range === 'month') {
|
||||
const useYear = year ? parseInt(year, 10) : new Date().getFullYear();
|
||||
const useMonth = month ? parseInt(month, 10) : (new Date().getMonth() + 1);
|
||||
const dr = getDateRange('month', { year: useYear, month: useMonth });
|
||||
const sales = await fetchSalesInRange(dr.start, dr.end);
|
||||
|
||||
const daysInMonth = new Date(useYear, useMonth, 0).getDate();
|
||||
const days = Array.from({ length: daysInMonth }, (_, i) => ({ day: i + 1, total: 0 }));
|
||||
|
||||
sales.forEach(s => {
|
||||
if (s.status !== 'completed') return;
|
||||
const day = new Date(s.sale_date).getDate();
|
||||
days[day - 1].total += Number(s.total_amount) || 0;
|
||||
});
|
||||
|
||||
res.json({ range: 'month', year: useYear, month: useMonth, data: days.map(d => ({ day: d.day, total: Number(d.total.toFixed(2)) })) });
|
||||
return;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('getSalesTrend error', err);
|
||||
res.status(500).json({ error: err.message || 'Internal server error' });
|
||||
}
|
||||
}
|
||||
|
||||
/** GET /api/reports/payment-methods */
|
||||
async function getPaymentMethods(req, res) {
|
||||
try {
|
||||
const { range = 'month', year, month, quarter, date } = req.query;
|
||||
const dr = getDateRange(range, { year, month, quarter, date });
|
||||
const sales = await fetchSalesInRange(dr.start, dr.end);
|
||||
|
||||
const map = {};
|
||||
sales.forEach(s => {
|
||||
const key = s.payment_type || 'unknown';
|
||||
if (!map[key]) map[key] = { count: 0, amount: 0 };
|
||||
map[key].count += 1;
|
||||
map[key].amount += Number(s.total_amount) || 0;
|
||||
});
|
||||
|
||||
const result = Object.entries(map).map(([payment_type, v]) => ({
|
||||
payment_type,
|
||||
count: v.count,
|
||||
amount: Number(v.amount.toFixed(2))
|
||||
})).sort((a, b) => b.amount - a.amount);
|
||||
|
||||
res.json({ range, start: dr.start.toISOString(), end: dr.end.toISOString(), data: result });
|
||||
} catch (err) {
|
||||
console.error('getPaymentMethods error', err);
|
||||
res.status(500).json({ error: err.message || 'Internal server error' });
|
||||
}
|
||||
}
|
||||
|
||||
/** GET /api/reports/top-products */
|
||||
async function getTopProducts(req, res) {
|
||||
try {
|
||||
const { range = 'month', year, month, quarter, date, limit = 10 } = req.query;
|
||||
const dr = getDateRange(range, { year, month, quarter, date });
|
||||
const sales = await fetchSalesInRange(dr.start, dr.end);
|
||||
|
||||
const productMap = new Map();
|
||||
for (const s of sales) {
|
||||
if (!Array.isArray(s.sale_items)) continue;
|
||||
for (const item of s.sale_items) {
|
||||
const pid = item.product_id;
|
||||
const qty = Number(item.quantity) || 0;
|
||||
const price = Number(item.price) || 0;
|
||||
const amount = qty * price;
|
||||
if (!productMap.has(pid)) productMap.set(pid, { product_id: pid, name: item.name || null, qty: 0, amount: 0 });
|
||||
const entry = productMap.get(pid);
|
||||
entry.qty += qty;
|
||||
entry.amount += amount;
|
||||
}
|
||||
}
|
||||
|
||||
const arr = Array.from(productMap.values())
|
||||
.map(p => ({ ...p, amount: Number(p.amount.toFixed(2)) }))
|
||||
.sort((a, b) => b.qty - a.qty)
|
||||
.slice(0, parseInt(limit, 10));
|
||||
|
||||
// Fill missing names
|
||||
const missingNames = arr.filter(p => !p.name).map(p => p.product_id);
|
||||
if (missingNames.length > 0) {
|
||||
const { data: products, error } = await supabase
|
||||
.from('products')
|
||||
.select('product_id, name')
|
||||
.in('product_id', missingNames);
|
||||
if (!error && products) {
|
||||
const prodMap = new Map(products.map(p => [p.product_id, p.name]));
|
||||
arr.forEach(p => { if (!p.name && prodMap.has(p.product_id)) p.name = prodMap.get(p.product_id); });
|
||||
}
|
||||
}
|
||||
|
||||
res.json({ range, start: dr.start.toISOString(), end: dr.end.toISOString(), data: arr });
|
||||
} catch (err) {
|
||||
console.error('getTopProducts error', err);
|
||||
res.status(500).json({ error: err.message || 'Internal server error' });
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
getSummary,
|
||||
getSalesTrend,
|
||||
getPaymentMethods,
|
||||
getTopProducts
|
||||
};
|
||||
@@ -0,0 +1,281 @@
|
||||
// server/controllers/salesController.js
|
||||
import supabase from "../config/supabaseClient.js";
|
||||
|
||||
// server/controllers/salesController.js
|
||||
export const getSales = async (req, res) => {
|
||||
try {
|
||||
const { page = 1, limit = 10 } = req.query;
|
||||
const pageNum = parseInt(page);
|
||||
const limitNum = parseInt(limit);
|
||||
const offset = (pageNum - 1) * limitNum;
|
||||
|
||||
// Get total count
|
||||
const { count, error: countError } = await supabase
|
||||
.from('sales')
|
||||
.select('*', { count: 'exact', head: true });
|
||||
|
||||
if (countError) throw countError;
|
||||
|
||||
// Get paginated sales
|
||||
const { data: sales, error } = await supabase
|
||||
.from('sales')
|
||||
.select(`
|
||||
*,
|
||||
users(full_name),
|
||||
sale_items(
|
||||
*,
|
||||
products(name, price)
|
||||
)
|
||||
`)
|
||||
.order('sale_date', { ascending: false })
|
||||
.range(offset, offset + limitNum - 1);
|
||||
|
||||
if (error) throw error;
|
||||
|
||||
res.json({
|
||||
sales,
|
||||
pagination: {
|
||||
currentPage: pageNum,
|
||||
totalPages: Math.ceil(count / limitNum),
|
||||
totalSales: count,
|
||||
hasNext: pageNum < Math.ceil(count / limitNum),
|
||||
hasPrev: pageNum > 1
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching sales:', error);
|
||||
res.status(500).json({ error: 'Failed to fetch sales' });
|
||||
}
|
||||
};
|
||||
|
||||
export const createSale = async (req, res) => {
|
||||
const {
|
||||
user_id,
|
||||
items,
|
||||
payment_type,
|
||||
amount_tendered,
|
||||
discount_type,
|
||||
discount_amount,
|
||||
customer_name
|
||||
} = req.body;
|
||||
|
||||
try {
|
||||
// Calculate total amount from items
|
||||
const subtotal = items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
|
||||
|
||||
// Calculate discount
|
||||
const discount = discount_amount || 0;
|
||||
|
||||
// Calculate tax (no tax if discount is applied)
|
||||
const taxable_amount = subtotal - discount;
|
||||
const tax = (discount > 0) ? 0 : taxable_amount * 0.12;
|
||||
|
||||
const total_amount = subtotal - discount + tax;
|
||||
|
||||
// For GCash and Card, amount_tendered should equal total_amount (no change)
|
||||
let change_due = 0;
|
||||
let final_amount_tendered = amount_tendered;
|
||||
|
||||
if (payment_type === 'cash') {
|
||||
change_due = amount_tendered - total_amount;
|
||||
if (change_due < 0) {
|
||||
return res.status(400).json({ error: 'Insufficient payment amount' });
|
||||
}
|
||||
} else {
|
||||
// For GCash and Card, payment should be exact
|
||||
final_amount_tendered = total_amount;
|
||||
change_due = 0;
|
||||
}
|
||||
|
||||
// Create sale record
|
||||
const { data: sale, error: saleError } = await supabase
|
||||
.from('sales')
|
||||
.insert([
|
||||
{
|
||||
user_id,
|
||||
total_amount,
|
||||
payment_type,
|
||||
amount_tendered: final_amount_tendered,
|
||||
change_due,
|
||||
discount_type,
|
||||
discount_amount: discount,
|
||||
tax_amount: tax,
|
||||
customer_name: customer_name || null, // Add customer name
|
||||
status: 'completed'
|
||||
}
|
||||
])
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (saleError) throw saleError;
|
||||
|
||||
// Insert sale items
|
||||
const saleItems = items.map(item => ({
|
||||
sale_id: sale.sale_id,
|
||||
product_id: item.product_id,
|
||||
quantity: item.quantity,
|
||||
price: item.price
|
||||
}));
|
||||
|
||||
const { error: itemsError } = await supabase
|
||||
.from('sale_items')
|
||||
.insert(saleItems);
|
||||
|
||||
if (itemsError) throw itemsError;
|
||||
|
||||
// Update inventory and stock together
|
||||
for (const item of items) {
|
||||
// Fetch current stock
|
||||
const { data: product, error: fetchError } = await supabase
|
||||
.from('products')
|
||||
.select('stock')
|
||||
.eq('product_id', item.product_id)
|
||||
.single();
|
||||
if (fetchError) throw fetchError;
|
||||
|
||||
if (product.stock < item.quantity) {
|
||||
return res.status(400).json({ error: `Insufficient stock for product ${item.product_id}` });
|
||||
}
|
||||
|
||||
// Update stock
|
||||
const { error: updateError } = await supabase
|
||||
.from('products')
|
||||
.update({ stock: product.stock - item.quantity })
|
||||
.eq('product_id', item.product_id);
|
||||
if (updateError) throw updateError;
|
||||
|
||||
// Insert inventory log
|
||||
const { error: inventoryError } = await supabase
|
||||
.from('inventory_logs')
|
||||
.insert([
|
||||
{
|
||||
product_id: item.product_id,
|
||||
user_id: user_id,
|
||||
action: 'sale',
|
||||
quantity: -item.quantity,
|
||||
remarks: `Sale #${sale.sale_id}`
|
||||
}
|
||||
]);
|
||||
if (inventoryError) throw inventoryError;
|
||||
}
|
||||
|
||||
res.status(201).json(sale);
|
||||
} catch (error) {
|
||||
console.error('Error creating sale:', error);
|
||||
res.status(500).json({ error: 'Failed to create sale' });
|
||||
}
|
||||
};
|
||||
|
||||
export const voidSale = async (req, res) => {
|
||||
const { sale_id } = req.params;
|
||||
|
||||
try {
|
||||
// Get sale details with items
|
||||
const { data: sale, error: saleError } = await supabase
|
||||
.from('sales')
|
||||
.select(`
|
||||
*,
|
||||
sale_items(
|
||||
*,
|
||||
products(name)
|
||||
)
|
||||
`)
|
||||
.eq('sale_id', sale_id)
|
||||
.single();
|
||||
|
||||
if (saleError) throw saleError;
|
||||
|
||||
// Check if sale can be voided
|
||||
if (sale.status !== 'completed') {
|
||||
return res.status(400).json({ error: 'Only completed sales can be voided' });
|
||||
}
|
||||
|
||||
// Start transaction - update sale status and restore inventory
|
||||
const { error: updateError } = await supabase
|
||||
.from('sales')
|
||||
.update({ status: 'voided' })
|
||||
.eq('sale_id', sale_id);
|
||||
|
||||
if (updateError) throw updateError;
|
||||
|
||||
// Restore inventory for each item
|
||||
for (const item of sale.sale_items) {
|
||||
const { error: inventoryError } = await supabase
|
||||
.from('inventory_logs')
|
||||
.insert([
|
||||
{
|
||||
product_id: item.product_id,
|
||||
user_id: req.user?.user_id, // from auth middleware
|
||||
action: 'adjust',
|
||||
quantity: item.quantity,
|
||||
remarks: `Voided sale #${sale_id} - ${item.products.name}`
|
||||
}
|
||||
]);
|
||||
|
||||
if (inventoryError) throw inventoryError;
|
||||
}
|
||||
|
||||
res.json({ message: 'Sale voided successfully', sale_id });
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error voiding sale:', error);
|
||||
res.status(500).json({ error: 'Failed to void sale' });
|
||||
}
|
||||
};
|
||||
|
||||
export const refundSale = async (req, res) => {
|
||||
const { sale_id } = req.params;
|
||||
|
||||
try {
|
||||
// Get sale details with items
|
||||
const { data: sale, error: saleError } = await supabase
|
||||
.from('sales')
|
||||
.select(`
|
||||
*,
|
||||
sale_items(
|
||||
*,
|
||||
products(name)
|
||||
)
|
||||
`)
|
||||
.eq('sale_id', sale_id)
|
||||
.single();
|
||||
|
||||
if (saleError) throw saleError;
|
||||
|
||||
// Check if sale can be refunded
|
||||
if (sale.status !== 'completed') {
|
||||
return res.status(400).json({ error: 'Only completed sales can be refunded' });
|
||||
}
|
||||
|
||||
// Update sale status
|
||||
const { error: updateError } = await supabase
|
||||
.from('sales')
|
||||
.update({ status: 'refunded' })
|
||||
.eq('sale_id', sale_id);
|
||||
|
||||
if (updateError) throw updateError;
|
||||
|
||||
// Restore inventory for each item
|
||||
for (const item of sale.sale_items) {
|
||||
const { error: inventoryError } = await supabase
|
||||
.from('inventory_logs')
|
||||
.insert([
|
||||
{
|
||||
product_id: item.product_id,
|
||||
user_id: req.user?.user_id, // from auth middleware
|
||||
action: 'adjust',
|
||||
quantity: item.quantity,
|
||||
remarks: `Refunded sale #${sale_id} - ${item.products.name}`
|
||||
}
|
||||
]);
|
||||
|
||||
if (inventoryError) throw inventoryError;
|
||||
}
|
||||
|
||||
res.json({ message: 'Sale refunded successfully', sale_id });
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error refunding sale:', error);
|
||||
res.status(500).json({ error: 'Failed to refund sale' });
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,63 @@
|
||||
import supabase from "../config/supabaseClient.js";
|
||||
|
||||
export const getSettings = async (req, res) => {
|
||||
try {
|
||||
const { data: settings, error } = await supabase
|
||||
.from('settings')
|
||||
.select('*')
|
||||
.order('setting_id', { ascending: true })
|
||||
.limit(1);
|
||||
|
||||
if (error) throw error;
|
||||
|
||||
res.json(settings);
|
||||
} catch (error) {
|
||||
console.error('Error fetching settings:', error);
|
||||
res.status(500).json({ error: 'Failed to fetch settings' });
|
||||
}
|
||||
};
|
||||
|
||||
export const updateSettings = async (req, res) => {
|
||||
const {
|
||||
store_name,
|
||||
address,
|
||||
contact,
|
||||
tax_rate,
|
||||
pwd_discount_rate,
|
||||
senior_discount_rate,
|
||||
dark_mode,
|
||||
fullscreen_mode,
|
||||
store_logo_url,
|
||||
business_hours,
|
||||
receipt_footer
|
||||
} = req.body;
|
||||
|
||||
try {
|
||||
const { data: settings, error } = await supabase
|
||||
.from('settings')
|
||||
.update({
|
||||
store_name,
|
||||
address,
|
||||
contact,
|
||||
tax_rate,
|
||||
pwd_discount_rate,
|
||||
senior_discount_rate,
|
||||
dark_mode,
|
||||
fullscreen_mode,
|
||||
store_logo_url,
|
||||
business_hours,
|
||||
receipt_footer
|
||||
// Remove updated_at since the column doesn't exist
|
||||
})
|
||||
.eq('setting_id', 1)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) throw error;
|
||||
|
||||
res.json(settings);
|
||||
} catch (error) {
|
||||
console.error('Error updating settings:', error);
|
||||
res.status(500).json({ error: 'Failed to update settings' });
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import cors from 'cors';
|
||||
|
||||
const corsOptions = {
|
||||
origin: ['http://localhost:3000'], // can use '*' for all origins
|
||||
allowedHeaders: ['Content-Type', 'Authorization'],
|
||||
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
|
||||
credentials: true
|
||||
};
|
||||
|
||||
export default cors(corsOptions);
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*)
|
||||
if command -v cygpath > /dev/null 2>&1; then
|
||||
basedir=`cygpath -w "$basedir"`
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../node-gyp-build/bin.js" "$@"
|
||||
else
|
||||
exec node "$basedir/../node-gyp-build/bin.js" "$@"
|
||||
fi
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*)
|
||||
if command -v cygpath > /dev/null 2>&1; then
|
||||
basedir=`cygpath -w "$basedir"`
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../node-gyp-build/optional.js" "$@"
|
||||
else
|
||||
exec node "$basedir/../node-gyp-build/optional.js" "$@"
|
||||
fi
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\node-gyp-build\optional.js" %*
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../node-gyp-build/optional.js" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../node-gyp-build/optional.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../node-gyp-build/optional.js" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../node-gyp-build/optional.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*)
|
||||
if command -v cygpath > /dev/null 2>&1; then
|
||||
basedir=`cygpath -w "$basedir"`
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../node-gyp-build/build-test.js" "$@"
|
||||
else
|
||||
exec node "$basedir/../node-gyp-build/build-test.js" "$@"
|
||||
fi
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\node-gyp-build\build-test.js" %*
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../node-gyp-build/build-test.js" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../node-gyp-build/build-test.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../node-gyp-build/build-test.js" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../node-gyp-build/build-test.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\node-gyp-build\bin.js" %*
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../node-gyp-build/bin.js" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../node-gyp-build/bin.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../node-gyp-build/bin.js" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../node-gyp-build/bin.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*)
|
||||
if command -v cygpath > /dev/null 2>&1; then
|
||||
basedir=`cygpath -w "$basedir"`
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../nodemon/bin/nodemon.js" "$@"
|
||||
else
|
||||
exec node "$basedir/../nodemon/bin/nodemon.js" "$@"
|
||||
fi
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\nodemon\bin\nodemon.js" %*
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../nodemon/bin/nodemon.js" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../nodemon/bin/nodemon.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../nodemon/bin/nodemon.js" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../nodemon/bin/nodemon.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*)
|
||||
if command -v cygpath > /dev/null 2>&1; then
|
||||
basedir=`cygpath -w "$basedir"`
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../touch/bin/nodetouch.js" "$@"
|
||||
else
|
||||
exec node "$basedir/../touch/bin/nodetouch.js" "$@"
|
||||
fi
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\touch\bin\nodetouch.js" %*
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../touch/bin/nodetouch.js" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../touch/bin/nodetouch.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../touch/bin/nodetouch.js" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../touch/bin/nodetouch.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*)
|
||||
if command -v cygpath > /dev/null 2>&1; then
|
||||
basedir=`cygpath -w "$basedir"`
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../semver/bin/semver.js" "$@"
|
||||
else
|
||||
exec node "$basedir/../semver/bin/semver.js" "$@"
|
||||
fi
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\semver\bin\semver.js" %*
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../semver/bin/semver.js" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../semver/bin/semver.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
+1500
File diff suppressed because it is too large.
Load diff
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020 Supabase
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
<br />
|
||||
<p align="center">
|
||||
<a href="https://supabase.io">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/supabase/supabase/master/packages/common/assets/images/supabase-logo-wordmark--dark.svg">
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/supabase/supabase/master/packages/common/assets/images/supabase-logo-wordmark--light.svg">
|
||||
<img alt="Supabase Logo" width="300" src="https://raw.githubusercontent.com/supabase/supabase/master/packages/common/assets/images/logo-preview.jpg">
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
<h1 align="center">Supabase Auth JS SDK</h1>
|
||||
|
||||
<h3 align="center">An isomorphic JavaScript SDK for the <a href="https://github.com/supabase/auth">Supabase Auth</a> API.</h3>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://supabase.com/docs/guides/auth">Guides</a>
|
||||
·
|
||||
<a href="https://supabase.com/docs/reference/javascript/auth-signup">Reference Docs</a>
|
||||
·
|
||||
<a href="https://supabase.github.io/supabase-js/auth-js/v2/spec.json">TypeDoc</a>
|
||||
</p>
|
||||
</p>
|
||||
|
||||
<div align="center">
|
||||
|
||||
[](https://github.com/supabase/supabase-js/actions?query=branch%3Amaster)
|
||||
[](https://www.npmjs.com/package/@supabase/auth-js)
|
||||
[](#license)
|
||||
[](https://pkg.pr.new/~/supabase/auth-js)
|
||||
</div>
|
||||
|
||||
## Quick start
|
||||
|
||||
Install
|
||||
|
||||
```bash
|
||||
npm install --save @supabase/auth-js
|
||||
```
|
||||
|
||||
Usage
|
||||
|
||||
```js
|
||||
import { AuthClient } from '@supabase/auth-js'
|
||||
|
||||
const GOTRUE_URL = 'http://localhost:9999'
|
||||
|
||||
const auth = new AuthClient({ url: GOTRUE_URL })
|
||||
```
|
||||
|
||||
- `signUp()`: https://supabase.com/docs/reference/javascript/auth-signup
|
||||
- `signIn()`: https://supabase.com/docs/reference/javascript/auth-signin
|
||||
- `signOut()`: https://supabase.com/docs/reference/javascript/auth-signout
|
||||
|
||||
### Custom `fetch` implementation
|
||||
|
||||
`auth-js` uses the [`cross-fetch`](https://www.npmjs.com/package/cross-fetch) library to make HTTP requests, but an alternative `fetch` implementation can be provided as an option. This is most useful in environments where `cross-fetch` is not compatible, for instance Cloudflare Workers:
|
||||
|
||||
```js
|
||||
import { AuthClient } from '@supabase/auth-js'
|
||||
|
||||
const AUTH_URL = 'http://localhost:9999'
|
||||
|
||||
const auth = new AuthClient({ url: AUTH_URL, fetch: fetch })
|
||||
```
|
||||
|
||||
## Development
|
||||
|
||||
This package is part of the [Supabase JavaScript monorepo](https://github.com/supabase/supabase-js). To work on this package:
|
||||
|
||||
### Building
|
||||
|
||||
```bash
|
||||
# Complete build (from monorepo root)
|
||||
npx nx build auth-js
|
||||
|
||||
# Build with watch mode for development
|
||||
npx nx build auth-js --watch
|
||||
|
||||
# Individual build targets
|
||||
npx nx build:main auth-js # CommonJS build (dist/main/)
|
||||
npx nx build:module auth-js # ES Modules build (dist/module/)
|
||||
|
||||
# Other useful commands
|
||||
npx nx clean auth-js # Clean build artifacts
|
||||
npx nx format auth-js # Format code with Prettier
|
||||
npx nx lint auth-js # Run ESLint
|
||||
npx nx typecheck auth-js # TypeScript type checking
|
||||
npx nx docs auth-js # Generate documentation
|
||||
```
|
||||
|
||||
#### Build Outputs
|
||||
|
||||
- **CommonJS (`dist/main/`)** - For Node.js environments
|
||||
- **ES Modules (`dist/module/`)** - For modern bundlers (Webpack, Vite, Rollup)
|
||||
- **TypeScript definitions (`dist/module/index.d.ts`)** - Type definitions for TypeScript projects
|
||||
|
||||
### Testing
|
||||
|
||||
**Docker Required!** The auth-js tests require a local Supabase Auth server (GoTrue) running in Docker.
|
||||
|
||||
```bash
|
||||
# Run complete test suite (from monorepo root)
|
||||
npx nx test:auth auth-js
|
||||
```
|
||||
|
||||
This command automatically:
|
||||
|
||||
1. Stops any existing test containers
|
||||
2. Starts a Supabase Auth server (GoTrue) and PostgreSQL database in Docker
|
||||
3. Waits for services to be ready (30 seconds)
|
||||
4. Runs the test suite
|
||||
5. Cleans up Docker containers after tests complete
|
||||
|
||||
#### Individual Test Commands
|
||||
|
||||
```bash
|
||||
# Run just the test suite (requires infrastructure to be running)
|
||||
npx nx test:suite auth-js
|
||||
|
||||
# Manually manage test infrastructure
|
||||
npx nx test:infra auth-js # Start Docker containers
|
||||
npx nx test:clean auth-js # Stop and remove containers
|
||||
```
|
||||
|
||||
#### Development Testing
|
||||
|
||||
For actively developing and debugging tests:
|
||||
|
||||
```bash
|
||||
# Start infrastructure once
|
||||
npx nx test:infra auth-js
|
||||
|
||||
# Run tests multiple times (faster since containers stay up)
|
||||
npx nx test:suite auth-js
|
||||
|
||||
# Clean up when done
|
||||
npx nx test:clean auth-js
|
||||
```
|
||||
|
||||
#### Test Infrastructure
|
||||
|
||||
The Docker setup includes:
|
||||
|
||||
- **Supabase Auth (GoTrue)** - The authentication server
|
||||
- **PostgreSQL** - Database for auth data
|
||||
- Pre-configured with test users and settings
|
||||
|
||||
#### Prerequisites
|
||||
|
||||
- **Docker** must be installed and running
|
||||
- Ports used by test infrastructure (check `infra/docker-compose.yml`)
|
||||
- No full Supabase instance needed - just the Auth server
|
||||
|
||||
### Contributing
|
||||
|
||||
We welcome contributions! Please see our [Contributing Guide](../../../CONTRIBUTING.md) for details on how to get started.
|
||||
|
||||
For major changes or if you're unsure about something, please open an issue first to discuss your proposed changes.
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import GoTrueAdminApi from './GoTrueAdminApi';
|
||||
declare const AuthAdminApi: typeof GoTrueAdminApi;
|
||||
export default AuthAdminApi;
|
||||
//# sourceMappingURL=AuthAdminApi.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"AuthAdminApi.d.ts","sourceRoot":"","sources":["../../src/AuthAdminApi.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAE7C,QAAA,MAAM,YAAY,uBAAiB,CAAA;AAEnC,eAAe,YAAY,CAAA"}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const tslib_1 = require("tslib");
|
||||
const GoTrueAdminApi_1 = tslib_1.__importDefault(require("./GoTrueAdminApi"));
|
||||
const AuthAdminApi = GoTrueAdminApi_1.default;
|
||||
exports.default = AuthAdminApi;
|
||||
//# sourceMappingURL=AuthAdminApi.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"AuthAdminApi.js","sourceRoot":"","sources":["../../src/AuthAdminApi.ts"],"names":[],"mappings":";;;AAAA,8EAA6C;AAE7C,MAAM,YAAY,GAAG,wBAAc,CAAA;AAEnC,kBAAe,YAAY,CAAA"}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import GoTrueClient from './GoTrueClient';
|
||||
declare const AuthClient: typeof GoTrueClient;
|
||||
export default AuthClient;
|
||||
//# sourceMappingURL=AuthClient.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"AuthClient.d.ts","sourceRoot":"","sources":["../../src/AuthClient.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,MAAM,gBAAgB,CAAA;AAEzC,QAAA,MAAM,UAAU,qBAAe,CAAA;AAE/B,eAAe,UAAU,CAAA"}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const tslib_1 = require("tslib");
|
||||
const GoTrueClient_1 = tslib_1.__importDefault(require("./GoTrueClient"));
|
||||
const AuthClient = GoTrueClient_1.default;
|
||||
exports.default = AuthClient;
|
||||
//# sourceMappingURL=AuthClient.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"AuthClient.js","sourceRoot":"","sources":["../../src/AuthClient.ts"],"names":[],"mappings":";;;AAAA,0EAAyC;AAEzC,MAAM,UAAU,GAAG,sBAAY,CAAA;AAE/B,kBAAe,UAAU,CAAA"}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
import { Fetch } from './lib/fetch';
|
||||
import { AdminUserAttributes, GenerateLinkParams, GenerateLinkResponse, Pagination, User, UserResponse, GoTrueAdminMFAApi, PageParams, SignOutScope, GoTrueAdminOAuthApi } from './lib/types';
|
||||
import { AuthError } from './lib/errors';
|
||||
export default class GoTrueAdminApi {
|
||||
/** Contains all MFA administration methods. */
|
||||
mfa: GoTrueAdminMFAApi;
|
||||
/**
|
||||
* Contains all OAuth client administration methods.
|
||||
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
|
||||
*/
|
||||
oauth: GoTrueAdminOAuthApi;
|
||||
protected url: string;
|
||||
protected headers: {
|
||||
[key: string]: string;
|
||||
};
|
||||
protected fetch: Fetch;
|
||||
constructor({ url, headers, fetch, }: {
|
||||
url: string;
|
||||
headers?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
fetch?: Fetch;
|
||||
});
|
||||
/**
|
||||
* Removes a logged-in session.
|
||||
* @param jwt A valid, logged-in JWT.
|
||||
* @param scope The logout sope.
|
||||
*/
|
||||
signOut(jwt: string, scope?: SignOutScope): Promise<{
|
||||
data: null;
|
||||
error: AuthError | null;
|
||||
}>;
|
||||
/**
|
||||
* Sends an invite link to an email address.
|
||||
* @param email The email address of the user.
|
||||
* @param options Additional options to be included when inviting.
|
||||
*/
|
||||
inviteUserByEmail(email: string, options?: {
|
||||
/** A custom data object to store additional metadata about the user. This maps to the `auth.users.user_metadata` column. */
|
||||
data?: object;
|
||||
/** The URL which will be appended to the email link sent to the user's email address. Once clicked the user will end up on this URL. */
|
||||
redirectTo?: string;
|
||||
}): Promise<UserResponse>;
|
||||
/**
|
||||
* Generates email links and OTPs to be sent via a custom email provider.
|
||||
* @param email The user's email.
|
||||
* @param options.password User password. For signup only.
|
||||
* @param options.data Optional user metadata. For signup only.
|
||||
* @param options.redirectTo The redirect url which should be appended to the generated link
|
||||
*/
|
||||
generateLink(params: GenerateLinkParams): Promise<GenerateLinkResponse>;
|
||||
/**
|
||||
* Creates a new user.
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
createUser(attributes: AdminUserAttributes): Promise<UserResponse>;
|
||||
/**
|
||||
* Get a list of users.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
* @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results.
|
||||
*/
|
||||
listUsers(params?: PageParams): Promise<{
|
||||
data: {
|
||||
users: User[];
|
||||
aud: string;
|
||||
} & Pagination;
|
||||
error: null;
|
||||
} | {
|
||||
data: {
|
||||
users: [];
|
||||
};
|
||||
error: AuthError;
|
||||
}>;
|
||||
/**
|
||||
* Get user by id.
|
||||
*
|
||||
* @param uid The user's unique identifier
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
getUserById(uid: string): Promise<UserResponse>;
|
||||
/**
|
||||
* Updates the user data.
|
||||
*
|
||||
* @param attributes The data you want to update.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
updateUserById(uid: string, attributes: AdminUserAttributes): Promise<UserResponse>;
|
||||
/**
|
||||
* Delete a user. Requires a `service_role` key.
|
||||
*
|
||||
* @param id The user id you want to remove.
|
||||
* @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible.
|
||||
* Defaults to false for backward compatibility.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
deleteUser(id: string, shouldSoftDelete?: boolean): Promise<UserResponse>;
|
||||
private _listFactors;
|
||||
private _deleteFactor;
|
||||
/**
|
||||
* Lists all OAuth clients with optional pagination.
|
||||
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
private _listOAuthClients;
|
||||
/**
|
||||
* Creates a new OAuth client.
|
||||
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
private _createOAuthClient;
|
||||
/**
|
||||
* Gets details of a specific OAuth client.
|
||||
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
private _getOAuthClient;
|
||||
/**
|
||||
* Deletes an OAuth client.
|
||||
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
private _deleteOAuthClient;
|
||||
/**
|
||||
* Regenerates the secret for an OAuth client.
|
||||
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
private _regenerateOAuthClientSecret;
|
||||
}
|
||||
//# sourceMappingURL=GoTrueAdminApi.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"GoTrueAdminApi.d.ts","sourceRoot":"","sources":["../../src/GoTrueAdminApi.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EAKN,MAAM,aAAa,CAAA;AAEpB,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,oBAAoB,EACpB,UAAU,EACV,IAAI,EACJ,YAAY,EACZ,iBAAiB,EAKjB,UAAU,EAEV,YAAY,EACZ,mBAAmB,EAIpB,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,SAAS,EAAe,MAAM,cAAc,CAAA;AAErD,MAAM,CAAC,OAAO,OAAO,cAAc;IACjC,+CAA+C;IAC/C,GAAG,EAAE,iBAAiB,CAAA;IAEtB;;;OAGG;IACH,KAAK,EAAE,mBAAmB,CAAA;IAE1B,SAAS,CAAC,GAAG,EAAE,MAAM,CAAA;IACrB,SAAS,CAAC,OAAO,EAAE;QACjB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KACtB,CAAA;IACD,SAAS,CAAC,KAAK,EAAE,KAAK,CAAA;gBAEV,EACV,GAAQ,EACR,OAAY,EACZ,KAAK,GACN,EAAE;QACD,GAAG,EAAE,MAAM,CAAA;QACX,OAAO,CAAC,EAAE;YACR,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;SACtB,CAAA;QACD,KAAK,CAAC,EAAE,KAAK,CAAA;KACd;IAiBD;;;;OAIG;IACG,OAAO,CACX,GAAG,EAAE,MAAM,EACX,KAAK,GAAE,YAAiC,GACvC,OAAO,CAAC;QAAE,IAAI,EAAE,IAAI,CAAC;QAAC,KAAK,EAAE,SAAS,GAAG,IAAI,CAAA;KAAE,CAAC;IAuBnD;;;;OAIG;IACG,iBAAiB,CACrB,KAAK,EAAE,MAAM,EACb,OAAO,GAAE;QACP,4HAA4H;QAC5H,IAAI,CAAC,EAAE,MAAM,CAAA;QAEb,wIAAwI;QACxI,UAAU,CAAC,EAAE,MAAM,CAAA;KACf,GACL,OAAO,CAAC,YAAY,CAAC;IAiBxB;;;;;;OAMG;IACG,YAAY,CAAC,MAAM,EAAE,kBAAkB,GAAG,OAAO,CAAC,oBAAoB,CAAC;IA8B7E;;;OAGG;IACG,UAAU,CAAC,UAAU,EAAE,mBAAmB,GAAG,OAAO,CAAC,YAAY,CAAC;IAgBxE;;;;;OAKG;IACG,SAAS,CACb,MAAM,CAAC,EAAE,UAAU,GAClB,OAAO,CACN;QAAE,IAAI,EAAE;YAAE,KAAK,EAAE,IAAI,EAAE,CAAC;YAAC,GAAG,EAAE,MAAM,CAAA;SAAE,GAAG,UAAU,CAAC;QAAC,KAAK,EAAE,IAAI,CAAA;KAAE,GAClE;QAAE,IAAI,EAAE;YAAE,KAAK,EAAE,EAAE,CAAA;SAAE,CAAC;QAAC,KAAK,EAAE,SAAS,CAAA;KAAE,CAC5C;IAmCD;;;;;;OAMG;IACG,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;IAiBrD;;;;;;OAMG;IACG,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,mBAAmB,GAAG,OAAO,CAAC,YAAY,CAAC;IAkBzF;;;;;;;;OAQG;IACG,UAAU,CAAC,EAAE,EAAE,MAAM,EAAE,gBAAgB,UAAQ,GAAG,OAAO,CAAC,YAAY,CAAC;YAoB/D,YAAY;YA2BZ,aAAa;IA0B3B;;;;;OAKG;YACW,iBAAiB;IAmC/B;;;;;OAKG;YACW,kBAAkB;IAoBhC;;;;;OAKG;YACW,eAAe;IAiB7B;;;;;OAKG;YACW,kBAAkB;IAsBhC;;;;;OAKG;YACW,4BAA4B;CAqB3C"}
|
||||
+405
@@ -0,0 +1,405 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const tslib_1 = require("tslib");
|
||||
const fetch_1 = require("./lib/fetch");
|
||||
const helpers_1 = require("./lib/helpers");
|
||||
const types_1 = require("./lib/types");
|
||||
const errors_1 = require("./lib/errors");
|
||||
class GoTrueAdminApi {
|
||||
constructor({ url = '', headers = {}, fetch, }) {
|
||||
this.url = url;
|
||||
this.headers = headers;
|
||||
this.fetch = (0, helpers_1.resolveFetch)(fetch);
|
||||
this.mfa = {
|
||||
listFactors: this._listFactors.bind(this),
|
||||
deleteFactor: this._deleteFactor.bind(this),
|
||||
};
|
||||
this.oauth = {
|
||||
listClients: this._listOAuthClients.bind(this),
|
||||
createClient: this._createOAuthClient.bind(this),
|
||||
getClient: this._getOAuthClient.bind(this),
|
||||
deleteClient: this._deleteOAuthClient.bind(this),
|
||||
regenerateClientSecret: this._regenerateOAuthClientSecret.bind(this),
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Removes a logged-in session.
|
||||
* @param jwt A valid, logged-in JWT.
|
||||
* @param scope The logout sope.
|
||||
*/
|
||||
async signOut(jwt, scope = types_1.SIGN_OUT_SCOPES[0]) {
|
||||
if (types_1.SIGN_OUT_SCOPES.indexOf(scope) < 0) {
|
||||
throw new Error(`@supabase/auth-js: Parameter scope must be one of ${types_1.SIGN_OUT_SCOPES.join(', ')}`);
|
||||
}
|
||||
try {
|
||||
await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/logout?scope=${scope}`, {
|
||||
headers: this.headers,
|
||||
jwt,
|
||||
noResolveJson: true,
|
||||
});
|
||||
return { data: null, error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Sends an invite link to an email address.
|
||||
* @param email The email address of the user.
|
||||
* @param options Additional options to be included when inviting.
|
||||
*/
|
||||
async inviteUserByEmail(email, options = {}) {
|
||||
try {
|
||||
return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/invite`, {
|
||||
body: { email, data: options.data },
|
||||
headers: this.headers,
|
||||
redirectTo: options.redirectTo,
|
||||
xform: fetch_1._userResponse,
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: { user: null }, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Generates email links and OTPs to be sent via a custom email provider.
|
||||
* @param email The user's email.
|
||||
* @param options.password User password. For signup only.
|
||||
* @param options.data Optional user metadata. For signup only.
|
||||
* @param options.redirectTo The redirect url which should be appended to the generated link
|
||||
*/
|
||||
async generateLink(params) {
|
||||
try {
|
||||
const { options } = params, rest = tslib_1.__rest(params, ["options"]);
|
||||
const body = Object.assign(Object.assign({}, rest), options);
|
||||
if ('newEmail' in rest) {
|
||||
// replace newEmail with new_email in request body
|
||||
body.new_email = rest === null || rest === void 0 ? void 0 : rest.newEmail;
|
||||
delete body['newEmail'];
|
||||
}
|
||||
return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/generate_link`, {
|
||||
body: body,
|
||||
headers: this.headers,
|
||||
xform: fetch_1._generateLinkResponse,
|
||||
redirectTo: options === null || options === void 0 ? void 0 : options.redirectTo,
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return {
|
||||
data: {
|
||||
properties: null,
|
||||
user: null,
|
||||
},
|
||||
error,
|
||||
};
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
// User Admin API
|
||||
/**
|
||||
* Creates a new user.
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
async createUser(attributes) {
|
||||
try {
|
||||
return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/users`, {
|
||||
body: attributes,
|
||||
headers: this.headers,
|
||||
xform: fetch_1._userResponse,
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: { user: null }, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Get a list of users.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
* @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results.
|
||||
*/
|
||||
async listUsers(params) {
|
||||
var _a, _b, _c, _d, _e, _f, _g;
|
||||
try {
|
||||
const pagination = { nextPage: null, lastPage: 0, total: 0 };
|
||||
const response = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users`, {
|
||||
headers: this.headers,
|
||||
noResolveJson: true,
|
||||
query: {
|
||||
page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '',
|
||||
per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '',
|
||||
},
|
||||
xform: fetch_1._noResolveJsonResponse,
|
||||
});
|
||||
if (response.error)
|
||||
throw response.error;
|
||||
const users = await response.json();
|
||||
const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0;
|
||||
const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : [];
|
||||
if (links.length > 0) {
|
||||
links.forEach((link) => {
|
||||
const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1));
|
||||
const rel = JSON.parse(link.split(';')[1].split('=')[1]);
|
||||
pagination[`${rel}Page`] = page;
|
||||
});
|
||||
pagination.total = parseInt(total);
|
||||
}
|
||||
return { data: Object.assign(Object.assign({}, users), pagination), error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: { users: [] }, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Get user by id.
|
||||
*
|
||||
* @param uid The user's unique identifier
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
async getUserById(uid) {
|
||||
(0, helpers_1.validateUUID)(uid);
|
||||
try {
|
||||
return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users/${uid}`, {
|
||||
headers: this.headers,
|
||||
xform: fetch_1._userResponse,
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: { user: null }, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Updates the user data.
|
||||
*
|
||||
* @param attributes The data you want to update.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
async updateUserById(uid, attributes) {
|
||||
(0, helpers_1.validateUUID)(uid);
|
||||
try {
|
||||
return await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/admin/users/${uid}`, {
|
||||
body: attributes,
|
||||
headers: this.headers,
|
||||
xform: fetch_1._userResponse,
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: { user: null }, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Delete a user. Requires a `service_role` key.
|
||||
*
|
||||
* @param id The user id you want to remove.
|
||||
* @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible.
|
||||
* Defaults to false for backward compatibility.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
async deleteUser(id, shouldSoftDelete = false) {
|
||||
(0, helpers_1.validateUUID)(id);
|
||||
try {
|
||||
return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, {
|
||||
headers: this.headers,
|
||||
body: {
|
||||
should_soft_delete: shouldSoftDelete,
|
||||
},
|
||||
xform: fetch_1._userResponse,
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: { user: null }, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async _listFactors(params) {
|
||||
(0, helpers_1.validateUUID)(params.userId);
|
||||
try {
|
||||
const { data, error } = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users/${params.userId}/factors`, {
|
||||
headers: this.headers,
|
||||
xform: (factors) => {
|
||||
return { data: { factors }, error: null };
|
||||
},
|
||||
});
|
||||
return { data, error };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async _deleteFactor(params) {
|
||||
(0, helpers_1.validateUUID)(params.userId);
|
||||
(0, helpers_1.validateUUID)(params.id);
|
||||
try {
|
||||
const data = await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/users/${params.userId}/factors/${params.id}`, {
|
||||
headers: this.headers,
|
||||
});
|
||||
return { data, error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Lists all OAuth clients with optional pagination.
|
||||
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
async _listOAuthClients(params) {
|
||||
var _a, _b, _c, _d, _e, _f, _g;
|
||||
try {
|
||||
const pagination = { nextPage: null, lastPage: 0, total: 0 };
|
||||
const response = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/oauth/clients`, {
|
||||
headers: this.headers,
|
||||
noResolveJson: true,
|
||||
query: {
|
||||
page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '',
|
||||
per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '',
|
||||
},
|
||||
xform: fetch_1._noResolveJsonResponse,
|
||||
});
|
||||
if (response.error)
|
||||
throw response.error;
|
||||
const clients = await response.json();
|
||||
const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0;
|
||||
const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : [];
|
||||
if (links.length > 0) {
|
||||
links.forEach((link) => {
|
||||
const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1));
|
||||
const rel = JSON.parse(link.split(';')[1].split('=')[1]);
|
||||
pagination[`${rel}Page`] = page;
|
||||
});
|
||||
pagination.total = parseInt(total);
|
||||
}
|
||||
return { data: Object.assign(Object.assign({}, clients), pagination), error: null };
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: { clients: [] }, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Creates a new OAuth client.
|
||||
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
async _createOAuthClient(params) {
|
||||
try {
|
||||
return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/oauth/clients`, {
|
||||
body: params,
|
||||
headers: this.headers,
|
||||
xform: (client) => {
|
||||
return { data: client, error: null };
|
||||
},
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Gets details of a specific OAuth client.
|
||||
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
async _getOAuthClient(clientId) {
|
||||
try {
|
||||
return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/oauth/clients/${clientId}`, {
|
||||
headers: this.headers,
|
||||
xform: (client) => {
|
||||
return { data: client, error: null };
|
||||
},
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Deletes an OAuth client.
|
||||
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
async _deleteOAuthClient(clientId) {
|
||||
try {
|
||||
return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/oauth/clients/${clientId}`, {
|
||||
headers: this.headers,
|
||||
xform: (client) => {
|
||||
return { data: client, error: null };
|
||||
},
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Regenerates the secret for an OAuth client.
|
||||
* Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
|
||||
*
|
||||
* This function should only be called on a server. Never expose your `service_role` key in the browser.
|
||||
*/
|
||||
async _regenerateOAuthClientSecret(clientId) {
|
||||
try {
|
||||
return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/oauth/clients/${clientId}/regenerate_secret`, {
|
||||
headers: this.headers,
|
||||
xform: (client) => {
|
||||
return { data: client, error: null };
|
||||
},
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
if ((0, errors_1.isAuthError)(error)) {
|
||||
return { data: null, error };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.default = GoTrueAdminApi;
|
||||
//# sourceMappingURL=GoTrueAdminApi.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"GoTrueAdminApi.js","sourceR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AO,CAAC,CAAC,IAAY,EAAE,EAAE;oBAC7B,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;oBACvE,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;oBACxD,UAAU,CAAC,GAAG,GAAG,MAAM,CAAC,GAAG,IAAI,CAAA;gBACjC,CAAC,CAAC,CAAA;gBAEF,UAAU,CAAC,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAA;YACpC,CAAC;YACD,OAAO,EAAE,IAAI,kCAAO,KAAK,GAAK,UAAU,CAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;QAC3D,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,IAAA,oBAAW,EAAC,KAAK,CAAC,EAAE,CAAC;gBACvB,OAAO,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,CAAA;YACvC,CAAC;YACD,MAAM,KAAK,CAAA;QACb,CAACLine truncated
|
||||
+550
@@ -0,0 +1,550 @@
|
||||
import GoTrueAdminApi from './GoTrueAdminApi';
|
||||
import { AuthError } from './lib/errors';
|
||||
import { Fetch } from './lib/fetch';
|
||||
import { Deferred } from './lib/helpers';
|
||||
import type { AuthChangeEvent, AuthFlowType, AuthOtpResponse, AuthResponse, AuthTokenResponse, AuthTokenResponsePassword, CallRefreshTokenResult, GoTrueClientOptions, GoTrueMFAApi, InitializeResult, JWK, JwtHeader, JwtPayload, LockFunc, OAuthResponse, ResendParams, Session, SignInAnonymouslyCredentials, SignInWithIdTokenCredentials, SignInWithOAuthCredentials, SignInWithPasswordCredentials, SignInWithPasswordlessCredentials, SignInWithSSO, SignOut, SignUpWithPasswordCredentials, SSOResponse, Subscription, SupportedStorage, User, UserAttributes, UserIdentity, UserResponse, VerifyOtpParams, Web3Credentials } from './lib/types';
|
||||
export default class GoTrueClient {
|
||||
private static nextInstanceID;
|
||||
private instanceID;
|
||||
/**
|
||||
* Namespace for the GoTrue admin methods.
|
||||
* These methods should only be used in a trusted server-side environment.
|
||||
*/
|
||||
admin: GoTrueAdminApi;
|
||||
/**
|
||||
* Namespace for the MFA methods.
|
||||
*/
|
||||
mfa: GoTrueMFAApi;
|
||||
/**
|
||||
* The storage key used to identify the values saved in localStorage
|
||||
*/
|
||||
protected storageKey: string;
|
||||
protected flowType: AuthFlowType;
|
||||
/**
|
||||
* The JWKS used for verifying asymmetric JWTs
|
||||
*/
|
||||
protected get jwks(): {
|
||||
keys: JWK[];
|
||||
};
|
||||
protected set jwks(value: {
|
||||
keys: JWK[];
|
||||
});
|
||||
protected get jwks_cached_at(): number;
|
||||
protected set jwks_cached_at(value: number);
|
||||
protected autoRefreshToken: boolean;
|
||||
protected persistSession: boolean;
|
||||
protected storage: SupportedStorage;
|
||||
/**
|
||||
* @experimental
|
||||
*/
|
||||
protected userStorage: SupportedStorage | null;
|
||||
protected memoryStorage: {
|
||||
[key: string]: string;
|
||||
} | null;
|
||||
protected stateChangeEmitters: Map<string, Subscription>;
|
||||
protected autoRefreshTicker: ReturnType<typeof setInterval> | null;
|
||||
protected visibilityChangedCallback: (() => Promise<any>) | null;
|
||||
protected refreshingDeferred: Deferred<CallRefreshTokenResult> | null;
|
||||
/**
|
||||
* Keeps track of the async client initialization.
|
||||
* When null or not yet resolved the auth state is `unknown`
|
||||
* Once resolved the auth state is known and it's safe to call any further client methods.
|
||||
* Keep extra care to never reject or throw uncaught errors
|
||||
*/
|
||||
protected initializePromise: Promise<InitializeResult> | null;
|
||||
protected detectSessionInUrl: boolean;
|
||||
protected url: string;
|
||||
protected headers: {
|
||||
[key: string]: string;
|
||||
};
|
||||
protected hasCustomAuthorizationHeader: boolean;
|
||||
protected suppressGetSessionWarning: boolean;
|
||||
protected fetch: Fetch;
|
||||
protected lock: LockFunc;
|
||||
protected lockAcquired: boolean;
|
||||
protected pendingInLock: Promise<any>[];
|
||||
/**
|
||||
* Used to broadcast state change events to other tabs listening.
|
||||
*/
|
||||
protected broadcastChannel: BroadcastChannel | null;
|
||||
protected logDebugMessages: boolean;
|
||||
protected logger: (message: string, ...args: any[]) => void;
|
||||
/**
|
||||
* Create a new client for use in the browser.
|
||||
*/
|
||||
constructor(options: GoTrueClientOptions);
|
||||
private _debug;
|
||||
/**
|
||||
* Initializes the client session either from the url or from storage.
|
||||
* This method is automatically called when instantiating the client, but should also be called
|
||||
* manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc).
|
||||
*/
|
||||
initialize(): Promise<InitializeResult>;
|
||||
/**
|
||||
* IMPORTANT:
|
||||
* 1. Never throw in this method, as it is called from the constructor
|
||||
* 2. Never return a session from this method as it would be cached over
|
||||
* the whole lifetime of the client
|
||||
*/
|
||||
private _initialize;
|
||||
/**
|
||||
* Creates a new anonymous user.
|
||||
*
|
||||
* @returns A session where the is_anonymous claim in the access token JWT set to true
|
||||
*/
|
||||
signInAnonymously(credentials?: SignInAnonymouslyCredentials): Promise<AuthResponse>;
|
||||
/**
|
||||
* Creates a new user.
|
||||
*
|
||||
* Be aware that if a user account exists in the system you may get back an
|
||||
* error message that attempts to hide this information from the user.
|
||||
* This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled.
|
||||
*
|
||||
* @returns A logged-in session if the server has "autoconfirm" ON
|
||||
* @returns A user if the server has "autoconfirm" OFF
|
||||
*/
|
||||
signUp(credentials: SignUpWithPasswordCredentials): Promise<AuthResponse>;
|
||||
/**
|
||||
* Log in an existing user with an email and password or phone and password.
|
||||
*
|
||||
* Be aware that you may get back an error message that will not distinguish
|
||||
* between the cases where the account does not exist or that the
|
||||
* email/phone and password combination is wrong or that the account can only
|
||||
* be accessed via social login.
|
||||
*/
|
||||
signInWithPassword(credentials: SignInWithPasswordCredentials): Promise<AuthTokenResponsePassword>;
|
||||
/**
|
||||
* Log in an existing user via a third-party provider.
|
||||
* This method supports the PKCE flow.
|
||||
*/
|
||||
signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse>;
|
||||
/**
|
||||
* Log in an existing user by exchanging an Auth Code issued during the PKCE flow.
|
||||
*/
|
||||
exchangeCodeForSession(authCode: string): Promise<AuthTokenResponse>;
|
||||
/**
|
||||
* Signs in a user by verifying a message signed by the user's private key.
|
||||
* Supports Ethereum (via Sign-In-With-Ethereum) & Solana (Sign-In-With-Solana) standards,
|
||||
* both of which derive from the EIP-4361 standard
|
||||
* With slight variation on Solana's side.
|
||||
* @reference https://eips.ethereum.org/EIPS/eip-4361
|
||||
*/
|
||||
signInWithWeb3(credentials: Web3Credentials): Promise<{
|
||||
data: {
|
||||
session: Session;
|
||||
user: User;
|
||||
};
|
||||
error: null;
|
||||
} | {
|
||||
data: {
|
||||
session: null;
|
||||
user: null;
|
||||
};
|
||||
error: AuthError;
|
||||
}>;
|
||||
private signInWithEthereum;
|
||||
private signInWithSolana;
|
||||
private _exchangeCodeForSession;
|
||||
/**
|
||||
* Allows signing in with an OIDC ID token. The authentication provider used
|
||||
* should be enabled and configured.
|
||||
*/
|
||||
signInWithIdToken(credentials: SignInWithIdTokenCredentials): Promise<AuthTokenResponse>;
|
||||
/**
|
||||
* Log in a user using magiclink or a one-time password (OTP).
|
||||
*
|
||||
* If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent.
|
||||
* If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent.
|
||||
* If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins.
|
||||
*
|
||||
* Be aware that you may get back an error message that will not distinguish
|
||||
* between the cases where the account does not exist or, that the account
|
||||
* can only be accessed via social login.
|
||||
*
|
||||
* Do note that you will need to configure a Whatsapp sender on Twilio
|
||||
* if you are using phone sign in with the 'whatsapp' channel. The whatsapp
|
||||
* channel is not supported on other providers
|
||||
* at this time.
|
||||
* This method supports PKCE when an email is passed.
|
||||
*/
|
||||
signInWithOtp(credentials: SignInWithPasswordlessCredentials): Promise<AuthOtpResponse>;
|
||||
/**
|
||||
* Log in a user given a User supplied OTP or TokenHash received through mobile or email.
|
||||
*/
|
||||
verifyOtp(params: VerifyOtpParams): Promise<AuthResponse>;
|
||||
/**
|
||||
* Attempts a single-sign on using an enterprise Identity Provider. A
|
||||
* successful SSO attempt will redirect the current page to the identity
|
||||
* provider authorization page. The redirect URL is implementation and SSO
|
||||
* protocol specific.
|
||||
*
|
||||
* You can use it by providing a SSO domain. Typically you can extract this
|
||||
* domain by asking users for their email address. If this domain is
|
||||
* registered on the Auth instance the redirect will use that organization's
|
||||
* currently active SSO Identity Provider for the login.
|
||||
*
|
||||
* If you have built an organization-specific login page, you can use the
|
||||
* organization's SSO Identity Provider UUID directly instead.
|
||||
*/
|
||||
signInWithSSO(params: SignInWithSSO): Promise<SSOResponse>;
|
||||
/**
|
||||
* Sends a reauthentication OTP to the user's email or phone number.
|
||||
* Requires the user to be signed-in.
|
||||
*/
|
||||
reauthenticate(): Promise<AuthResponse>;
|
||||
private _reauthenticate;
|
||||
/**
|
||||
* Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP.
|
||||
*/
|
||||
resend(credentials: ResendParams): Promise<AuthOtpResponse>;
|
||||
/**
|
||||
* Returns the session, refreshing it if necessary.
|
||||
*
|
||||
* The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out.
|
||||
*
|
||||
* **IMPORTANT:** This method loads values directly from the storage attached
|
||||
* to the client. If that storage is based on request cookies for example,
|
||||
* the values in it may not be authentic and therefore it's strongly advised
|
||||
* against using this method and its results in such circumstances. A warning
|
||||
* will be emitted if this is detected. Use {@link #getUser()} instead.
|
||||
*/
|
||||
getSession(): Promise<{
|
||||
data: {
|
||||
session: Session;
|
||||
};
|
||||
error: null;
|
||||
} | {
|
||||
data: {
|
||||
session: null;
|
||||
};
|
||||
error: AuthError;
|
||||
} | {
|
||||
data: {
|
||||
session: null;
|
||||
};
|
||||
error: null;
|
||||
}>;
|
||||
/**
|
||||
* Acquires a global lock based on the storage key.
|
||||
*/
|
||||
private _acquireLock;
|
||||
/**
|
||||
* Use instead of {@link #getSession} inside the library. It is
|
||||
* semantically usually what you want, as getting a session involves some
|
||||
* processing afterwards that requires only one client operating on the
|
||||
* session at once across multiple tabs or processes.
|
||||
*/
|
||||
private _useSession;
|
||||
/**
|
||||
* NEVER USE DIRECTLY!
|
||||
*
|
||||
* Always use {@link #_useSession}.
|
||||
*/
|
||||
private __loadSession;
|
||||
/**
|
||||
* Gets the current user details if there is an existing session. This method
|
||||
* performs a network request to the Supabase Auth server, so the returned
|
||||
* value is authentic and can be used to base authorization rules on.
|
||||
*
|
||||
* @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used.
|
||||
*/
|
||||
getUser(jwt?: string): Promise<UserResponse>;
|
||||
private _getUser;
|
||||
/**
|
||||
* Updates user data for a logged in user.
|
||||
*/
|
||||
updateUser(attributes: UserAttributes, options?: {
|
||||
emailRedirectTo?: string | undefined;
|
||||
}): Promise<UserResponse>;
|
||||
protected _updateUser(attributes: UserAttributes, options?: {
|
||||
emailRedirectTo?: string | undefined;
|
||||
}): Promise<UserResponse>;
|
||||
/**
|
||||
* Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session.
|
||||
* If the refresh token or access token in the current session is invalid, an error will be thrown.
|
||||
* @param currentSession The current session that minimally contains an access token and refresh token.
|
||||
*/
|
||||
setSession(currentSession: {
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
}): Promise<AuthResponse>;
|
||||
protected _setSession(currentSession: {
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
}): Promise<AuthResponse>;
|
||||
/**
|
||||
* Returns a new session, regardless of expiry status.
|
||||
* Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession().
|
||||
* If the current session's refresh token is invalid, an error will be thrown.
|
||||
* @param currentSession The current session. If passed in, it must contain a refresh token.
|
||||
*/
|
||||
refreshSession(currentSession?: {
|
||||
refresh_token: string;
|
||||
}): Promise<AuthResponse>;
|
||||
protected _refreshSession(currentSession?: {
|
||||
refresh_token: string;
|
||||
}): Promise<AuthResponse>;
|
||||
/**
|
||||
* Gets the session data from a URL string
|
||||
*/
|
||||
private _getSessionFromURL;
|
||||
/**
|
||||
* Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2)
|
||||
*/
|
||||
private _isImplicitGrantCallback;
|
||||
/**
|
||||
* Checks if the current URL and backing storage contain parameters given by a PKCE flow
|
||||
*/
|
||||
private _isPKCECallback;
|
||||
/**
|
||||
* Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event.
|
||||
*
|
||||
* For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`.
|
||||
* There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason.
|
||||
*
|
||||
* If using `others` scope, no `SIGNED_OUT` event is fired!
|
||||
*/
|
||||
signOut(options?: SignOut): Promise<{
|
||||
error: AuthError | null;
|
||||
}>;
|
||||
protected _signOut({ scope }?: SignOut): Promise<{
|
||||
error: AuthError | null;
|
||||
}>;
|
||||
/**
|
||||
* Receive a notification every time an auth event happens.
|
||||
* Safe to use without an async function as callback.
|
||||
*
|
||||
* @param callback A callback function to be invoked when an auth event happens.
|
||||
*/
|
||||
onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => void): {
|
||||
data: {
|
||||
subscription: Subscription;
|
||||
};
|
||||
};
|
||||
/**
|
||||
* Avoid using an async function inside `onAuthStateChange` as you might end
|
||||
* up with a deadlock. The callback function runs inside an exclusive lock,
|
||||
* so calling other Supabase Client APIs that also try to acquire the
|
||||
* exclusive lock, might cause a deadlock. This behavior is observable across
|
||||
* tabs. In the next major library version, this behavior will not be supported.
|
||||
*
|
||||
* Receive a notification every time an auth event happens.
|
||||
*
|
||||
* @param callback A callback function to be invoked when an auth event happens.
|
||||
* @deprecated Due to the possibility of deadlocks with async functions as callbacks, use the version without an async function.
|
||||
*/
|
||||
onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => Promise<void>): {
|
||||
data: {
|
||||
subscription: Subscription;
|
||||
};
|
||||
};
|
||||
private _emitInitialSession;
|
||||
/**
|
||||
* Sends a password reset request to an email address. This method supports the PKCE flow.
|
||||
*
|
||||
* @param email The email address of the user.
|
||||
* @param options.redirectTo The URL to send the user to after they click the password reset link.
|
||||
* @param options.captchaToken Verification token received when the user completes the captcha on the site.
|
||||
*/
|
||||
resetPasswordForEmail(email: string, options?: {
|
||||
redirectTo?: string;
|
||||
captchaToken?: string;
|
||||
}): Promise<{
|
||||
data: {};
|
||||
error: null;
|
||||
} | {
|
||||
data: null;
|
||||
error: AuthError;
|
||||
}>;
|
||||
/**
|
||||
* Gets all the identities linked to a user.
|
||||
*/
|
||||
getUserIdentities(): Promise<{
|
||||
data: {
|
||||
identities: UserIdentity[];
|
||||
};
|
||||
error: null;
|
||||
} | {
|
||||
data: null;
|
||||
error: AuthError;
|
||||
}>;
|
||||
/**
|
||||
* Links an oauth identity to an existing user.
|
||||
* This method supports the PKCE flow.
|
||||
*/
|
||||
linkIdentity(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse>;
|
||||
/**
|
||||
* Links an OIDC identity to an existing user.
|
||||
*/
|
||||
linkIdentity(credentials: SignInWithIdTokenCredentials): Promise<AuthTokenResponse>;
|
||||
private linkIdentityOAuth;
|
||||
private linkIdentityIdToken;
|
||||
/**
|
||||
* Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked.
|
||||
*/
|
||||
unlinkIdentity(identity: UserIdentity): Promise<{
|
||||
data: {};
|
||||
error: null;
|
||||
} | {
|
||||
data: null;
|
||||
error: AuthError;
|
||||
}>;
|
||||
/**
|
||||
* Generates a new JWT.
|
||||
* @param refreshToken A valid refresh token that was returned on login.
|
||||
*/
|
||||
private _refreshAccessToken;
|
||||
private _isValidSession;
|
||||
private _handleProviderSignIn;
|
||||
/**
|
||||
* Recovers the session from LocalStorage and refreshes the token
|
||||
* Note: this method is async to accommodate for AsyncStorage e.g. in React native.
|
||||
*/
|
||||
private _recoverAndRefresh;
|
||||
private _callRefreshToken;
|
||||
private _notifyAllSubscribers;
|
||||
/**
|
||||
* set currentSession and currentUser
|
||||
* process to _startAutoRefreshToken if possible
|
||||
*/
|
||||
private _saveSession;
|
||||
private _removeSession;
|
||||
/**
|
||||
* Removes any registered visibilitychange callback.
|
||||
*
|
||||
* {@see #startAutoRefresh}
|
||||
* {@see #stopAutoRefresh}
|
||||
*/
|
||||
private _removeVisibilityChangedCallback;
|
||||
/**
|
||||
* This is the private implementation of {@link #startAutoRefresh}. Use this
|
||||
* within the library.
|
||||
*/
|
||||
private _startAutoRefresh;
|
||||
/**
|
||||
* This is the private implementation of {@link #stopAutoRefresh}. Use this
|
||||
* within the library.
|
||||
*/
|
||||
private _stopAutoRefresh;
|
||||
/**
|
||||
* Starts an auto-refresh process in the background. The session is checked
|
||||
* every few seconds. Close to the time of expiration a process is started to
|
||||
* refresh the session. If refreshing fails it will be retried for as long as
|
||||
* necessary.
|
||||
*
|
||||
* If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need
|
||||
* to call this function, it will be called for you.
|
||||
*
|
||||
* On browsers the refresh process works only when the tab/window is in the
|
||||
* foreground to conserve resources as well as prevent race conditions and
|
||||
* flooding auth with requests. If you call this method any managed
|
||||
* visibility change callback will be removed and you must manage visibility
|
||||
* changes on your own.
|
||||
*
|
||||
* On non-browser platforms the refresh process works *continuously* in the
|
||||
* background, which may not be desirable. You should hook into your
|
||||
* platform's foreground indication mechanism and call these methods
|
||||
* appropriately to conserve resources.
|
||||
*
|
||||
* {@see #stopAutoRefresh}
|
||||
*/
|
||||
startAutoRefresh(): Promise<void>;
|
||||
/**
|
||||
* Stops an active auto refresh process running in the background (if any).
|
||||
*
|
||||
* If you call this method any managed visibility change callback will be
|
||||
* removed and you must manage visibility changes on your own.
|
||||
*
|
||||
* See {@link #startAutoRefresh} for more details.
|
||||
*/
|
||||
stopAutoRefresh(): Promise<void>;
|
||||
/**
|
||||
* Runs the auto refresh token tick.
|
||||
*/
|
||||
private _autoRefreshTokenTick;
|
||||
/**
|
||||
* Registers callbacks on the browser / platform, which in-turn run
|
||||
* algorithms when the browser window/tab are in foreground. On non-browser
|
||||
* platforms it assumes always foreground.
|
||||
*/
|
||||
private _handleVisibilityChange;
|
||||
/**
|
||||
* Callback registered with `window.addEventListener('visibilitychange')`.
|
||||
*/
|
||||
private _onVisibilityChanged;
|
||||
/**
|
||||
* Generates the relevant login URL for a third-party provider.
|
||||
* @param options.redirectTo A URL or mobile address to send the user to after they are confirmed.
|
||||
* @param options.scopes A space-separated list of scopes granted to the OAuth application.
|
||||
* @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application.
|
||||
*/
|
||||
private _getUrlForProvider;
|
||||
private _unenroll;
|
||||
/**
|
||||
* {@see GoTrueMFAApi#enroll}
|
||||
*/
|
||||
private _enroll;
|
||||
/**
|
||||
* {@see GoTrueMFAApi#verify}
|
||||
*/
|
||||
private _verify;
|
||||
/**
|
||||
* {@see GoTrueMFAApi#challenge}
|
||||
*/
|
||||
private _challenge;
|
||||
/**
|
||||
* {@see GoTrueMFAApi#challengeAndVerify}
|
||||
*/
|
||||
private _challengeAndVerify;
|
||||
/**
|
||||
* {@see GoTrueMFAApi#listFactors}
|
||||
*/
|
||||
private _listFactors;
|
||||
/**
|
||||
* {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel}
|
||||
*/
|
||||
private _getAuthenticatorAssuranceLevel;
|
||||
private fetchJwk;
|
||||
/**
|
||||
* Extracts the JWT claims present in the access token by first verifying the
|
||||
* JWT against the server's JSON Web Key Set endpoint
|
||||
* `/.well-known/jwks.json` which is often cached, resulting in significantly
|
||||
* faster responses. Prefer this method over {@link #getUser} which always
|
||||
* sends a request to the Auth server for each JWT.
|
||||
*
|
||||
* If the project is not using an asymmetric JWT signing key (like ECC or
|
||||
* RSA) it always sends a request to the Auth server (similar to {@link
|
||||
* #getUser}) to verify the JWT.
|
||||
*
|
||||
* @param jwt An optional specific JWT you wish to verify, not the one you
|
||||
* can obtain from {@link #getSession}.
|
||||
* @param options Various additional options that allow you to customize the
|
||||
* behavior of this method.
|
||||
*/
|
||||
getClaims(jwt?: string, options?: {
|
||||
/**
|
||||
* @deprecated Please use options.jwks instead.
|
||||
*/
|
||||
keys?: JWK[];
|
||||
/** If set to `true` the `exp` claim will not be validated against the current time. */
|
||||
allowExpired?: boolean;
|
||||
/** If set, this JSON Web Key Set is going to have precedence over the cached value available on the server. */
|
||||
jwks?: {
|
||||
keys: JWK[];
|
||||
};
|
||||
}): Promise<{
|
||||
data: {
|
||||
claims: JwtPayload;
|
||||
header: JwtHeader;
|
||||
signature: Uint8Array;
|
||||
};
|
||||
error: null;
|
||||
} | {
|
||||
data: null;
|
||||
error: AuthError;
|
||||
} | {
|
||||
data: null;
|
||||
error: null;
|
||||
}>;
|
||||
}
|
||||
//# sourceMappingURL=GoTrueClient.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"GoTrueClient.d.ts","sourceRoot":"","sources":["../../src/GoTrueClient.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAU7C,OAAO,EACL,SAAS,EAaV,MAAM,cAAc,CAAA;AACrB,OAAO,EACL,KAAK,EAMN,MAAM,aAAa,CAAA;AACpB,OAAO,EAGL,QAAQ,EAeT,MAAM,eAAe,CAAA;AAOtB,OAAO,KAAK,EACV,eAAe,EAEf,YAAY,EAcZ,eAAe,EACf,YAAY,EAEZ,iBAA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e,CAAC,cAAc,CAAC,EAAE;QAC/C,aAAa,EAAE,MAAM,CAAA;KACtB,GAAG,OAAO,CAAC,YAAY,CAAC;IAoCzB;;OAEG;YACW,kBAAkB;IAmIhC;;OAEG;IACH,OAAO,CAAC,wBAAwB;IAIhC;;OAEG;YACW,eAAe;IAS7B;;;;;;;OAOG;IACG,OAAO,CAAC,OAAO,GAAE,OAA6B,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,SAAS,GAAG,IAAI,CAAA;KAAE,CAAC;cAQ3E,QAAQ,CACtB,EAAE,KAAK,EAAE,GAAE,OAA6B,GACvC,OAAO,CAAC;QAAE,KAAK,EAAE,SAAS,GAAG,IAAI,CAAA;KAAE,CAAC;IA8BvC;;;;;OAKG;IACH,iBAAiB,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,eAAe,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI,KAAK,IAAI,GAAG;Line truncated
|
||||
+2558
File diff suppressed because it is too large.
Load diff
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"GoTrueClient.js","sourceRoot":"","sources":["../../src/GoTrueClient.ts"],"names":[],"mappings":";;;AAAA,8EAA6C;AAC7C,+CAQwB;AACxB,yCAcqB;AACrB,uCAOoB;AACpB,2CAkBsB;AACtB,uDAA+D;AAC/D,uCAAoE;AACpE,+CAAoD;AACpD,2CAAuC;AAEvC,+CAAsE;AA2EtE,kDAO4B;AAC5B,6CAMuB;AAOvB,IAAA,8BAAkB,GAAE,CAAA,CAAC,8BAA8B;AAEnD,MAAM,eAAe,GAGjB;IACF,GAAG,EAAE,sBAAU;IACf,UAAU,EAAE,uBAAW;IACvB,gBAAgB,EAAE,IAAI;IACtB,cAAc,EAAE,IAAI;IACpB,kBAAkB,EAAE,IAAI;IACxB,OAAO,EAAE,2BAAe;IACxB,QAAQ,EAAE,UAAU;IACpB,KAAK,EAAE,KAAK;IACZ,4BAA4B,EAAE,KAAK;CACpC,CAAA;AAED,KAAK,UAAU,QAAQ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C,MAAM,CAAC,0DAA0D,EAAE,KAAK,CAAC,CAAA;gBAE9E,MAAM,IAAI,CAAC,qBAAqB,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA,CAAC,gEAAgE;YAChJ,CAAC,CAAC,CAAA;QACJ,CAAC;QAED,IAAI,CAAC,UAAU,EAAE,CAAA;IACnB,CAAC;IAEO,MAAM,CAAC,GAAG,IAAW;QAC3B,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YALine truncated
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import GoTrueAdminApi from './GoTrueAdminApi';
|
||||
import GoTrueClient from './GoTrueClient';
|
||||
import AuthAdminApi from './AuthAdminApi';
|
||||
import AuthClient from './AuthClient';
|
||||
export { GoTrueAdminApi, GoTrueClient, AuthAdminApi, AuthClient };
|
||||
export * from './lib/types';
|
||||
export * from './lib/errors';
|
||||
export { navigatorLock, NavigatorLockAcquireTimeoutError, internals as lockInternals, processLock, } from './lib/locks';
|
||||
//# sourceMappingURL=index.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAC7C,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,UAAU,MAAM,cAAc,CAAA;AACrC,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,CAAA;AACjE,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,OAAO,EACL,aAAa,EACb,gCAAgC,EAChC,SAAS,IAAI,aAAa,EAC1B,WAAW,GACZ,MAAM,aAAa,CAAA"}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.processLock = exports.lockInternals = exports.NavigatorLockAcquireTimeoutError = exports.navigatorLock = exports.AuthClient = exports.AuthAdminApi = exports.GoTrueClient = exports.GoTrueAdminApi = void 0;
|
||||
const tslib_1 = require("tslib");
|
||||
const GoTrueAdminApi_1 = tslib_1.__importDefault(require("./GoTrueAdminApi"));
|
||||
exports.GoTrueAdminApi = GoTrueAdminApi_1.default;
|
||||
const GoTrueClient_1 = tslib_1.__importDefault(require("./GoTrueClient"));
|
||||
exports.GoTrueClient = GoTrueClient_1.default;
|
||||
const AuthAdminApi_1 = tslib_1.__importDefault(require("./AuthAdminApi"));
|
||||
exports.AuthAdminApi = AuthAdminApi_1.default;
|
||||
const AuthClient_1 = tslib_1.__importDefault(require("./AuthClient"));
|
||||
exports.AuthClient = AuthClient_1.default;
|
||||
tslib_1.__exportStar(require("./lib/types"), exports);
|
||||
tslib_1.__exportStar(require("./lib/errors"), exports);
|
||||
var locks_1 = require("./lib/locks");
|
||||
Object.defineProperty(exports, "navigatorLock", { enumerable: true, get: function () { return locks_1.navigatorLock; } });
|
||||
Object.defineProperty(exports, "NavigatorLockAcquireTimeoutError", { enumerable: true, get: function () { return locks_1.NavigatorLockAcquireTimeoutError; } });
|
||||
Object.defineProperty(exports, "lockInternals", { enumerable: true, get: function () { return locks_1.internals; } });
|
||||
Object.defineProperty(exports, "processLock", { enumerable: true, get: function () { return locks_1.processLock; } });
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;AAAA,8EAA6C;AAIpC,yBAJF,wBAAc,CAIE;AAHvB,0EAAyC;AAGhB,uBAHlB,sBAAY,CAGkB;AAFrC,0EAAyC;AAEF,uBAFhC,sBAAY,CAEgC;AADnD,sEAAqC;AACgB,qBAD9C,oBAAU,CAC8C;AAC/D,sDAA2B;AAC3B,uDAA4B;AAC5B,qCAKoB;AAJlB,sGAAA,aAAa,OAAA;AACb,yHAAA,gCAAgC,OAAA;AAChC,sGAAA,SAAS,OAAiB;AAC1B,oGAAA,WAAW,OAAA"}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* Avoid modifying this file. It's part of
|
||||
* https://github.com/supabase-community/base64url-js. Submit all fixes on
|
||||
* that repo!
|
||||
*/
|
||||
import { Uint8Array_ } from './webauthn.dom';
|
||||
/**
|
||||
* Converts a byte to a Base64-URL string.
|
||||
*
|
||||
* @param byte The byte to convert, or null to flush at the end of the byte sequence.
|
||||
* @param state The Base64 conversion state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`.
|
||||
* @param emit A function called with the next Base64 character when ready.
|
||||
*/
|
||||
export declare function byteToBase64URL(byte: number | null, state: {
|
||||
queue: number;
|
||||
queuedBits: number;
|
||||
}, emit: (char: string) => void): void;
|
||||
/**
|
||||
* Converts a String char code (extracted using `string.charCodeAt(position)`) to a sequence of Base64-URL characters.
|
||||
*
|
||||
* @param charCode The char code of the JavaScript string.
|
||||
* @param state The Base64 state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`.
|
||||
* @param emit A function called with the next byte.
|
||||
*/
|
||||
export declare function byteFromBase64URL(charCode: number, state: {
|
||||
queue: number;
|
||||
queuedBits: number;
|
||||
}, emit: (byte: number) => void): void;
|
||||
/**
|
||||
* Converts a JavaScript string (which may include any valid character) into a
|
||||
* Base64-URL encoded string. The string is first encoded in UTF-8 which is
|
||||
* then encoded as Base64-URL.
|
||||
*
|
||||
* @param str The string to convert.
|
||||
*/
|
||||
export declare function stringToBase64URL(str: string): string;
|
||||
/**
|
||||
* Converts a Base64-URL encoded string into a JavaScript string. It is assumed
|
||||
* that the underlying string has been encoded as UTF-8.
|
||||
*
|
||||
* @param str The Base64-URL encoded string.
|
||||
*/
|
||||
export declare function stringFromBase64URL(str: string): string;
|
||||
/**
|
||||
* Converts a Unicode codepoint to a multi-byte UTF-8 sequence.
|
||||
*
|
||||
* @param codepoint The Unicode codepoint.
|
||||
* @param emit Function which will be called for each UTF-8 byte that represents the codepoint.
|
||||
*/
|
||||
export declare function codepointToUTF8(codepoint: number, emit: (byte: number) => void): void;
|
||||
/**
|
||||
* Converts a JavaScript string to a sequence of UTF-8 bytes.
|
||||
*
|
||||
* @param str The string to convert to UTF-8.
|
||||
* @param emit Function which will be called for each UTF-8 byte of the string.
|
||||
*/
|
||||
export declare function stringToUTF8(str: string, emit: (byte: number) => void): void;
|
||||
/**
|
||||
* Converts a UTF-8 byte to a Unicode codepoint.
|
||||
*
|
||||
* @param byte The UTF-8 byte next in the sequence.
|
||||
* @param state The shared state between consecutive UTF-8 bytes in the
|
||||
* sequence, an object with the shape `{ utf8seq: 0, codepoint: 0 }`.
|
||||
* @param emit Function which will be called for each codepoint.
|
||||
*/
|
||||
export declare function stringFromUTF8(byte: number, state: {
|
||||
utf8seq: number;
|
||||
codepoint: number;
|
||||
}, emit: (codepoint: number) => void): void;
|
||||
/**
|
||||
* Helper functions to convert different types of strings to Uint8Array
|
||||
*/
|
||||
export declare function base64UrlToUint8Array(str: string): Uint8Array_;
|
||||
export declare function stringToUint8Array(str: string): Uint8Array_;
|
||||
export declare function bytesToBase64URL(bytes: Uint8Array): string;
|
||||
//# sourceMappingURL=base64url.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"base64url.d.ts","sourceRoot":"","sources":["../../../src/lib/base64url.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAoC5C;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,MAAM,GAAG,IAAI,EACnB,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,EAC5C,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAqB7B;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,EAC5C,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAmB7B;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,UAgB5C;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,UAuB9C;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAsB9E;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAgBrE;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAC5B,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,EAC7C,IAAI,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,QAuClC;AAED;;GAEG;AAEH,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,WAAW,CAa9D;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,WAAW,CAI3D;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,UAAU,UAcjD"}
|
||||
+269
@@ -0,0 +1,269 @@
|
||||
"use strict";
|
||||
/**
|
||||
* Avoid modifying this file. It's part of
|
||||
* https://github.com/supabase-community/base64url-js. Submit all fixes on
|
||||
* that repo!
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.byteToBase64URL = byteToBase64URL;
|
||||
exports.byteFromBase64URL = byteFromBase64URL;
|
||||
exports.stringToBase64URL = stringToBase64URL;
|
||||
exports.stringFromBase64URL = stringFromBase64URL;
|
||||
exports.codepointToUTF8 = codepointToUTF8;
|
||||
exports.stringToUTF8 = stringToUTF8;
|
||||
exports.stringFromUTF8 = stringFromUTF8;
|
||||
exports.base64UrlToUint8Array = base64UrlToUint8Array;
|
||||
exports.stringToUint8Array = stringToUint8Array;
|
||||
exports.bytesToBase64URL = bytesToBase64URL;
|
||||
/**
|
||||
* An array of characters that encode 6 bits into a Base64-URL alphabet
|
||||
* character.
|
||||
*/
|
||||
const TO_BASE64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'.split('');
|
||||
/**
|
||||
* An array of characters that can appear in a Base64-URL encoded string but
|
||||
* should be ignored.
|
||||
*/
|
||||
const IGNORE_BASE64URL = ' \t\n\r='.split('');
|
||||
/**
|
||||
* An array of 128 numbers that map a Base64-URL character to 6 bits, or if -2
|
||||
* used to skip the character, or if -1 used to error out.
|
||||
*/
|
||||
const FROM_BASE64URL = (() => {
|
||||
const charMap = new Array(128);
|
||||
for (let i = 0; i < charMap.length; i += 1) {
|
||||
charMap[i] = -1;
|
||||
}
|
||||
for (let i = 0; i < IGNORE_BASE64URL.length; i += 1) {
|
||||
charMap[IGNORE_BASE64URL[i].charCodeAt(0)] = -2;
|
||||
}
|
||||
for (let i = 0; i < TO_BASE64URL.length; i += 1) {
|
||||
charMap[TO_BASE64URL[i].charCodeAt(0)] = i;
|
||||
}
|
||||
return charMap;
|
||||
})();
|
||||
/**
|
||||
* Converts a byte to a Base64-URL string.
|
||||
*
|
||||
* @param byte The byte to convert, or null to flush at the end of the byte sequence.
|
||||
* @param state The Base64 conversion state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`.
|
||||
* @param emit A function called with the next Base64 character when ready.
|
||||
*/
|
||||
function byteToBase64URL(byte, state, emit) {
|
||||
if (byte !== null) {
|
||||
state.queue = (state.queue << 8) | byte;
|
||||
state.queuedBits += 8;
|
||||
while (state.queuedBits >= 6) {
|
||||
const pos = (state.queue >> (state.queuedBits - 6)) & 63;
|
||||
emit(TO_BASE64URL[pos]);
|
||||
state.queuedBits -= 6;
|
||||
}
|
||||
}
|
||||
else if (state.queuedBits > 0) {
|
||||
state.queue = state.queue << (6 - state.queuedBits);
|
||||
state.queuedBits = 6;
|
||||
while (state.queuedBits >= 6) {
|
||||
const pos = (state.queue >> (state.queuedBits - 6)) & 63;
|
||||
emit(TO_BASE64URL[pos]);
|
||||
state.queuedBits -= 6;
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Converts a String char code (extracted using `string.charCodeAt(position)`) to a sequence of Base64-URL characters.
|
||||
*
|
||||
* @param charCode The char code of the JavaScript string.
|
||||
* @param state The Base64 state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`.
|
||||
* @param emit A function called with the next byte.
|
||||
*/
|
||||
function byteFromBase64URL(charCode, state, emit) {
|
||||
const bits = FROM_BASE64URL[charCode];
|
||||
if (bits > -1) {
|
||||
// valid Base64-URL character
|
||||
state.queue = (state.queue << 6) | bits;
|
||||
state.queuedBits += 6;
|
||||
while (state.queuedBits >= 8) {
|
||||
emit((state.queue >> (state.queuedBits - 8)) & 0xff);
|
||||
state.queuedBits -= 8;
|
||||
}
|
||||
}
|
||||
else if (bits === -2) {
|
||||
// ignore spaces, tabs, newlines, =
|
||||
return;
|
||||
}
|
||||
else {
|
||||
throw new Error(`Invalid Base64-URL character "${String.fromCharCode(charCode)}"`);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Converts a JavaScript string (which may include any valid character) into a
|
||||
* Base64-URL encoded string. The string is first encoded in UTF-8 which is
|
||||
* then encoded as Base64-URL.
|
||||
*
|
||||
* @param str The string to convert.
|
||||
*/
|
||||
function stringToBase64URL(str) {
|
||||
const base64 = [];
|
||||
const emitter = (char) => {
|
||||
base64.push(char);
|
||||
};
|
||||
const state = { queue: 0, queuedBits: 0 };
|
||||
stringToUTF8(str, (byte) => {
|
||||
byteToBase64URL(byte, state, emitter);
|
||||
});
|
||||
byteToBase64URL(null, state, emitter);
|
||||
return base64.join('');
|
||||
}
|
||||
/**
|
||||
* Converts a Base64-URL encoded string into a JavaScript string. It is assumed
|
||||
* that the underlying string has been encoded as UTF-8.
|
||||
*
|
||||
* @param str The Base64-URL encoded string.
|
||||
*/
|
||||
function stringFromBase64URL(str) {
|
||||
const conv = [];
|
||||
const utf8Emit = (codepoint) => {
|
||||
conv.push(String.fromCodePoint(codepoint));
|
||||
};
|
||||
const utf8State = {
|
||||
utf8seq: 0,
|
||||
codepoint: 0,
|
||||
};
|
||||
const b64State = { queue: 0, queuedBits: 0 };
|
||||
const byteEmit = (byte) => {
|
||||
stringFromUTF8(byte, utf8State, utf8Emit);
|
||||
};
|
||||
for (let i = 0; i < str.length; i += 1) {
|
||||
byteFromBase64URL(str.charCodeAt(i), b64State, byteEmit);
|
||||
}
|
||||
return conv.join('');
|
||||
}
|
||||
/**
|
||||
* Converts a Unicode codepoint to a multi-byte UTF-8 sequence.
|
||||
*
|
||||
* @param codepoint The Unicode codepoint.
|
||||
* @param emit Function which will be called for each UTF-8 byte that represents the codepoint.
|
||||
*/
|
||||
function codepointToUTF8(codepoint, emit) {
|
||||
if (codepoint <= 0x7f) {
|
||||
emit(codepoint);
|
||||
return;
|
||||
}
|
||||
else if (codepoint <= 0x7ff) {
|
||||
emit(0xc0 | (codepoint >> 6));
|
||||
emit(0x80 | (codepoint & 0x3f));
|
||||
return;
|
||||
}
|
||||
else if (codepoint <= 0xffff) {
|
||||
emit(0xe0 | (codepoint >> 12));
|
||||
emit(0x80 | ((codepoint >> 6) & 0x3f));
|
||||
emit(0x80 | (codepoint & 0x3f));
|
||||
return;
|
||||
}
|
||||
else if (codepoint <= 0x10ffff) {
|
||||
emit(0xf0 | (codepoint >> 18));
|
||||
emit(0x80 | ((codepoint >> 12) & 0x3f));
|
||||
emit(0x80 | ((codepoint >> 6) & 0x3f));
|
||||
emit(0x80 | (codepoint & 0x3f));
|
||||
return;
|
||||
}
|
||||
throw new Error(`Unrecognized Unicode codepoint: ${codepoint.toString(16)}`);
|
||||
}
|
||||
/**
|
||||
* Converts a JavaScript string to a sequence of UTF-8 bytes.
|
||||
*
|
||||
* @param str The string to convert to UTF-8.
|
||||
* @param emit Function which will be called for each UTF-8 byte of the string.
|
||||
*/
|
||||
function stringToUTF8(str, emit) {
|
||||
for (let i = 0; i < str.length; i += 1) {
|
||||
let codepoint = str.charCodeAt(i);
|
||||
if (codepoint > 0xd7ff && codepoint <= 0xdbff) {
|
||||
// most UTF-16 codepoints are Unicode codepoints, except values in this
|
||||
// range where the next UTF-16 codepoint needs to be combined with the
|
||||
// current one to get the Unicode codepoint
|
||||
const highSurrogate = ((codepoint - 0xd800) * 0x400) & 0xffff;
|
||||
const lowSurrogate = (str.charCodeAt(i + 1) - 0xdc00) & 0xffff;
|
||||
codepoint = (lowSurrogate | highSurrogate) + 0x10000;
|
||||
i += 1;
|
||||
}
|
||||
codepointToUTF8(codepoint, emit);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Converts a UTF-8 byte to a Unicode codepoint.
|
||||
*
|
||||
* @param byte The UTF-8 byte next in the sequence.
|
||||
* @param state The shared state between consecutive UTF-8 bytes in the
|
||||
* sequence, an object with the shape `{ utf8seq: 0, codepoint: 0 }`.
|
||||
* @param emit Function which will be called for each codepoint.
|
||||
*/
|
||||
function stringFromUTF8(byte, state, emit) {
|
||||
if (state.utf8seq === 0) {
|
||||
if (byte <= 0x7f) {
|
||||
emit(byte);
|
||||
return;
|
||||
}
|
||||
// count the number of 1 leading bits until you reach 0
|
||||
for (let leadingBit = 1; leadingBit < 6; leadingBit += 1) {
|
||||
if (((byte >> (7 - leadingBit)) & 1) === 0) {
|
||||
state.utf8seq = leadingBit;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (state.utf8seq === 2) {
|
||||
state.codepoint = byte & 31;
|
||||
}
|
||||
else if (state.utf8seq === 3) {
|
||||
state.codepoint = byte & 15;
|
||||
}
|
||||
else if (state.utf8seq === 4) {
|
||||
state.codepoint = byte & 7;
|
||||
}
|
||||
else {
|
||||
throw new Error('Invalid UTF-8 sequence');
|
||||
}
|
||||
state.utf8seq -= 1;
|
||||
}
|
||||
else if (state.utf8seq > 0) {
|
||||
if (byte <= 0x7f) {
|
||||
throw new Error('Invalid UTF-8 sequence');
|
||||
}
|
||||
state.codepoint = (state.codepoint << 6) | (byte & 63);
|
||||
state.utf8seq -= 1;
|
||||
if (state.utf8seq === 0) {
|
||||
emit(state.codepoint);
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Helper functions to convert different types of strings to Uint8Array
|
||||
*/
|
||||
function base64UrlToUint8Array(str) {
|
||||
const result = [];
|
||||
const state = { queue: 0, queuedBits: 0 };
|
||||
const onByte = (byte) => {
|
||||
result.push(byte);
|
||||
};
|
||||
for (let i = 0; i < str.length; i += 1) {
|
||||
byteFromBase64URL(str.charCodeAt(i), state, onByte);
|
||||
}
|
||||
return new Uint8Array(result);
|
||||
}
|
||||
function stringToUint8Array(str) {
|
||||
const result = [];
|
||||
stringToUTF8(str, (byte) => result.push(byte));
|
||||
return new Uint8Array(result);
|
||||
}
|
||||
function bytesToBase64URL(bytes) {
|
||||
const result = [];
|
||||
const state = { queue: 0, queuedBits: 0 };
|
||||
const onChar = (char) => {
|
||||
result.push(char);
|
||||
};
|
||||
bytes.forEach((byte) => byteToBase64URL(byte, state, onChar));
|
||||
// always call with `null` after processing all bytes
|
||||
byteToBase64URL(null, state, onChar);
|
||||
return result.join('');
|
||||
}
|
||||
//# sourceMappingURL=base64url.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"base64url.js","sourceRoot":"","sources":["../../../src/lib/base64url.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AA6CH,0CAwBC;AASD,8CAsBC;AASD,8CAgBC;AAQD,kDAuBC;AAQD,0CAsBC;AAQD,oCAgBC;AAUD,wCA0CC;AAMD,sDAaC;AAED,gDAIC;AAED,4CAcC;AA3SD;;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E,CAAC,CAAC,CAAA;QAC9B,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,SAAS,IAAI,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC,CAAA;QACvC,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAA;QACtC,IAAI,CAAC,IAAI,GAAG,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC,CAAA;QAC/B,OAAM;IACR,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,mCAAmC,SAAS,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE,CAAC,CAAA;AAC9E,CAAC;AAED;;;;;GAKG;AACH,SAAgB,YAAY,CAAC,GAAW,EAAE,IAA4B;IACpE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;QACvC,IAAI,SAAS,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAA;QAEjC,IAAI,SAAS,GAAG,MAAM,IAAI,SAALine truncated
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
/** Current session will be checked for refresh at this interval. */
|
||||
export declare const AUTO_REFRESH_TICK_DURATION_MS: number;
|
||||
/**
|
||||
* A token refresh will be attempted this many ticks before the current session expires. */
|
||||
export declare const AUTO_REFRESH_TICK_THRESHOLD = 3;
|
||||
export declare const EXPIRY_MARGIN_MS: number;
|
||||
export declare const GOTRUE_URL = "http://localhost:9999";
|
||||
export declare const STORAGE_KEY = "supabase.auth.token";
|
||||
export declare const AUDIENCE = "";
|
||||
export declare const DEFAULT_HEADERS: {
|
||||
'X-Client-Info': string;
|
||||
};
|
||||
export declare const NETWORK_FAILURE: {
|
||||
MAX_RETRIES: number;
|
||||
RETRY_INTERVAL: number;
|
||||
};
|
||||
export declare const API_VERSION_HEADER_NAME = "X-Supabase-Api-Version";
|
||||
export declare const API_VERSIONS: {
|
||||
'2024-01-01': {
|
||||
timestamp: number;
|
||||
name: string;
|
||||
};
|
||||
};
|
||||
export declare const BASE64URL_REGEX: RegExp;
|
||||
export declare const JWKS_TTL: number;
|
||||
//# sourceMappingURL=constants.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AAEA,oEAAoE;AACpE,eAAO,MAAM,6BAA6B,QAAY,CAAA;AAEtD;2FAC2F;AAC3F,eAAO,MAAM,2BAA2B,IAAI,CAAA;AAK5C,eAAO,MAAM,gBAAgB,QAA8D,CAAA;AAE3F,eAAO,MAAM,UAAU,0BAA0B,CAAA;AACjD,eAAO,MAAM,WAAW,wBAAwB,CAAA;AAChD,eAAO,MAAM,QAAQ,KAAK,CAAA;AAC1B,eAAO,MAAM,eAAe;;CAA8C,CAAA;AAC1E,eAAO,MAAM,eAAe;;;CAG3B,CAAA;AAED,eAAO,MAAM,uBAAuB,2BAA2B,CAAA;AAC/D,eAAO,MAAM,YAAY;;;;;CAKxB,CAAA;AAED,eAAO,MAAM,eAAe,QAAyD,CAAA;AAErF,eAAO,MAAM,QAAQ,QAAiB,CAAA"}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.JWKS_TTL = exports.BASE64URL_REGEX = exports.API_VERSIONS = exports.API_VERSION_HEADER_NAME = exports.NETWORK_FAILURE = exports.DEFAULT_HEADERS = exports.AUDIENCE = exports.STORAGE_KEY = exports.GOTRUE_URL = exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD = exports.AUTO_REFRESH_TICK_DURATION_MS = void 0;
|
||||
const version_1 = require("./version");
|
||||
/** Current session will be checked for refresh at this interval. */
|
||||
exports.AUTO_REFRESH_TICK_DURATION_MS = 30 * 1000;
|
||||
/**
|
||||
* A token refresh will be attempted this many ticks before the current session expires. */
|
||||
exports.AUTO_REFRESH_TICK_THRESHOLD = 3;
|
||||
/*
|
||||
* Earliest time before an access token expires that the session should be refreshed.
|
||||
*/
|
||||
exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD * exports.AUTO_REFRESH_TICK_DURATION_MS;
|
||||
exports.GOTRUE_URL = 'http://localhost:9999';
|
||||
exports.STORAGE_KEY = 'supabase.auth.token';
|
||||
exports.AUDIENCE = '';
|
||||
exports.DEFAULT_HEADERS = { 'X-Client-Info': `gotrue-js/${version_1.version}` };
|
||||
exports.NETWORK_FAILURE = {
|
||||
MAX_RETRIES: 10,
|
||||
RETRY_INTERVAL: 2, // in deciseconds
|
||||
};
|
||||
exports.API_VERSION_HEADER_NAME = 'X-Supabase-Api-Version';
|
||||
exports.API_VERSIONS = {
|
||||
'2024-01-01': {
|
||||
timestamp: Date.parse('2024-01-01T00:00:00.0Z'),
|
||||
name: '2024-01-01',
|
||||
},
|
||||
};
|
||||
exports.BASE64URL_REGEX = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;
|
||||
exports.JWKS_TTL = 10 * 60 * 1000; // 10 minutes
|
||||
//# sourceMappingURL=constants.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":";;;AAAA,uCAAmC;AAEnC,oEAAoE;AACvD,QAAA,6BAA6B,GAAG,EAAE,GAAG,IAAI,CAAA;AAEtD;2FAC2F;AAC9E,QAAA,2BAA2B,GAAG,CAAC,CAAA;AAE5C;;GAEG;AACU,QAAA,gBAAgB,GAAG,mCAA2B,GAAG,qCAA6B,CAAA;AAE9E,QAAA,UAAU,GAAG,uBAAuB,CAAA;AACpC,QAAA,WAAW,GAAG,qBAAqB,CAAA;AACnC,QAAA,QAAQ,GAAG,EAAE,CAAA;AACb,QAAA,eAAe,GAAG,EAAE,eAAe,EAAE,aAAa,iBAAO,EAAE,EAAE,CAAA;AAC7D,QAAA,eAAe,GAAG;IAC7B,WAAW,EAAE,EAAE;IACf,cAAc,EAAE,CAAC,EAAE,iBAAiB;CACrC,CAAA;AAEY,QAAA,uBAAuB,GAAG,wBAAwB,CAAA;AAClD,QAAA,YAAY,GAAG;IAC1B,YAAY,EAAE;QACZ,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,wBAAwB,CAAC;QAC/C,IAAI,EAAE,YAAY;KACnB;CACF,CAAA;AAEY,QAAA,eAAe,GAAG,sDAAsD,CAAA;AAExE,QAAA,QAAQ,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAA,CAAC,aAAa"}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* Known error codes. Note that the server may also return other error codes
|
||||
* not included in this list (if the SDK is older than the version
|
||||
* on the server).
|
||||
*/
|
||||
export type ErrorCode = 'unexpected_failure' | 'validation_failed' | 'bad_json' | 'email_exists' | 'phone_exists' | 'bad_jwt' | 'not_admin' | 'no_authorization' | 'user_not_found' | 'session_not_found' | 'session_expired' | 'refresh_token_not_found' | 'refresh_token_already_used' | 'flow_state_not_found' | 'flow_state_expired' | 'signup_disabled' | 'user_banned' | 'provider_email_needs_verification' | 'invite_not_found' | 'bad_oauth_state' | 'bad_oauth_callback' | 'oauth_provider_not_supported' | 'unexpected_audience' | 'single_identity_not_deletable' | 'email_conflict_identity_not_deletable' | 'identity_already_exists' | 'email_provider_disabled' | 'phone_provider_disabled' | 'too_many_enrolled_mfa_factors' | 'mfa_factor_name_conflict' | 'mfa_factor_not_found' | 'mfa_ip_address_mismatch' | 'mfa_challenge_expired' | 'mfa_verification_failed' | 'mfa_verification_rejected' | 'insufficient_aal' | 'captcha_failed' | 'saml_provider_disabled' | 'manual_linking_disabled' | 'sms_send_failed' | 'email_not_confirmed' | 'phone_not_confirmed' | 'reauth_nonce_missing' | 'saml_relay_state_not_found' | 'saml_relay_state_expired' | 'saml_idp_not_found' | 'saml_assertion_no_user_id' | 'saml_assertion_no_email' | 'user_already_exists' | 'sso_provider_not_found' | 'saml_metadata_fetch_failed' | 'saml_idp_already_exists' | 'sso_domain_already_exists' | 'saml_entity_id_mismatch' | 'conflict' | 'provider_disabled' | 'user_sso_managed' | 'reauthentication_needed' | 'same_password' | 'reauthentication_not_valid' | 'otp_expired' | 'otp_disabled' | 'identity_not_found' | 'weak_password' | 'over_request_rate_limit' | 'over_email_send_rate_limit' | 'over_sms_send_rate_limit' | 'bad_code_verifier' | 'anonymous_provider_disabled' | 'hook_timeout' | 'hook_timeout_after_retry' | 'hook_payload_over_size_limit' | 'hook_payload_invalid_content_type' | 'request_timeout' | 'mfa_phone_enroll_not_enabled' | 'mfa_phone_verify_not_enabled' | 'mfa_totp_enroll_not_enabled' | 'mfa_totp_verify_not_enabled' | 'mfa_webauthn_enroll_not_enabled' | 'mfa_webauthn_verify_not_enabled' | 'mfa_verified_factor_exists' | 'invalid_credentials' | 'email_address_not_authorized' | 'email_address_invalid';
|
||||
//# sourceMappingURL=error-codes.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"error-codes.d.ts","sourceRoot":"","sources":["../../../src/lib/error-codes.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,MAAM,SAAS,GACjB,oBAAoB,GACpB,mBAAmB,GACnB,UAAU,GACV,cAAc,GACd,cAAc,GACd,SAAS,GACT,WAAW,GACX,kBAAkB,GAClB,gBAAgB,GAChB,mBAAmB,GACnB,iBAAiB,GACjB,yBAAyB,GACzB,4BAA4B,GAC5B,sBAAsB,GACtB,oBAAoB,GACpB,iBAAiB,GACjB,aAAa,GACb,mCAAmC,GACnC,kBAAkB,GAClB,iBAAiB,GACjB,oBAAoB,GACpB,8BAA8B,GAC9B,qBAAqB,GACrB,+BAA+B,GAC/B,uCAAuC,GACvC,yBAAyB,GACzB,yBAAyB,GACzB,yBAAyB,GACzB,+BAA+B,GAC/B,0BAA0B,GAC1B,sBAAsB,GACtB,yBAAyB,GACzB,uBAAuB,GACvB,yBAAyB,GACzB,2BAA2B,GAC3B,kBAAkB,GAClB,gBAAgB,GAChB,wBAAwB,GACxB,yBAAyB,GACzB,iBAAiB,GACjB,qBAAqB,GACrB,qBAAqB,GACrB,sBAAsB,GACtB,4BAA4B,GAC5B,0BAA0B,GAC1B,oBAAoB,GACpB,2BAA2B,GAC3B,yBAAyB,GACzB,qBAAqB,GACrB,wBAAwB,GACxB,4BAA4B,GAC5B,yBAAyB,GACzB,2BAA2B,GAC3B,yBAAyB,GACzB,UAAU,GACV,mBAAmB,GACnB,kBAAkB,GAClB,yBAAyB,GACzB,eAAe,GACf,4BAA4B,GAC5B,aAAa,GACb,cAAc,GACd,oBAAoB,GACpB,eAAe,GACf,yBAAyB,GACzB,4BAA4B,GAC5B,0BAA0B,GAC1B,mBAAmB,GACnB,6BAA6B,GAC7B,cAAc,GACd,0BAA0B,GAC1B,8BAA8B,GAC9B,mCAAmC,GACnC,iBAAiB,GACjB,8BAA8B,GAC9B,8BAA8B,GAC9B,6BAA6B,GAC7B,6BAA6B,GAC7B,iCAAiC,GACjC,iCAAiC,GACjC,4BAA4B,GAC5B,qBAAqB,GACrB,8BAA8B,GAC9B,uBAAuB,CAAA"}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
//# sourceMappingURL=error-codes.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"error-codes.js","sourceRoot":"","sources":["../../../src/lib/error-codes.ts"],"names":[],"mappings":""}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
import { WeakPasswordReasons } from './types';
|
||||
import { ErrorCode } from './error-codes';
|
||||
export declare class AuthError extends Error {
|
||||
/**
|
||||
* Error code associated with the error. Most errors coming from
|
||||
* HTTP responses will have a code, though some errors that occur
|
||||
* before a response is received will not have one present. In that
|
||||
* case {@link #status} will also be undefined.
|
||||
*/
|
||||
code: ErrorCode | (string & {}) | undefined;
|
||||
/** HTTP status code that caused the error. */
|
||||
status: number | undefined;
|
||||
protected __isAuthError: boolean;
|
||||
constructor(message: string, status?: number, code?: string);
|
||||
}
|
||||
export declare function isAuthError(error: unknown): error is AuthError;
|
||||
export declare class AuthApiError extends AuthError {
|
||||
status: number;
|
||||
constructor(message: string, status: number, code: string | undefined);
|
||||
}
|
||||
export declare function isAuthApiError(error: unknown): error is AuthApiError;
|
||||
export declare class AuthUnknownError extends AuthError {
|
||||
originalError: unknown;
|
||||
constructor(message: string, originalError: unknown);
|
||||
}
|
||||
export declare class CustomAuthError extends AuthError {
|
||||
name: string;
|
||||
status: number;
|
||||
constructor(message: string, name: string, status: number, code: string | undefined);
|
||||
}
|
||||
export declare class AuthSessionMissingError extends CustomAuthError {
|
||||
constructor();
|
||||
}
|
||||
export declare function isAuthSessionMissingError(error: any): error is AuthSessionMissingError;
|
||||
export declare class AuthInvalidTokenResponseError extends CustomAuthError {
|
||||
constructor();
|
||||
}
|
||||
export declare class AuthInvalidCredentialsError extends CustomAuthError {
|
||||
constructor(message: string);
|
||||
}
|
||||
export declare class AuthImplicitGrantRedirectError extends CustomAuthError {
|
||||
details: {
|
||||
error: string;
|
||||
code: string;
|
||||
} | null;
|
||||
constructor(message: string, details?: {
|
||||
error: string;
|
||||
code: string;
|
||||
} | null);
|
||||
toJSON(): {
|
||||
name: string;
|
||||
message: string;
|
||||
status: number;
|
||||
details: {
|
||||
error: string;
|
||||
code: string;
|
||||
} | null;
|
||||
};
|
||||
}
|
||||
export declare function isAuthImplicitGrantRedirectError(error: any): error is AuthImplicitGrantRedirectError;
|
||||
export declare class AuthPKCEGrantCodeExchangeError extends CustomAuthError {
|
||||
details: {
|
||||
error: string;
|
||||
code: string;
|
||||
} | null;
|
||||
constructor(message: string, details?: {
|
||||
error: string;
|
||||
code: string;
|
||||
} | null);
|
||||
toJSON(): {
|
||||
name: string;
|
||||
message: string;
|
||||
status: number;
|
||||
details: {
|
||||
error: string;
|
||||
code: string;
|
||||
} | null;
|
||||
};
|
||||
}
|
||||
export declare class AuthRetryableFetchError extends CustomAuthError {
|
||||
constructor(message: string, status: number);
|
||||
}
|
||||
export declare function isAuthRetryableFetchError(error: unknown): error is AuthRetryableFetchError;
|
||||
/**
|
||||
* This error is thrown on certain methods when the password used is deemed
|
||||
* weak. Inspect the reasons to identify what password strength rules are
|
||||
* inadequate.
|
||||
*/
|
||||
export declare class AuthWeakPasswordError extends CustomAuthError {
|
||||
/**
|
||||
* Reasons why the password is deemed weak.
|
||||
*/
|
||||
reasons: WeakPasswordReasons[];
|
||||
constructor(message: string, status: number, reasons: WeakPasswordReasons[]);
|
||||
}
|
||||
export declare function isAuthWeakPasswordError(error: unknown): error is AuthWeakPasswordError;
|
||||
export declare class AuthInvalidJwtError extends CustomAuthError {
|
||||
constructor(message: string);
|
||||
}
|
||||
//# sourceMappingURL=errors.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/lib/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAA;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAA;AAEzC,qBAAa,SAAU,SAAQ,KAAK;IAClC;;;;;OAKG;IACH,IAAI,EAAE,SAAS,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,GAAG,SAAS,CAAA;IAE3C,8CAA8C;IAC9C,MAAM,EAAE,MAAM,GAAG,SAAS,CAAA;IAE1B,SAAS,CAAC,aAAa,UAAO;gBAElB,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM;CAM5D;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,SAAS,CAE9D;AAED,qBAAa,YAAa,SAAQ,SAAS;IACzC,MAAM,EAAE,MAAM,CAAA;gBAEF,OAAO,EAAE,MAAM,EAAE,MAAM,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O,EAAE,MAAM,EAAE,OAAO,GAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,IAAW;IAKnF,MAAM;;;;;mBAPY,MAAM;kBAAQ,MAAM;;;CAevC;AAED,qBAAa,uBAAwB,SAAQ,eAAe;gBAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;CAG5C;AAED,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,uBAAuB,CAE1F;AAED;;;;GAIG;AACH,qBAAa,qBAAsB,SAAQ,eAAe;IACxD;;OAEG;IACH,OAAO,EAAE,mBAAmB,EAAE,CAAA;gBAElB,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,mBAAmB,EAAE;CAK5E;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,qBAAqB,CAEtF;AAED,qBAAa,mBAAoB,SAAQ,eAAe;gBAC1C,OAAO,EAAE,MAAM;CAG5B"}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.AuthInvalidJwtError = exports.AuthWeakPasswordError = exports.AuthRetryableFetchError = exports.AuthPKCEGrantCodeExchangeError = exports.AuthImplicitGrantRedirectError = exports.AuthInvalidCredentialsError = exports.AuthInvalidTokenResponseError = exports.AuthSessionMissingError = exports.CustomAuthError = exports.AuthUnknownError = exports.AuthApiError = exports.AuthError = void 0;
|
||||
exports.isAuthError = isAuthError;
|
||||
exports.isAuthApiError = isAuthApiError;
|
||||
exports.isAuthSessionMissingError = isAuthSessionMissingError;
|
||||
exports.isAuthImplicitGrantRedirectError = isAuthImplicitGrantRedirectError;
|
||||
exports.isAuthRetryableFetchError = isAuthRetryableFetchError;
|
||||
exports.isAuthWeakPasswordError = isAuthWeakPasswordError;
|
||||
class AuthError extends Error {
|
||||
constructor(message, status, code) {
|
||||
super(message);
|
||||
this.__isAuthError = true;
|
||||
this.name = 'AuthError';
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
exports.AuthError = AuthError;
|
||||
function isAuthError(error) {
|
||||
return typeof error === 'object' && error !== null && '__isAuthError' in error;
|
||||
}
|
||||
class AuthApiError extends AuthError {
|
||||
constructor(message, status, code) {
|
||||
super(message, status, code);
|
||||
this.name = 'AuthApiError';
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
exports.AuthApiError = AuthApiError;
|
||||
function isAuthApiError(error) {
|
||||
return isAuthError(error) && error.name === 'AuthApiError';
|
||||
}
|
||||
class AuthUnknownError extends AuthError {
|
||||
constructor(message, originalError) {
|
||||
super(message);
|
||||
this.name = 'AuthUnknownError';
|
||||
this.originalError = originalError;
|
||||
}
|
||||
}
|
||||
exports.AuthUnknownError = AuthUnknownError;
|
||||
class CustomAuthError extends AuthError {
|
||||
constructor(message, name, status, code) {
|
||||
super(message, status, code);
|
||||
this.name = name;
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
exports.CustomAuthError = CustomAuthError;
|
||||
class AuthSessionMissingError extends CustomAuthError {
|
||||
constructor() {
|
||||
super('Auth session missing!', 'AuthSessionMissingError', 400, undefined);
|
||||
}
|
||||
}
|
||||
exports.AuthSessionMissingError = AuthSessionMissingError;
|
||||
function isAuthSessionMissingError(error) {
|
||||
return isAuthError(error) && error.name === 'AuthSessionMissingError';
|
||||
}
|
||||
class AuthInvalidTokenResponseError extends CustomAuthError {
|
||||
constructor() {
|
||||
super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500, undefined);
|
||||
}
|
||||
}
|
||||
exports.AuthInvalidTokenResponseError = AuthInvalidTokenResponseError;
|
||||
class AuthInvalidCredentialsError extends CustomAuthError {
|
||||
constructor(message) {
|
||||
super(message, 'AuthInvalidCredentialsError', 400, undefined);
|
||||
}
|
||||
}
|
||||
exports.AuthInvalidCredentialsError = AuthInvalidCredentialsError;
|
||||
class AuthImplicitGrantRedirectError extends CustomAuthError {
|
||||
constructor(message, details = null) {
|
||||
super(message, 'AuthImplicitGrantRedirectError', 500, undefined);
|
||||
this.details = null;
|
||||
this.details = details;
|
||||
}
|
||||
toJSON() {
|
||||
return {
|
||||
name: this.name,
|
||||
message: this.message,
|
||||
status: this.status,
|
||||
details: this.details,
|
||||
};
|
||||
}
|
||||
}
|
||||
exports.AuthImplicitGrantRedirectError = AuthImplicitGrantRedirectError;
|
||||
function isAuthImplicitGrantRedirectError(error) {
|
||||
return isAuthError(error) && error.name === 'AuthImplicitGrantRedirectError';
|
||||
}
|
||||
class AuthPKCEGrantCodeExchangeError extends CustomAuthError {
|
||||
constructor(message, details = null) {
|
||||
super(message, 'AuthPKCEGrantCodeExchangeError', 500, undefined);
|
||||
this.details = null;
|
||||
this.details = details;
|
||||
}
|
||||
toJSON() {
|
||||
return {
|
||||
name: this.name,
|
||||
message: this.message,
|
||||
status: this.status,
|
||||
details: this.details,
|
||||
};
|
||||
}
|
||||
}
|
||||
exports.AuthPKCEGrantCodeExchangeError = AuthPKCEGrantCodeExchangeError;
|
||||
class AuthRetryableFetchError extends CustomAuthError {
|
||||
constructor(message, status) {
|
||||
super(message, 'AuthRetryableFetchError', status, undefined);
|
||||
}
|
||||
}
|
||||
exports.AuthRetryableFetchError = AuthRetryableFetchError;
|
||||
function isAuthRetryableFetchError(error) {
|
||||
return isAuthError(error) && error.name === 'AuthRetryableFetchError';
|
||||
}
|
||||
/**
|
||||
* This error is thrown on certain methods when the password used is deemed
|
||||
* weak. Inspect the reasons to identify what password strength rules are
|
||||
* inadequate.
|
||||
*/
|
||||
class AuthWeakPasswordError extends CustomAuthError {
|
||||
constructor(message, status, reasons) {
|
||||
super(message, 'AuthWeakPasswordError', status, 'weak_password');
|
||||
this.reasons = reasons;
|
||||
}
|
||||
}
|
||||
exports.AuthWeakPasswordError = AuthWeakPasswordError;
|
||||
function isAuthWeakPasswordError(error) {
|
||||
return isAuthError(error) && error.name === 'AuthWeakPasswordError';
|
||||
}
|
||||
class AuthInvalidJwtError extends CustomAuthError {
|
||||
constructor(message) {
|
||||
super(message, 'AuthInvalidJwtError', 400, 'invalid_jwt');
|
||||
}
|
||||
}
|
||||
exports.AuthInvalidJwtError = AuthInvalidJwtError;
|
||||
//# sourceMappingURL=errors.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/lib/errors.ts"],"names":[],"mappings":";;;AAyBA,kCAEC;AAaD,wCAEC;AA6BD,8DAEC;AA+BD,4EAIC;AA0BD,8DAEC;AAoBD,0DAEC;AA3JD,MAAa,SAAU,SAAQ,KAAK;IAclC,YAAY,OAAe,EAAE,MAAe,EAAE,IAAa;QACzD,KAAK,CAAC,OAAO,CAAC,CAAA;QAHN,kBAAa,GAAG,IAAI,CAAA;QAI5B,IAAI,CAAC,IAAI,GAAG,WAAW,CAAA;QACvB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;IAClB,CAAC;CACF;AApBD,8BAoBC;AAED,SAAgB,WAAW,CAAC,KAAc;IACxC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,eAAe,IAAI,KAAK,CAAA;AAChF,CAAC;AAED,MAAa,YAAa,SAAQ,SAAS;IAGzC,YAAY,OAAe,EAAE,MAAc,EAAE,IAAwB;QACnE,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,CAAA;QAC5B,IAAI,CAAC,IAAI,GAAG,cAAc,CAAA;QAC1B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;IAClB,CAAC;CACF;AATD,oCASC;AAED,SAAgB,cAAc,CAAC,KAAc;IAC3C,OAAO,WAAW,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK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,OAA8B;QACzE,KAAK,CAAC,OAAO,EAAE,uBAAuB,EAAE,MAAM,EAAE,eAAe,CAAC,CAAA;QAEhE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;CACF;AAXD,sDAWC;AAED,SAAgB,uBAAuB,CAAC,KAAc;IACpD,OAAO,WAAW,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,uBAAuB,CAAA;AACrE,CAAC;AAED,MAAa,mBAAoB,SAAQ,eAAe;IACtD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,EAAE,qBAAqB,EAAE,GAAG,EAAE,aAAa,CAAC,CAAA;IAC3D,CAAC;CACF;AAJD,kDAIC"}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
import { AuthResponse, AuthResponsePassword, SSOResponse, GenerateLinkResponse, UserResponse } from './types';
|
||||
export type Fetch = typeof fetch;
|
||||
export interface FetchOptions {
|
||||
headers?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
noResolveJson?: boolean;
|
||||
}
|
||||
export interface FetchParameters {
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
export type RequestMethodType = 'GET' | 'POST' | 'PUT' | 'DELETE';
|
||||
export declare function handleError(error: unknown): Promise<void>;
|
||||
interface GotrueRequestOptions extends FetchOptions {
|
||||
jwt?: string;
|
||||
redirectTo?: string;
|
||||
body?: object;
|
||||
query?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
/**
|
||||
* Function that transforms api response from gotrue into a desirable / standardised format
|
||||
*/
|
||||
xform?: (data: any) => any;
|
||||
}
|
||||
export declare function _request(fetcher: Fetch, method: RequestMethodType, url: string, options?: GotrueRequestOptions): Promise<any>;
|
||||
export declare function _sessionResponse(data: any): AuthResponse;
|
||||
export declare function _sessionResponsePassword(data: any): AuthResponsePassword;
|
||||
export declare function _userResponse(data: any): UserResponse;
|
||||
export declare function _ssoResponse(data: any): SSOResponse;
|
||||
export declare function _generateLinkResponse(data: any): GenerateLinkResponse;
|
||||
export declare function _noResolveJsonResponse(data: any): Response;
|
||||
export {};
|
||||
//# sourceMappingURL=fetch.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,YAAY,EACZ,oBAAoB,EACpB,WAAW,EAEX,oBAAoB,EAEpB,YAAY,EACb,MAAM,SAAS,CAAA;AAShB,MAAM,MAAM,KAAK,GAAG,OAAO,KAAK,CAAA;AAEhC,MAAM,WAAW,YAAY;IAC3B,OAAO,CAAC,EAAE;QACR,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KACtB,CAAA;IACD,aAAa,CAAC,EAAE,OAAO,CAAA;CACxB;AAED,MAAM,WAAW,eAAe;IAC9B,MAAM,CAAC,EAAE,WAAW,CAAA;CACrB;AAED,MAAM,MAAM,iBAAiB,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,CAAA;AAOjE,wBAAsB,WAAW,CAAC,KAAK,EAAE,OAAO,iBA+D/C;AAmBD,UAAU,oBAAqB,SAAQ,YAAY;IACjD,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,KAAK,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAA;IACjC;;OAEG;IACH,KAAK,CAAC,EAAE,CAAC,IAAI,EAAE,GAAG,KAAK,GAAG,CAAA;CAC3B;AAED,wBAAsB,QAAQ,CAC5B,OAAO,EAAE,KAAK,EACd,MAAM,EAAE,iBAAiB,EACzB,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,oBAAoB,gBAgC/B;AAwCD,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,GAAG,GAAG,YAAY,CAYxD;AAED,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,GAAG,GAAG,oBAAoB,CAiBxE;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,GAAG,GAAG,YAAY,CAGrD;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE,GAAG,GAAG,WAAW,CAEnD;AAED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,GAAG,GAAG,oBAAoB,CAmBrE;AAED,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,GAAG,GAAG,QAAQ,CAE1D"}
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.handleError = handleError;
|
||||
exports._request = _request;
|
||||
exports._sessionResponse = _sessionResponse;
|
||||
exports._sessionResponsePassword = _sessionResponsePassword;
|
||||
exports._userResponse = _userResponse;
|
||||
exports._ssoResponse = _ssoResponse;
|
||||
exports._generateLinkResponse = _generateLinkResponse;
|
||||
exports._noResolveJsonResponse = _noResolveJsonResponse;
|
||||
const tslib_1 = require("tslib");
|
||||
const constants_1 = require("./constants");
|
||||
const helpers_1 = require("./helpers");
|
||||
const errors_1 = require("./errors");
|
||||
const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err);
|
||||
const NETWORK_ERROR_CODES = [502, 503, 504];
|
||||
async function handleError(error) {
|
||||
var _a;
|
||||
if (!(0, helpers_1.looksLikeFetchResponse)(error)) {
|
||||
throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), 0);
|
||||
}
|
||||
if (NETWORK_ERROR_CODES.includes(error.status)) {
|
||||
// status in 500...599 range - server had an error, request might be retryed.
|
||||
throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), error.status);
|
||||
}
|
||||
let data;
|
||||
try {
|
||||
data = await error.json();
|
||||
}
|
||||
catch (e) {
|
||||
throw new errors_1.AuthUnknownError(_getErrorMessage(e), e);
|
||||
}
|
||||
let errorCode = undefined;
|
||||
const responseAPIVersion = (0, helpers_1.parseResponseAPIVersion)(error);
|
||||
if (responseAPIVersion &&
|
||||
responseAPIVersion.getTime() >= constants_1.API_VERSIONS['2024-01-01'].timestamp &&
|
||||
typeof data === 'object' &&
|
||||
data &&
|
||||
typeof data.code === 'string') {
|
||||
errorCode = data.code;
|
||||
}
|
||||
else if (typeof data === 'object' && data && typeof data.error_code === 'string') {
|
||||
errorCode = data.error_code;
|
||||
}
|
||||
if (!errorCode) {
|
||||
// Legacy support for weak password errors, when there were no error codes
|
||||
if (typeof data === 'object' &&
|
||||
data &&
|
||||
typeof data.weak_password === 'object' &&
|
||||
data.weak_password &&
|
||||
Array.isArray(data.weak_password.reasons) &&
|
||||
data.weak_password.reasons.length &&
|
||||
data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) {
|
||||
throw new errors_1.AuthWeakPasswordError(_getErrorMessage(data), error.status, data.weak_password.reasons);
|
||||
}
|
||||
}
|
||||
else if (errorCode === 'weak_password') {
|
||||
throw new errors_1.AuthWeakPasswordError(_getErrorMessage(data), error.status, ((_a = data.weak_password) === null || _a === void 0 ? void 0 : _a.reasons) || []);
|
||||
}
|
||||
else if (errorCode === 'session_not_found') {
|
||||
// The `session_id` inside the JWT does not correspond to a row in the
|
||||
// `sessions` table. This usually means the user has signed out, has been
|
||||
// deleted, or their session has somehow been terminated.
|
||||
throw new errors_1.AuthSessionMissingError();
|
||||
}
|
||||
throw new errors_1.AuthApiError(_getErrorMessage(data), error.status || 500, errorCode);
|
||||
}
|
||||
const _getRequestParams = (method, options, parameters, body) => {
|
||||
const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} };
|
||||
if (method === 'GET') {
|
||||
return params;
|
||||
}
|
||||
params.headers = Object.assign({ 'Content-Type': 'application/json;charset=UTF-8' }, options === null || options === void 0 ? void 0 : options.headers);
|
||||
params.body = JSON.stringify(body);
|
||||
return Object.assign(Object.assign({}, params), parameters);
|
||||
};
|
||||
async function _request(fetcher, method, url, options) {
|
||||
var _a;
|
||||
const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers);
|
||||
if (!headers[constants_1.API_VERSION_HEADER_NAME]) {
|
||||
headers[constants_1.API_VERSION_HEADER_NAME] = constants_1.API_VERSIONS['2024-01-01'].name;
|
||||
}
|
||||
if (options === null || options === void 0 ? void 0 : options.jwt) {
|
||||
headers['Authorization'] = `Bearer ${options.jwt}`;
|
||||
}
|
||||
const qs = (_a = options === null || options === void 0 ? void 0 : options.query) !== null && _a !== void 0 ? _a : {};
|
||||
if (options === null || options === void 0 ? void 0 : options.redirectTo) {
|
||||
qs['redirect_to'] = options.redirectTo;
|
||||
}
|
||||
const queryString = Object.keys(qs).length ? '?' + new URLSearchParams(qs).toString() : '';
|
||||
const data = await _handleRequest(fetcher, method, url + queryString, {
|
||||
headers,
|
||||
noResolveJson: options === null || options === void 0 ? void 0 : options.noResolveJson,
|
||||
}, {}, options === null || options === void 0 ? void 0 : options.body);
|
||||
return (options === null || options === void 0 ? void 0 : options.xform) ? options === null || options === void 0 ? void 0 : options.xform(data) : { data: Object.assign({}, data), error: null };
|
||||
}
|
||||
async function _handleRequest(fetcher, method, url, options, parameters, body) {
|
||||
const requestParams = _getRequestParams(method, options, parameters, body);
|
||||
let result;
|
||||
try {
|
||||
result = await fetcher(url, Object.assign({}, requestParams));
|
||||
}
|
||||
catch (e) {
|
||||
console.error(e);
|
||||
// fetch failed, likely due to a network or CORS error
|
||||
throw new errors_1.AuthRetryableFetchError(_getErrorMessage(e), 0);
|
||||
}
|
||||
if (!result.ok) {
|
||||
await handleError(result);
|
||||
}
|
||||
if (options === null || options === void 0 ? void 0 : options.noResolveJson) {
|
||||
return result;
|
||||
}
|
||||
try {
|
||||
return await result.json();
|
||||
}
|
||||
catch (e) {
|
||||
await handleError(e);
|
||||
}
|
||||
}
|
||||
function _sessionResponse(data) {
|
||||
var _a;
|
||||
let session = null;
|
||||
if (hasSession(data)) {
|
||||
session = Object.assign({}, data);
|
||||
if (!data.expires_at) {
|
||||
session.expires_at = (0, helpers_1.expiresAt)(data.expires_in);
|
||||
}
|
||||
}
|
||||
const user = (_a = data.user) !== null && _a !== void 0 ? _a : data;
|
||||
return { data: { session, user }, error: null };
|
||||
}
|
||||
function _sessionResponsePassword(data) {
|
||||
const response = _sessionResponse(data);
|
||||
if (!response.error &&
|
||||
data.weak_password &&
|
||||
typeof data.weak_password === 'object' &&
|
||||
Array.isArray(data.weak_password.reasons) &&
|
||||
data.weak_password.reasons.length &&
|
||||
data.weak_password.message &&
|
||||
typeof data.weak_password.message === 'string' &&
|
||||
data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) {
|
||||
response.data.weak_password = data.weak_password;
|
||||
}
|
||||
return response;
|
||||
}
|
||||
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 = tslib_1.__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;
|
||||
}
|
||||
/**
|
||||
* hasSession checks if the response object contains a valid session
|
||||
* @param data A response object
|
||||
* @returns true if a session is in the response
|
||||
*/
|
||||
function hasSession(data) {
|
||||
return data.access_token && data.refresh_token && data.expires_in;
|
||||
}
|
||||
//# sourceMappingURL=fetch.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":";;AAuCA,kCA+DC;AA8BD,4BAoCC;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AAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;IAC3D,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;QACf,MAAM,WAAW,CAAC,MAAM,CAAC,CAAA;IAC3B,CAAC;IAED,IAAI,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,aAAa,EAAE,CAAC;QAC3B,OAAO,MAAM,CAAA;IACf,CAAC;IAED,IAAI,CAAC;QACH,OAAO,MAAM,MAAM,CAAC,IAAI,EAAE,CAAA;IAC5B,CAAC;IAAC,OAAO,CAAM,EAAE,CAAC;QAChB,MAAM,WAAW,CAAC,CAAC,CAAC,CAAA;IACtB,CAAC;AACH,CAAC;AAED,SAAgB,gBAAgB,CAAC,IAAS;;IACxC,IAAI,OAAO,GAAG,IAAI,CAAA;IAClB,IAAI,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QACrB,OAAO,qBAAQ,IAAI,CAAE,CAAA;QAErB,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC;YACrB,OAAO,CAAC,UAAU,GAAG,IAAA,mBAAS,EAAC,IAAI,CAAC,UAAU,CAAC,CAAA;QACjD,CAAC;IACH,CAAC;IAED,MAAM,IAAI,GAAS,MAAA,IAAI,CAAC,IAAI,mCAALine truncated
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
import { JwtHeader, JwtPayload, SupportedStorage, User } from './types';
|
||||
import { Uint8Array_ } from './webauthn.dom';
|
||||
export declare function expiresAt(expiresIn: number): number;
|
||||
export declare function uuid(): string;
|
||||
export declare const isBrowser: () => boolean;
|
||||
/**
|
||||
* Checks whether localStorage is supported on this browser.
|
||||
*/
|
||||
export declare const supportsLocalStorage: () => boolean;
|
||||
/**
|
||||
* Extracts parameters encoded in the URL both in the query and fragment.
|
||||
*/
|
||||
export declare function parseParametersFromURL(href: string): {
|
||||
[parameter: string]: string;
|
||||
};
|
||||
type Fetch = typeof fetch;
|
||||
export declare const resolveFetch: (customFetch?: Fetch) => Fetch;
|
||||
export declare const looksLikeFetchResponse: (maybeResponse: unknown) => maybeResponse is Response;
|
||||
export declare const setItemAsync: (storage: SupportedStorage, key: string, data: any) => Promise<void>;
|
||||
export declare const getItemAsync: (storage: SupportedStorage, key: string) => Promise<unknown>;
|
||||
export declare const removeItemAsync: (storage: SupportedStorage, key: string) => Promise<void>;
|
||||
/**
|
||||
* A deferred represents some asynchronous work that is not yet finished, which
|
||||
* may or may not culminate in a value.
|
||||
* Taken from: https://github.com/mike-north/types/blob/master/src/async.ts
|
||||
*/
|
||||
export declare class Deferred<T = any> {
|
||||
static promiseConstructor: PromiseConstructor;
|
||||
readonly promise: PromiseLike<T>;
|
||||
readonly resolve: (value?: T | PromiseLike<T>) => void;
|
||||
readonly reject: (reason?: any) => any;
|
||||
constructor();
|
||||
}
|
||||
export declare function decodeJWT(token: string): {
|
||||
header: JwtHeader;
|
||||
payload: JwtPayload;
|
||||
signature: Uint8Array_;
|
||||
raw: {
|
||||
header: string;
|
||||
payload: string;
|
||||
};
|
||||
};
|
||||
/**
|
||||
* Creates a promise that resolves to null after some time.
|
||||
*/
|
||||
export declare function sleep(time: number): Promise<null>;
|
||||
/**
|
||||
* Converts the provided async function into a retryable function. Each result
|
||||
* or thrown error is sent to the isRetryable function which should return true
|
||||
* if the function should run again.
|
||||
*/
|
||||
export declare function retryable<T>(fn: (attempt: number) => Promise<T>, isRetryable: (attempt: number, error: any | null, result?: T) => boolean): Promise<T>;
|
||||
export declare function generatePKCEVerifier(): string;
|
||||
export declare function generatePKCEChallenge(verifier: string): Promise<string>;
|
||||
export declare function getCodeChallengeAndMethod(storage: SupportedStorage, storageKey: string, isPasswordRecovery?: boolean): Promise<string[]>;
|
||||
export declare function parseResponseAPIVersion(response: Response): Date | null;
|
||||
export declare function validateExp(exp: number): void;
|
||||
export declare function getAlgorithm(alg: 'HS256' | 'RS256' | 'ES256'): RsaHashedImportParams | EcKeyImportParams;
|
||||
export declare function validateUUID(str: string): void;
|
||||
export declare function userNotAvailableProxy(): User;
|
||||
/**
|
||||
* Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)).
|
||||
* Note: Only works for JSON-safe data.
|
||||
*/
|
||||
export declare function deepClone<T>(obj: T): T;
|
||||
export {};
|
||||
//# sourceMappingURL=helpers.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,gBAAgB,EAAE,IAAI,EAAE,MAAM,SAAS,CAAA;AACvE,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAE5C,wBAAgB,SAAS,CAAC,SAAS,EAAE,MAAM,UAG1C;AAED,wBAAgB,IAAI,WAMnB;AAED,eAAO,MAAM,SAAS,eAAyE,CAAA;AAO/F;;GAEG;AACH,eAAO,MAAM,oBAAoB,eAmChC,CAAA;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM;;EAsBlD;AAED,KAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,eAAO,MAAM,YAAY,GAAI,cAAc,KAAK,KAAG,KAWlD,CAAA;AAED,eAAO,MAAM,sBAAsB,GAAI,eAAe,OAAO,KAAG,aAAa,IAAI,QAShF,CAAA;AAGD,eAAO,MAAM,YAAY,GACvB,SAAS,gBAAgB,EACzB,KAAK,MAAM,EACX,MAAM,GAAG,KACR,OAAO,CAAC,IAAI,CAEd,CAAA;AAED,eAAO,MAAM,YAAY,GAAU,SAAS,gBAAgB,EAAE,KAAK,MAAM,KAAG,OAAO,CAAC,OAAO,CAY1F,CAAA;AAED,eAAO,MAAM,eAAe,GAAU,SAAS,gBAAgB,EAAE,KAAK,MAAM,KAAG,OAAO,CAAC,IAAI,CAE1F,CAAA;AAED;;;;GAIG;AACH,qBAAa,QAAQ,CAAC,CAAC,GAAG,GAAG;IAC3B,OAAc,kBA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GAAG,OAAO,GAC/B,qBAAqB,GAAG,iBAAiB,CAgB3C;AAID,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,QAIvC;AAED,wBAAgB,qBAAqB,IAAI,IAAI,CAoC5C;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAEtC"}
|
||||
+388
@@ -0,0 +1,388 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || (function () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Deferred = exports.removeItemAsync = exports.getItemAsync = exports.setItemAsync = exports.looksLikeFetchResponse = exports.resolveFetch = exports.supportsLocalStorage = exports.isBrowser = void 0;
|
||||
exports.expiresAt = expiresAt;
|
||||
exports.uuid = uuid;
|
||||
exports.parseParametersFromURL = parseParametersFromURL;
|
||||
exports.decodeJWT = decodeJWT;
|
||||
exports.sleep = sleep;
|
||||
exports.retryable = retryable;
|
||||
exports.generatePKCEVerifier = generatePKCEVerifier;
|
||||
exports.generatePKCEChallenge = generatePKCEChallenge;
|
||||
exports.getCodeChallengeAndMethod = getCodeChallengeAndMethod;
|
||||
exports.parseResponseAPIVersion = parseResponseAPIVersion;
|
||||
exports.validateExp = validateExp;
|
||||
exports.getAlgorithm = getAlgorithm;
|
||||
exports.validateUUID = validateUUID;
|
||||
exports.userNotAvailableProxy = userNotAvailableProxy;
|
||||
exports.deepClone = deepClone;
|
||||
const constants_1 = require("./constants");
|
||||
const errors_1 = require("./errors");
|
||||
const base64url_1 = require("./base64url");
|
||||
function expiresAt(expiresIn) {
|
||||
const timeNow = Math.round(Date.now() / 1000);
|
||||
return timeNow + expiresIn;
|
||||
}
|
||||
function uuid() {
|
||||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
|
||||
const r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8;
|
||||
return v.toString(16);
|
||||
});
|
||||
}
|
||||
const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined';
|
||||
exports.isBrowser = isBrowser;
|
||||
const localStorageWriteTests = {
|
||||
tested: false,
|
||||
writable: false,
|
||||
};
|
||||
/**
|
||||
* Checks whether localStorage is supported on this browser.
|
||||
*/
|
||||
const supportsLocalStorage = () => {
|
||||
if (!(0, exports.isBrowser)()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
if (typeof globalThis.localStorage !== 'object') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
// DOM exception when accessing `localStorage`
|
||||
return false;
|
||||
}
|
||||
if (localStorageWriteTests.tested) {
|
||||
return localStorageWriteTests.writable;
|
||||
}
|
||||
const randomKey = `lswt-${Math.random()}${Math.random()}`;
|
||||
try {
|
||||
globalThis.localStorage.setItem(randomKey, randomKey);
|
||||
globalThis.localStorage.removeItem(randomKey);
|
||||
localStorageWriteTests.tested = true;
|
||||
localStorageWriteTests.writable = true;
|
||||
}
|
||||
catch (e) {
|
||||
// localStorage can't be written to
|
||||
// https://www.chromium.org/for-testers/bug-reporting-guidelines/uncaught-securityerror-failed-to-read-the-localstorage-property-from-window-access-is-denied-for-this-document
|
||||
localStorageWriteTests.tested = true;
|
||||
localStorageWriteTests.writable = false;
|
||||
}
|
||||
return localStorageWriteTests.writable;
|
||||
};
|
||||
exports.supportsLocalStorage = supportsLocalStorage;
|
||||
/**
|
||||
* Extracts parameters encoded in the URL both in the query and fragment.
|
||||
*/
|
||||
function parseParametersFromURL(href) {
|
||||
const result = {};
|
||||
const url = new URL(href);
|
||||
if (url.hash && url.hash[0] === '#') {
|
||||
try {
|
||||
const hashSearchParams = new URLSearchParams(url.hash.substring(1));
|
||||
hashSearchParams.forEach((value, key) => {
|
||||
result[key] = value;
|
||||
});
|
||||
}
|
||||
catch (e) {
|
||||
// hash is not a query string
|
||||
}
|
||||
}
|
||||
// search parameters take precedence over hash parameters
|
||||
url.searchParams.forEach((value, key) => {
|
||||
result[key] = value;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
const resolveFetch = (customFetch) => {
|
||||
let _fetch;
|
||||
if (customFetch) {
|
||||
_fetch = customFetch;
|
||||
}
|
||||
else if (typeof fetch === 'undefined') {
|
||||
_fetch = (...args) => Promise.resolve(`${'@supabase/node-fetch'}`).then(s => __importStar(require(s))).then(({ default: fetch }) => fetch(...args));
|
||||
}
|
||||
else {
|
||||
_fetch = fetch;
|
||||
}
|
||||
return (...args) => _fetch(...args);
|
||||
};
|
||||
exports.resolveFetch = resolveFetch;
|
||||
const looksLikeFetchResponse = (maybeResponse) => {
|
||||
return (typeof maybeResponse === 'object' &&
|
||||
maybeResponse !== null &&
|
||||
'status' in maybeResponse &&
|
||||
'ok' in maybeResponse &&
|
||||
'json' in maybeResponse &&
|
||||
typeof maybeResponse.json === 'function');
|
||||
};
|
||||
exports.looksLikeFetchResponse = looksLikeFetchResponse;
|
||||
// Storage helpers
|
||||
const setItemAsync = async (storage, key, data) => {
|
||||
await storage.setItem(key, JSON.stringify(data));
|
||||
};
|
||||
exports.setItemAsync = setItemAsync;
|
||||
const getItemAsync = async (storage, key) => {
|
||||
const value = await storage.getItem(key);
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
}
|
||||
catch (_a) {
|
||||
return value;
|
||||
}
|
||||
};
|
||||
exports.getItemAsync = getItemAsync;
|
||||
const removeItemAsync = async (storage, key) => {
|
||||
await storage.removeItem(key);
|
||||
};
|
||||
exports.removeItemAsync = removeItemAsync;
|
||||
/**
|
||||
* A deferred represents some asynchronous work that is not yet finished, which
|
||||
* may or may not culminate in a value.
|
||||
* Taken from: https://github.com/mike-north/types/blob/master/src/async.ts
|
||||
*/
|
||||
class Deferred {
|
||||
constructor() {
|
||||
// eslint-disable-next-line @typescript-eslint/no-extra-semi
|
||||
;
|
||||
this.promise = new Deferred.promiseConstructor((res, rej) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-extra-semi
|
||||
;
|
||||
this.resolve = res;
|
||||
this.reject = rej;
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.Deferred = Deferred;
|
||||
Deferred.promiseConstructor = Promise;
|
||||
function decodeJWT(token) {
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 3) {
|
||||
throw new errors_1.AuthInvalidJwtError('Invalid JWT structure');
|
||||
}
|
||||
// Regex checks for base64url format
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
if (!constants_1.BASE64URL_REGEX.test(parts[i])) {
|
||||
throw new errors_1.AuthInvalidJwtError('JWT not in base64url format');
|
||||
}
|
||||
}
|
||||
const data = {
|
||||
// using base64url lib
|
||||
header: JSON.parse((0, base64url_1.stringFromBase64URL)(parts[0])),
|
||||
payload: JSON.parse((0, base64url_1.stringFromBase64URL)(parts[1])),
|
||||
signature: (0, base64url_1.base64UrlToUint8Array)(parts[2]),
|
||||
raw: {
|
||||
header: parts[0],
|
||||
payload: parts[1],
|
||||
},
|
||||
};
|
||||
return data;
|
||||
}
|
||||
/**
|
||||
* Creates a promise that resolves to null after some time.
|
||||
*/
|
||||
async function sleep(time) {
|
||||
return await new Promise((accept) => {
|
||||
setTimeout(() => accept(null), time);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Converts the provided async function into a retryable function. Each result
|
||||
* or thrown error is sent to the isRetryable function which should return true
|
||||
* if the function should run again.
|
||||
*/
|
||||
function retryable(fn, isRetryable) {
|
||||
const promise = new Promise((accept, reject) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-extra-semi
|
||||
;
|
||||
(async () => {
|
||||
for (let attempt = 0; attempt < Infinity; attempt++) {
|
||||
try {
|
||||
const result = await fn(attempt);
|
||||
if (!isRetryable(attempt, null, result)) {
|
||||
accept(result);
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
if (!isRetryable(attempt, e)) {
|
||||
reject(e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
})();
|
||||
});
|
||||
return promise;
|
||||
}
|
||||
function dec2hex(dec) {
|
||||
return ('0' + dec.toString(16)).substr(-2);
|
||||
}
|
||||
// Functions below taken from: https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs
|
||||
function generatePKCEVerifier() {
|
||||
const verifierLength = 56;
|
||||
const array = new Uint32Array(verifierLength);
|
||||
if (typeof crypto === 'undefined') {
|
||||
const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
|
||||
const charSetLen = charSet.length;
|
||||
let verifier = '';
|
||||
for (let i = 0; i < verifierLength; i++) {
|
||||
verifier += charSet.charAt(Math.floor(Math.random() * charSetLen));
|
||||
}
|
||||
return verifier;
|
||||
}
|
||||
crypto.getRandomValues(array);
|
||||
return Array.from(array, dec2hex).join('');
|
||||
}
|
||||
async function sha256(randomString) {
|
||||
const encoder = new TextEncoder();
|
||||
const encodedData = encoder.encode(randomString);
|
||||
const hash = await crypto.subtle.digest('SHA-256', encodedData);
|
||||
const bytes = new Uint8Array(hash);
|
||||
return Array.from(bytes)
|
||||
.map((c) => String.fromCharCode(c))
|
||||
.join('');
|
||||
}
|
||||
async function generatePKCEChallenge(verifier) {
|
||||
const hasCryptoSupport = typeof crypto !== 'undefined' &&
|
||||
typeof crypto.subtle !== 'undefined' &&
|
||||
typeof TextEncoder !== 'undefined';
|
||||
if (!hasCryptoSupport) {
|
||||
console.warn('WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.');
|
||||
return verifier;
|
||||
}
|
||||
const hashed = await sha256(verifier);
|
||||
return btoa(hashed).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
}
|
||||
async function getCodeChallengeAndMethod(storage, storageKey, isPasswordRecovery = false) {
|
||||
const codeVerifier = generatePKCEVerifier();
|
||||
let storedCodeVerifier = codeVerifier;
|
||||
if (isPasswordRecovery) {
|
||||
storedCodeVerifier += '/PASSWORD_RECOVERY';
|
||||
}
|
||||
await (0, exports.setItemAsync)(storage, `${storageKey}-code-verifier`, storedCodeVerifier);
|
||||
const codeChallenge = await generatePKCEChallenge(codeVerifier);
|
||||
const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256';
|
||||
return [codeChallenge, codeChallengeMethod];
|
||||
}
|
||||
/** Parses the API version which is 2YYY-MM-DD. */
|
||||
const API_VERSION_REGEX = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;
|
||||
function parseResponseAPIVersion(response) {
|
||||
const apiVersion = response.headers.get(constants_1.API_VERSION_HEADER_NAME);
|
||||
if (!apiVersion) {
|
||||
return null;
|
||||
}
|
||||
if (!apiVersion.match(API_VERSION_REGEX)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const date = new Date(`${apiVersion}T00:00:00.0Z`);
|
||||
return date;
|
||||
}
|
||||
catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
function validateExp(exp) {
|
||||
if (!exp) {
|
||||
throw new Error('Missing exp claim');
|
||||
}
|
||||
const timeNow = Math.floor(Date.now() / 1000);
|
||||
if (exp <= timeNow) {
|
||||
throw new Error('JWT has expired');
|
||||
}
|
||||
}
|
||||
function getAlgorithm(alg) {
|
||||
switch (alg) {
|
||||
case 'RS256':
|
||||
return {
|
||||
name: 'RSASSA-PKCS1-v1_5',
|
||||
hash: { name: 'SHA-256' },
|
||||
};
|
||||
case 'ES256':
|
||||
return {
|
||||
name: 'ECDSA',
|
||||
namedCurve: 'P-256',
|
||||
hash: { name: 'SHA-256' },
|
||||
};
|
||||
default:
|
||||
throw new Error('Invalid alg claim');
|
||||
}
|
||||
}
|
||||
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
||||
function validateUUID(str) {
|
||||
if (!UUID_REGEX.test(str)) {
|
||||
throw new Error('@supabase/auth-js: Expected parameter to be UUID but is not');
|
||||
}
|
||||
}
|
||||
function userNotAvailableProxy() {
|
||||
const proxyTarget = {};
|
||||
return new Proxy(proxyTarget, {
|
||||
get: (target, prop) => {
|
||||
if (prop === '__isUserNotAvailableProxy') {
|
||||
return true;
|
||||
}
|
||||
// Preventative check for common problematic symbols during cloning/inspection
|
||||
// These symbols might be accessed by structuredClone or other internal mechanisms.
|
||||
if (typeof prop === 'symbol') {
|
||||
const sProp = prop.toString();
|
||||
if (sProp === 'Symbol(Symbol.toPrimitive)' ||
|
||||
sProp === 'Symbol(Symbol.toStringTag)' ||
|
||||
sProp === 'Symbol(util.inspect.custom)') {
|
||||
// Node.js util.inspect
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${prop}" property of the session object is not supported. Please use getUser() instead.`);
|
||||
},
|
||||
set: (_target, prop) => {
|
||||
throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`);
|
||||
},
|
||||
deleteProperty: (_target, prop) => {
|
||||
throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`);
|
||||
},
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)).
|
||||
* Note: Only works for JSON-safe data.
|
||||
*/
|
||||
function deepClone(obj) {
|
||||
return JSON.parse(JSON.stringify(obj));
|
||||
}
|
||||
//# sourceMappingURL=helpers.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,8BAGC;AAED,oBAMC;AAoDD,wDAsBC;AAgFD,8BAgCC;AAKD,sBAIC;AAOD,8BA0BC;AAOD,oDAcC;AAaD,sDAcC;AAED,8DAcC;AAKD,0DAiBC;AAED,kCAQC;AAED,oCAkBC;AAID,oCAIC;AAED,sDAoCC;AAMD,8BAEC;AA/ZD,2CAAsE;AACtE,qCAA8C;AAC9C,2CAAwE;AAIxE,SAAgB,SAAS,CAAC,SAAiB;IACzC,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAA;IAC7C,OAAO,OAAO,GAAG,SAAS,CAAA;AAC5B,CAAC;AAED,SAAgB,IAAI;IAClB,OAAO,sC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sBAAsB;QACtB,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,IAAA,+BAAmB,EAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;QACjD,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,IAAA,+BAAmB,EAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;QAClD,SAAS,EAAE,IAAA,iCAAqB,EAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QAC1C,GAAG,EAAE;YACH,MAAM,EAAE,KAAK,CAAC,CAALine truncated
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import { SupportedStorage } from './types';
|
||||
/**
|
||||
* Returns a localStorage-like object that stores the key-value pairs in
|
||||
* memory.
|
||||
*/
|
||||
export declare function memoryLocalStorageAdapter(store?: {
|
||||
[key: string]: string;
|
||||
}): SupportedStorage;
|
||||
//# sourceMappingURL=local-storage.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"local-storage.d.ts","sourceRoot":"","sources":["../../../src/lib/local-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAE1C;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,GAAE;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;CAAO,GAAG,gBAAgB,CAcjG"}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.memoryLocalStorageAdapter = memoryLocalStorageAdapter;
|
||||
/**
|
||||
* Returns a localStorage-like object that stores the key-value pairs in
|
||||
* memory.
|
||||
*/
|
||||
function memoryLocalStorageAdapter(store = {}) {
|
||||
return {
|
||||
getItem: (key) => {
|
||||
return store[key] || null;
|
||||
},
|
||||
setItem: (key, value) => {
|
||||
store[key] = value;
|
||||
},
|
||||
removeItem: (key) => {
|
||||
delete store[key];
|
||||
},
|
||||
};
|
||||
}
|
||||
//# sourceMappingURL=local-storage.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"local-storage.js","sourceRoot":"","sources":["../../../src/lib/local-storage.ts"],"names":[],"mappings":";;AAMA,8DAcC;AAlBD;;;GAGG;AACH,SAAgB,yBAAyB,CAAC,QAAmC,EAAE;IAC7E,OAAO;QACL,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE;YACf,OAAO,KAAK,CAAC,GAAG,CAAC,IAAI,IAAI,CAAA;QAC3B,CAAC;QAED,OAAO,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE;YACtB,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAA;QACpB,CAAC;QAED,UAAU,EAAE,CAAC,GAAG,EAAE,EAAE;YAClB,OAAO,KAAK,CAAC,GAAG,CAAC,CAAA;QACnB,CAAC;KACF,CAAA;AACH,CAAC"}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* @experimental
|
||||
*/
|
||||
export declare const internals: {
|
||||
/**
|
||||
* @experimental
|
||||
*/
|
||||
debug: boolean;
|
||||
};
|
||||
/**
|
||||
* An error thrown when a lock cannot be acquired after some amount of time.
|
||||
*
|
||||
* Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`.
|
||||
*/
|
||||
export declare abstract class LockAcquireTimeoutError extends Error {
|
||||
readonly isAcquireTimeout = true;
|
||||
constructor(message: string);
|
||||
}
|
||||
export declare class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError {
|
||||
}
|
||||
export declare class ProcessLockAcquireTimeoutError extends LockAcquireTimeoutError {
|
||||
}
|
||||
/**
|
||||
* Implements a global exclusive lock using the Navigator LockManager API. It
|
||||
* is available on all browsers released after 2022-03-15 with Safari being the
|
||||
* last one to release support. If the API is not available, this function will
|
||||
* throw. Make sure you check availablility before configuring {@link
|
||||
* GoTrueClient}.
|
||||
*
|
||||
* You can turn on debugging by setting the `supabase.gotrue-js.locks.debug`
|
||||
* local storage item to `true`.
|
||||
*
|
||||
* Internals:
|
||||
*
|
||||
* Since the LockManager API does not preserve stack traces for the async
|
||||
* function passed in the `request` method, a trick is used where acquiring the
|
||||
* lock releases a previously started promise to run the operation in the `fn`
|
||||
* function. The lock waits for that promise to finish (with or without error),
|
||||
* while the function will finally wait for the result anyway.
|
||||
*
|
||||
* @param name Name of the lock to be acquired.
|
||||
* @param acquireTimeout If negative, no timeout. If 0 an error is thrown if
|
||||
* the lock can't be acquired without waiting. If positive, the lock acquire
|
||||
* will time out after so many milliseconds. An error is
|
||||
* a timeout if it has `isAcquireTimeout` set to true.
|
||||
* @param fn The operation to run once the lock is acquired.
|
||||
*/
|
||||
export declare function navigatorLock<R>(name: string, acquireTimeout: number, fn: () => Promise<R>): Promise<R>;
|
||||
/**
|
||||
* Implements a global exclusive lock that works only in the current process.
|
||||
* Useful for environments like React Native or other non-browser
|
||||
* single-process (i.e. no concept of "tabs") environments.
|
||||
*
|
||||
* Use {@link #navigatorLock} in browser environments.
|
||||
*
|
||||
* @param name Name of the lock to be acquired.
|
||||
* @param acquireTimeout If negative, no timeout. If 0 an error is thrown if
|
||||
* the lock can't be acquired without waiting. If positive, the lock acquire
|
||||
* will time out after so many milliseconds. An error is
|
||||
* a timeout if it has `isAcquireTimeout` set to true.
|
||||
* @param fn The operation to run once the lock is acquired.
|
||||
*/
|
||||
export declare function processLock<R>(name: string, acquireTimeout: number, fn: () => Promise<R>): Promise<R>;
|
||||
//# sourceMappingURL=locks.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"locks.d.ts","sourceRoot":"","sources":["../../../src/lib/locks.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,eAAO,MAAM,SAAS;IACpB;;OAEG;;CAOJ,CAAA;AAED;;;;GAIG;AACH,8BAAsB,uBAAwB,SAAQ,KAAK;IACzD,SAAgB,gBAAgB,QAAO;gBAE3B,OAAO,EAAE,MAAM;CAG5B;AAED,qBAAa,gCAAiC,SAAQ,uBAAuB;CAAG;AAChF,qBAAa,8BAA+B,SAAQ,uBAAuB;CAAG;AAE9E;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAsB,aAAa,CAAC,CAAC,EACnC,IAAI,EAAE,MAAM,EACZ,cAAc,EAAE,MAAM,EACtB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACnB,OAAO,CAAC,CAAC,CAAC,CA0FZ;AAID;;;;;;;;;;;;;GAaG;AACH,wBAAsB,WAAW,CAAC,CAAC,EACjC,IAAI,EAAE,MAAM,EACZ,cAAc,EAAE,MAAM,EACtB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACnB,OAAO,CAAC,CAAC,CAAC,CAkDZ"}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ProcessLockAcquireTimeoutError = exports.NavigatorLockAcquireTimeoutError = exports.LockAcquireTimeoutError = exports.internals = void 0;
|
||||
exports.navigatorLock = navigatorLock;
|
||||
exports.processLock = processLock;
|
||||
const helpers_1 = require("./helpers");
|
||||
/**
|
||||
* @experimental
|
||||
*/
|
||||
exports.internals = {
|
||||
/**
|
||||
* @experimental
|
||||
*/
|
||||
debug: !!(globalThis &&
|
||||
(0, helpers_1.supportsLocalStorage)() &&
|
||||
globalThis.localStorage &&
|
||||
globalThis.localStorage.getItem('supabase.gotrue-js.locks.debug') === 'true'),
|
||||
};
|
||||
/**
|
||||
* An error thrown when a lock cannot be acquired after some amount of time.
|
||||
*
|
||||
* Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`.
|
||||
*/
|
||||
class LockAcquireTimeoutError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.isAcquireTimeout = true;
|
||||
}
|
||||
}
|
||||
exports.LockAcquireTimeoutError = LockAcquireTimeoutError;
|
||||
class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError {
|
||||
}
|
||||
exports.NavigatorLockAcquireTimeoutError = NavigatorLockAcquireTimeoutError;
|
||||
class ProcessLockAcquireTimeoutError extends LockAcquireTimeoutError {
|
||||
}
|
||||
exports.ProcessLockAcquireTimeoutError = ProcessLockAcquireTimeoutError;
|
||||
/**
|
||||
* Implements a global exclusive lock using the Navigator LockManager API. It
|
||||
* is available on all browsers released after 2022-03-15 with Safari being the
|
||||
* last one to release support. If the API is not available, this function will
|
||||
* throw. Make sure you check availablility before configuring {@link
|
||||
* GoTrueClient}.
|
||||
*
|
||||
* You can turn on debugging by setting the `supabase.gotrue-js.locks.debug`
|
||||
* local storage item to `true`.
|
||||
*
|
||||
* Internals:
|
||||
*
|
||||
* Since the LockManager API does not preserve stack traces for the async
|
||||
* function passed in the `request` method, a trick is used where acquiring the
|
||||
* lock releases a previously started promise to run the operation in the `fn`
|
||||
* function. The lock waits for that promise to finish (with or without error),
|
||||
* while the function will finally wait for the result anyway.
|
||||
*
|
||||
* @param name Name of the lock to be acquired.
|
||||
* @param acquireTimeout If negative, no timeout. If 0 an error is thrown if
|
||||
* the lock can't be acquired without waiting. If positive, the lock acquire
|
||||
* will time out after so many milliseconds. An error is
|
||||
* a timeout if it has `isAcquireTimeout` set to true.
|
||||
* @param fn The operation to run once the lock is acquired.
|
||||
*/
|
||||
async function navigatorLock(name, acquireTimeout, fn) {
|
||||
if (exports.internals.debug) {
|
||||
console.log('@supabase/gotrue-js: navigatorLock: acquire lock', name, acquireTimeout);
|
||||
}
|
||||
const abortController = new globalThis.AbortController();
|
||||
if (acquireTimeout > 0) {
|
||||
setTimeout(() => {
|
||||
abortController.abort();
|
||||
if (exports.internals.debug) {
|
||||
console.log('@supabase/gotrue-js: navigatorLock acquire timed out', name);
|
||||
}
|
||||
}, acquireTimeout);
|
||||
}
|
||||
// MDN article: https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request
|
||||
// Wrapping navigator.locks.request() with a plain Promise is done as some
|
||||
// libraries like zone.js patch the Promise object to track the execution
|
||||
// context. However, it appears that most browsers use an internal promise
|
||||
// implementation when using the navigator.locks.request() API causing them
|
||||
// to lose context and emit confusing log messages or break certain features.
|
||||
// This wrapping is believed to help zone.js track the execution context
|
||||
// better.
|
||||
return await Promise.resolve().then(() => globalThis.navigator.locks.request(name, acquireTimeout === 0
|
||||
? {
|
||||
mode: 'exclusive',
|
||||
ifAvailable: true,
|
||||
}
|
||||
: {
|
||||
mode: 'exclusive',
|
||||
signal: abortController.signal,
|
||||
}, async (lock) => {
|
||||
if (lock) {
|
||||
if (exports.internals.debug) {
|
||||
console.log('@supabase/gotrue-js: navigatorLock: acquired', name, lock.name);
|
||||
}
|
||||
try {
|
||||
return await fn();
|
||||
}
|
||||
finally {
|
||||
if (exports.internals.debug) {
|
||||
console.log('@supabase/gotrue-js: navigatorLock: released', name, lock.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (acquireTimeout === 0) {
|
||||
if (exports.internals.debug) {
|
||||
console.log('@supabase/gotrue-js: navigatorLock: not immediately available', name);
|
||||
}
|
||||
throw new NavigatorLockAcquireTimeoutError(`Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed`);
|
||||
}
|
||||
else {
|
||||
if (exports.internals.debug) {
|
||||
try {
|
||||
const result = await globalThis.navigator.locks.query();
|
||||
console.log('@supabase/gotrue-js: Navigator LockManager state', JSON.stringify(result, null, ' '));
|
||||
}
|
||||
catch (e) {
|
||||
console.warn('@supabase/gotrue-js: Error when querying Navigator LockManager state', e);
|
||||
}
|
||||
}
|
||||
// Browser is not following the Navigator LockManager spec, it
|
||||
// returned a null lock when we didn't use ifAvailable. So we can
|
||||
// pretend the lock is acquired in the name of backward compatibility
|
||||
// and user experience and just run the function.
|
||||
console.warn('@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request');
|
||||
return await fn();
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
const PROCESS_LOCKS = {};
|
||||
/**
|
||||
* Implements a global exclusive lock that works only in the current process.
|
||||
* Useful for environments like React Native or other non-browser
|
||||
* single-process (i.e. no concept of "tabs") environments.
|
||||
*
|
||||
* Use {@link #navigatorLock} in browser environments.
|
||||
*
|
||||
* @param name Name of the lock to be acquired.
|
||||
* @param acquireTimeout If negative, no timeout. If 0 an error is thrown if
|
||||
* the lock can't be acquired without waiting. If positive, the lock acquire
|
||||
* will time out after so many milliseconds. An error is
|
||||
* a timeout if it has `isAcquireTimeout` set to true.
|
||||
* @param fn The operation to run once the lock is acquired.
|
||||
*/
|
||||
async function processLock(name, acquireTimeout, fn) {
|
||||
var _a;
|
||||
const previousOperation = (_a = PROCESS_LOCKS[name]) !== null && _a !== void 0 ? _a : Promise.resolve();
|
||||
const currentOperation = Promise.race([
|
||||
previousOperation.catch(() => {
|
||||
// ignore error of previous operation that we're waiting to finish
|
||||
return null;
|
||||
}),
|
||||
acquireTimeout >= 0
|
||||
? new Promise((_, reject) => {
|
||||
setTimeout(() => {
|
||||
reject(new ProcessLockAcquireTimeoutError(`Acquring process lock with name "${name}" timed out`));
|
||||
}, acquireTimeout);
|
||||
})
|
||||
: null,
|
||||
].filter((x) => x))
|
||||
.catch((e) => {
|
||||
if (e && e.isAcquireTimeout) {
|
||||
throw e;
|
||||
}
|
||||
return null;
|
||||
})
|
||||
.then(async () => {
|
||||
// previous operations finished and we didn't get a race on the acquire
|
||||
// timeout, so the current operation can finally start
|
||||
return await fn();
|
||||
});
|
||||
PROCESS_LOCKS[name] = currentOperation.catch(async (e) => {
|
||||
if (e && e.isAcquireTimeout) {
|
||||
// if the current operation timed out, it doesn't mean that the previous
|
||||
// operation finished, so we need contnue waiting for it to finish
|
||||
await previousOperation;
|
||||
return null;
|
||||
}
|
||||
throw e;
|
||||
});
|
||||
// finally wait for the current operation to finish successfully, with an
|
||||
// error or with an acquire timeout error
|
||||
return await currentOperation;
|
||||
}
|
||||
//# sourceMappingURL=locks.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version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AE;QAChB,IAAI,CAAC,IAAI,CAAC,CAAC,gBAAgB,EAAE,CAAC;YAC5B,MAAM,CAAC,CAAA;QACT,CAAC;QAED,OAAO,IAAI,CAAA;IACb,CAAC,CAAC;SACD,IAAI,CAAC,KAAK,IAAI,EAAE;QACf,uEAAuE;QACvE,sDAAsD;QACtD,OAAO,MAAM,EAAE,EAAE,CAAA;IACnB,CAAC,CAAC,CAAA;IAEJ,aAAa,CAAC,IAAI,CAAC,GAAG,gBAAgB,CAAC,KAAK,CAAC,KAAK,EAAE,CAAM,EAAE,EAAE;QAC5D,IAAI,CAAC,IAAI,CAAC,CAAC,gBAAgB,EAAE,CAAC;YAC5B,wEAAwE;YACxE,kEAAkE;YAClE,MAAM,iBAAiB,CAAA;YAEvB,OAAO,IAAI,CAAA;QACb,CAAC;QAED,MAAM,CAAC,CAAA;IACT,CAAC,CAAC,CAAA;IAEF,yEAAyE;IACzE,yCAAyC;IACzC,OAAO,MAAM,gBAAgB,CAAA;AAC/B,CAAC"}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
/**
|
||||
* https://mathiasbynens.be/notes/globalthis
|
||||
*/
|
||||
export declare function polyfillGlobalThis(): void;
|
||||
//# sourceMappingURL=polyfills.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"polyfills.d.ts","sourceRoot":"","sources":["../../../src/lib/polyfills.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,wBAAgB,kBAAkB,SAmBjC"}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.polyfillGlobalThis = polyfillGlobalThis;
|
||||
/**
|
||||
* https://mathiasbynens.be/notes/globalthis
|
||||
*/
|
||||
function polyfillGlobalThis() {
|
||||
if (typeof globalThis === 'object')
|
||||
return;
|
||||
try {
|
||||
Object.defineProperty(Object.prototype, '__magic__', {
|
||||
get: function () {
|
||||
return this;
|
||||
},
|
||||
configurable: true,
|
||||
});
|
||||
// @ts-expect-error 'Allow access to magic'
|
||||
__magic__.globalThis = __magic__;
|
||||
// @ts-expect-error 'Allow access to magic'
|
||||
delete Object.prototype.__magic__;
|
||||
}
|
||||
catch (e) {
|
||||
if (typeof self !== 'undefined') {
|
||||
// @ts-expect-error 'Allow access to globals'
|
||||
self.globalThis = self;
|
||||
}
|
||||
}
|
||||
}
|
||||
//# sourceMappingURL=polyfills.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"polyfills.js","sourceRoot":"","sources":["../../../src/lib/polyfills.ts"],"names":[],"mappings":";;AAGA,gDAmBC;AAtBD;;GAEG;AACH,SAAgB,kBAAkB;IAChC,IAAI,OAAO,UAAU,KAAK,QAAQ;QAAE,OAAM;IAC1C,IAAI,CAAC;QACH,MAAM,CAAC,cAAc,CAAC,MAAM,CAAC,SAAS,EAAE,WAAW,EAAE;YACnD,GAAG,EAAE;gBACH,OAAO,IAAI,CAAA;YACb,CAAC;YACD,YAAY,EAAE,IAAI;SACnB,CAAC,CAAA;QACF,2CAA2C;QAC3C,SAAS,CAAC,UAAU,GAAG,SAAS,CAAA;QAChC,2CAA2C;QAC3C,OAAO,MAAM,CAAC,SAAS,CAAC,SAAS,CAAA;IACnC,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE,CAAC;YAChC,6CAA6C;YAC7C,IAAI,CAAC,UAAU,GAAG,IAAI,CAAA;QACxB,CAAC;IACH,CAAC;AACH,CAAC"}
|
||||
+1262
File diff suppressed because it is too large.
Load diff
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAA;AACpC,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAC/B,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,GAAG,EAAE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IACnB,QAAQ,EAAE,MAAM,CAAA;IAChB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED,QAAA,MAAM,WAAW,wCAAyC,CAAA;AAE1D;;GAEG;AACH,MAAM,MAAM,UAAU,GAAG,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,CAAC,CAAA;AAErD,QAAA,MAAM,0BAA0B,qCAAsC,CAAA;AAEtE;;GAEG;AACH,KAAK,wBAAwB,GAAG,CAAC,OAAO,0BAA0B,CAAC,CAAC,MAAM,CAAC,CAAA;AAE3E;;;;;;GAMG;AACH,MAAM,MAAM,MAAM,CAChB,IAAI,SAAS,UAAU,GAAG,UAAU,EACpC,MAAM,SAAS,wBAAwB,GAAG,CAAC,OAAO,0BAA0B,CAAC,CAAC,MAAM,CAAC,IACnF;IACF,wBAAwB;IACxB,EAAE,EAAE,MAAM,CAAA;IAEV,oFAAoF;IACpF,aAAa,CAAC,EAAE,MAAM,CAAA;Line truncated
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SIGN_OUT_SCOPES = void 0;
|
||||
const WeakPasswordReasons = ['length', 'characters', 'pwned'];
|
||||
const AMRMethods = [
|
||||
'password',
|
||||
'otp',
|
||||
'oauth',
|
||||
'totp',
|
||||
'mfa/totp',
|
||||
'mfa/phone',
|
||||
'mfa/webauthn',
|
||||
'anonymous',
|
||||
'sso/saml',
|
||||
'magiclink',
|
||||
'web3',
|
||||
];
|
||||
const FactorTypes = ['totp', 'phone', 'webauthn'];
|
||||
const FactorVerificationStatuses = ['verified', 'unverified'];
|
||||
const MFATOTPChannels = ['sms', 'whatsapp'];
|
||||
exports.SIGN_OUT_SCOPES = ['global', 'local', 'others'];
|
||||
//# sourceMappingURL=types.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":";;;AA+GA,MAAM,mBAAmB,GAAG,CAAC,QAAQ,EAAE,YAAY,EAAE,OAAO,CAAU,CAAA;AA+ItE,MAAM,UAAU,GAAG;IACjB,UAAU;IACV,KAAK;IACL,OAAO;IACP,MAAM;IACN,UAAU;IACV,WAAW;IACX,cAAc;IACd,WAAW;IACX,UAAU;IACV,WAAW;IACX,MAAM;CACE,CAAA;AAoCV,MAAM,WAAW,GAAG,CAAC,MAAM,EAAE,OAAO,EAAE,UAAU,CAAU,CAAA;AAO1D,MAAM,0BAA0B,GAAG,CAAC,UAAU,EAAE,YAAY,CAAU,CAAA;AAsnBtE,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,UAAU,CAAU,CAAA;AA6fvC,QAAA,eAAe,GAAG,CAAC,QAAQ,EAAE,OAAO,EAAE,QAAQ,CAAU,CAAA"}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export declare const version = "2.76.1";
|
||||
//# sourceMappingURL=version.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,OAAO,WAAW,CAAA"}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.version = void 0;
|
||||
// Generated automatically during releases by scripts/update-version-files.ts
|
||||
// This file provides runtime access to the package version for:
|
||||
// - HTTP request headers (e.g., X-Client-Info header for API requests)
|
||||
// - Debugging and support (identifying which version is running)
|
||||
// - Telemetry and logging (version reporting in errors/analytics)
|
||||
// - Ensuring build artifacts match the published package version
|
||||
exports.version = '2.76.1';
|
||||
//# sourceMappingURL=version.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":";;;AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,uEAAuE;AACvE,iEAAiE;AACjE,kEAAkE;AAClE,iEAAiE;AACpD,QAAA,OAAO,GAAG,QAAQ,CAAA"}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
export type Hex = `0x${string}`;
|
||||
export type Address = Hex;
|
||||
export type EIP1193EventMap = {
|
||||
accountsChanged(accounts: Address[]): void;
|
||||
chainChanged(chainId: string): void;
|
||||
connect(connectInfo: {
|
||||
chainId: string;
|
||||
}): void;
|
||||
disconnect(error: {
|
||||
code: number;
|
||||
message: string;
|
||||
}): void;
|
||||
message(message: {
|
||||
type: string;
|
||||
data: unknown;
|
||||
}): void;
|
||||
};
|
||||
export type EIP1193Events = {
|
||||
on<event extends keyof EIP1193EventMap>(event: event, listener: EIP1193EventMap[event]): void;
|
||||
removeListener<event extends keyof EIP1193EventMap>(event: event, listener: EIP1193EventMap[event]): void;
|
||||
};
|
||||
export type EIP1193RequestFn = (args: {
|
||||
method: string;
|
||||
params?: unknown;
|
||||
}) => Promise<unknown>;
|
||||
export type EIP1193Provider = EIP1193Events & {
|
||||
address: string;
|
||||
request: EIP1193RequestFn;
|
||||
};
|
||||
export type EthereumWallet = EIP1193Provider;
|
||||
/**
|
||||
* EIP-4361 message fields
|
||||
*/
|
||||
export type SiweMessage = {
|
||||
/**
|
||||
* The Ethereum address performing the signing.
|
||||
*/
|
||||
address: Address;
|
||||
/**
|
||||
* The [EIP-155](https://eips.ethereum.org/EIPS/eip-155) Chain ID to which the session is bound,
|
||||
*/
|
||||
chainId: number;
|
||||
/**
|
||||
* [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority that is requesting the signing.
|
||||
*/
|
||||
domain: string;
|
||||
/**
|
||||
* Time when the signed authentication message is no longer valid.
|
||||
*/
|
||||
expirationTime?: Date | undefined;
|
||||
/**
|
||||
* Time when the message was generated, typically the current time.
|
||||
*/
|
||||
issuedAt?: Date | undefined;
|
||||
/**
|
||||
* A random string typically chosen by the relying party and used to prevent replay attacks.
|
||||
*/
|
||||
nonce?: string;
|
||||
/**
|
||||
* Time when the signed authentication message will become valid.
|
||||
*/
|
||||
notBefore?: Date | undefined;
|
||||
/**
|
||||
* A system-specific identifier that may be used to uniquely refer to the sign-in request.
|
||||
*/
|
||||
requestId?: string | undefined;
|
||||
/**
|
||||
* A list of information or references to information the user wishes to have resolved as part of authentication by the relying party.
|
||||
*/
|
||||
resources?: string[] | undefined;
|
||||
/**
|
||||
* [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme of the origin of the request.
|
||||
*/
|
||||
scheme?: string | undefined;
|
||||
/**
|
||||
* A human-readable ASCII assertion that the user will sign.
|
||||
*/
|
||||
statement?: string | undefined;
|
||||
/**
|
||||
* [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) URI referring to the resource that is the subject of the signing (as in the subject of a claim).
|
||||
*/
|
||||
uri: string;
|
||||
/**
|
||||
* The current version of the SIWE Message.
|
||||
*/
|
||||
version: '1';
|
||||
};
|
||||
export type EthereumSignInInput = SiweMessage;
|
||||
export declare function getAddress(address: string): Address;
|
||||
export declare function fromHex(hex: Hex): number;
|
||||
export declare function toHex(value: string): Hex;
|
||||
/**
|
||||
* Creates EIP-4361 formatted message.
|
||||
*/
|
||||
export declare function createSiweMessage(parameters: SiweMessage): string;
|
||||
//# sourceMappingURL=ethereum.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"ethereum.d.ts","sourceRoot":"","sources":["../../../../src/lib/web3/ethereum.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,GAAG,GAAG,KAAK,MAAM,EAAE,CAAA;AAE/B,MAAM,MAAM,OAAO,GAAG,GAAG,CAAA;AAEzB,MAAM,MAAM,eAAe,GAAG;IAC5B,eAAe,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,IAAI,CAAA;IAC1C,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAA;IACnC,OAAO,CAAC,WAAW,EAA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AC,EAAE,MAAM,CAAA;IACd;;OAEG;IACH,SAAS,CAAC,EAAE,IAAI,GAAG,SAAS,CAAA;IAC5B;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC9B;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,EAAE,GAAG,SAAS,CAAA;IAChC;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC3B;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC9B;;OAEG;IACH,GAAG,EAAE,MAAM,CAAA;IACX;;OAEG;IACH,OAAO,EAAE,GAAG,CAAA;CACb,CAAA;AAED,MAAM,MAAM,mBAAmB,GAAG,WAAW,CAAA;AAE7C,wBAAgB,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAKnD;AAED,wBAAgB,OAAO,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,CAExC;AAED,wBAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,CAIxC;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,WAAW,GAAG,MAAM,CAwEjE"}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
"use strict";
|
||||
// types and functions copied over from viem so this library doesn't depend on it
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getAddress = getAddress;
|
||||
exports.fromHex = fromHex;
|
||||
exports.toHex = toHex;
|
||||
exports.createSiweMessage = createSiweMessage;
|
||||
function getAddress(address) {
|
||||
if (!/^0x[a-fA-F0-9]{40}$/.test(address)) {
|
||||
throw new Error(`@supabase/auth-js: Address "${address}" is invalid.`);
|
||||
}
|
||||
return address.toLowerCase();
|
||||
}
|
||||
function fromHex(hex) {
|
||||
return parseInt(hex, 16);
|
||||
}
|
||||
function toHex(value) {
|
||||
const bytes = new TextEncoder().encode(value);
|
||||
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
|
||||
return ('0x' + hex);
|
||||
}
|
||||
/**
|
||||
* Creates EIP-4361 formatted message.
|
||||
*/
|
||||
function createSiweMessage(parameters) {
|
||||
var _a;
|
||||
const { chainId, domain, expirationTime, issuedAt = new Date(), nonce, notBefore, requestId, resources, scheme, uri, version, } = parameters;
|
||||
// Validate fields
|
||||
{
|
||||
if (!Number.isInteger(chainId))
|
||||
throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${chainId}`);
|
||||
if (!domain)
|
||||
throw new Error(`@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.`);
|
||||
if (nonce && nonce.length < 8)
|
||||
throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${nonce}`);
|
||||
if (!uri)
|
||||
throw new Error(`@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.`);
|
||||
if (version !== '1')
|
||||
throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${version}`);
|
||||
if ((_a = parameters.statement) === null || _a === void 0 ? void 0 : _a.includes('\n'))
|
||||
throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${parameters.statement}`);
|
||||
}
|
||||
// Construct message
|
||||
const address = getAddress(parameters.address);
|
||||
const origin = scheme ? `${scheme}://${domain}` : domain;
|
||||
const statement = parameters.statement ? `${parameters.statement}\n` : '';
|
||||
const prefix = `${origin} wants you to sign in with your Ethereum account:\n${address}\n\n${statement}`;
|
||||
let suffix = `URI: ${uri}\nVersion: ${version}\nChain ID: ${chainId}${nonce ? `\nNonce: ${nonce}` : ''}\nIssued At: ${issuedAt.toISOString()}`;
|
||||
if (expirationTime)
|
||||
suffix += `\nExpiration Time: ${expirationTime.toISOString()}`;
|
||||
if (notBefore)
|
||||
suffix += `\nNot Before: ${notBefore.toISOString()}`;
|
||||
if (requestId)
|
||||
suffix += `\nRequest ID: ${requestId}`;
|
||||
if (resources) {
|
||||
let content = '\nResources:';
|
||||
for (const resource of resources) {
|
||||
if (!resource || typeof resource !== 'string')
|
||||
throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${resource}`);
|
||||
content += `\n- ${resource}`;
|
||||
}
|
||||
suffix += content;
|
||||
}
|
||||
return `${prefix}\n${suffix}`;
|
||||
}
|
||||
//# sourceMappingURL=ethereum.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"ethereum.js","sourceRoot":"","sources":["../../../../src/lib/web3/ethereum.ts"],"names":[],"mappings":";AAAA,iFAAiF;;AA2FjF,gCAKC;AAED,0BAEC;AAED,sBAIC;AAKD,8CAwEC;AA5FD,SAAgB,UAAU,CAAC,OAAe;IACxC,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QACzC,MAAM,IAAI,KAAK,CAAC,+BAA+B,OAAO,eAAe,CAAC,CAAA;IACxE,CAAC;IACD,OAAO,OAAO,CAAC,WAAW,EAAa,CAAA;AACzC,CAAC;AAED,SAAgB,OAAO,CAAC,GAAQ;IAC9B,OAAO,QAAQ,CAAC,GAAG,EAAE,EAAE,CAAC,CAAA;AAC1B,CAAC;AAED,SAAgB,KAAK,CAAC,KAAa;IACjC,MAAM,KAAK,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;IAC7C,MAAM,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;IACpF,OAAO,CAAC,IAAI,GAAG,GAAG,CAAQ,CAAA;AAC5B,CAAC;AAED;;GAEG;AACH,SAAgB,iBAAiB,CAAC,UAAuB;;IACvD,MAAM,EACJ,OA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AG,cAAc,OAAO,eAAe,OAAO,GACjE,KAAK,CAAC,CAAC,CAAC,YAAY,KAAK,EAAE,CAAC,CAAC,CAAC,EAChC,gBAAgB,QAAQ,CAAC,WAAW,EAAE,EAAE,CAAA;IAExC,IAAI,cAAc;QAAE,MAAM,IAAI,sBAAsB,cAAc,CAAC,WAAW,EAAE,EAAE,CAAA;IAClF,IAAI,SAAS;QAAE,MAAM,IAAI,iBAAiB,SAAS,CAAC,WAAW,EAAE,EAAE,CAAA;IACnE,IAAI,SAAS;QAAE,MAAM,IAAI,iBAAiB,SAAS,EAAE,CAAA;IACrD,IAAI,SAAS,EAAE,CAAC;QACd,IAAI,OAAO,GAAG,cAAc,CAAA;QAC5B,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;YACjC,IAAI,CAAC,QAAQ,IAAI,OAAO,QAAQ,KAAK,QAAQ;gBAC3C,MAAM,IAAI,KAAK,CACb,qHAAqH,QAAQ,EAAE,CAChI,CAAA;YACH,OAAO,IAAI,OAAO,QAAQ,EAAE,CAAA;QAC9B,CAAC;QACD,MAAM,IAAI,OAAO,CAAA;IACnB,CAAC;IAED,OAAO,GAAG,MAAM,KAAK,MAAM,EAAE,CAAA;AAC/B,CAAC"}
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* A namespaced identifier in the format `${namespace}:${reference}`.
|
||||
*
|
||||
* Used by {@link IdentifierArray} and {@link IdentifierRecord}.
|
||||
*
|
||||
* @group Identifier
|
||||
*/
|
||||
export type IdentifierString = `${string}:${string}`;
|
||||
/**
|
||||
* A read-only array of namespaced identifiers in the format `${namespace}:${reference}`.
|
||||
*
|
||||
* Used by {@link Wallet.chains | Wallet::chains}, {@link WalletAccount.chains | WalletAccount::chains}, and
|
||||
* {@link WalletAccount.features | WalletAccount::features}.
|
||||
*
|
||||
* @group Identifier
|
||||
*/
|
||||
export type IdentifierArray = readonly IdentifierString[];
|
||||
/**
|
||||
* Version of the Wallet Standard implemented by a {@link Wallet}.
|
||||
*
|
||||
* Used by {@link Wallet.version | Wallet::version}.
|
||||
*
|
||||
* Note that this is _NOT_ a version of the Wallet, but a version of the Wallet Standard itself that the Wallet
|
||||
* supports.
|
||||
*
|
||||
* This may be used by the app to determine compatibility and feature detect.
|
||||
*
|
||||
* @group Wallet
|
||||
*/
|
||||
export type WalletVersion = '1.0.0';
|
||||
/**
|
||||
* A data URI containing a base64-encoded SVG, WebP, PNG, or GIF image.
|
||||
*
|
||||
* Used by {@link Wallet.icon | Wallet::icon} and {@link WalletAccount.icon | WalletAccount::icon}.
|
||||
*
|
||||
* @group Wallet
|
||||
*/
|
||||
export type WalletIcon = `data:image/${'svg+xml' | 'webp' | 'png' | 'gif'};base64,${string}`;
|
||||
/**
|
||||
* Interface of a **WalletAccount**, also referred to as an **Account**.
|
||||
*
|
||||
* An account is a _read-only data object_ that is provided from the Wallet to the app, authorizing the app to use it.
|
||||
*
|
||||
* The app can use an account to display and query information from a chain.
|
||||
*
|
||||
* The app can also act using an account by passing it to {@link Wallet.features | features} of the Wallet.
|
||||
*
|
||||
* Wallets may use or extend {@link "@wallet-standard/wallet".ReadonlyWalletAccount} which implements this interface.
|
||||
*
|
||||
* @group Wallet
|
||||
*/
|
||||
export interface WalletAccount {
|
||||
/** Address of the account, corresponding with a public key. */
|
||||
readonly address: string;
|
||||
/** Public key of the account, corresponding with a secret key to use. */
|
||||
readonly publicKey: Uint8Array;
|
||||
/**
|
||||
* Chains supported by the account.
|
||||
*
|
||||
* This must be a subset of the {@link Wallet.chains | chains} of the Wallet.
|
||||
*/
|
||||
readonly chains: IdentifierArray;
|
||||
/**
|
||||
* Feature names supported by the account.
|
||||
*
|
||||
* This must be a subset of the names of {@link Wallet.features | features} of the Wallet.
|
||||
*/
|
||||
readonly features: IdentifierArray;
|
||||
/** Optional user-friendly descriptive label or name for the account. This may be displayed by the app. */
|
||||
readonly label?: string;
|
||||
/** Optional user-friendly icon for the account. This may be displayed by the app. */
|
||||
readonly icon?: WalletIcon;
|
||||
}
|
||||
/** Input for signing in. */
|
||||
export interface SolanaSignInInput {
|
||||
/**
|
||||
* Optional EIP-4361 Domain.
|
||||
* If not provided, the wallet must determine the Domain to include in the message.
|
||||
*/
|
||||
readonly domain?: string;
|
||||
/**
|
||||
* Optional EIP-4361 Address.
|
||||
* If not provided, the wallet must determine the Address to include in the message.
|
||||
*/
|
||||
readonly address?: string;
|
||||
/**
|
||||
* Optional EIP-4361 Statement.
|
||||
* If not provided, the wallet must not include Statement in the message.
|
||||
*/
|
||||
readonly statement?: string;
|
||||
/**
|
||||
* Optional EIP-4361 URI.
|
||||
* If not provided, the wallet must not include URI in the message.
|
||||
*/
|
||||
readonly uri?: string;
|
||||
/**
|
||||
* Optional EIP-4361 Version.
|
||||
* If not provided, the wallet must not include Version in the message.
|
||||
*/
|
||||
readonly version?: string;
|
||||
/**
|
||||
* Optional EIP-4361 Chain ID.
|
||||
* If not provided, the wallet must not include Chain ID in the message.
|
||||
*/
|
||||
readonly chainId?: string;
|
||||
/**
|
||||
* Optional EIP-4361 Nonce.
|
||||
* If not provided, the wallet must not include Nonce in the message.
|
||||
*/
|
||||
readonly nonce?: string;
|
||||
/**
|
||||
* Optional EIP-4361 Issued At.
|
||||
* If not provided, the wallet must not include Issued At in the message.
|
||||
*/
|
||||
readonly issuedAt?: string;
|
||||
/**
|
||||
* Optional EIP-4361 Expiration Time.
|
||||
* If not provided, the wallet must not include Expiration Time in the message.
|
||||
*/
|
||||
readonly expirationTime?: string;
|
||||
/**
|
||||
* Optional EIP-4361 Not Before.
|
||||
* If not provided, the wallet must not include Not Before in the message.
|
||||
*/
|
||||
readonly notBefore?: string;
|
||||
/**
|
||||
* Optional EIP-4361 Request ID.
|
||||
* If not provided, the wallet must not include Request ID in the message.
|
||||
*/
|
||||
readonly requestId?: string;
|
||||
/**
|
||||
* Optional EIP-4361 Resources.
|
||||
* If not provided, the wallet must not include Resources in the message.
|
||||
*/
|
||||
readonly resources?: readonly string[];
|
||||
}
|
||||
/** Output of signing in. */
|
||||
export interface SolanaSignInOutput {
|
||||
/**
|
||||
* Account that was signed in.
|
||||
* The address of the account may be different from the provided input Address.
|
||||
*/
|
||||
readonly account: WalletAccount;
|
||||
/**
|
||||
* Message bytes that were signed.
|
||||
* The wallet may prefix or otherwise modify the message before signing it.
|
||||
*/
|
||||
readonly signedMessage: Uint8Array;
|
||||
/**
|
||||
* Message signature produced.
|
||||
* If the signature type is provided, the signature must be Ed25519.
|
||||
*/
|
||||
readonly signature: Uint8Array;
|
||||
/**
|
||||
* Optional type of the message signature produced.
|
||||
* If not provided, the signature must be Ed25519.
|
||||
*/
|
||||
readonly signatureType?: 'ed25519';
|
||||
}
|
||||
//# sourceMappingURL=solana.d.ts.map
|
||||
Loaded 100 of 4614 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user