/** * Server / venue configuration — the single place that knows WHERE the backend is. * * Two ways the waiter app runs: * * 1. Served by the venue's own server (https domain, or plain http://). * No venue is configured → every URL is same-origin and storage uses the * original un-prefixed keys. Behaviour is identical to before venues existed, * so existing installs keep their token and offline queue across the update. * * 2. Bundled in the native app (Capacitor), or a dev build with VITE_SERVER_URL. * An active venue { siteId, name, baseUrl } → absolute URLs to that server, * and all persistent storage (token, IndexedDB, per-venue prefs) is namespaced * by siteId so several venues can live side by side on one phone. * * The active venue is resolved ONCE at module load. Switching venue reloads the * app so every module-level singleton (Dexie db, auth store, persisted stores) * re-initialises against the new namespace — no half-switched state. */ const VENUES_KEY = 'xenia.venues' export const APPLY_BUNDLE_NOW_KEY = 'xenia.applyBundleNow' function normalizeBaseUrl(url) { const trimmed = String(url || '').trim().replace(/\/+$/, '') if (!/^https?:\/\/[^/]+/i.test(trimmed)) { throw new Error(`Invalid server URL: "${url}" (expected http(s)://host[:port])`) } return trimmed } function readState() { try { const parsed = JSON.parse(localStorage.getItem(VENUES_KEY) || 'null') if (parsed && typeof parsed === 'object') { return { active: parsed.active ?? null, venues: parsed.venues ?? {} } } } catch { // corrupted or unavailable storage — fall through to empty state } return { active: null, venues: {} } } function writeState(state) { localStorage.setItem(VENUES_KEY, JSON.stringify(state)) } function resolveActiveVenue() { // Dev convenience: point a `npm run dev` build at a real server on the LAN. // Deliberately DEV-only — a URL/query-controlled server in production would let // a crafted link send waiters' PINs to someone else's machine. const devUrl = import.meta.env.DEV ? import.meta.env.VITE_SERVER_URL : '' if (devUrl) { return { siteId: 'dev', name: 'Dev server', baseUrl: normalizeBaseUrl(devUrl) } } const { active, venues } = readState() return (active && venues[active]) || null } const ACTIVE_VENUE = resolveActiveVenue() // ── Reading ─────────────────────────────────────────────────────────────────── /** The venue this app instance is talking to, or null when running same-origin. */ export function getActiveVenue() { return ACTIVE_VENUE } /** All paired venues (used by the venue switcher). */ export function listVenues() { return Object.values(readState().venues) } /** Base URL for REST calls: '' (same-origin) or 'http(s)://host[:port]'. */ export function apiBase() { return ACTIVE_VENUE?.baseUrl ?? '' } /** Absolute ws(s):// URL for a backend path such as '/api/ws/connect?token=…'. */ export function wsUrl(path) { if (ACTIVE_VENUE) { return ACTIVE_VENUE.baseUrl.replace(/^http/i, 'ws') + path } const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:' return `${protocol}//${window.location.host}${path}` } /** * URL for a backend-served asset (product images, avatars). The backend returns * root-relative paths like '/static/product_images/x.jpg'; in native mode those * must point at the venue server, not at the app bundle. */ export function assetUrl(url) { if (!url || !ACTIVE_VENUE) return url if (/^(https?:|data:|blob:)/i.test(url)) return url return url.startsWith('/') ? ACTIVE_VENUE.baseUrl + url : url } /** * localStorage key for per-venue data. Same-origin mode keeps the original * un-prefixed key so existing installs don't lose their session. */ export function storageKey(name) { return ACTIVE_VENUE ? `xenia:${ACTIVE_VENUE.siteId}:${name}` : name } /** IndexedDB (Dexie) database name — the original name in same-origin mode. */ export function dbName() { return ACTIVE_VENUE ? `pos_snapshot__${ACTIVE_VENUE.siteId}` : 'pos_snapshot' } /** * How the app is being delivered: * 'native' — inside the Capacitor app * 'secure-web' — https (or localhost): service worker, installable PWA * 'plain-web' — plain http://: no service worker, no real install */ export function deliveryMode() { if (window.Capacitor?.isNativePlatform?.()) return 'native' return window.isSecureContext ? 'secure-web' : 'plain-web' } // ── Writing (used by pairing / venue switcher in the native app) ───────────── /** * Add or update a paired venue without switching to it. Fields not passed are * kept (e.g. `bundleVersion`, remembered by src/native/bundles.js). * `spki` = the server's TLS public-key pin (native app, plan step 7). */ export function saveVenue({ siteId, name, baseUrl, spki, bundleVersion }) { if (!siteId) throw new Error('saveVenue: siteId is required') const state = readState() const prev = state.venues[siteId] || {} state.venues[siteId] = { ...prev, siteId, name: name || prev.name || siteId, baseUrl: normalizeBaseUrl(baseUrl || prev.baseUrl), ...(spki ? { spki } : {}), ...(bundleVersion ? { bundleVersion } : {}), } writeState(state) return state.venues[siteId] } /** Make a paired venue active and reload the app into it. */ export function switchVenue(siteId) { const state = readState() if (!state.venues[siteId]) throw new Error(`switchVenue: unknown venue ${siteId}`) state.active = siteId writeState(state) // Nobody is mid-service right after a switch: the venue's own UI bundle may be // applied immediately on the next start (src/native/bundles.js) try { sessionStorage.setItem(APPLY_BUNDLE_NOW_KEY, '1') } catch { // storage unavailable — the bundle is then applied at the next background/restart } window.location.replace('/') } /** * Forget a paired venue. Its namespaced storage and IndexedDB are left in place * on purpose — they may hold unsynced offline orders. Cleanup is an explicit, * separate action (see the native app's venue manager). */ export function removeVenue(siteId) { const state = readState() delete state.venues[siteId] if (state.active === siteId) state.active = null writeState(state) }