{"version":3,"file":"study_imagine_script.min.js","names":["el","isEmbedded","__classPrivateFieldGet","__classPrivateFieldSet","retryDelay","GROUP_NOTICE_KEY","sessionStore","sleep","retryDelay","IDENTITY_KEY","storageOrNull","isEmbedded","formatDateTime","formatDateTimeIn","el","el","appConnection","el","connection","el","el","el","el","el$1","children","node","tag","key","value","attrs","child","clear","createNotifier","timer","message","kind","formatBytes","bytes","lang","number","digits","field","id","control","labelText","hint","select","optionValue","label","options","isEmbedded$1","loc","themeFromSearch","applyEmbedTheme","theme","themeFromMessage","data","type","followLessonTheme","target","event","_typeof","o","toPrimitive","t","e","i","r","toPropertyKey","_defineProperty","_checkPrivateRedeclaration","_classPrivateMethodInitSpec","a","_classPrivateFieldInitSpec","_assertClassBrand","_classPrivateFieldSet2","s","_classPrivateFieldGet2","ApiError","detail","status","code","HEADER_PASSWORD","HEADER_ADMIN","HEADER_TOKEN","_passwordKey","_adminKey","_storage$1","_fetch","_extraHeaders","_WorkshopClient_brand","WorkshopClient","extra","input","init","_importLegacyPassword","path","password","probePath","error","isPasswordError","isAdminPasswordError","headers","body","admin","response","text","record","firstFieldError","legacyKey","old","EMPTY","_key","_app","_storage","_memory","_IdentityStore_brand","IdentityStore","_importLegacy","_load","identity","name","_save","_mine","m","upper","entry","membership","_same","groupName","participantName","held","workshop","registration","_gone","rest","attendees","tokens","token","_old","_read","raw","storage","parsed","legacy","imported","own","_appOf","b","_GroupsApi_brand","GroupsApi","client","_group","patch","registrationBody","attendee","query","participantId","isRegistrationError","normaliseCode","_groupLabel","_pollTimer","_WorkshopSession_brand","WorkshopSession","group","handler","fn","settings","asked","f","kept","fields","clean","creatorName","_registrationToSend","result","_attendeeToSend","_forgetRefused","_adopt","existing","elsewhere","_join","mine","active","stale","intervalMs","participant","joinCodeFromLocation","search","direct","params","__classPrivateFieldGet$1","state","receiver","__classPrivateFieldSet$1","_Connection_failures","OUTAGE_CODE","RETRY_MIN_MS","RETRY_MAX_MS","FRONT_STATUSES","isFrontStatus","retryDelay$1","failures","min","max","Connection","connection","isOutage","jsonOf","fromFront","v","outageResponse","isGet","watchConnection","line","timeoutMs","request","abort","base","connectionNotice","online","TEAM_API","TEAM_APP","HEADER_PARTICIPANT_TOKENS","store","adoptMemberships","joinedAt","memberships","app","membershipsOf","toolTokens","forgetTeam","apps","shared","teamClient","join","GROUP_NOTICE_KEY$1","FOLLOW_TEXTS","followTexts","sessionStore$1","setGroupNotice","teamToken","followMember","found","texts","notices","setGroupsFlashText","team","BASE_API","ACCESS_PROBE","ONLY_PASSWORD","serverAway","sleep$1","resolve","ms","shellDataset","readEntryConfig","fromPath","derived","safeNext","char","addressWithoutJoin","groupsAddress","groupsUrl","next","groupPageUrl","config","activeGroupCode","session","accessClient","hasAccess","resolved","url","requireAccess","go","GROUPS_FLASH_KEY","flashStore","setGroupsFlash","leaveForGroups","followOrLeave","follow","where","address","requireGroup","joinCode","retries","wait","delay","workshopsKey","identityKey","normaliseWorkshop","slug","localStore","readMap","workshopOf","rememberWorkshop","map","storedActiveCode","activeCode","pageWorkshop","given","searchWithWorkshop","WORKSHOP_PATH","addressInWorkshop","match","pathname","SWITCH_KEY","storageOrNull$1","followedKeys","keys","rememberKey","known","switchTarget","answer","pollSwitch","fetcher","args","startSwitchPoll","THEME_KEY","LANG_KEY","IDENTITY_KEY","GROUP_NOTICE_KEY","TEXT","LANGUAGE_NAMES","ICON_LANGUAGE","ICON_MENU","ICON_APPS","ICON_THEME","counter","languageName","el","className","currentTheme","explicit","toggleTheme","applyStoredTheme","stored","urlTheme","location","isEmbedded","keepEmbed","href","hash","parentRoot","applyParentTheme","languageUrl","parts","langs","activeTeamCode","storageOrNull","appHref","joined","readShellApps","host","item","readGroupsUrl","groupPageHref","takeGroupNotice","sessionOrNull","isActive","link","route","mountAppbar","current","switchWorkshop","stopSwitch","navId","header","menuButton","langMenu","appMenu","appNodes","shellApps","notice","linkNodes","langNodes","setOpen","open","refreshLangLinks","markLinks","place","embedded","main","refreshAppLinks","render","embed","brand","wordmarkHref","title","groupHref","chip","links","nav","actions","tools","menu","here","summary","panel","home","heading","codeLabel","meta","toggle","noticeLine","said","close","onKey","onOutside","syncTheme","onStorage","onMessage","observer","root","changes","staffFromDataset","csrfFromDataset","SAFE_METHODS","csrfHeader","method","withCsrf","MOUNT_ID","mountElement","appRoot","pageSearch","readShellConfig","pageLang","followed","readConfig","shell","asLang","pickText","localeOf","formatDateTime$1","date","isoDate","getLang","pick","STRINGS","generationError","formatDateTime","sessionStore","searchWithout","names","pathNamesWorkshop","withWorkshop","carryWorkshop","qrUrl","groups","createLaunchPrompt","promptFromSearch","stashLaunchPrompt","prompt","replace","takeLaunchPrompt","pendingLaunchPrompt","clearLaunchPrompt","lessonBanner","instruction","banner","doc","labels","dismiss","currentPath","onNavigate","setNavigator","givenName","trimmed","inJoinOrder","participants","stillMember","createMemberRules","numberedLabel","index","memberLabel","ordered","applyMemberRules","row","list","staff","meId","remove","createAppSession","followGroupWorkshops","assign","forgetMembership","watchMembership","onGone","ENGLISH_DETAILS","BUSY_RETRY_MS","retryDelay","seconds","bodyOf","sleep","createApiErrors","generic","translate","english","ambiguous","listeners","isCode","codeOf","pattern","codeText","apiErrorCode","errorText","onApiCode","listener","withApiErrors","notify","apiFetch","watch","workshopHeaders","resolveUrl","rawHeaders","rawFetch","failure","api","file","publicId","setFlash","noticePanel","action","closedPanel","unknownWorkshopPanel","patchBoard","follower","isReloading","dropMembership","LANGS","bar","appbar","embedNav","draw","groupPage","items","mountChrome","fragment","BACK_FLASH_MS","mountConnectionBanner","spinner","backTimer","clearBack","show","connection$1","offChange","onNetwork","showEntryWait","joinName","dropPlaceholderName","createRoute","navigation","deps","renderDownloads","payload","rank","entries","extensionOf","renderHistory","runs","run","runCard","qualityLabel","quality","runFacts","facts","outcome","frames","image","POLL_IDLE_MS","POLL_BUSY_MS","SAVE_DEBOUNCE_MS","renderStudio","controls","results","capabilities","refreshError","lost","lastBoard","board","debounced","save","savePrompt","roomProvider","aspects","fallbackAspect","aspect","aspectPicker","qualityPicker","negative","saveNegative","seed","saveSeed","generateButton","start","uploadInput","uploadButton","referenceHost","renderedReference","renderReference","reference","upload","qualityField","negativeField","launchPrompt","syncControls","idle","has","picker","option","seedValue","busy","started","generation","reportFinished","startError","schedulePoll","revealResults","watching","latest","renderedFrom","signature","force","runningCard","imageGrid","refineCard","runTitle","count","elapsed","tick","aspectStyle","grid","images","isSelected","selectedId","figure","promptLine","choose","deleteButton","size","button","refineChanges","vary","pollTimer","polling","offRestored","busyNow","poll","w","h","stopped","view"],"sources":["../../../../../../node_modules/@starling-study/study-base/dist/lib/dom.js","../../../../../../node_modules/@starling-study/study-base/dist/lib/embed.js","../../../../../../node_modules/@starling-cloud/sturnia-workshop/dist/client/client.js","../../../../../../node_modules/@starling-cloud/sturnia-workshop/dist/client/identity.js","../../../../../../node_modules/@starling-cloud/sturnia-workshop/dist/client/groups.js","../../../../../../node_modules/@starling-cloud/sturnia-workshop/dist/client/session.js","../../../../../../node_modules/@starling-cloud/sturnia-workshop/dist/client/boot.js","../../../../../../node_modules/@starling-study/study-base/dist/lib/connection.js","../../../../../../node_modules/@starling-study/study-base/dist/lib/team.js","../../../../../../node_modules/@starling-study/study-base/dist/lib/entry.js","../../../../../../node_modules/@starling-study/study-base/dist/lib/workshops.js","../../../../../../node_modules/@starling-study/study-base/dist/appbar/switch.js","../../../../../../node_modules/@starling-study/study-base/dist/appbar/appbar.js","../../../../../../node_modules/@starling-study/study-base/dist/lib/access.js","../../../../../../node_modules/@starling-study/study-base/dist/lib/config.js","../../../../../ts/lib/config.ts","../../../../../../node_modules/@starling-study/study-base/dist/lib/i18n.js","../../../../../ts/lib/i18n.ts","../../../../../../node_modules/@starling-study/study-base/dist/lib/launch.js","../../../../../ts/lib/launch.ts","../../../../../../node_modules/@starling-study/study-base/dist/lib/router.js","../../../../../ts/lib/router.ts","../../../../../../node_modules/@starling-study/study-base/dist/lib/members.js","../../../../../../node_modules/@starling-study/study-base/dist/lib/session.js","../../../../../../node_modules/@starling-study/study-base/dist/lib/errors.js","../../../../../ts/lib/errors.ts","../../../../../ts/lib/fetch.ts","../../../../../ts/api.ts","../../../../../ts/components/notice.ts","../../../../../ts/session.ts","../../../../../ts/components/chrome.ts","../../../../../ts/components/connection.ts","../../../../../ts/lib/members.ts","../../../../../ts/lib/route.ts","../../../../../ts/views/downloads.ts","../../../../../ts/views/history.ts","../../../../../ts/views/studio.ts","../../../../../ts/index.ts"],"sourcesContent":["/** DOM helpers of the participant apps: a tiny element builder, the status\n * line, a few controls in the shape the Starling forms expect, and saving\n * or copying text. No framework: the views stay declarative with `el`. */\n/** Tiny element builder: `class` sets the class name, `text` the text, a\n * `true` value an empty attribute; `undefined` and `false` are left out. */\nexport function el(tag, attrs = {}, ...children) {\n    const node = document.createElement(tag);\n    for (const [key, value] of Object.entries(attrs)) {\n        if (value === undefined || value === false)\n            continue;\n        if (key === \"class\")\n            node.className = String(value);\n        else if (key === \"text\")\n            node.textContent = String(value);\n        else if (value === true)\n            node.setAttribute(key, \"\");\n        else\n            node.setAttribute(key, String(value));\n    }\n    for (const child of children) {\n        if (child === null || child === undefined || child === false)\n            continue;\n        node.append(typeof child === \"string\" ? document.createTextNode(child) : child);\n    }\n    return node;\n}\nexport function clear(node) {\n    node.replaceChildren();\n}\nexport function on(node, event, handler) {\n    node.addEventListener(event, handler);\n}\n/** Status line used across views: every action replaces what it said\n * before (an old \"Copied.\" never lingers); an error stays put and is\n * marked `study-status--error`. */\nexport function createNotifier(node) {\n    let timer;\n    return (message, kind = \"info\") => {\n        node.textContent = message;\n        node.classList.toggle(\"study-status--error\", kind === \"error\" && message !== \"\");\n        window.clearTimeout(timer);\n        if (kind === \"error\" || !message)\n            return;\n        timer = window.setTimeout(() => {\n            node.textContent = \"\";\n        }, 3000);\n    };\n}\n/** A file size. With a language, the way that language writes it (\"1,5\n * kB\" in Dutch, \"1.5 KB\" in English); without one, plain \"1.5 KB\". */\nexport function formatBytes(bytes, lang) {\n    if (bytes < 1024)\n        return `${bytes} B`;\n    if (lang === undefined) {\n        if (bytes < 1024 * 1024)\n            return `${(bytes / 1024).toFixed(1)} KB`;\n        return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;\n    }\n    const number = (value, digits) => value.toLocaleString(lang === \"nl\" ? \"nl-NL\" : \"en-GB\", {\n        minimumFractionDigits: digits,\n        maximumFractionDigits: digits,\n    });\n    if (bytes < 1024 * 1024)\n        return `${number(bytes / 1024, 1)} ${lang === \"nl\" ? \"kB\" : \"KB\"}`;\n    return `${number(bytes / (1024 * 1024), lang === \"nl\" ? 1 : 2)} MB`;\n}\n/** A filename a phone will accept: the title, flattened to ASCII-ish;\n * `fallback` when nothing is left of it. */\nexport function filenameFor(title, fallback = \"tekst\") {\n    const stem = title\n        .normalize(\"NFKD\")\n        .replace(/[^\\w\\s-]/g, \"\")\n        .trim()\n        .replace(/\\s+/g, \"-\")\n        .slice(0, 60)\n        .toLowerCase() || fallback;\n    return `${stem}.txt`;\n}\n/** Saves a text as a .txt file. Built in the browser: the text is already\n * here, and a link to the API could not carry the workshop password. */\nexport function downloadText(title, content, filename = filenameFor(title)) {\n    const body = title ? `${title}\\n\\n${content}\\n` : `${content}\\n`;\n    const url = URL.createObjectURL(new Blob([body], { type: \"text/plain;charset=utf-8\" }));\n    const link = el(\"a\", { href: url, download: filename });\n    document.body.append(link);\n    link.click();\n    link.remove();\n    window.setTimeout(() => URL.revokeObjectURL(url), 1000);\n}\n/** Copies to the clipboard; false when the browser will not (an insecure\n * origin on a LAN, say), so the caller can say so. */\nexport async function copyText(content) {\n    try {\n        await navigator.clipboard.writeText(content);\n        return true;\n    }\n    catch {\n        return false;\n    }\n}\n/** A labelled control, the shape the Starling forms expect. */\nexport function field(labelText, control, hint) {\n    const id = control.id || `f-${Math.random().toString(36).slice(2, 9)}`;\n    control.id = id;\n    return el(\"div\", { class: \"ss-field\" }, el(\"label\", { class: \"ss-label\", for: id }, labelText), control, hint ? el(\"p\", { class: \"ss-hint\", text: hint }) : null);\n}\n/** A <select> filled from [value, label] pairs. */\nexport function select(options, value) {\n    const node = el(\"select\", { class: \"ss-select\" });\n    for (const [optionValue, label] of options) {\n        node.append(el(\"option\", { value: optionValue }, label));\n    }\n    if (options.some(([optionValue]) => optionValue === value))\n        node.value = value;\n    return node;\n}\n//# sourceMappingURL=dom.js.map","/** The app inside a lesson (study-syllabus puts the tool in an iframe):\n *\n *   /<lang>/<app>/?embed=1&theme=dark&join=ABCDE&workshop=<slug>&task=<text>\n *\n * - `embed=1`: no app bar at all — the lesson has the one header.\n * - `theme`: the lesson's theme, put on `<html data-theme>`.\n * - `join` (+ `workshop`): the group the participant is in already; the\n *   start screen joins it without a second QR scan. Groups are per app, so\n *   a course group's code is usually unknown here: then it counts as no\n *   group (the ordinary start screen, no error).\n * - `task`: the lesson's instruction, used like `?prompt=` (lib/launch).\n * - Later theme changes arrive as a message from the lesson:\n *   `{type: \"study:theme\", theme: \"light\" | \"dark\"}` (followLessonTheme).\n *\n * Read from the address once; the parameters stay in it, so a reload is\n * still embedded. */\n/** Whether the page asks for the embedded layout (`?embed=1`). */\nexport function isEmbedded(loc = location) {\n    const value = new URLSearchParams(loc.search).get(\"embed\");\n    return value === \"1\" || value === \"true\";\n}\n/** The lesson's theme (`?theme=light|dark`), or null. */\nexport function themeFromSearch(loc = location) {\n    const value = new URLSearchParams(loc.search).get(\"theme\");\n    return value === \"light\" || value === \"dark\" ? value : null;\n}\n/** Follow the lesson's theme: `data-theme` on `<html>` (nothing without\n * one). */\nexport function applyEmbedTheme(loc = location, root = document.documentElement) {\n    const theme = themeFromSearch(loc);\n    if (theme)\n        root.dataset.theme = theme;\n    return theme;\n}\n/** The theme of a lesson's `{type: \"study:theme\", theme}` message, or null. */\nexport function themeFromMessage(data) {\n    if (typeof data !== \"object\" || data === null)\n        return null;\n    const { type, theme } = data;\n    return type === \"study:theme\" && (theme === \"light\" || theme === \"dark\")\n        ? theme\n        : null;\n}\n/** Follow the lesson's theme changes (messages from the parent frame only). */\nexport function followLessonTheme(target = window, root = document.documentElement) {\n    target.addEventListener(\"message\", (event) => {\n        if (event.source !== target.parent)\n            return;\n        const theme = themeFromMessage(event.data);\n        if (theme)\n            root.dataset.theme = theme;\n    });\n}\n//# sourceMappingURL=embed.js.map","/** WorkshopClient — the fetch wrapper every workshop app uses.\n *\n * It owns the two device-held secrets and puts them on every request:\n *   - the shared workshop password  → `X-Workshop-Password`\n *   - the shared admin password     → `X-Workshop-Admin-Password` (optional)\n * and, per call, the participant token → `X-Participant-Token`.\n *\n * The backend enforces the passwords (this client is a public file); a\n * 403 whose detail mentions \"password\" is the signal to show the gate.\n */\nexport class ApiError extends Error {\n    status;\n    detail;\n    /** The server's machine-readable `code` (e.g. `workshop_closed`, `busy`), or \"\". */\n    code;\n    constructor(status, detail, code = \"\") {\n        super(detail);\n        this.name = \"ApiError\";\n        this.status = status;\n        this.detail = detail;\n        this.code = code;\n    }\n}\nconst HEADER_PASSWORD = \"X-Workshop-Password\";\nconst HEADER_ADMIN = \"X-Workshop-Admin-Password\";\nconst HEADER_TOKEN = \"X-Participant-Token\";\nexport class WorkshopClient {\n    baseUrl;\n    #passwordKey;\n    #adminKey;\n    #storage;\n    #fetch;\n    #extraHeaders;\n    constructor(options = {}) {\n        const extra = options.headers;\n        this.#extraHeaders =\n            typeof extra === \"function\" ? extra : () => ({ ...(extra ?? {}) });\n        this.baseUrl = options.baseUrl ?? \"\";\n        this.#passwordKey = options.passwordKey ?? \"workshop:password\";\n        this.#adminKey = options.adminPasswordKey ?? \"workshop:admin-password\";\n        this.#storage =\n            options.storage ??\n                (typeof localStorage !== \"undefined\" ? localStorage : null);\n        this.#fetch =\n            options.fetch ?? ((input, init) => globalThis.fetch(input, init));\n        if (options.legacyPasswordKey) {\n            this.#importLegacyPassword(options.legacyPasswordKey);\n        }\n    }\n    #importLegacyPassword(legacyKey) {\n        if (!this.#storage || legacyKey === this.#passwordKey)\n            return;\n        const old = this.#storage.getItem(legacyKey);\n        if (old === null)\n            return;\n        if (old && !this.storedPassword())\n            this.storePassword(old);\n        this.#storage.removeItem(legacyKey);\n    }\n    /** An API path as a full URL — for resources the browser loads\n     * directly (`<img src>` for the QR code), which bypass request(). */\n    url(path) {\n        return `${this.baseUrl}${path}`;\n    }\n    // -- workshop password -----------------------------------------------\n    storedPassword() {\n        return this.#storage?.getItem(this.#passwordKey) ?? \"\";\n    }\n    storePassword(password) {\n        this.#storage?.setItem(this.#passwordKey, password);\n    }\n    clearPassword() {\n        this.#storage?.removeItem(this.#passwordKey);\n    }\n    // -- admin password ---------------------------------------------------\n    storedAdminPassword() {\n        return this.#storage?.getItem(this.#adminKey) ?? \"\";\n    }\n    storeAdminPassword(password) {\n        this.#storage?.setItem(this.#adminKey, password);\n    }\n    clearAdminPassword() {\n        this.#storage?.removeItem(this.#adminKey);\n    }\n    // -- gate helpers -----------------------------------------------------\n    /** Whether the backend wants a workshop password this device does not\n     * have (or has wrong). `probePath` is any cheap gated GET. Network or\n     * server trouble counts as \"no gate\" — the app boots and surfaces the\n     * error in its normal places. */\n    async passwordRequired(probePath) {\n        try {\n            await this.request(\"GET\", probePath);\n            return false;\n        }\n        catch (error) {\n            if (isPasswordError(error)) {\n                this.clearPassword();\n                return true;\n            }\n            return false;\n        }\n    }\n    /** Try a password: store it, probe, keep it only if the probe passes.\n     * Throws the ApiError when it does not (so the gate can tell \"wrong\n     * password\" from \"server unreachable\"). */\n    async unlock(password, probePath) {\n        this.storePassword(password);\n        try {\n            await this.request(\"GET\", probePath);\n        }\n        catch (error) {\n            this.clearPassword();\n            throw error;\n        }\n    }\n    /** Whether the admin gate must be shown. Admin routes are never open\n     * without an admin password (contract §3), so with none stored the\n     * answer is yes without a request — a probe could only come back 403,\n     * which the browser logs as an error. A stored password is probed.\n     * The backend checks the workshop password first, so a workshop-password\n     * 403 means this device is not through the outer gate either: that\n     * password is forgotten and the admin screen stays shut. Other failures\n     * count as \"no gate\", as in `passwordRequired`. */\n    async adminRequired(probePath) {\n        if (!this.storedAdminPassword())\n            return true;\n        try {\n            await this.request(\"GET\", probePath);\n            return false;\n        }\n        catch (error) {\n            if (isAdminPasswordError(error)) {\n                this.clearAdminPassword();\n                return true;\n            }\n            if (isPasswordError(error)) {\n                this.clearPassword();\n                return true;\n            }\n            return false;\n        }\n    }\n    async unlockAdmin(password, probePath) {\n        this.storeAdminPassword(password);\n        try {\n            await this.request(\"GET\", probePath);\n        }\n        catch (error) {\n            this.clearAdminPassword();\n            throw error;\n        }\n    }\n    // -- requests ---------------------------------------------------------\n    async request(method, path, options = {}) {\n        const headers = {\n            ...this.#extraHeaders(path),\n            ...(options.headers ?? {}),\n        };\n        let body;\n        if (options.json !== undefined) {\n            headers[\"Content-Type\"] = \"application/json\";\n            body = JSON.stringify(options.json);\n        }\n        else if (options.form) {\n            body = options.form;\n        }\n        if (options.token)\n            headers[HEADER_TOKEN] = options.token;\n        const password = this.storedPassword();\n        if (password)\n            headers[HEADER_PASSWORD] = password;\n        const admin = this.storedAdminPassword();\n        if (admin)\n            headers[HEADER_ADMIN] = admin;\n        let response;\n        try {\n            response = await this.#fetch(this.url(path), {\n                method,\n                headers,\n                body,\n                signal: options.signal,\n            });\n        }\n        catch {\n            throw new ApiError(0, \"No connection — is the server running?\");\n        }\n        if (response.status === 204)\n            return undefined;\n        let data = null;\n        const text = await response.text();\n        if (text) {\n            try {\n                data = JSON.parse(text);\n            }\n            catch {\n                data = null;\n            }\n        }\n        if (!response.ok) {\n            const record = (data ?? {});\n            const detail = (typeof record.detail === \"string\" && record.detail) ||\n                (typeof record.message === \"string\" && record.message) ||\n                (typeof record.error === \"string\" && record.error) ||\n                firstFieldError(record) ||\n                `Request failed (${response.status})`;\n            const code = typeof record.code === \"string\" ? record.code : \"\";\n            throw new ApiError(response.status, detail, code);\n        }\n        return data;\n    }\n}\n/** A 403 whose detail talks about the workshop password. */\nexport function isPasswordError(error) {\n    return (error instanceof ApiError &&\n        error.status === 403 &&\n        error.detail.toLowerCase().includes(\"password\") &&\n        !error.detail.toLowerCase().includes(\"admin\"));\n}\n/** A 403 whose detail talks about the admin password. */\nexport function isAdminPasswordError(error) {\n    return (error instanceof ApiError &&\n        error.status === 403 &&\n        error.detail.toLowerCase().includes(\"admin\"));\n}\nfunction firstFieldError(record) {\n    for (const value of Object.values(record)) {\n        if (Array.isArray(value) && typeof value[0] === \"string\") {\n            return value[0];\n        }\n        if (typeof value === \"string\")\n            return value;\n    }\n    return \"\";\n}\n//# sourceMappingURL=client.js.map","/** IdentityStore — device-held identity: your name and the groups you have\n * joined on this device, persisted in localStorage.\n *\n * One store per origin (`workshop.identity.v1`): every app on the origin\n * shares the name and the active code, while each membership belongs to\n * the app that holds the token (`Membership.app`). An app passes `app` and\n * sees its own memberships; `membershipElsewhere` tells it when another\n * app already joined the same team code, so it can join silently.\n *\n * Reference implementation of the identity half of doc/contract.md\n * (extracted from widget-scapescene `src/data/identity.ts`). */\nconst EMPTY = { name: \"\", activeCode: null, memberships: [] };\nexport class IdentityStore {\n    #key;\n    #app;\n    #storage;\n    /** Fallback when there is no storage (SSR, tests). */\n    #memory = { ...EMPTY, memberships: [] };\n    constructor(options = {}) {\n        this.#key = options.key ?? \"workshop.identity.v1\";\n        this.#app = options.app ?? \"\";\n        this.#storage =\n            options.storage ??\n                (typeof localStorage !== \"undefined\" ? localStorage : null);\n        if (options.legacyKey)\n            this.#importLegacy(options.legacyKey);\n    }\n    /** The app this store is scoped to, or \"\" for a single-app store. */\n    get app() {\n        return this.#app;\n    }\n    #read(storage, key) {\n        try {\n            const raw = storage.getItem(key);\n            if (raw) {\n                const parsed = JSON.parse(raw);\n                if (parsed && Array.isArray(parsed.memberships))\n                    return parsed;\n            }\n        }\n        catch {\n            // an unreadable store counts as none\n        }\n        return null;\n    }\n    #load() {\n        if (!this.#storage)\n            return this.#memory;\n        return (this.#read(this.#storage, this.#key) ?? {\n            name: \"\",\n            activeCode: null,\n            memberships: [],\n        });\n    }\n    #save(identity) {\n        if (this.#app) {\n            // A legacy entry (written before memberships carried an app) is\n            // this app's; claim it so the next app on the origin cannot.\n            for (const m of identity.memberships)\n                if (!m.app)\n                    m.app = this.#app;\n        }\n        if (!this.#storage) {\n            this.#memory = identity;\n            return;\n        }\n        this.#storage.setItem(this.#key, JSON.stringify(identity));\n    }\n    /** Move an old per-app store into the shared one: its memberships get\n     * this app, the shared name and active code win when they are set, and\n     * the old key goes. Memberships the shared store already holds for the\n     * same code and app are kept as they are. */\n    #importLegacy(legacyKey) {\n        if (!this.#storage || legacyKey === this.#key)\n            return;\n        const legacy = this.#read(this.#storage, legacyKey);\n        if (!legacy)\n            return;\n        const identity = this.#load();\n        const imported = legacy.memberships\n            .map((m) => ({ ...m, app: m.app || this.#app || undefined }))\n            .filter((m) => !identity.memberships.some((own) => this.#same(own, m)));\n        identity.memberships = [...identity.memberships, ...imported];\n        identity.name = identity.name || legacy.name || \"\";\n        identity.activeCode = identity.activeCode ?? legacy.activeCode ?? null;\n        this.#save(identity);\n        this.#storage.removeItem(legacyKey);\n    }\n    /** Whether a membership belongs to this store's app. Without an app\n     * every membership does; with one, a legacy entry without `app` does. */\n    #mine(membership) {\n        return !this.#app || !membership.app || membership.app === this.#app;\n    }\n    /** The app a membership belongs to, a legacy entry counting as this\n     * app's. */\n    #appOf(membership) {\n        return membership.app || this.#app;\n    }\n    /** Whether two memberships name the same group: same code and, for\n     * app-scoped stores, the same app. */\n    #same(a, b) {\n        if (a.code !== b.code)\n            return false;\n        return !this.#app || this.#appOf(a) === this.#appOf(b);\n    }\n    get() {\n        return this.#load();\n    }\n    get name() {\n        return this.#load().name;\n    }\n    setName(name) {\n        const identity = this.#load();\n        identity.name = name.trim();\n        this.#save(identity);\n    }\n    /** This app's memberships (every membership for a store without an app). */\n    get memberships() {\n        return this.#load().memberships.filter((m) => this.#mine(m));\n    }\n    /** Every membership on the device, whichever app holds it. */\n    allMemberships() {\n        return this.#load().memberships;\n    }\n    membership(code) {\n        const upper = code.toUpperCase();\n        return (this.#load().memberships.find((m) => m.code === upper && this.#mine(m)) ?? null);\n    }\n    /** A membership of the same code held by another app on this origin —\n     * the sign that this device may join the team here without asking.\n     * Always null for a store without an app. */\n    membershipElsewhere(code) {\n        if (!this.#app)\n            return null;\n        const upper = code.toUpperCase();\n        return (this.#load().memberships.find((m) => m.code === upper && !this.#mine(m)) ?? null);\n    }\n    upsertMembership(membership) {\n        const identity = this.#load();\n        const entry = this.#app\n            ? { ...membership, app: membership.app || this.#app }\n            : membership;\n        const rest = identity.memberships.filter((m) => !this.#same(m, entry));\n        identity.memberships = [entry, ...rest];\n        identity.activeCode = entry.code;\n        this.#save(identity);\n    }\n    updateGroupName(code, groupName) {\n        const identity = this.#load();\n        const membership = identity.memberships.find((m) => m.code === code && this.#mine(m));\n        if (membership) {\n            membership.groupName = groupName;\n            this.#save(identity);\n        }\n    }\n    updateParticipantName(code, participantName) {\n        const identity = this.#load();\n        const membership = identity.memberships.find((m) => m.code === code && this.#mine(m));\n        if (membership) {\n            membership.participantName = participantName;\n            this.#save(identity);\n        }\n    }\n    /** Forget this app's membership of the code. Leaving is per app: other\n     * apps keep theirs, and the shared active code stays while one of them\n     * still holds the code (the device is still in that team, only not\n     * here). It is cleared only when no membership of the code remains. */\n    removeMembership(code) {\n        const identity = this.#load();\n        identity.memberships = identity.memberships.filter((m) => !(m.code === code && this.#mine(m)));\n        const held = identity.memberships.some((m) => m.code === code);\n        if (identity.activeCode === code && !held)\n            identity.activeCode = null;\n        this.#save(identity);\n    }\n    /** The details this device gave `workshop`, or null. */\n    registration(workshop) {\n        return this.#load().registrations?.[workshop] ?? null;\n    }\n    /** Keep the details given to `workshop`, for every app on the origin. */\n    setRegistration(workshop, registration) {\n        const identity = this.#load();\n        identity.registrations = {\n            ...(identity.registrations ?? {}),\n            [workshop]: registration,\n        };\n        this.#save(identity);\n    }\n    /** Forget the details given to `workshop` (the server refused them). */\n    clearRegistration(workshop) {\n        const identity = this.#load();\n        if (!identity.registrations?.[workshop])\n            return;\n        const { [workshop]: _gone, ...rest } = identity.registrations;\n        identity.registrations = rest;\n        this.#save(identity);\n    }\n    /** The attendee token of `workshop`; without a workshop (or none kept\n     * for it) the one given last — a backend ignores a token of another\n     * workshop. \"\" when the device has none. */\n    attendeeToken(workshop = \"\") {\n        const attendees = this.#load().attendees ?? {};\n        if (workshop && attendees[workshop])\n            return attendees[workshop];\n        const tokens = Object.values(attendees);\n        return tokens.length ? tokens[tokens.length - 1] : \"\";\n    }\n    /** Keep the attendee token a join answered for `workshop`. */\n    setAttendee(workshop, token) {\n        if (!token)\n            return;\n        const identity = this.#load();\n        const { [workshop]: _old, ...rest } = identity.attendees ?? {};\n        identity.attendees = { ...rest, [workshop]: token };\n        this.#save(identity);\n    }\n    /** Forget the attendee token of `workshop` (with its details, on a\n     * shared device: the server links a join with the token to the person\n     * who registered, and reuses their details). */\n    clearAttendee(workshop) {\n        const identity = this.#load();\n        if (!identity.attendees || !(workshop in identity.attendees))\n            return;\n        const { [workshop]: _gone, ...rest } = identity.attendees;\n        identity.attendees = rest;\n        this.#save(identity);\n    }\n    /** The active code is shared by every app on the origin. */\n    setActive(code) {\n        const identity = this.#load();\n        identity.activeCode = code;\n        this.#save(identity);\n    }\n    /** This app's membership of the shared active code, or null (also when\n     * only another app holds that code — see `membershipElsewhere`). */\n    activeMembership() {\n        const identity = this.#load();\n        if (!identity.activeCode)\n            return null;\n        return (identity.memberships.find((m) => m.code === identity.activeCode && this.#mine(m)) ?? null);\n    }\n}\n//# sourceMappingURL=identity.js.map","/** GroupsApi — typed wrappers for the group/participant endpoints of\n * doc/contract.md. `basePath` is the app's API prefix (`/api/v1` in\n * scapescene, `/api` in cocoder); paths use trailing slashes and every\n * conforming server accepts both forms. */\nimport { ApiError } from \"./client.js\";\nexport class GroupsApi {\n    client;\n    basePath;\n    constructor(client, options = {}) {\n        this.client = client;\n        this.basePath = (options.basePath ?? \"/api/v1\").replace(/\\/+$/, \"\");\n    }\n    #group(code) {\n        return `${this.basePath}/groups/${encodeURIComponent(code.toUpperCase())}`;\n    }\n    /** POST /groups/ — create a group and its founding participant. */\n    create(creatorName, name = \"\", extra = {}) {\n        // `extra` may carry `attendee` (the device's attendee token).\n        return this.client.request(\"POST\", `${this.basePath}/groups/`, {\n            json: { creatorName, name, ...extra },\n        });\n    }\n    /** GET /groups/{code}/ */\n    get(code) {\n        return this.client.request(\"GET\", `${this.#group(code)}/`);\n    }\n    /** PATCH /groups/{code}/ */\n    patch(code, patch, token) {\n        return this.client.request(\"PATCH\", `${this.#group(code)}/`, {\n            json: patch,\n            token,\n        });\n    }\n    /** POST /groups/{code}/join/ — with the workshop's registration when\n     * it asks for one (only `fields` and `consent` are sent) and the\n     * device's attendee token when it has one. */\n    join(code, name, registration, attendee = \"\") {\n        return this.client.request(\"POST\", `${this.#group(code)}/join/`, {\n            json: {\n                name,\n                ...(registration\n                    ? { registration: registrationBody(registration) }\n                    : {}),\n                ...(attendee ? { attendee } : {}),\n            },\n        });\n    }\n    /** GET /registration/ — what the workshop asks on joining. A backend\n     * without the route (404) asks nothing. */\n    async registration(lang = \"\") {\n        const query = lang ? `?lang=${encodeURIComponent(lang)}` : \"\";\n        try {\n            return await this.client.request(\"GET\", `${this.basePath}/registration/${query}`);\n        }\n        catch (error) {\n            if (error instanceof ApiError && error.status === 404) {\n                return { enabled: false, workshop: \"\" };\n            }\n            throw error;\n        }\n    }\n    /** The QR image for the join link — a full URL, because it is loaded\n     * by an <img> which resolves relative URLs against the page's origin. */\n    qrUrl(code) {\n        return this.client.url(`${this.#group(code)}/qr.png`);\n    }\n    /** POST /groups/{code}/participants/ — a name-only participant without\n     * their own device. Requires a member's token. */\n    addParticipant(code, name, token) {\n        return this.client.request(\"POST\", `${this.#group(code)}/participants/`, {\n            json: { name },\n            token,\n        });\n    }\n    renameParticipant(code, participantId, name, token) {\n        return this.client.request(\"PATCH\", `${this.#group(code)}/participants/${encodeURIComponent(participantId)}/`, { json: { name }, token });\n    }\n    removeParticipant(code, participantId, token) {\n        return this.client.request(\"DELETE\", `${this.#group(code)}/participants/${encodeURIComponent(participantId)}/`, { token });\n    }\n}\n/** The registration as the server takes it: the details and the consent. */\nexport function registrationBody(registration) {\n    return { fields: { ...registration.fields }, consent: true };\n}\n//# sourceMappingURL=groups.js.map","/** WorkshopSession — the state behind the shared start/group screens.\n *\n * Combines a WorkshopClient, an IdentityStore and a GroupsApi into one\n * EventTarget that screens subscribe to. Apps keep their own store for\n * app-specific state and either wrap this session or extend it.\n *\n * Events:\n *   \"change\"        — anything observable changed (identity, group cache)\n *   \"group-entered\" — detail: { code }   after create / join / switch\n *   \"left\"          — the active group was cleared (back to start)\n *\n * Registration: a workshop may ask for details on joining\n * (`loadRegistration`). The details are asked once per workshop\n * (`register`), kept in the identity store for every app on the origin,\n * and sent with every join — the silent one of `ensureMembership` too.\n */\nimport { ApiError } from \"./client.js\";\nimport { GroupsApi, registrationBody } from \"./groups.js\";\nimport { IdentityStore } from \"./identity.js\";\n/** The `code` of a join the server refused for want of registration. */\nexport const REGISTRATION_REQUIRED = \"registration_required\";\n/** Whether `error` is a join refused for want of (valid) registration. */\nexport function isRegistrationError(error) {\n    return error instanceof ApiError && error.code === REGISTRATION_REQUIRED;\n}\n/** Normalised as the server does (normaliseCode in server/ids): only\n * uppercasing let \"ABC-12\" miss the stored \"ABC12\" membership, and the\n * server then joined the same group again as a second participant. */\nfunction normaliseCode(code) {\n    return code.toUpperCase().replace(/[^A-Z0-9]/g, \"\");\n}\nexport class WorkshopSession extends EventTarget {\n    client;\n    /** The app this session belongs to, or \"\" (see `WorkshopSessionOptions.app`). */\n    app;\n    identity;\n    groups;\n    #groupLabel;\n    /** The active group, as last fetched. Null until loaded. */\n    group = null;\n    /** Non-blocking error from the last background refresh. */\n    lastError = \"\";\n    /** What the workshop asks on joining, once loaded (`loadRegistration`). */\n    registrationSettings = null;\n    #pollTimer = null;\n    constructor(options) {\n        super();\n        this.client = options.client;\n        this.app = options.app ?? \"\";\n        this.identity =\n            options.identity ?? new IdentityStore({ app: this.app || undefined });\n        this.groups =\n            options.groups ?? new GroupsApi(options.client, { basePath: options.basePath });\n        this.#groupLabel = options.groupLabel ?? ((group) => group.name);\n    }\n    // -- subscriptions ----------------------------------------------------\n    onChange(fn) {\n        const handler = () => fn();\n        this.addEventListener(\"change\", handler);\n        return () => this.removeEventListener(\"change\", handler);\n    }\n    emitChange() {\n        this.dispatchEvent(new Event(\"change\"));\n    }\n    // -- identity ---------------------------------------------------------\n    get userName() {\n        return this.identity.name;\n    }\n    setUserName(name) {\n        this.identity.setName(name);\n        this.emitChange();\n    }\n    get memberships() {\n        return this.identity.memberships;\n    }\n    get membership() {\n        return this.identity.activeMembership();\n    }\n    /** The active member's token, or \"\" — for group-scoped mutations. */\n    get token() {\n        return this.membership?.token ?? \"\";\n    }\n    // -- registration -----------------------------------------------------\n    /** Ask the server what the workshop asks on joining (labels in `lang`)\n     * and keep the answer. A failed request leaves it unknown (null): the\n     * server still refuses a join without details, and the start screen\n     * then asks. */\n    async loadRegistration(lang = \"\") {\n        try {\n            this.registrationSettings = await this.groups.registration(lang);\n        }\n        catch {\n            return this.registrationSettings;\n        }\n        this.emitChange();\n        return this.registrationSettings;\n    }\n    /** The details this device gave the workshop, or null. */\n    get registration() {\n        const workshop = this.registrationSettings?.workshop;\n        return workshop ? this.identity.registration(workshop) : null;\n    }\n    /** Whether the workshop asks for details this device has not given. */\n    get registrationNeeded() {\n        return Boolean(this.registrationSettings?.enabled) && !this.registration;\n    }\n    /** Keep the details for the workshop (after the participant agreed to\n     * the consent text); the next join sends them. Only the asked fields\n     * are kept. */\n    register(fields) {\n        const settings = this.registrationSettings;\n        if (!settings?.enabled)\n            throw new Error(\"No registration asked.\");\n        const asked = new Set((settings.fields ?? []).map((f) => f.key));\n        const kept = {};\n        for (const [key, value] of Object.entries(fields)) {\n            const clean = value.trim();\n            if (asked.has(key) && clean)\n                kept[key] = clean;\n        }\n        const registration = {\n            fields: kept,\n            consent: true,\n            at: new Date().toISOString(),\n        };\n        this.identity.setRegistration(settings.workshop, registration);\n        this.emitChange();\n        return registration;\n    }\n    /** Forget the details this device gave the workshop, and the attendee\n     * token that carries them on the server, so the next person on a\n     * shared device is asked again and is not joined as the previous one.\n     * Only this device: the workshop leader keeps what was registered.\n     * False when nothing was kept. */\n    forgetRegistration() {\n        const workshop = this.registrationSettings?.workshop;\n        if (!workshop || !this.identity.registration(workshop))\n            return false;\n        this.identity.clearRegistration(workshop);\n        this.identity.clearAttendee(workshop);\n        this.emitChange();\n        return true;\n    }\n    /** The registration to send with a join, when the workshop asks one. */\n    #registrationToSend() {\n        return this.registrationSettings?.enabled ? this.registration : null;\n    }\n    /** A join the server refused for want of registration: forget the\n     * stored details (they no longer do) so the start screen asks again. */\n    #forgetRefused(error) {\n        if (!isRegistrationError(error))\n            return;\n        const workshop = this.registrationSettings?.workshop;\n        if (workshop)\n            this.identity.clearRegistration(workshop);\n        if (this.registrationSettings) {\n            this.registrationSettings = { ...this.registrationSettings, enabled: true };\n        }\n        this.emitChange();\n    }\n    // -- group lifecycle --------------------------------------------------\n    async createGroup(creatorName, name = \"\", extra = {}) {\n        this.identity.setName(creatorName);\n        const registration = this.#registrationToSend();\n        let result;\n        try {\n            const attendee = this.#attendeeToSend();\n            result = await this.groups.create(creatorName, name, {\n                ...extra,\n                ...(registration\n                    ? { registration: registrationBody(registration) }\n                    : {}),\n                ...(attendee ? { attendee } : {}),\n            });\n        }\n        catch (error) {\n            this.#forgetRefused(error);\n            throw error;\n        }\n        this.#adopt(result.group, result.participant, result.attendee);\n        return result.group;\n    }\n    async joinGroup(code, name) {\n        this.identity.setName(name);\n        code = normaliseCode(code);\n        const existing = this.identity.membership(code);\n        if (existing) {\n            // Already a member on this device — just switch back.\n            this.switchGroup(existing.code);\n            return this.group;\n        }\n        // A team code another app on this device already joined: the server\n        // creates this app's group lazily, so join with the name we know.\n        const elsewhere = this.identity.membershipElsewhere(code);\n        return this.#join(code, name || elsewhere?.participantName || \"\");\n    }\n    /** Make sure this device is in the group `code` of this app, without a\n     * start screen when it can: a membership this app already holds is\n     * made active; a membership of the same code in another app means the\n     * team is known, so the device joins here silently with that name\n     * (falling back to the stored name). Null when the code is unknown on\n     * this device — the caller shows the start screen. Also null when the\n     * workshop asks for details this device has not given (yet): the start\n     * screen asks for them. */\n    async ensureMembership(code) {\n        code = normaliseCode(code);\n        if (!code)\n            return null;\n        const mine = this.identity.membership(code);\n        if (mine) {\n            this.switchGroup(mine.code);\n            return mine;\n        }\n        const elsewhere = this.identity.membershipElsewhere(code);\n        if (!elsewhere)\n            return null;\n        if (!this.registrationSettings)\n            await this.loadRegistration();\n        if (this.registrationNeeded)\n            return null;\n        try {\n            await this.#join(code, elsewhere.participantName || this.identity.name);\n        }\n        catch (error) {\n            if (isRegistrationError(error))\n                return null;\n            throw error;\n        }\n        return this.identity.membership(code);\n    }\n    async #join(code, name) {\n        let result;\n        try {\n            result = await this.groups.join(code, name, this.#registrationToSend(), this.#attendeeToSend());\n        }\n        catch (error) {\n            this.#forgetRefused(error);\n            throw error;\n        }\n        this.#adopt(result.group, result.participant, result.attendee);\n        return result.group;\n    }\n    /** The attendee token to send with a join: the one of this workshop\n     * when it is known (`registrationSettings`), else the last one. */\n    #attendeeToSend() {\n        return this.identity.attendeeToken(this.registrationSettings?.workshop);\n    }\n    #adopt(group, participant, attendee) {\n        if (attendee?.token) {\n            this.identity.setAttendee(attendee.workshop ?? this.registrationSettings?.workshop ?? \"\", attendee.token);\n        }\n        this.identity.upsertMembership({\n            code: group.code,\n            ...(this.app ? { app: this.app } : {}),\n            groupName: this.#groupLabel(group),\n            participantId: participant.id,\n            participantName: participant.name,\n            token: participant.token,\n            joinedAt: new Date().toISOString(),\n        });\n        this.group = group;\n        this.emitChange();\n        this.dispatchEvent(new CustomEvent(\"group-entered\", { detail: { code: group.code } }));\n    }\n    switchGroup(code) {\n        this.identity.setActive(code);\n        this.group = null;\n        this.emitChange();\n        void this.refreshGroup().catch(() => undefined);\n        this.dispatchEvent(new CustomEvent(\"group-entered\", { detail: { code } }));\n    }\n    /** Clear the active group (keep the membership) and go back to start. */\n    leaveToStart() {\n        this.identity.setActive(null);\n        this.group = null;\n        this.stopPolling();\n        this.emitChange();\n        this.dispatchEvent(new Event(\"left\"));\n    }\n    /** Forget this app's membership of the code (per app, like\n     * `removeParticipant` on oneself: other apps keep the team). */\n    forgetGroup(code) {\n        this.identity.removeMembership(code);\n        if (this.group?.code === code)\n            this.group = null;\n        this.emitChange();\n    }\n    async refreshGroup() {\n        const active = this.identity.activeMembership();\n        if (!active)\n            return;\n        // A poll, or the refresh a switch starts, can still be in flight when\n        // the visitor switches group or leaves: its answer is for a group that\n        // is no longer active and must not become `this.group`.\n        const stale = () => this.identity.activeMembership()?.code !== active.code;\n        try {\n            const group = await this.groups.get(active.code);\n            this.identity.updateGroupName(active.code, this.#groupLabel(group));\n            if (stale())\n                return;\n            this.group = group;\n            this.lastError = \"\";\n        }\n        catch (error) {\n            if (!stale()) {\n                this.lastError =\n                    error instanceof Error ? error.message : \"Could not load the group.\";\n            }\n            throw error;\n        }\n        finally {\n            this.emitChange();\n        }\n    }\n    async patchGroup(patch) {\n        const active = this.identity.activeMembership();\n        if (!active)\n            throw new Error(\"No active group.\");\n        const group = await this.groups.patch(active.code, patch, active.token);\n        this.group = group;\n        this.identity.updateGroupName(active.code, this.#groupLabel(group));\n        this.emitChange();\n        return group;\n    }\n    // -- participants -----------------------------------------------------\n    async addParticipant(name) {\n        const active = this.identity.activeMembership();\n        if (!active)\n            throw new Error(\"No active group.\");\n        await this.groups.addParticipant(active.code, name, active.token);\n        await this.refreshGroup();\n    }\n    async renameParticipant(participantId, name) {\n        const active = this.identity.activeMembership();\n        if (!active)\n            throw new Error(\"No active group.\");\n        await this.groups.renameParticipant(active.code, participantId, name, active.token);\n        if (participantId === active.participantId) {\n            this.identity.updateParticipantName(active.code, name);\n        }\n        await this.refreshGroup();\n    }\n    async removeParticipant(participantId) {\n        const active = this.identity.activeMembership();\n        if (!active)\n            throw new Error(\"No active group.\");\n        await this.groups.removeParticipant(active.code, participantId, active.token);\n        if (participantId === active.participantId) {\n            // Removed ourselves: this app no longer belongs to the group. The\n            // leave is per app — the store keeps the shared active code while\n            // another app on the device still holds the team — so this\n            // session has no active membership left and goes back to start,\n            // while the other apps stay in the team.\n            this.identity.removeMembership(active.code);\n            this.group = null;\n            this.stopPolling();\n            this.emitChange();\n            this.dispatchEvent(new Event(\"left\"));\n            return;\n        }\n        await this.refreshGroup();\n    }\n    // -- polling ----------------------------------------------------------\n    startPolling(intervalMs = 5000) {\n        if (this.#pollTimer !== null)\n            return;\n        this.#pollTimer = setInterval(() => {\n            void this.refreshGroup().catch(() => undefined);\n        }, intervalMs);\n    }\n    stopPolling() {\n        if (this.#pollTimer !== null) {\n            clearInterval(this.#pollTimer);\n            this.#pollTimer = null;\n        }\n    }\n}\n//# sourceMappingURL=session.js.map","/** Boot helpers — the same two lines at the top of every workshop app. */\nimport { renderPasswordGate, } from \"./screens/password-gate.js\";\n/** Show the password gate first when the backend demands one and resolve\n * once the device is let in (immediately when no gate is needed). */\nexport async function passGate(options) {\n    const required = options.admin\n        ? await options.client.adminRequired(options.probePath)\n        : await options.client.passwordRequired(options.probePath);\n    if (!required)\n        return;\n    await new Promise((resolve) => {\n        const gate = renderPasswordGate(options.host, {\n            client: options.client,\n            probePath: options.probePath,\n            title: options.title,\n            hint: options.hint,\n            buttonLabel: options.buttonLabel,\n            admin: options.admin,\n            labels: options.labels,\n            onUnlocked: () => {\n                gate.destroy();\n                resolve();\n            },\n        });\n    });\n}\n/** The join code carried by a deep link — `?join=CODE`, `?code=CODE`, or a\n * hash route `#/join?code=CODE` — normalised to uppercase, or \"\". */\nexport function joinCodeFromLocation(loc = window.location) {\n    const search = new URLSearchParams(loc.search);\n    const direct = search.get(\"join\") ?? search.get(\"code\");\n    if (direct)\n        return direct.toUpperCase();\n    const hash = loc.hash.startsWith(\"#\") ? loc.hash.slice(1) : loc.hash;\n    const query = hash.split(\"?\")[1];\n    if (query) {\n        const params = new URLSearchParams(query);\n        const code = params.get(\"code\") ?? params.get(\"join\");\n        if (code)\n            return code.toUpperCase();\n    }\n    return \"\";\n}\n/** The code an app should resume on boot: the deep link's `?join=` when\n * there is one, else the active code the apps on this origin share, else\n * \"\". With `WorkshopSession.ensureMembership` this is the whole boot:\n *\n *   const code = resumeCode(session.identity);\n *   if (code && (await session.ensureMembership(code))) showGroup();\n *   else showStart();\n */\nexport function resumeCode(identity, loc = window.location) {\n    return joinCodeFromLocation(loc) || identity.get().activeCode || \"\";\n}\n/** The join URL for a code — what the QR encodes and what people share. */\nexport function joinUrl(origin, code) {\n    return `${origin.replace(/\\/+$/, \"\")}/?join=${encodeURIComponent(code.toUpperCase())}`;\n}\n//# sourceMappingURL=boot.js.map","/** Whether the server answers, for every request of a tool.\n *\n * While the server restarts (a container that is replaced takes minutes),\n * the front before it (Scaleway's edge, Cloudflare) answers instead: a\n * refused connection, a 502/503/504 or a Cloudflare 52x, often as an HTML\n * page instead of JSON. `watchConnection` sits under the client's fetch\n * and tells such an answer from the app's own: it marks the connection\n * down (`Connection.lost`) and hands the client a 503 JSON body with the\n * code `server_unreachable` instead of the front's page, so the screens\n * word it (lib/errors). The first real answer of the app (any status)\n * marks it up again (`Connection.up`), which a banner, a poll and an\n * autosave hear (`restored`); `connectionNotice` says what the banner\n * shows.\n *\n * A poll asks again after `retryDelay` while the connection is down:\n * 2 s, 4 s, 8 s, then every 15 s, instead of its own pace. `requireGroup`\n * (lib/entry) waits the same way when the server is away at page load.\n *\n * Tools import it from the package: `@starling-study/study-base/lib/connection`\n * (study-storyboard-public and study-horizon-public had a copy each). It\n * imports nothing. */\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n    return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n    if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n    return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _Connection_failures;\n/** The code of an answer that came from the front, not from the app. */\nexport const OUTAGE_CODE = \"server_unreachable\";\n/** The first and the longest pause between two tries while it is down. */\nexport const RETRY_MIN_MS = 2000;\nexport const RETRY_MAX_MS = 15000;\n/** How long a GET may wait for its answer: a front that holds the request\n * while the container starts would otherwise keep the poll waiting. */\nexport const GET_TIMEOUT_MS = 30000;\n/** What the front answers while the app is away (502/503/504; Cloudflare's\n * 52x and 530). The app's own 503 (a locked database, generation paused)\n * is JSON with a `code` or a `detail` and stays the app's. */\nconst FRONT_STATUSES = new Set([\n    502, 503, 504, 520, 521, 522, 523, 524, 525, 526, 527, 530,\n]);\n/** Whether `status` is one the front answers with while the app is away. */\nexport function isFrontStatus(status) {\n    return FRONT_STATUSES.has(status);\n}\n/** The pause before the next try after `failures` failed ones: doubling\n * from `min` up to `max`. */\nexport function retryDelay(failures, min = RETRY_MIN_MS, max = RETRY_MAX_MS) {\n    if (failures <= 1)\n        return min;\n    return Math.min(max, min * 2 ** (failures - 1));\n}\n/** The state of the line to the server, shared by the whole app. */\nexport class Connection extends EventTarget {\n    constructor() {\n        super(...arguments);\n        _Connection_failures.set(this, 0);\n    }\n    /** No answer from the app since the last failure. */\n    get down() {\n        return __classPrivateFieldGet(this, _Connection_failures, \"f\") > 0;\n    }\n    /** Failed tries in a row (0: up). */\n    get failures() {\n        return __classPrivateFieldGet(this, _Connection_failures, \"f\");\n    }\n    /** The pause before the next try of a poll while it is down. */\n    retryDelay() {\n        return retryDelay(__classPrivateFieldGet(this, _Connection_failures, \"f\"));\n    }\n    /** A request did not reach the app. */\n    lost() {\n        __classPrivateFieldSet(this, _Connection_failures, __classPrivateFieldGet(this, _Connection_failures, \"f\") + 1, \"f\");\n        if (__classPrivateFieldGet(this, _Connection_failures, \"f\") === 1)\n            this.dispatchEvent(new Event(\"change\"));\n    }\n    /** The app answered. */\n    up() {\n        if (__classPrivateFieldGet(this, _Connection_failures, \"f\") === 0)\n            return;\n        __classPrivateFieldSet(this, _Connection_failures, 0, \"f\");\n        this.dispatchEvent(new Event(\"change\"));\n        this.dispatchEvent(new Event(\"restored\"));\n    }\n    /** Hear the connection go down or come back. */\n    onChange(fn) {\n        const handler = () => fn();\n        this.addEventListener(\"change\", handler);\n        return () => this.removeEventListener(\"change\", handler);\n    }\n    /** Hear the connection come back. */\n    onRestored(fn) {\n        const handler = () => fn();\n        this.addEventListener(\"restored\", handler);\n        return () => this.removeEventListener(\"restored\", handler);\n    }\n}\n_Connection_failures = new WeakMap();\n/** The app's one connection. */\nexport const connection = new Connection();\n/** Whether a failed request failed for want of the server (no connection\n * at all, or the front's answer): worth trying again once it is back. */\nexport function isOutage(error) {\n    if (!error || typeof error !== \"object\")\n        return false;\n    const { status, code } = error;\n    return status === 0 || code === OUTAGE_CODE;\n}\nasync function jsonOf(response) {\n    try {\n        return await response.clone().json();\n    }\n    catch {\n        return null;\n    }\n}\n/** Whether `response` is the front's, not the app's. */\nexport async function fromFront(response) {\n    const type = response.headers.get(\"Content-Type\") ?? \"\";\n    if (FRONT_STATUSES.has(response.status)) {\n        if (!type.includes(\"json\"))\n            return true;\n        const body = await jsonOf(response);\n        if (!body || typeof body !== \"object\")\n            return true;\n        const { code, detail, error } = body;\n        return ![code, detail, error].some((v) => typeof v === \"string\");\n    }\n    // An HTML page where the API answers JSON: an error or maintenance page.\n    return response.ok && type.includes(\"text/html\");\n}\n/** The answer the client gets instead of the front's page. */\nfunction outageResponse(status) {\n    return new Response(JSON.stringify({\n        code: OUTAGE_CODE,\n        detail: \"The server cannot be reached; it may be restarting.\",\n    }), {\n        status: FRONT_STATUSES.has(status) ? status : 503,\n        headers: { \"Content-Type\": \"application/json\" },\n    });\n}\nfunction isGet(input, init) {\n    const method = init?.method ??\n        (typeof Request !== \"undefined\" && input instanceof Request\n            ? input.method\n            : \"GET\");\n    return method.toUpperCase() === \"GET\";\n}\n/** The fetch under the client that keeps `connection` up to date (see the\n * module docstring). A GET without a signal of its own is given up after\n * `timeoutMs`, which counts as no connection. */\nexport function watchConnection(base, options = {}) {\n    const line = options.connection ?? connection;\n    const timeoutMs = options.timeoutMs ?? GET_TIMEOUT_MS;\n    return async (input, init) => {\n        let timer = null;\n        let request = init;\n        if (timeoutMs > 0 && !init?.signal && isGet(input, init)) {\n            const abort = new AbortController();\n            timer = setTimeout(() => abort.abort(), timeoutMs);\n            request = { ...init, signal: abort.signal };\n        }\n        let response;\n        try {\n            response = await base(input, request);\n        }\n        catch (error) {\n            // A request the caller cancelled says nothing about the server.\n            if (!init?.signal?.aborted)\n                line.lost();\n            throw error;\n        }\n        finally {\n            if (timer !== null)\n                clearTimeout(timer);\n        }\n        if (await fromFront(response)) {\n            line.lost();\n            return outageResponse(response.status);\n        }\n        line.up();\n        return response;\n    };\n}\nexport function connectionNotice(line, online) {\n    if (!line.down)\n        return \"\";\n    return online ? \"serverRestarting\" : \"connectionOffline\";\n}\n//# sourceMappingURL=connection.js.map","/** The group of a workshop, once for every tool: the base API's team\n * routes (`/api/base/team/`, study.base.api.views.view_team) and what the\n * device keeps of them.\n *\n * The team routes speak sturnia-workshop's group contract, so a\n * `WorkshopSession` talks to them as to a tool (`TEAM_API`, app\n * `TEAM_APP`). A create or a join there makes the team's group in every\n * tool that is on and answers with the device's membership in each\n * (`memberships`); `TeamGroupsApi` writes those into the one identity\n * store every tool shares, so each tool finds the group without asking.\n *\n * A member of the team is a person: `a-<id>` (their attendee token is the\n * device's token for the team), a name-only member `n-<id>`, or an older\n * membership without an attendee `p-<id>`. Leaving, renaming oneself,\n * \"that's me\" (`claim`) and forgetting a group act on every tool's\n * membership on the device. */\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n    if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n    return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n    return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _TeamGroupsApi_instances, _TeamGroupsApi_storage, _TeamGroupsApi_keep;\nimport { GroupsApi, IdentityStore, WorkshopClient, } from \"@starling-cloud/sturnia-workshop\";\n/** The team routes of the base API. */\nexport const TEAM_API = \"/api/base/team\";\n/** The app the device keeps its membership of a team under: no tool, so\n * every tool sees \"this team is known on the device\" (sturnia-workshop's\n * `membershipElsewhere`) and joins it silently. */\nexport const TEAM_APP = \"team\";\n/** The header that names an older device's memberships of a code. */\nexport const HEADER_PARTICIPANT_TOKENS = \"X-Participant-Tokens\";\nfunction store(app, storage) {\n    return new IdentityStore({\n        app,\n        ...(storage ? { storage: storage } : {}),\n    });\n}\n/** Keep the device's membership in each tool, so every tool finds the\n * group (and its own token) without a join of its own. */\nexport function adoptMemberships(code, groupName, memberships = [], storage) {\n    const joinedAt = new Date().toISOString();\n    for (const { app, participant } of memberships) {\n        if (!app || !participant?.token)\n            continue;\n        store(app, storage).upsertMembership({\n            code: code.toUpperCase(),\n            app,\n            groupName,\n            participantId: participant.id,\n            participantName: participant.name,\n            token: participant.token,\n            joinedAt,\n        });\n    }\n}\n/** Every membership of `code` on the device, whichever tool holds it. */\nexport function membershipsOf(code, storage) {\n    const upper = code.toUpperCase();\n    return store(TEAM_APP, storage)\n        .allMemberships()\n        .filter((m) => m.code.toUpperCase() === upper);\n}\n/** The tokens of the device's memberships of `code` in the tools (an\n * older device's way of saying who it is). */\nexport function toolTokens(code, storage) {\n    return membershipsOf(code, storage)\n        .filter((m) => m.app !== TEAM_APP && m.token)\n        .map((m) => m.token);\n}\n/** Forget `code` on the device in every tool (left, or taken out). */\nexport function forgetTeam(code, storage) {\n    const upper = code.toUpperCase();\n    const apps = new Set(membershipsOf(upper, storage).map((m) => m.app ?? \"\"));\n    for (const app of apps)\n        store(app, storage).removeMembership(upper);\n    const shared = store(TEAM_APP, storage);\n    if ((shared.get().activeCode ?? \"\").toUpperCase() === upper)\n        shared.setActive(null);\n}\n/** The device's name, and its name in every tool's membership of `code`. */\nexport function renameOnDevice(code, name, storage) {\n    const upper = code.toUpperCase();\n    store(TEAM_APP, storage).setName(name);\n    for (const m of membershipsOf(upper, storage))\n        store(m.app ?? \"\", storage).updateParticipantName(upper, name);\n}\n/** The group name in every tool's membership of `code` (\"your groups\"). */\nexport function renameGroupOnDevice(code, groupName, storage) {\n    const upper = code.toUpperCase();\n    for (const m of membershipsOf(upper, storage))\n        store(m.app ?? \"\", storage).updateGroupName(upper, groupName);\n}\n/** The groups API of the team routes: a create or a join also keeps the\n * device's membership in every tool (`adoptMemberships`). */\nexport class TeamGroupsApi extends GroupsApi {\n    constructor(client, storage) {\n        super(client, { basePath: \"\" });\n        _TeamGroupsApi_instances.add(this);\n        _TeamGroupsApi_storage.set(this, void 0);\n        __classPrivateFieldSet(this, _TeamGroupsApi_storage, storage, \"f\");\n    }\n    async create(creatorName, name = \"\", extra = {}) {\n        return __classPrivateFieldGet(this, _TeamGroupsApi_instances, \"m\", _TeamGroupsApi_keep).call(this, await super.create(creatorName, name, extra));\n    }\n    async join(code, name, registration, attendee = \"\") {\n        return __classPrivateFieldGet(this, _TeamGroupsApi_instances, \"m\", _TeamGroupsApi_keep).call(this, await super.join(code, name, registration, attendee));\n    }\n    /** \"That's me\": the device's person (`token`) is the name-only member\n     * `memberId` in every tool from now on; the device keeps its new\n     * membership in each tool. A 409 (`claimed`): another device was first. */\n    async claim(code, memberId, token) {\n        const path = `/groups/${encodeURIComponent(code.toUpperCase())}/participants/${encodeURIComponent(memberId)}/claim/`;\n        return __classPrivateFieldGet(this, _TeamGroupsApi_instances, \"m\", _TeamGroupsApi_keep).call(this, await this.client.request(\"POST\", path, { token }));\n    }\n}\n_TeamGroupsApi_storage = new WeakMap(), _TeamGroupsApi_instances = new WeakSet(), _TeamGroupsApi_keep = function _TeamGroupsApi_keep(entered) {\n    const group = entered.group;\n    adoptMemberships(group.code, group.name || group.code, entered.memberships, __classPrivateFieldGet(this, _TeamGroupsApi_storage, \"f\"));\n    return entered;\n};\n/** The client of the team routes: the page's workshop and language on\n * every call and, on a join, the device's memberships of the code in the\n * tools (`X-Participant-Tokens`). */\nexport function teamClient(options) {\n    return new WorkshopClient({\n        baseUrl: TEAM_API,\n        ...(options.fetch ? { fetch: options.fetch } : {}),\n        headers: (path) => {\n            const headers = {\n                \"Accept-Language\": options.lang,\n            };\n            if (options.workshop && options.workshop !== \"default\")\n                headers[\"X-Workshop\"] = options.workshop;\n            const join = /^\\/groups\\/([^/]+)\\/join\\/$/.exec(path);\n            if (join) {\n                const tokens = toolTokens(decodeURIComponent(join[1]), options.storage);\n                if (tokens.length)\n                    headers[HEADER_PARTICIPANT_TOKENS] = tokens.join(\",\");\n            }\n            return headers;\n        },\n    });\n}\n// -- following a person staff moved --------------------------------------------\n/** The sessionStorage key of the one-line notice the app bar shows once\n * (\"You were moved to Table 2\"). */\nexport const GROUP_NOTICE_KEY = \"study:group-notice\";\nconst FOLLOW_TEXTS = {\n    nl: {\n        moved: \"Je bent verplaatst naar {name}.\",\n        gone: \"Je bent uit de groep gehaald.\",\n    },\n    en: {\n        moved: \"You were moved to {name}.\",\n        gone: \"You were taken out of the group.\",\n    },\n};\n/** The follow texts in `lang` (Dutch unless English). */\nexport function followTexts(lang) {\n    return lang.slice(0, 2).toLowerCase() === \"en\" ? FOLLOW_TEXTS.en : FOLLOW_TEXTS.nl;\n}\nfunction sessionStore() {\n    try {\n        return typeof sessionStorage === \"undefined\" ? null : sessionStorage;\n    }\n    catch {\n        return null;\n    }\n}\n/** Keep a line for the app bar to show once (\"\" forgets it). */\nexport function setGroupNotice(text, store = sessionStore()) {\n    try {\n        if (text)\n            store?.setItem(GROUP_NOTICE_KEY, text);\n        else\n            store?.removeItem(GROUP_NOTICE_KEY);\n    }\n    catch {\n        // Storage blocked: no notice.\n    }\n}\n/** The device's token for the team `code`: its membership of the team,\n * else its attendee token of the workshop. */\nexport function teamToken(code, workshop, storage) {\n    const own = store(TEAM_APP, storage).membership(code.toUpperCase());\n    return own?.token || store(TEAM_APP, storage).attendeeToken(workshop);\n}\n/** Ask the server where this device's person is, holding `code`, and\n * follow: a person staff moved to another group (Tables) is switched to\n * it on this device in every tool (a notice for the app bar); one taken\n * out loses the code on this device (a line for the groups page). */\nexport async function followMember(code, options) {\n    const upper = code.toUpperCase();\n    if (!upper)\n        return \"unknown\";\n    const client = options.client ?? teamClient(options);\n    const tokens = toolTokens(upper, options.storage);\n    let found;\n    try {\n        found = await client.request(\"POST\", \"/whereabouts/\", {\n            json: { code: upper },\n            token: teamToken(upper, options.workshop, options.storage),\n            headers: tokens.length ? { [HEADER_PARTICIPANT_TOKENS]: tokens.join(\",\") } : {},\n        });\n    }\n    catch {\n        return \"unknown\";\n    }\n    const texts = followTexts(options.lang);\n    const notices = options.notices ?? {\n        moved: (text) => setGroupNotice(text),\n        gone: (text) => setGroupsFlashText(text),\n    };\n    if (found?.status === \"moved\" && found.code) {\n        const groupName = found.name || found.code;\n        forgetTeam(upper, options.storage);\n        adoptMemberships(found.code, groupName, found.memberships, options.storage);\n        const team = store(TEAM_APP, options.storage);\n        if (found.participant?.token)\n            team.upsertMembership({\n                code: found.code,\n                app: TEAM_APP,\n                groupName,\n                participantId: found.participant.id,\n                participantName: found.participant.name,\n                token: found.participant.token,\n                joinedAt: new Date().toISOString(),\n            });\n        team.setActive(found.code);\n        notices.moved(texts.moved.replace(\"{name}\", groupName));\n        return \"moved\";\n    }\n    if (found?.status === \"gone\") {\n        forgetTeam(upper, options.storage);\n        notices.gone(texts.gone);\n        return \"gone\";\n    }\n    return found?.status === \"here\" ? \"here\" : \"unknown\";\n}\n/** The groups page's one line (lib/entry's `setGroupsFlash`, kept here\n * under the same key so this module imports nothing of entry). */\nfunction setGroupsFlashText(text, store = sessionStore()) {\n    try {\n        store?.setItem(\"study:groups-flash\", text);\n    }\n    catch {\n        // Storage blocked: the line is simply not shown.\n    }\n}\n//# sourceMappingURL=team.js.map","/** The way into a tool: the workshop password and the group, both on the\n * workshop's groups page (`/<lang>/workshops/<slug>/groups/`).\n *\n * A tool has no start screen of its own. On boot it calls\n *\n * - `requireGroup({ session })` when it works in groups: it resolves to\n *   the device's membership of this tool's group, or sends the device to\n *   the groups page and resolves to `null` (render nothing then);\n * - `requireAccess()` when it only needs the workshop password (a tool\n *   without groups, a screen or gallery route): `true`, or off to the\n *   groups page (`?only=password`) and `false`;\n * - `leaveForGroups()` when the device is out of its group later on\n *   (\"switch group\", removed by staff): to the groups page, coming back to\n *   this tool's first screen.\n *\n * A tool has no group screen of its own either (study-base 0.8): the\n * group's page of the workshop, `/<lang>/workshops/<slug>/groups/<CODE>/`\n * (`groupPageUrl(code)`), shows its name, code and QR code, who is in it\n * (one list for every tool), every tool of the workshop, and lets the\n * device rename itself, add a name-only member, switch group and leave.\n * The app bar's group chip links there (`mountAppbar` does it by itself\n * for a group without `onClick`); `openGroupPage()` goes there.\n *\n * The groups page comes back to the tool's own address (`?next=`, with its\n * query and hash), so a screen link (`?screen=`), a check-in\n * (`?checkin=`) or a lesson's `?prompt=` survive the detour.\n *\n * What the device holds (localStorage, shared by every tool on the origin,\n * sturnia-workshop): the workshop password (`workshop:password`) and one\n * identity store (`workshop.identity.v1`) with the active team code and a\n * membership per tool. A team code is valid in every tool of the workshop,\n * so a device in a team in one tool joins this tool's group of the team\n * without asking (`ensureMembership`). The server enforces all of it: the\n * password on every API call (`HasWorkshopPassword`; a staff session\n * passes), creating a group by `CanCreateGroup`.\n *\n * The shell (`study/base/app.html.jinja`) says what it knows on\n * `#study-app`: `data-groups-url`, `data-password` (\"true\": this viewer\n * needs the workshop password), `data-staff`, `data-workshop`.\n *\n * Staff may move a person to another group, or take them out (Tables).\n * The device is not told then: on entry `requireGroup` asks where the\n * person is now (`followMember`, lib/team) and follows a move silently\n * (the app bar shows \"You were moved to …\" once) or goes to the groups\n * page (\"You were taken out of the group\").\n *\n * A server that is away at page load (a restart: no connection, or the\n * front's 502/503/504 page) does not send the device to the groups page,\n * which is away too: `requireGroup` tries again after 2, 4, 8, then every\n * 15 s (`retryDelay` of lib/connection, `ENTRY_RETRIES` times; `onWait`\n * lets the tool say so meanwhile).\n *\n * Tools import it from the package: `@starling-study/study-base/lib/entry`\n * (a tool keeps no copy of it). It imports nothing but sturnia-workshop,\n * lib/team and lib/connection. */\nimport { joinCodeFromLocation, WorkshopClient, } from \"@starling-cloud/sturnia-workshop\";\nimport { isFrontStatus, isOutage, retryDelay } from \"./connection.js\";\nimport { followMember } from \"./team.js\";\n/** The base API, whose `access/` probe checks the workshop password. */\nexport const BASE_API = \"/api/base\";\nexport const ACCESS_PROBE = \"/access/\";\n/** `?only=password` on the groups page: the tool needs no group. */\nexport const ONLY_PASSWORD = \"password\";\n/** How often `requireGroup` tries again while the server is away at page\n * load: 2 + 4 + 8 + 15 × 5 s, about a minute and a half. */\nexport const ENTRY_RETRIES = 8;\n/** Whether a failed request failed for want of the server: no connection\n * (status 0), the outage answer of lib/connection, or the front's\n * 502/503/504/52x without a code of the app's (its HTML page). */\nexport function serverAway(error) {\n    if (isOutage(error))\n        return true;\n    if (!error || typeof error !== \"object\")\n        return false;\n    const { status, code } = error;\n    return typeof status === \"number\" && isFrontStatus(status) && !code;\n}\nfunction sleep(ms) {\n    return new Promise((resolve) => setTimeout(resolve, ms));\n}\n/** The shell's dataset (`#study-app`), `{}` without a page. */\nfunction shellDataset() {\n    if (typeof document === \"undefined\")\n        return {};\n    return document.getElementById(\"study-app\")?.dataset ?? {};\n}\n/** The entry attributes of the shell. Without `data-groups-url` (an older\n * server) the groups page is derived from the address: `/<lang>/workshops/<slug>/groups/`. */\nexport function readEntryConfig(data = shellDataset(), loc = typeof location ===\n    \"undefined\"\n    ? undefined\n    : location) {\n    const workshop = data.workshop || \"\";\n    const lang = (data.lang || \"nl\").slice(0, 2);\n    const fromPath = /^(\\/(?:[\\w-]+\\/)?workshops\\/[^/]+\\/)/.exec(loc?.pathname ?? \"\");\n    const derived = fromPath\n        ? `${fromPath[1]}groups/`\n        : `/${lang}/workshops/${workshop || \"default\"}/groups/`;\n    return {\n        groupsUrl: data.groupsUrl || derived,\n        password: data.password === \"true\",\n        staff: data.staff === \"true\",\n        workshop,\n        lang,\n    };\n}\n/** A `next` the groups page may send the device to: a path on this site\n * (with query and hash), never another host. `\"\"` for anything else. */\nexport function safeNext(value) {\n    const target = (value ?? \"\").trim();\n    if (!target.startsWith(\"/\") || target.startsWith(\"//\"))\n        return \"\";\n    if (target.includes(\"\\\\\"))\n        return \"\";\n    // Control characters (a browser drops a tab or newline: \"/\\t/evil\").\n    for (const char of target) {\n        const code = char.charCodeAt(0);\n        if (code < 32 || code === 127)\n            return \"\";\n    }\n    return target;\n}\n/** The page's address without `join`/`code` (they go to the groups page\n * on their own): path, query and hash. */\nexport function addressWithoutJoin(loc) {\n    const params = new URLSearchParams(loc.search);\n    params.delete(\"join\");\n    params.delete(\"code\");\n    const search = params.toString();\n    return `${loc.pathname}${search ? `?${search}` : \"\"}${loc.hash}`;\n}\n/** The groups page with `next` and the other parameters. */\nexport function groupsAddress(groupsUrl, next, extra = {}) {\n    const [path, query = \"\"] = groupsUrl.split(\"?\");\n    const params = new URLSearchParams(query);\n    for (const [key, value] of Object.entries(extra))\n        if (value)\n            params.set(key, value);\n    const target = safeNext(next);\n    if (target)\n        params.set(\"next\", target);\n    const search = params.toString();\n    return `${path}${search ? `?${search}` : \"\"}`;\n}\n/** The page of group `code` of the workshop: the groups page's address\n * with the code (`/<lang>/workshops/<slug>/groups/<CODE>/`). `\"\"` without\n * a code. */\nexport function groupPageUrl(code, config = readEntryConfig()) {\n    const clean = code.trim().toUpperCase().replace(/[^A-Z0-9]/g, \"\");\n    if (!clean)\n        return \"\";\n    const [path] = config.groupsUrl.split(/[?#]/, 1);\n    return `${path.endsWith(\"/\") ? path : `${path}/`}${clean}/`;\n}\n/** The team code this device is in right now (the active code every tool\n * shares), or `\"\"`. */\nexport function activeGroupCode(session) {\n    if (session)\n        return session.identity.get().activeCode ?? \"\";\n    try {\n        const raw = typeof localStorage === \"undefined\"\n            ? null\n            : localStorage.getItem(\"workshop.identity.v1\");\n        const parsed = raw ? JSON.parse(raw) : {};\n        return typeof parsed.activeCode === \"string\" ? parsed.activeCode : \"\";\n    }\n    catch {\n        return \"\";\n    }\n}\n/** To the page of the device's group (`code`, else the active one); the\n * groups page when there is none. A navigation the visitor chose: Back\n * comes back to the tool (`location.assign`). */\nexport function openGroupPage(code = \"\", options = {}) {\n    const config = options.config ?? readEntryConfig();\n    const go = options.go ?? ((url) => location.assign(url));\n    go(groupPageUrl(code || activeGroupCode(), config) || config.groupsUrl);\n}\n/** The client of the base API's password probe: the device's one stored\n * workshop password, the page's workshop in `X-Workshop`. */\nexport function accessClient(workshop, storage) {\n    return new WorkshopClient({\n        baseUrl: BASE_API,\n        ...(storage ? { storage } : {}),\n        headers: workshop && workshop !== \"default\"\n            ? { \"X-Workshop\": workshop }\n            : {},\n    });\n}\n/** Whether this device may use the workshop: staff, a workshop without a\n * password, or a stored password the server takes. A device that never\n * typed it costs no request. A server that cannot be reached counts as\n * \"in\": the tool then shows its own connection error. */\nexport async function hasAccess(config, client) {\n    if (config.staff || !config.password)\n        return true;\n    if (!client.storedPassword())\n        return false;\n    return !(await client.passwordRequired(ACCESS_PROBE));\n}\nfunction resolved(options) {\n    const config = options.config ?? readEntryConfig();\n    return {\n        config,\n        client: options.client ?? accessClient(config.workshop),\n        loc: options.loc ?? location,\n        go: options.go ?? ((url) => location.replace(url)),\n    };\n}\n/** The workshop password, for a page that needs no group: `true` when the\n * device may go on; otherwise it is sent to the groups page (which asks\n * the password and comes straight back) and `false`. */\nexport async function requireAccess(options = {}) {\n    const { config, client, loc, go } = resolved(options);\n    if (await hasAccess(config, client))\n        return true;\n    const next = `${loc.pathname}${loc.search}${loc.hash}`;\n    go(groupsAddress(config.groupsUrl, next, { only: ONLY_PASSWORD }));\n    return false;\n}\n/** The sessionStorage key of the line the groups page shows once (\"You\n * were taken out of the group\"): set by a tool, taken by the page. */\nexport const GROUPS_FLASH_KEY = \"study:groups-flash\";\nfunction flashStore() {\n    try {\n        return typeof sessionStorage === \"undefined\" ? null : sessionStorage;\n    }\n    catch {\n        return null;\n    }\n}\n/** Keep a line for the groups page to show once (in the tool's words and\n * language), e.g. why the device is back there. \"\" forgets it. */\nexport function setGroupsFlash(text, store = flashStore()) {\n    try {\n        if (text)\n            store?.setItem(GROUPS_FLASH_KEY, text);\n        else\n            store?.removeItem(GROUPS_FLASH_KEY);\n    }\n    catch {\n        // Storage blocked: the line is simply not shown.\n    }\n}\n/** The waiting line, taken (shown once); \"\" when there is none. */\nexport function takeGroupsFlash(store = flashStore()) {\n    try {\n        const text = store?.getItem(GROUPS_FLASH_KEY) ?? \"\";\n        if (text)\n            store?.removeItem(GROUPS_FLASH_KEY);\n        return text;\n    }\n    catch {\n        return \"\";\n    }\n}\n/** To the groups page, coming back to this tool's page without its hash\n * route (the tool's first screen) and without a join code: the device\n * left its group (\"switch group\") or was taken out of it. A line set with\n * `setGroupsFlash` before is shown there. */\nexport function leaveForGroups(options = {}) {\n    const { config, loc, go } = resolved(options);\n    const next = addressWithoutJoin({ ...loc, hash: \"\" });\n    go(groupsAddress(config.groupsUrl, next));\n}\n/** The device is out of its group in this tool (its token refused, the\n * group loads without it): ask where the person is now. Moved by staff:\n * this page again, in the new group (the app bar says so once). Anything\n * else: the groups page (`leaveForGroups`; \"taken out of the group\" when\n * the server says so). Resolves to what it found. */\nexport async function followOrLeave(options = {}) {\n    const { config, loc } = resolved(options);\n    const code = options.code ?? activeGroupCode();\n    const follow = options.follow ??\n        ((active) => followMember(active, { workshop: config.workshop, lang: config.lang ?? \"nl\" }));\n    const where = code ? await follow(code) : \"unknown\";\n    if (where === \"moved\") {\n        const reload = options.reload ?? ((address) => location.replace(address));\n        reload(addressWithoutJoin(loc));\n        return where;\n    }\n    leaveForGroups(options);\n    return where;\n}\n/** The password, then this tool's group:\n *\n * - a `?join=CODE` link enters that team's group here, straight away (a\n *   team this device knows, else a join under `joinName()`);\n * - else the team this device is in (the active code every tool shares);\n * - else, or when that fails (unknown code, details the workshop asks\n *   first, the server says no), the groups page with `next` = this page\n *   (and the link's `join`), which comes back here once the device is in;\n * - a server that is away meanwhile (`serverAway`) is asked again after\n *   `retryDelay` (`retries` times) before the device is sent anywhere.\n *\n * Resolves to the membership, or `null` after sending the device away. */\nexport async function requireGroup(options) {\n    const { config, client, loc, go } = resolved(options);\n    const { session } = options;\n    const joinCode = joinCodeFromLocation(loc);\n    const next = addressWithoutJoin(loc);\n    if (!(await hasAccess(config, client))) {\n        go(groupsAddress(config.groupsUrl, next, { join: joinCode }));\n        return null;\n    }\n    let code = joinCode || session.identity.get().activeCode || \"\";\n    if (code && !joinCode) {\n        // Moved by staff since: follow (the active code is the new one);\n        // taken out: the groups page, which says so.\n        const follow = options.follow ??\n            ((active) => followMember(active, {\n                workshop: config.workshop,\n                lang: config.lang ?? \"nl\",\n            }));\n        const where = await follow(code);\n        if (where === \"gone\") {\n            go(groupsAddress(config.groupsUrl, next));\n            return null;\n        }\n        if (where === \"moved\")\n            code = session.identity.get().activeCode || \"\";\n    }\n    let membership = null;\n    const retries = options.retries ?? ENTRY_RETRIES;\n    const wait = options.wait ?? sleep;\n    for (let failures = 0;;) {\n        try {\n            membership = code ? await session.ensureMembership(code) : null;\n            if (!membership && joinCode) {\n                const name = options.joinName?.() ?? session.identity.name;\n                await session.joinGroup(joinCode, name);\n                membership = session.membership;\n            }\n            break;\n        }\n        catch (error) {\n            membership = null;\n            if (!serverAway(error) || failures >= retries)\n                break;\n            failures += 1;\n            const delay = retryDelay(failures);\n            options.onWait?.(failures, delay);\n            await wait(delay);\n        }\n    }\n    if (membership) {\n        if (joinCode) {\n            const drop = options.dropJoin ??\n                ((address) => history.replaceState(history.state, \"\", address));\n            drop(next);\n        }\n        return membership;\n    }\n    go(groupsAddress(config.groupsUrl, next, { join: joinCode }));\n    return null;\n}\n//# sourceMappingURL=entry.js.map","/** Which workshop each group of this device belongs to.\n *\n * sturnia-workshop's identity store keeps the group code and the token, not\n * the workshop, and the API looks a group up inside the request's workshop.\n * A bookmark of `/<lang>/<app>/` without `?workshop=` (the page then belongs\n * to the default workshop) asked for the stored group in the wrong one and\n * got a 404. So the workshop of every group joined is kept next to the\n * identity, and a page without a workshop of its own takes the one of the\n * active group (lib/config). */\n/** The slug that means \"no workshop named\": the API's default one. */\nexport const DEFAULT_WORKSHOP = \"default\";\nexport function workshopsKey(app) {\n    return `study-${app}.workshops.v1`;\n}\n/** The shared identity store of every app on the origin (sturnia-workshop 0.2). */\nexport const IDENTITY_KEY = \"workshop.identity.v1\";\n/** The per-app identity store of study-base 0.3, imported once into the\n * shared one by `createAppSession` (`legacyKey`) and then removed. */\nexport function identityKey(app) {\n    return `study-${app}.identity.v1`;\n}\n/** \"\" for the default workshop, else the slug. */\nexport function normaliseWorkshop(slug) {\n    const value = (slug ?? \"\").trim();\n    return value === DEFAULT_WORKSHOP ? \"\" : value;\n}\nfunction localStore() {\n    try {\n        return typeof localStorage === \"undefined\" ? null : localStorage;\n    }\n    catch {\n        return null;\n    }\n}\nfunction readMap(app, store) {\n    if (!store)\n        return {};\n    try {\n        const parsed = JSON.parse(store.getItem(workshopsKey(app)) ?? \"{}\");\n        return parsed && typeof parsed === \"object\"\n            ? parsed\n            : {};\n    }\n    catch {\n        return {};\n    }\n}\n/** The workshop a group was joined in: `\"\"` for the default one, `null`\n * when this device does not know (a group joined before this was kept). */\nexport function workshopOf(app, code, store = localStore()) {\n    const value = readMap(app, store)[code.toUpperCase()];\n    return typeof value === \"string\" ? normaliseWorkshop(value) : null;\n}\n/** Remember the workshop of a group. */\nexport function rememberWorkshop(app, code, slug, store = localStore()) {\n    if (!store)\n        return;\n    const map = readMap(app, store);\n    map[code.toUpperCase()] = normaliseWorkshop(slug);\n    try {\n        store.setItem(workshopsKey(app), JSON.stringify(map));\n    }\n    catch {\n        // Storage full or blocked: the page's own workshop still works.\n    }\n}\nfunction storedActiveCode(store, key) {\n    try {\n        const identity = JSON.parse(store.getItem(key) ?? \"{}\");\n        return typeof identity.activeCode === \"string\"\n            ? identity.activeCode\n            : \"\";\n    }\n    catch {\n        return \"\";\n    }\n}\n/** The active team code of the shared identity store\n * (`workshop.identity.v1`: `activeCode` is one for every app), or, on a\n * device that still has only the old per-app store, that one's; \"\" when\n * neither has one. */\nexport function activeCode(app, store = localStore()) {\n    if (!store)\n        return \"\";\n    return (storedActiveCode(store, IDENTITY_KEY) ||\n        storedActiveCode(store, identityKey(app)));\n}\n/** The workshop this page talks to: the page's own (`?workshop=`, also\n * `default`), or — when the address names none — the active group's,\n * unless the address joins another group (a QR code of the default\n * workshop). */\nexport function pageWorkshop(app, given, search, store = localStore()) {\n    const own = normaliseWorkshop(given);\n    const params = new URLSearchParams(search);\n    // A workshop in the address is the page's, `?workshop=default` too.\n    if (own || params.has(\"workshop\"))\n        return own;\n    const code = activeCode(app, store);\n    if (!code)\n        return \"\";\n    const join = (params.get(\"join\") ??\n        params.get(\"code\") ??\n        \"\").toUpperCase();\n    if (join && join !== code.toUpperCase())\n        return \"\";\n    return workshopOf(app, code, store) ?? \"\";\n}\n/** `search` with `workshop=<slug>` set (or removed for `\"\"`). */\nexport function searchWithWorkshop(search, slug) {\n    const params = new URLSearchParams(search);\n    if (slug)\n        params.set(\"workshop\", slug);\n    else\n        params.delete(\"workshop\");\n    const rest = params.toString();\n    return rest ? `?${rest}` : \"\";\n}\n/** A page address under `/<lang>/workshops/<slug>/`: its prefix and the rest after the slug. */\nconst WORKSHOP_PATH = /^(\\/(?:[\\w-]+\\/)?workshops\\/)[^/]+(\\/.*)$/;\n/** The same page in workshop `slug` (`\"\"`: the default one): the slug in\n * the path swapped on a `/<lang>/workshops/<slug>/<app>/` page (whose path,\n * not `?workshop=`, names its workshop; the query loses `workshop`), else\n * `?workshop=<slug>` on an old `/<lang>/<app>/` page. */\nexport function addressInWorkshop(pathname, search, slug) {\n    const match = WORKSHOP_PATH.exec(pathname);\n    if (!match)\n        return `${pathname}${searchWithWorkshop(search, slug || DEFAULT_WORKSHOP)}`;\n    return `${match[1]}${slug || DEFAULT_WORKSHOP}${match[2]}${searchWithWorkshop(search, \"\")}`;\n}\n//# sourceMappingURL=workshops.js.map","// ============================================================================\n// Switching phones: an app may send every phone of a workshop (or a team)\n// elsewhere, e.g. Agenda at the start of a block set to \"switch every phone\n// into the app\". The lobby (`[data-study-switch]`) and the participant app\n// bar (`mountAppbar`) ask `GET /api/base/switch/?workshop=<slug>&team=<code>`\n// every 20 seconds; an answer `{url, key}` whose key this device has not\n// followed yet opens the URL once (the key is remembered in localStorage).\n// ============================================================================\nexport const SWITCH_KEY = 'study:switch';\nexport const SWITCH_INTERVAL = 20000;\nfunction storageOrNull() {\n    try {\n        return window.localStorage;\n    }\n    catch {\n        return null;\n    }\n}\n/** The keys this device has followed (newest last, at most 20). */\nexport function followedKeys(store) {\n    try {\n        const raw = store?.getItem(SWITCH_KEY);\n        const keys = raw ? JSON.parse(raw) : [];\n        return Array.isArray(keys) ? keys.filter((key) => typeof key === 'string') : [];\n    }\n    catch {\n        return [];\n    }\n}\n/** Remember `key` as followed. */\nexport function rememberKey(key, store) {\n    const keys = followedKeys(store).filter((known) => known !== key);\n    keys.push(key);\n    try {\n        store?.setItem(SWITCH_KEY, JSON.stringify(keys.slice(-20)));\n    }\n    catch {\n        // No storage: the key is followed again on the next page.\n    }\n}\n/** The URL to open for `answer`, or `null` (none, or followed before). */\nexport function switchTarget(answer, store) {\n    if (!answer || !answer.url || !answer.key)\n        return null;\n    if (followedKeys(store).includes(answer.key))\n        return null;\n    return answer.url;\n}\n/** One poll: fetch the answer and follow it when it is new. Resolves to the URL followed, or `null`. */\nexport async function pollSwitch(options) {\n    const fetcher = options.fetcher ?? ((...args) => fetch(...args));\n    const store = options.store === undefined ? storageOrNull() : options.store;\n    const query = new URLSearchParams({ workshop: options.workshop });\n    if (options.team)\n        query.set('team', options.team);\n    let answer = null;\n    try {\n        const response = await fetcher(`${options.endpoint}?${query}`, { credentials: 'same-origin', headers: { Accept: 'application/json' } });\n        if (!response.ok)\n            return null;\n        answer = (await response.json());\n    }\n    catch {\n        return null;\n    }\n    const url = switchTarget(answer, store);\n    if (!url)\n        return null;\n    rememberKey(answer.key, store);\n    (options.navigate ?? ((target) => window.location.assign(target)))(url);\n    return url;\n}\n/** Poll every `interval` ms while the page is shown; returns a stop function. */\nexport function startSwitchPoll(options) {\n    if (!options.workshop)\n        return () => undefined;\n    const timer = options.timer ?? window;\n    const id = timer.setInterval(() => {\n        if (typeof document !== 'undefined' && document.visibilityState === 'hidden')\n            return;\n        void pollSwitch(options);\n    }, options.interval ?? SWITCH_INTERVAL);\n    return () => timer.clearInterval(id);\n}\n/** The lobby: `<section data-study-switch=\"/api/base/switch/\" data-workshop=\"slug\" data-team=\"CODE\">`. */\nexport function initSwitch(root = document) {\n    root.querySelectorAll('[data-study-switch][data-workshop]').forEach((node) => {\n        startSwitchPoll({\n            endpoint: node.dataset.studySwitch || '/api/base/switch/',\n            workshop: node.dataset.workshop ?? '',\n            team: node.dataset.team ?? '',\n        });\n    });\n}\n//# sourceMappingURL=switch.js.map","import { startSwitchPoll } from './switch.js';\n// ============================================================================\n// Starling Study Base - The participant app bar\n// ============================================================================\n// `mountAppbar(host, options)` builds the one header of a participant app:\n// the theme's `study-appbar` (stylescape-starling-studio doc/study/dashboard.md §6)\n// with the wordmark and the app name, the group chip, the app's links, the\n// app switcher, the language menu (the theme's `study-lang-menu`, §1.1.1),\n// the theme toggle and a phone menu button. The wordmark's mark is the\n// Starling '+'.\n//\n// The app switcher lists the other apps of the workshop (`options.apps`,\n// else the shell's `data-apps` on `#study-app`) as a `study-menu`. Each\n// link carries `?join=<code>` with the team code the device is active in\n// (`activeCode` of the shared identity store `workshop.identity.v1`, read\n// again every time the menu opens), so a team moves between apps without\n// joining again. One app or none: no switcher; embedded: none either.\n//\n// The group chip is a link to the group's page of the workshop\n// (`/<lang>/workshops/<slug>/groups/<CODE>/`: its members, QR code and\n// every tool): `group.href`, else derived from the shell's\n// `data-groups-url`. A group with `onClick` (a tool released before\n// study-base 0.8, with a group screen of its own) keeps its button. The\n// switcher's panel starts with the same page (\"Your group · all tools\"),\n// and a line left in sessionStorage (`study:group-notice`: \"You were moved\n// to Table 2\", lib/team) is shown once under the bar.\n//\n// An app imports the source through its `file:../study-base` dependency:\n//\n//     import { mountAppbar } from '@starling-cloud/study-base/appbar'\n//\n// The built bundle `study/base/js/study_base_appbar[.min].js` is the same\n// module for a page without a bundler; it also sets\n// `window.StudyBase.mountAppbar`.\n//\n// The page structure is `header` + `main` as siblings: when the host sits\n// inside the shell's `<main>` (`app.html.jinja`), the bar goes right before\n// that `main`, else it is the host's first child. An app view must not\n// render a `main` of its own (the shell has it) and should not move\n// `handle.element` back inside the host.\n//\n// Embedded in a lesson (study-syllabus puts a tool in an iframe with\n// `?embed=1`), there is no bar at all: the lesson's header is the page's one\n// header. The bar is still drawn (`study-appbar--embed`, `hidden`) for apps\n// that read `handle.element`, but it is not in the page; `is-embedded` is set\n// on <html>. The theme follows the lesson: `?theme=light|dark` in the URL,\n// else the parent page's `data-theme`, else the stored choice; a later\n// `postMessage({type: 'study:theme', theme})` from the lesson (same origin\n// only) switches it. `mountAppbar`\n// reads `embed=1` from the URL itself; `options.embed` forces it.\n//\n// This file imports nothing, so it can be bundled into any app as it is.\n// ============================================================================\n/** The localStorage key of the theme choice (shared with the portal script). */\nexport const THEME_KEY = 'study:theme';\n/** The localStorage key of the last language chosen. */\nexport const LANG_KEY = 'study:lang';\n/** The localStorage key of the identity store every app shares (sturnia-workshop). */\nexport const IDENTITY_KEY = 'workshop.identity.v1';\n/** The sessionStorage key of the line shown once under the bar (lib/team's `setGroupNotice`). */\nexport const GROUP_NOTICE_KEY = 'study:group-notice';\nconst TEXT = {\n    nl: {\n        language: 'Taal',\n        languageOf: 'Taal: ',\n        menu: 'Menu',\n        theme: 'Wissel tussen licht en donker thema',\n        group: 'Groep',\n        yourGroup: 'Je groep',\n        apps: 'Tools',\n        switchApp: 'Naar een andere tool',\n        groupPage: 'Je groep · alle tools',\n        openGroup: 'Groepspagina openen',\n        dismiss: 'Sluiten',\n    },\n    en: {\n        language: 'Language',\n        languageOf: 'Language: ',\n        menu: 'Menu',\n        theme: 'Switch light or dark theme',\n        group: 'Group',\n        yourGroup: 'Your group',\n        apps: 'Tools',\n        switchApp: 'Switch to another tool',\n        groupPage: 'Your group · all tools',\n        openGroup: 'Open the group page',\n        dismiss: 'Dismiss',\n    },\n};\n/** Each language in its own name, as the menu lists it. */\nconst LANGUAGE_NAMES = {\n    nl: 'Nederlands',\n    en: 'English',\n};\nconst ICON_LANGUAGE = '<svg class=\"study-lang-menu__icon\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\" aria-hidden=\"true\"><path d=\"M12 21a9 9 0 100-18 9 9 0 000 18zM3 12h18M12 3c2.5 2.6 3.8 5.6 3.8 9s-1.3 6.4-3.8 9M12 3C9.5 5.6 8.2 8.6 8.2 12s1.3 6.4 3.8 9\"/></svg>';\nconst ICON_MENU = '<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\" aria-hidden=\"true\"><path d=\"M4 7h16M4 12h16M4 17h16\"/></svg>';\nconst ICON_APPS = '<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\" aria-hidden=\"true\"><path d=\"M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z\"/></svg>';\nconst ICON_THEME = '<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"12\" r=\"8\"/><path d=\"M12 4a8 8 0 000 16z\" fill=\"currentColor\"/></svg>';\nlet counter = 0;\nfunction text(lang, key) {\n    return (TEXT[lang] ?? TEXT.en)[key];\n}\nfunction languageName(code) {\n    return LANGUAGE_NAMES[code] ?? code.toUpperCase();\n}\nfunction el(tag, className, attrs = {}) {\n    const node = document.createElement(tag);\n    if (className)\n        node.className = className;\n    for (const [name, value] of Object.entries(attrs))\n        node.setAttribute(name, value);\n    return node;\n}\n// -- theme --------------------------------------------------------------------\n/** The theme in force: the explicit one on `<html>`, else the OS's. */\nexport function currentTheme() {\n    const explicit = document.documentElement.dataset.theme;\n    if (explicit === 'light' || explicit === 'dark')\n        return explicit;\n    return window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n}\n/** Flip the theme, remember it under `study:theme` and return the new one. */\nexport function toggleTheme() {\n    const next = currentTheme() === 'dark' ? 'light' : 'dark';\n    document.documentElement.dataset.theme = next;\n    try {\n        localStorage.setItem(THEME_KEY, next);\n    }\n    catch {\n        // Private mode: the choice lasts for this page only.\n    }\n    return next;\n}\n/** Put a stored theme choice on `<html>` (call it early to avoid a flash). */\nexport function applyStoredTheme() {\n    try {\n        const stored = localStorage.getItem(THEME_KEY);\n        if (stored === 'light' || stored === 'dark')\n            document.documentElement.dataset.theme = stored;\n    }\n    catch {\n        // No storage: the page follows the OS.\n    }\n}\n// -- embedding ----------------------------------------------------------------\n/** The theme a lesson passes to an embedded tool (`?theme=light|dark`), or `null`. */\nexport function urlTheme(location = window.location) {\n    const theme = new URLSearchParams(location.search).get('theme');\n    return theme === 'light' || theme === 'dark' ? theme : null;\n}\n/** Whether the page URL asks for the embedded layout (`?embed=1`). */\nexport function isEmbedded(location = window.location) {\n    return new URLSearchParams(location.search).get('embed') === '1';\n}\n/**\n * `href` with `embed=1` added, for a link that leaves the page from inside\n * an embedded app (as an app keeps `workshop`). Hash links and links that\n * have it already come back unchanged.\n */\nexport function keepEmbed(href) {\n    if (href.startsWith('#') || /[?&]embed=1(&|#|$)/.test(href))\n        return href;\n    const [rest, hash = ''] = href.split('#', 2);\n    return `${rest}${rest.includes('?') ? '&' : '?'}embed=1${hash ? `#${hash}` : ''}`;\n}\n/** The parent page's `<html>` when this page is framed same-origin, else `null`. */\nfunction parentRoot() {\n    try {\n        if (window.parent && window.parent !== window)\n            return window.parent.document.documentElement;\n    }\n    catch {\n        // Another origin: not readable.\n    }\n    return null;\n}\n/**\n * Take the theme of the page this one is embedded in (when it is readable\n * and has an explicit one), else the stored choice.\n */\nexport function applyParentTheme() {\n    const theme = urlTheme() ?? parentRoot()?.dataset.theme;\n    if (theme === 'light' || theme === 'dark')\n        document.documentElement.dataset.theme = theme;\n    else\n        applyStoredTheme();\n}\n// -- language -----------------------------------------------------------------\n/**\n * The current page in another language: the `/<lang>/` prefix swapped (or\n * added), the query and the hash kept.\n */\nexport function languageUrl(lang, langs, location = window.location) {\n    const parts = location.pathname.split('/');\n    if (langs.includes(parts[1])) {\n        parts[1] = lang;\n    }\n    else {\n        parts.splice(1, 0, lang);\n    }\n    return `${parts.join('/')}${location.search}${location.hash}`;\n}\n// -- apps -----------------------------------------------------------------------\n/**\n * The team code the device is active in, from the shared identity store\n * (`workshop.identity.v1`: `{name, activeCode, memberships}`), or `\"\"`.\n */\nexport function activeTeamCode(storage = storageOrNull()) {\n    try {\n        const raw = storage?.getItem(IDENTITY_KEY);\n        if (!raw)\n            return '';\n        const identity = JSON.parse(raw);\n        return typeof identity.activeCode === 'string' ? identity.activeCode.trim() : '';\n    }\n    catch {\n        return '';\n    }\n}\nfunction storageOrNull() {\n    try {\n        return typeof localStorage === 'undefined' ? null : localStorage;\n    }\n    catch {\n        return null;\n    }\n}\n/** `href` with `join=<code>` added (`&` after a query); unchanged without a code. */\nexport function appHref(href, code) {\n    if (!code)\n        return href;\n    const [rest, hash = ''] = href.split('#', 2);\n    const joined = `${rest}${rest.includes('?') ? '&' : '?'}join=${encodeURIComponent(code)}`;\n    return hash ? `${joined}#${hash}` : joined;\n}\n/**\n * The apps the shell lists: `data-apps` (JSON `[{slug, label, path}]`) on the\n * closest `#study-app` or `[data-apps]` above or at `host`; `[]` without it.\n */\nexport function readShellApps(host) {\n    const node = host.closest('#study-app, [data-apps]');\n    const raw = node?.dataset.apps;\n    if (!raw)\n        return [];\n    try {\n        const parsed = JSON.parse(raw);\n        if (!Array.isArray(parsed))\n            return [];\n        return parsed\n            .map((item) => item)\n            .filter((item) => typeof item.slug === 'string' && typeof (item.path ?? item.href) === 'string')\n            .map((item) => ({\n            slug: item.slug,\n            label: typeof item.label === 'string' ? item.label : item.slug,\n            href: (item.path ?? item.href),\n        }));\n    }\n    catch {\n        return [];\n    }\n}\n/** The shell's groups page (`data-groups-url` on `#study-app` or `[data-groups-url]` at or above `host`), or `\"\"`. */\nexport function readGroupsUrl(host) {\n    return host.closest('#study-app, [data-groups-url]')?.dataset.groupsUrl ?? '';\n}\n/** The page of group `code` under the groups page `groupsUrl` (`…/groups/<CODE>/`), `\"\"` without either. */\nexport function groupPageHref(groupsUrl, code) {\n    const clean = code.trim().toUpperCase().replace(/[^A-Z0-9]/g, '');\n    const path = groupsUrl.split(/[?#]/, 1)[0];\n    if (!clean || !path)\n        return '';\n    return `${path.endsWith('/') ? path : `${path}/`}${clean}/`;\n}\n/** Take the line left for the bar (shown once), `\"\"` when there is none. */\nexport function takeGroupNotice(store = sessionOrNull()) {\n    try {\n        const text = store?.getItem(GROUP_NOTICE_KEY) ?? '';\n        if (text)\n            store?.removeItem(GROUP_NOTICE_KEY);\n        return text;\n    }\n    catch {\n        return '';\n    }\n}\nfunction sessionOrNull() {\n    try {\n        return typeof sessionStorage === 'undefined' ? null : sessionStorage;\n    }\n    catch {\n        return null;\n    }\n}\nfunction isActive(link) {\n    if (link.active !== undefined)\n        return link.active;\n    if (!link.href.startsWith('#'))\n        return false;\n    const hash = window.location.hash || '#/';\n    const route = link.href.replace(/\\/$/, '');\n    // The root route (`#/`) is current on itself only: every other route is\n    // \"under\" it, and would leave two tabs current.\n    if (route === '#')\n        return hash === '#/' || hash === '#';\n    return hash === link.href || hash === route || hash.startsWith(`${route}/`);\n}\n// -- the bar ------------------------------------------------------------------\n/**\n * Build the app bar as the first child of `host` and keep it working.\n */\nexport function mountAppbar(host, options) {\n    let current = { ...options };\n    // The switch poll: every 20 s, unless embedded or switched off.\n    const switchWorkshop = options.workshop ?? host.dataset.workshop ?? '';\n    const stopSwitch = options.switchEndpoint === false || (options.embed ?? isEmbedded()) || !switchWorkshop\n        ? () => undefined\n        : startSwitchPoll({\n            endpoint: options.switchEndpoint || '/api/base/switch/',\n            workshop: switchWorkshop,\n            team: activeTeamCode(),\n        });\n    const navId = `study-appbar-nav-${++counter}`;\n    const header = el('header', 'study-appbar');\n    let menuButton = null;\n    let langMenu = null;\n    let appMenu = null;\n    let appNodes = [];\n    const shellApps = options.apps ? [] : readShellApps(host);\n    const groupsUrl = readGroupsUrl(host);\n    let notice = null;\n    let linkNodes = [];\n    let langNodes = [];\n    const setOpen = (open) => {\n        header.classList.toggle('is-open', open);\n        menuButton?.setAttribute('aria-expanded', String(open));\n    };\n    // The language links keep the current route (`#/final`, not the one the bar was drawn on).\n    const refreshLangLinks = () => {\n        for (const { code, node } of langNodes)\n            node.href = languageUrl(code, current.langs);\n    };\n    const markLinks = () => {\n        for (const { link, node } of linkNodes) {\n            if (isActive(link))\n                node.setAttribute('aria-current', 'page');\n            else\n                node.removeAttribute('aria-current');\n        }\n        refreshLangLinks();\n    };\n    // `header` + `main` as siblings: before the shell's `main` when the host is in it.\n    const place = () => {\n        if (embedded()) {\n            header.remove();\n            return;\n        }\n        if (header.isConnected)\n            return;\n        const main = host.closest('main');\n        if (main)\n            main.before(header);\n        else\n            host.prepend(header);\n    };\n    const embedded = () => current.embed ?? isEmbedded();\n    // The switcher's links carry the team code the device is in right now.\n    const refreshAppLinks = () => {\n        const code = activeTeamCode();\n        for (const { app, node } of appNodes)\n            node.href = appHref(app.href, code);\n    };\n    const render = () => {\n        const { app, title, lang, langs, wordmarkHref, group, links, actions } = current;\n        const apps = current.apps ?? shellApps;\n        const embed = embedded();\n        header.dataset.app = app;\n        header.classList.remove('is-open');\n        header.classList.toggle('study-appbar--embed', embed);\n        header.hidden = embed;\n        document.documentElement.classList.toggle('is-embedded', embed);\n        header.replaceChildren();\n        langNodes = [];\n        // Embedded, the wordmark is plain text: its link would leave the lesson's frame.\n        const brand = embed\n            ? el('span', 'study-wordmark study-appbar__brand')\n            : el('a', 'study-wordmark study-appbar__brand', { href: wordmarkHref });\n        brand.append(el('span', 'study-wordmark__mark', { 'aria-hidden': 'true' }), Object.assign(el('span', 'study-wordmark__name'), { textContent: 'Starling' }), Object.assign(el('span', 'study-wordmark__study'), { textContent: 'Study' }), Object.assign(el('span', 'study-wordmark__app'), { textContent: title }));\n        header.append(brand);\n        // The group's page: given, else the shell's groups page with the code.\n        const groupHref = group ? group.href || groupPageHref(groupsUrl, group.code) : '';\n        if (group) {\n            const chip = group.onClick\n                ? el('button', 'study-appbar__group', { type: 'button' })\n                : groupHref\n                    ? el('a', 'study-appbar__group', {\n                        href: embed ? keepEmbed(groupHref) : groupHref,\n                        'aria-label': `${text(lang, 'openGroup')}: ${group.name || group.code}`,\n                    })\n                    : el('span', 'study-appbar__group');\n            if (groupHref && !group.onClick && window.location.pathname === groupHref)\n                chip.setAttribute('aria-current', 'page');\n            chip.title = group.name || text(lang, 'yourGroup');\n            const label = el('span', 'study-appbar__group-label');\n            label.textContent = text(lang, 'group');\n            chip.append(label, ` ${group.code}`);\n            if (group.onClick)\n                chip.addEventListener('click', group.onClick);\n            header.append(chip);\n        }\n        linkNodes = [];\n        if (links.length) {\n            const nav = el('nav', 'study-appbar__nav', { id: navId, 'aria-label': title });\n            for (const link of links) {\n                const node = el('a', 'study-appbar__link', { href: embed ? keepEmbed(link.href) : link.href });\n                node.textContent = link.label;\n                node.addEventListener('click', () => setOpen(false));\n                linkNodes.push({ link, node });\n                nav.append(node);\n            }\n            header.append(nav);\n            markLinks();\n        }\n        if (actions?.length) {\n            const extra = el('div', 'study-appbar__extra');\n            extra.append(...actions);\n            header.append(extra);\n        }\n        const tools = el('div', 'study-appbar__actions');\n        appMenu = null;\n        appNodes = [];\n        if (apps.length > 1 && !embed) {\n            const menu = el('details', 'study-menu study-menu--end', { 'data-study-apps': '' });\n            const here = apps.find((item) => item.slug === app);\n            const summary = el('summary', 'study-menu__button', { 'aria-label': text(lang, 'switchApp') });\n            summary.innerHTML = ICON_APPS;\n            const value = el('span', 'study-menu__value');\n            value.textContent = here?.label ?? title;\n            summary.append(value);\n            const panel = el('div', 'study-menu__panel');\n            // The group's page first: every tool of the workshop, the members.\n            if (groupHref && !group?.onClick) {\n                const home = el('a', 'study-menu__item', { href: groupHref, 'data-group-page': '' });\n                home.textContent = text(lang, 'groupPage');\n                home.addEventListener('click', () => {\n                    menu.open = false;\n                });\n                panel.append(home);\n            }\n            const heading = el('p', 'study-menu__heading');\n            heading.textContent = text(lang, 'apps');\n            panel.append(heading);\n            for (const item of apps) {\n                if (item.slug === app)\n                    continue;\n                const link = el('a', 'study-menu__item', { href: item.href, 'data-app': item.slug });\n                link.textContent = item.label;\n                link.addEventListener('click', () => {\n                    link.href = appHref(item.href, activeTeamCode());\n                    menu.open = false;\n                });\n                panel.append(link);\n                appNodes.push({ app: item, node: link });\n            }\n            menu.addEventListener('toggle', refreshAppLinks);\n            menu.append(summary, panel);\n            refreshAppLinks();\n            appMenu = menu;\n            tools.append(menu);\n        }\n        langMenu = null;\n        if (langs.length > 1 && !embed) {\n            // A `<details>`: it opens and closes without this script's help.\n            const menu = el('details', 'study-menu study-menu--end study-lang-menu');\n            const summary = el('summary', 'study-menu__button', {\n                'aria-label': `${text(lang, 'languageOf')}${languageName(lang)}`,\n            });\n            summary.innerHTML = ICON_LANGUAGE;\n            const codeLabel = el('span', 'study-lang-menu__code', { 'aria-hidden': 'true' });\n            codeLabel.textContent = lang;\n            summary.append(codeLabel);\n            const panel = el('div', 'study-menu__panel');\n            for (const code of langs) {\n                const link = el('a', 'study-menu__item', {\n                    href: languageUrl(code, langs),\n                    hreflang: code,\n                    lang: code,\n                    'aria-current': String(code === lang),\n                });\n                // The code repeats the name for a screen reader: hidden from it.\n                const meta = el('span', 'study-menu__meta', { 'aria-hidden': 'true' });\n                meta.textContent = code.toUpperCase();\n                link.append(`${languageName(code)} `, meta);\n                link.addEventListener('click', (event) => {\n                    // The hash may have changed since the bar was drawn.\n                    link.href = languageUrl(code, langs);\n                    menu.open = false;\n                    if (code === current.lang) {\n                        event.preventDefault();\n                        return;\n                    }\n                    try {\n                        localStorage.setItem(LANG_KEY, code);\n                    }\n                    catch {\n                        // Not remembered; the link still works.\n                    }\n                    if (current.onLangChange?.(code) === false)\n                        event.preventDefault();\n                });\n                panel.append(link);\n                langNodes.push({ code, node: link });\n            }\n            // Opening the menu reads the route again (an app may change it without a hashchange).\n            menu.addEventListener('toggle', refreshLangLinks);\n            menu.append(summary, panel);\n            langMenu = menu;\n            tools.append(menu);\n        }\n        if (!embed) {\n            const toggle = el('button', 'study-theme-toggle', {\n                type: 'button',\n                'aria-label': text(lang, 'theme'),\n                'aria-pressed': String(currentTheme() === 'dark'),\n            });\n            toggle.innerHTML = ICON_THEME;\n            toggle.addEventListener('click', () => {\n                toggle.setAttribute('aria-pressed', String(toggleTheme() === 'dark'));\n            });\n            tools.append(toggle);\n        }\n        menuButton = null;\n        if (links.length) {\n            menuButton = el('button', 'study-appbar__menu', {\n                type: 'button',\n                'aria-controls': navId,\n                'aria-expanded': 'false',\n                'aria-label': text(lang, 'menu'),\n            });\n            menuButton.innerHTML = ICON_MENU;\n            menuButton.addEventListener('click', () => setOpen(!header.classList.contains('is-open')));\n            tools.append(menuButton);\n        }\n        header.append(tools);\n        place();\n        // A line left for the bar (a move by staff, found on entry after the\n        // bar was drawn): once, under the bar, until dismissed.\n        if (!notice)\n            notice = noticeLine(lang);\n        if (notice && !embed && header.isConnected)\n            header.after(notice);\n    };\n    const noticeLine = (lang) => {\n        const said = takeGroupNotice();\n        if (!said)\n            return null;\n        const line = el('p', 'study-banner study-appbar-notice', { role: 'status' });\n        const close = el('button', 'ss-btn ss-btn--ghost ss-btn--sm', { type: 'button' });\n        close.textContent = text(lang, 'dismiss');\n        close.addEventListener('click', () => {\n            line.remove();\n            notice = null;\n        });\n        line.append(said, ' ', close);\n        return line;\n    };\n    const onKey = (event) => {\n        if (event.key !== 'Escape')\n            return;\n        setOpen(false);\n        if (langMenu)\n            langMenu.open = false;\n        if (appMenu)\n            appMenu.open = false;\n    };\n    const onOutside = (event) => {\n        const target = event.target;\n        if (header.classList.contains('is-open') && !header.contains(target))\n            setOpen(false);\n        if (langMenu?.open && !langMenu.contains(target))\n            langMenu.open = false;\n        if (appMenu?.open && !appMenu.contains(target))\n            appMenu.open = false;\n    };\n    // Embedded: follow the lesson page's theme, also when it is toggled there.\n    const syncTheme = () => (embedded() ? applyParentTheme() : applyStoredTheme());\n    const onStorage = (event) => {\n        if (event.key === THEME_KEY)\n            syncTheme();\n    };\n    // Embedded: the lesson posts `{type: \"study:theme\", theme}` when its theme changes (same origin only).\n    const onMessage = (event) => {\n        if (!embedded() || event.origin !== window.location.origin)\n            return;\n        const data = event.data;\n        if (data?.type !== 'study:theme')\n            return;\n        if (data.theme === 'light' || data.theme === 'dark')\n            document.documentElement.dataset.theme = data.theme;\n    };\n    let observer = null;\n    const root = parentRoot();\n    if (embedded() && root && typeof MutationObserver !== 'undefined') {\n        observer = new MutationObserver(syncTheme);\n        observer.observe(root, { attributes: true, attributeFilter: ['data-theme'] });\n    }\n    syncTheme();\n    render();\n    window.addEventListener('storage', onStorage);\n    window.addEventListener('message', onMessage);\n    document.addEventListener('keydown', onKey);\n    document.addEventListener('click', onOutside);\n    window.addEventListener('hashchange', markLinks);\n    return {\n        element: header,\n        update(changes) {\n            current = { ...current, ...changes };\n            render();\n            syncTheme();\n        },\n        destroy() {\n            stopSwitch();\n            document.removeEventListener('keydown', onKey);\n            document.removeEventListener('click', onOutside);\n            window.removeEventListener('hashchange', markLinks);\n            window.removeEventListener('storage', onStorage);\n            window.removeEventListener('message', onMessage);\n            observer?.disconnect();\n            document.documentElement.classList.remove('is-embedded');\n            notice?.remove();\n            header.remove();\n        },\n    };\n}\nif (typeof window !== 'undefined') {\n    window.StudyBase = { ...(window.StudyBase ?? {}), mountAppbar };\n}\n//# sourceMappingURL=appbar.js.map","/** Who gets in at the start screen (the access rule of the suite).\n *\n * The page shell marks a signed-in staff user with `data-staff=\"true\"` on\n * `#study-app` (a missing attribute is \"not staff\"); the server refuses to\n * create a group for anyone else (403). So:\n *\n * - **staff** see the whole start screen: create a group, enter a code.\n * - **a visitor with a join link** (`?join=CODE`, the QR code of a group)\n *   gets the join card with the code filled in, and no create card.\n * - **any other visitor** gets neither: a short panel says to scan the\n *   QR code of the workshop leader, or to sign in when they lead the workshop.\n *\n * A device that already joined a group is not stopped here: the start\n * screen sends it on to its group, and lists the groups it joined.\n *\n * A staff user is signed in by the session cookie, so the server wants\n * Django's CSRF token on every unsafe call (`X-CSRFToken`); the shell\n * renders it as `data-csrf-token` for staff only. A refused token (403,\n * `\"code\": \"csrf_failed\"`, an old page) is not \"no staff\": the screen asks\n * to reload the page instead of falling back to the visitor's panel. */\nimport { ApiError } from \"@starling-cloud/sturnia-workshop\";\n/** `data-staff` as a flag: only `\"true\"` is staff. */\nexport function staffFromDataset(value) {\n    return value === \"true\";\n}\n/** `data-csrf-token`: Django's CSRF token of a staff session (empty for\n * anyone else, or when the attribute is missing). */\nexport function csrfFromDataset(value) {\n    return (value ?? \"\").trim();\n}\n/** Methods that change nothing: no CSRF token needed. */\nconst SAFE_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\"]);\n/** `X-CSRFToken` for a request of this method: the token on an unsafe\n * method (`POST`, `PATCH`, `PUT`, `DELETE`), nothing on a safe one or\n * without a token. For a request made by hand (outside the client). */\nexport function csrfHeader(token, method = \"GET\") {\n    return token && !SAFE_METHODS.has(method.toUpperCase())\n        ? { \"X-CSRFToken\": token }\n        : {};\n}\n/** A fetch for the workshop client that adds `X-CSRFToken` to every\n * unsafe request when there is a token; the fetch itself without one. */\nexport function withCsrf(token, base = (input, init) => globalThis.fetch(input, init)) {\n    if (!token)\n        return base;\n    return (input, init = {}) => {\n        const extra = csrfHeader(token, init.method ?? \"GET\");\n        if (!extra[\"X-CSRFToken\"])\n            return base(input, init);\n        const headers = new Headers(init.headers);\n        headers.set(\"X-CSRFToken\", token);\n        return base(input, { ...init, headers });\n    };\n}\n/** Which start screen a visitor gets. */\nexport function startMode(staff, joinCode) {\n    if (staff)\n        return \"staff\";\n    return joinCode ? \"join\" : \"closed\";\n}\n/** Where \"sign in\" goes: `data-sign-in-url` of the shell, or the login\n * page of study-base with the app page as `next`. */\nexport function signInUrl(lang, given, loc) {\n    if (given)\n        return given;\n    const prefix = lang === \"en\" ? \"en\" : \"nl\";\n    const next = encodeURIComponent(`${loc.pathname}${loc.search}`);\n    return `/${prefix}/account/login/?next=${next}`;\n}\n/** A refused request: the `ApiError` of the client with status 403. */\nexport function isForbidden(error) {\n    return (typeof error === \"object\" &&\n        error !== null &&\n        error.status === 403);\n}\n/** A 403 of the CSRF check (`\"code\": \"csrf_failed\"`): the staff session\n * is there, its token is not (or no longer) valid. The shared client keeps\n * only the `detail` (\"CSRF check failed …\"), so that is read too. */\nexport function isCsrfFailure(error) {\n    if (!isForbidden(error))\n        return false;\n    const { code, detail } = error;\n    if (code === \"csrf_failed\")\n        return true;\n    return typeof detail === \"string\" && /\\bcsrf\\b/i.test(detail);\n}\n/** Call `onForbidden` when creating a group is refused with a 403 (a\n * staff session that ran out, say), before the error goes on to the start\n * screen. A refused CSRF token is not that: the user stays staff and the\n * error reaches the screen as `reloadText` (reload the page). Returns the\n * function that takes the guard off again. */\nexport function guardCreate(target, onForbidden, reloadText = \"\") {\n    const create = target.createGroup;\n    target.createGroup = async (...args) => {\n        try {\n            return await create.apply(target, args);\n        }\n        catch (error) {\n            if (isCsrfFailure(error))\n                throw reloadText ? new ApiError(403, reloadText) : error;\n            if (isForbidden(error))\n                onForbidden();\n            throw error;\n        }\n    };\n    return () => {\n        target.createGroup = create;\n    };\n}\n/** The panel a visitor without a way in sees instead of the two cards.\n * Marked `data-access-panel`; styled as a card of sturnia-workshop. */\nexport function accessPanel(texts, signInHref) {\n    const panel = document.createElement(\"section\");\n    panel.className = \"ss-card sw-start__card\";\n    panel.setAttribute(\"data-access-panel\", \"\");\n    const title = document.createElement(\"h2\");\n    title.className = \"sw-start__h2\";\n    title.textContent = texts.title;\n    const scan = document.createElement(\"p\");\n    scan.className = \"sw-hint\";\n    scan.textContent = texts.scan;\n    const lead = document.createElement(\"p\");\n    lead.className = \"sw-hint\";\n    lead.textContent = texts.lead;\n    const link = document.createElement(\"a\");\n    link.className = \"ss-btn ss-btn--block\";\n    link.href = signInHref;\n    link.textContent = texts.signIn;\n    panel.append(title, scan, lead, link);\n    return panel;\n}\n//# sourceMappingURL=access.js.map","/** What the Django shell tells an app's bundle: the `#study-app` element's\n * dataset (`study/base/app.html.jinja`):\n *\n *   <div id=\"study-app\" data-app=\"chat\" data-api-base=\"/api/chat\"\n *        data-lang=\"nl\" data-workshop=\"default\" data-staff=\"false\"\n *        data-csrf-token=\"…\" data-sign-in-url=\"…\"></div>\n *\n * (the token: staff only). `readShellConfig` reads the attributes every\n * app has; an app adds its own (`embedded`, a workshop taken from the\n * active group) on top. */\nimport { csrfFromDataset, staffFromDataset } from \"./access.js\";\nimport { pageWorkshop } from \"./workshops.js\";\n/** The id of the mount point the shell renders. */\nexport const MOUNT_ID = \"study-app\";\n/** The mount point, or null (no page, or a page without it). */\nexport function mountElement() {\n    return typeof document === \"undefined\"\n        ? null\n        : document.getElementById(MOUNT_ID);\n}\n/** The mount point every view renders into; throws when it is missing. */\nexport function appRoot() {\n    const node = mountElement();\n    if (!node)\n        throw new Error(`#${MOUNT_ID} is missing`);\n    return node;\n}\nfunction pageSearch() {\n    return typeof location === \"undefined\" ? \"\" : location.search;\n}\n/** The shell's attributes, with the app's defaults for the missing ones:\n * `app` names the app, the API prefix defaults to `/api/<app>`, the\n * language to the page's `<html lang>`, else Dutch. When neither the\n * shell nor the address (`search`) names a workshop, the workshop is the\n * active group's (`pageWorkshop`, read from `store`, default\n * `localStorage`), so a bookmark without `?workshop=` does not ask for\n * the group in the default workshop. */\nexport function readShellConfig(app, data = mountElement()?.dataset ?? {}, search = pageSearch(), store) {\n    const name = data.app || app;\n    const pageLang = typeof document === \"undefined\"\n        ? \"\"\n        : (document.documentElement?.lang ?? \"\");\n    const own = data.workshop || \"\";\n    const followed = store === undefined\n        ? pageWorkshop(name, own, search)\n        : pageWorkshop(name, own, search, store);\n    return {\n        app: name,\n        apiBase: (data.apiBase || `/api/${app}`).replace(/\\/+$/, \"\"),\n        lang: data.lang || pageLang || \"nl\",\n        workshop: followed || own,\n        staff: staffFromDataset(data.staff),\n        csrfToken: csrfFromDataset(data.csrfToken),\n        signInUrl: data.signInUrl || \"\",\n    };\n}\n//# sourceMappingURL=config.js.map","/** What the page tells the bundle: the `#study-app` element's data\n * attributes, rendered by study.base's app shell template\n * (`data-app`, `data-api-base`, `data-lang`, `data-workshop`, `data-staff`,\n * `data-csrf-token`), read by study-base's lib/config. `data-groups-url`\n * and `data-password` are read by study-base's lib/entry itself. */\n\nimport {\n    appRoot,\n    readShellConfig,\n    type ShellConfig,\n} from \"@starling-study/study-base/lib/config\";\nimport { isEmbedded } from \"@starling-study/study-base/lib/embed\";\nimport { pageWorkshop } from \"@starling-study/study-base/lib/workshops\";\n\n/** The shell's attributes, with the workshop of the active group for a\n * page without one (lib/workshops). */\nexport interface AppConfig extends ShellConfig {\n    /** The mount point. */\n    root: HTMLElement;\n    /** Inside a lesson (`?embed=1`): no app bar (lib/embed). */\n    embedded: boolean;\n}\n\nfunction readConfig(): AppConfig {\n    const root = appRoot();\n    const shell = readShellConfig(\"imagine\", root.dataset);\n    return {\n        ...shell,\n        root,\n        workshop: pageWorkshop(shell.app, shell.workshop, location.search),\n        embedded: isEmbedded(location),\n    };\n}\n\nexport const config: AppConfig = readConfig();\n","/** The language helpers every participant app shares. The dictionary and\n * `t(key)` stay in the app (its words are its own); this is the part\n * around it:\n *\n * - the page's language is the URL's: Django serves an app under\n *   `/<lang>/<app>/` and the shell passes it on as `data-lang`, Dutch by\n *   default, English as the guest language (`asLang`);\n * - switching goes to the other language's URL, keeping the query\n *   (`?workshop=`) and the hash route (`langUrl`);\n * - a value from the server may be a plain string (the same in both\n *   languages) or `{ nl, en }` (`pickText`);\n * - dates and times in the page's language, a word count, and the texts\n *   of sturnia-workshop's password gate (`gateTexts`). */\n/** The page's language of a `data-lang` (or `<html lang>`): English when\n * it says so, else Dutch. */\nexport function asLang(value) {\n    return (value ?? \"\").slice(0, 2).toLowerCase() === \"en\" ? \"en\" : \"nl\";\n}\n/** The same page in another language: `/nl/chat/#/studio` →\n * `/en/chat/#/studio`. A path without a language prefix gets one. */\nexport function langUrl(lang, path, hash, search = \"\") {\n    const swapped = /^\\/(nl|en)(\\/|$)/.test(path)\n        ? path.replace(/^\\/(nl|en)(?=\\/|$)/, `/${lang}`)\n        : `/${lang}${path}`;\n    return `${swapped}${search}${hash}`;\n}\n/** A localized value in `lang`; the other language when that one is\n * missing, `\"\"` for none. */\nexport function pickText(value, lang) {\n    if (value === undefined)\n        return \"\";\n    if (typeof value === \"string\")\n        return value;\n    return value[lang] ?? value.nl ?? value.en ?? \"\";\n}\n/** The locale of a language, for `toLocaleString`. */\nexport function localeOf(lang) {\n    return lang === \"nl\" ? \"nl-NL\" : \"en-GB\";\n}\n/** A clock time (\"14:05\"), `\"\"` for no date. */\nexport function formatTime(isoDate, lang) {\n    const date = new Date(isoDate);\n    if (Number.isNaN(date.getTime()))\n        return \"\";\n    return date.toLocaleTimeString(localeOf(lang), {\n        hour: \"2-digit\",\n        minute: \"2-digit\",\n    });\n}\n/** A date and time (\"15 okt. 14:05\"), `\"\"` for no date. */\nexport function formatDateTime(isoDate, lang) {\n    const date = new Date(isoDate);\n    if (Number.isNaN(date.getTime()))\n        return \"\";\n    return date.toLocaleString(localeOf(lang), {\n        day: \"numeric\",\n        month: \"short\",\n        hour: \"2-digit\",\n        minute: \"2-digit\",\n    });\n}\n/** Words in a text, the way a reader counts them (punctuation is no word). */\nexport function wordCount(text) {\n    return text.split(/\\s+/).filter((word) => /[\\p{L}\\p{N}]/u.test(word))\n        .length;\n}\n/** The gate's texts from the app's dictionary (`text`, in the page's\n * language) under the app's name. */\nexport function gateTexts(text, title) {\n    return {\n        title,\n        hint: text(\"gateHint\"),\n        buttonLabel: text(\"gateButton\"),\n        labels: {\n            password: text(\"gatePassword\"),\n            wrongPassword: text(\"gateWrongPassword\"),\n            workshopPasswordFirst: text(\"gateWorkshopPasswordFirst\"),\n            unreachable: text(\"gateUnreachable\"),\n        },\n    };\n}\n//# sourceMappingURL=i18n.js.map","/** Bilingual (NL/EN) support for everything participants see.\n *\n * Two mechanisms, both tiny:\n * - `t(key)` — fixed UI strings from the dictionary below.\n * - `pick(value)` — localized text from the server (the downloads\n *   manifest): a field may be a plain string (shown as-is in both\n *   languages) or `{ nl, en }`.\n *\n * The language is the page's (`data-lang`, from the `/nl/…` or `/en/…`\n * URL), Dutch by default — this is a Dutch workshop app; EN is the guest\n * language. Switching navigates to the same app page under the other\n * language prefix, keeping the hash route: every view rebuilds from server\n * state anyway.\n */\n\nimport {\n    asLang,\n    formatDateTime as formatDateTimeIn,\n    langUrl as langUrlOf,\n    pickText,\n    type Lang,\n    type LocalizedText,\n} from \"@starling-study/study-base/lib/i18n\";\n\nimport { config } from \"./config\";\n\nexport type { Lang, LocalizedText };\n\nexport function getLang(): Lang {\n    return asLang(config.lang);\n}\n\n/** The same page under the other language prefix (`/nl/imagine/` ↔\n * `/en/imagine/`), hash route included. */\nexport function langUrl(lang: Lang, loc: Location = location): string {\n    return langUrlOf(lang, loc.pathname, loc.hash, loc.search);\n}\n\nexport function setLang(lang: Lang): void {\n    location.assign(langUrl(lang));\n}\n\n/** Resolves a localized value for a language (default: current). */\nexport function pick(value: LocalizedText | undefined, lang?: Lang): string {\n    return pickText(value, lang ?? getLang());\n}\n\nconst STRINGS = {\n    // chrome\n    appName: { nl: \"Imagine\", en: \"Imagine\" },\n    downloads: { nl: \"Downloads\", en: \"Downloads\" },\n    studio: { nl: \"Studio\", en: \"Studio\" },\n    history: { nl: \"Geschiedenis\", en: \"History\" },\n    start: { nl: \"Beginnen\", en: \"Start\" },\n\n    // the group page (embedded: the app's own link to it)\n    yourGroup: { nl: \"Jullie groep\", en: \"Your group\" },\n\n    // members (the same wording in every app of the suite)\n    participant: { nl: \"Deelnemer\", en: \"Participant\" },\n    memberName: { nl: \"Naam\", en: \"Name\" },\n    memberRemove: { nl: \"Uit de groep halen\", en: \"Remove from the group\" },\n    removedFromGroup: {\n        nl: \"Je bent uit de groep gehaald.\",\n        en: \"You were removed from the group.\",\n    },\n\n    // the workshop is over, or not there\n    closedTitle: {\n        nl: \"Deze workshop is afgelopen\",\n        en: \"This workshop has ended\",\n    },\n    closedText: {\n        nl: \"Bedankt voor het meedoen!\",\n        en: \"Thanks for taking part!\",\n    },\n    nothingHereTitle: {\n        nl: \"Deze workshop is er niet\",\n        en: \"This workshop isn't here\",\n    },\n    toStart: { nl: \"Naar het begin\", en: \"To the start\" },\n\n    // studio — the prompt\n    framePromptHint: {\n        nl: \"De prompt en instellingen van dit beeld. Tik om alles te lezen.\",\n        en: \"This frame's prompt and settings. Tap to read it all.\",\n    },\n    seedRandom: { nl: \"willekeurig\", en: \"random\" },\n    promptLabel: {\n        nl: \"Wat willen jullie zien?\",\n        en: \"What do you want to see?\",\n    },\n    promptPlaceholder: {\n        nl: \"Beschrijf het beeld in één of twee zinnen.\",\n        en: \"Describe the image in a sentence or two.\",\n    },\n    promptHint: {\n        nl: \"Noem wat er te zien is, waar het is en hoe het voelt — en in welke stijl: foto, poster, schets. Hoe concreter, hoe beter.\",\n        en: \"Say what is in it, where it is, how it feels — and in what style: photo, poster, sketch. The more concrete, the better.\",\n    },\n    settings: { nl: \"Instellingen\", en: \"Settings\" },\n    provider: { nl: \"Model\", en: \"Model\" },\n    aspect: { nl: \"Verhouding\", en: \"Aspect ratio\" },\n    quality: { nl: \"Kwaliteit\", en: \"Quality\" },\n    qualityLow: { nl: \"Snel\", en: \"Fast\" },\n    qualityMedium: { nl: \"Normaal\", en: \"Normal\" },\n    qualityHigh: { nl: \"Hoog\", en: \"Best\" },\n    negativePrompt: {\n        nl: \"Wat je juist niet wilt zien\",\n        en: \"What you don't want to see\",\n    },\n    negativePlaceholder: {\n        nl: \"Bijvoorbeeld: tekst, wazige randen\",\n        en: \"For example: text, blurry edges\",\n    },\n    negativePromptHint: {\n        nl: \"Optioneel. Modellen zonder dit veld krijgen het als zin in de prompt mee.\",\n        en: \"Optional. Models without this field get it as a sentence in the prompt.\",\n    },\n    seed: { nl: \"Startgetal\", en: \"Seed\" },\n    seedHint: {\n        nl: \"Optioneel. Het startpunt van het toeval: met hetzelfde getal en dezelfde prompt komt hetzelfde beeld terug, met een ander getal een andere variant. Leeg laten kiest elke keer een nieuw getal.\",\n        en: \"Optional. Where the randomness starts: the same number with the same prompt brings back the same image, another number another variant. Leave it empty to get a fresh one every time.\",\n    },\n    generate: { nl: \"Maak het beeld\", en: \"Make the image\" },\n    generateAgain: { nl: \"Nog een keer\", en: \"Once more\" },\n\n    // studio — running\n    queued: { nl: \"In de wachtrij…\", en: \"Queued…\" },\n    queuedAt: { nl: \"In de wachtrij, plek\", en: \"Queued, position\" },\n    running: { nl: \"Bezig met tekenen…\", en: \"Drawing…\" },\n    runningHint: {\n        nl: \"Dit duurt meestal een halve tot twee minuten. Je kunt je telefoon gerust even wegleggen: het beeld staat er straks gewoon.\",\n        en: \"This usually takes half a minute to two minutes. Feel free to put your phone down — the image will be here when you're back.\",\n    },\n\n    // studio — results\n    results: { nl: \"Resultaten\", en: \"Results\" },\n    chooseHint: {\n        nl: \"Tik op het rondje bij een beeld om het te kiezen: daarmee kun je het daarna aanpassen.\",\n        en: \"Tap the circle on an image to pick it: then you can change it.\",\n    },\n    choose: { nl: \"Kies dit beeld\", en: \"Pick this image\" },\n    chosen: { nl: \"Gekozen\", en: \"Picked\" },\n    emptyStudio: { nl: \"Nog geen beelden\", en: \"No images yet\" },\n    emptyStudioHint: {\n        nl: \"Wat jullie maken, verschijnt hier. Iedereen in de groep ziet hetzelfde.\",\n        en: \"What you make shows up here. Everyone in the group sees the same.\",\n    },\n    refine: { nl: \"Iets veranderen\", en: \"Change something\" },\n    refineLabel: {\n        nl: \"Wat moet er anders?\",\n        en: \"What should be different?\",\n    },\n    refinePlaceholder: {\n        nl: \"Bijvoorbeeld: meer mensen op straat, en aan het eind van de middag.\",\n        en: \"For example: more people on the street, and late in the afternoon.\",\n    },\n    refineHint: {\n        nl: \"Het gekozen beeld is het uitgangspunt — er komt een nieuwe versie bij.\",\n        en: \"The picked image is the starting point — a new version is added.\",\n    },\n    refineButton: { nl: \"Maak de nieuwe versie\", en: \"Make the new version\" },\n    varyButton: { nl: \"Meer zoals deze\", en: \"More like this\" },\n    varyHint: {\n        nl: \"Of maak zonder iets te veranderen nog een variant van het gekozen beeld.\",\n        en: \"Or make another variant of the picked image without changing anything.\",\n    },\n    download: { nl: \"Downloaden\", en: \"Download\" },\n    deleteImage: { nl: \"Weggooien\", en: \"Delete\" },\n    referenceLabel: { nl: \"Voorbeeldbeeld\", en: \"Guidance image\" },\n    referenceHint: {\n        nl: \"Optioneel: een foto of tekening waar het model van uitgaat. De prompt zegt wat ermee moet gebeuren.\",\n        en: \"Optional: a photo or a drawing the model works from. The prompt says what to do with it.\",\n    },\n    uploadImage: {\n        nl: \"Foto of tekening kiezen\",\n        en: \"Pick a photo or drawing\",\n    },\n    removeReference: { nl: \"Weghalen\", en: \"Remove\" },\n    uploading: { nl: \"Beeld uploaden…\", en: \"Uploading…\" },\n    uploadDone: {\n        nl: \"Voorbeeldbeeld staat klaar. Het volgende beeld gaat ervan uit.\",\n        en: \"Guidance image is set. The next image works from it.\",\n    },\n    uploadTooBig: {\n        nl: \"Dat bestand is te groot.\",\n        en: \"That file is too big.\",\n    },\n    uploaded: { nl: \"Eigen beeld\", en: \"Your own image\" },\n    deleteConfirm: { nl: \"Dit beeld weggooien?\", en: \"Delete this image?\" },\n    openFull: { nl: \"Groot bekijken\", en: \"View full size\" },\n\n    // history\n    historyTitle: {\n        nl: \"Alles wat jullie maakten\",\n        en: \"Everything you made\",\n    },\n    historyIntro: {\n        nl: \"Elke keer dat jullie op Maak het beeld drukten, met wat je vroeg en wat eruit kwam — nieuwste bovenaan.\",\n        en: \"Every time you pressed Make the image, with what you asked and what came out — newest first.\",\n    },\n    historyEmpty: { nl: \"Nog niets gemaakt.\", en: \"Nothing made yet.\" },\n    historyRefine: { nl: \"Aanpassing\", en: \"Change\" },\n    historyVary: { nl: \"Variant\", en: \"Variant\" },\n    historyFailed: { nl: \"Mislukt\", en: \"Failed\" },\n    historyNoFrames: { nl: \"Geen beelden\", en: \"No images\" },\n    imageCount: { nl: \"{n} beeld\", en: \"{n} image\" },\n    imagesCount: { nl: \"{n} beelden\", en: \"{n} images\" },\n    negativeShort: { nl: \"Niet\", en: \"Not\" },\n    toStudio: { nl: \"Naar de studio\", en: \"To the studio\" },\n\n    needSelection: { nl: \"Kies eerst een beeld.\", en: \"Pick an image first.\" },\n    needPrompt: {\n        nl: \"Beschrijf eerst wat je wilt zien.\",\n        en: \"Describe what you want to see first.\",\n    },\n\n    // downloads\n    downloadsTitle: {\n        nl: \"Uitleg en werkbladen\",\n        en: \"Instructions and worksheets\",\n    },\n    downloadsIntro: {\n        nl: \"Alles wat op tafel ligt, ook hier om te downloaden.\",\n        en: \"Everything that is on the table, here to download too.\",\n    },\n    downloadsEmpty: {\n        nl: \"Er staat nog niets klaar om te downloaden.\",\n        en: \"Nothing to download yet.\",\n    },\n    kindInstructions: { nl: \"Uitleg\", en: \"Instructions\" },\n    kindSheet: { nl: \"Werkblad\", en: \"Worksheet\" },\n    kindOther: { nl: \"Bijlage\", en: \"Attachment\" },\n\n    // errors\n    errorGeneric: {\n        nl: \"Er ging iets mis. Probeer het nog eens.\",\n        en: \"Something went wrong. Try again.\",\n    },\n    errorWorkshopClosed: {\n        nl: \"Deze workshop is afgelopen — bedankt voor het meedoen.\",\n        en: \"This workshop has ended — thanks for taking part.\",\n    },\n    errorWorkshopNotFound: {\n        nl: \"Deze workshop bestaat niet (meer). Controleer de link of vraag het je workshopleider.\",\n        en: \"This workshop doesn't exist (any more). Check the link or ask your workshop leader.\",\n    },\n    errorGroupNotFound: {\n        nl: \"Deze groep is niet gevonden. Controleer de code of vraag het je workshopleider.\",\n        en: \"We couldn't find this group. Check the code or ask your workshop leader.\",\n    },\n    errorNotInGroup: {\n        nl: \"Je zit niet meer in deze groep.\",\n        en: \"You are no longer in this group.\",\n    },\n    errorNotAllowed: {\n        nl: \"Je kunt alleen jezelf uit de groep halen.\",\n        en: \"You can only remove yourself from the group.\",\n    },\n    errorOff: {\n        nl: \"Beelden maken staat uit op deze server.\",\n        en: \"Generating is off on this server.\",\n    },\n    errorPaused: {\n        nl: \"Genereren is even gepauzeerd.\",\n        en: \"Generating is paused for a moment.\",\n    },\n    errorBusy: {\n        nl: \"Er wordt al een beeld gemaakt voor deze groep.\",\n        en: \"An image is already being made for this group.\",\n    },\n    errorLimit: {\n        nl: \"Deze groep heeft het maximum voor vandaag bereikt.\",\n        en: \"This group has reached today's maximum.\",\n    },\n    errorRestarting: {\n        nl: \"De server start opnieuw op. Probeer het over een minuut nog eens.\",\n        en: \"The server is restarting. Try again in a minute.\",\n    },\n    // the connection banner (components/connection)\n    serverRestarting: {\n        nl: \"De server start opnieuw op — we blijven het proberen…\",\n        en: \"The server is restarting — still trying…\",\n    },\n    connectionOffline: {\n        nl: \"Geen internetverbinding — we blijven het proberen…\",\n        en: \"No internet connection — still trying…\",\n    },\n    connectionBack: { nl: \"Weer verbonden.\", en: \"Connected again.\" },\n    entryWaiting: {\n        nl: \"Je groep gaat open zodra de server terug is.\",\n        en: \"Your group opens as soon as the server is back.\",\n    },\n    errorRoomBusy: {\n        nl: \"Het is even druk. Probeer het zo nog eens.\",\n        en: \"It is busy right now. Try again in a moment.\",\n    },\n    errorTimeout: {\n        nl: \"Het duurde te lang. Probeer het nog eens.\",\n        en: \"It took too long. Try again.\",\n    },\n    errorRefused: {\n        nl: \"Het model wilde dit beeld niet maken. Probeer een andere beschrijving.\",\n        en: \"The model refused this image. Try describing it differently.\",\n    },\n    retry: { nl: \"Opnieuw proberen\", en: \"Try again\" },\n} satisfies Record<string, { nl: string; en: string }>;\n\nexport type StringKey = keyof typeof STRINGS;\n\nexport function t(key: StringKey, lang?: Lang): string {\n    return STRINGS[key][lang ?? getLang()];\n}\n\n/** The message for a generation's error code — the server sends a code,\n * never a sentence a participant should read. */\nexport function generationError(code: string | null): string {\n    switch (code) {\n        case \"timeout\":\n        case \"stale\":\n            return t(\"errorTimeout\");\n        case \"generation_off\":\n            return t(\"errorOff\");\n        case \"generation_paused\":\n            return t(\"errorPaused\");\n        case \"already_running\":\n            return t(\"errorBusy\");\n        case \"group_limit\":\n            return t(\"errorLimit\");\n        case \"busy\":\n            return t(\"errorRoomBusy\");\n        case \"no_images\":\n        case \"upstream\":\n            return t(\"errorRefused\");\n        default:\n            return t(\"errorGeneric\");\n    }\n}\n\n/** A date and time for a run in the history, in the device's locale. */\nexport function formatDateTime(isoDate: string): string {\n    return formatDateTimeIn(isoDate, getLang());\n}\n","/** The launch parameters a lesson opens an app with. study-syllabus's\n * `ToolBlock` links (or iframes) the page as\n *\n *   /<lang>/<app>/?prompt=<instruction>&workshop=<slug>\n *\n * - `workshop` is read by the page shell into `data-workshop` (lib/config)\n *   and sent as `X-Workshop` on every API call. It stays in the address,\n *   so a reload or a language switch keeps the page's workshop, and it is\n *   added to the URLs the browser loads itself (the QR <img>), which\n *   cannot carry the header (`withWorkshop`, `carryWorkshop`).\n * - `prompt` (or `task`, as an embedded lesson names it) is the lesson's\n *   instruction. On boot it moves from the address into sessionStorage\n *   (`stashLaunchPrompt`), so it survives the password gate and the start\n *   and group screens. What the app does with it is its own: pre-fill a\n *   field once (`takeLaunchPrompt`), or show it as a banner until the group\n *   dismisses it (`pendingLaunchPrompt`, `lessonBanner`). It is never sent\n *   by itself.\n *\n * Each app names its own storage key and length cap (`createLaunchPrompt`). */\nexport const PROMPT_PARAM = \"prompt\";\nexport const TASK_PARAM = \"task\";\n/** The page's sessionStorage, or null when it is blocked (a sandboxed\n * frame, a strict privacy mode). */\nexport function sessionStore() {\n    try {\n        return typeof sessionStorage === \"undefined\" ? null : sessionStorage;\n    }\n    catch {\n        return null;\n    }\n}\n/** A query string without the named parameters (`\"\"` when nothing is left). */\nexport function searchWithout(search, ...names) {\n    const params = new URLSearchParams(search);\n    for (const name of names)\n        params.delete(name);\n    const rest = params.toString();\n    return rest ? `?${rest}` : \"\";\n}\n/** Whether a site path already names its workshop\n * (`/<lang>/workshops/<slug>/…`, the participant pages since study-base\n * 0.7): it needs no `?workshop=`. */\nexport function pathNamesWorkshop(url) {\n    return /^(?:\\/[\\w-]+)?\\/workshops\\/[\\w-]+\\//.test(url.split(/[?#]/, 1)[0]);\n}\n/** A URL with `?workshop=<slug>` added, for what the browser loads without\n * our headers. The default workshop needs nothing, and neither does a\n * path that names its workshop (`pathNamesWorkshop`). */\nexport function withWorkshop(url, workshop) {\n    if (!workshop || workshop === \"default\" || pathNamesWorkshop(url))\n        return url;\n    const join = url.includes(\"?\") ? \"&\" : \"?\";\n    return `${url}${join}workshop=${encodeURIComponent(workshop)}`;\n}\n/** Make a groups API's `qrUrl` carry the workshop. sturnia-workshop's group\n * card draws its QR image from `session.groups.qrUrl(code)`, and an <img>\n * request has no `X-Workshop` header, so the slug has to be in the URL.\n * Returns the same object. */\nexport function carryWorkshop(groups, workshop) {\n    const qrUrl = groups.qrUrl.bind(groups);\n    groups.qrUrl = (code) => withWorkshop(qrUrl(code), workshop);\n    return groups;\n}\n/** The launch prompt of one app: its key, its cap, its parameters. */\nexport function createLaunchPrompt(options) {\n    const { key, max } = options;\n    const names = options.params ?? [PROMPT_PARAM, TASK_PARAM];\n    function promptFromSearch(search) {\n        const params = new URLSearchParams(search);\n        for (const name of names) {\n            const value = (params.get(name) ?? \"\").trim();\n            if (value)\n                return value.slice(0, max);\n        }\n        return \"\";\n    }\n    function stashLaunchPrompt(loc = location, storage = sessionStore(), replace = (url) => history.replaceState(history.state, \"\", url)) {\n        const params = new URLSearchParams(loc.search);\n        if (!names.some((name) => params.has(name)))\n            return \"\";\n        const prompt = promptFromSearch(loc.search);\n        if (prompt && storage) {\n            try {\n                storage.setItem(key, prompt);\n            }\n            catch {\n                // Nowhere to keep it; the address still loses it below.\n            }\n        }\n        replace(`${loc.pathname}${searchWithout(loc.search, ...names)}${loc.hash}`);\n        return prompt;\n    }\n    function takeLaunchPrompt(storage = sessionStore()) {\n        if (!storage)\n            return \"\";\n        try {\n            const prompt = storage.getItem(key) ?? \"\";\n            storage.removeItem(key);\n            return prompt;\n        }\n        catch {\n            return \"\";\n        }\n    }\n    function pendingLaunchPrompt(storage = sessionStore()) {\n        try {\n            return storage?.getItem(key) ?? \"\";\n        }\n        catch {\n            return \"\";\n        }\n    }\n    function clearLaunchPrompt(storage = sessionStore()) {\n        try {\n            storage?.removeItem(key);\n        }\n        catch {\n            // Nothing stored that could be removed.\n        }\n    }\n    function lessonBanner(labels, storage = sessionStore(), doc = document) {\n        const instruction = pendingLaunchPrompt(storage);\n        if (!instruction)\n            return null;\n        const banner = doc.createElement(\"aside\");\n        banner.className =\n            \"study-banner study-banner--info study-banner--capped\";\n        banner.setAttribute(\"role\", \"note\");\n        const title = doc.createElement(\"strong\");\n        title.className = \"study-banner__title\";\n        title.textContent = labels.title;\n        const text = doc.createElement(\"p\");\n        text.className = \"study-banner__text\";\n        text.textContent = instruction;\n        const dismiss = doc.createElement(\"button\");\n        dismiss.type = \"button\";\n        dismiss.className = \"study-banner__dismiss ss-btn ss-btn--sm\";\n        dismiss.textContent = labels.dismiss;\n        dismiss.addEventListener(\"click\", () => {\n            clearLaunchPrompt(storage);\n            banner.remove();\n        });\n        banner.append(title, text, dismiss);\n        return banner;\n    }\n    return {\n        promptFromSearch,\n        stashLaunchPrompt,\n        takeLaunchPrompt,\n        pendingLaunchPrompt,\n        clearLaunchPrompt,\n        lessonBanner,\n    };\n}\n//# sourceMappingURL=launch.js.map","/** The launch parameters a lesson opens this app with. study-syllabus's\n * `ToolBlock` links (or iframes) the page as\n *\n *   /<lang>/imagine/?prompt=<instruction>&workshop=<slug>\n *\n * - `workshop` is read by the page shell into `data-workshop` (lib/config)\n *   and sent as `X-Workshop` on every API call. It stays in the address,\n *   so a reload or a language switch keeps the page's workshop, and it is\n *   added to the URLs the browser loads itself (the QR <img>), which\n *   cannot carry the header.\n * - `prompt` is the lesson's instruction. On boot it moves from the\n *   address into sessionStorage, so it survives the workshop's groups page\n *   and group page. The studio puts it in the board prompt once\n *   the group is in, but only when that prompt is still empty, and then\n *   drops it. It never starts a generation by itself.\n * - `task` is the same instruction from a lesson that embeds the app\n *   (`?embed=1`, lib/embed); `prompt` wins when both are there. */\n\nimport { createLaunchPrompt } from \"@starling-study/study-base/lib/launch\";\n\nexport {\n    PROMPT_PARAM,\n    TASK_PARAM,\n    carryWorkshop,\n    searchWithout,\n    withWorkshop,\n} from \"@starling-study/study-base/lib/launch\";\n\nexport const PROMPT_KEY = \"study-imagine:launch-prompt\";\n/** The board prompt's own `maxlength`. */\nexport const PROMPT_MAX = 2000;\n\nexport const { promptFromSearch, stashLaunchPrompt, takeLaunchPrompt } =\n    createLaunchPrompt({ key: PROMPT_KEY, max: PROMPT_MAX });\n","/** Hash routing inside an app page (`/<lang>/<app>/#/group`). The Django\n * page is one URL and the views live behind the hash:\n *\n *   #/            start: join, create, rejoin\n *   #/group       the group card, members and the way in\n *   #/<view>      the app's own views\n *\n * A view registers what must stop when it is left (a poll timer, a\n * listener) with `onLeave`; the router runs those before the next view.\n * An app with a router of its own can still use `currentPath`, `href` and\n * `clearJoinQuery`.\n *\n * A view that awaits (a fetch) can be left while it waits. Each render has\n * its own `View` (the renderer's second argument, or `currentView()` at the\n * start of the view): check `view.current` after every `await` before\n * touching the page, pass `view.signal` to `fetch`, and register with\n * `view.onLeave` (or `onLeave(fn, view.signal)`), which runs the cleanup at\n * once when the view was already left instead of handing it to the next\n * view:\n *\n *   startRouter(async (path, view) => {\n *       const data = await api.get(url, { signal: view.signal })\n *       if (!view.current) return\n *       draw(data)\n *       const timer = setInterval(poll, 5000)\n *       view.onLeave(() => clearInterval(timer))\n *   })\n */\nimport { searchWithout } from \"./launch.js\";\nlet cleanups = [];\nlet renderer = null;\nlet controller = new AbortController();\n/** The current route: `/`, `/group`, `/studio`, … (query and trailing\n * slash dropped). */\nexport function currentPath(loc = location) {\n    const hash = loc.hash.replace(/^#/, \"\");\n    const path = (hash.split(\"?\")[0] ?? \"\").replace(/\\/+$/, \"\");\n    return path.startsWith(\"/\") ? path : `/${path}`;\n}\n/** The href for a route. */\nexport function href(path) {\n    return `#${path}`;\n}\nfunction runSafely(fn) {\n    try {\n        fn();\n    }\n    catch {\n        // A cleanup that fails must not keep the next view from rendering.\n    }\n}\n/** Something to stop when the current view is left. With the `signal` of\n * the render that registers it (`View.signal`, `viewSignal()`), a render\n * that was already left runs `fn` at once: its poller must not end up\n * among the next view's cleanups. */\nexport function onLeave(fn, signal) {\n    if (signal?.aborted) {\n        runSafely(fn);\n        return;\n    }\n    cleanups.push(fn);\n}\n/** The signal of the view on screen now: aborted when it is left. Read it\n * at the start of a view, before its first `await`. */\nexport function viewSignal() {\n    return controller.signal;\n}\n/** The view on screen now, as a `View` (see the module docs). Take it at\n * the start of a view, before its first `await`. */\nexport function currentView() {\n    const signal = controller.signal;\n    return {\n        signal,\n        get current() {\n            return !signal.aborted;\n        },\n        onLeave(fn) {\n            onLeave(fn, signal);\n        },\n    };\n}\n/** Run the current view's cleanups now (a whole-screen notice replaces it).\n * Its render's signal is aborted: a render still waiting is left too. */\nexport function leaveView() {\n    controller.abort();\n    controller = new AbortController();\n    const pending = cleanups;\n    cleanups = [];\n    for (const fn of pending)\n        runSafely(fn);\n}\nasync function render() {\n    leaveView();\n    if (!renderer)\n        return;\n    const view = currentView();\n    try {\n        await renderer(currentPath(), view);\n    }\n    catch (error) {\n        // A render that was left fails on its aborted fetch: no error.\n        if (view.current)\n            throw error;\n    }\n}\n/** Go to a route (re-render when it is the current one). */\nexport function navigate(path) {\n    if (currentPath() === path) {\n        void render();\n        return;\n    }\n    location.hash = href(path);\n}\n/** Drop `?join=CODE` from the address once it has done its work, so a\n * later \"switch group\" does not pre-fill it again. The rest of the query\n * (`?workshop=`, `?embed=`) stays: a reload must land in the same place. */\nexport function clearJoinQuery() {\n    const params = new URLSearchParams(location.search);\n    if (!params.has(\"join\") && !params.has(\"code\"))\n        return;\n    const search = searchWithout(location.search, \"join\", \"code\");\n    history.replaceState(history.state, \"\", `${location.pathname}${search}${location.hash}`);\n}\n/** Render the current route now and on every change of the hash. */\nexport function startRouter(fn) {\n    renderer = fn;\n    window.addEventListener(\"hashchange\", () => void render());\n    void render();\n}\n//# sourceMappingURL=router.js.map","/** Hash routing inside the app page (`/<lang>/imagine/#/studio`). The\n * studio's paths (`/`, `/group`, `/studio`, `/history`,\n * `/downloads`) live after the `#`, so the Django URL never changes.\n * Reading the route and dropping `?join=` are study-base's (lib/router);\n * going to a route re-renders through the render function of index.ts. */\n\nexport {\n    clearJoinQuery,\n    currentPath,\n    href,\n} from \"@starling-study/study-base/lib/router\";\n\nlet onNavigate: (() => void) | null = null;\n\n/** Registers the router's render function (index.ts). */\nexport function setNavigator(render: () => void): void {\n    onNavigate = render;\n}\n\n/** Goes to a route; re-renders even when it is the current one. */\nexport function go(path: string): void {\n    const target = `#${path}`;\n    if (location.hash === target || (path === \"/\" && location.hash === \"\")) {\n        onNavigate?.();\n        return;\n    }\n    location.hash = target;\n}\n","/** Who is who in a group, the same in every app of the suite:\n *\n * - A member without a name (or with the placeholder \"—\") is\n *   \"Deelnemer 3\" / \"Participant 3\", numbered in join order.\n * - A participant may remove only themselves (\"Leave this group\"); staff\n *   may remove anyone. So a visitor sees no ✕ on the other members, and\n *   only staff may rename someone else.\n *\n * The words are the app's (`createMemberRules`). */\n/** The name every device joins under before it is asked for one (the\n * shared start screen will not join without a name). Never shown. */\nexport const MEMBER_PLACEHOLDER = \"—\";\n/** A name a person gave, or \"\" for none (empty or the placeholder). */\nexport function givenName(name) {\n    const trimmed = (name ?? \"\").trim();\n    return trimmed === MEMBER_PLACEHOLDER ? \"\" : trimmed;\n}\n/** The members in join order (the order of the numbers). */\nexport function inJoinOrder(participants) {\n    return [...participants].sort((a, b) => a.joinedAt < b.joinedAt ? -1 : a.joinedAt > b.joinedAt ? 1 : 0);\n}\n/** Whether this device's participant is still in the group it holds. */\nexport function stillMember(group, participantId) {\n    return group.participants.some((participant) => participant.id === participantId);\n}\n/** The member rules with the app's words (`text`, the app's `t`: read at\n * every call, in the page's language). */\nexport function createMemberRules(text) {\n    function numberedLabel(index) {\n        return `${text(\"participant\")} ${index + 1}`;\n    }\n    function memberLabel(group, participantId) {\n        if (!group || !participantId)\n            return null;\n        const ordered = inJoinOrder(group.participants);\n        const index = ordered.findIndex((participant) => participant.id === participantId);\n        if (index < 0)\n            return null;\n        return givenName(ordered[index].name) || numberedLabel(index);\n    }\n    function applyMemberRules(list, group, meId, staff) {\n        const ordered = inJoinOrder(group?.participants ?? []);\n        for (const row of list.querySelectorAll(\"[data-participant-id]\")) {\n            const id = row.dataset.participantId ?? \"\";\n            const index = ordered.findIndex((participant) => participant.id === id);\n            const input = row.querySelector(\"input\");\n            if (input) {\n                input.setAttribute(\"aria-label\", text(\"memberName\"));\n                if (index >= 0)\n                    input.placeholder = numberedLabel(index);\n                if (input.value.trim() === MEMBER_PLACEHOLDER &&\n                    document.activeElement !== input)\n                    input.value = \"\";\n                // Only staff may rename someone else (the server answers\n                // 403 not_allowed).\n                input.readOnly = !staff && id !== meId;\n            }\n            const remove = row.querySelector(\"button\");\n            if (remove) {\n                remove.setAttribute(\"aria-label\", text(\"memberRemove\"));\n                remove.hidden = !staff || id === meId;\n            }\n        }\n    }\n    return { numberedLabel, memberLabel, applyMemberRules };\n}\n//# sourceMappingURL=members.js.map","/** The app-wide workshop session and the suite's membership rules.\n *\n * Every app has one `WorkshopSession`, so every view shares the same\n * identity, active group and polling (`createAppSession`). Around it:\n *\n * - the workshop of each group joined is remembered (lib/workshops), and a\n *   group of another workshop picked from \"your groups\" loads the page of\n *   that workshop (`followGroupWorkshops`);\n * - a device whose participant is gone (removed by staff, or a refused\n *   token) forgets the group (`forgetMembership`); `watchMembership` tells\n *   the app when the group still loads without this device in it. Where\n *   the device goes then (a flash, the start screen) is the app's. */\nimport { GroupsApi, IdentityStore, WorkshopSession, } from \"@starling-cloud/sturnia-workshop\";\nimport { carryWorkshop } from \"./launch.js\";\nimport { stillMember } from \"./members.js\";\nimport { addressInWorkshop, identityKey, normaliseWorkshop, rememberWorkshop, workshopOf, } from \"./workshops.js\";\n/** The app's identity store, groups API and session. */\nexport function createAppSession(options) {\n    const identity = options.identity ??\n        new IdentityStore({\n            app: options.app,\n            legacyKey: identityKey(options.app),\n        });\n    const groups = carryWorkshop(new GroupsApi(options.client, { basePath: \"\" }), options.workshop);\n    const session = new WorkshopSession({\n        client: options.client,\n        app: options.app,\n        identity,\n        groups,\n        basePath: \"\",\n        groupLabel: options.groupLabel ?? ((group) => group.name || group.code),\n    });\n    return { identity, groups, session };\n}\n/** A group entered: remember its workshop, or, for a group of another\n * workshop picked from \"your groups\", load the page of that workshop at\n * `#/group`. Register it before any screen's listener, so it runs first;\n * while `reloading` is set, the app renders nothing. */\nexport function followGroupWorkshops(session, options) {\n    const state = { reloading: false };\n    const assign = options.assign ?? ((url) => location.assign(url));\n    session.addEventListener(\"group-entered\", (event) => {\n        const code = String(event.detail?.code ?? \"\");\n        if (!code)\n            return;\n        const known = workshopOf(options.app, code);\n        if (known !== null && known !== normaliseWorkshop(options.workshop)) {\n            const loc = options.loc ?? location;\n            state.reloading = true;\n            assign(`${addressInWorkshop(loc.pathname, loc.search, known)}#/group`);\n            return;\n        }\n        rememberWorkshop(options.app, code, options.workshop);\n    });\n    return {\n        get reloading() {\n            return state.reloading;\n        },\n    };\n}\n/** Forget the group this device's participant is gone from: the\n * membership, the group, the polling. False when there was none. */\nexport function forgetMembership(session, identity) {\n    const membership = session.membership;\n    if (!membership)\n        return false;\n    identity.removeMembership(membership.code);\n    session.group = null;\n    session.stopPolling();\n    session.emitChange();\n    return true;\n}\n/** Call `onGone` when the active group loads without this device's\n * participant in it (removed by staff). Returns the function that stops. */\nexport function watchMembership(session, onGone) {\n    return session.onChange(() => {\n        const membership = session.membership;\n        const group = session.group;\n        if (!membership ||\n            !group ||\n            group.code.toUpperCase() !== membership.code.toUpperCase())\n            return;\n        if (!stillMember(group, membership.participantId))\n            onGone();\n    });\n}\n//# sourceMappingURL=session.js.map","/** The API's refusals, as the participant reads them (the suite's shared\n * contract, 2026-10-15).\n *\n * The server names a refusal with a `code` (sturnus-workshop) or an\n * `error` (an app's own routes) next to its `detail`. sturnia-workshop's\n * `ApiError` keeps only `status` and `detail`, so the code is read here, in\n * a fetch wrapper under the client, and the body handed on with a\n * translated `detail`: every screen that shows `error.detail` (the shared\n * start screen too) then shows Dutch on a Dutch page. Where a server only\n * sends its English sentence, the sentence is matched instead.\n *\n * The wrapper also retries a 503 `busy` (a locked database) once after the\n * `Retry-After` pause, and tells the app about codes that change the whole\n * screen (`workshop_closed`, a membership that is gone).\n *\n * The codes and their sentences are the app's: `createApiErrors` takes\n * them and returns the functions that use them. */\n/** The English sentences of servers that send no code (yet). */\nexport const ENGLISH_DETAILS = [\n    [/^workshop not found/i, \"workshop_not_found\"],\n    [/workshop has ended/i, \"workshop_closed\"],\n    [/^group not found/i, \"group_not_found\"],\n    [/^participant not found/i, \"participant_not_found\"],\n    [/invalid participant token/i, \"bad_token\"],\n    [/database is locked/i, \"busy\"],\n];\n/** How long to wait before the one retry of a 503 `busy`. */\nexport const BUSY_RETRY_MS = 2000;\n/** The pause a 503 asks for (`Retry-After` in seconds), at most 5 s. */\nexport function retryDelay(response) {\n    const seconds = Number(response.headers.get(\"Retry-After\"));\n    return Number.isFinite(seconds) && seconds > 0\n        ? Math.min(seconds, 5) * 1000\n        : BUSY_RETRY_MS;\n}\n/** The JSON body of a response, or null (none, or not JSON). */\nexport async function bodyOf(response) {\n    try {\n        return await response.clone().json();\n    }\n    catch {\n        return null;\n    }\n}\n/** The HTTP status of an error the client threw (0: no connection), or\n * null. */\nexport function apiStatus(error) {\n    if (typeof error !== \"object\" || error === null)\n        return null;\n    const { status } = error;\n    return typeof status === \"number\" ? status : null;\n}\nconst sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n/** The refusal handling of one app, with its codes and sentences. */\nexport function createApiErrors(options) {\n    const { texts, translate } = options;\n    const generic = () => translate(options.generic);\n    const english = options.english ?? ENGLISH_DETAILS;\n    const ambiguous = new Set(options.ambiguous ?? []);\n    const listeners = new Set();\n    function isCode(value) {\n        return (typeof value === \"string\" &&\n            Object.prototype.hasOwnProperty.call(texts, value));\n    }\n    function codeOf(body) {\n        if (typeof body !== \"object\" || body === null)\n            return null;\n        const { code, error, detail } = body;\n        if (isCode(code))\n            return code;\n        if (isCode(error))\n            return error;\n        if (typeof detail !== \"string\")\n            return null;\n        for (const [pattern, match] of english)\n            if (isCode(match) && pattern.test(detail))\n                return match;\n        return null;\n    }\n    function codeText(code) {\n        return translate(texts[code]);\n    }\n    function apiErrorCode(error) {\n        if (typeof error !== \"object\" || error === null)\n            return null;\n        const { code, detail } = error;\n        if (isCode(code))\n            return code;\n        if (typeof detail !== \"string\")\n            return null;\n        for (const key of Object.keys(texts)) {\n            if (ambiguous.has(key))\n                continue;\n            if (detail === translate(texts[key], \"nl\") ||\n                detail === translate(texts[key], \"en\"))\n                return key;\n        }\n        return codeOf({ detail });\n    }\n    function errorText(error) {\n        if (typeof error === \"object\" && error !== null) {\n            const { status, detail } = error;\n            if (typeof status === \"number\" &&\n                typeof detail === \"string\" &&\n                detail &&\n                !/^Request failed/.test(detail)) {\n                return status === 0 && options.offline\n                    ? translate(options.offline)\n                    : detail;\n            }\n        }\n        return generic();\n    }\n    function onApiCode(listener) {\n        listeners.add(listener);\n        return () => listeners.delete(listener);\n    }\n    function withApiErrors(base, wait = sleep, notify = true) {\n        return async (input, init) => {\n            let response = await base(input, init);\n            if (response.status === 503 &&\n                codeOf(await bodyOf(response)) === \"busy\") {\n                await wait(retryDelay(response));\n                response = await base(input, init);\n            }\n            if (response.ok)\n                return response;\n            const body = await bodyOf(response);\n            const code = codeOf(body);\n            if (code && notify)\n                for (const listener of listeners)\n                    listener(code, response.status);\n            let detail = null;\n            if (code)\n                detail = codeText(code);\n            else if (body === null ||\n                (response.status >= 500 && typeof body === \"object\"))\n                detail = generic();\n            if (detail === null)\n                return response;\n            const record = typeof body === \"object\" && body !== null ? body : {};\n            return new Response(JSON.stringify({\n                ...record,\n                ...(code ? { code } : {}),\n                detail,\n            }), {\n                status: response.status,\n                statusText: response.statusText,\n                headers: { \"Content-Type\": \"application/json\" },\n            });\n        };\n    }\n    return {\n        codeOf,\n        codeText,\n        apiErrorCode,\n        errorText,\n        onApiCode,\n        withApiErrors,\n    };\n}\n//# sourceMappingURL=errors.js.map","/** The API's refusals, as the participant reads them (the suite's shared\n * contract, 2026-10-15).\n *\n * The server names a refusal with a `code` (sturnus-workshop) or an\n * `error` (this app's generate routes) next to its `detail`. sturnia-workshop's\n * `ApiError` keeps only `status` and `detail`, so the code is read here, in\n * a fetch wrapper under the client, and the body handed on with a\n * translated `detail`: every screen that shows `error.detail` (the shared\n * start screen too) then shows Dutch on a Dutch page. Where a server only\n * sends its English sentence, the sentence is matched instead.\n *\n * The wrapper also retries a 503 `busy` (a locked database) once after the\n * `Retry-After` pause, and tells the app about codes that change the whole\n * screen (`workshop_closed`, a membership that is gone). The code is\n * study-base's (lib/errors); the codes and their sentences are this app's.\n *\n * `server_unreachable` is no answer of the app: lib/connection, under this\n * wrapper (lib/fetch), puts it on the front's answer while the server\n * restarts. */\n\nimport {\n    BUSY_RETRY_MS,\n    createApiErrors,\n    retryDelay,\n} from \"@starling-study/study-base/lib/errors\";\n\nimport { t, type StringKey } from \"./i18n\";\n\nexport { BUSY_RETRY_MS, retryDelay };\n\nexport type ApiCode =\n    | \"workshop_closed\"\n    | \"workshop_not_found\"\n    | \"group_not_found\"\n    | \"participant_not_found\"\n    | \"bad_token\"\n    | \"not_allowed\"\n    | \"busy\"\n    | \"generation_off\"\n    | \"generation_paused\"\n    | \"already_running\"\n    | \"group_limit\"\n    | \"server_unreachable\";\n\n/** The translated sentence of each code. */\nconst TEXTS: Record<ApiCode, StringKey> = {\n    workshop_closed: \"errorWorkshopClosed\",\n    workshop_not_found: \"errorWorkshopNotFound\",\n    group_not_found: \"errorGroupNotFound\",\n    participant_not_found: \"errorNotInGroup\",\n    bad_token: \"errorNotInGroup\",\n    not_allowed: \"errorNotAllowed\",\n    busy: \"errorRoomBusy\",\n    generation_off: \"errorOff\",\n    generation_paused: \"errorPaused\",\n    already_running: \"errorBusy\",\n    group_limit: \"errorLimit\",\n    server_unreachable: \"errorRestarting\",\n};\n\nexport const {\n    codeOf,\n    codeText,\n    apiErrorCode,\n    errorText,\n    onApiCode,\n    withApiErrors,\n} = createApiErrors<ApiCode, StringKey>({\n    texts: TEXTS,\n    translate: t,\n    generic: \"errorGeneric\",\n});\n","/** The fetch under the app's one client (api.ts), from the top:\n *\n * - lib/errors retries a busy database once and translates the refusals;\n * - study-base's lib/connection tells the front's answer while the server\n *   restarts (a refused connection, a 502/503/504/52x, an HTML page) from\n *   the app's own: it marks the shared `connection` down, which the banner\n *   (components/connection) and the studio's poll hear, and hands on a\n *   JSON `server_unreachable` instead of the front's page;\n * - `base`: the CSRF token (api.ts).\n *\n * Kept apart from api.ts so the wrapping is tested without a client. */\n\nimport {\n    watchConnection,\n    type WatchOptions,\n} from \"@starling-study/study-base/lib/connection\";\n\nimport { withApiErrors } from \"./errors\";\n\nexport interface ApiFetchOptions extends WatchOptions {\n    /** The pause before the one retry of a 503 `busy` (lib/errors). */\n    wait?: (ms: number) => Promise<void>;\n}\n\nexport function apiFetch(\n    base: typeof fetch,\n    options: ApiFetchOptions = {},\n): typeof fetch {\n    const { wait, ...watch } = options;\n    return withApiErrors(watchConnection(base, watch), wait);\n}\n","import {\n    ApiError,\n    WorkshopClient,\n    type WorkshopGroup,\n} from \"@starling-cloud/sturnia-workshop\";\nimport { csrfHeader, withCsrf } from \"@starling-study/study-base/lib/access\";\n\nimport { config } from \"./lib/config\";\nimport { apiFetch } from \"./lib/fetch\";\nimport type { LocalizedText } from \"./lib/i18n\";\nimport { withWorkshop } from \"./lib/launch\";\n\nexport { ApiError, isPasswordError } from \"@starling-cloud/sturnia-workshop\";\n\n/** The workshop this page belongs to travels on every call, and the page's\n * language as `Accept-Language`, so a refusal's `detail` comes back in it\n * (the API itself is not language-prefixed), as in study-chat-public. */\nfunction workshopHeaders(): Record<string, string> {\n    return {\n        \"Accept-Language\": config.lang,\n        ...(config.workshop ? { \"X-Workshop\": config.workshop } : {}),\n    };\n}\n\n// One client for the whole app: attaches X-Workshop-Password and\n// X-Participant-Token to every call and knows how to store/clear the\n// workshop password on this device. The password lives under the one key\n// every app on the origin shares (`workshop:password`, sturnia-workshop's\n// default), so a device let in by chat is let in here too; the key this\n// app used before is moved over once. Paths below are relative to the\n// app's API prefix (data-api-base, `/api/imagine`). A staff session sends\n// its CSRF token on every unsafe call (`X-CSRFToken`). Under it, lib/errors\n// retries a busy database once and translates the refusals, and under that\n// lib/connection tells the front's answer while the server restarts from\n// the app's own (lib/fetch).\nexport const client = new WorkshopClient({\n    baseUrl: config.apiBase,\n    legacyPasswordKey: `study-${config.app}:password`,\n    fetch: apiFetch(withCsrf(config.csrfToken)),\n    headers: workshopHeaders,\n});\n\n/** The app's own password probe: a cheap gated GET. The bundle no longer\n * calls it (the entry checks study-base's `GET /api/base/access/`). */\nexport const PROBE_PATH = \"/session/\";\n\n/** A URL from the server: absolute paths and full URLs as they are, a\n * relative one under the API prefix. */\nexport function resolveUrl(url: string): string {\n    if (/^(https?:)?\\/\\//.test(url) || url.startsWith(\"/\")) return url;\n    return client.url(`/${url.replace(/^\\.?\\//, \"\")}`);\n}\n\n/** Every header a hand-made request needs (the raw upload, a POST). */\nfunction rawHeaders(\n    extra: Record<string, string> = {},\n    method = \"POST\",\n): Record<string, string> {\n    const headers: Record<string, string> = {\n        ...workshopHeaders(),\n        ...csrfHeader(config.csrfToken, method),\n        ...extra,\n    };\n    const password = client.storedPassword();\n    if (password) headers[\"X-Workshop-Password\"] = password;\n    return headers;\n}\n\n/** The fetch of a hand-made request: the same retry, translations and\n * connection watch (lib/fetch). */\nconst rawFetch = apiFetch((input, init) => globalThis.fetch(input, init));\n\nasync function failure(response: Response): Promise<ApiError> {\n    let detail = \"\";\n    let code = \"\";\n    try {\n        const body = (await response.json()) as {\n            detail?: string;\n            code?: string;\n        };\n        detail = String(body.detail ?? \"\");\n        code = typeof body.code === \"string\" ? body.code : \"\";\n    } catch {\n        // No JSON body; the status is all there is.\n    }\n    return new ApiError(response.status, detail || response.statusText, code);\n}\n\n// ---- what the server can do ----------------------------------------------\n\nexport type Aspect = \"1:1\" | \"4:3\" | \"3:4\" | \"3:2\" | \"2:3\" | \"16:9\" | \"9:16\";\nexport type Quality = \"low\" | \"medium\" | \"high\";\n\nexport interface ProviderInfo {\n    id: string;\n    label: string;\n    model: string;\n    aspects: Aspect[];\n    supportsQuality: boolean;\n    supportsNegativePrompt: boolean;\n    supportsReference: boolean;\n    maxCount: number;\n}\n\nexport interface Capabilities {\n    enabled: boolean;\n    paused: boolean;\n    defaultProvider: string | null;\n    /** Frames every run makes — the room's setting, not the group's. */\n    imagesPerRun: number;\n    /** The aspect a new board starts on (the organiser's set-up). */\n    defaultAspect?: string;\n    /** A quality the organiser fixed for the room, else null. */\n    quality?: string | null;\n    /** The room's provider; the alternatives only once the workshop was switched. */\n    providers: ProviderInfo[];\n}\n\n/** One file behind /downloads. `url` is open — no password needed. */\nexport interface DownloadInfo {\n    id: string;\n    file: string;\n    url: string;\n    title: LocalizedText;\n    description: LocalizedText | null;\n    lang: \"nl\" | \"en\" | \"both\";\n    kind: \"instructions\" | \"sheet\" | \"other\";\n    sizeBytes: number;\n    mime: string;\n}\n\nexport interface DownloadsInfo {\n    intro: LocalizedText | null;\n    downloads: DownloadInfo[];\n}\n\n// ---- the group's board, riding along on the shared group object ----------\n\n/** The group's controls. The model and the frames per run are the room's,\n * chosen by the organiser — see Capabilities. */\nexport interface BoardState {\n    prompt: string;\n    negativePrompt: string;\n    aspect: Aspect;\n    quality: Quality;\n    seed: number | null;\n    selected: string | null;\n    /** The group's own picture as guidance for the next new image. */\n    reference: ImageInfo | null;\n    step: string;\n    updatedAt: string;\n}\n\nexport interface ImageInfo {\n    publicId: string;\n    url: string;\n    provider: string;\n    model: string;\n    /** The group's own words (the provider's instructions left out). */\n    prompt: string;\n    /** The refinement the group asked for (\"\" for a new image or a variant). */\n    change?: string;\n    negativePrompt: string;\n    revisedPrompt: string | null;\n    aspect: string;\n    quality: string;\n    seed: number | null;\n    mime: string;\n    width: number | null;\n    height: number | null;\n    sizeBytes: number;\n    createdAt: string;\n}\n\n/** A new image, a described change of the picked one, or \"more like this\". */\nexport type GenerationKind = \"initial\" | \"refine\" | \"vary\";\n\nexport interface GeneratingInfo {\n    id: number;\n    kind: GenerationKind;\n    status: \"queued\" | \"running\";\n    participantId: string | null;\n    count: number;\n    /** 1 = next in the room; null once the run has started. */\n    queuePosition: number | null;\n    createdAt: string;\n    startedAt: string | null;\n}\n\nexport interface ImagineGroup extends WorkshopGroup {\n    board: BoardState;\n    images: ImageInfo[];\n    generating: GeneratingInfo | null;\n}\n\nexport type GenerationStatus = \"queued\" | \"running\" | \"done\" | \"error\";\n\nexport interface GenerationInfo {\n    id: number;\n    kind: GenerationKind;\n    status: GenerationStatus;\n    participantId: string | null;\n    provider: string;\n    model: string;\n    count: number;\n    imagesMade: number;\n    queuePosition: number | null;\n    error: string | null;\n    createdAt: string;\n    startedAt: string | null;\n    finishedAt: string | null;\n    images: ImageInfo[];\n}\n\n/** Everything a participant may change on the board. */\nexport interface BoardPatch {\n    prompt?: string;\n    negativePrompt?: string;\n    aspect?: Aspect;\n    quality?: Quality;\n    seed?: number | null;\n    selected?: string | null;\n    /** `null` takes the guidance picture away; api.uploadImage sets it. */\n    reference?: null;\n    step?: string;\n}\n\n/** One run as the group's history shows it: what was sent, and what came\n * back. */\nexport interface RunInfo extends GenerationInfo {\n    prompt: string;\n    /** The refinement the group asked for (\"\" for a new image or a variant). */\n    change?: string;\n    negativePrompt: string;\n    aspect: string;\n    quality: string;\n    seed: number | null;\n}\n\nexport const api = {\n    capabilities: () => client.request<Capabilities>(\"GET\", \"/providers/\"),\n    downloads: () => client.request<DownloadsInfo>(\"GET\", \"/downloads/\"),\n\n    images: (code: string, token: string) =>\n        client.request<ImageInfo[]>(\"GET\", `/groups/${code}/images/`, {\n            token,\n        }),\n    history: (code: string, token: string) =>\n        client.request<RunInfo[]>(\"GET\", `/groups/${code}/history/`, {\n            token,\n        }),\n\n    generate: (\n        code: string,\n        token: string,\n        body: { kind: GenerationKind; changes?: string },\n    ) =>\n        client.request<{ generation: GenerationInfo }>(\n            \"POST\",\n            `/groups/${code}/generate/`,\n            {\n                json: body,\n                token,\n            },\n        ),\n    generation: (code: string, token: string) =>\n        client.request<{ generation: GenerationInfo | null }>(\n            \"GET\",\n            `/groups/${code}/generate/`,\n            { token },\n        ),\n\n    /** A picture from the phone as guidance: the raw file is the body, so\n     * this one bypasses request() (which only speaks JSON and forms). */\n    uploadImage: async (\n        code: string,\n        token: string,\n        file: File,\n    ): Promise<ImageInfo> => {\n        const response = await rawFetch(\n            client.url(`/groups/${code}/images/`),\n            {\n                method: \"POST\",\n                headers: rawHeaders({\n                    \"Content-Type\": file.type || \"application/octet-stream\",\n                    \"X-Participant-Token\": token,\n                }),\n                body: file,\n            },\n        );\n        if (!response.ok) throw await failure(response);\n        return (await response.json()) as ImageInfo;\n    },\n    deleteImage: (code: string, token: string, publicId: string) =>\n        client.request<void>(\"DELETE\", `/groups/${code}/images/${publicId}/`, {\n            token,\n        }),\n\n    /** The QR <img> cannot send `X-Workshop`: the workshop rides in the query.\n     * The group card's own image gets the same URL from `session.groups.qrUrl`\n     * (`carryWorkshop` in session.ts). */\n    qrUrl: (code: string) =>\n        withWorkshop(\n            client.url(\n                `/groups/${encodeURIComponent(code.toUpperCase())}/qr.png`,\n            ),\n            config.workshop,\n        ),\n};\n","/** Whole-screen notices, and the one-line message the workshop's groups\n * page shows after a group was left (or this device was taken out of it). */\n\nimport { el } from \"@starling-study/study-base/lib/dom\";\nimport { setGroupsFlash } from \"@starling-study/study-base/lib/entry\";\n\nimport { t } from \"../lib/i18n\";\n\n/** A short message for the groups page, where the device goes next\n * (study-base's `setGroupsFlash`: shown there once). */\nexport function setFlash(text: string): void {\n    setGroupsFlash(text);\n}\n\n/** A calm full panel: a title, a sentence and maybe one way on. */\nexport function noticePanel(\n    title: string,\n    text: string,\n    action?: { label: string; href: string },\n): HTMLElement {\n    return el(\n        \"div\",\n        { class: \"study-centered\" },\n        el(\n            \"section\",\n            { class: \"ss-card ss-stack\", role: \"status\" },\n            el(\"h1\", { class: \"ss-card__title\", text: title }),\n            el(\"p\", { class: \"ss-hint\", text }),\n            action\n                ? el(\"a\", { class: \"ss-btn\", href: action.href }, action.label)\n                : null,\n        ),\n    );\n}\n\n/** The workshop is over (`workshop_closed`): thanks, nothing more to do. */\nexport function closedPanel(): HTMLElement {\n    return noticePanel(t(\"closedTitle\"), t(\"closedText\"));\n}\n\n/** The page's workshop does not exist: the way on is the default one. */\nexport function unknownWorkshopPanel(\n    loc: Pick<Location, \"pathname\" | \"search\"> = location,\n): HTMLElement {\n    const params = new URLSearchParams(loc.search);\n    params.set(\"workshop\", \"default\");\n    params.delete(\"join\");\n    params.delete(\"code\");\n    return noticePanel(t(\"nothingHereTitle\"), t(\"errorWorkshopNotFound\"), {\n        label: t(\"toStart\"),\n        href: `${loc.pathname}?${params.toString()}#/`,\n    });\n}\n","/** The app-wide session: one WorkshopSession<ImagineGroup>, so every view\n * shares the same identity, active group and polling.\n *\n * It also keeps the suite's membership rules for every screen (study-base's\n * lib/session): the workshop of each group joined is remembered\n * (lib/workshops), and a device whose participant is gone (removed by\n * staff, or a refused token) goes back to the workshop's groups page (via\n * `#/`, lib/route) with a short message. */\n\nimport {\n    createAppSession,\n    followGroupWorkshops,\n    forgetMembership,\n    watchMembership,\n} from \"@starling-study/study-base/lib/session\";\n\nimport { client, type BoardPatch, type ImagineGroup } from \"./api\";\nimport { setFlash } from \"./components/notice\";\nimport { config } from \"./lib/config\";\nimport { onApiCode } from \"./lib/errors\";\nimport { t } from \"./lib/i18n\";\nimport { go } from \"./lib/router\";\n\n// The client already carries the API prefix (data-api-base); the group\n// routes sit right under it. sturnia-workshop's group card draws its QR\n// image from `session.groups.qrUrl`: the page's workshop goes in that URL,\n// which an <img> request cannot send as a header (lib/launch).\n//\n// The identity is the one store every app on the origin shares\n// (`workshop.identity.v1`): the name and the active team code are common,\n// and this app's memberships are the entries tagged with its slug. A team\n// joined in chat is then known here (study-base's lib/entry joins it\n// silently).\n// study-base 0.4.0 builds that store from the app's slug and imports the\n// store this app kept under its own key (`study-imagine.identity.v1`) once.\nexport const { identity, session } = createAppSession<ImagineGroup>({\n    client,\n    app: config.app,\n    workshop: config.workshop,\n});\n\n/** patchGroup({ board: {...} }) typed for the board's own (fully optional)\n * patch shape — WorkshopSession<G>.patchGroup takes Partial<G>, whose\n * `board` field is a *complete* BoardState, which a partial patch like\n * `{ step: \"results\" }` does not satisfy. This is the one place that gap is\n * bridged, instead of an `as never` at every call site. */\nexport function patchBoard(board: BoardPatch): Promise<ImagineGroup> {\n    return session.patchGroup({ board } as unknown as Partial<ImagineGroup>);\n}\n\n// A group entered: remember its workshop — or, for a group of another\n// workshop picked from \"your groups\", load the page of that workshop.\n// Registered before any screen's listener, so it runs first.\nconst follower = followGroupWorkshops(session, {\n    app: config.app,\n    workshop: config.workshop,\n});\n\n/** Set while the page reloads into another workshop: render nothing. */\nexport function isReloading(): boolean {\n    return follower.reloading;\n}\n\n/** This device's participant is gone: forget the group, off to the\n * groups page. */\nexport function dropMembership(message: string): void {\n    if (!forgetMembership(session, identity)) return;\n    setFlash(message);\n    go(\"/\");\n}\n\n// Removed by staff: the group still loads, without this device in it.\nwatchMembership(session, () => dropMembership(t(\"removedFromGroup\")));\n\n// …or a call with its token is refused.\nonApiCode((code) => {\n    if (code === \"bad_token\") dropMembership(t(\"removedFromGroup\"));\n});\n","/** The one header every screen shares: study-base's app bar\n * (`mountAppbar`, the theme's `study-appbar`). It is mounted once, outside\n * the screens' mount, and kept across routes; a screen only says what sits\n * under it.\n *\n * The bar holds the wordmark with the app's name, the group chip (a link\n * to the workshop's group page, which `mountAppbar` makes from the shell's\n * `data-groups-url`: members, code, QR code and every tool) and the links Studio, Geschiedenis and Downloads;\n * the language switch and the theme toggle are study-base's. */\n\nimport {\n    keepEmbed,\n    mountAppbar,\n    type AppbarHandle,\n    type AppbarLink,\n} from \"@starling-study/study-base/appbar\";\nimport { el } from \"@starling-study/study-base/lib/dom\";\nimport { groupPageUrl } from \"@starling-study/study-base/lib/entry\";\n\nimport { config } from \"../lib/config\";\nimport { getLang, t } from \"../lib/i18n\";\nimport { withWorkshop } from \"../lib/launch\";\nimport { href } from \"../lib/router\";\nimport { session } from \"../session\";\n\nconst LANGS = [\"nl\", \"en\"];\n\nlet bar: AppbarHandle | null = null;\n\n/** Studio and Geschiedenis need a group; the downloads are for everyone. */\nfunction links(): AppbarLink[] {\n    const inGroup =\n        session.membership !== null && session.membership !== undefined;\n    return [\n        ...(inGroup\n            ? [\n                  { label: t(\"studio\"), href: href(\"/studio\") },\n                  { label: t(\"history\"), href: href(\"/history\") },\n              ]\n            : []),\n        { label: t(\"downloads\"), href: href(\"/downloads\") },\n    ];\n}\n\nfunction group(): { name: string; code: string } | null {\n    const membership = session.membership;\n    if (!membership) return null;\n    return {\n        name:\n            membership.groupName && membership.groupName !== membership.code\n                ? membership.groupName\n                : \"\",\n        code: membership.code,\n    };\n}\n\n/** The app bar, up to date with the session: built once, on `host` (the\n * shell's `#study-app`), outside the element the screens render into — so\n * no screen moves or removes it. */\nexport function appbar(host: HTMLElement = config.root): HTMLElement {\n    if (!bar) {\n        bar = mountAppbar(host, {\n            app: config.app,\n            title: t(\"appName\"),\n            lang: getLang(),\n            langs: LANGS,\n            wordmarkHref: withWorkshop(`/${getLang()}/`, config.workshop),\n            group: group(),\n            links: links(),\n        });\n        // Joining, leaving or renaming the group shows in the chip at once.\n        session.onChange(() =>\n            bar?.update({ group: group(), links: links() }),\n        );\n    }\n    return bar.element;\n}\n\n/** Inside a lesson there is no bar (the lesson has the one header), so the\n * app's own few links sit on top of the screen: the group page (inside the\n * lesson too), the studio, the history and the downloads. Built once on `host`, before the screens. */\nexport function embedNav(host: HTMLElement): HTMLElement {\n    const nav = el(\"nav\", {\n        class: \"ss-toolbar ss-toolbar--wrap\",\n        \"aria-label\": t(\"appName\"),\n    });\n    const draw = (): void => {\n        const membership = session.membership;\n        const groupPage = membership ? groupPageUrl(membership.code) : \"\";\n        const items = [\n            ...(groupPage\n                ? [{ label: t(\"yourGroup\"), href: keepEmbed(groupPage) }]\n                : []),\n            ...links(),\n        ];\n        nav.replaceChildren(\n            ...items.map((item) =>\n                el(\n                    \"a\",\n                    {\n                        class: \"ss-btn ss-btn--sm ss-btn--ghost\",\n                        href: item.href,\n                    },\n                    item.label,\n                ),\n            ),\n        );\n    };\n    draw();\n    session.onChange(draw);\n    host.prepend(nav);\n    return nav;\n}\n\n/** The chrome of the page, once: the app bar, or inside a lesson the\n * app's own links. */\nexport function mountChrome(host: HTMLElement = config.root): void {\n    if (config.embedded) {\n        embedNav(host);\n        // No bar on top in a lesson's frame: what sticks (the restart\n        // banner) sticks at the frame's own top edge.\n        document.documentElement.style.setProperty(\n            \"--study-sticky-top\",\n            \"0px\",\n        );\n    } else appbar(host);\n}\n\n/** What a screen puts in its mount: just its own content (no wrapper; the\n * theme's `.study-app` is the column itself). The bar is not in it. */\nexport function shell(main: HTMLElement): DocumentFragment {\n    const fragment = document.createDocumentFragment();\n    fragment.append(main);\n    return fragment;\n}\n","/** The notice while the server cannot be reached (lib/connection).\n *\n * A strip under the app bar, in the page flow: it pushes the page down\n * while it shows and covers nothing. It is the first child of the content\n * root (after the app bar when the bar sits in the same host) and sticks\n * under the bar while the page scrolls: \"The server is restarting — still\n * trying…\" with a spinner while the connection is down (\"No internet\n * connection…\" when the device itself is offline), \"Connected again\" for a\n * moment once the app answers again, then gone. The poll asks again\n * meanwhile with a growing pause and loads the group once it is back\n * (views/studio).\n *\n * `showEntryWait` is the line of the page itself while the way in waits\n * for a server that is away at page load (`requireGroup`'s `onWait`). */\n\nimport {\n    connection as appConnection,\n    connectionNotice,\n    type Connection,\n} from \"@starling-study/study-base/lib/connection\";\nimport { el } from \"@starling-study/study-base/lib/dom\";\n\nimport { t } from \"../lib/i18n\";\n\n/** How long \"Connected again\" stays. */\nexport const BACK_FLASH_MS = 3000;\n\nexport function mountConnectionBanner(\n    host: HTMLElement,\n    connection: Connection = appConnection,\n): () => void {\n    const spinner = el(\"span\", {\n        class: \"study-running__spinner\",\n        \"aria-hidden\": \"true\",\n    });\n    const text = el(\"p\", { class: \"study-banner__text\" });\n    const banner = el(\n        \"div\",\n        {\n            class: \"study-banner study-banner--warn imagine-connection\",\n            role: \"status\",\n            \"aria-live\": \"polite\",\n            \"data-role\": \"connection\",\n        },\n        spinner,\n        text,\n    );\n    banner.hidden = true;\n    // First in the content, under the bar (`mountAppbar` puts the bar\n    // before the shell's `main`, or first in a host outside one).\n    const bar = host.querySelector(\":scope > .study-appbar\");\n    if (bar) bar.after(banner);\n    else host.prepend(banner);\n\n    let backTimer: ReturnType<typeof setTimeout> | null = null;\n    const clearBack = (): void => {\n        if (backTimer !== null) clearTimeout(backTimer);\n        backTimer = null;\n    };\n\n    const show = (): void => {\n        clearBack();\n        const notice = connectionNotice(connection, navigator.onLine);\n        if (notice) {\n            banner.classList.replace(\n                \"study-banner--success\",\n                \"study-banner--warn\",\n            );\n            spinner.hidden = false;\n            text.textContent = t(notice);\n            banner.hidden = false;\n            return;\n        }\n        if (banner.hidden) return;\n        // Back: say so for a moment, then step aside.\n        banner.classList.replace(\n            \"study-banner--warn\",\n            \"study-banner--success\",\n        );\n        spinner.hidden = true;\n        text.textContent = t(\"connectionBack\");\n        backTimer = setTimeout(() => {\n            backTimer = null;\n            banner.hidden = true;\n        }, BACK_FLASH_MS);\n    };\n\n    const offChange = connection.onChange(show);\n    // The device's own network: the wording follows it while down.\n    const onNetwork = (): void => {\n        if (connection.down) show();\n    };\n    window.addEventListener(\"online\", onNetwork);\n    window.addEventListener(\"offline\", onNetwork);\n\n    return () => {\n        clearBack();\n        offChange();\n        window.removeEventListener(\"online\", onNetwork);\n        window.removeEventListener(\"offline\", onNetwork);\n        banner.remove();\n    };\n}\n\n/** The page while the way in waits for the server (`onWait` of\n * `requireGroup`): one calm line in place of the empty screen (\"your group\n * opens as soon as the server is back\"; the banner above says why), until\n * a view renders or the device is sent to the groups page. */\nexport function showEntryWait(root: HTMLElement): void {\n    root.replaceChildren(\n        el(\"p\", {\n            class: \"imagine-entry-wait\",\n            role: \"status\",\n            \"aria-live\": \"polite\",\n            \"data-role\": \"entry-wait\",\n            text: t(\"entryWaiting\"),\n        }),\n    );\n}\n","/** Who is who in a group, the same in every app of the suite (study-base's\n * lib/members, with this app's words):\n *\n * - A member without a name (or with the old placeholder \"—\") is\n *   \"Deelnemer 3\" / \"Participant 3\", numbered in join order.\n * - A device joins under the name the apps on this origin share (one typed\n *   in chat, say), else under the placeholder; the workshop's group page\n *   then asks for a first name (`joinName`, `dropPlaceholderName`).\n *\n * Who is in the group, renaming and leaving are the workshop's group page\n * (study-base), not this app's. */\n\nimport type { WorkshopSession } from \"@starling-cloud/sturnia-workshop\";\nimport {\n    createMemberRules,\n    givenName,\n    MEMBER_PLACEHOLDER,\n} from \"@starling-study/study-base/lib/members\";\n\nimport { t } from \"./i18n\";\n\nexport {\n    MEMBER_PLACEHOLDER,\n    givenName,\n    inJoinOrder,\n    stillMember,\n} from \"@starling-study/study-base/lib/members\";\n\nexport const { numberedLabel, memberLabel } = createMemberRules(t);\n\n/** The session's name, as far as the join name needs it. */\ntype NamedSession = Pick<WorkshopSession, \"userName\" | \"setUserName\">;\n\n/** The name to join with: the shared one when a person gave it, else the\n * placeholder. */\nexport function joinName(session: Pick<NamedSession, \"userName\">): string {\n    return givenName(session.userName) || MEMBER_PLACEHOLDER;\n}\n\n/** The placeholder must not stay in the shared name: every app on the\n * origin reads it, and `joinGroup` stores whatever name it joins with. So\n * after a placeholder join — done or refused — the shared name goes back\n * to empty. */\nexport function dropPlaceholderName(session: NamedSession): void {\n    if (session.userName === MEMBER_PLACEHOLDER) session.setUserName(\"\");\n}\n","/** Imagine's boot wiring: which screen a hash route gets, after the way in.\n *\n * The way in is study-base's (`@starling-study/study-base/lib/entry`): the\n * workshop password and the group are the workshop's groups page's, not\n * this app's. So:\n *\n * - `#/downloads` needs the password only (`requireAccess`);\n * - every other route enters the group once per page load\n *   (`requireGroup`: a `?join=` link's team at once — inside a lesson too —,\n *   else the team this device is in, else off to the groups page with\n *   `?next=` this page);\n * - a device out of its group later on (switched, left, removed) goes to\n *   the groups page (`leaveForGroups`), never back in silently;\n * - `#/history` is a screen of its own; `#/studio`, `#/`, an old `#/group`\n *   and anything unknown is the studio, under the address `#/studio`. The\n *   group itself (its members, code, QR code, the other tools) is the\n *   workshop's group page, which the app bar's group chip opens;\n * - a route the user already left while it waited (a slow password check\n *   or join) renders nothing; a route asked for during the entry waits for\n *   that same entry.\n *\n * Everything it calls comes in as `deps`, so the wiring is tested without\n * a page (tst/route.test.ts). */\n\nexport type View = \"studio\" | \"history\" | \"downloads\";\n\nexport interface RouteDeps {\n    /** A whole-screen notice replaced the app, or the page reloads into\n     * another workshop: render nothing. */\n    halted: () => boolean;\n    hasMembership: () => boolean;\n    requireAccess: () => Promise<boolean>;\n    /** Resolves to the membership, or null after leaving for the groups page. */\n    requireGroup: () => Promise<unknown>;\n    /** After the join: the placeholder name leaves the shared name again. */\n    afterEntry: () => void;\n    leaveForGroups: () => void;\n    /** Put `#/studio` in the address without a new route. */\n    showHomeAddress: () => void;\n    render: (view: View) => void | Promise<void>;\n}\n\n/** The router's callback for Imagine (see above). */\nexport function createRoute(deps: RouteDeps): (path: string) => Promise<void> {\n    /** The one entry of this page load; a route asked for while it runs\n     * waits for the same one. */\n    let entry: Promise<unknown> | null = null;\n    /** Bumped on every navigation: a route the user already left must not\n     * render over the new one. */\n    let navigation = 0;\n    return async (path: string): Promise<void> => {\n        const mine = ++navigation;\n        const current = (): boolean => mine === navigation && !deps.halted();\n        if (deps.halted()) return;\n        if (path === \"/downloads\") {\n            if ((await deps.requireAccess()) && current())\n                await deps.render(\"downloads\");\n            return;\n        }\n        entry ??= deps.requireGroup().then((membership) => {\n            deps.afterEntry();\n            return membership;\n        });\n        if (!(await entry)) return;\n        if (!current()) return;\n        if (!deps.hasMembership()) {\n            deps.leaveForGroups();\n            return;\n        }\n        if (path === \"/history\") return deps.render(\"history\");\n        if (path !== \"/studio\") deps.showHomeAddress();\n        return deps.render(\"studio\");\n    };\n}\n","/** #/downloads — the instruction sheet, the workshop sheets and whatever\n * else the organiser hands out, as files. The list sits behind the workshop\n * password; the files themselves are open, so a printed card can link\n * straight to one. The list is the workshop's own (the organiser edits it\n * in the dashboard; the files bundled with the app are the defaults); this\n * screen only draws it, the current language's files first. */\n\nimport { el, formatBytes } from \"@starling-study/study-base/lib/dom\";\n\nimport { api, resolveUrl, type DownloadInfo } from \"../api\";\nimport { shell } from \"../components/chrome\";\nimport { getLang, pick, t } from \"../lib/i18n\";\n\nexport async function renderDownloads(root: HTMLElement): Promise<void> {\n    const main = el(\"div\", { class: \"study-page\" });\n    root.replaceChildren(shell(main));\n\n    const payload = await api.downloads().catch(() => null);\n    if (!payload) {\n        main.append(el(\"p\", { class: \"ss-hint\", text: t(\"errorGeneric\") }));\n        return;\n    }\n\n    // The current language first, then what is for both, then the other.\n    const lang = getLang();\n    const rank = (entry: DownloadInfo): number =>\n        entry.lang === lang ? 0 : entry.lang === \"both\" ? 1 : 2;\n    const entries = [...payload.downloads].sort((a, b) => rank(a) - rank(b));\n\n    const list = el(\"div\", { class: \"study-downloads\" });\n    for (const entry of entries) list.append(item(entry));\n\n    main.append(\n        el(\n            \"div\",\n            { class: \"ss-card ss-stack\" },\n            el(\"h1\", { class: \"ss-card__title\", text: t(\"downloadsTitle\") }),\n            el(\"p\", {\n                class: \"ss-hint\",\n                text: pick(payload.intro ?? undefined) || t(\"downloadsIntro\"),\n            }),\n            entries.length === 0\n                ? el(\"p\", { class: \"ss-hint\", text: t(\"downloadsEmpty\") })\n                : list,\n        ),\n    );\n}\n\nfunction item(entry: DownloadInfo): HTMLElement {\n    const kind =\n        entry.kind === \"instructions\"\n            ? t(\"kindInstructions\")\n            : entry.kind === \"sheet\"\n              ? t(\"kindSheet\")\n              : t(\"kindOther\");\n    const lang = entry.lang === \"both\" ? \"NL / EN\" : entry.lang.toUpperCase();\n    return el(\n        \"article\",\n        { class: \"study-download\" },\n        el(\n            \"div\",\n            { class: \"study-download__body\" },\n            el(\"strong\", {\n                class: \"study-download__title\",\n                text: pick(entry.title),\n            }),\n            entry.description\n                ? el(\"p\", { class: \"ss-hint\", text: pick(entry.description) })\n                : null,\n            el(\n                \"div\",\n                { class: \"study-download__meta\" },\n                el(\"span\", { class: \"ss-badge\", text: kind }),\n                el(\"span\", { class: \"ss-badge\", text: lang }),\n                el(\"span\", {\n                    text: `${extensionOf(entry.file)} · ${formatBytes(entry.sizeBytes, getLang())}`,\n                }),\n            ),\n        ),\n        el(\n            \"a\",\n            {\n                class: \"ss-btn ss-btn--primary\",\n                href: resolveUrl(entry.url),\n                download: entry.file,\n            },\n            t(\"download\"),\n        ),\n    );\n}\n\nfunction extensionOf(file: string): string {\n    return (file.split(\".\").pop() ?? \"\").toUpperCase();\n}\n","/** #/history — everything the group ever made: one card per run, newest\n * first, with the words that were sent, the settings, and every frame\n * that came back. The strip on the studio only shows the latest few;\n * this is the whole record. */\n\nimport { el, formatBytes } from \"@starling-study/study-base/lib/dom\";\n\nimport { api, type RunInfo } from \"../api\";\nimport { shell } from \"../components/chrome\";\nimport { formatDateTime, generationError, getLang, t } from \"../lib/i18n\";\nimport { go, href } from \"../lib/router\";\nimport { session } from \"../session\";\n\nexport async function renderHistory(root: HTMLElement): Promise<void> {\n    const membership = session.membership;\n    if (!membership) {\n        go(\"/\");\n        return;\n    }\n\n    const main = el(\"div\", { class: \"study-page\" });\n    root.replaceChildren(shell(main));\n\n    const runs = await api\n        .history(membership.code, membership.token)\n        .catch((): RunInfo[] | null => null);\n    if (!runs) {\n        main.append(\n            el(\"h1\", { class: \"ss-sr-only\", text: t(\"historyTitle\") }),\n            el(\"p\", { class: \"ss-hint\", text: t(\"errorGeneric\") }),\n        );\n        return;\n    }\n\n    const list = el(\"div\", { class: \"study-history\" });\n    for (const run of runs) list.append(runCard(run));\n\n    main.append(\n        el(\n            \"div\",\n            { class: \"ss-card ss-stack\" },\n            el(\"h1\", { class: \"ss-card__title\", text: t(\"historyTitle\") }),\n            el(\"p\", { class: \"ss-hint\", text: t(\"historyIntro\") }),\n            runs.length === 0\n                ? el(\"p\", { class: \"ss-hint\", text: t(\"historyEmpty\") })\n                : list,\n            el(\n                \"div\",\n                { class: \"ss-toolbar ss-toolbar--wrap\" },\n                el(\n                    \"a\",\n                    { class: \"ss-btn ss-btn--sm\", href: href(\"/studio\") },\n                    t(\"toStudio\"),\n                ),\n            ),\n        ),\n    );\n}\n\n/** A quality as the studio's picker names it. */\nfunction qualityLabel(quality: string): string {\n    if (quality === \"low\") return t(\"qualityLow\");\n    if (quality === \"high\") return t(\"qualityHigh\");\n    return quality === \"medium\" ? t(\"qualityMedium\") : \"\";\n}\n\n/** The facts of a run in the participant's words: no provider ids, no\n * raw setting values. */\nexport function runFacts(\n    run: Pick<RunInfo, \"createdAt\" | \"aspect\" | \"quality\" | \"count\" | \"seed\">,\n): string[] {\n    const quality = qualityLabel(run.quality);\n    return [\n        formatDateTime(run.createdAt),\n        run.aspect ? `${t(\"aspect\")} ${run.aspect}` : \"\",\n        quality ? `${t(\"quality\")}: ${quality.toLowerCase()}` : \"\",\n        t(run.count === 1 ? \"imageCount\" : \"imagesCount\").replace(\n            \"{n}\",\n            String(run.count),\n        ),\n        run.seed === null ? \"\" : `${t(\"seed\")} ${run.seed}`,\n    ].filter(Boolean);\n}\n\nfunction runCard(run: RunInfo): HTMLElement {\n    const facts = runFacts(run);\n\n    const outcome =\n        run.status === \"error\"\n            ? el(\"span\", {\n                  class: \"ss-badge ss-badge--warn\",\n                  title: generationError(run.error),\n                  text: t(\"historyFailed\"),\n              })\n            : run.status === \"done\"\n              ? null\n              : el(\"span\", {\n                    class: \"ss-badge\",\n                    text: run.status === \"queued\" ? t(\"queued\") : t(\"running\"),\n                });\n\n    const frames = el(\"div\", {\n        class: \"study-history__frames study-history__frames--lg\",\n    });\n    for (const image of run.images) {\n        frames.append(\n            el(\n                \"figure\",\n                { class: \"study-history__figure\" },\n                el(\n                    \"a\",\n                    { href: image.url, target: \"_blank\", rel: \"noopener\" },\n                    el(\"img\", {\n                        class: \"study-history__frame\",\n                        src: image.url,\n                        alt: image.prompt.slice(0, 120),\n                        loading: \"lazy\",\n                    }),\n                ),\n                el(\n                    \"figcaption\",\n                    { class: \"study-history__caption\" },\n                    el(\"span\", {\n                        text: formatBytes(image.sizeBytes, getLang()),\n                    }),\n                    el(\n                        \"a\",\n                        {\n                            class: \"ss-btn ss-btn--sm\",\n                            href: `${image.url}?download=1`,\n                        },\n                        t(\"download\"),\n                    ),\n                ),\n            ),\n        );\n    }\n\n    return el(\n        \"article\",\n        { class: \"study-history__run\" },\n        el(\n            \"header\",\n            { class: \"study-history__head\" },\n            el(\"span\", { class: \"ss-hint\", text: facts.join(\" · \") }),\n            run.kind === \"refine\"\n                ? el(\"span\", { class: \"ss-badge\", text: t(\"historyRefine\") })\n                : run.kind === \"vary\"\n                  ? el(\"span\", { class: \"ss-badge\", text: t(\"historyVary\") })\n                  : null,\n            outcome,\n        ),\n        el(\"p\", {\n            class: \"study-history__prompt study-history__prompt--full\",\n            text: run.prompt,\n        }),\n        run.change\n            ? el(\"p\", {\n                  class: \"ss-hint\",\n                  text: `${t(\"historyRefine\")}: ${run.change}`,\n              })\n            : null,\n        run.negativePrompt\n            ? el(\"p\", {\n                  class: \"ss-hint\",\n                  text: `${t(\"negativeShort\")}: ${run.negativePrompt}`,\n              })\n            : null,\n        run.images.length > 0\n            ? frames\n            : run.status === \"done\"\n              ? el(\"p\", { class: \"ss-hint\", text: t(\"historyNoFrames\") })\n              : null,\n    );\n}\n","/** #/studio — where the group actually works: the prompt and its controls on\n * the left, everything the group has made on the right.\n *\n * All state lives on the group (the board + its images), so the screen is a\n * pure function of the last poll: any member's phone, refreshed at any\n * moment, shows the same thing. Inputs are the one exception — they are\n * built once and only written to when they are not focused, so a poll can\n * never eat what someone is typing.\n */\n\nimport { connection } from \"@starling-study/study-base/lib/connection\";\nimport {\n    clear,\n    createNotifier,\n    el,\n    field,\n    formatBytes,\n    select,\n} from \"@starling-study/study-base/lib/dom\";\n\nimport {\n    type GenerationKind,\n    ApiError,\n    api,\n    type BoardState,\n    type Capabilities,\n    type GeneratingInfo,\n    type ImageInfo,\n} from \"../api\";\nimport { shell } from \"../components/chrome\";\nimport { setFlash } from \"../components/notice\";\nimport { apiErrorCode, codeText, errorText } from \"../lib/errors\";\nimport { generationError, getLang, t } from \"../lib/i18n\";\nimport { takeLaunchPrompt } from \"../lib/launch\";\nimport { go } from \"../lib/router\";\nimport { patchBoard, session } from \"../session\";\n\nconst POLL_IDLE_MS = 6000;\nconst POLL_BUSY_MS = 2500;\nconst SAVE_DEBOUNCE_MS = 700;\n\nexport async function renderStudio(root: HTMLElement): Promise<void> {\n    if (!session.membership) {\n        go(\"/\");\n        return;\n    }\n\n    const controls = el(\"section\", { class: \"study-studio__controls\" });\n    const results = el(\"section\", { class: \"study-studio__results\" });\n    const status = el(\"p\", { class: \"study-status\", role: \"status\" });\n    const notify = createNotifier(status);\n\n    root.replaceChildren(\n        shell(\n            el(\n                \"div\",\n                { class: \"study-studio study-studio--page\" },\n                el(\"h1\", { class: \"ss-sr-only\", text: t(\"studio\") }),\n                controls,\n                results,\n            ),\n        ),\n    );\n\n    const capabilities = await api.capabilities().catch((): Capabilities => ({\n        enabled: false,\n        paused: false,\n        defaultProvider: null,\n        imagesPerRun: 1,\n        providers: [],\n    }));\n\n    let refreshError: unknown = null;\n    const lost = await session.refreshGroup().then(\n        () => false,\n        (error: unknown) => {\n            refreshError = error;\n            return apiErrorCode(error) === \"group_not_found\";\n        },\n    );\n    // Another route replaced this screen while the refresh was out: that\n    // screen decides where the device goes, not this one.\n    const left = !results.isConnected;\n    if (left) return;\n    if (lost) {\n        // The group is gone (or in another workshop): back to the start, with why.\n        session.leaveToStart();\n        setFlash(codeText(\"group_not_found\"));\n        go(\"/\");\n        return;\n    }\n    if (!session.group) {\n        // Not loaded (no connection): say so; the next visit tries again.\n        controls.append(status);\n        status.textContent = errorText(refreshError);\n        status.classList.add(\"study-status--error\");\n        return;\n    }\n\n    // ---- the controls, built once -----------------------------------------\n\n    // The board of the last poll. A device that leaves the group while a\n    // timer still runs keeps the last one it saw instead of failing.\n    let lastBoard: BoardState = session.group.board;\n    const board = (): BoardState =>\n        (lastBoard = session.group?.board ?? lastBoard);\n\n    /** Saves after a pause, and never while the field is mid-word. */\n    function debounced<T>(save: (value: T) => void): (value: T) => void {\n        let timer: number | undefined;\n        return (value: T) => {\n            window.clearTimeout(timer);\n            timer = window.setTimeout(() => save(value), SAVE_DEBOUNCE_MS);\n        };\n    }\n\n    const prompt = el(\"textarea\", {\n        class: \"ss-textarea study-studio__prompt\",\n        rows: 4,\n        placeholder: t(\"promptPlaceholder\"),\n        maxlength: 2000,\n    }) as HTMLTextAreaElement;\n    prompt.value = board().prompt;\n    const savePrompt = debounced<string>(\n        (value) => void save({ prompt: value }),\n    );\n    prompt.addEventListener(\"input\", () => savePrompt(prompt.value));\n\n    // The model is the room's, chosen by the organiser: shown, not offered.\n    // Its aspect ratios and whether it has a quality knob shape the controls.\n    const roomProvider = capabilities.providers.find(\n        (entry) => entry.id === capabilities.defaultProvider,\n    );\n    const aspects = roomProvider?.aspects ?? [\"1:1\"];\n\n    // A board aspect that is no longer allowed falls back the way the server\n    // does when it generates: the room's default when allowed, else the first.\n    const fallbackAspect =\n        aspects.find((aspect) => aspect === capabilities.defaultAspect) ??\n        aspects[0] ??\n        \"1:1\";\n    const aspectPicker = select(\n        aspects.map((aspect) => [aspect, aspect] as [string, string]),\n        aspects.includes(board().aspect) ? board().aspect : fallbackAspect,\n    );\n    aspectPicker.addEventListener(\n        \"change\",\n        () => void save({ aspect: aspectPicker.value as never }),\n    );\n\n    const qualityPicker = select(\n        [\n            [\"low\", t(\"qualityLow\")],\n            [\"medium\", t(\"qualityMedium\")],\n            [\"high\", t(\"qualityHigh\")],\n        ],\n        board().quality,\n    );\n    qualityPicker.addEventListener(\n        \"change\",\n        () => void save({ quality: qualityPicker.value as never }),\n    );\n\n    const negative = el(\"input\", {\n        class: \"ss-input\",\n        type: \"text\",\n        maxlength: 1000,\n        placeholder: t(\"negativePlaceholder\"),\n    }) as HTMLInputElement;\n    negative.value = board().negativePrompt;\n    const saveNegative = debounced<string>(\n        (value) => void save({ negativePrompt: value }),\n    );\n    negative.addEventListener(\"input\", () => saveNegative(negative.value));\n\n    const seed = el(\"input\", {\n        class: \"ss-input\",\n        type: \"number\",\n        min: 0,\n        max: 4294967295,\n    }) as HTMLInputElement;\n    seed.value = board().seed === null ? \"\" : String(board().seed);\n    const saveSeed = debounced<string>(\n        (value) => void save({ seed: value === \"\" ? null : Number(value) }),\n    );\n    seed.addEventListener(\"input\", () => saveSeed(seed.value));\n\n    const generateButton = el(\n        \"button\",\n        {\n            class: \"ss-btn ss-btn--primary ss-btn--lg ss-btn--block\",\n            type: \"button\",\n        },\n        t(\"generate\"),\n    );\n    generateButton.addEventListener(\"click\", () => void start(\"initial\", \"\"));\n\n    // The guidance picture: a setting on the prompt. The file picker (a\n    // camera on a phone) sits behind a plain button; once there is a\n    // picture, the field shows it with a way to take it away again.\n    const uploadInput = el(\"input\", {\n        type: \"file\",\n        accept: \"image/png,image/jpeg,image/webp\",\n        hidden: true,\n    }) as HTMLInputElement;\n    const uploadButton = el(\n        \"button\",\n        { class: \"ss-btn ss-btn--sm\", type: \"button\" },\n        t(\"uploadImage\"),\n    );\n    uploadButton.addEventListener(\"click\", () => uploadInput.click());\n    const referenceHost = el(\"div\", { class: \"study-reference\" });\n    let renderedReference: string | null | undefined;\n\n    function renderReference(): void {\n        const reference = board().reference;\n        const key = reference?.publicId ?? null;\n        if (key === renderedReference) return;\n        renderedReference = key;\n        clear(referenceHost);\n        if (!reference) {\n            referenceHost.append(uploadInput, uploadButton);\n            return;\n        }\n        const remove = el(\n            \"button\",\n            { class: \"ss-btn ss-btn--sm\", type: \"button\" },\n            t(\"removeReference\"),\n        );\n        remove.addEventListener(\"click\", () => {\n            remove.disabled = true;\n            void save({ reference: null }).then(() => render(true));\n        });\n        referenceHost.append(\n            el(\"img\", {\n                class: \"study-reference__img\",\n                src: reference.url,\n                alt: t(\"uploaded\"),\n                loading: \"lazy\",\n            }),\n            el(\n                \"div\",\n                { class: \"study-reference__facts\" },\n                el(\"span\", {\n                    text: `${reference.aspect}${reference.width && reference.height ? ` · ${reference.width}×${reference.height}` : \"\"}`,\n                }),\n                el(\n                    \"div\",\n                    { class: \"ss-toolbar ss-toolbar--wrap\" },\n                    uploadInput,\n                    uploadButton,\n                    remove,\n                ),\n            ),\n        );\n    }\n    uploadInput.addEventListener(\"change\", () => {\n        const file = uploadInput.files?.[0];\n        uploadInput.value = \"\";\n        if (file) void upload(file);\n    });\n\n    async function upload(file: File): Promise<void> {\n        const membership = session.membership;\n        if (!membership) return;\n        uploadButton.disabled = true;\n        notify(t(\"uploading\"));\n        try {\n            await api.uploadImage(membership.code, membership.token, file);\n            await session.refreshGroup().catch(() => undefined);\n            notify(t(\"uploadDone\"));\n            render(true);\n        } catch (error) {\n            if (error instanceof ApiError && error.status === 413)\n                notify(t(\"uploadTooBig\"), \"error\");\n            else notify(errorText(error), \"error\");\n        } finally {\n            uploadButton.disabled = false;\n        }\n    }\n\n    const qualityField = field(t(\"quality\"), qualityPicker);\n    qualityField.hidden = !(roomProvider?.supportsQuality ?? false);\n    const negativeField = field(\n        t(\"negativePrompt\"),\n        negative,\n        t(\"negativePromptHint\"),\n    );\n    const settings = el(\n        \"details\",\n        { class: \"study-settings\" },\n        el(\"summary\", { text: t(\"settings\") }),\n        el(\n            \"div\",\n            { class: \"study-settings__body\" },\n            roomProvider\n                ? el(\"p\", {\n                      class: \"ss-hint\",\n                      text: `${t(\"provider\")}: ${roomProvider.label} · ${roomProvider.model}`,\n                  })\n                : null,\n            field(t(\"aspect\"), aspectPicker),\n            qualityField,\n            negativeField,\n            field(t(\"seed\"), seed, t(\"seedHint\")),\n        ),\n    );\n\n    controls.append(\n        el(\n            \"div\",\n            { class: \"ss-card ss-stack\" },\n            field(t(\"promptLabel\"), prompt, t(\"promptHint\")),\n            field(t(\"referenceLabel\"), referenceHost, t(\"referenceHint\")),\n            settings,\n            generateButton,\n            status,\n        ),\n    );\n    renderReference();\n\n    // A ratio the room's model does not render (picked before the organiser\n    // moved the room) is put back to the model's first — the server would\n    // clamp it the same way at the next run.\n    if (aspectPicker.value !== board().aspect)\n        void save({ aspect: aspectPicker.value as never });\n\n    // A lesson's instruction (`?prompt=`, kept since boot) becomes the\n    // board prompt, saved for the whole group, but only on an empty board:\n    // it never overwrites what the group wrote, and never generates.\n    const launchPrompt = takeLaunchPrompt();\n    if (launchPrompt && !board().prompt.trim()) {\n        prompt.value = launchPrompt;\n        // On this device's copy of the board too: the first render below runs\n        // before the save is back and would put the empty prompt in the field.\n        session.group.board = { ...board(), prompt: launchPrompt };\n        void save({ prompt: launchPrompt });\n    }\n\n    /** Another member's settings, applied to every picker nobody here is\n     * touching — the same rule as the text inputs. */\n    function syncControls(): void {\n        const current = board();\n        const idle = (node: HTMLElement): boolean =>\n            document.activeElement !== node;\n        const has = (picker: HTMLSelectElement, value: string): boolean =>\n            [...picker.options].some((option) => option.value === value);\n\n        if (\n            idle(aspectPicker) &&\n            current.aspect !== aspectPicker.value &&\n            has(aspectPicker, current.aspect)\n        ) {\n            aspectPicker.value = current.aspect;\n        }\n        if (\n            idle(qualityPicker) &&\n            current.quality !== qualityPicker.value &&\n            has(qualityPicker, current.quality)\n        ) {\n            qualityPicker.value = current.quality;\n        }\n        const seedValue = current.seed === null ? \"\" : String(current.seed);\n        if (idle(seed) && seed.value !== seedValue) seed.value = seedValue;\n    }\n\n    async function save(\n        patch: Parameters<typeof patchBoard>[0],\n    ): Promise<void> {\n        try {\n            await patchBoard(patch);\n        } catch (error) {\n            notify(errorText(error), \"error\");\n        }\n    }\n\n    // ---- generating --------------------------------------------------------\n\n    let busy = false;\n\n    async function start(\n        kind: GenerationKind,\n        changes: string,\n    ): Promise<void> {\n        if (busy) return;\n        const membership = session.membership;\n        if (!membership) return;\n        let started = false;\n        if (kind === \"initial\" && !prompt.value.trim()) {\n            notify(t(\"needPrompt\"), \"error\");\n            prompt.focus();\n            return;\n        }\n        busy = true;\n        generateButton.disabled = true;\n        // A new action: the last one's message (an error too) goes.\n        notify(\"\");\n        try {\n            // Flush anything the debounce is still holding, so the server\n            // generates from what is on screen rather than from a stale board.\n            await patchBoard({\n                prompt: prompt.value,\n                negativePrompt: negative.value,\n                seed: seed.value === \"\" ? null : Number(seed.value),\n            });\n            const { generation } = await api.generate(\n                membership.code,\n                membership.token,\n                { kind, changes },\n            );\n            watching = generation.id;\n            if (kind === \"refine\") refineChanges.value = \"\";\n            await session.refreshGroup().catch(() => undefined);\n            await reportFinished();\n            started = true;\n        } catch (error) {\n            // What was typed stays; the error stays until the next try.\n            notify(startError(error), \"error\");\n        } finally {\n            busy = false;\n            generateButton.disabled = false;\n            render(true);\n            schedulePoll();\n        }\n        // On a phone the results sit under the long form: show the run.\n        if (started) revealResults();\n    }\n\n    /** Scroll the results into view when they start below the fold. */\n    function revealResults(): void {\n        if (results.getBoundingClientRect().top > window.innerHeight * 0.6) {\n            results.scrollIntoView({ block: \"start\", behavior: \"smooth\" });\n        }\n    }\n\n    /** The server's refusals, in the participant's language where we know\n     * the reason; its own sentence otherwise. */\n    function startError(error: unknown): string {\n        if (!(error instanceof ApiError)) return t(\"errorGeneric\");\n        if (apiErrorCode(error)) return error.detail;\n        if (error.status === 409) return t(\"errorBusy\");\n        if (error.status === 429)\n            return /druk|busy/i.test(error.detail)\n                ? t(\"errorRoomBusy\")\n                : t(\"errorLimit\");\n        return errorText(error);\n    }\n\n    /** The run this screen is waiting on — one it started, or one another\n     * member started that a poll saw. When the group stops generating, its\n     * outcome is fetched once: a run that failed fast (before any poll saw it\n     * running) must still explain itself. */\n    let watching: number | null = null;\n\n    async function reportFinished(): Promise<void> {\n        const group = session.group;\n        if (!group) return;\n        if (group.generating) {\n            watching = group.generating.id;\n            return;\n        }\n        if (watching === null) return;\n        const membership = session.membership;\n        const id = watching;\n        watching = null;\n        if (!membership) return;\n        const latest = await api\n            .generation(membership.code, membership.token)\n            .then((payload) => payload.generation)\n            .catch(() => null);\n        if (latest?.id === id && latest.status === \"error\")\n            notify(generationError(latest.error), \"error\");\n    }\n\n    // ---- the results pane, rebuilt from the group ---------------------------\n\n    /** What the results pane was last built from. Rebuilding it throws away\n     * whatever has focus, so a poll that changed nothing leaves it alone. */\n    let renderedFrom = \"\";\n\n    function render(force = false): void {\n        const group = session.group;\n        if (!group) return;\n        syncControls();\n\n        // Inputs are only written to when they are not focused — a poll must\n        // never overwrite what someone is typing.\n        if (\n            document.activeElement !== prompt &&\n            prompt.value !== group.board.prompt\n        ) {\n            prompt.value = group.board.prompt;\n        }\n        if (\n            document.activeElement !== negative &&\n            negative.value !== group.board.negativePrompt\n        ) {\n            negative.value = group.board.negativePrompt;\n        }\n        renderReference();\n        generateButton.textContent =\n            group.images.length > 0 ? t(\"generateAgain\") : t(\"generate\");\n        generateButton.disabled =\n            busy || group.generating !== null || !capabilities.enabled;\n\n        const signature = JSON.stringify([\n            // The place in the queue too: \"position 3\" must count down.\n            group.generating && [\n                group.generating.id,\n                group.generating.status,\n                group.generating.queuePosition,\n            ],\n            group.board.selected,\n            group.images.map((image) => image.publicId),\n        ]);\n        if (!force && signature === renderedFrom) return;\n        renderedFrom = signature;\n        clear(results);\n\n        if (group.generating) {\n            results.append(runningCard(group.generating));\n            return;\n        }\n\n        if (group.images.length === 0) {\n            results.append(\n                el(\n                    \"div\",\n                    { class: \"study-empty\" },\n                    el(\"h2\", {\n                        class: \"study-empty__title\",\n                        text: t(\"emptyStudio\"),\n                    }),\n                    el(\"p\", {\n                        class: \"study-empty__text\",\n                        text: t(\"emptyStudioHint\"),\n                    }),\n                ),\n            );\n            return;\n        }\n\n        // How picking works, until a frame is picked.\n        if (\n            !group.images.some(\n                (image) => image.publicId === group.board.selected,\n            )\n        ) {\n            results.append(\n                el(\"p\", { class: \"ss-hint\", text: t(\"chooseHint\") }),\n            );\n        }\n        results.append(imageGrid(group.images, group.board.selected));\n\n        const selected =\n            group.images.find(\n                (image) => image.publicId === group.board.selected,\n            ) ?? null;\n        if (selected) {\n            results.append(refineCard());\n        }\n    }\n\n    /** \"Queued, position 3\" only when others are ahead; else the plain state. */\n    function runTitle(run: GeneratingInfo): string {\n        if (run.status !== \"queued\") return t(\"running\");\n        return run.queuePosition && run.queuePosition > 1\n            ? `${t(\"queuedAt\")} ${run.queuePosition}`\n            : t(\"queued\");\n    }\n\n    function runningCard(run: GeneratingInfo): HTMLElement {\n        const count = run.count;\n        // Counted from the run's own start, not from when this card was built\n        // — the card is rebuilt, and a refreshed phone should not restart at 0.\n        const started =\n            Date.parse(run.startedAt ?? run.createdAt) || Date.now();\n        const elapsed = el(\"span\", { class: \"study-running__elapsed\" });\n        const tick = (): void => {\n            const seconds = Math.max(\n                0,\n                Math.floor((Date.now() - started) / 1000),\n            );\n            elapsed.textContent = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, \"0\")}`;\n        };\n        tick();\n        const timer = window.setInterval(() => {\n            if (!elapsed.isConnected) window.clearInterval(timer);\n            else tick();\n        }, 1000);\n\n        return el(\n            \"div\",\n            { class: \"ss-card ss-stack\" },\n            el(\"div\", {\n                class: \"study-running__spinner study-running__spinner--lg\",\n                \"aria-hidden\": \"true\",\n            }),\n            el(\"h2\", { class: \"ss-card__title\", text: runTitle(run) }),\n            el(\"p\", { class: \"ss-hint\", text: t(\"runningHint\") }),\n            el(\n                \"p\",\n                { class: \"study-running__meta\" },\n                elapsed,\n                el(\"span\", {\n                    text: ` · ${t(count === 1 ? \"imageCount\" : \"imagesCount\").replace(\"{n}\", String(count))}`,\n                }),\n            ),\n            // Placeholders in the aspect the group asked for, so the layout does\n            // not jump when the frames land.\n            el(\n                \"div\",\n                { class: \"study-image-grid study-image-grid--lg\" },\n                ...Array.from({ length: count }, () =>\n                    el(\"div\", {\n                        class: \"study-frame study-frame--natural study-frame--placeholder study-frame--running\",\n                        style: aspectStyle(board().aspect),\n                    }),\n                ),\n            ),\n        );\n    }\n\n    function imageGrid(\n        images: ImageInfo[],\n        selectedId: string | null,\n    ): HTMLElement {\n        const grid = el(\"div\", {\n            class: \"study-image-grid study-image-grid--lg\",\n        });\n        for (const image of images) {\n            const isSelected = image.publicId === selectedId;\n            // No aspect-ratio on the figure: it has a caption and a row of\n            // buttons under the picture, and a fixed ratio on the box they live\n            // in clips them away. The image sizes itself.\n            const figure = el(\n                \"figure\",\n                {\n                    class: `study-frame study-frame--natural${isSelected ? \" study-frame--selected\" : \"\"}`,\n                },\n                el(\"img\", {\n                    class: \"study-frame__img\",\n                    src: image.url,\n                    alt: image.prompt.slice(0, 120),\n                    loading: \"lazy\",\n                }),\n                el(\n                    \"figcaption\",\n                    { class: \"study-frame__meta\" },\n                    el(\"span\", {\n                        text: formatBytes(image.sizeBytes, getLang()),\n                    }),\n                ),\n                promptLine(image),\n            );\n\n            const choose = el(\"button\", {\n                class: \"study-frame__choose\",\n                type: \"button\",\n                \"aria-label\": isSelected ? t(\"chosen\") : t(\"choose\"),\n                title: isSelected ? t(\"chosen\") : t(\"choose\"),\n                \"aria-pressed\": isSelected ? \"true\" : \"false\",\n            });\n            choose.addEventListener(\"click\", () => {\n                void save({ selected: image.publicId }).then(() =>\n                    render(true),\n                );\n            });\n            figure.prepend(choose);\n\n            figure.append(\n                el(\n                    \"div\",\n                    { class: \"study-frame__actions\" },\n                    el(\n                        \"a\",\n                        {\n                            class: \"ss-btn ss-btn--sm\",\n                            href: image.url,\n                            target: \"_blank\",\n                            rel: \"noopener\",\n                        },\n                        t(\"openFull\"),\n                    ),\n                    el(\n                        \"a\",\n                        {\n                            class: \"ss-btn ss-btn--sm\",\n                            href: `${image.url}?download=1`,\n                        },\n                        t(\"download\"),\n                    ),\n                    deleteButton(image),\n                ),\n            );\n            grid.append(figure);\n        }\n        return grid;\n    }\n\n    /** The prompt this frame was made from — as sent, refinement included —\n     * and the settings it was made with. Three lines by default; a tap shows\n     * the whole thing. */\n    function promptLine(image: ImageInfo): HTMLElement {\n        const size =\n            image.width && image.height\n                ? ` · ${image.width}×${image.height}`\n                : \"\";\n        const facts = [\n            `${t(\"aspect\")}: ${image.aspect}${size}`,\n            image.quality\n                ? `${t(\"quality\")}: ${qualityLabel(image.quality)}`\n                : \"\",\n            `${t(\"seed\")}: ${image.seed === null ? t(\"seedRandom\") : String(image.seed)}`,\n        ].filter(Boolean);\n        const line = el(\n            \"div\",\n            { class: \"study-frame__prompt\", title: t(\"framePromptHint\") },\n            el(\"p\", { class: \"study-frame__text\", text: image.prompt }),\n            image.change\n                ? el(\"p\", {\n                      class: \"study-frame__negative\",\n                      text: `${t(\"historyRefine\")}: ${image.change}`,\n                  })\n                : null,\n            image.negativePrompt\n                ? el(\"p\", {\n                      class: \"study-frame__negative\",\n                      text: `${t(\"negativePrompt\")}: ${image.negativePrompt}`,\n                  })\n                : null,\n            el(\"p\", { class: \"study-frame__facts\", text: facts.join(\" · \") }),\n        );\n        line.addEventListener(\"click\", () => line.classList.toggle(\"is-open\"));\n        return line;\n    }\n\n    function qualityLabel(quality: string): string {\n        return quality === \"low\"\n            ? t(\"qualityLow\")\n            : quality === \"high\"\n              ? t(\"qualityHigh\")\n              : t(\"qualityMedium\");\n    }\n\n    function deleteButton(image: ImageInfo): HTMLElement {\n        // Quiet next to Download: a ghost button, with a confirm.\n        const button = el(\n            \"button\",\n            { class: \"ss-btn ss-btn--sm ss-btn--ghost\", type: \"button\" },\n            t(\"deleteImage\"),\n        );\n        button.addEventListener(\"click\", () => {\n            if (!window.confirm(t(\"deleteConfirm\"))) return;\n            const membership = session.membership;\n            if (!membership) return;\n            void api\n                .deleteImage(membership.code, membership.token, image.publicId)\n                .then(() => session.refreshGroup())\n                .then(() => render(true))\n                .catch((error: unknown) => notify(errorText(error), \"error\"));\n        });\n        return button;\n    }\n\n    // Built once: the results pane is rebuilt when the group changes, and a\n    // fresh textarea each time would throw away what someone is typing.\n    const refineChanges = el(\"textarea\", {\n        class: \"ss-textarea\",\n        rows: 2,\n        placeholder: t(\"refinePlaceholder\"),\n        maxlength: 2000,\n    }) as HTMLTextAreaElement;\n\n    function refineCard(): HTMLElement {\n        const changes = refineChanges;\n        const button = el(\n            \"button\",\n            { class: \"ss-btn ss-btn--primary\", type: \"button\" },\n            t(\"refineButton\"),\n        );\n        button.addEventListener(\"click\", () => {\n            if (!changes.value.trim()) {\n                notify(t(\"refineLabel\"), \"error\");\n                changes.focus();\n                return;\n            }\n            void start(\"refine\", changes.value);\n        });\n        // \"More like this\": the picked frame again with a new seed, nothing\n        // typed. What is in the change box stays there for a later refine.\n        const vary = el(\n            \"button\",\n            { class: \"ss-btn\", type: \"button\" },\n            t(\"varyButton\"),\n        );\n        vary.addEventListener(\"click\", () => void start(\"vary\", \"\"));\n        return el(\n            \"div\",\n            { class: \"ss-card ss-stack\" },\n            el(\"h2\", { class: \"ss-card__title\", text: t(\"refine\") }),\n            field(t(\"refineLabel\"), changes, t(\"refineHint\")),\n            el(\"div\", { class: \"ss-toolbar ss-toolbar--wrap\" }, button, vary),\n            el(\"p\", { class: \"ss-hint\", text: t(\"varyHint\") }),\n        );\n    }\n\n    // ---- polling ------------------------------------------------------------\n    //\n    // Idle, the group refresh every few seconds is enough. While something is\n    // generating, poll faster — and ask the generation endpoint too, because\n    // that is the only place a failed run explains itself. While the server\n    // cannot be reached (a restart; the banner says so) the growing pause of\n    // lib/connection, and at once when it answers again. One request and\n    // one timer at a time.\n\n    let pollTimer: number | undefined;\n    let polling = false;\n\n    function schedulePoll(): void {\n        window.clearTimeout(pollTimer);\n        pollTimer = undefined;\n        // Another route replaced this screen: stop polling.\n        if (!results.isConnected) {\n            offRestored();\n            return;\n        }\n        const busyNow = Boolean(session.group?.generating);\n        pollTimer = window.setTimeout(\n            poll,\n            connection.down\n                ? connection.retryDelay()\n                : busyNow\n                  ? POLL_BUSY_MS\n                  : POLL_IDLE_MS,\n        );\n    }\n\n    async function poll(): Promise<void> {\n        const membership = session.membership;\n        if (!membership || !results.isConnected || polling) return;\n        polling = true;\n        try {\n            await session.refreshGroup().catch(() => undefined);\n            await reportFinished();\n        } finally {\n            polling = false;\n        }\n        render();\n        schedulePoll();\n    }\n\n    const offRestored = connection.onRestored(() => {\n        if (!results.isConnected) offRestored();\n        else if (pollTimer !== undefined) {\n            window.clearTimeout(pollTimer);\n            pollTimer = undefined;\n            void poll();\n        }\n    });\n\n    if (session.group.generating) watching = session.group.generating.id;\n    render();\n    schedulePoll();\n}\n\n/** The shape of a frame that is still being drawn, so the grid does not\n * jump when the real ones arrive. */\nfunction aspectStyle(aspect: string): string {\n    const [w, h] = aspect.split(\":\");\n    return `aspect-ratio: ${Number(w) || 1} / ${Number(h) || 1}`;\n}\n","/** Study Imagine — the app bundle.\n *\n * Mounted on study-base's SPA shell (`<div id=\"study-app\" data-app\n * data-api-base data-lang data-workshop>`), hash-routed:\n *\n *   #/studio      prompt, frames, pick and refine (also `#/`, an old\n *                 `#/group` and anything unknown)\n *   #/history     everything the group made (Geschiedenis)\n *   #/downloads   the instruction sheets and worksheets\n *\n * The way in is study-base's (lib/entry, wired in lib/route): the workshop\n * password and the group are the workshop's groups page's, not this app's.\n * A device without them goes there (`/<lang>/workshops/<slug>/groups/?next=…`)\n * and comes back with them; a `?join=` link (also inside a lesson) enters\n * that team's group at once. `#/` and an unknown route are the studio.\n * The group itself is the workshop's group page (the app bar's chip), and\n * a device out of its group asks where it went (`followOrLeave`: a move by\n * staff reloads this page in the new group). The downloads need the\n * password only. A workshop that has ended or does not exist replaces\n * the whole screen with a calm panel. Inside a lesson (`?embed=1`) there is\n * no app bar and the lesson's theme is this page's (lib/embed). The\n * organiser's side is not in this bundle: it is the dashboard at\n * /<lang>/portal/imagine/. A server that cannot be reached (a restart)\n * puts a notice under the bar until it answers again\n * (components/connection); a server away at page load is waited for, and\n * the page says so.\n */\n\nimport { el } from \"@starling-study/study-base/lib/dom\";\nimport {\n    applyEmbedTheme,\n    followLessonTheme,\n} from \"@starling-study/study-base/lib/embed\";\nimport {\n    followOrLeave,\n    requireAccess,\n    requireGroup,\n} from \"@starling-study/study-base/lib/entry\";\nimport { searchWithWorkshop } from \"@starling-study/study-base/lib/workshops\";\n\nimport { mountChrome } from \"./components/chrome\";\nimport { mountConnectionBanner, showEntryWait } from \"./components/connection\";\nimport { closedPanel, unknownWorkshopPanel } from \"./components/notice\";\nimport { config } from \"./lib/config\";\nimport { onApiCode } from \"./lib/errors\";\nimport { stashLaunchPrompt } from \"./lib/launch\";\nimport { dropPlaceholderName, joinName } from \"./lib/members\";\nimport { createRoute } from \"./lib/route\";\nimport { currentPath, setNavigator } from \"./lib/router\";\nimport { isReloading, session } from \"./session\";\nimport { renderDownloads } from \"./views/downloads\";\nimport { renderHistory } from \"./views/history\";\nimport { renderStudio } from \"./views/studio\";\n\n// A lesson's `?prompt=` (or `?task=`) waits in sessionStorage until the\n// studio uses it.\nstashLaunchPrompt();\n\n// A page opened without `?workshop=` that talks to the active group's\n// workshop (lib/workshops) says so in its address: a reload and the\n// language switch keep it.\nif (config.workshop && !new URLSearchParams(location.search).has(\"workshop\")) {\n    history.replaceState(\n        history.state,\n        \"\",\n        `${location.pathname}${searchWithWorkshop(location.search, config.workshop)}${location.hash}`,\n    );\n}\n\n// The chrome (the bar, or inside a lesson the app's own links) on the\n// shell's `#study-app`, the screens in a column of their own under it: a\n// screen replaces only what is its own.\nconst root = el(\"div\", { class: \"study-app\" });\nconfig.root.replaceChildren(root);\nmountChrome(config.root);\n// While the server cannot be reached (a restart): a notice under the bar.\nmountConnectionBanner(config.root);\nif (config.embedded) {\n    applyEmbedTheme();\n    followLessonTheme();\n}\n\n/** Set once the workshop turned out to be over or unknown: nothing else renders. */\nlet stopped = false;\n\nonApiCode((code) => {\n    if (\n        stopped ||\n        (code !== \"workshop_closed\" && code !== \"workshop_not_found\")\n    )\n        return;\n    stopped = true;\n    root.replaceChildren(\n        code === \"workshop_closed\" ? closedPanel() : unknownWorkshopPanel(),\n    );\n});\n\nconst route = createRoute({\n    halted: () => stopped || isReloading(),\n    hasMembership: () => Boolean(session.membership),\n    requireAccess: () => requireAccess(),\n    // A device joins under the name the apps on this origin share, else\n    // under the placeholder, which leaves the shared name again\n    // (lib/members); the group page asks for a first name.\n    // A server away at page load (a restart) is asked again with a growing\n    // pause; the page says it is waiting meanwhile.\n    requireGroup: () =>\n        requireGroup({\n            session,\n            joinName: () => joinName(session),\n            onWait: () => showEntryWait(root),\n        }),\n    afterEntry: () => dropPlaceholderName(session),\n    leaveForGroups: () => void followOrLeave(),\n    showHomeAddress: () =>\n        history.replaceState(\n            history.state,\n            \"\",\n            `${location.pathname}${location.search}#/studio`,\n        ),\n    render: (view) => {\n        if (view === \"downloads\") return renderDownloads(root);\n        if (view === \"history\") return renderHistory(root);\n        return renderStudio(root);\n    },\n});\n\nsetNavigator(() => void route(currentPath()));\nwindow.addEventListener(\"hashchange\", () => void route(currentPath()));\nvoid route(currentPath());\n"],"ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,18,20,22,23,24],"mappings":"AAKA,SAAgBA,EAAG,EAAK,EAAQ,CAAC,EAAG,GAAGwB,EAAU,CAC7C,IAAMC,EAAO,SAAS,cAAcC,CAAG,EACvC,IAAK,GAAM,CAACC,EAAKC,KAAU,OAAO,QAAQC,CAAK,EACvCD,IAAU,IAAA,IAAaA,IAAU,KAEjCD,IAAQ,QACR,EAAK,UAAY,OAAOC,CAAK,EACxBD,IAAQ,OACb,EAAK,YAAc,OAAOC,CAAK,EAC1BA,IAAU,GACfH,EAAK,aAAaE,EAAK,EAAE,EAEzBF,EAAK,aAAaE,EAAK,OAAOC,CAAK,CAAC,GAE5C,IAAK,IAAME,KAASN,EACZM,GAAU,MAA+BA,IAAU,IAEvDL,EAAK,OAAO,OAAOK,GAAU,SAAW,SAAS,eAAeA,CAAK,EAAIA,CAAK,EAElF,OAAOL,CACX,CACA,SAAgBM,EAAM,EAAM,CACxBN,EAAK,gBAAgB,CACzB,CAOA,SAAgBO,EAAe,EAAM,CACjC,IAAIC,EACJ,OAAQ,EAAS,EAAO,SAAW,CAC/B,EAAK,YAAcC,EACnBT,EAAK,UAAU,OA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