Add guest cart drawer, Continue handoff, and shared customer login.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
co-authored by
Cursor
parent
ad05241a77
commit
16340c3b48
+16
@@ -195,6 +195,22 @@ export async function getCategoryBySlug(slug: string) {
|
||||
return categories.find((category) => category.slug === slug) ?? null;
|
||||
}
|
||||
|
||||
export type ApiTenant = {
|
||||
id: string | number;
|
||||
name: string;
|
||||
nameFa?: string | null;
|
||||
slug?: string;
|
||||
domain?: string;
|
||||
};
|
||||
|
||||
export async function getTenant() {
|
||||
try {
|
||||
return await apiGet<ApiTenant>(`/tenants/${API.domain}`);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getComments(entityType: "product" | "blog", entityId: string) {
|
||||
try {
|
||||
const data = await apiGet<{ items: ApiComment[] }>(`${tenant()}/comments`, { entityType, entityId });
|
||||
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
export type CartItem = {
|
||||
productId: string;
|
||||
variantId?: string;
|
||||
slug: string;
|
||||
name: string;
|
||||
image: string;
|
||||
price: number;
|
||||
qty: number;
|
||||
};
|
||||
|
||||
const KEY = "salar-cart";
|
||||
|
||||
export function getCart(): CartItem[] {
|
||||
if (typeof window === "undefined") return [];
|
||||
try {
|
||||
const raw = window.localStorage.getItem(KEY);
|
||||
return raw ? (JSON.parse(raw) as CartItem[]) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function cartCount() {
|
||||
return getCart().reduce((sum, item) => sum + item.qty, 0);
|
||||
}
|
||||
|
||||
export function addToCart(item: CartItem) {
|
||||
const cart = getCart();
|
||||
const index = cart.findIndex(
|
||||
(entry) => entry.productId === item.productId && entry.variantId === item.variantId,
|
||||
);
|
||||
if (index >= 0) {
|
||||
cart[index] = { ...cart[index], qty: cart[index].qty + item.qty };
|
||||
} else {
|
||||
cart.push(item);
|
||||
}
|
||||
window.localStorage.setItem(KEY, JSON.stringify(cart));
|
||||
window.dispatchEvent(new Event("cart-updated"));
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import type { GuestCartLine } from "./customer";
|
||||
|
||||
export type CartItem = GuestCartLine;
|
||||
|
||||
const KEY = "meshkee-guest-cart";
|
||||
const LEGACY_KEY = "salar-cart";
|
||||
const CART_EVENT = "cart-updated";
|
||||
|
||||
function cookieDomain(): string | undefined {
|
||||
if (typeof window === "undefined") return undefined;
|
||||
const host = window.location.hostname.toLowerCase();
|
||||
if (host === "localhost" || host === "127.0.0.1") return undefined;
|
||||
const parts = host.split(".").filter(Boolean);
|
||||
if (parts.length < 2) return undefined;
|
||||
return `.${parts.slice(-2).join(".")}`;
|
||||
}
|
||||
|
||||
function parseItems(raw: string | null): CartItem[] {
|
||||
if (!raw) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed
|
||||
.map((entry) => normalizeLine(entry))
|
||||
.filter((item): item is CartItem => Boolean(item));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeLine(entry: unknown): CartItem | null {
|
||||
if (!entry || typeof entry !== "object") return null;
|
||||
const item = entry as Record<string, unknown>;
|
||||
const id = String(item.id ?? item.variantId ?? item.storeItemVariantId ?? "").trim();
|
||||
if (!id) return null;
|
||||
const quantity = Math.max(1, Math.floor(Number(item.quantity ?? item.qty) || 1));
|
||||
const price = Number(item.price) || 0;
|
||||
const name = String(item.name ?? "محصول");
|
||||
const slug = item.slug ? String(item.slug) : undefined;
|
||||
const image = item.image != null && item.image !== "" ? String(item.image) : undefined;
|
||||
return { id, name, ...(slug ? { slug } : {}), price, quantity, ...(image ? { image } : {}) };
|
||||
}
|
||||
|
||||
function writeSharedCookie(items: CartItem[]) {
|
||||
if (typeof document === "undefined") return;
|
||||
const domain = cookieDomain();
|
||||
const maxAge = 60 * 60 * 24 * 30;
|
||||
const encoded = encodeURIComponent(
|
||||
JSON.stringify(
|
||||
items.map(({ id, name, slug, price, quantity }) => ({
|
||||
id,
|
||||
name,
|
||||
slug,
|
||||
price,
|
||||
quantity,
|
||||
image: null as string | null,
|
||||
})),
|
||||
),
|
||||
);
|
||||
if (encoded.length > 3500) return;
|
||||
let cookie = `${KEY}=${encoded}; path=/; max-age=${maxAge}; SameSite=Lax`;
|
||||
if (domain) cookie += `; domain=${domain}`;
|
||||
document.cookie = cookie;
|
||||
}
|
||||
|
||||
function notify() {
|
||||
window.dispatchEvent(new Event(CART_EVENT));
|
||||
}
|
||||
|
||||
export function getCart(): CartItem[] {
|
||||
if (typeof window === "undefined") return [];
|
||||
const primary = parseItems(window.localStorage.getItem(KEY));
|
||||
if (primary.length > 0) return primary;
|
||||
const legacy = parseItems(window.localStorage.getItem(LEGACY_KEY));
|
||||
if (legacy.length > 0) {
|
||||
writeCart(legacy);
|
||||
window.localStorage.removeItem(LEGACY_KEY);
|
||||
return legacy;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export function writeCart(items: CartItem[]) {
|
||||
if (typeof window === "undefined") return;
|
||||
window.localStorage.setItem(KEY, JSON.stringify(items));
|
||||
window.localStorage.removeItem(LEGACY_KEY);
|
||||
try {
|
||||
writeSharedCookie(items);
|
||||
} catch {
|
||||
// ignore cookie failures
|
||||
}
|
||||
notify();
|
||||
}
|
||||
|
||||
export function cartCount() {
|
||||
return getCart().reduce((sum, item) => sum + item.quantity, 0);
|
||||
}
|
||||
|
||||
export function cartTotal() {
|
||||
return getCart().reduce((sum, item) => sum + item.price * item.quantity, 0);
|
||||
}
|
||||
|
||||
export function addToCart(item: CartItem) {
|
||||
const cart = getCart();
|
||||
const quantity = Math.max(1, Math.floor(item.quantity) || 1);
|
||||
const index = cart.findIndex((entry) => entry.id === item.id);
|
||||
if (index >= 0) {
|
||||
cart[index] = {
|
||||
...cart[index],
|
||||
...item,
|
||||
quantity: cart[index].quantity + quantity,
|
||||
};
|
||||
} else {
|
||||
cart.push({ ...item, quantity });
|
||||
}
|
||||
writeCart(cart);
|
||||
}
|
||||
|
||||
export function setCartQuantity(id: string, quantity: number) {
|
||||
if (quantity < 1) {
|
||||
writeCart(getCart().filter((item) => item.id !== id));
|
||||
return;
|
||||
}
|
||||
writeCart(getCart().map((item) => (item.id === id ? { ...item, quantity } : item)));
|
||||
}
|
||||
|
||||
export function removeFromCart(id: string) {
|
||||
writeCart(getCart().filter((item) => item.id !== id));
|
||||
}
|
||||
|
||||
type CartContextValue = {
|
||||
items: CartItem[];
|
||||
itemCount: number;
|
||||
total: number;
|
||||
addItem: (item: CartItem) => void;
|
||||
removeItem: (id: string) => void;
|
||||
setQuantity: (id: string, quantity: number) => void;
|
||||
};
|
||||
|
||||
const CartContext = createContext<CartContextValue | null>(null);
|
||||
|
||||
export function CartProvider({ children }: { children: ReactNode }) {
|
||||
const [items, setItems] = useState<CartItem[]>([]);
|
||||
|
||||
const sync = useCallback(() => setItems(getCart()), []);
|
||||
|
||||
useEffect(() => {
|
||||
sync();
|
||||
window.addEventListener(CART_EVENT, sync);
|
||||
window.addEventListener("storage", sync);
|
||||
return () => {
|
||||
window.removeEventListener(CART_EVENT, sync);
|
||||
window.removeEventListener("storage", sync);
|
||||
};
|
||||
}, [sync]);
|
||||
|
||||
const addItem = useCallback((item: CartItem) => addToCart(item), []);
|
||||
const removeItem = useCallback((id: string) => removeFromCart(id), []);
|
||||
const setQuantity = useCallback((id: string, quantity: number) => setCartQuantity(id, quantity), []);
|
||||
|
||||
const itemCount = useMemo(() => items.reduce((sum, item) => sum + item.quantity, 0), [items]);
|
||||
const total = useMemo(() => items.reduce((sum, item) => sum + item.price * item.quantity, 0), [items]);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({ items, itemCount, total, addItem, removeItem, setQuantity }),
|
||||
[items, itemCount, total, addItem, removeItem, setQuantity],
|
||||
);
|
||||
|
||||
return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
|
||||
}
|
||||
|
||||
export function useCart() {
|
||||
const ctx = useContext(CartContext);
|
||||
if (!ctx) throw new Error("useCart must be used within CartProvider");
|
||||
return ctx;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { BUSINESS_ORIGIN, CUSTOMER_ORIGIN } from "./site";
|
||||
|
||||
export const GUEST_CART_URL_PARAM = "guestCart";
|
||||
|
||||
export type GuestCartLine = {
|
||||
id: string;
|
||||
name: string;
|
||||
slug?: string;
|
||||
price: number;
|
||||
quantity: number;
|
||||
image?: string | null;
|
||||
};
|
||||
|
||||
export function encodeGuestCartForUrl(items: GuestCartLine[]): string {
|
||||
const payload = items.map(({ id, name, slug, price, quantity, image }) => ({
|
||||
id,
|
||||
name,
|
||||
...(slug ? { slug } : {}),
|
||||
price,
|
||||
quantity,
|
||||
image: image ?? null,
|
||||
}));
|
||||
const json = JSON.stringify(payload);
|
||||
return btoa(unescape(encodeURIComponent(json)))
|
||||
.replace(/\+/g, "-")
|
||||
.replace(/\//g, "_")
|
||||
.replace(/=+$/, "");
|
||||
}
|
||||
|
||||
export function customerDashboardUrl(path = "/"): string {
|
||||
const normalized = path.startsWith("/") ? path : `/${path}`;
|
||||
return `${CUSTOMER_ORIGIN}${normalized}`;
|
||||
}
|
||||
|
||||
export function businessDashboardUrl(): string {
|
||||
return `${BUSINESS_ORIGIN}/`;
|
||||
}
|
||||
|
||||
export function customerLoginUrl(redirectPath = "/", cartItems?: GuestCartLine[]): string {
|
||||
let redirect = redirectPath.startsWith("/") ? redirectPath : `/${redirectPath}`;
|
||||
if (cartItems && cartItems.length > 0) {
|
||||
const join = redirect.includes("#") ? "&" : "#";
|
||||
redirect = `${redirect}${join}${GUEST_CART_URL_PARAM}=${encodeGuestCartForUrl(cartItems)}`;
|
||||
}
|
||||
const url = new URL("/login", CUSTOMER_ORIGIN);
|
||||
url.searchParams.set("redirect", redirect);
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
export function customerContinueCheckoutUrl(isAuthenticated: boolean, cartItems: GuestCartLine[] = []): string {
|
||||
if (isAuthenticated) {
|
||||
const url = new URL("/checkout/cart", CUSTOMER_ORIGIN);
|
||||
if (cartItems.length > 0) {
|
||||
url.hash = `${GUEST_CART_URL_PARAM}=${encodeGuestCartForUrl(cartItems)}`;
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
return customerLoginUrl("/checkout/cart", cartItems);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { API } from "./site";
|
||||
|
||||
export function getBearerToken(request: Request): string | null {
|
||||
const auth = request.headers.get("authorization");
|
||||
if (auth?.startsWith("Bearer ")) return auth.slice(7);
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function meshkeeFetch(
|
||||
path: string,
|
||||
init?: RequestInit & { token?: string | null },
|
||||
): Promise<{ ok: boolean; status: number; data: unknown }> {
|
||||
const headers = new Headers(init?.headers);
|
||||
if (!headers.has("Content-Type") && init?.body) {
|
||||
headers.set("Content-Type", "application/json");
|
||||
}
|
||||
if (init?.token) {
|
||||
headers.set("Authorization", `Bearer ${init.token}`);
|
||||
}
|
||||
|
||||
const res = await fetch(`${API.base}${path}`, {
|
||||
...init,
|
||||
headers,
|
||||
});
|
||||
|
||||
let data: unknown = null;
|
||||
try {
|
||||
data = await res.json();
|
||||
} catch {
|
||||
data = null;
|
||||
}
|
||||
|
||||
return { ok: res.ok, status: res.status, data };
|
||||
}
|
||||
|
||||
export function jsonResponse(data: unknown, status = 200) {
|
||||
return Response.json(data, { status });
|
||||
}
|
||||
|
||||
export function unauthorizedResponse() {
|
||||
return jsonResponse({ error: "Unauthorized" }, 401);
|
||||
}
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import {
|
||||
clearSharedAuthCookies,
|
||||
hydrateLocalTokensFromSharedCookies,
|
||||
SHARED_ACCESS_TOKEN_KEY,
|
||||
SHARED_REFRESH_TOKEN_KEY,
|
||||
writeSharedAuthCookies,
|
||||
} from "./shared-auth-cookie";
|
||||
|
||||
export type AuthBusinessMembership = {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
isOwner: boolean;
|
||||
teamRole: string | null;
|
||||
};
|
||||
|
||||
export type AuthUser = {
|
||||
id: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
cellNumber?: string;
|
||||
email?: string;
|
||||
roles?: string[];
|
||||
isSuperAdmin?: boolean;
|
||||
businesses?: AuthBusinessMembership[];
|
||||
};
|
||||
|
||||
type SessionContextValue = {
|
||||
user: AuthUser | null;
|
||||
isAuthenticated: boolean;
|
||||
ready: boolean;
|
||||
businessId: string;
|
||||
isWebsiteAdmin: boolean;
|
||||
logout: () => void;
|
||||
getAccessToken: () => string | null;
|
||||
};
|
||||
|
||||
function normalizeUser(raw: Partial<AuthUser> & { id?: string | number }): AuthUser | null {
|
||||
if (raw.id == null) return null;
|
||||
return {
|
||||
id: String(raw.id),
|
||||
firstName: raw.firstName ?? undefined,
|
||||
lastName: raw.lastName ?? undefined,
|
||||
cellNumber: raw.cellNumber ?? undefined,
|
||||
email: raw.email ?? undefined,
|
||||
roles: Array.isArray(raw.roles) ? raw.roles : undefined,
|
||||
isSuperAdmin: Boolean(raw.isSuperAdmin),
|
||||
businesses: Array.isArray(raw.businesses)
|
||||
? raw.businesses.map((business) => ({
|
||||
id: String(business.id),
|
||||
name: business.name,
|
||||
slug: business.slug,
|
||||
isOwner: Boolean(business.isOwner),
|
||||
teamRole: business.teamRole ?? null,
|
||||
}))
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function isWebsiteAdminForBusiness(user: AuthUser | null | undefined, businessId: string): boolean {
|
||||
if (!user || !businessId) return false;
|
||||
if (user.isSuperAdmin || user.roles?.includes("super_admin")) return true;
|
||||
return Boolean(
|
||||
user.businesses?.some(
|
||||
(business) => String(business.id) === String(businessId) && (business.isOwner || Boolean(business.teamRole)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const SessionContext = createContext<SessionContextValue | null>(null);
|
||||
|
||||
function readToken(key: string): string | null {
|
||||
try {
|
||||
return localStorage.getItem(key);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeToken(key: string, value: string | null) {
|
||||
try {
|
||||
if (value) localStorage.setItem(key, value);
|
||||
else localStorage.removeItem(key);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
export function SessionProvider({
|
||||
children,
|
||||
businessId,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
businessId: string;
|
||||
}) {
|
||||
const [user, setUser] = useState<AuthUser | null>(null);
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
const getAccessToken = useCallback(() => {
|
||||
hydrateLocalTokensFromSharedCookies(SHARED_ACCESS_TOKEN_KEY, SHARED_REFRESH_TOKEN_KEY);
|
||||
return readToken(SHARED_ACCESS_TOKEN_KEY);
|
||||
}, []);
|
||||
|
||||
const clearTokens = useCallback(() => {
|
||||
writeToken(SHARED_ACCESS_TOKEN_KEY, null);
|
||||
writeToken(SHARED_REFRESH_TOKEN_KEY, null);
|
||||
writeToken("accessToken", null);
|
||||
writeToken("meshkee_access_token", null);
|
||||
clearSharedAuthCookies();
|
||||
setUser(null);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const token = getAccessToken();
|
||||
if (!token) {
|
||||
setReady(true);
|
||||
return;
|
||||
}
|
||||
|
||||
const refresh = readToken(SHARED_REFRESH_TOKEN_KEY);
|
||||
writeSharedAuthCookies(token, refresh ?? undefined);
|
||||
|
||||
fetch("/api/auth/me", { headers: { Authorization: `Bearer ${token}` } })
|
||||
.then(async (res) => {
|
||||
if (res.status === 401) {
|
||||
clearTokens();
|
||||
return;
|
||||
}
|
||||
if (!res.ok) return;
|
||||
const data = (await res.json()) as { user?: AuthUser } & AuthUser;
|
||||
const next = normalizeUser(data.user ?? data);
|
||||
if (next) setUser(next);
|
||||
})
|
||||
.catch(() => undefined)
|
||||
.finally(() => setReady(true));
|
||||
}, [clearTokens, getAccessToken]);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
clearTokens();
|
||||
}, [clearTokens]);
|
||||
|
||||
const isWebsiteAdmin = useMemo(() => isWebsiteAdminForBusiness(user, businessId), [user, businessId]);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
user,
|
||||
isAuthenticated: Boolean(user),
|
||||
ready,
|
||||
businessId,
|
||||
isWebsiteAdmin,
|
||||
logout,
|
||||
getAccessToken,
|
||||
}),
|
||||
[user, ready, businessId, isWebsiteAdmin, logout, getAccessToken],
|
||||
);
|
||||
|
||||
return <SessionContext.Provider value={value}>{children}</SessionContext.Provider>;
|
||||
}
|
||||
|
||||
export function useSession() {
|
||||
const ctx = useContext(SessionContext);
|
||||
if (!ctx) throw new Error("useSession must be used within SessionProvider");
|
||||
return ctx;
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/** Shared auth cookies so storefront + customer.{domain} share one login. */
|
||||
|
||||
export const SHARED_ACCESS_TOKEN_KEY = "meshkee_customer_access_token";
|
||||
export const SHARED_REFRESH_TOKEN_KEY = "meshkee_customer_refresh_token";
|
||||
|
||||
const CHUNK_SIZE = 2800;
|
||||
const MAX_CHUNKS = 24;
|
||||
|
||||
function cookieDomain(): string | undefined {
|
||||
if (typeof window === "undefined") return undefined;
|
||||
const host = window.location.hostname.toLowerCase();
|
||||
if (host === "localhost" || host === "127.0.0.1") return undefined;
|
||||
const parts = host.split(".").filter(Boolean);
|
||||
if (parts.length < 2) return undefined;
|
||||
return `.${parts.slice(-2).join(".")}`;
|
||||
}
|
||||
|
||||
function readRawCookie(name: string): string | null {
|
||||
if (typeof document === "undefined") return null;
|
||||
const prefix = `${name}=`;
|
||||
const match = document.cookie.split("; ").find((row) => row.startsWith(prefix));
|
||||
if (!match) return null;
|
||||
return match.slice(prefix.length);
|
||||
}
|
||||
|
||||
function writeRawCookie(name: string, value: string | null) {
|
||||
if (typeof document === "undefined") return;
|
||||
const domain = cookieDomain();
|
||||
if (value == null) {
|
||||
let cookie = `${name}=; path=/; max-age=0; SameSite=Lax`;
|
||||
if (domain) cookie += `; domain=${domain}`;
|
||||
document.cookie = cookie;
|
||||
return;
|
||||
}
|
||||
const maxAge = 60 * 60 * 24 * 30;
|
||||
let cookie = `${name}=${value}; path=/; max-age=${maxAge}; SameSite=Lax`;
|
||||
if (domain) cookie += `; domain=${domain}`;
|
||||
document.cookie = cookie;
|
||||
}
|
||||
|
||||
function clearChunkedCookie(name: string) {
|
||||
writeRawCookie(name, null);
|
||||
const n = Number(readRawCookie(`${name}_n`) || "0");
|
||||
writeRawCookie(`${name}_n`, null);
|
||||
for (let i = 0; i < Math.max(n, MAX_CHUNKS); i++) {
|
||||
writeRawCookie(`${name}_${i}`, null);
|
||||
}
|
||||
}
|
||||
|
||||
function writeCookie(name: string, value: string | null) {
|
||||
clearChunkedCookie(name);
|
||||
if (value == null || value === "") return;
|
||||
|
||||
const encoded = encodeURIComponent(value);
|
||||
if (encoded.length <= 3500) {
|
||||
writeRawCookie(name, encoded);
|
||||
return;
|
||||
}
|
||||
|
||||
const chunks: string[] = [];
|
||||
for (let i = 0; i < encoded.length; i += CHUNK_SIZE) {
|
||||
chunks.push(encoded.slice(i, i + CHUNK_SIZE));
|
||||
}
|
||||
writeRawCookie(`${name}_n`, String(chunks.length));
|
||||
chunks.forEach((chunk, i) => writeRawCookie(`${name}_${i}`, chunk));
|
||||
}
|
||||
|
||||
function readCookie(name: string): string | null {
|
||||
const n = Number(readRawCookie(`${name}_n`) || "0");
|
||||
if (n > 0) {
|
||||
let encoded = "";
|
||||
for (let i = 0; i < n; i++) {
|
||||
const part = readRawCookie(`${name}_${i}`);
|
||||
if (part == null) return null;
|
||||
encoded += part;
|
||||
}
|
||||
try {
|
||||
return decodeURIComponent(encoded);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const raw = readRawCookie(name);
|
||||
if (raw == null) return null;
|
||||
try {
|
||||
return decodeURIComponent(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function writeSharedAuthCookies(accessToken: string, refreshToken?: string) {
|
||||
writeCookie(SHARED_ACCESS_TOKEN_KEY, accessToken);
|
||||
if (refreshToken) writeCookie(SHARED_REFRESH_TOKEN_KEY, refreshToken);
|
||||
}
|
||||
|
||||
export function clearSharedAuthCookies() {
|
||||
writeCookie(SHARED_ACCESS_TOKEN_KEY, null);
|
||||
writeCookie(SHARED_REFRESH_TOKEN_KEY, null);
|
||||
}
|
||||
|
||||
export function readSharedAccessToken(): string | null {
|
||||
return readCookie(SHARED_ACCESS_TOKEN_KEY);
|
||||
}
|
||||
|
||||
export function readSharedRefreshToken(): string | null {
|
||||
return readCookie(SHARED_REFRESH_TOKEN_KEY);
|
||||
}
|
||||
|
||||
export function hydrateLocalTokensFromSharedCookies(
|
||||
accessKey = SHARED_ACCESS_TOKEN_KEY,
|
||||
refreshKey = SHARED_REFRESH_TOKEN_KEY,
|
||||
): boolean {
|
||||
if (typeof window === "undefined") return false;
|
||||
if (localStorage.getItem(accessKey)) return false;
|
||||
const access = readSharedAccessToken();
|
||||
if (!access) return false;
|
||||
localStorage.setItem(accessKey, access);
|
||||
const refresh = readSharedRefreshToken();
|
||||
if (refresh) localStorage.setItem(refreshKey, refresh);
|
||||
return true;
|
||||
}
|
||||
+9
-3
@@ -1,16 +1,22 @@
|
||||
export const DOMAIN = "salarstore.com";
|
||||
export const DOMAIN = process.env.NEXT_PUBLIC_DOMAIN || "salarstore.com";
|
||||
|
||||
export const API = {
|
||||
base: "https://api.meshkee.com/api/v1",
|
||||
base: process.env.NEXT_PUBLIC_API_BASE_URL?.replace(/\/$/, "") || "https://api.meshkee.com/api/v1",
|
||||
domain: DOMAIN,
|
||||
};
|
||||
|
||||
export const CUSTOMER_ORIGIN =
|
||||
process.env.NEXT_PUBLIC_CUSTOMER_ORIGIN?.replace(/\/$/, "") || `https://customer.${DOMAIN}`;
|
||||
|
||||
export const BUSINESS_ORIGIN =
|
||||
process.env.NEXT_PUBLIC_BUSINESS_ORIGIN?.replace(/\/$/, "") || `https://business.${DOMAIN}`;
|
||||
|
||||
export const SITE = {
|
||||
nameFa: "سالار استور",
|
||||
nameEn: "SALAR STORE",
|
||||
tagline: "فروشگاه لوازم ورزشی و کوهنوردی",
|
||||
domain: DOMAIN,
|
||||
customerUrl: `https://customer.${DOMAIN}`,
|
||||
customerUrl: CUSTOMER_ORIGIN,
|
||||
phone: "09127491700",
|
||||
phoneDisplay: "0912 749 1700",
|
||||
address: "قم، بسیج (هنرستان)، نبش کوچه ۹",
|
||||
|
||||
Reference in New Issue
Block a user