class Dom {
static blockedAttrs = /^(on.*|style|title)$/i;
static urlAttrs = /^(href|src|action|formaction)$/i;
static safeUrl = /^(https?:|mailto:|tel:|\/|\.\/|\.\.\/|#|\?|[^:]*$)/i;
static fieldDefaults = { autocomplete: 'off', autocorrect: 'off', autocapitalize: 'off' };
static mediaDefaults = { playsinline: true, disablepictureinpicture: true, disableremoteplayback: true, controlslist: 'nodownload nofullscreen noremoteplayback' };
static defaults = { input: Dom.fieldDefaults, textarea: Dom.fieldDefaults, form: { novalidate: true, autocomplete: 'off' }, video: Dom.mediaDefaults, audio: Dom.mediaDefaults };
static el(tag, attrs = {}, children = []) {
const node = document.createElement(tag);
const merged = { ...(Dom.defaults[String(tag).toLowerCase()] || {}), ...attrs };
for (const [key, value] of Object.entries(merged)) {
if (value === null || value === undefined || value === false) continue;
if (key === 'text') node.textContent = String(value);
else if (key === 'dataset') Object.assign(node.dataset, value);
else if (key === 'class') node.className = value;
else if (Dom.blockedAttrs.test(key)) continue;
else if (Dom.urlAttrs.test(key) && !Dom.safeUrl.test(String(value).trim())) continue;
else node.setAttribute(key, value === true ? '' : String(value));
}
for (const child of [].concat(children)) {
if (child === null || child === undefined) continue;
node.append(typeof child === 'string' ? document.createTextNode(child) : child);
}
return node;
}
static clear(node) {
while (node.firstChild) node.removeChild(node.firstChild);
return node;
}
static closest(event, selector = '[data-action]') {
return event.target instanceof Element ? event.target.closest(selector) : null;
}
}
class Tokens {
static cache = new Map();
static get(name) {
if (Tokens.cache.has(name)) return Tokens.cache.get(name);
const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
if (value) Tokens.cache.set(name, value);
return value;
}
static ms(name) {
const raw = Tokens.get(name);
if (raw.endsWith('ms')) return parseFloat(raw) || 0;
if (raw.endsWith('s')) return (parseFloat(raw) || 0) * 1000;
return parseFloat(raw) || 0;
}
}
class Media {
static lists = new Map();
static query(q) {
if (!Media.lists.has(q)) Media.lists.set(q, window.matchMedia(q));
return Media.lists.get(q);
}
static matches(q) {
return Media.query(q).matches;
}
}
class Device {
static osNames = { ios: 'iOS', ipados: 'iPadOS', android: 'Android', tizen: 'Tizen', webos: 'webOS', macos: 'macOS', windows: 'Windows', chromeos: 'ChromeOS', linux: 'Linux', unknown: 'Unbekannt' };
static browserNames = { safari: 'Safari', chrome: 'Chrome', edge: 'Edge', firefox: 'Firefox', samsung: 'Samsung Internet', opera: 'Opera', uc: 'UC Browser', yandex: 'Yandex', huawei: 'Huawei Browser', miui: 'Mi Browser', unknown: 'Unbekannt' };
static engineNames = { webkit: 'WebKit', blink: 'Blink', gecko: 'Gecko', unknown: 'Unbekannt' };
static formNames = { phone: 'Smartphone', tablet: 'Tablet', desktop: 'Desktop', tv: 'TV' };
static tvPattern = /SMART-TV|SmartTV|Tizen|Web0S|webOS|BRAVIA|NetCast|HbbTV|AFT[A-Z]|CrKey|GoogleTV|Android ?TV|Roku|PlayStation|Xbox/i;
static sizes = [[600, 'compact'], [840, 'medium'], [Infinity, 'expanded']];
static browsers = [
['edge', /(?:Edg|EdgA|EdgiOS)\/(\d+)/],
['opera', /(?:OPR|OPT)\/(\d+)/],
['samsung', /SamsungBrowser\/(\d+)/],
['uc', /UCBrowser\/(\d+)/],
['yandex', /YaBrowser\/(\d+)/],
['huawei', /HuaweiBrowser\/(\d+)/],
['miui', /MiuiBrowser\/(\d+)/],
['firefox', /(?:Firefox|FxiOS)\/(\d+)/],
['chrome', /(?:Chrome|CriOS)\/(\d+)/],
['safari', /Version\/(\d+)[^]*Safari\//]
];
static inAppPattern = /FBAN|FBAV|Instagram|Line\/|MicroMessenger|TikTok|Snapchat|; wv\)/;
static watched = ['(pointer: coarse)', '(hover: hover)', '(display-mode: standalone)', '(prefers-reduced-motion: reduce)'];
static listeners = new Set();
static current = null;
static frame = 0;
static get ua() {
return navigator.userAgent || '';
}
static get touchPoints() {
return navigator.maxTouchPoints || 0;
}
static get info() {
if (!Device.current) Device.current = Device.detect();
return Device.current;
}
static os(ua, touchPoints) {
if (/iPad/.test(ua) || (/Macintosh/.test(ua) && touchPoints > 1 && !navigator.userAgentData)) return 'ipados';
if (/iPhone|iPod/.test(ua)) return 'ios';
if (/Tizen/.test(ua)) return 'tizen';
if (/Web0S|webOS/.test(ua)) return 'webos';
if (/Android/.test(ua)) return 'android';
if (/CrOS/.test(ua)) return 'chromeos';
if (/Windows/.test(ua)) return 'windows';
if (/Macintosh|Mac OS X/.test(ua)) return 'macos';
if (/Linux/.test(ua)) return 'linux';
return 'unknown';
}
static browser(ua) {
for (const [name, pattern] of Device.browsers) {
const match = ua.match(pattern);
if (match) return { name, version: parseInt(match[1], 10) || 0 };
}
return { name: 'unknown', version: 0 };
}
static engine(ua, os, browser) {
if (os === 'ios' || os === 'ipados' || browser === 'safari') return 'webkit';
if (browser === 'firefox') return 'gecko';
if (/Chrome\//.test(ua)) return 'blink';
if (/AppleWebKit/.test(ua)) return 'webkit';
return 'unknown';
}
static form(ua, os) {
if (Device.tvPattern.test(ua)) return 'tv';
if (os === 'ios') return 'phone';
if (os === 'ipados') return 'tablet';
if (os === 'android') return /Mobile/.test(ua) ? 'phone' : 'tablet';
return 'desktop';
}
static parse(ua, touchPoints) {
const os = Device.os(ua, touchPoints);
const browser = Device.browser(ua);
const engine = Device.engine(ua, os, browser.name);
const form = Device.form(ua, os);
return {
os,
osName: Device.osNames[os],
browser: browser.name,
browserName: Device.browserNames[browser.name],
version: browser.version,
engine,
engineName: Device.engineNames[engine],
form,
formName: Device.formNames[form],
inApp: Device.inAppPattern.test(ua)
};
}
static get lowPower() {
const connection = navigator.connection;
const memory = navigator.deviceMemory;
const cores = navigator.hardwareConcurrency;
return Boolean(connection && connection.saveData) || (typeof memory === 'number' && memory <= 2) || (typeof cores === 'number' && cores <= 2);
}
static size(width) {
return Device.sizes.find(([limit]) => width < limit)[1];
}
static screen() {
const width = Math.round(window.innerWidth || document.documentElement.clientWidth || 0);
const height = Math.round(window.innerHeight || document.documentElement.clientHeight || 0);
const dpr = Math.round((window.devicePixelRatio || 1) * 100) / 100;
return {
width,
height,
dpr,
physical: `${Math.round((window.screen ? window.screen.width : width) * dpr)}×${Math.round((window.screen ? window.screen.height : height) * dpr)}`,
orientation: width >= height ? 'landscape' : 'portrait',
size: Device.size(width)
};
}
static hardware() {
const connection = navigator.connection || null;
return {
cores: typeof navigator.hardwareConcurrency === 'number' ? navigator.hardwareConcurrency : null,
memory: typeof navigator.deviceMemory === 'number' ? navigator.deviceMemory : null,
network: connection && connection.effectiveType ? connection.effectiveType : null,
saveData: Boolean(connection && connection.saveData)
};
}
static tier(base, hardware) {
if (Device.lowPower || base.form === 'tv') return 'low';
const small = (hardware.cores !== null && hardware.cores <= 4) || (hardware.memory !== null && hardware.memory <= 3);
if (base.form === 'phone' && small) return 'low';
if (base.form === 'desktop' && (hardware.cores === null || hardware.cores >= 8)) return 'high';
return 'mid';
}
static detect() {
const base = Device.parse(Device.ua, Device.touchPoints);
const hardware = Device.hardware();
const screen = Device.screen();
return {
...base,
input: Media.matches('(pointer: coarse)') ? 'touch' : 'mouse',
hover: Media.matches('(hover: hover)'),
standalone: Media.matches('(display-mode: standalone)') || navigator.standalone === true,
lowPower: Device.lowPower,
dpr: screen.dpr,
screen,
hardware,
tier: Device.tier(base, hardware)
};
}
static apply() {
const info = Device.info;
const root = document.documentElement;
Object.assign(root.dataset, { os: info.os, browser: info.browser, engine: info.engine, form: info.form, input: info.input, perf: info.lowPower ? 'low' : 'normal', tier: info.tier, size: info.screen.size, orientation: info.screen.orientation, hover: info.hover ? 'yes' : 'no' });
root.toggleAttribute('data-standalone', info.standalone);
root.toggleAttribute('data-inapp', info.inApp);
}
static init() {
Device.apply();
for (const q of Device.watched) Media.query(q).addEventListener('change', () => Device.refresh());
if (navigator.connection && typeof navigator.connection.addEventListener === 'function') navigator.connection.addEventListener('change', () => Device.refresh());
window.addEventListener('resize', () => Device.resized(), { passive: true });
}
static resized() {
cancelAnimationFrame(Device.frame);
Device.frame = requestAnimationFrame(() => {
const before = Device.info.screen;
const now = Device.screen();
if (now.size === before.size && now.orientation === before.orientation && now.dpr === before.dpr) {
Device.current.screen = now;
return;
}
Device.refresh();
});
}
static refresh() {
Device.current = Device.detect();
Device.apply();
for (const listener of Device.listeners) listener(Device.current);
}
static onChange(listener) {
Device.listeners.add(listener);
return () => Device.listeners.delete(listener);
}
}
class Compat {
static checks = [
['dialog', () => typeof HTMLDialogElement === 'function' && typeof HTMLDialogElement.prototype.showModal === 'function'],
['animate', () => typeof Element.prototype.animate === 'function'],
['dvh', () => CSS.supports('height', '100dvh')],
['overscroll', () => CSS.supports('overscroll-behavior', 'none')],
['color-mix', () => CSS.supports('color', 'color-mix(in srgb, red 50%, blue)')],
['hasOwn', () => typeof Object.hasOwn === 'function'],
['replaceChildren', () => typeof Element.prototype.replaceChildren === 'function'],
['ResizeObserver', () => typeof ResizeObserver === 'function']
];
static backKeys = new Set(['GoBack', 'BrowserBack', 'XF86Back']);
static backCodes = new Set([461, 10009]);
static frame = 0;
static height = 0;
static result = null;
static get missing() {
if (!Compat.result) {
Compat.result = Compat.checks.filter(([, test]) => {
try {
return !test();
} catch {
return true;
}
}).map(([name]) => name);
}
return Compat.result;
}
static get supported() {
return Compat.missing.length === 0;
}
static get painted() {
return performance.getEntriesByName('first-contentful-paint').length > 0;
}
static init() {
window.addEventListener('scroll', () => window.scrollTo(0, 0), { passive: true });
const viewport = window.visualViewport;
if (viewport) viewport.addEventListener('resize', () => Compat.resize(viewport), { passive: true });
window.addEventListener('keydown', (event) => Compat.back(event), true);
}
static back(event) {
if (!Compat.backKeys.has(event.key) && !Compat.backCodes.has(event.keyCode)) return;
event.preventDefault();
event.stopImmediatePropagation();
(document.activeElement || document.body).dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', bubbles: true, cancelable: true }));
}
static resize(viewport) {
cancelAnimationFrame(Compat.frame);
Compat.frame = requestAnimationFrame(() => {
const height = Math.round(viewport.height);
if (height === Compat.height) return;
Compat.height = height;
document.documentElement.style.setProperty('--app-h', `${height}px`);
});
}
static showUnsupported() {
const target = document.querySelector('[data-role="page"]') || document.body;
Dom.clear(target);
target.append(Dom.el('div', { role: 'alert' }, [
Dom.el('div', { class: 'dos-line dos-line--error', text: 'This browser is not supported.' }),
Dom.el('div', { class: 'dos-line', text: 'Please use a current Safari, Chrome, Edge or Firefox.' })
]));
}
}
class BackGesture {
static stack = [];
static armed = false;
static leaving = false;
static bound = false;
static onRoute = null;
static bind() {
if (BackGesture.bound) return;
BackGesture.bound = true;
if ('scrollRestoration' in history) history.scrollRestoration = 'manual';
window.addEventListener('popstate', () => BackGesture.onPop());
}
static push(onBack) {
BackGesture.bind();
const entry = { onBack };
BackGesture.stack.push(entry);
BackGesture.sync();
return entry;
}
static release(entry) {
const index = BackGesture.stack.indexOf(entry);
if (index === -1) return;
BackGesture.stack.splice(index, 1);
BackGesture.sync();
}
static drop() {
const armed = BackGesture.armed && !BackGesture.leaving;
BackGesture.stack = [];
if (armed) BackGesture.armed = false;
return armed;
}
static sync() {
if (BackGesture.leaving) return;
if (BackGesture.stack.length && !BackGesture.armed) {
history.pushState({ layer: true }, '');
BackGesture.armed = true;
} else if (!BackGesture.stack.length && BackGesture.armed) {
BackGesture.leaving = true;
history.back();
}
}
static onPop() {
if (BackGesture.leaving) {
BackGesture.leaving = false;
BackGesture.armed = false;
BackGesture.sync();
return;
}
if (!BackGesture.armed) {
if (BackGesture.onRoute) BackGesture.onRoute();
return;
}
BackGesture.armed = false;
const entry = BackGesture.stack.pop();
if (entry) entry.onBack();
BackGesture.sync();
}
}
class Env {
static localHosts = new Set(['', 'localhost', '127.0.0.1', '::1', '[::1]']);
static privateHost = /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)|\.(local|localhost|test)$/;
static get development() {
const host = location.hostname;
return Env.localHosts.has(host) || Env.privateHost.test(host);
}
}
class BrowserLock {
static textTypes = new Set(['', 'text', 'search', 'email', 'password', 'tel', 'url', 'number']);
static editKeys = new Set(['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'Shift', 'CapsLock', 'Meta', 'Control', 'AltGraph', 'Dead', 'Process', 'Unidentified']);
static editShortcuts = new Set(['a', 'c', 'v', 'x', 'z', 'y']);
static devtoolsCodes = new Set(['KeyI', 'KeyJ', 'KeyC']);
static blocked = ['contextmenu', 'dragstart', 'dragover', 'drop', 'webkitmouseforcewillbegin', 'webkitmouseforcedown', 'gesturestart', 'gesturechange', 'gestureend'];
constructor() {
this.bind();
}
bind() {
const capture = { capture: true };
const active = { capture: true, passive: false };
document.addEventListener('keydown', (e) => { if (!this.allowsKey(e)) e.preventDefault(); }, capture);
document.addEventListener('cancel', (e) => e.preventDefault(), capture);
for (const type of BrowserLock.blocked) document.addEventListener(type, (e) => e.preventDefault(), active);
for (const type of ['mousedown', 'auxclick']) document.addEventListener(type, (e) => { if (e.button === 1) e.preventDefault(); }, capture);
document.addEventListener('click', (e) => { if (this.isModifiedLink(e)) e.preventDefault(); }, capture);
document.addEventListener('wheel', (e) => { if (e.ctrlKey) e.preventDefault(); }, active);
document.addEventListener('touchstart', () => {}, { capture: true, passive: true });
}
isModifiedLink(e) {
return (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) && e.target instanceof Element && e.target.closest('a') !== null;
}
field(target) {
if (!(target instanceof Element)) return null;
const el = target.closest('input, textarea, [contenteditable="true"]');
if (el instanceof HTMLInputElement && !BrowserLock.textTypes.has((el.getAttribute('type') || '').toLowerCase())) return null;
return el;
}
isDevKey(e) {
if (!Env.development) return false;
const code = e.code || '';
if (code === 'F12') return true;
if ((e.metaKey || e.ctrlKey) && e.shiftKey && code === 'KeyR') return true;
return BrowserLock.devtoolsCodes.has(code) && ((e.metaKey && e.altKey) || (e.ctrlKey && e.shiftKey));
}
allowsKey(e) {
const key = e.key || '';
if (this.isDevKey(e)) return true;
if (e.isComposing) return true;
const field = this.field(e.target);
if (!field) return false;
const altGraph = (typeof e.getModifierState === 'function' && e.getModifierState('AltGraph')) || (e.ctrlKey && e.altKey);
if ((e.metaKey || e.ctrlKey) && !(altGraph && key.length === 1)) {
return BrowserLock.editShortcuts.has(key.toLowerCase()) || key.startsWith('Arrow') || key === 'Backspace' || key === 'Delete';
}
if (key === 'Enter') return !(field instanceof HTMLInputElement);
if (BrowserLock.editKeys.has(key)) return true;
return key.length === 1;
}
}
class Animate {
static running = new WeakMap();
static get reduced() {
return Media.matches('(prefers-reduced-motion: reduce)') || Device.info.lowPower;
}
static ms(token) {
const value = Tokens.ms(Animate.reduced ? '--dur-instant' : token);
return value > 0 ? value : Tokens.ms('--dur-base');
}
static easing(token) {
const value = Tokens.get(token) || Tokens.get('--ease-standard');
return value.startsWith('cubic-bezier') || value.startsWith('linear') ? value : 'ease';
}
static stop(el) {
const current = Animate.running.get(el);
if (!current) return;
Animate.running.delete(el);
current.cancel();
}
static run(el, keyframes, { duration, easing, delay = 0 }) {
if (!(el instanceof Element)) return Promise.resolve(false);
Animate.stop(el);
if (!el.isConnected || duration <= 0) return Promise.resolve(true);
let animation;
try {
animation = el.animate(keyframes, { duration, easing, delay, fill: 'both' });
} catch {
return Promise.resolve(true);
}
Animate.running.set(el, animation);
return animation.finished.then(
() => {
if (Animate.running.get(el) !== animation) return false;
Animate.running.delete(el);
animation.cancel();
return true;
},
() => false
);
}
static show(el, { duration = '--dur-base', y = 0, scale = 1, delay = 0 } = {}) {
if (!(el instanceof Element)) return Promise.resolve(false);
el.hidden = false;
const moving = !Animate.reduced && (y !== 0 || scale !== 1);
const from = { opacity: 0, transform: moving ? `translateY(${y}px) scale(${scale})` : 'none' };
const to = { opacity: 1, transform: 'none' };
return Animate.run(el, [from, to], { duration: Animate.ms(duration), easing: Animate.easing('--ease-enter'), delay });
}
static hide(el, { duration = '--dur-fast' } = {}) {
if (!(el instanceof Element)) return Promise.resolve(false);
if (el.hidden) return Promise.resolve(true);
return Animate.run(el, [{ opacity: 1 }, { opacity: 0 }], { duration: Animate.ms(duration), easing: Animate.easing('--ease-exit') }).then((done) => {
if (done) el.hidden = true;
return done;
});
}
static collapse(el, open, { duration = '--dur-base' } = {}) {
if (!(el instanceof Element)) return Promise.resolve(false);
if (open) el.hidden = false;
const height = el.scrollHeight;
const frames = open ? [{ height: '0px' }, { height: `${height}px` }] : [{ height: `${height}px` }, { height: '0px' }];
el.style.overflow = 'hidden';
return Animate.run(el, frames, { duration: Animate.ms(duration), easing: Animate.easing('--ease-standard') }).then((done) => {
if (!Animate.running.has(el)) el.style.overflow = '';
if (done && !open) el.hidden = true;
return done;
});
}
static stagger(list, { duration = '--dur-base', y = 8, step = 30, max = 5 } = {}) {
const items = Array.from(list).filter((item) => item instanceof Element).slice(0, max);
return Promise.all(items.map((item, index) => Animate.show(item, { duration, y, delay: Animate.reduced ? 0 : index * step })));
}
static flicker(el) {
if (!(el instanceof Element) || Animate.reduced) return null;
Animate.stop(el);
const animation = el.animate([{ opacity: 1 }, { opacity: 0.86 }, { opacity: 1 }, { opacity: 0.93 }, { opacity: 1 }], { duration: 4200, iterations: Infinity, easing: 'linear' });
Animate.running.set(el, animation);
return animation;
}
static blink(el, on, off, period = 1060) {
if (!(el instanceof Element) || Animate.reduced) return null;
Animate.stop(el);
const animation = el.animate([on, off], { duration: period, iterations: Infinity, easing: 'steps(2, jump-none)' });
Animate.running.set(el, animation);
return animation;
}
}
class Store {
constructor(prefix) {
this.prefix = prefix;
}
key(name) {
return `${this.prefix}:${name}`;
}
get(name, fallback = null) {
try {
const raw = localStorage.getItem(this.key(name));
return raw === null ? fallback : JSON.parse(raw);
} catch {
return fallback;
}
}
set(name, value) {
try {
localStorage.setItem(this.key(name), JSON.stringify(value));
return true;
} catch {
return false;
}
}
remove(name) {
try {
localStorage.removeItem(this.key(name));
return true;
} catch {
return false;
}
}
}
class ApiError extends Error {
constructor(status, code, message, fields = {}) {
super(message);
this.status = status;
this.code = code;
this.fields = fields;
}
}
class Api {
static timeout = 15000;
static retryDelay = 800;
static maxBody = 2 * 1024 * 1024;
static encoder = new TextEncoder();
static csrfPattern = /(?:^|;\s*)(?:__Host-)?csrf=([^;]+)/;
static fallback = 'Request failed. Please try again.';
constructor(base = '/api') {
this.base = base;
this.pending = new Map();
this.latest = new Map();
this.onUnauthorized = null;
}
get token() {
const match = document.cookie.match(Api.csrfPattern);
return match ? decodeURIComponent(match[1]) : '';
}
get(path, options) {
return this.request('GET', path, undefined, options);
}
post(path, body, options) {
return this.request('POST', path, body, options);
}
static messages = {
aborted: 'Aborted.',
too_large: 'Request too large.',
offline: 'No network connection.',
timeout: 'Server not responding. Please try again.',
network: 'Server unreachable. Check the connection.'
};
static interrupted(reason) {
return reason === 'timeout' ? new ApiError(0, 'timeout', Api.messages.timeout) : new ApiError(0, 'aborted', Api.messages.aborted);
}
static retryable(error) {
return error.code === 'network' || error.code === 'timeout' || [502, 503, 504].includes(error.status);
}
static message(error) {
return error instanceof ApiError ? error.message : Api.fallback;
}
async request(method, path, body, { key = null, timeout = Api.timeout } = {}) {
const ticket = {};
if (key) this.latest.set(key, ticket);
const attempts = method === 'GET' ? 2 : 1;
try {
for (let attempt = 1; ; attempt += 1) {
try {
return await this.send(method, path, body, key, timeout);
} catch (error) {
if (attempt >= attempts || !Api.retryable(error)) throw error;
await new Promise((resolve) => setTimeout(resolve, Api.retryDelay));
if (key && this.latest.get(key) !== ticket) throw new ApiError(0, 'aborted', Api.messages.aborted);
}
}
} finally {
if (key && this.latest.get(key) === ticket) this.latest.delete(key);
}
}
static payload(body) {
if (body === undefined) return undefined;
const text = JSON.stringify(body);
if (text.length * 3 > Api.maxBody && Api.encoder.encode(text).length > Api.maxBody) throw new ApiError(413, 'too_large', Api.messages.too_large);
return text;
}
async send(method, path, body, key, timeout) {
if (!navigator.onLine) throw new ApiError(0, 'offline', Api.messages.offline);
const payload = Api.payload(body);
const controller = new AbortController();
if (key) {
const previous = this.pending.get(key);
if (previous) previous.abort('replaced');
this.pending.set(key, controller);
}
const timer = setTimeout(() => controller.abort('timeout'), timeout);
const headers = { Accept: 'application/json' };
if (body !== undefined) headers['Content-Type'] = 'application/json';
if (method !== 'GET') headers['X-CSRF-Token'] = this.token;
try {
const response = await fetch(`${this.base}${path}`, {
method,
headers,
body: payload,
credentials: 'same-origin',
cache: 'no-store',
signal: controller.signal
});
const data = await this.parse(response);
if (controller.signal.aborted) throw Api.interrupted(controller.signal.reason);
if (!response.ok) throw this.failure(response.status, data);
return data;
} catch (error) {
if (error instanceof ApiError) throw error;
if (controller.signal.aborted) throw Api.interrupted(controller.signal.reason);
throw new ApiError(0, 'network', Api.messages.network);
} finally {
clearTimeout(timer);
if (key && this.pending.get(key) === controller) this.pending.delete(key);
}
}
async parse(response) {
if (response.status === 204) return null;
if (!(response.headers.get('content-type') || '').includes('application/json')) return null;
try {
return await response.json();
} catch {
return null;
}
}
failure(status, data) {
const error = data && typeof data.error === 'object' && data.error ? data.error : {};
if (status === 401 && error.code === 'unauthorized' && this.onUnauthorized) this.onUnauthorized();
return new ApiError(status, error.code || 'http', error.message || Api.fallback, error.fields || {});
}
}
class Connection {
constructor(bar) {
this.bar = bar;
if (!this.bar) return;
window.addEventListener('online', () => this.sync());
window.addEventListener('offline', () => this.sync());
if (!navigator.onLine) this.sync();
}
sync() {
if (navigator.onLine) Animate.hide(this.bar);
else Animate.show(this.bar, { duration: '--dur-fast' });
}
}
class Theme {
static modes = ['light', 'dark', 'system'];
constructor(store) {
this.store = store;
this.mode = 'system';
this.metas = Array.from(document.querySelectorAll('meta[name="theme-color"]'), (meta) => ({
meta,
color: meta.getAttribute('content') || '',
scheme: (meta.getAttribute('media') || '').includes('dark') ? 'dark' : 'light'
}));
this.apply(this.store.get('theme', 'system'), false);
}
apply(mode, save = true) {
if (!Theme.modes.includes(mode)) mode = 'system';
if (mode === this.mode) return;
this.mode = mode;
if (mode === 'system') document.documentElement.removeAttribute('data-theme');
else document.documentElement.dataset.theme = mode;
if (save) this.store.set('theme', mode);
this.syncBrowserColor();
}
get effective() {
if (this.mode !== 'system') return this.mode;
return Media.matches('(prefers-color-scheme: dark)') ? 'dark' : 'light';
}
syncBrowserColor() {
const forced = this.metas.find((item) => item.scheme === this.mode);
for (const item of this.metas) item.meta.setAttribute('content', forced ? forced.color : item.color);
}
toggle() {
this.apply(this.effective === 'dark' ? 'light' : 'dark');
}
}
class Layer {
constructor() {
this.timers = new Map();
}
schedule(key, fn, ms) {
this.unschedule(key);
this.timers.set(key, setTimeout(() => {
this.timers.delete(key);
fn();
}, ms));
}
unschedule(key) {
const timer = this.timers.get(key);
if (timer === undefined) return;
clearTimeout(timer);
this.timers.delete(key);
}
closeButton(action, className) {
return Dom.el('button', { class: className, type: 'button', 'aria-label': 'Close', dataset: { action }, text: '×' });
}
delegate(root, handlers) {
root.addEventListener('click', (e) => {
const btn = Dom.closest(e);
if (!btn) return;
const handler = handlers[btn.dataset.action];
if (handler) handler(btn, e);
});
}
}
class Toast extends Layer {
static tones = ['info', 'success', 'warning', 'danger'];
constructor(region) {
super();
this.region = region;
this.max = 3;
this.durations = { info: 4000, success: 4000, warning: 6000, danger: 0 };
if (this.region) this.delegate(this.region, { 'toast-close': (btn) => this.dismiss(btn.closest('.toast')) });
}
show(text, tone = 'info') {
if (!this.region) return null;
if (!Toast.tones.includes(tone)) tone = 'info';
const active = Array.from(this.region.children).filter((item) => !item.dataset.leaving);
for (const old of active.slice(0, Math.max(0, active.length - this.max + 1))) this.dismiss(old);
const el = Dom.el('div', { class: 'toast', role: tone === 'danger' ? 'alert' : 'status', dataset: { tone } }, [Dom.el('span', { class: 'toast__text', text }), this.closeButton('toast-close', 'toast__close')]);
this.region.append(el);
Animate.show(el, { y: 8 });
const ms = this.durations[tone];
if (!ms) return el;
const start = () => this.schedule(el, () => this.dismiss(el), ms);
const pause = () => this.unschedule(el);
el.addEventListener('pointerenter', pause);
el.addEventListener('pointerleave', start);
el.addEventListener('focusin', pause);
el.addEventListener('focusout', start);
start();
return el;
}
dismiss(el) {
if (!(el instanceof Element)) return Promise.resolve(false);
this.unschedule(el);
if (!el.isConnected || el.dataset.leaving) return Promise.resolve(false);
el.dataset.leaving = 'true';
return Animate.hide(el).then((done) => {
if (done) el.remove();
return done;
});
}
}
class View {
constructor(app, params = {}) {
this.app = app;
this.params = params;
}
get title() {
return '';
}
get actions() {
return {};
}
async build() {
return Dom.el('div');
}
leave() {}
}
class Router {
constructor(app, outlet) {
this.app = app;
this.outlet = outlet;
this.routes = [];
this.fallback = View;
this.view = null;
this.ticket = 0;
this.base = document.title;
}
add(pattern, view, { params = {} } = {}) {
const keys = [];
const source = pattern.replace(/\/:([a-z_]+)/gi, (_, key) => {
keys.push(key);
return '/([^/]+)';
});
this.routes.push({ view, keys, params, regex: new RegExp(`^${source === '/' ? '' : source}/?$`) });
return this;
}
missing(view) {
this.fallback = view;
return this;
}
start() {
BackGesture.onRoute = () => this.render();
BackGesture.bind();
document.addEventListener('click', (e) => this.intercept(e));
return this.render();
}
intercept(e) {
if (e.defaultPrevented) return;
const link = Dom.closest(e, 'a[href]');
if (!link || link.target || link.hasAttribute('download') || link.hasAttribute('data-external')) return;
const url = new URL(link.href, location.href);
if (url.origin !== location.origin || url.pathname.startsWith('/api/')) return;
e.preventDefault();
this.go(url.pathname + url.search);
}
go(path, { replace = false } = {}) {
if (this.dismiss()) history.replaceState(null, '', path);
else if (path !== location.pathname + location.search) history[replace ? 'replaceState' : 'pushState'](null, '', path);
return this.render();
}
dismiss() {
return BackGesture.drop();
}
match(path) {
for (const route of this.routes) {
const found = path.match(route.regex);
if (!found) continue;
try {
return { route, params: Object.fromEntries(route.keys.map((key, index) => [key, decodeURIComponent(found[index + 1])])) };
} catch {
break;
}
}
return { route: { view: this.fallback, params: {} }, params: {} };
}
async render() {
const ticket = ++this.ticket;
const { route, params } = this.match(location.pathname);
const view = new route.view(this.app, { ...Object.fromEntries(new URLSearchParams(location.search)), ...params, ...route.params });
let node;
try {
node = await view.build();
} catch (error) {
node = this.failure(error);
}
if (ticket !== this.ticket) {
view.leave();
return;
}
if (this.view) this.view.leave();
this.view = view;
Dom.clear(this.outlet).append(node);
document.title = view.title ? `${view.title} · ${this.base}` : this.base;
const main = this.outlet.closest('.shell-main');
if (main) main.scrollTop = 0;
Animate.show(this.outlet, { y: 6 });
}
failure(error) {
return Terminal.line(`ERROR: ${Api.message(error)}`, 'error');
}
}
class UI {
constructor(app) {
this.app = app;
this.toast = new Toast(document.querySelector('[data-role="toast-region"]'));
}
bind() {
document.addEventListener('click', (e) => {
const target = Dom.closest(e);
if (!target || target.closest('dialog') || target.closest('[data-role="toast-region"]')) return;
Promise.resolve()
.then(() => this.app.dispatch(target.dataset.action, target, e))
.catch((error) => this.fail(error));
});
}
fail(error) {
if (error instanceof ApiError && error.code === 'aborted') return;
this.toast.show(Api.message(error), 'danger');
}
}
class Terminal {
static line(text, kind = '') {
return Dom.el('div', { class: kind ? `dos-line dos-line--${kind}` : 'dos-line', text });
}
static prompt(label, onEnter) {
const input = Dom.el('input', { type: 'text', name: 'command', autocomplete: 'off', maxlength: '4096', 'aria-label': label });
const before = Dom.el('span');
const cursor = Dom.el('span', { class: 'dos-cursor', text: ' ' });
const after = Dom.el('span');
const form = Dom.el('form', { class: 'dos-input' }, [Dom.el('span', { text: label }), before, cursor, after, input]);
const sync = () => {
const value = input.value;
const at = input.selectionStart ?? value.length;
const next = before.textContent !== value.slice(0, at) || after.textContent !== value.slice(at + 1);
if (!next && cursor.textContent === (value[at] || ' ')) return;
before.textContent = value.slice(0, at);
cursor.textContent = value[at] || ' ';
after.textContent = value.slice(at + 1);
};
for (const type of ['input', 'keyup', 'select', 'click']) input.addEventListener(type, sync, { passive: true });
input.addEventListener('focus', () => {
cursor.classList.add('dos-cursor--on');
const green = Tokens.get('--color-primary');
const dark = Tokens.get('--color-bg');
Animate.blink(cursor, { backgroundColor: green, color: dark }, { backgroundColor: 'transparent', color: green });
}, { passive: true });
input.addEventListener('blur', () => {
cursor.classList.remove('dos-cursor--on');
Animate.stop(cursor);
}, { passive: true });
form.addEventListener('submit', (event) => {
event.preventDefault();
onEnter(input);
sync();
});
input.addEventListener('keydown', (event) => {
if (event.key !== 'Enter' || event.isComposing) return;
event.preventDefault();
form.requestSubmit();
});
return { form, input };
}
}
class Screen {
constructor() {
this.log = Dom.el('div', { role: 'log', 'aria-live': 'polite' });
}
write(text = '', kind = '') {
this.log.append(Terminal.line(text, kind));
this.log.lastChild.scrollIntoView({ block: 'end' });
}
clear() {
Dom.clear(this.log);
}
}
class Shell {
static prompt = 'AIRust>';
static aliases = { '?': 'HELP', CLEAR: 'CLS' };
constructor(app, screen) {
this.app = app;
this.screen = screen;
this.chatId = null;
this.commands = {
HELP: { usage: 'HELP, ?', text: 'Show this list.', takes: false, run: () => this.help() },
CLS: { usage: 'CLS, CLEAR', text: 'Clear the screen.', takes: false, run: () => this.screen.clear() },
VER: { usage: 'VER', text: 'Show the AIRust version.', takes: false, run: () => this.version() },
STATUS: { usage: 'STATUS', text: 'Show the active agent and the knowledge size.', takes: false, run: () => this.status() },
KB: { usage: 'KB [filter]', text: 'List knowledge entries (first 20), optionally filtered.', takes: true, run: (rest) => this.knowledge(rest) },
NEW: { usage: 'NEW', text: 'Start a new conversation.', takes: false, run: () => this.restart() },
ASK: { usage: 'ASK <text>', text: 'Ask AIRust a question, also a single word.', takes: true, run: (rest) => this.askCommand(rest) }
};
}
boot() {
this.screen.log.append(Dom.el('img', { class: 'dos-bootlogo', src: '/logo.png', alt: '' }));
this.version();
this.screen.write('(C) LEVOGNE. Knowledge engine ready.');
this.screen.write();
this.screen.write('Type HELP for commands, or just ask a question.');
this.screen.write();
}
find(line) {
const [word, ...rest] = line.split(/\s+/);
const upper = word.toUpperCase();
const name = Shell.aliases[upper] || upper;
const command = this.commands[name];
if (command && !command.takes && rest.length) return { error: `Invalid parameter - ${name} takes no parameters.` };
if (command) return { command, rest: rest.join(' ') };
if (!rest.length && !line.endsWith('?')) return { error: 'Bad command or file name. Type HELP for commands.' };
return null;
}
async execute(line) {
this.screen.write(`${Shell.prompt}${line}`);
const found = this.find(line);
try {
if (found && found.error) this.screen.write(found.error);
else if (found) await found.command.run(found.rest);
else await this.ask(line);
} catch (error) {
this.screen.write(`ERROR: ${Api.message(error)}`, 'error');
}
if (this.screen.log.childElementCount) this.screen.write();
}
help() {
this.screen.write('AIRust commands:');
for (const command of Object.values(this.commands)) this.screen.write(` ${command.usage.padEnd(14)}${command.text}`);
this.screen.write(` ${'<question>'.padEnd(14)}Several words or a closing "?" are asked directly.`);
}
async askCommand(text) {
if (!text) {
this.screen.write('Required parameter missing - ASK <question>.');
return;
}
await this.ask(text);
}
version() {
this.screen.write(`AIRust Version ${document.documentElement.dataset.version || ''}`);
}
async status() {
const status = await this.app.api.get('/status', { key: 'status' });
this.screen.write(`Agent ${status.agent}`);
this.screen.write(`Examples ${status.examples}`);
this.screen.write(`Session ${this.chatId === null ? 'not started' : `#${this.chatId}`}`);
}
async knowledge(filter) {
const query = new URLSearchParams({ limit: '20', offset: '0' });
if (filter) query.set('search', filter);
const page = await this.app.api.get(`/knowledge?${query}`, { key: 'knowledge' });
for (const entry of page.entries) this.screen.write(`${String(entry.index).padStart(5, '0')} ${entry.input} -> ${entry.output}`);
this.screen.write(`${page.filtered} of ${page.total} entries${filter ? ` matching "${filter}"` : ''}${page.filtered > page.entries.length ? `, first ${page.entries.length} shown` : ''}`, 'meta');
}
restart() {
this.chatId = null;
this.screen.write('New conversation started.');
}
async ask(text) {
if (this.chatId === null) {
const chat = await this.app.api.post('/chats', { title: text.slice(0, 60) });
this.chatId = chat.id;
}
const answer = await this.app.api.post('/query', { input: text, chat_id: this.chatId });
this.screen.write(answer.response);
this.screen.write(`[${answer.agent} ${Math.round(answer.confidence * 100)}%]`, 'meta');
}
}
class TerminalView extends View {
async build() {
this.screen = new Screen();
this.shell = new Shell(this.app, this.screen);
this.shell.boot();
const { form, input } = Terminal.prompt(Shell.prompt, (field) => this.submit(field));
this.input = input;
requestAnimationFrame(() => input.focus());
return Dom.el('div', {}, [this.screen.log, form]);
}
async submit(field) {
const line = field.value.trim();
field.value = '';
if (this.busy) return;
if (!line) {
this.screen.write(Shell.prompt);
return;
}
this.busy = true;
try {
await this.shell.execute(line);
} finally {
this.busy = false;
field.focus();
field.scrollIntoView({ block: 'end' });
}
}
}
class Focus {
constructor(app) {
this.app = app;
}
bind() {
const target = () => this.app.router.view && this.app.router.view.input;
document.addEventListener('click', () => {
if (String(window.getSelection()).length) return;
const input = target();
if (input) input.focus();
}, { passive: true });
document.addEventListener('keydown', (event) => {
const input = target();
if (input && document.activeElement !== input && event.key.length === 1 && !event.metaKey && !event.ctrlKey) input.focus();
}, { passive: true });
}
}
class App {
constructor() {
Device.init();
Compat.init();
this.lock = new BrowserLock();
this.store = new Store('airust');
this.theme = new Theme(this.store);
this.theme.apply('dark', false);
this.api = new Api();
this.connection = new Connection(document.querySelector('[data-role="offline"]'));
this.ui = new UI(this);
this.focus = new Focus(this);
this.router = new Router(this, document.querySelector('[data-role="page"]'));
this.routes();
}
get name() {
return this.router.base;
}
routes() {
this.router.add('/', TerminalView).missing(TerminalView);
}
get actions() {
return {};
}
async dispatch(name, target, event) {
const view = this.router.view;
const handler = (view && view.actions[name]) || this.actions[name];
if (!handler) {
this.ui.toast.show(`Unknown action: ${name}`, 'warning');
return;
}
await handler(target, event);
}
async start() {
if (!Compat.supported) {
Compat.showUnsupported();
return;
}
this.ui.bind();
this.focus.bind();
Animate.flicker(document.querySelector('[data-role="crt"]'));
await this.router.start();
}
}
new App().start();