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AgB,QAAQ,MAAQA,EAC7C,CAAC,EAKLgc,EAAM,UAAU,IAAI,cAAc,EAClClc,GAAiB,EAIjBsL,GAAsB4Q,EAAM,eAAiB,SAAS,IAAI,EAGtDpZ,GACA,SAAS,gBAAgB,MAAM,YAC3B,qBACA,KACJ,EAEJ,OAAO,iBAAiBpF,GAAkB,GAAU,CAChD,IAAM1R,EAAQqY,EAAiC,QAC3CrY,IAAS,mBAAqBA,IAAS,wBAEvCwR,GAAuB+kB,GAAoBv2B,CAAI,EAC9Cs2B,GAAoBpG,EAAOlwB,CAAI,EACxC,CAAC,EAGDwgB,GAAa,EAIb,IAAImW,EAAWlc,GAASH,GAAa,CAAC,EAEtC,OAAO,iBAAiB,iBAAoB,CACnCE,GAAY,SAAS,IAAI,GAC1BC,GAASH,GAAa,CAAC,IAAMqc,GAAU,SAAS,OAAO,CAC/D,CAAC,EAODH,GAH6BtG,MAAa,CACtC,EAAWzV,GAASH,GAAa,CAAC,CACtC,CACK,EAAMA,GAAa,CAAC,CAC7B,C","names":["ApiError","detail","_defineProperty","status","code","HEADER_PASSWORD","HEADER_ADMIN","HEADER_TOKEN","WorkshopClient","extra","options","_classPrivateFieldSet2","_extraHeaders","_passwordKey","_adminKey","_storage$1","_fetch","input","init","_assertClassBrand","_WorkshopClient_brand","_importLegacyPassword","path","_classPrivateFieldGet2","password","probePath","error","isPasswordError","isAdminPasswordError","headers","body","admin","response","data","text","record","firstFieldError","legacyKey","old","value","EMPTY","IdentityStore","_classPrivateFieldInitSpec","_memory","_key","_app","_storage","_IdentityStore_brand","_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","key","parsed","legacy","imported","own","_appOf","a","b","GroupsApi","client","_GroupsApi_brand","_group","patch","registrationBody","attendee","query","lang","participantId","isRegistrationError","normaliseCode","WorkshopSession","_pollTimer","_groupLabel","group","handler","fn","settings","asked","f","kept","fields","clean","creatorName","_WorkshopSession_brand","_registrationToSend","result","_attendeeToSend","_forgetRefused","_adopt","existing","elsewhere","_join","mine","active","stale","intervalMs","participant","joinCodeFromLocation","search","loc","direct","params","__classPrivateFieldGet","kind","state","receiver","__classPrivateFieldSet","_Connection_failures","OUTAGE_CODE","RETRY_MIN_MS","RETRY_MAX_MS","FRONT_STATUSES","isFrontStatus","retryDelay","failures","min","max","Connection","__classPrivateFieldSet$1","connection","isOutage","jsonOf","fromFront","type","v","outageResponse","isGet","watchConnection","line","timeoutMs","timer","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","FOLLOW_TEXTS","followTexts","sessionStore","setGroupNotice","teamToken","followMember","found","texts","notices","setGroupsFlashText","team","BASE_API","ACCESS_PROBE","ONLY_PASSWORD","serverAway","sleep","resolve","ms","shellDataset","readEntryConfig","fromPath","derived","safeNext","target","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","staffFromDataset","csrfFromDataset","SAFE_METHODS","csrfHeader","method","withCsrf","ERROR_TEXT","CODES","DETAILS","classify","named","codeOfText","errorCode","IDEMPOTENT","ATOMIC_POST","requestMethod","requestPath","retriesWhenBusy","BUSY_WAIT_MS","BUSY_WAIT_MAX_MS","retryAfter","seconds","readJson","withApiErrors","clientFetch","pickText","LANG_KEY","pageLang","asLang","short","setDefaultLang","getLang","stored","pick","countWords","trimmed","STRINGS","t","WORKSHOPS_KEY","localStore","load","save","map","workshopOf","rememberWorkshop","forgetWorkshop","joinCodeOf","resolveWorkshopSource","fromShell","shell","joining","activeCode","searchWithoutStoredWorkshop","searchWithWorkshop","mountData","API_BASE","WORKSHOP","WORKSHOP_FROM_STORAGE","ACCESS","API_ERROR_EVENT","errorText","errorMessage","args","rawUrl","publicId","api","id","on","SWITCH_KEY","storageOrNull","followedKeys","keys","rememberKey","known","switchTarget","answer","pollSwitch","fetcher","startSwitchPoll","THEME_KEY","IDENTITY_KEY","TEXT","LANGUAGE_NAMES","ICON_LANGUAGE","ICON_MENU","ICON_APPS","ICON_THEME","counter","languageName","el","node","tag","className","attrs","currentTheme","explicit","toggleTheme","applyStoredTheme","urlTheme","theme","location","isEmbedded","keepEmbed","href","hash","parentRoot","applyParentTheme","applyStoredTheme$1","languageUrl","parts","langs","activeTeamCode","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","label","links","nav","actions","tools","menu","here","summary","panel","home","heading","codeLabel","meta","event","toggle","noticeLine","said","close","onKey","onOutside","syncTheme","onStorage","onMessage","observer","root","changes","langFromSearch","dataLang","themeFromMessage","themeFromSearch","LESSON_THEME_KEY","rememberLessonTheme","lessonTheme","fromSearch","from","publicGallery","galleryIsPublic","setGalleryPublic","publicGalleryOf","closedWithoutGallery","parseHash","pathPart","queryPart","segments","head","param","currentRoute","navigate","isRouteHash","routeKey","searchWithout","names","pathNamesWorkshop","withWorkshop","carryWorkshop","qrUrl","groups","createLaunchPrompt","promptFromSearch","stashLaunchPrompt","prompt","replace","takeLaunchPrompt","pendingLaunchPrompt","clearLaunchPrompt","lessonBanner","instruction","banner","doc","labels","dismiss","identityKey","createAppSession","forgetGroup","patchPage","children","child","clear","createNotifier","message","formatBytes","bytes","number","digits","SVG_NS","icon","svg","shapes","messageScreen","action","STEPS","introSteps","steps","generate","introContent","video","player","videoUrl","step","videos","urls","dialog","openIntroDialog","closeButton","lesson","INTRO_HREF","isDark","themeListener","themeObserver","watchTheme","listener","portalHref","currentBar","unsubscribe","createHeader","onThemeChange","inGroup","showGroup","showIntro","introOnClick","navLinks","anchor","toolbar","bar","shellMain","BACK_FLASH_MS","mountConnectionBanner","appConnection","spinner","backTimer","clearBack","show","offChange","onNetwork","setFlash","PLACEHOLDER_NAMES","hasOwnName","joinName","removedFromGroup","p","dropPlaceholderName","appSession","session$1","outOfGroup","watchRemoval","loadGroup","session$3","enterGroup","enter","viewOf","createRoute","entered","deps","view","gallery","EDIT_SANDBOX","DEBOUNCE_MS","createPreview","iframe","sandbox","extraCredits","credits","starLabel","star","count","startPoll","setTimer","clearTimer","stopped","inFlight","schedule","pause","round","now","offRestored","newTileLoad","beginTileLoad","releaseTileLoad","settleTileLoad","ok","REFRESH_MS","LOAD_MARGIN","KEEP_MARGIN","renderGallery","highlightId","highlightOwn","highlightAny","scrolled","grid","empty","refreshButton","tiles","loader","records","tile","html","releaser","buildStar","button","paint","refresh","buildTile","frame","card","entries","seen","highlighted","poll","renderViewer","info","rawLink","showVersion","versions","index","version","byline","optionalKeys","template","q","isEmptyAnswer","defaultFor","previous","saved","question","optionLabel","option","wordCounter","update","words","getValue","enough","renderHelp","lines","l","list","bullet","numbered","createPromptForm","answers","setters","form","initial","control","textarea","onChange","select","selected","help","example","field","recheck","mark","setter","formatHtml","__vitePreload","__toESM","html_beautify","readFileAsText","reader","reject","file","copyToClipboard","downloadHtml","stamp","blob","STARTER_TEXT","starterHtml","documentFromPartial","start","end","renderablePartial","out","elapsedSeconds","since","startFailureKey","generationErrorKey","trackedGenerationGone","latest","tracked","UNSAFE_KEYS","lookup","source","part","interpolate","missing","values","optional","mergeRemoteAnswers","local","remote","pending","remoteHtmlToTake","remoteHtml","remoteStep","starter","isoMicros","match","micros","isOlderPage","candidate","newest","toText","diffAnswers","diffs","before","after","to","formatDiff","d","buildRevisionPrompt","slots","utf8ByteLength","paneSwitch","buttons","panes","pane","i","statusLine","element","DEVICES","NARROW","AUTOSAVE_MS","POLL_MS","GEN_POLL_MS","VIBE_URL","hashStep","renderWork","generateEnabled","notify","saveError","setSaveError","savedNote","page","currentHtml","currentAnswers","baseAnswers","revisionMode","editor","formHandle","dirty","focused","pendingKeys","reportedTemplateId","tabs","stepTab","generationBusy","gen","reachable","updateTabs","order","tab","saveTimer","queued","scheduleSave","doSave","lastSave","sentKeys","updated","flushSave","saveNow","genView","lastRequest","trackedId","trackedMine","genTimer","setGen","genErrorMessage","track","genPoll","untrack","startGeneration","tokenFor","generation","applyGeneration","currentStep","other","r","partial","g","finishGeneration","pollTimer","running","formRefresh","take","previewSetQuiet","previewRefresh","dock","autosaveNote","footer","narrow","syncNarrow","stepNode","stepSwitch","showing","mount","ticket","built","buildFormStep","changed","switched","templateId","isFocused","handle","buildPreviewStep","buildSubmitStep","dark","summaries","formPane","promptPane","workbench","switcher","output","missingNote","copyButton","vibeLink","downloadButton","nextButton","generateButton","progress","ready","busy","ticker","syncButton","elapsed","position","tick","sentPrompt","storedTemplateId","s","picker","formHost","showFullForm","changesError","changesField","changesInput","editAllToggle","setFullForm","labelsOf","tpl","focusField","showMissing","shownPrompt","mountForm","diffText","copiedTimer","copied","preview","stage","fullscreenButton","fullscreen","FS_STATE","closeFullscreen","onPop","openFullscreen","fromHistory","editorHost","pasteHint","editButton","hasCurrent","quiet","accept","createEditor","setCodeQuiet","fileInput","deviceButtons","device","setDevice","devices","versionsButton","versionsList","versionsPanel","showVersions","toggleVersions","revisions","row","revision","openFile","changeButton","looksGoodButton","retryButton","progressBar","lastRendered","editorPane","previewPane","savedCredits","defaultCredits","ideaName","tagline","description","publishButton","backButton","published","cause","takenOver","renderWorkshopPanel","leaveStoredWorkshop","createAppRoute","onHomeAddress","mountApp","rendered"],"ignoreList":[0,1,2,3,4,5,6,7,8,10,14,15,19,20,21,23],"sources":["../../../../../../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/access.js","../../../../../ts/lib/errors.ts","../../../../../../node_modules/@starling-study/study-base/dist/lib/i18n.js","../../../../../ts/lib/i18n.ts","../../../../../ts/lib/workshop.ts","../../../../../ts/api.ts","../../../../../../node_modules/@starling-study/study-base/dist/appbar/switch.js","../../../../../../node_modules/@starling-study/study-base/dist/appbar/appbar.js","../../../../../ts/lib/embed.ts","../../../../../ts/lib/gallery.ts","../../../../../ts/lib/router.ts","../../../../../../node_modules/@starling-study/study-base/dist/lib/launch.js","../../../../../../node_modules/@starling-study/study-base/dist/lib/workshops.js","../../../../../../node_modules/@starling-study/study-base/dist/lib/session.js","../../../../../ts/session.ts","../../../../../../node_modules/@starling-study/study-base/dist/lib/dom.js","../../../../../ts/lib/dom.ts","../../../../../ts/components/intro.ts","../../../../../ts/components/chrome.ts","../../../../../ts/components/connection.ts","../../../../../ts/lib/flash.ts","../../../../../ts/lib/participants.ts","../../../../../ts/components/members.ts","../../../../../ts/lib/enter.ts","../../../../../ts/lib/launch.ts","../../../../../ts/lib/route.ts","../../../../../ts/components/preview.ts","../../../../../ts/lib/credits.ts","../../../../../ts/lib/favourite.ts","../../../../../ts/lib/poll.ts","../../../../../ts/lib/tileload.ts","../../../../../ts/views/gallery.ts","../../../../../ts/views/viewer.ts","../../../../../ts/components/promptForm.ts","../../../../../ts/lib/actions.ts","../../../../../ts/lib/generation.ts","../../../../../ts/lib/interpolate.ts","../../../../../ts/lib/pagemerge.ts","../../../../../ts/lib/revision.ts","../../../../../ts/views/work.ts","../../../../../ts/index.ts"],"sourcesContent":["/** 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","/** 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 a refused API call means, in the page's language.\n *\n * The suite's servers name the reason of a refusal in `code` (sturnus-\n * workshop: `workshop_closed`, `busy`, `not_allowed`, …) or, for cocoder's\n * own refusals, in `error` (`form_incomplete`, `already_running`, …). The\n * shared client (`@starling-cloud/sturnia-workshop`'s `ApiError`) keeps\n * only `status` and `detail`, and that `detail` is English (or Dutch) server\n * text. So the client's fetch goes through `withApiErrors`:\n *\n * - a `503` with `\"code\": \"busy\"` (a locked database) is tried once more\n *   after `Retry-After` (about 2 s) before it reaches the app — but only a\n *   call that is safe to send twice (`retriesWhenBusy`): a join, a new\n *   participant or a removal is not atomic on the server, so a second try\n *   could add a second participant;\n * - the `detail` of every other refusal is replaced by a translated text\n *   for its code (or a known English detail, or a translated generic\n *   message), and the code is remembered for that text, so `errorCode`\n *   can tell what happened from the `ApiError` alone;\n * - a refusal about the workshop password is left as it is: the gate of\n *   sturnia-workshop recognises it by its English detail.\n *\n * Under it (`clientFetch`) study-base's lib/connection tells the front's\n * answer while the server restarts (a refused connection, 502/503/504, an\n * HTML page) from the app's own: it arrives here as `server_unreachable`,\n * never as a busy call to try again, and marks the shared line down (the\n * banner, the polls' pause). */\n\nimport {\n    watchConnection,\n    type Connection,\n} from \"@starling-study/study-base/lib/connection\";\n\nimport type { StringKey } from \"./i18n\";\n\n/** The codes the app acts on (or shows a text of its own for). */\nexport type ErrorCode =\n    | \"workshop_closed\"\n    | \"workshop_not_found\"\n    | \"group_not_found\"\n    | \"participant_gone\"\n    | \"busy\"\n    | \"not_allowed\"\n    | \"staff_required\"\n    | \"app_disabled\"\n    | \"csrf_failed\"\n    | \"offline\"\n    | \"server_unreachable\"\n    | \"form_incomplete\"\n    | \"no_page\"\n    | \"nothing_to_change\"\n    | \"already_running\"\n    | \"generation_off\"\n    | \"generation_paused\"\n    | \"generation_limit\"\n    | \"empty_html\"\n    | \"not_html\"\n    | \"too_large\"\n    | \"unknown_upload\"\n    | \"own_page\"\n    | \"gallery_off\"\n    | \"unknown\";\n\n/** The translated text of each code. */\nexport const ERROR_TEXT: Record<ErrorCode, StringKey> = {\n    workshop_closed: \"errWorkshopClosed\",\n    workshop_not_found: \"errWorkshopNotFound\",\n    group_not_found: \"errGroupNotFound\",\n    participant_gone: \"errParticipantGone\",\n    busy: \"errBusy\",\n    not_allowed: \"errNotAllowed\",\n    staff_required: \"errStaffRequired\",\n    app_disabled: \"errAppDisabled\",\n    csrf_failed: \"csrfReload\",\n    offline: \"errOffline\",\n    server_unreachable: \"errRestarting\",\n    form_incomplete: \"fillFormFirst\",\n    no_page: \"errNoPage\",\n    nothing_to_change: \"errNothingToChange\",\n    already_running: \"genErrorRunning\",\n    generation_off: \"errGenerationOff\",\n    generation_paused: \"genErrorPaused\",\n    generation_limit: \"genErrorLimit\",\n    empty_html: \"errEmptyHtml\",\n    not_html: \"errNotHtml\",\n    too_large: \"tooBig\",\n    unknown_upload: \"viewerNotFoundHint\",\n    own_page: \"errOwnPage\",\n    gallery_off: \"galleryOffText\",\n    unknown: \"errGeneric\",\n};\n\n/** Server codes that stand for one of the app's codes: study-base's\n * `MemberAPIView` refuses a call without a valid participant token with\n * `403 {\"detail\", \"code\": \"bad_token\"}`, its detail in the page's language. */\nconst CODES: Record<string, ErrorCode> = {\n    bad_token: \"participant_gone\",\n    unknown_group: \"group_not_found\",\n};\n\n/** Server details without a code (sturnus-workshop's English texts). The\n * participant-token text is a fallback for a server from before the\n * `bad_token` code; drop it after one release. */\nconst DETAILS: Record<string, ErrorCode> = {\n    \"group not found.\": \"group_not_found\",\n    \"workshop not found.\": \"workshop_not_found\",\n    \"participant not found.\": \"participant_gone\",\n    \"missing or invalid participant token.\": \"participant_gone\",\n};\n\n/** Read a refusal: its code, or `null` when it must stay as it is (the\n * workshop password, which the gate reads). */\nexport function classify(status: number, body: unknown): ErrorCode | null {\n    const record = (\n        typeof body === \"object\" && body !== null ? body : {}\n    ) as Record<string, unknown>;\n    const detail = typeof record.detail === \"string\" ? record.detail : \"\";\n    if (status === 403 && /password/i.test(detail)) return null;\n    const named = [record.code, record.error].find(\n        (value) => typeof value === \"string\",\n    ) as string | undefined;\n    if (named && Object.hasOwn(ERROR_TEXT, named)) return named as ErrorCode;\n    if (named && Object.hasOwn(CODES, named)) return CODES[named];\n    const known = DETAILS[detail.trim().toLowerCase()];\n    if (known) return known;\n    if (/csrf/i.test(detail)) return \"csrf_failed\";\n    if (status === 429) return \"generation_limit\";\n    if (status === 503) return \"busy\";\n    return \"unknown\";\n}\n\n/** The translated text → the code it stands for (filled as texts are made). */\nconst codeOfText = new Map<string, ErrorCode>();\n\n/** The code behind a refused call: the `code` an error carries, else the\n * one remembered for its (translated) detail. `null` for anything else. */\nexport function errorCode(error: unknown): ErrorCode | null {\n    if (typeof error !== \"object\" || error === null) return null;\n    const { code, detail, status } = error as {\n        code?: unknown;\n        detail?: unknown;\n        status?: unknown;\n    };\n    if (typeof code === \"string\" && Object.hasOwn(ERROR_TEXT, code))\n        return code as ErrorCode;\n    if (status === 0) return \"offline\";\n    return typeof detail === \"string\"\n        ? (codeOfText.get(detail) ?? null)\n        : null;\n}\n\nexport interface ApiErrorOptions {\n    /** The text for a code, in the page's language. */\n    text: (code: ErrorCode) => string;\n    /** Told about every refusal read (the app shows a closed workshop). */\n    onError?: (code: ErrorCode) => void;\n    /** Waits between the two tries of a busy call (tests pass a fake). */\n    wait?: (ms: number) => Promise<void>;\n}\n\n/** Methods that may be sent twice: the same call, the same result. */\nconst IDEMPOTENT = new Set([\"GET\", \"HEAD\", \"OPTIONS\", \"PUT\", \"PATCH\"]);\n\n/** POSTs that run in one transaction on the server (a busy one wrote\n * nothing), so they may be tried again: a generation, a publish. */\nconst ATOMIC_POST = /\\/groups\\/[^/]+\\/(generate|publish)\\/?$/;\n\nfunction requestMethod(input: RequestInfo | URL, init?: RequestInit): string {\n    const method =\n        init?.method ??\n        (typeof Request !== \"undefined\" && input instanceof Request\n            ? input.method\n            : \"GET\");\n    return method.toUpperCase();\n}\n\nfunction requestPath(input: RequestInfo | URL): string {\n    const raw =\n        typeof input === \"string\"\n            ? input\n            : input instanceof URL\n              ? input.href\n              : input.url;\n    return new URL(raw, \"http://localhost\").pathname;\n}\n\n/** Whether a busy (`503`) call may be tried once more: an idempotent\n * method, or a POST the server runs atomically. Never a join, a new\n * participant or a DELETE. */\nexport function retriesWhenBusy(method: string, path: string): boolean {\n    const upper = method.toUpperCase();\n    if (IDEMPOTENT.has(upper)) return true;\n    return upper === \"POST\" && ATOMIC_POST.test(path);\n}\n\nconst BUSY_WAIT_MS = 2000;\nconst BUSY_WAIT_MAX_MS = 5000;\n\nfunction retryAfter(response: Response): number {\n    const seconds = Number(response.headers.get(\"Retry-After\"));\n    return Number.isFinite(seconds) && seconds > 0\n        ? Math.min(seconds * 1000, BUSY_WAIT_MAX_MS)\n        : BUSY_WAIT_MS;\n}\n\nasync function readJson(response: Response): Promise<unknown> {\n    try {\n        return await response.clone().json();\n    } catch {\n        return null;\n    }\n}\n\n/** A fetch for the workshop client that retries a busy call once and\n * turns every refusal's `detail` into a translated text. */\nexport function withApiErrors(\n    base: typeof fetch,\n    options: ApiErrorOptions,\n): typeof fetch {\n    const wait =\n        options.wait ??\n        ((ms: number) =>\n            new Promise<void>((resolve) => setTimeout(resolve, ms)));\n    return async (input: RequestInfo | URL, init?: RequestInit) => {\n        let response = await base(input, init);\n        if (response.ok) return response;\n        let body = await readJson(response);\n        if (\n            response.status === 503 &&\n            classify(503, body) === \"busy\" &&\n            retriesWhenBusy(requestMethod(input, init), requestPath(input))\n        ) {\n            await wait(retryAfter(response));\n            response = await base(input, init);\n            if (response.ok) return response;\n            body = await readJson(response);\n        }\n        const code = classify(response.status, body);\n        if (code === null) return response;\n        options.onError?.(code);\n        const detail = options.text(code);\n        codeOfText.set(detail, code);\n        const record = typeof body === \"object\" && body !== null ? body : {};\n        const headers = new Headers(response.headers);\n        headers.set(\"Content-Type\", \"application/json\");\n        return new Response(JSON.stringify({ ...record, detail, code }), {\n            status: response.status,\n            statusText: response.statusText,\n            headers,\n        });\n    };\n}\n\n/** The client's fetch: `withApiErrors` over study-base's `watchConnection`\n * (see the module docstring); `connection` is the app's shared line unless\n * a test passes its own. */\nexport function clientFetch(\n    base: typeof fetch,\n    options: ApiErrorOptions,\n    connection?: Connection,\n): typeof fetch {\n    return withApiErrors(\n        watchConnection(base, connection ? { connection } : {}),\n        options,\n    );\n}\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 template text: YAML fields may be a plain\n *   string (shown as-is in both languages) or `{ nl, en }`.\n *\n * The language comes from the page: study-base renders the app shell under\n * a language prefix (`/nl/cocoder/`, `/en/cocoder/`) and puts it on the\n * mount as `data-lang` — Dutch by default, EN as the guest language.\n * Switching moves to the other prefix (keeping the hash route): every view\n * rebuilds from server state anyway, so a page load is simpler and safer\n * than threading re-render hooks through each view. Outside a prefixed URL\n * the choice is remembered per device (`study-cocoder:lang`).\n */\n\nimport { pickText } from \"@starling-study/study-base/lib/i18n\";\n\nexport type Lang = \"nl\" | \"en\";\n\nexport type LocalizedText = string | { nl: string; en: string };\n\nconst LANG_KEY = \"study-cocoder:lang\";\n\nlet pageLang: Lang | null = null;\n\nfunction asLang(value: string | null | undefined): Lang | null {\n    const short = (value ?? \"\").slice(0, 2).toLowerCase();\n    return short === \"nl\" || short === \"en\" ? short : null;\n}\n\n/** The page's language (`data-lang` of the mount), set once by index.ts. */\nexport function setDefaultLang(lang: string | undefined): void {\n    pageLang = asLang(lang);\n}\n\nexport function getLang(): Lang {\n    if (pageLang) return pageLang;\n    try {\n        const stored = asLang(localStorage.getItem(LANG_KEY));\n        if (stored) return stored;\n    } catch {\n        // localStorage unavailable — fall through to the default.\n    }\n    return \"nl\";\n}\n\n/** The URL of this page in another language: the `/<lang>/` prefix\n * swapped, the hash route kept. `null` when the path has no prefix. */\nexport function urlForLang(\n    lang: Lang,\n    loc: Pick<Location, \"pathname\" | \"search\" | \"hash\"> = location,\n): string | null {\n    const match = /^\\/(nl|en)(\\/.*)?$/.exec(loc.pathname);\n    if (!match) return null;\n    return `/${lang}${match[2] ?? \"/\"}${loc.search}${loc.hash}`;\n}\n\nexport function setLang(lang: Lang): void {\n    try {\n        localStorage.setItem(LANG_KEY, lang);\n    } catch {\n        // Nothing to persist to; the URL carries it anyway.\n    }\n    const target = urlForLang(lang);\n    if (target) location.assign(target);\n    else location.reload();\n}\n\n/** Resolves a localized template value for a language (default: current). */\nexport function pick(value: LocalizedText | undefined, lang?: Lang): string {\n    return pickText(value, lang ?? getLang());\n}\n\n/** Word count for the soft ≥N-words fields — whitespace-separated tokens. */\nexport function countWords(text: string): number {\n    const trimmed = text.trim();\n    if (!trimmed) return 0;\n    return trimmed.split(/\\s+/).length;\n}\n\nconst STRINGS = {\n    // chrome\n    gallery: { nl: \"Galerij\", en: \"Gallery\" },\n    myPage: { nl: \"Mijn AI-oplossing\", en: \"My AI solution\" },\n    groupLink: { nl: \"Groep\", en: \"Group\" },\n    refresh: { nl: \"Ververs\", en: \"Refresh\" },\n\n    // group, and the explainer (\"Uitleg\")\n    introTitle: { nl: \"Hoe werkt het?\", en: \"How does it work?\" },\n    introText: {\n        nl: \"Deze korte video laat zien hoe Cocoder werkt.\",\n        en: \"This short video shows how Cocoder works.\",\n    },\n    introButton: { nl: \"Uitleg\", en: \"Explanation\" },\n    close: { nl: \"Sluiten\", en: \"Close\" },\n    groupLoadFailed: {\n        nl: \"Kon je groep niet laden\",\n        en: \"Could not load your group\",\n    },\n    tryAgain: { nl: \"Probeer het zo nog eens.\", en: \"Try again in a moment.\" },\n    backToGroup: { nl: \"Terug naar je groep\", en: \"Back to group\" },\n    whatAreYouMaking: {\n        nl: \"Wat gaan jullie maken?\",\n        en: \"What are you making?\",\n    },\n    lessonInstruction: {\n        nl: \"Opdracht uit de les\",\n        en: \"Instruction from the lesson\",\n    },\n    dismissInstruction: { nl: \"Verbergen\", en: \"Dismiss\" },\n\n    csrfReload: {\n        nl: \"Deze pagina is verlopen. Laad de pagina opnieuw en probeer het nog eens.\",\n        en: \"This page has expired. Reload the page and try again.\",\n    },\n\n    // work: mobile pane switch (one pane at a time on narrow screens)\n    paneForm: { nl: \"Formulier\", en: \"Form\" },\n    panePrompt: { nl: \"Prompt\", en: \"Prompt\" },\n    paneHtml: { nl: \"HTML\", en: \"HTML\" },\n    panePreview: { nl: \"Voorbeeld\", en: \"Preview\" },\n\n    // work: fullscreen preview (roadmap 0.7.0 §3)\n    fullscreen: { nl: \"Volledig scherm\", en: \"Fullscreen\" },\n    closeFullscreen: { nl: \"Sluiten\", en: \"Close\" },\n\n    // work: steps\n    stepForm: { nl: \"Formulier\", en: \"Form\" },\n    stepPreview: { nl: \"Voorbeeld\", en: \"Preview\" },\n    stepSubmit: { nl: \"Publiceren\", en: \"Publish\" },\n\n    // work: form step\n    yourPrompt: { nl: \"Jouw prompt\", en: \"Your prompt\" },\n    copyPrompt: { nl: \"Kopieer prompt\", en: \"Copy prompt\" },\n    copied: { nl: \"✓ Gekopieerd\", en: \"✓ Copied\" },\n    openVibe: { nl: \"Open Mistral ↗\", en: \"Open Mistral ↗\" },\n    promptHowTo: {\n        nl: \"Kopieer deze prompt en plak hem in Mistral (of de coding agent van je keuze). Breng daarna de HTML die je krijgt hier terug.\",\n        en: \"Copy this prompt into Mistral (or the coding agent of your choice), then bring the finished HTML back here.\",\n    },\n    promptHowToRevision: {\n        nl: \"Kopieer deze prompt en plak hem in Mistral om een nieuwe versie van je AI-oplossing te krijgen.\",\n        en: \"Copy this into Mistral to get an updated version of your AI solution.\",\n    },\n    stillMissing: { nl: \"Nog invullen:\", en: \"Still to fill in:\" },\n    missingSlot: { nl: \"nog invullen\", en: \"still to fill in\" },\n    haveHtml: { nl: \"Ik heb mijn HTML →\", en: \"I have my HTML →\" },\n    haveUpdatedHtml: {\n        nl: \"Ik heb de nieuwe HTML →\",\n        en: \"I have the updated HTML →\",\n    },\n    downloadCurrentHtml: {\n        nl: \"Download huidige HTML\",\n        en: \"Download current HTML\",\n    },\n    promptCopied: {\n        nl: \"Prompt gekopieerd — plak hem in je coding agent\",\n        en: \"Prompt copied — paste it into your coding agent\",\n    },\n    copyFailed: {\n        nl: \"Kopiëren lukte niet — selecteer de tekst en kopieer handmatig\",\n        en: \"Copy failed — select the text and copy manually\",\n    },\n    required: { nl: \"Deze is verplicht.\", en: \"This one is required.\" },\n    choose: { nl: \"Kies…\", en: \"Choose…\" },\n    example: { nl: \"Voorbeeld\", en: \"Example\" },\n    words: { nl: \"woorden\", en: \"words\" },\n\n    // work: in-app generation (0.6)\n    makeMyPage: { nl: \"Maak mijn AI-oplossing\", en: \"Make my AI solution\" },\n    generateRevision: {\n        nl: \"Genereer nieuwe versie\",\n        en: \"Generate new version\",\n    },\n    generateHowTo: {\n        nl: \"Vul het formulier in en druk op de knop: de AI maakt je AI-oplossing hier in de app. Dat duurt ongeveer een minuut.\",\n        en: \"Fill in the form and press the button: the AI builds your AI solution right here. It takes about a minute.\",\n    },\n    generateHowToRevision: {\n        nl: \"Beschrijf wat er anders moet en druk op de knop: de AI maakt een nieuwe versie van je AI-oplossing.\",\n        en: \"Describe what should change and press the button: the AI makes a new version of your AI solution.\",\n    },\n    whatWeSend: {\n        nl: \"Dit sturen we naar de AI\",\n        en: \"This is what we send to the AI\",\n    },\n    generating: {\n        nl: \"Bezig… dit duurt ongeveer een minuut\",\n        en: \"Working… this takes about a minute\",\n    },\n    generatingQueued: { nl: \"In de wachtrij\", en: \"Queued\" },\n    generatingPosition: { nl: \"plek\", en: \"position\" },\n    generatingElapsed: { nl: \"seconden\", en: \"seconds\" },\n    generatingByOther: {\n        nl: \"Iemand uit je groep is een AI-oplossing aan het maken…\",\n        en: \"Someone in your group is making an AI solution…\",\n    },\n    generatedDone: {\n        nl: \"Je AI-oplossing is klaar\",\n        en: \"Your AI solution is ready\",\n    },\n    generateFailed: { nl: \"Dat lukte niet\", en: \"That did not work\" },\n    tryAgainButton: { nl: \"Probeer opnieuw\", en: \"Try again\" },\n    fillFormFirst: {\n        nl: \"Vul eerst de verplichte velden in.\",\n        en: \"Fill in the required fields first.\",\n    },\n    genErrorTruncated: {\n        nl: \"De AI stopte voordat de AI-oplossing af was. Probeer het nog eens, of maak je beschrijving korter.\",\n        en: \"The AI stopped before the AI solution was complete. Try again, or shorten your description.\",\n    },\n    genErrorNoHtml: {\n        nl: \"De AI gaf geen bruikbare AI-oplossing terug. Probeer het nog eens.\",\n        en: \"The AI did not return a usable AI solution. Try again.\",\n    },\n    genErrorUpstream: {\n        nl: \"De AI-dienst reageerde niet goed. Probeer het over een minuut nog eens.\",\n        en: \"The AI service did not respond properly. Try again in a minute.\",\n    },\n    genErrorTooLarge: {\n        nl: \"De AI maakte een AI-oplossing die te groot is om te bewaren. Probeer het nog eens, of vraag om een eenvoudigere pagina.\",\n        en: \"The AI made an AI solution that is too big to keep. Try again, or ask for a simpler page.\",\n    },\n    genErrorTimeout: {\n        nl: \"De AI deed er te lang over. Probeer het nog eens.\",\n        en: \"The AI took too long. Try again.\",\n    },\n    genErrorInternal: {\n        nl: \"Er ging iets mis bij het maken van je AI-oplossing. Probeer het nog eens.\",\n        en: \"Something went wrong while making your AI solution. Try again.\",\n    },\n    genErrorPaused: {\n        nl: \"Genereren is even gepauzeerd door de organisatie.\",\n        en: \"Generation is paused by the organisers for now.\",\n    },\n    genErrorLimit: {\n        nl: \"Je groep heeft het maximum aantal generaties voor vandaag bereikt.\",\n        en: \"Your group has reached today's maximum number of generations.\",\n    },\n    genErrorRunning: {\n        nl: \"Er wordt al een AI-oplossing gemaakt voor je groep.\",\n        en: \"An AI solution is already being made for your group.\",\n    },\n    genErrorStale: {\n        nl: \"De verbinding met de AI ging verloren. Probeer het nog eens.\",\n        en: \"The connection to the AI was lost. Try again.\",\n    },\n    watchItBuild: {\n        nl: \"Kijk hoe je AI-oplossing ontstaat…\",\n        en: \"Watch your AI solution take shape…\",\n    },\n\n    // work: revision view\n    whatAreYouChanging: {\n        nl: \"Wat wil je veranderen?\",\n        en: \"What are you changing?\",\n    },\n    whatShouldBeDifferent: {\n        nl: \"Wat moet er anders?\",\n        en: \"What should be different?\",\n    },\n    changesPlaceholder: {\n        nl: \"bijv. Maak de kop groter en gebruik groen als accentkleur.\",\n        en: \"e.g. Make the header bigger and change the accent colour to green.\",\n    },\n    changesHint: {\n        nl: \"Beschrijf alleen wat er anders moet — de rest van de prompt vullen wij aan.\",\n        en: \"Describe only what should change — we fill in the rest of the prompt.\",\n    },\n    editAllAnswers: {\n        nl: \"Alle antwoorden aanpassen\",\n        en: \"Edit all answers\",\n    },\n    hideAllAnswers: { nl: \"Verberg de antwoorden\", en: \"Hide the answers\" },\n\n    // work: preview step\n    yourCode: {\n        nl: \"De code van je AI-oplossing\",\n        en: \"Your AI solution's code\",\n    },\n    editCodeHint: {\n        nl: \"Wil je zelf iets aanpassen? Druk op \\u201cHuidige HTML bewerken\\u201d, of plak hier HTML van een andere AI.\",\n        en: \"Want to tweak something yourself? Press \\u201cEdit current HTML\\u201d, or paste HTML from another AI here.\",\n    },\n    pasteYourHtml: { nl: \"Plak je nieuwe HTML\", en: \"Paste your new HTML\" },\n    pasteHint: {\n        nl: \"Het veld is leeg: plak hier de HTML uit Mistral. De huidige versie blijft in de preview staan tot je plakt.\",\n        en: \"The field is empty: paste the HTML from Mistral here. The current version stays in the preview until you paste.\",\n    },\n    editCurrentHtml: { nl: \"Huidige HTML bewerken\", en: \"Edit current HTML\" },\n    livePreview: { nl: \"Live preview\", en: \"Live preview\" },\n    beautify: { nl: \"Netjes maken\", en: \"Beautify\" },\n    importFile: { nl: \"Bestand openen\", en: \"Import file\" },\n    download: { nl: \"Download\", en: \"Download\" },\n    run: { nl: \"Run\", en: \"Run\" },\n    beautified: { nl: \"Opgeschoond\", en: \"Beautified\" },\n    previewUpdated: { nl: \"Preview ververst\", en: \"Preview updated\" },\n    opened: { nl: \"Geopend:\", en: \"Opened\" },\n    dropHint: {\n        nl: \"Sleep je HTML-bestand hierheen\",\n        en: \"Drop your HTML file to open it\",\n    },\n    desktop: { nl: \"Desktop\", en: \"Desktop\" },\n    tablet: { nl: \"Tablet\", en: \"Tablet\" },\n    mobile: { nl: \"Mobiel\", en: \"Mobile\" },\n    previewSize: { nl: \"Preview-formaat\", en: \"Preview size\" },\n    versions: { nl: \"Versies\", en: \"Versions\" },\n    noVersionsYet: {\n        nl: \"Nog geen eerdere versies.\",\n        en: \"No earlier versions yet.\",\n    },\n    versionsLoadFailed: {\n        nl: \"Kon eerdere versies niet laden.\",\n        en: \"Could not load earlier versions.\",\n    },\n    restore: { nl: \"Terugzetten\", en: \"Restore\" },\n    restored: {\n        nl: \"Eerdere versie teruggezet\",\n        en: \"Restored an earlier version\",\n    },\n    version: { nl: \"Versie\", en: \"Version\" },\n    changeSomething: { nl: \"Iets veranderen\", en: \"Change something\" },\n    looksGood: { nl: \"Ziet er goed uit →\", en: \"Looks good →\" },\n    showPromptAgain: { nl: \"Mijn prompt\", en: \"My prompt\" },\n    myPromptHint: {\n        nl: \"Dit is de prompt waarmee deze AI-oplossing is gemaakt.\",\n        en: \"This is the prompt this AI solution was made with.\",\n    },\n\n    // work: submit step\n    publishYourPage: {\n        nl: \"Publiceer je AI-oplossing\",\n        en: \"Publish your AI solution\",\n    },\n    publishExplainer: {\n        nl: \"Publiceren zet je AI-oplossing in de gezamenlijke galerij. Opnieuw publiceren maakt een nieuwe versie — de nieuwste is wat iedereen ziet, oudere versies blijven bekeken kunnen worden.\",\n        en: \"Publishing puts your AI solution in the shared gallery. Publishing again adds a new version — the newest one is what everyone sees; older versions stay viewable.\",\n    },\n    pageTitle: { nl: \"Titel van je AI-oplossing\", en: \"AI solution title\" },\n    pageTitlePlaceholder: {\n        nl: \"Geef je AI-oplossing een naam\",\n        en: \"Give your AI solution a name\",\n    },\n    description: { nl: \"Beschrijving\", en: \"Description\" },\n    descriptionPlaceholder: {\n        nl: \"Eén zin over je oplossing (mag leeg blijven)\",\n        en: \"One line about your solution (optional)\",\n    },\n    credits: { nl: \"Credits\", en: \"Credits\" },\n    creditsPlaceholder: {\n        nl: \"Wie hebben eraan gewerkt? (mag leeg blijven)\",\n        en: \"Who worked on it? (optional)\",\n    },\n    publish: { nl: \"Publiceer in de galerij\", en: \"Publish to the gallery\" },\n    republish: {\n        nl: \"Publiceer opnieuw (nieuwe versie in de galerij)\",\n        en: \"Re-publish (a new version in the gallery)\",\n    },\n    keepWorking: { nl: \"Verder werken\", en: \"Keep working\" },\n    titleFirst: {\n        nl: \"Geef je AI-oplossing eerst een titel.\",\n        en: \"Give your AI solution a title first.\",\n    },\n    notSignedIn: {\n        nl: \"Je bent op dit apparaat niet aangemeld bij deze groep.\",\n        en: \"You are not signed in to this group on this device.\",\n    },\n    tooBig: {\n        nl: \"Die AI-oplossing is te groot om te publiceren.\",\n        en: \"That AI solution is too big to publish.\",\n    },\n    publishFailed: {\n        nl: \"Publiceren lukte niet. Probeer het nog eens.\",\n        en: \"Publishing failed. Try again.\",\n    },\n\n    // statusbar\n    saved: { nl: \"Opgeslagen\", en: \"Saved\" },\n    autosaveNote: {\n        nl: \"Slaat automatisch op in je groep — wat groepsleden invullen verschijnt hier binnen een paar seconden.\",\n        en: \"Autosaves to your group — what group members fill in shows up here within a few seconds.\",\n    },\n    saveFailed: {\n        nl: \"Opslaan lukte niet — check je verbinding.\",\n        en: \"Could not save — check your connection.\",\n    },\n\n    // gallery\n    pagesPublished: {\n        nl: \"AI-oplossingen gepubliceerd\",\n        en: \"AI solutions published\",\n    },\n    pagePublished: {\n        nl: \"AI-oplossing gepubliceerd\",\n        en: \"AI solution published\",\n    },\n    noPagesYet: { nl: \"Nog geen AI-oplossingen\", en: \"No AI solutions yet\" },\n    noPagesHintMember: {\n        nl: \"Open je AI-oplossing om een prompt te maken en publiceer de eerste.\",\n        en: \"Open your AI solution to write a prompt and publish the first one.\",\n    },\n    noPagesHintGuest: {\n        nl: \"Doe mee met een groep om de eerste AI-oplossing te maken.\",\n        en: \"Join or create a group to make the first AI solution.\",\n    },\n    untitled: { nl: \"Zonder titel\", en: \"Untitled\" },\n    favourite: { nl: \"Favoriet maken\", en: \"Add to favourites\" },\n    unfavourite: { nl: \"Geen favoriet meer\", en: \"Remove from favourites\" },\n    favourites: { nl: \"favorieten\", en: \"favourites\" },\n\n    // viewer\n    viewerNotFound: {\n        nl: \"AI-oplossing niet gevonden\",\n        en: \"AI solution not found\",\n    },\n    viewerNotFoundHint: {\n        nl: \"Deze AI-oplossing bestaat niet (meer), of de link klopt niet.\",\n        en: \"This AI solution does not exist (any more), or the link is wrong.\",\n    },\n    backToGallery: { nl: \"Terug naar de galerij\", en: \"Back to the gallery\" },\n    galleryOffTitle: {\n        nl: \"De galerij staat uit\",\n        en: \"The gallery is switched off\",\n    },\n    galleryOffText: {\n        nl: \"In deze workshop is het gepubliceerde werk niet buiten de groep te zien.\",\n        en: \"In this workshop the published work is not shown outside the group.\",\n    },\n    publishedNoGallery: {\n        nl: \"Gepubliceerd. De galerij staat uit in deze workshop, dus alleen je groep en de workshopleider zien het.\",\n        en: \"Published. The gallery is switched off in this workshop, so only your group and the workshop leader see it.\",\n    },\n    openFullScreen: { nl: \"Open beeldvullend ↗\", en: \"Open full screen ↗\" },\n    newest: { nl: \"nieuwste\", en: \"newest\" },\n    by: { nl: \"door\", en: \"by\" },\n\n    // misc\n    toGallery: { nl: \"Naar de galerij\", en: \"Go to the gallery\" },\n    toStart: { nl: \"Naar het begin\", en: \"Go to the start\" },\n\n    // the workshop as a whole\n    workshopClosedTitle: {\n        nl: \"Deze workshop is afgelopen\",\n        en: \"This workshop has ended\",\n    },\n    workshopClosedText: {\n        nl: \"Bedankt voor het meedoen!\",\n        en: \"Thanks for taking part!\",\n    },\n    workshopNotFoundTitle: {\n        nl: \"Workshop niet gevonden\",\n        en: \"Workshop not found\",\n    },\n\n    // errors (lib/errors): what a refused call means\n    errWorkshopClosed: {\n        nl: \"Deze workshop is afgelopen — bedankt voor het meedoen.\",\n        en: \"This workshop has ended — thanks for taking part.\",\n    },\n    errWorkshopNotFound: {\n        nl: \"Deze workshop bestaat niet. Controleer de link of vraag het je workshopleider.\",\n        en: \"This workshop does not exist. Check the link or ask your workshop leader.\",\n    },\n    errGroupNotFound: {\n        nl: \"Die groep bestaat niet (meer). Controleer de code of vraag het je workshopleider.\",\n        en: \"That group does not exist (any more). Check the code or ask your workshop leader.\",\n    },\n    errParticipantGone: {\n        nl: \"Je hoort niet meer bij deze groep.\",\n        en: \"You are no longer in this group.\",\n    },\n    errBusy: {\n        nl: \"Het is even druk. Je invoer is bewaard: probeer het zo nog eens.\",\n        en: \"Busy, try again in a moment. What you entered is kept.\",\n    },\n    errNotAllowed: {\n        nl: \"Dat mag alleen de workshopleider.\",\n        en: \"Only the workshop leader can do that.\",\n    },\n    errStaffRequired: {\n        nl: \"Log in als workshopleider om dit te doen.\",\n        en: \"Log in as the workshop leader to do this.\",\n    },\n    errAppDisabled: {\n        nl: \"Deze app staat uit in deze workshop.\",\n        en: \"This app is switched off in this workshop.\",\n    },\n    // The server cannot be reached (study-base's lib/connection): a restart.\n    errRestarting: {\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    errOffline: {\n        nl: \"Geen verbinding. Controleer je internet en probeer het nog eens.\",\n        en: \"No connection. Check your internet and try again.\",\n    },\n    errNoPage: {\n        nl: \"Er is nog geen AI-oplossing om te veranderen.\",\n        en: \"There is no AI solution to change yet.\",\n    },\n    errNothingToChange: {\n        nl: \"Beschrijf eerst wat er anders moet.\",\n        en: \"Describe what should change first.\",\n    },\n    errGenerationOff: {\n        nl: \"Genereren in de app staat uit.\",\n        en: \"Generating in the app is switched off.\",\n    },\n    errEmptyHtml: {\n        nl: \"Er is nog niets om te publiceren.\",\n        en: \"There is nothing to publish yet.\",\n    },\n    errNotHtml: {\n        nl: \"Dat lijkt geen HTML-pagina.\",\n        en: \"That does not look like an HTML page.\",\n    },\n    errOwnPage: {\n        nl: \"Je kunt de AI-oplossing van je eigen groep geen ster geven.\",\n        en: \"You cannot star your own group's AI solution.\",\n    },\n    errGeneric: {\n        nl: \"Er ging iets mis. Probeer het zo nog eens.\",\n        en: \"Something went wrong. Try again in a moment.\",\n    },\n} satisfies Record<string, { nl: string; en: string }>;\n\nexport type StringKey = keyof typeof STRINGS;\n\nexport function t(key: StringKey): string {\n    return STRINGS[key][getLang()];\n}\n","/** Which workshop the page works in, and which workshop each group this\n * device joined belongs to.\n *\n * The page shell puts the workshop of the address (`?workshop=<slug>`) on\n * the mount as `data-workshop`, and `\"default\"` when the address has none.\n * A bookmark of the work screen (`/nl/cocoder/#/work`) has none, so the\n * slug is stored with each membership (`study-cocoder.workshops.v1`, group\n * code → slug): without `?workshop=` in the address, the workshop of the\n * group the device is active in wins. */\n\nexport const WORKSHOPS_KEY = \"study-cocoder.workshops.v1\";\nexport const DEFAULT_WORKSHOP = \"default\";\n\ntype Store = Pick<Storage, \"getItem\" | \"setItem\">;\n\nfunction localStore(): Store | null {\n    try {\n        return typeof localStorage === \"undefined\" ? null : localStorage;\n    } catch {\n        return null;\n    }\n}\n\nfunction load(storage: Store | null): Record<string, string> {\n    try {\n        const parsed: unknown = JSON.parse(\n            storage?.getItem(WORKSHOPS_KEY) ?? \"{}\",\n        );\n        return typeof parsed === \"object\" && parsed !== null\n            ? (parsed as Record<string, string>)\n            : {};\n    } catch {\n        return {};\n    }\n}\n\nfunction save(map: Record<string, string>, storage: Store | null): void {\n    try {\n        storage?.setItem(WORKSHOPS_KEY, JSON.stringify(map));\n    } catch {\n        // Nowhere to keep it: the address has to carry ?workshop=.\n    }\n}\n\n/** The workshop stored for a group code (`\"\"` when none is). */\nexport function workshopOf(\n    code: string,\n    storage: Store | null = localStore(),\n): string {\n    return load(storage)[code.toUpperCase()] ?? \"\";\n}\n\n/** Remember the workshop of a group this device joined. */\nexport function rememberWorkshop(\n    code: string,\n    workshop: string,\n    storage: Store | null = localStore(),\n): void {\n    if (!code) return;\n    const map = load(storage);\n    map[code.toUpperCase()] = workshop || DEFAULT_WORKSHOP;\n    save(map, storage);\n}\n\n/** Forget the workshop of a group this device left. */\nexport function forgetWorkshop(\n    code: string,\n    storage: Store | null = localStore(),\n): void {\n    const map = load(storage);\n    delete map[code.toUpperCase()];\n    save(map, storage);\n}\n\n/** The join code of the address (`?join=` or `?code=`), upper-cased;\n * `\"\"` when it has none. */\nfunction joinCodeOf(search: string): string {\n    const params = new URLSearchParams(search);\n    return (params.get(\"join\") ?? params.get(\"code\") ?? \"\").toUpperCase();\n}\n\n/** The page's workshop and where it came from: the one of the address\n * when it names one, else the one stored for the active group (`stored`:\n * true), else the shell's (`\"default\"`). A join link of another group\n * (a QR code of the default workshop names no workshop) is not the active\n * group's: then the stored one is not used. */\nexport function resolveWorkshopSource(\n    shell: string | undefined,\n    search: string,\n    activeCode: string | null,\n    storage: Store | null = localStore(),\n): { workshop: string; stored: boolean } {\n    const fromShell = shell || DEFAULT_WORKSHOP;\n    if (new URLSearchParams(search).has(\"workshop\"))\n        return { workshop: fromShell, stored: false };\n    const joining = joinCodeOf(search);\n    if (!activeCode || (joining && joining !== activeCode.toUpperCase()))\n        return { workshop: fromShell, stored: false };\n    const stored = workshopOf(activeCode, storage);\n    return stored && stored !== fromShell\n        ? { workshop: stored, stored: true }\n        : { workshop: fromShell, stored: false };\n}\n\n/** The page's workshop (see `resolveWorkshopSource`). */\nexport function resolveWorkshop(\n    shell: string | undefined,\n    search: string,\n    activeCode: string | null,\n    storage: Store | null = localStore(),\n): string {\n    return resolveWorkshopSource(shell, search, activeCode, storage).workshop;\n}\n\n/** The address to fall back to when the workshop stored for the active\n * group is closed or gone: without `?workshop=`, and without a join code\n * of that same group (it would lead back into it), so the start screen of\n * the default workshop opens. */\nexport function searchWithoutStoredWorkshop(\n    search: string,\n    activeCode: string | null,\n): string {\n    const params = new URLSearchParams(search);\n    params.delete(\"workshop\");\n    const active = (activeCode ?? \"\").toUpperCase();\n    for (const key of [\"join\", \"code\"]) {\n        if (active && (params.get(key) ?? \"\").toUpperCase() === active)\n            params.delete(key);\n    }\n    const rest = params.toString();\n    return rest ? `?${rest}` : \"\";\n}\n\n/** The address with `?workshop=` added (or replaced), so a reload or a\n * language switch keeps it; the default workshop needs none. */\nexport function searchWithWorkshop(search: string, workshop: string): string {\n    const params = new URLSearchParams(search);\n    if (!workshop || workshop === DEFAULT_WORKSHOP) params.delete(\"workshop\");\n    else params.set(\"workshop\", workshop);\n    const rest = params.toString();\n    return rest ? `?${rest}` : \"\";\n}\n","import {\n    ApiError,\n    IdentityStore,\n    WorkshopClient,\n    type WorkshopGroup,\n} from \"@starling-cloud/sturnia-workshop\";\nimport {\n    csrfFromDataset,\n    staffFromDataset,\n    withCsrf,\n} from \"@starling-study/study-base/lib/access\";\n\nimport {\n    ERROR_TEXT,\n    clientFetch,\n    errorCode,\n    type ErrorCode,\n} from \"./lib/errors\";\nimport { t, type LocalizedText } from \"./lib/i18n\";\nimport { resolveWorkshopSource, searchWithWorkshop } from \"./lib/workshop\";\n\nexport { ApiError, isPasswordError } from \"@starling-cloud/sturnia-workshop\";\n\n/** The mount's data attributes (study-base's app shell): the API prefix\n * (`/api/cocoder`) and the workshop slug. The bundle is an ES module, so\n * the DOM is parsed by the time this runs. */\nconst mountData: DOMStringMap =\n    document.getElementById(\"study-app\")?.dataset ?? {};\n\n/** The app's API prefix, e.g. `/api/cocoder` — every path below is relative\n * to it. */\nexport const API_BASE = (mountData.apiBase || \"/api/cocoder\").replace(\n    /\\/+$/,\n    \"\",\n);\n\n/** The device's identity: its name and the groups it joined. The store is\n * the one every app on the origin shares (`workshop.identity.v1`): the\n * name and the active team code are common, and this app's memberships\n * are the entries tagged `cocoder`, so a team joined in chat is known here\n * (views/start joins it silently). The store this app kept under its own\n * key before is imported once. */\nexport const identity = new IdentityStore({\n    app: \"cocoder\",\n    legacyKey: \"study-cocoder.identity.v1\",\n});\n\n/** The workshop this page belongs to; sent as `X-Workshop` so the backend\n * scopes groups and the gallery to it. An address without `?workshop=` (a\n * bookmark) takes the one stored with the active group (lib/workshop), and\n * gets it put back into the address, so a reload keeps it. */\nconst resolved = resolveWorkshopSource(\n    mountData.workshop,\n    location.search,\n    identity.get().activeCode,\n);\nexport const WORKSHOP = resolved.workshop;\n/** Whether WORKSHOP is the one stored for the active group, not the\n * address's: a closed or unknown one then sends the page to the default\n * workshop (index.ts), not to the full-page panel. */\nexport const WORKSHOP_FROM_STORAGE = resolved.stored;\nif (WORKSHOP !== (mountData.workshop || \"default\")) {\n    history.replaceState(\n        history.state,\n        \"\",\n        `${location.pathname}${searchWithWorkshop(location.search, WORKSHOP)}${location.hash}`,\n    );\n}\n\n/** Who is looking (`data-staff`; lib/access): staff may rename and\n * remove any member (components/members). */\nexport const ACCESS = {\n    staff: staffFromDataset(mountData.staff),\n    /** Django's CSRF token (`data-csrf-token`), rendered for staff only: sent\n     * as `X-CSRFToken` on every unsafe call. Empty for a visitor. */\n    csrfToken: csrfFromDataset(mountData.csrfToken),\n};\n\n/** The event every refused call raises on `window` (detail: its code):\n * index.ts answers a closed or unknown workshop with a full panel. */\nexport const API_ERROR_EVENT = \"cocoder:api-error\";\n\n/** The translated text of an error code. */\nexport function errorText(code: ErrorCode): string {\n    return t(ERROR_TEXT[code]);\n}\n\n/** What to tell the participant about a failed call, in the page's\n * language: the translated text of its code, else a generic one. */\nexport function errorMessage(error: unknown): string {\n    if (error instanceof ApiError && errorCode(error)) return error.detail;\n    return errorText(\"unknown\");\n}\n\n/** The shared client, with the reason of a refusal kept as `code` on its\n * `ApiError` (lib/errors) and \"no connection\" in the page's language. */\nclass CocoderClient extends WorkshopClient {\n    override async request<T>(\n        ...args: Parameters<WorkshopClient[\"request\"]>\n    ): Promise<T> {\n        try {\n            return await super.request<T>(...args);\n        } catch (error) {\n            if (error instanceof ApiError) {\n                if (error.status === 0)\n                    throw Object.assign(\n                        new ApiError(0, errorText(\"offline\")),\n                        { code: \"offline\" },\n                    );\n                const code = errorCode(error);\n                if (code) Object.assign(error, { code });\n            }\n            throw error;\n        }\n    }\n}\n\n// One client for the whole app: attaches X-Workshop-Password /\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. A staff session sends its CSRF token\n// on every unsafe call (`X-CSRFToken`). A busy server is tried once more,\n// and every refusal is read in the page's language (lib/errors); under\n// that study-base's lib/connection tells the front's answer while the\n// server restarts (`server_unreachable`) and keeps the app's connection\n// state (the banner, the polls' pause).\nexport const client = new CocoderClient({\n    baseUrl: API_BASE,\n    legacyPasswordKey: \"study-cocoder:password\",\n    fetch: clientFetch(withCsrf(ACCESS.csrfToken), {\n        text: errorText,\n        onError: (code) =>\n            window.dispatchEvent(\n                new CustomEvent(API_ERROR_EVENT, { detail: code }),\n            ),\n    }),\n    headers: (): Record<string, string> =>\n        WORKSHOP ? { \"X-Workshop\": WORKSHOP } : {},\n});\n\n/** The full-page, chrome-less view of one upload (sandboxed by its CSP\n * header) — opened in a new tab from the viewer. */\nexport function rawUrl(publicId: string): string {\n    return `${API_BASE}/raw/${encodeURIComponent(publicId)}`;\n}\n\nexport type QuestionType =\n    \"text\" | \"textarea\" | \"select\" | \"radio\" | \"checkbox\";\n\n/** A choice: `value` is what lands in answers and the prompt; nl/en are\n * what the participant sees. */\nexport interface QuestionOption {\n    value: string;\n    nl?: string;\n    en?: string;\n}\n\nexport interface Question {\n    key: string;\n    label: LocalizedText;\n    type: QuestionType;\n    help?: LocalizedText;\n    placeholder?: LocalizedText;\n    example?: LocalizedText;\n    minWords?: number;\n    required?: boolean;\n    options?: QuestionOption[];\n    default?: string | string[];\n}\n\nexport interface TemplateSummary {\n    id: string;\n    title: LocalizedText;\n    description?: LocalizedText;\n}\n\nexport interface PromptTemplate extends TemplateSummary {\n    questions: Question[];\n    preset: Record<string, string>;\n    prompt: string;\n    revision?: string;\n}\n\n// ---- the group's page, riding along on the shared group object -----------\n\nexport interface PageState {\n    templateId: string | null;\n    answers: Record<string, unknown>;\n    html: string;\n    title: string;\n    description: string;\n    credits: string;\n    step: string;\n    updatedAt: string;\n}\n\nexport interface PublishedInfo {\n    publicId: string;\n    title: string;\n    createdAt: string;\n}\n\n/** A queued/running in-app generation for the group (0.6), as carried on\n * the group object so every member's poll sees it. */\nexport interface GeneratingInfo {\n    id: number;\n    kind: \"initial\" | \"revision\";\n    status: \"queued\" | \"running\";\n    participantId: string | null;\n    startedAt: string | null;\n    createdAt: string;\n}\n\nexport interface CocoderGroup extends WorkshopGroup {\n    page: PageState;\n    published: PublishedInfo | null;\n    generating: GeneratingInfo | null;\n}\n\nexport type GenerationStatus = \"queued\" | \"running\" | \"done\" | \"error\";\n\nexport interface GenerationInfo {\n    id: number;\n    kind: \"initial\" | \"revision\";\n    status: GenerationStatus;\n    participantId: string | null;\n    createdAt: string;\n    startedAt: string | null;\n    finishedAt: string | null;\n    queuePosition: number | null;\n    partialLength: number;\n    error: string | null;\n    model: string | null;\n    usage: { inputTokens: number; outputTokens: number } | null;\n}\n\nexport interface GenerateStatus {\n    enabled: boolean;\n    paused: boolean;\n    model: string | null;\n    provider?: string | null;\n    /** The workshop's public gallery switch (missing from older servers: on). */\n    publicGallery?: boolean;\n}\n\n/** The intro video URL per language (null = transcript only). */\nexport interface IntroVideos {\n    nl: string | null;\n    en: string | null;\n}\n\nexport interface PagePatch {\n    templateId?: string;\n    answers?: Record<string, unknown>;\n    html?: string;\n    title?: string;\n    description?: string;\n    credits?: string;\n    step?: string;\n    /** Carried along only so the server can attach it to the page_revisions\n     * row it pushes when html changes — never read back. */\n    revisionPrompt?: string;\n}\n\nexport interface RevisionSummary {\n    id: number;\n    createdAt: string;\n    sizeBytes: number;\n}\n\nexport interface GalleryEntry {\n    publicId: string;\n    title: string;\n    description: string;\n    credits: string;\n    groupName: string;\n    participants: string[];\n    createdAt: string;\n    sizeBytes: number;\n    /** Stars from participants of other groups (kept across re-publishes). */\n    favourites: number;\n    /** Whether the participant behind the request's token starred it. */\n    favourited?: boolean;\n    /** Whether it is that participant's own group's page (cannot be starred). */\n    own?: boolean;\n}\n\n/** The answer to starring / unstarring a gallery page. */\nexport interface FavouriteResult {\n    publicId: string;\n    favourites: number;\n    favourited: boolean;\n}\n\n/** One published version of a group's page, for the viewer's switcher. */\nexport interface PageVersionInfo {\n    publicId: string;\n    title: string;\n    createdAt: string;\n    sizeBytes: number;\n    current: boolean;\n}\n\nexport interface ViewerInfo {\n    publicId: string;\n    title: string;\n    description: string;\n    credits: string;\n    groupName: string;\n    versions: PageVersionInfo[];\n}\n\nexport const api = {\n    templates: () => client.request<TemplateSummary[]>(\"GET\", \"/templates\"),\n    template: (id: string) =>\n        client.request<PromptTemplate>(\n            \"GET\",\n            `/templates/${encodeURIComponent(id)}`,\n        ),\n\n    revisions: (code: string, token: string) =>\n        client.request<RevisionSummary[]>(\"GET\", `/groups/${code}/revisions`, {\n            token,\n        }),\n    revisionHtml: (code: string, id: number, token: string) =>\n        client.request<{ html: string }>(\n            \"GET\",\n            `/groups/${code}/revisions/${id}`,\n            { token },\n        ),\n\n    publish: (\n        code: string,\n        token: string,\n        body: { title: string; description?: string; credits?: string },\n    ) =>\n        client.request<{ publicId: string; sizeBytes: number }>(\n            \"POST\",\n            `/groups/${code}/publish`,\n            { json: body, token },\n        ),\n\n    // ---- in-app generation (0.6) -----------------------------------------\n\n    generateStatus: () =>\n        client.request<GenerateStatus>(\"GET\", \"/generate/status\"),\n    intro: () => client.request<IntroVideos>(\"GET\", \"/intro\"),\n    generate: (\n        code: string,\n        token: string,\n        body: { kind: \"initial\" | \"revision\"; 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    generationPartial: (code: string, id: number, token: string) =>\n        client.request<{ status: GenerationStatus; partial: string }>(\n            \"GET\",\n            `/groups/${code}/generate/${id}/partial`,\n            {\n                token,\n            },\n        ),\n\n    /** With a participant token the entries also say `favourited` / `own`. */\n    gallery: (token?: string) =>\n        client.request<GalleryEntry[]>(\n            \"GET\",\n            \"/gallery\",\n            token ? { token } : {},\n        ),\n    setFavourite: (publicId: string, token: string, on: boolean) =>\n        client.request<FavouriteResult>(\n            on ? \"POST\" : \"DELETE\",\n            `/gallery/${publicId}/favourite`,\n            { token },\n        ),\n    galleryHtml: (publicId: string) =>\n        client.request<{ html: string }>(\"GET\", `/gallery/${publicId}/html`),\n    viewerInfo: (publicId: string) =>\n        client.request<ViewerInfo>(\"GET\", `/gallery/${publicId}/versions`),\n};\n","// ============================================================================\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","/** The page inside a lesson (study-syllabus): `?embed=1` drops the app bar\n * (the lesson has its own header; one header only), `&theme=light|dark`\n * sets the lesson's theme on `<html>`, `&join=<code>&workshop=<slug>`\n * joins the lesson's group (study-base's lib/entry, `requireGroup`, which\n * also drops the code from the address) and `&task=<text>` is the\n * lesson's instruction (lib/launch). */\n\ntype Search = Pick<Location, \"search\">;\n\n/** Whether the address asks for the embedded page (`?embed=1`). */\nexport function isEmbedded(loc: Search = location): boolean {\n    return new URLSearchParams(loc.search).get(\"embed\") === \"1\";\n}\n\n/** The lesson's language (`?lang=nl|en`), or `null`. */\nexport function langFromSearch(search: string): \"nl\" | \"en\" | null {\n    const lang = new URLSearchParams(search).get(\"lang\");\n    return lang === \"nl\" || lang === \"en\" ? lang : null;\n}\n\n/** The page's language: inside a lesson (`?embed=1`) the lesson's `&lang=`\n * wins over the address prefix (the mount's `data-lang`), so the whole\n * page speaks the lesson's language. */\nexport function pageLang(\n    search: string,\n    dataLang: string | undefined,\n): string | undefined {\n    return (isEmbedded({ search }) && langFromSearch(search)) || dataLang;\n}\n\n/** The theme of a lesson's message (`{type: \"study:theme\", theme}`), or\n * `null` for any other message. */\nexport function themeFromMessage(data: unknown): \"light\" | \"dark\" | null {\n    if (typeof data !== \"object\" || data === null) return null;\n    const { type, theme } = data as { type?: unknown; theme?: unknown };\n    return type === \"study:theme\" && (theme === \"light\" || theme === \"dark\")\n        ? theme\n        : null;\n}\n\n/** The lesson's theme (`?theme=light|dark`), or `null`. */\nexport function themeFromSearch(search: string): \"light\" | \"dark\" | null {\n    const theme = new URLSearchParams(search).get(\"theme\");\n    return theme === \"light\" || theme === \"dark\" ? theme : null;\n}\n\n/** The lesson's latest theme (a `study:theme` message), kept for the tab:\n * every route change reloads the page, and the address's `?theme=` is only\n * the theme the lesson had when it opened the page. Kept together with\n * that `?theme=`, so a lesson page that opens the app afresh (with another\n * `?theme=`) is not overruled by an old message. */\nexport const LESSON_THEME_KEY = \"study-cocoder:lesson-theme\";\n\ntype Theme = \"light\" | \"dark\";\ntype Store = Pick<Storage, \"getItem\" | \"setItem\">;\n\nfunction sessionStore(): Store | null {\n    try {\n        return typeof sessionStorage === \"undefined\" ? null : sessionStorage;\n    } catch {\n        return null;\n    }\n}\n\n/** Keep the theme a lesson's message set, with the address's `?theme=`\n * (sessionStorage). */\nexport function rememberLessonTheme(\n    theme: Theme,\n    search: string,\n    storage: Store | null = sessionStore(),\n): void {\n    try {\n        storage?.setItem(\n            LESSON_THEME_KEY,\n            JSON.stringify({ theme, from: themeFromSearch(search) }),\n        );\n    } catch {\n        // No storage: the next page load takes `?theme=` again.\n    }\n}\n\n/** The lesson's theme: the one its last message set (while the address\n * still carries the same `?theme=`), else `?theme=`, else `null`. */\nexport function lessonTheme(\n    search: string,\n    storage: Store | null = sessionStore(),\n): Theme | null {\n    const fromSearch = themeFromSearch(search);\n    try {\n        const kept: unknown = JSON.parse(\n            storage?.getItem(LESSON_THEME_KEY) ?? \"null\",\n        );\n        if (typeof kept === \"object\" && kept !== null) {\n            const { theme, from } = kept as {\n                theme?: unknown;\n                from?: unknown;\n            };\n            if ((theme === \"light\" || theme === \"dark\") && from === fromSearch)\n                return theme;\n        }\n    } catch {\n        // Nothing (readable) kept: the address's theme.\n    }\n    return fromSearch;\n}\n","/** The workshop's public gallery switch (its `public_gallery` setting on\n * the dashboard, on by default). The server says it in `publicGallery` of\n * `GET generate/status` (the app's config read); index.ts reads it once\n * after the gate. Off, the gallery and its viewer are closed (the API\n * answers 404 `gallery_off`), the bar has no gallery link and a publish\n * stays on the work screen. A group's own work is not the gallery and\n * stays. */\n\nlet publicGallery = true;\n\n/** Whether the gallery is open outside the group (true until told otherwise). */\nexport function galleryIsPublic(): boolean {\n    return publicGallery;\n}\n\n/** Remember the switch for this page load. */\nexport function setGalleryPublic(on: boolean): void {\n    publicGallery = on;\n}\n\n/** The switch in a status answer: anything but `false` keeps the gallery\n * open (an older server sends no `publicGallery`, a failed read none). */\nexport function publicGalleryOf(\n    status: { publicGallery?: boolean } | null | undefined,\n): boolean {\n    return status?.publicGallery !== false;\n}\n\n/** Whether `route` is closed while the gallery is off: the gallery grid\n * and the full-page viewer of its pages. */\nexport function closedWithoutGallery(route: string, on: boolean): boolean {\n    return !on && (route === \"gallery\" || route === \"view\");\n}\n","/** Hash routing inside the app page (/<lang>/cocoder/): the studio app's\n * paths become hash routes —\n *\n *   #/               the work view (there is no start screen: joining and\n *                    creating a group are the workshop's groups page's,\n *                    the group itself its group page, study-base; lib/route)\n *   #/work/<step>    the form → preview → submit loop (form|preview|submit)\n *   #/gallery        gallery grid (?g=CODE highlights a group's card)\n *   #/view/<id>      full-page viewer with the version switcher\n *\n * Anything else (the former `#/admin` included: the organiser's screens are\n * the server-rendered dashboard now) and an old `#/group` is `notfound`,\n * shown as the work view.\n *\n * Moving between top-level routes reloads the page (index.ts), exactly like\n * the studio app's full page loads, so no view leaks timers into the next. */\n\nexport type RouteName = \"start\" | \"work\" | \"gallery\" | \"view\" | \"notfound\";\n\nexport interface Route {\n    name: RouteName;\n    /** The second path segment: the work step, or the viewer's public id. */\n    param: string;\n    query: URLSearchParams;\n}\n\nexport function parseHash(hash: string = location.hash): Route {\n    const raw = hash.replace(/^#\\/?/, \"\");\n    const [pathPart = \"\", queryPart = \"\"] = raw.split(\"?\");\n    const segments = pathPart.split(\"/\").filter(Boolean);\n    const query = new URLSearchParams(queryPart);\n    const head = segments[0] ?? \"\";\n    const param = segments[1] ?? \"\";\n    switch (head) {\n        case \"\":\n            return { name: \"start\", param: \"\", query };\n        case \"work\":\n        case \"gallery\":\n            return { name: head, param, query };\n        case \"view\":\n            return /^[A-Za-z0-9_-]{8,64}$/.test(param)\n                ? { name: \"view\", param, query }\n                : { name: \"notfound\", param: \"\", query };\n        default:\n            return { name: \"notfound\", param: \"\", query };\n    }\n}\n\nexport function currentRoute(): Route {\n    return parseHash(location.hash);\n}\n\n/** An in-app link target: `href(\"gallery\")` → `#/gallery`. */\nexport function href(path: string): string {\n    return `#/${path.replace(/^\\/+/, \"\")}`;\n}\n\n/** Go to an in-app route. */\nexport function navigate(path: string): void {\n    const target = href(path);\n    if (location.hash === target) return;\n    location.hash = target;\n}\n\n/** Whether a hash is an app route (`#/…`, or none at all) and not an\n * in-page anchor (`#q-name`, `#main`): following an anchor scrolls to it,\n * it does not leave the view. Read as a route, every anchor is an unknown\n * one — the reload on a route change (index.ts) then lands on the work\n * view's first step, a tap on an in-page link throwing away the work screen. */\nexport function isRouteHash(hash: string): boolean {\n    return hash === \"\" || hash === \"#\" || hash.startsWith(\"#/\");\n}\n\n/** A stable key for \"which view is rendered\" — the work step does not\n * count (the work view routes its own steps). */\nexport function routeKey(route: Route): string {\n    return route.name === \"view\" ? `view:${route.param}` : route.name;\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","/** 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","/** 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 app-wide session: one WorkshopSession<CocoderGroup>, so every view\n * shares the same identity, active group and polling (study-base's\n * lib/session). */\n\nimport { createAppSession } from \"@starling-study/study-base/lib/session\";\n\nimport {\n    client,\n    identity,\n    WORKSHOP,\n    type CocoderGroup,\n    type PagePatch,\n} from \"./api\";\nimport { forgetWorkshop, rememberWorkshop, workshopOf } from \"./lib/workshop\";\n\nexport { identity };\n\n// Paths are relative to the client's baseUrl (/api/cocoder), so no prefix.\n// The group card's QR image comes from `groups.qrUrl`, which has to name a\n// workshop other than the default in its URL.\nexport const { session } = createAppSession<CocoderGroup>({\n    client,\n    app: \"cocoder\",\n    workshop: WORKSHOP,\n    identity,\n});\n\n// Every group this device enters is remembered with the page's workshop,\n// so a bookmark without `?workshop=` finds it again (lib/workshop). A group\n// that has one already keeps it.\nsession.addEventListener(\"group-entered\", (event) => {\n    const code = (event as CustomEvent<{ code: string }>).detail?.code;\n    if (code && !workshopOf(code)) rememberWorkshop(code, WORKSHOP);\n});\n\n/** Forget a group on this device: its membership and its workshop. */\nexport function forgetGroup(code: string): void {\n    session.forgetGroup(code);\n    forgetWorkshop(code);\n}\n\n/** patchGroup({ page: {...} }) typed for the page's own (fully optional)\n * patch shape — WorkshopSession<G>.patchGroup takes Partial<G>, whose `page`\n * field is a *complete* PageState (page is required on CocoderGroup), which\n * a partial page patch like `{ step: \"preview\" }` does not satisfy. This is\n * the one place that gap is bridged, instead of an `as never` at every call\n * site. */\nexport function patchPage(page: PagePatch): Promise<CocoderGroup> {\n    return session.patchGroup({ page } as unknown as Partial<CocoderGroup>);\n}\n","/** 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","/** DOM helpers. The element builder, the status line and the file size\n * are study-base's (lib/dom); the icon and the message screen are this\n * app's. */\n\nimport { el } from \"@starling-study/study-base/lib/dom\";\n\nexport {\n    clear,\n    createNotifier,\n    el,\n    formatBytes,\n    on,\n} from \"@starling-study/study-base/lib/dom\";\n\nconst SVG_NS = \"http://www.w3.org/2000/svg\";\n\n/** A small line icon (24x24 grid, drawn in the text colour); `shapes` is\n * SVG markup written here in the source, never user input. */\nexport function icon(shapes: string): SVGSVGElement {\n    const svg = document.createElementNS(SVG_NS, \"svg\");\n    for (const [name, value] of Object.entries({\n        viewBox: \"0 0 24 24\",\n        width: \"18\",\n        height: \"18\",\n        fill: \"none\",\n        stroke: \"currentColor\",\n        \"stroke-width\": \"2\",\n        \"stroke-linecap\": \"round\",\n        \"stroke-linejoin\": \"round\",\n        \"aria-hidden\": \"true\",\n    })) {\n        svg.setAttribute(name, value);\n    }\n    svg.innerHTML = shapes;\n    return svg;\n}\n\n/** A whole-screen message with at most one way out (not found, could not\n * load, the workshop has ended): the theme's centred page around its\n * `.ss-state`. */\nexport function messageScreen(\n    title: string,\n    message: string,\n    action?: { href: string; label: string },\n): HTMLElement {\n    return el(\n        \"div\",\n        { class: \"study-centered\" },\n        el(\n            \"div\",\n            { class: \"ss-state\", role: \"status\" },\n            el(\"h1\", { class: \"ss-state__title\", text: title }),\n            el(\"p\", { class: \"ss-state__message\", text: message }),\n            action\n                ? el(\n                      \"a\",\n                      { class: \"ss-btn ss-state__action\", href: action.href },\n                      action.label,\n                  )\n                : null,\n        ),\n    );\n}\n","/** \"How does it work?\" — what Cocoder does, in five steps (NL/EN), with\n * the intro video above them when a deployment has one.\n *\n * Shown from every screen through the header's \"Uitleg\" link, which opens\n * it in a modal dialog.\n *\n * The videos (~43 MB each) are not bundled: `GET intro/` says where they\n * are (STUDY_COCODER[\"INTRO_VIDEOS\"], COCODER_INTRO_VIDEO_NL/EN, or\n * static/study/cocoder/video/vibecode-<lang>.mp4 when a deployment drops\n * them there). Without one there is no video block at all: no empty\n * player, no sentence about a video.\n */\n\nimport { api } from \"../api\";\nimport { el } from \"../lib/dom\";\nimport { getLang, t, type Lang } from \"../lib/i18n\";\n\n/** The steps, with in-app generation on (`generate`) or off (`paste`:\n * the prompt goes to a chat AI and the HTML comes back). */\nconst STEPS: Record<\n    Lang,\n    {\n        start: string[];\n        generate: string;\n        paste: string;\n        end: string[];\n        note: string;\n    }\n> = {\n    nl: {\n        start: [\n            \"Doe mee met de groep van je tafel: scan de QR-code of typ de groepscode.\",\n            \"Vul samen het formulier in: de stedelijke opgave, de publieke waarden, hoe jullie AI-oplossing werkt en hoe die eruitziet.\",\n        ],\n        generate:\n            \"Druk op “Maak mijn AI-oplossing”. De AI bouwt in ongeveer een minuut een werkende webpagina: een prototype met verzonnen data.\",\n        paste: \"Kopieer de prompt die het formulier maakt, plak hem in een AI-chat en breng de HTML die je terugkrijgt hier terug.\",\n        end: [\n            \"Bekijk de preview en probeer hem uit. Moet er iets anders? Beschrijf wat er anders moet en maak een nieuwe versie.\",\n            \"Tevreden? Publiceer je AI-oplossing in de galerij en kijk wat de andere groepen hebben gemaakt.\",\n        ],\n        note: \"Eén telefoon per tafel is genoeg. Iedereen in de groep kan meetypen en ziet hetzelfde formulier.\",\n    },\n    en: {\n        start: [\n            \"Join your table's group: scan the QR code or type the group code.\",\n            \"Fill in the form together: the urban challenge, the public values, how your AI solution works and what it looks like.\",\n        ],\n        generate:\n            \"Press “Make my AI solution”. In about a minute the AI builds a working web page: a prototype with made-up data.\",\n        paste: \"Copy the prompt the form makes, paste it into an AI chat and bring the HTML you get back here.\",\n        end: [\n            \"Look at the preview and try it out. Something to change? Describe what should be different and make a new version.\",\n            \"Happy with it? Publish your AI solution to the gallery and see what the other groups made.\",\n        ],\n        note: \"One phone per table is enough. Everyone in the group can type along and sees the same form.\",\n    },\n};\n\n/** The steps of the intro, in a language (pure, for the tests). */\nexport function introSteps(lang: Lang, generate: boolean): string[] {\n    const steps = STEPS[lang];\n    return [\n        ...steps.start,\n        generate ? steps.generate : steps.paste,\n        ...steps.end,\n    ];\n}\n\n/** The intro's body: the video (only when there is one) and the steps. */\nexport function introContent(generate: boolean): HTMLElement {\n    const lang = getLang();\n    const video = el(\"video\", {\n        class: \"study-video__file\",\n        controls: true,\n        preload: \"metadata\",\n        playsinline: true,\n    }) as HTMLVideoElement;\n    const player = el(\n        \"figure\",\n        { class: \"study-video\", hidden: true },\n        el(\"div\", { class: \"study-video__player\" }, video),\n        el(\"figcaption\", { class: \"ss-hint\", text: t(\"introText\") }),\n    );\n    void videoUrl(lang).then((url) => {\n        if (!url) return;\n        video.src = url;\n        player.hidden = false;\n    });\n    return el(\n        \"div\",\n        { class: \"ss-stack cocoder-intro\" },\n        player,\n        el(\n            \"ol\",\n            { class: \"cocoder-intro__steps\" },\n            ...introSteps(lang, generate).map((step) =>\n                el(\"li\", { text: step }),\n            ),\n        ),\n        el(\"p\", { class: \"ss-hint\", text: STEPS[lang].note }),\n    );\n}\n\nlet videos: Promise<Record<Lang, string | null>> | undefined;\n\n/** The intro video for a language, or null (asked once per page). */\nfunction videoUrl(lang: Lang): Promise<string | null> {\n    videos ??= api.intro().catch(() => ({ nl: null, en: null }));\n    return videos.then((urls) => urls[lang] ?? null);\n}\n\nlet dialog: HTMLDialogElement | undefined;\n\n/** Opens the intro in a modal dialog (built once per page load). */\nexport function openIntroDialog(): void {\n    if (!dialog) {\n        const closeButton = el(\n            \"button\",\n            {\n                class: \"study-dialog__close\",\n                type: \"button\",\n                \"aria-label\": t(\"close\"),\n            },\n            \"×\",\n        );\n        const body = el(\"div\", { class: \"study-dialog__body\" });\n        dialog = el(\n            \"dialog\",\n            {\n                class: \"study-dialog\",\n                \"aria-labelledby\": \"cocoder-intro-title\",\n            },\n            el(\n                \"div\",\n                { class: \"study-dialog__head\" },\n                el(\"h2\", {\n                    class: \"study-dialog__title\",\n                    id: \"cocoder-intro-title\",\n                    text: t(\"introTitle\"),\n                }),\n                closeButton,\n            ),\n            body,\n        );\n        void api\n            .generateStatus()\n            .then((status) => status.enabled)\n            .catch(() => false)\n            .then((generate) => body.replaceChildren(introContent(generate)));\n        closeButton.addEventListener(\"click\", () => dialog?.close());\n        dialog.addEventListener(\"close\", () =>\n            dialog?.querySelector(\"video\")?.pause(),\n        );\n        document.body.append(dialog);\n    }\n    dialog.showModal();\n}\n","/** The app's one header: study-base's `mountAppbar` (the theme's\n * `study-appbar`) with cocoder's group chip and links. The chip links to\n * the workshop's group page (`mountAppbar` makes it from the shell's\n * `data-groups-url`): members, code, QR code and every tool. The wordmark, the\n * language switch, the theme toggle and the phone menu are the bar's own.\n *\n * Inside a lesson (`?embed=1`) there is no app bar at all: the lesson has\n * its own header. The view's own controls (the gallery's refresh button)\n * then sit in a plain toolbar, and the lesson's `&theme=` is the theme. */\n\nimport {\n    applyStoredTheme as applyBarTheme,\n    currentTheme,\n    keepEmbed,\n    mountAppbar,\n    type AppbarLink,\n} from \"@starling-study/study-base/appbar\";\nimport { groupPageUrl } from \"@starling-study/study-base/lib/entry\";\n\nimport { isEmbedded, lessonTheme } from \"../lib/embed\";\nimport { galleryIsPublic } from \"../lib/gallery\";\nimport { getLang, t } from \"../lib/i18n\";\nimport { href } from \"../lib/router\";\nimport { session } from \"../session\";\n\nimport { openIntroDialog } from \"./intro\";\n\n/** Put the theme on `<html>`: the lesson's when embedded (its last\n * `study:theme` message, else `?theme=`), else the one stored on this\n * device. */\nexport function applyStoredTheme(): void {\n    const lesson = isEmbedded() ? lessonTheme(location.search) : null;\n    if (lesson) document.documentElement.dataset.theme = lesson;\n    else applyBarTheme();\n}\n\n/** The href of the \"Uitleg\" link: not a route, it opens the intro dialog. */\nconst INTRO_HREF = \"#uitleg\";\n\nexport function isDark(): boolean {\n    return currentTheme() === \"dark\";\n}\n\n// One listener at a time (the current view's): the bar's toggle lands as a\n// `data-theme` change on <html>, which the code editor follows.\nlet themeListener: ((dark: boolean) => void) | undefined;\nlet themeObserver: MutationObserver | undefined;\n\nfunction watchTheme(listener: ((dark: boolean) => void) | undefined): void {\n    themeListener = listener;\n    if (themeObserver || !listener) return;\n    themeObserver = new MutationObserver(() => themeListener?.(isDark()));\n    themeObserver.observe(document.documentElement, {\n        attributes: true,\n        attributeFilter: [\"data-theme\"],\n    });\n}\n\nexport interface HeaderOptions {\n    /** The view's own controls in the bar (the gallery's refresh button). */\n    actions?: HTMLElement[];\n    /** Show the group chip and the links into the group's work (default\n     * true; they only show while the participant is in a group). */\n    showGroup?: boolean;\n    /** Show the \"Uitleg\" link that reopens the explainer video and its\n     * transcript (default true). False where it is on the page already. */\n    showIntro?: boolean;\n    onThemeChange?: (dark: boolean) => void;\n}\n\n/** The portal in the page's language: where the wordmark leads. */\nfunction portalHref(): string {\n    return `/${getLang()}/`;\n}\n\n/** The bar on screen (one per page): a re-rendered view replaces it. */\nlet currentBar: { destroy(): void } | null = null;\nlet unsubscribe: (() => void) | null = null;\n\n/**\n * The page's header. Outside a lesson that is study-base's app bar, which\n * sits right before the shell's `<main>` (header and main are siblings;\n * the views render no `main` of their own): nothing for the view to place,\n * so the result is empty. Inside a lesson there is no bar; the result is a\n * slim row for the view to put first, with the app's own links (the\n * lesson's header cannot navigate inside the tool) and the view's controls.\n */\nexport function createHeader({\n    actions = [],\n    showGroup = true,\n    showIntro = true,\n    onThemeChange,\n}: HeaderOptions = {}): HTMLElement[] {\n    watchTheme(onThemeChange);\n    currentBar?.destroy();\n    currentBar = null;\n    unsubscribe?.();\n    unsubscribe = null;\n\n    // The group itself is the chip (a link to the workshop's group page): no second\n    // \"Group\" link next to it.\n    function links(): AppbarLink[] {\n        const inGroup = showGroup && Boolean(session.membership);\n        return [\n            ...(showIntro\n                ? [\n                      {\n                          label: t(\"introButton\"),\n                          href: INTRO_HREF,\n                          active: false,\n                      },\n                  ]\n                : []),\n            ...(galleryIsPublic()\n                ? [{ label: t(\"gallery\"), href: href(\"gallery\") }]\n                : []),\n            ...(inGroup ? [{ label: t(\"myPage\"), href: href(\"work\") }] : []),\n        ];\n    }\n\n    function group() {\n        const membership = session.membership;\n        if (!showGroup || !membership) return null;\n        return {\n            name: membership.groupName || membership.code,\n            code: membership.code,\n        };\n    }\n\n    /** \"Uitleg\" opens a dialog instead of going anywhere. */\n    function introOnClick(node: HTMLElement): void {\n        node.addEventListener(\"click\", (event) => {\n            const link = (event.target as HTMLElement).closest(\n                `a[href=\"${INTRO_HREF}\"]`,\n            );\n            if (!link) return;\n            event.preventDefault();\n            openIntroDialog();\n        });\n    }\n\n    if (isEmbedded()) {\n        // One header only: the lesson's. The tool's own links and the view's\n        // controls stay, in a row of their own.\n        const nav = document.createElement(\"nav\");\n        nav.className = \"ss-toolbar ss-toolbar--wrap cocoder-embed-bar__nav\";\n        nav.setAttribute(\"aria-label\", \"Cocoder\");\n        const navLinks = [\n            ...links(),\n            ...(showGroup && session.membership\n                ? [\n                      {\n                          label: t(\"groupLink\"),\n                          href: keepEmbed(\n                              groupPageUrl(session.membership.code),\n                          ),\n                      },\n                  ]\n                : []),\n        ];\n        for (const link of navLinks) {\n            const anchor = document.createElement(\"a\");\n            anchor.className = \"ss-btn ss-btn--sm ss-btn--ghost\";\n            anchor.href = link.href;\n            anchor.textContent = link.label;\n            if (\n                location.hash &&\n                link.href !== INTRO_HREF &&\n                location.hash.startsWith(link.href)\n            ) {\n                anchor.setAttribute(\"aria-current\", \"page\");\n            }\n            nav.append(anchor);\n        }\n        introOnClick(nav);\n        const toolbar = document.createElement(\"div\");\n        toolbar.className = \"cocoder-embed-bar\";\n        toolbar.append(nav, ...actions);\n        return [toolbar];\n    }\n\n    const host = document.getElementById(\"study-app\") ?? document.body;\n    const bar = mountAppbar(host, {\n        app: \"cocoder\",\n        title: \"Cocoder\",\n        lang: getLang(),\n        langs: [\"nl\", \"en\"],\n        wordmarkHref: portalHref(),\n        group: group(),\n        links: links(),\n        actions,\n    });\n    // study-base puts the bar before the shell's `main`; an older study-base\n    // put it into the host: move it out there too.\n    const shellMain = host.closest(\"main\");\n    if (shellMain && bar.element.parentElement !== shellMain.parentElement)\n        shellMain.before(bar.element);\n    currentBar = bar;\n    unsubscribe = session.onChange(() =>\n        bar.update({ group: group(), links: links() }),\n    );\n    introOnClick(bar.element);\n    return [];\n}\n","/** The notice while the server cannot be reached (study-base's\n * 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. \"The server is restarting — still trying…\" with a spinner while the\n * connection is down (\"No internet connection…\" when the device itself is\n * offline), \"Connected again\" for a moment once the app answers again,\n * then gone. It is the first child of the mount's parent (the shell's\n * `<main>`), right before the mount, not in it, so a screen that\n * re-renders keeps it. The polls ask again meanwhile with a growing pause\n * (lib/poll). */\n\nimport {\n    connection as appConnection,\n    connectionNotice,\n    type Connection,\n} from \"@starling-study/study-base/lib/connection\";\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 banner = document.createElement(\"div\");\n    banner.className = \"study-banner study-banner--warn cocoder-connection\";\n    banner.dataset.role = \"connection\";\n    banner.setAttribute(\"role\", \"status\");\n    banner.setAttribute(\"aria-live\", \"polite\");\n    banner.hidden = true;\n    const spinner = document.createElement(\"span\");\n    spinner.className = \"study-running__spinner\";\n    spinner.setAttribute(\"aria-hidden\", \"true\");\n    const text = document.createElement(\"p\");\n    text.className = \"study-banner__text\";\n    banner.append(spinner, text);\n    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","/** A message for the workshop's groups page, where a device goes once it\n * is out of its group: \"you left the group\", \"you were removed from the\n * group\", \"that group does not exist\" — in the page's words (`t(key)` at\n * the caller). Handed to study-base's `setGroupsFlash` (sessionStorage)\n * and shown there once. */\n\nimport { setGroupsFlash } from \"@starling-study/study-base/lib/entry\";\n\ntype Store = Pick<Storage, \"getItem\" | \"setItem\" | \"removeItem\">;\n\n/** Keep a message for the groups page (\"\" forgets it). */\nexport function setFlash(text: string, storage?: Store | null): void {\n    if (storage === undefined) setGroupsFlash(text);\n    else setGroupsFlash(text, storage);\n}\n","/** The names a device joins with, and whether it is still in its group\n * (pure). Who is in the group, and how they are shown, is the workshop's\n * group page (study-base). */\n\n/** The name a participant has until they give one. The shared server\n * requires a non-empty name, so it is a constant, never shown. */\nexport const MEMBER_PLACEHOLDER = \"lid\";\n\n/** Every placeholder an app of the suite joins with when nobody gave a\n * name: cocoder's \"lid\", and the dash of chat, imagine and casette (the\n * same set as study-base's server-side `PLACEHOLDER_NAMES`). The name a\n * device joins with is shared by every app on the origin, so a device that\n * was in imagine first joins cocoder as \"—\": that is no name either. */\nexport const PLACEHOLDER_NAMES: ReadonlySet<string> = new Set([\n    MEMBER_PLACEHOLDER,\n    \"—\",\n    \"–\",\n    \"-\",\n]);\n\n/** Whether a participant gave a name of their own. */\nexport function hasOwnName(name: string | undefined): boolean {\n    const clean = (name ?? \"\").trim();\n    return clean !== \"\" && !PLACEHOLDER_NAMES.has(clean);\n}\n\n/** The name a device joins with: the name the apps on this origin share\n * (`shared`, one typed in chat, say) when a person gave it, else the\n * placeholder. */\nexport function joinName(shared: string | undefined): string {\n    return hasOwnName(shared) ? (shared ?? \"\").trim() : MEMBER_PLACEHOLDER;\n}\n\n/** Whether this device's participant is no longer in its (loaded) group. */\nexport function removedFromGroup(\n    membership: { code: string; participantId: string } | null,\n    group: { code: string; participants: { id: string }[] } | null,\n): boolean {\n    if (!membership || !group || group.code !== membership.code) return false;\n    return !group.participants.some((p) => p.id === membership.participantId);\n}\n","/** The group as far as this app still needs it. Who is in the group, the\n * first name, renaming, adding a name-only member, leaving and switching\n * are the workshop's group page (study-base, `groupPageUrl`), not this\n * app's. What stays here:\n *\n * - the placeholder name leaves the shared name again after a join;\n * - a device whose participant is gone (removed by staff) or whose group is\n *   gone asks where the person is now (study-base's `followOrLeave`: moved\n *   by staff, this page in the new group; else the groups page), never a\n *   dead work view. */\n\nimport type { WorkshopSession } from \"@starling-cloud/sturnia-workshop\";\nimport {\n    followOrLeave,\n    leaveForGroups,\n} from \"@starling-study/study-base/lib/entry\";\n\nimport { WORKSHOP, type CocoderGroup } from \"../api\";\nimport { errorCode } from \"../lib/errors\";\nimport { setFlash } from \"../lib/flash\";\nimport { t, type StringKey } from \"../lib/i18n\";\nimport { MEMBER_PLACEHOLDER, removedFromGroup } from \"../lib/participants\";\nimport { workshopOf } from \"../lib/workshop\";\nimport { forgetGroup, session as appSession } from \"../session\";\n\nexport { MEMBER_PLACEHOLDER };\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(\n    session: WorkshopSession<CocoderGroup> = appSession,\n): void {\n    if (session.userName === MEMBER_PLACEHOLDER) session.setUserName(\"\");\n}\n\n/** Out of group `code`: ask where the person is now (`followOrLeave`:\n * moved by staff, this page in the new group; else the groups page, with\n * `message` shown there once, lib/flash, when given; study-base says\n * \"taken out of the group\" itself). The way back leaves a lesson's\n * `?join=` out, so it does not join the group again. */\nexport function outOfGroup(code: string, message?: StringKey): void {\n    if (message) setFlash(t(message));\n    void followOrLeave(code ? { code } : {});\n}\n\n/** Watch the session for \"this device was removed from its group\" and\n * follow the person (`outOfGroup`). Call once. */\nexport function watchRemoval(\n    session: WorkshopSession<CocoderGroup> = appSession,\n): () => void {\n    return session.onChange(() => {\n        const membership = session.membership;\n        if (!removedFromGroup(membership, session.group)) return;\n        forgetGroup(membership.code);\n        outOfGroup(membership.code);\n    });\n}\n\n/** Load the active group. A group that does not exist (any more), or\n * one this device was taken out of, is forgotten and the person followed\n * (`outOfGroup`); a group of another workshop is left for the groups\n * page: false then (the view stops). */\nexport async function loadGroup(\n    session: WorkshopSession<CocoderGroup> = appSession,\n): Promise<boolean> {\n    const active = session.membership;\n    if (\n        active &&\n        workshopOf(active.code) &&\n        workshopOf(active.code) !== WORKSHOP\n    ) {\n        // A group of another workshop than the page's: not forgotten, but not\n        // this page's either.\n        session.leaveToStart();\n        leaveForGroups();\n        return false;\n    }\n    try {\n        await session.refreshGroup();\n        return true;\n    } catch (error) {\n        const code = errorCode(error);\n        if (code === \"group_not_found\" || code === \"participant_gone\") {\n            const membership = session.membership;\n            if (membership) forgetGroup(membership.code);\n            outOfGroup(\n                membership?.code ?? \"\",\n                code === \"group_not_found\" ? \"errGroupNotFound\" : undefined,\n            );\n            return false;\n        }\n        // Any other trouble (busy, offline): the view shows what it can.\n        return true;\n    }\n}\n","/** The way into the group with the connection banner (components/connection)\n * during the wait at page load.\n *\n * study-base's `requireGroup` (lib/entry) tries again while the server is\n * away (a restart: no connection, or the front's 502/503/504 page) and\n * tells each pause to `onWait`. Here that marks the app's connection down,\n * so the banner says \"The server is restarting — still trying…\" instead\n * of an empty page; once the device is in its group the line is up again\n * (\"Connected again\"). */\n\nimport type {\n    Membership,\n    WorkshopGroup,\n} from \"@starling-cloud/sturnia-workshop\";\nimport {\n    connection as appConnection,\n    type Connection,\n} from \"@starling-study/study-base/lib/connection\";\nimport {\n    requireGroup,\n    type GroupEntryOptions,\n} from \"@starling-study/study-base/lib/entry\";\n\nexport async function enterGroup<G extends WorkshopGroup>(\n    options: GroupEntryOptions<G>,\n    line: Connection = appConnection,\n    enter: (\n        options: GroupEntryOptions<G>,\n    ) => Promise<Membership | null> = requireGroup,\n): Promise<Membership | null> {\n    const membership = await enter({\n        ...options,\n        onWait: (failures, delay) => {\n            line.lost();\n            options.onWait?.(failures, delay);\n        },\n    });\n    if (membership) line.up();\n    return membership;\n}\n","/** The launch parameters a lesson opens this app with. study-syllabus's\n * `ToolBlock` links (or iframes) the page as\n *\n *   /<lang>/cocoder/?prompt=<instruction>&workshop=<slug>\n *\n * - `workshop` is read by the page shell into `data-workshop` (api.ts)\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>, see\n *   `carryWorkshop`), which cannot carry the header.\n * - `prompt` (or `task`, as an embedded lesson names it) is the lesson's\n *   instruction. On boot it moves from the\n *   address into sessionStorage, so it survives the password gate and the\n *   start and group screens (and the page reloads between routes). The\n *   form is template-driven, so nothing is pre-filled: the work view shows\n *   the instruction as a banner above the form until the group dismisses\n *   it. It never generates by itself. */\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-cocoder:launch-prompt\";\n/** Plenty for an instruction; the banner shows it as plain text. */\nexport const PROMPT_MAX = 4000;\n\nexport const {\n    promptFromSearch,\n    stashLaunchPrompt,\n    pendingLaunchPrompt,\n    clearLaunchPrompt,\n} = createLaunchPrompt({ key: PROMPT_KEY, max: PROMPT_MAX });\n","/** Cocoder's boot wiring: which view 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 * - `#/gallery` and `#/view/<id>` need the password only (`requireAccess`);\n * - every other route enters the group once per page load\n *   (`requireGroup`: a `?join=` link's team at once, else the team this\n *   device is in, else off to the groups page with `?next=` this page).\n *   The first name is asked on the workshop's group page, once per group\n *   for every tool, not here;\n * - a device out of its group later on (left, removed, moved by staff)\n *   asks where it went (`leaveForGroups`, wired to study-base's\n *   `followOrLeave`), never back in silently;\n * - after the way in, the workshop's gallery switch is read: a gallery\n *   route of a closed gallery is the \"gallery is off\" panel (`closedPanel`);\n * - the gallery routes are views of their own; `#/work`, `#/`, an old\n *   `#/group` and anything unknown is the work view, under the address\n *   `#/work`. The group itself (members, code, QR code) is the\n *   workshop's group page, the app bar's chip.\n *\n * A move to another top-level route reloads the page (index.ts), so the\n * route runs once per page load. Everything it calls comes in as `deps`,\n * so the wiring is tested without a page (tst/route.test.ts). */\n\nimport type { Route } from \"./router\";\n\nexport type View = \"work\" | \"gallery\" | \"view\";\n\nexport interface RouteDeps {\n    /** A whole-screen panel (closed or unknown workshop) replaced the app,\n     * or the page reloads into another workshop: render nothing. */\n    halted: () => boolean;\n    requireAccess: () => Promise<boolean>;\n    /** Resolves to the membership, or null after leaving for the groups page. */\n    requireGroup: () => Promise<{ code: string } | null>;\n    /** After the join: the placeholder name leaves the shared name again. */\n    afterEntry: () => void;\n    hasMembership: () => boolean;\n    leaveForGroups: () => void;\n    /** Read the gallery switch; true when the \"gallery is off\" panel took\n     * the screen for `view`. */\n    closedPanel: (view: View) => Promise<boolean>;\n    /** Put `#/work` in the address without a new route. */\n    showHomeAddress: () => void;\n    render: (view: View, param: string) => void | Promise<void>;\n}\n\n/** The view of a route: `#/`, an old `#/group` and unknown routes are\n * the work view. */\nexport function viewOf(route: Route): View {\n    return route.name === \"start\" || route.name === \"notfound\"\n        ? \"work\"\n        : route.name;\n}\n\n/** The router's callback for Cocoder (see above). */\nexport function createRoute(deps: RouteDeps): (route: Route) => Promise<void> {\n    let entered = false;\n    return async (route: Route): Promise<void> => {\n        if (deps.halted()) return;\n        const view = viewOf(route);\n        const gallery = view === \"gallery\" || view === \"view\";\n        if (gallery) {\n            if (!(await deps.requireAccess())) return;\n        } else if (!entered) {\n            entered = true;\n            const membership = await deps.requireGroup();\n            deps.afterEntry();\n            if (!membership) return;\n        }\n        if (deps.halted()) return;\n        if (!gallery && !deps.hasMembership()) {\n            deps.leaveForGroups();\n            return;\n        }\n        if (await deps.closedPanel(view)) return;\n        if (deps.halted()) return;\n        if (view === \"work\" && route.name !== \"work\") deps.showHomeAddress();\n        return deps.render(view, route.param);\n    };\n}\n","/**\n * Sandboxed preview of untrusted HTML.\n *\n * An iframe whose srcdoc is set without a sandbox — or with\n * `allow-same-origin` — is same-origin with this page and can read and\n * rewrite the whole app. So the sandbox attribute is applied here, in code,\n * rather than trusted to the markup, and `allow-same-origin` is never\n * granted: the framed document stays in an opaque origin with no access to\n * cocoder's cookies, storage or DOM.\n *\n * The same opaque origin is what lets browsers put each frame in its own\n * process, which is why the gallery's tiles are sandboxed too.\n */\nexport const EDIT_SANDBOX = \"allow-scripts\";\nexport const TILE_SANDBOX = \"\"; // gallery thumbnails: render, but no scripts\n\nconst DEBOUNCE_MS = 250;\n\nexport interface Preview {\n    render(code: string): void;\n    schedule(code: string): void;\n    cancel(): void;\n}\n\nexport function createPreview(\n    iframe: HTMLIFrameElement,\n    sandbox: string = EDIT_SANDBOX,\n): Preview {\n    iframe.setAttribute(\"sandbox\", sandbox);\n    let timer: number | undefined;\n\n    function render(code: string): void {\n        window.clearTimeout(timer);\n        iframe.srcdoc = code;\n    }\n\n    return {\n        render,\n        schedule(code) {\n            window.clearTimeout(timer);\n            timer = window.setTimeout(() => render(code), DEBOUNCE_MS);\n        },\n        cancel() {\n            window.clearTimeout(timer);\n        },\n    };\n}\n","/** The credits of a published page next to its group's name: shown only\n * when they add something (pages published before 2026-10 carry the group\n * name as their credits, which showed the name twice). */\nexport function extraCredits(groupName: string, credits: string): string {\n    const clean = (credits ?? \"\").trim();\n    return clean.toLowerCase() === (groupName ?? \"\").trim().toLowerCase()\n        ? \"\"\n        : clean;\n}\n","/** The gallery star's text: a filled star when it is on (or just a count\n * to show), an outline when the participant can still give it; the count is\n * left out at zero. */\nexport function starLabel(count: number, on: boolean): string {\n    const star = on ? \"★\" : \"☆\";\n    return count > 0 ? `${star} ${count}` : star;\n}\n","/** Asking the server again and again, one request at a time.\n *\n * A chain of timeouts instead of a `setInterval`: the next round goes out\n * a pause after the last one came back, so a server that holds requests\n * while it restarts never piles them up. The pause is `intervalMs` while\n * the server answers and the growing pause of study-base's lib/connection\n * (2 s, 4 s, 8 s, then 15 s) while it does not; the first answer after\n * that (any request of the app, an action too) starts a round at once.\n * A round that fails is not told here: the client already marked the line\n * (and the banner says so). `paused` skips a round (a hidden tab). */\n\nimport {\n    connection as appConnection,\n    type Connection,\n} from \"@starling-study/study-base/lib/connection\";\n\nexport interface PollOptions {\n    /** One round; the next is scheduled once it settles. */\n    run: () => Promise<unknown>;\n    /** The pause after a round while the server answers. */\n    intervalMs: number;\n    /** Whether to skip a round (default: never). */\n    paused?: () => boolean;\n    connection?: Connection;\n    setTimer?: (fn: () => void, ms: number) => unknown;\n    clearTimer?: (id: unknown) => void;\n}\n\nexport interface Poll {\n    /** A round now (unless one is in flight), then on at the pace. */\n    now(): void;\n    stop(): void;\n}\n\nexport function startPoll(options: PollOptions): Poll {\n    const line = options.connection ?? appConnection;\n    const setTimer =\n        options.setTimer ??\n        ((fn: () => void, ms: number) => setTimeout(fn, ms));\n    const clearTimer =\n        options.clearTimer ??\n        ((id: unknown) => clearTimeout(id as ReturnType<typeof setTimeout>));\n    let timer: unknown = null;\n    let stopped = false;\n    let inFlight = false;\n\n    const clear = (): void => {\n        if (timer !== null) clearTimer(timer);\n        timer = null;\n    };\n\n    const schedule = (): void => {\n        clear();\n        if (stopped) return;\n        const pause = line.down ? line.retryDelay() : options.intervalMs;\n        timer = setTimer(() => void round(), pause);\n    };\n\n    async function round(): Promise<void> {\n        timer = null;\n        if (stopped || inFlight) return;\n        if (options.paused?.()) {\n            schedule();\n            return;\n        }\n        inFlight = true;\n        try {\n            await options.run();\n        } catch {\n            // The client marked the line; the next round asks again.\n        } finally {\n            inFlight = false;\n            schedule();\n        }\n    }\n\n    const now = (): void => {\n        if (stopped || inFlight) return;\n        clear();\n        void round();\n    };\n    const offRestored = line.onRestored(now);\n    schedule();\n\n    return {\n        now,\n        stop: () => {\n            stopped = true;\n            clear();\n            offRestored();\n        },\n    };\n}\n","/**\n * The load state of one gallery tile. `request` numbers the tile's preview\n * requests: a release or a newer request makes an older one stale, so a\n * stale answer (success or failure) never touches the tile.\n */\nexport interface TileLoad {\n    loaded: boolean;\n    request: number;\n}\n\nexport function newTileLoad(): TileLoad {\n    return { loaded: false, request: 0 };\n}\n\n/** Start loading: the request's token, or `null` when already loaded. */\nexport function beginTileLoad(state: TileLoad): number | null {\n    if (state.loaded) return null;\n    state.loaded = true;\n    return ++state.request;\n}\n\n/** Drop the content: true when there was any to drop. Any request still\n * in flight is stale from now on. */\nexport function releaseTileLoad(state: TileLoad): boolean {\n    state.request++;\n    if (!state.loaded) return false;\n    state.loaded = false;\n    return true;\n}\n\n/** A request answered: true when its HTML should be shown. A failed\n * current request lets the tile load again next time it comes into view;\n * a stale one changes nothing. */\nexport function settleTileLoad(\n    state: TileLoad,\n    token: number,\n    ok: boolean,\n): boolean {\n    if (token !== state.request) return false;\n    if (!ok) state.loaded = false;\n    return ok;\n}\n","import { api, type GalleryEntry } from \"../api\";\nimport { applyStoredTheme, createHeader } from \"../components/chrome\";\nimport { TILE_SANDBOX } from \"../components/preview\";\nimport { extraCredits } from \"../lib/credits\";\nimport { clear, el } from \"../lib/dom\";\nimport { starLabel } from \"../lib/favourite\";\nimport { t } from \"../lib/i18n\";\nimport { startPoll } from \"../lib/poll\";\nimport { currentRoute, href } from \"../lib/router\";\nimport {\n    beginTileLoad,\n    newTileLoad,\n    releaseTileLoad,\n    settleTileLoad,\n    type TileLoad,\n} from \"../lib/tileload\";\nimport { session } from \"../session\";\n\nconst REFRESH_MS = 30_000;\n// Load a little before a tile scrolls into view, drop it well after it leaves,\n// so scrolling back and forth does not thrash.\nconst LOAD_MARGIN = \"600px\";\nconst KEEP_MARGIN = \"1800px\";\n\ninterface Tile {\n    entry: GalleryEntry;\n    frame: HTMLIFrameElement;\n    load: TileLoad;\n}\n\nexport async function renderGallery(root: HTMLElement): Promise<void> {\n    applyStoredTheme();\n\n    const params = currentRoute().query;\n    // `?p=<publicId>` (set after a publish) highlights that page; an older\n    // `?g=<code>` link highlights the participant's own group's page, which the\n    // server marks `own` (the gallery never hands out group codes).\n    const highlightId = params.get(\"p\");\n    const highlightOwn = params.has(\"g\");\n    const highlightAny = Boolean(highlightId) || highlightOwn;\n    let scrolled = false;\n\n    const grid = el(\"ul\", { class: \"study-gallery\" });\n    const empty = el(\"div\", {\n        class: \"ss-state ss-state--empty\",\n        hidden: true,\n    });\n    const count = el(\"p\", { class: \"ss-hint\", hidden: true });\n\n    const refreshButton = el(\n        \"button\",\n        { class: \"ss-btn ss-btn--sm\", type: \"button\" },\n        t(\"refresh\"),\n    );\n    const header = createHeader({ actions: [refreshButton] });\n\n    root.replaceChildren(\n        ...header,\n        el(\"div\", { class: \"study-page\" }, count, empty, grid),\n    );\n\n    const tiles = new Map<string, Tile>();\n\n    // srcdoc has no network request to defer, so loading=\"lazy\" cannot be\n    // relied on here: the content is only assigned once a tile approaches the\n    // viewport, and released again when it is far away. Every frame is\n    // sandboxed without allow-same-origin, which both isolates the untrusted\n    // markup and lets the browser give each frame its own process.\n    const loader = new IntersectionObserver(\n        (records) => {\n            for (const record of records) {\n                if (!record.isIntersecting) continue;\n                const id =\n                    (record.target as HTMLElement).dataset.publicId ?? \"\";\n                const tile = tiles.get(id);\n                if (!tile) continue;\n                const token = beginTileLoad(tile.load);\n                if (token === null) continue;\n                // Released, or loaded anew, while the request was in flight:\n                // its answer is stale and leaves the frame alone.\n                void api\n                    .galleryHtml(id)\n                    .then(({ html }) => {\n                        if (settleTileLoad(tile.load, token, true))\n                            tile.frame.srcdoc = html;\n                    })\n                    .catch(() => {\n                        settleTileLoad(tile.load, token, false);\n                    });\n            }\n        },\n        { rootMargin: LOAD_MARGIN },\n    );\n\n    const releaser = new IntersectionObserver(\n        (records) => {\n            for (const record of records) {\n                if (record.isIntersecting) continue;\n                const id =\n                    (record.target as HTMLElement).dataset.publicId ?? \"\";\n                const tile = tiles.get(id);\n                if (!tile || !releaseTileLoad(tile.load)) continue;\n                tile.frame.removeAttribute(\"srcdoc\");\n            }\n        },\n        { rootMargin: KEEP_MARGIN },\n    );\n\n    // The star, in the corner of the tile: a toggle for a participant looking\n    // at another group's page, a plain count for guests and on the\n    // participant's own page.\n    function buildStar(entry: GalleryEntry): HTMLElement | null {\n        const token = session.membership?.token;\n        if (!token || entry.own) {\n            return entry.favourites\n                ? el(\"span\", {\n                      class: \"ss-badge cocoder-gallery-star\",\n                      text: starLabel(entry.favourites, true),\n                      title: `${entry.favourites} ${t(\"favourites\")}`,\n                  })\n                : null;\n        }\n        const button = el(\"button\", {\n            class: \"ss-btn ss-btn--sm cocoder-gallery-star\",\n            type: \"button\",\n        });\n        let on = Boolean(entry.favourited);\n        const paint = (count: number): void => {\n            button.textContent = starLabel(count, on);\n            button.setAttribute(\"aria-pressed\", String(on));\n            button.setAttribute(\n                \"aria-label\",\n                `${t(on ? \"unfavourite\" : \"favourite\")} (${count})`,\n            );\n            button.classList.toggle(\"ss-btn--primary\", on);\n        };\n        paint(entry.favourites);\n        button.addEventListener(\"click\", async () => {\n            button.disabled = true;\n            try {\n                const result = await api.setFavourite(\n                    entry.publicId,\n                    token,\n                    !on,\n                );\n                on = result.favourited;\n                paint(result.favourites);\n            } catch {\n                // A superseded or hidden page: the next refresh sorts it out.\n                void refresh();\n            } finally {\n                button.disabled = false;\n            }\n        });\n        return button;\n    }\n\n    function buildTile(entry: GalleryEntry): HTMLElement {\n        const frame = el(\"iframe\", {\n            class: \"study-gallery__frame\",\n            sandbox: TILE_SANDBOX,\n            loading: \"lazy\",\n            title: `${entry.title || t(\"untitled\")} ${t(\"by\")} ${entry.groupName}`,\n            tabindex: -1,\n        }) as HTMLIFrameElement;\n\n        const isHighlighted = highlightId\n            ? entry.publicId === highlightId\n            : highlightOwn && entry.own === true;\n\n        const card = el(\n            \"li\",\n            {\n                class: `study-gallery__card${isHighlighted ? \" study-gallery__card--highlight\" : \"\"}`,\n                \"data-public-id\": entry.publicId,\n            },\n            el(\n                \"div\",\n                { class: \"study-gallery__stage\" },\n                frame,\n                // Tiles are previews, not playgrounds: this overlay swallows clicks\n                // so the whole card stays one link target — into the full-page\n                // viewer (with version switcher), not the chrome-less /raw view.\n                el(\"a\", {\n                    class: \"study-gallery__hit\",\n                    href: href(`view/${entry.publicId}`),\n                    \"aria-label\": `${entry.title || t(\"untitled\")} ${t(\"by\")} ${entry.groupName}`,\n                }),\n            ),\n            el(\n                \"div\",\n                { class: \"study-gallery__meta\" },\n                el(\"span\", {\n                    class: \"study-gallery__title\",\n                    text: entry.title || t(\"untitled\"),\n                }),\n                entry.groupName\n                    ? el(\"span\", {\n                          class: \"study-gallery__name\",\n                          text: entry.groupName,\n                      })\n                    : null,\n                extraCredits(entry.groupName, entry.credits)\n                    ? el(\"span\", {\n                          class: \"study-gallery__credits\",\n                          text: extraCredits(entry.groupName, entry.credits),\n                      })\n                    : null,\n            ),\n            buildStar(entry),\n        );\n\n        tiles.set(entry.publicId, { entry, frame, load: newTileLoad() });\n        loader.observe(card);\n        releaser.observe(card);\n        return card;\n    }\n\n    async function refresh(): Promise<void> {\n        const entries = await api.gallery(session.membership?.token);\n        count.textContent = entries.length\n            ? `${entries.length} ${entries.length === 1 ? t(\"pagePublished\") : t(\"pagesPublished\")}`\n            : \"\";\n        count.hidden = entries.length === 0;\n        empty.hidden = entries.length > 0;\n\n        const seen = new Set(entries.map((entry) => entry.publicId));\n        for (const [id] of tiles) {\n            if (!seen.has(id)) tiles.delete(id);\n        }\n\n        clear(empty);\n        if (entries.length === 0) {\n            empty.append(\n                el(\"h2\", { class: \"ss-state__title\", text: t(\"noPagesYet\") }),\n                el(\"p\", {\n                    class: \"ss-state__message\",\n                    text: session.membership\n                        ? t(\"noPagesHintMember\")\n                        : t(\"noPagesHintGuest\"),\n                }),\n            );\n        }\n\n        // Rebuild in one pass — the list is small and order changes with each\n        // publish, so diffing would cost more than it saves. The old cards are\n        // unobserved first: observers keep their targets alive (a wall display\n        // refreshing every 30 s would pile up detached tiles), and a detached\n        // card's final \"not intersecting\" record would otherwise release the\n        // new tile that now owns its publicId.\n        for (const card of Array.from(grid.children)) {\n            loader.unobserve(card);\n            releaser.unobserve(card);\n        }\n        clear(grid);\n        for (const entry of entries) grid.append(buildTile(entry));\n\n        if (!scrolled && highlightAny) {\n            const highlighted = grid.querySelector(\n                \".study-gallery__card--highlight\",\n            );\n            if (highlighted) {\n                highlighted.scrollIntoView({\n                    behavior: \"smooth\",\n                    block: \"center\",\n                });\n                scrolled = true;\n            }\n        }\n    }\n\n    await refresh();\n\n    // One refresh at a time, skipped while the tab is hidden, with a\n    // growing pause while the server cannot be reached (lib/poll).\n    const poll = startPoll({\n        run: refresh,\n        intervalMs: REFRESH_MS,\n        paused: () => document.visibilityState !== \"visible\",\n    });\n    window.addEventListener(\"pagehide\", () => poll.stop(), {\n        once: true,\n    });\n    refreshButton.addEventListener(\"click\", () => void refresh());\n}\n","/** #/view/<publicId> — the gallery's full-page viewer: one published page,\n * full-height, with a switcher over every published version of that\n * group's page (the newest is current; older ones stay viewable).\n *\n * The tiles in the gallery are cropped previews; this is where a page is\n * meant to be *seen*. raw/<publicId> (API) stays the chrome-less full-screen\n * escape hatch. */\n\nimport { api, rawUrl, type ViewerInfo } from \"../api\";\nimport { applyStoredTheme, createHeader } from \"../components/chrome\";\nimport { EDIT_SANDBOX } from \"../components/preview\";\nimport { extraCredits } from \"../lib/credits\";\nimport { el, messageScreen } from \"../lib/dom\";\nimport { t } from \"../lib/i18n\";\nimport { href } from \"../lib/router\";\n\nexport async function renderViewer(\n    root: HTMLElement,\n    publicId: string,\n): Promise<void> {\n    applyStoredTheme();\n\n    let info: ViewerInfo;\n    try {\n        info = await api.viewerInfo(publicId);\n    } catch {\n        root.replaceChildren(\n            messageScreen(t(\"viewerNotFound\"), t(\"viewerNotFoundHint\"), {\n                href: href(\"gallery\"),\n                label: t(\"backToGallery\"),\n            }),\n        );\n        return;\n    }\n\n    const frame = el(\"iframe\", {\n        class: \"study-preview__frame\",\n        sandbox: EDIT_SANDBOX,\n        title: info.title || t(\"untitled\"),\n    }) as HTMLIFrameElement;\n\n    const rawLink = el(\n        \"a\",\n        { class: \"ss-btn ss-btn--sm\", target: \"_blank\", rel: \"noreferrer\" },\n        t(\"openFullScreen\"),\n    ) as HTMLAnchorElement;\n\n    async function showVersion(id: string): Promise<void> {\n        rawLink.href = rawUrl(id);\n        try {\n            const { html } = await api.galleryHtml(id);\n            frame.srcdoc = html;\n        } catch {\n            frame.srcdoc = `<p style=\"font-family: sans-serif; padding: 2rem\">${t(\"viewerNotFoundHint\")}</p>`;\n        }\n    }\n\n    // The version switcher: the theme's segmented choice, newest first and\n    // numbered so the newest is the highest.\n    const versions = el(\"div\", {\n        class: \"study-segmented\",\n        role: \"radiogroup\",\n        \"aria-label\": t(\"versions\"),\n    });\n    info.versions.forEach((version, index) => {\n        const number = info.versions.length - index;\n        const input = el(\"input\", {\n            type: \"radio\",\n            name: \"version\",\n            value: version.publicId,\n        }) as HTMLInputElement;\n        input.checked = version.publicId === publicId;\n        input.addEventListener(\n            \"change\",\n            () => void showVersion(version.publicId),\n        );\n        versions.append(\n            el(\n                \"label\",\n                { title: new Date(version.createdAt).toLocaleString() },\n                input,\n                `${t(\"version\")} ${number}${version.current ? ` (${t(\"newest\")})` : \"\"}`,\n            ),\n        );\n    });\n\n    const header = createHeader();\n    const byline = [info.groupName, extraCredits(info.groupName, info.credits)]\n        .filter(Boolean)\n        .join(\" · \");\n\n    const toolbar = el(\n        \"div\",\n        { class: \"study-preview__bar\" },\n        el(\"strong\", { text: info.title || t(\"untitled\") }),\n        byline ? el(\"span\", { class: \"ss-muted\", text: byline }) : null,\n        info.versions.length > 1 ? versions : null,\n        rawLink,\n        info.description\n            ? el(\"span\", { class: \"ss-muted\", text: info.description })\n            : null,\n    );\n\n    // The page fills what the bars leave of the viewport (from 768px up).\n    root.classList.add(\"study-app--fill\");\n    root.replaceChildren(\n        ...header,\n        toolbar,\n        el(\"div\", { class: \"study-preview\" }, frame),\n    );\n    await showVersion(publicId);\n}\n","import type { PromptTemplate, Question, QuestionOption } from \"../api\";\nimport { el } from \"../lib/dom\";\nimport { countWords, pick, t } from \"../lib/i18n\";\n\nexport type Answers = Record<string, string | string[]>;\n\nexport interface PromptForm {\n    element: HTMLFormElement;\n    getAnswers(): Answers;\n    /** Update one field from outside (another group member's input) without\n     * firing onChange. Skipped when that field currently has focus. */\n    setAnswer(key: string, value: string | string[]): void;\n    /** Mark every empty required field (`aria-invalid` and a message under\n     * it); true when there is none. */\n    validate(): boolean;\n    /** The keys of the required fields that are still empty, in form order. */\n    missing(): string[];\n    /** Bring a field into view and put the focus in it. */\n    focusField(key: string): void;\n}\n\n/** The keys of a template's questions that may stay empty: their prompt\n * slots become empty text (lib/interpolate). */\nexport function optionalKeys(\n    template: Pick<PromptTemplate, \"questions\">,\n): Set<string> {\n    return new Set(\n        template.questions.filter((q) => !q.required).map((q) => q.key),\n    );\n}\n\n/** Whether an answer counts as not filled in. */\nexport function isEmptyAnswer(value: unknown): boolean {\n    return (\n        value === undefined ||\n        value === null ||\n        (typeof value === \"string\" && value.trim() === \"\") ||\n        (Array.isArray(value) && value.length === 0)\n    );\n}\n\nfunction defaultFor(question: Question, saved: Answers): string | string[] {\n    const previous = saved[question.key];\n    if (previous !== undefined) return previous;\n    if (question.default !== undefined) return question.default;\n    return question.type === \"checkbox\" ? [] : \"\";\n}\n\n/** The participant sees the localized label; the answer carries `value`. */\nfunction optionLabel(option: QuestionOption): string {\n    return pick({\n        nl: option.nl ?? option.value,\n        en: option.en ?? option.value,\n    });\n}\n\n/** Live \"n / N words\" counter for minWords textareas. Soft: it is in the\n * warning colour below the target but never blocks — a group must not get stuck\n * on a word count mid-workshop. */\nfunction wordCounter(\n    question: Question,\n    getValue: () => string,\n): { element: HTMLElement; update(): void } {\n    const node = el(\"p\", { class: \"study-wordcount\", \"aria-live\": \"polite\" });\n    function update(): void {\n        const words = countWords(getValue());\n        const enough = words >= (question.minWords ?? 0);\n        node.textContent = `${words} / ${question.minWords} ${t(\"words\")}`;\n        node.classList.toggle(\"study-wordcount--short\", !enough);\n    }\n    update();\n    return { element: node, update };\n}\n\n/** Help text: plain lines become paragraphs; runs of lines starting with\n * \"- \" or \"1) \" become a real <ul>/<ol>. Keeps the YAML readable and the\n * on-screen explanation scannable. The theme's `.study-help` is a one-line\n * hint; `.cocoder-instructions` (scss/_app.scss) sets it as running text. */\nexport function renderHelp(text: string): HTMLElement {\n    const host = el(\"div\", { class: \"study-help cocoder-instructions\" });\n    const lines = text\n        .split(\"\\n\")\n        .map((l) => l.trim())\n        .filter(Boolean);\n    let list: HTMLElement | null = null;\n    for (const line of lines) {\n        const bullet = /^[-•]\\s+/.test(line);\n        const numbered = /^\\d+[).]\\s+/.test(line);\n        if (bullet || numbered) {\n            const tag = numbered ? \"ol\" : \"ul\";\n            if (!list || list.tagName.toLowerCase() !== tag) {\n                list = el(tag, {});\n                host.append(list);\n            }\n            list.append(\n                el(\"li\", { text: line.replace(/^([-•]|\\d+[).])\\s+/, \"\") }),\n            );\n        } else {\n            list = null;\n            host.append(el(\"p\", { text: line }));\n        }\n    }\n    return host;\n}\n\n/**\n * Builds the participant-facing form from a template's `questions` list —\n * the same YAML file that supplies the prompt text, so adding a question\n * never means touching this code.\n */\nexport function createPromptForm(\n    template: PromptTemplate,\n    saved: Answers,\n    onChange: () => void,\n): PromptForm {\n    const answers: Answers = {};\n    const fields: {\n        question: Question;\n        field: HTMLElement;\n        error: HTMLElement;\n        control: HTMLElement;\n    }[] = [];\n    const setters = new Map<string, (value: string | string[]) => void>();\n\n    const form = el(\"form\", { class: \"study-form study-form--wide\" });\n    form.addEventListener(\"submit\", (event) => event.preventDefault());\n\n    for (const question of template.questions) {\n        const initial = defaultFor(question, saved);\n        answers[question.key] = initial;\n\n        const id = `q-${question.key}`;\n        // Added to the field only while there is something to say: the theme\n        // marks a field that holds a `.study-field-error` as invalid.\n        const error = el(\"p\", {\n            class: \"study-field-error\",\n            id: `${id}-error`,\n        });\n        const label = el(\n            \"label\",\n            { class: \"ss-label\", for: id, id: `${id}-label` },\n            pick(question.label),\n            question.required\n                ? el(\"span\", { class: \"study-required\", text: \" *\" })\n                : null,\n        );\n\n        let control: HTMLElement;\n        let counter: { element: HTMLElement; update(): void } | null = null;\n\n        switch (question.type) {\n            case \"textarea\": {\n                const textarea = el(\"textarea\", {\n                    class: \"ss-textarea\",\n                    id,\n                    rows: question.minWords ? 7 : 4,\n                    placeholder: pick(question.placeholder),\n                });\n                textarea.value = String(initial);\n                if (question.minWords) {\n                    counter = wordCounter(question, () => textarea.value);\n                }\n                textarea.addEventListener(\"input\", () => {\n                    answers[question.key] = textarea.value;\n                    counter?.update();\n                    onChange();\n                });\n                setters.set(question.key, (value) => {\n                    if (document.activeElement === textarea) return;\n                    textarea.value = String(value);\n                    counter?.update();\n                });\n                control = textarea;\n                break;\n            }\n\n            case \"select\": {\n                const select = el(\"select\", { class: \"ss-select\", id });\n                select.append(el(\"option\", { value: \"\" }, t(\"choose\")));\n                for (const option of question.options ?? []) {\n                    select.append(\n                        el(\n                            \"option\",\n                            { value: option.value },\n                            optionLabel(option),\n                        ),\n                    );\n                }\n                select.value = String(initial);\n                select.addEventListener(\"change\", () => {\n                    answers[question.key] = select.value;\n                    onChange();\n                });\n                setters.set(question.key, (value) => {\n                    if (document.activeElement === select) return;\n                    select.value = String(value);\n                });\n                control = select;\n                break;\n            }\n\n            case \"radio\": {\n                const group = el(\"div\", {\n                    class: \"study-choices\",\n                    role: \"radiogroup\",\n                    id,\n                    \"aria-labelledby\": `${id}-label`,\n                });\n                for (const option of question.options ?? []) {\n                    const input = el(\"input\", {\n                        class: \"ss-radio\",\n                        type: \"radio\",\n                        name: question.key,\n                        value: option.value,\n                    });\n                    input.checked = initial === option.value;\n                    input.addEventListener(\"change\", () => {\n                        answers[question.key] = option.value;\n                        onChange();\n                    });\n                    group.append(\n                        el(\n                            \"label\",\n                            { class: \"ss-choice\" },\n                            input,\n                            el(\"span\", {}, optionLabel(option)),\n                        ),\n                    );\n                }\n                setters.set(question.key, (value) => {\n                    if (group.contains(document.activeElement)) return;\n                    for (const input of group.querySelectorAll<HTMLInputElement>(\n                        \"input\",\n                    )) {\n                        input.checked = input.value === String(value);\n                    }\n                });\n                control = group;\n                break;\n            }\n\n            case \"checkbox\": {\n                const group = el(\"div\", {\n                    class: \"study-choices\",\n                    role: \"group\",\n                    id,\n                    \"aria-labelledby\": `${id}-label`,\n                });\n                const selected = new Set(\n                    Array.isArray(initial) ? initial : [],\n                );\n                answers[question.key] = [...selected];\n                for (const option of question.options ?? []) {\n                    const input = el(\"input\", {\n                        class: \"ss-checkbox\",\n                        type: \"checkbox\",\n                        value: option.value,\n                    });\n                    input.checked = selected.has(option.value);\n                    input.addEventListener(\"change\", () => {\n                        if (input.checked) selected.add(option.value);\n                        else selected.delete(option.value);\n                        answers[question.key] = [...selected];\n                        onChange();\n                    });\n                    group.append(\n                        el(\n                            \"label\",\n                            { class: \"ss-choice\" },\n                            input,\n                            el(\"span\", {}, optionLabel(option)),\n                        ),\n                    );\n                }\n                setters.set(question.key, (value) => {\n                    if (group.contains(document.activeElement)) return;\n                    selected.clear();\n                    for (const v of Array.isArray(value) ? value : [])\n                        selected.add(v);\n                    for (const input of group.querySelectorAll<HTMLInputElement>(\n                        \"input\",\n                    )) {\n                        input.checked = selected.has(input.value);\n                    }\n                });\n                control = group;\n                break;\n            }\n\n            default: {\n                const input = el(\"input\", {\n                    class: \"ss-input\",\n                    type: \"text\",\n                    id,\n                    placeholder: pick(question.placeholder),\n                });\n                input.value = String(initial);\n                input.addEventListener(\"input\", () => {\n                    answers[question.key] = input.value;\n                    onChange();\n                });\n                setters.set(question.key, (value) => {\n                    if (document.activeElement === input) return;\n                    input.value = String(value);\n                });\n                control = input;\n            }\n        }\n\n        const help = pick(question.help);\n        const example = pick(question.example);\n\n        const field = el(\n            \"div\",\n            { class: \"ss-field\" },\n            label,\n            help ? renderHelp(help) : null,\n            control,\n            counter?.element ?? null,\n            example\n                ? el(\n                      \"p\",\n                      { class: \"ss-hint\" },\n                      el(\"strong\", {}, `${t(\"example\")}: `),\n                      example,\n                  )\n                : null,\n        );\n        form.append(field);\n        const entry = { question, field, error, control };\n        fields.push(entry);\n        if (question.required) control.setAttribute(\"aria-required\", \"true\");\n        // Once marked, a field is checked again as it is filled in.\n        const recheck = (): void => {\n            if (control.getAttribute(\"aria-invalid\") === \"true\") mark(entry);\n        };\n        control.addEventListener(\"input\", recheck);\n        control.addEventListener(\"change\", recheck);\n    }\n\n    /** Mark one field as it is now; true when it is fine. */\n    function mark(entry: (typeof fields)[number]): boolean {\n        const { question, field, error, control } = entry;\n        if (question.required && isEmptyAnswer(answers[question.key])) {\n            error.textContent = t(\"required\");\n            field.append(error);\n            control.setAttribute(\"aria-invalid\", \"true\");\n            control.setAttribute(\"aria-describedby\", error.id);\n            return false;\n        }\n        error.remove();\n        control.removeAttribute(\"aria-invalid\");\n        control.removeAttribute(\"aria-describedby\");\n        return true;\n    }\n\n    return {\n        element: form,\n        getAnswers: () => ({ ...answers }),\n        setAnswer(key, value) {\n            const setter = setters.get(key);\n            if (!setter) return;\n            answers[key] = Array.isArray(value) ? [...value] : value;\n            setter(value);\n        },\n        validate() {\n            let ok = true;\n            for (const entry of fields) ok = mark(entry) && ok;\n            return ok;\n        },\n        missing() {\n            return fields\n                .filter(\n                    ({ question }) =>\n                        question.required &&\n                        isEmptyAnswer(answers[question.key]),\n                )\n                .map(({ question }) => question.key);\n        },\n        focusField(key) {\n            const entry = fields.find(({ question }) => question.key === key);\n            if (!entry) return;\n            const target = entry.control.matches(\"input, textarea, select\")\n                ? entry.control\n                : entry.control.querySelector<HTMLElement>(\"input\");\n            entry.field.scrollIntoView({\n                block: \"center\",\n                behavior: \"smooth\",\n            });\n            target?.focus({ preventScroll: true });\n        },\n    };\n}\n","import { getLang, type Lang } from \"./i18n\";\n\nexport async function formatHtml(code: string): Promise<string> {\n    // Loaded on demand — js-beautify is only needed when Format is pressed.\n    const { html_beautify } = await import(\"js-beautify\");\n    return html_beautify(code, {\n        indent_size: 2,\n        wrap_line_length: 120,\n        preserve_newlines: true,\n        max_preserve_newlines: 2,\n        end_with_newline: true,\n    });\n}\n\nexport function readFileAsText(file: File): Promise<string> {\n    return new Promise((resolve, reject) => {\n        const reader = new FileReader();\n        reader.onload = () => resolve(String(reader.result ?? \"\"));\n        reader.onerror = () => reject(reader.error);\n        reader.readAsText(file);\n    });\n}\n\nexport async function copyToClipboard(text: string): Promise<boolean> {\n    try {\n        await navigator.clipboard.writeText(text);\n        return true;\n    } catch {\n        return false;\n    }\n}\n\nexport function downloadHtml(code: string, name: string): void {\n    const stamp = new Date().toISOString().replace(/[:T]/g, \"-\").slice(0, 19);\n    const blob = new Blob([code], { type: \"text/html\" });\n    const url = URL.createObjectURL(blob);\n    const link = document.createElement(\"a\");\n    link.href = url;\n    link.download = `${name}-${stamp}.html`;\n    link.click();\n    window.setTimeout(() => URL.revokeObjectURL(url), 10_000);\n}\n\n/** The starter page's words per language (the editor's first content in\n * the paste flow). */\nconst STARTER_TEXT: Record<\n    Lang,\n    { title: string; heading: string; body: string }\n> = {\n    nl: {\n        title: \"Mijn pagina\",\n        heading: \"Plak hier je gegenereerde HTML\",\n        body: `Vervang alles in deze editor door het ene HTML-bestand dat je\n       coding agent maakte en publiceer het daarna in de galerij.`,\n    },\n    en: {\n        title: \"My page\",\n        heading: \"Paste your generated HTML here\",\n        body: `Replace everything in this editor with the single HTML file your\n       coding agent produced, then publish it to the gallery.`,\n    },\n};\n\n/** The paste flow's starter page, in the page's language. */\nexport function starterHtml(lang: Lang = getLang()): string {\n    const text = STARTER_TEXT[lang];\n    return `<!doctype html>\n<html lang=\"${lang}\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <title>${text.title}</title>\n  </head>\n  <body>\n    <h1>${text.heading}</h1>\n    <p>${text.body}</p>\n  </body>\n</html>\n`;\n}\n","/** Helpers for the in-app generation flow (roadmap 0.6). Pure functions,\n * so the progress card's decisions are unit-testable without a DOM. */\n\n/** The document inside the model's streamed reply so far: the fence and\n * any prose before it are dropped, everything from the document start is\n * rendered as-is (a half-finished page renders fine in a sandbox). `null`\n * until the document has started. */\nexport function documentFromPartial(text: string): string | null {\n    const start = text.search(/<!doctype\\s+html|<html[\\s>]/i);\n    if (start === -1) return null;\n    const html = text.slice(start);\n    // Drop a closing fence that may already have streamed in after </html>.\n    const end = html.toLowerCase().lastIndexOf(\"</html>\");\n    return end === -1 ? html : html.slice(0, end + \"</html>\".length);\n}\n\n/** A half-streamed page with an open <style> or <script> renders as a\n * blank sheet (the browser is still inside the block), so the live\n * preview closes any block that has no closing tag yet. The editor shows\n * the text as it is; only what goes into the iframe is patched. */\nexport function renderablePartial(html: string): string {\n    let out = html;\n    for (const tag of [\"script\", \"style\"]) {\n        const opens =\n            out.match(new RegExp(`<${tag}[\\\\s>]`, \"gi\"))?.length ?? 0;\n        const closes =\n            out.match(new RegExp(`</${tag}\\\\s*>`, \"gi\"))?.length ?? 0;\n        if (opens > closes) out += `\\n</${tag}>`;\n    }\n    return out;\n}\n\n/** Whole seconds since `since`, never negative (clock skew between the\n * server's timestamps and the device is common on phones). */\nexport function elapsedSeconds(\n    since: number,\n    now: number = Date.now(),\n): number {\n    return Math.max(0, Math.round((now - since) / 1000));\n}\n\n/** Which of the client's messages a failed *start* maps to, by HTTP\n * status. The server's own detail text wins where it is participant-\n * facing (400 lists the missing fields, 503 says why it is off). */\nexport function startFailureKey(\n    status: number,\n):\n    | \"genErrorRunning\"\n    | \"genErrorLimit\"\n    | \"detailOrForm\"\n    | \"detailOrPaused\"\n    | \"genErrorUpstream\" {\n    if (status === 409) return \"genErrorRunning\";\n    if (status === 429) return \"genErrorLimit\";\n    if (status === 400) return \"detailOrForm\";\n    if (status === 503) return \"detailOrPaused\";\n    return \"genErrorUpstream\";\n}\n\n/** The text key for a failed generation's `error_code` (the server's\n * `truncated`, `no_html`, `too_large`, `upstream`, `timeout`, `internal`,\n * or the app's own `stale`). An unknown or missing code reads as a\n * provider error. */\nexport function generationErrorKey(\n    code: string | null,\n):\n    | \"genErrorTruncated\"\n    | \"genErrorNoHtml\"\n    | \"genErrorStale\"\n    | \"genErrorTooLarge\"\n    | \"genErrorTimeout\"\n    | \"genErrorInternal\"\n    | \"genErrorUpstream\" {\n    switch (code) {\n        case \"truncated\":\n            return \"genErrorTruncated\";\n        case \"no_html\":\n            return \"genErrorNoHtml\";\n        case \"stale\":\n            return \"genErrorStale\";\n        case \"too_large\":\n            return \"genErrorTooLarge\";\n        case \"timeout\":\n            return \"genErrorTimeout\";\n        case \"internal\":\n            return \"genErrorInternal\";\n        default:\n            return \"genErrorUpstream\";\n    }\n}\n\n/** Whether the generation a device tracks is gone: the group's latest is\n * missing or older (an organiser reset deleted the row). `undefined`, an\n * unanswered poll, says nothing yet. */\nexport function trackedGenerationGone(\n    latest: { id: number } | null | undefined,\n    tracked: number,\n): boolean {\n    if (latest === undefined) return false;\n    return latest === null || latest.id < tracked;\n}\n","export interface InterpolationResult {\n    text: string;\n    missing: string[];\n}\n\nconst UNSAFE_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction lookup(source: Record<string, unknown>, path: string): unknown {\n    let current: unknown = source;\n    for (const part of path.split(\".\")) {\n        if (UNSAFE_KEYS.has(part)) return undefined;\n        if (typeof current !== \"object\" || current === null) return undefined;\n        current = (current as Record<string, unknown>)[part];\n    }\n    return current;\n}\n\n/**\n * Fills {{key}} and {{preset.name}} slots from the answer/preset bag.\n *\n * Deliberately hand-rolled: the output is a plain-text prompt (no markup,\n * so nothing to escape), the syntax is one regex, and the alternatives on\n * npm are unmaintained. Unknown or empty slots stay visible in the output\n * so a half-filled prompt can never be pasted unnoticed — except the\n * `optional` ones (the keys of the questions that are not required), which\n * become empty text and are not missing.\n */\nexport function interpolate(\n    template: string,\n    values: Record<string, unknown>,\n    optional: ReadonlySet<string> = new Set(),\n): InterpolationResult {\n    const missing: string[] = [];\n\n    const text = template.replace(\n        /\\{\\{\\s*([A-Za-z0-9_.]+)\\s*\\}\\}/g,\n        (_match, path: string) => {\n            const value = lookup(values, path);\n            const empty =\n                value === undefined ||\n                value === null ||\n                value === \"\" ||\n                (Array.isArray(value) && value.length === 0);\n            if (empty) {\n                if (optional.has(path)) return \"\";\n                if (!missing.includes(path)) missing.push(path);\n                return `⚠ missing: ${path}`;\n            }\n            if (Array.isArray(value)) {\n                return value.join(\", \");\n            }\n            return String(value);\n        },\n    );\n\n    return { text, missing };\n}\n","import type { Answers } from \"../components/promptForm\";\n\n/** One field the open form has to show anew. */\nexport interface AnswerChange {\n    key: string;\n    value: string | string[];\n}\n\n/**\n * Merge the group's answers (from a poll) into this device's: a field this\n * device has unsaved edits for (`pending`) keeps the local value, every\n * other field follows the group. A field the group no longer has (an\n * organiser reset the page) is cleared, not kept, so the open form stops\n * showing answers the server has dropped. `changes` are the fields the form\n * must be told about (`setAnswer`).\n */\nexport function mergeRemoteAnswers(\n    local: Answers,\n    remote: Answers,\n    pending: ReadonlySet<string>,\n): { answers: Answers; changes: AnswerChange[] } {\n    const answers: Answers = { ...local };\n    const changes: AnswerChange[] = [];\n    for (const [key, value] of Object.entries(remote)) {\n        if (pending.has(key)) continue;\n        if (JSON.stringify(answers[key]) === JSON.stringify(value)) continue;\n        answers[key] = value;\n        changes.push({ key, value });\n    }\n    for (const key of Object.keys(local)) {\n        if (key in remote || pending.has(key)) continue;\n        const value = local[key];\n        if (value === \"\" || (Array.isArray(value) && value.length === 0))\n            continue; // already empty: nothing to clear\n        const empty: string | string[] = Array.isArray(value) ? [] : \"\";\n        delete answers[key];\n        changes.push({ key, value: empty });\n    }\n    return { answers, changes };\n}\n\n/**\n * What a poll does with the group's HTML: `null` keeps this device's\n * `current`, otherwise `html` replaces it. Nothing changes while this\n * device is editing (`focused`, `dirty`) or a generation is under way. A\n * new remote page is taken. An empty one is taken only when the group's\n * page went back to the form step (an organiser reset): the device then\n * starts again from `starter`, as on a fresh load, with `reset` set, so it\n * does not keep (and later publish) a page the server has dropped.\n */\nexport function remoteHtmlToTake(options: {\n    remoteHtml: string;\n    remoteStep: string;\n    current: string;\n    starter: string;\n    focused: boolean;\n    dirty: boolean;\n    busy: boolean;\n}): { html: string; reset: boolean } | null {\n    const { remoteHtml, remoteStep, current, starter } = options;\n    if (options.focused || options.dirty || options.busy) return null;\n    if (remoteHtml)\n        return remoteHtml === current\n            ? null\n            : { html: remoteHtml, reset: false };\n    if (remoteStep !== \"form\" || current === starter) return null;\n    return { html: starter, reset: true };\n}\n\n/**\n * An ISO-8601 time as microseconds since the epoch, or `null` when it does\n * not parse. The server's `updatedAt` carries microseconds (and drops the\n * fraction when it is zero), which `Date.parse` would round to\n * milliseconds; two saves within one millisecond must still order.\n */\nfunction isoMicros(value: string | null | undefined): number | null {\n    if (!value) return null;\n    const match =\n        /^(\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d)(?:\\.(\\d+))?(Z|[+-]\\d\\d:\\d\\d)?$/.exec(\n            value,\n        );\n    if (!match) return null;\n    const ms = Date.parse(match[1] + (match[3] ?? \"Z\"));\n    if (Number.isNaN(ms)) return null;\n    const micros = Number((match[2] ?? \"\").padEnd(6, \"0\").slice(0, 6));\n    return ms * 1000 + micros;\n}\n\n/**\n * Whether a page state the server sent (`candidate`, from a poll or a save\n * response) is older than the newest one this device has taken (`newest`).\n * A poll that left the server before a save landed can arrive after the\n * save's response: taking it would revert (or, as a reset, clear) the\n * answer just saved, so it is dropped. Unparsable times are never \"older\",\n * so a page without `updatedAt` still merges.\n */\nexport function isOlderPage(\n    candidate: string | null | undefined,\n    newest: string | null | undefined,\n): boolean {\n    const a = isoMicros(candidate);\n    const b = isoMicros(newest);\n    return a !== null && b !== null && a < b;\n}\n","import type { Answers } from \"../components/promptForm\";\n\n/** Default revision-prompt template, mirroring the server's\n * DEFAULT_REVISION_PROMPT (src/server/src/templates.ts) — used when a\n * template has no `revision:` section of its own. Placeholders: {{html}},\n * {{changes}}, {{diff}}. */\nexport const DEFAULT_REVISION_PROMPT = `Here is the current single-file HTML page:\n\n{{html}}\n\nKeep everything else, apply these changes: {{changes}}\n{{diff}}\nKeep the permanently visible disclaimer that this is a prototype with\nfictional data and a simulated AI; add it if it is missing.\nReturn the complete updated single-file HTML inside ONE fenced \\`\\`\\`html\ncode block, with no text before or after it.`;\n\n/** Above this size, don't inline the HTML in the prompt — point at the\n * download instead. Keeps the generated prompt pasteable everywhere. */\nexport const HTML_INLINE_LIMIT_BYTES = 60_000;\n\nexport interface FieldDiff {\n    key: string;\n    label: string;\n    from: string;\n    to: string;\n}\n\nfunction toText(value: string | string[] | undefined): string {\n    if (value === undefined) return \"\";\n    return Array.isArray(value) ? value.join(\", \") : value;\n}\n\n/** Field-by-field diff between the answers a page was generated from and\n * the answers now in the (re-opened) form — \"Title changed from A to B\". */\nexport function diffAnswers(\n    before: Answers,\n    after: Answers,\n    labels: Record<string, string>,\n): FieldDiff[] {\n    const diffs: FieldDiff[] = [];\n    const keys = new Set([...Object.keys(before), ...Object.keys(after)]);\n    for (const key of keys) {\n        const from = toText(before[key]);\n        const to = toText(after[key]);\n        if (from !== to) {\n            diffs.push({ key, label: labels[key] ?? key, from, to });\n        }\n    }\n    return diffs;\n}\n\nexport function formatDiff(diffs: FieldDiff[]): string {\n    if (diffs.length === 0) return \"\";\n    return diffs\n        .map((d) =>\n            d.from\n                ? `${d.label} changed from \"${d.from}\" to \"${d.to}\".`\n                : `${d.label} set to \"${d.to}\".`,\n        )\n        .join(\"\\n\");\n}\n\nexport interface RevisionPromptInput {\n    template: string;\n    html: string;\n    changes: string;\n    diff: string;\n}\n\n/** Fills the revision template's {{html}}/{{changes}}/{{diff}} slots. Kept\n * separate from lib/interpolate.ts's {{key}}/{{preset.name}} syntax since\n * the revision template's slots are fixed and never come from YAML answers\n * (avoids the \"possible slot collision with a question key\" edge case). */\nexport function buildRevisionPrompt(input: RevisionPromptInput): string {\n    const htmlBlock =\n        utf8ByteLength(input.html) > HTML_INLINE_LIMIT_BYTES\n            ? '(attached: current page HTML — see \"Download current HTML\" and attach it to your message to the agent)'\n            : \"```html\\n\" + input.html + \"\\n```\";\n\n    const slots: Record<string, string> = {\n        html: htmlBlock,\n        changes: input.changes || \"(no changes described yet)\",\n        diff: input.diff ? `\\nField changes:\\n${input.diff}\\n` : \"\",\n    };\n    // One pass, so a slot inside the inserted page HTML or changes is left as is.\n    return input.template.replace(\n        /\\{\\{\\s*(html|changes|diff)\\s*\\}\\}/g,\n        (_match, name: string) => slots[name] ?? \"\",\n    );\n}\n\n// Browsers don't have Buffer.byteLength — TextEncoder gives the same UTF-8\n// byte count the server's size guard uses.\nfunction utf8ByteLength(text: string): number {\n    return new TextEncoder().encode(text).length;\n}\n","/** #/work — the form -> preview -> submit loop (roadmap §5), hash-routed\n * inside the group: #/work/form, #/work/preview, #/work/submit. State autosaves to the\n * group's page (patchPage({...}), a typed wrapper over session.patchGroup)\n * so a refresh or a\n * second device in the same group resumes where the group is. */\n\nimport { groupPageUrl } from \"@starling-study/study-base/lib/entry\";\n\nimport {\n    api,\n    ApiError,\n    errorMessage,\n    type GenerationInfo,\n    type PagePatch,\n    type PageState,\n    type PromptTemplate,\n    type RevisionSummary,\n    type TemplateSummary,\n} from \"../api\";\nimport { applyStoredTheme, createHeader, isDark } from \"../components/chrome\";\nimport type { Editor } from \"../components/editor\";\nimport { loadGroup } from \"../components/members\";\nimport { createPreview, EDIT_SANDBOX } from \"../components/preview\";\nimport type { Answers, PromptForm } from \"../components/promptForm\";\nimport { createPromptForm, optionalKeys } from \"../components/promptForm\";\nimport {\n    copyToClipboard,\n    downloadHtml,\n    formatHtml,\n    readFileAsText,\n    starterHtml,\n} from \"../lib/actions\";\nimport {\n    clear,\n    createNotifier,\n    el,\n    formatBytes,\n    icon,\n    messageScreen,\n} from \"../lib/dom\";\nimport { errorCode } from \"../lib/errors\";\nimport { galleryIsPublic } from \"../lib/gallery\";\nimport {\n    documentFromPartial,\n    elapsedSeconds,\n    generationErrorKey,\n    renderablePartial,\n    startFailureKey,\n    trackedGenerationGone,\n} from \"../lib/generation\";\nimport { pick, t } from \"../lib/i18n\";\nimport { interpolate } from \"../lib/interpolate\";\nimport { clearLaunchPrompt, pendingLaunchPrompt } from \"../lib/launch\";\nimport {\n    isOlderPage,\n    mergeRemoteAnswers,\n    remoteHtmlToTake,\n} from \"../lib/pagemerge\";\nimport { startPoll, type Poll } from \"../lib/poll\";\nimport {\n    buildRevisionPrompt,\n    diffAnswers,\n    formatDiff,\n    DEFAULT_REVISION_PROMPT,\n} from \"../lib/revision\";\nimport { currentRoute, href, isRouteHash, navigate } from \"../lib/router\";\nimport { session, patchPage } from \"../session\";\n\ntype Step = \"form\" | \"preview\" | \"submit\";\n\n/** What a step hands the shell: its content, the pane switch a phone needs\n * when the step is a two-pane workbench, and the step's own actions, which\n * go into the dock at the foot of the screen. */\ninterface StepMount {\n    element: HTMLElement;\n    paneSwitch?: HTMLElement;\n    actions?: HTMLElement[];\n}\n\n/** Below 768px the theme shows one `.study-pane` of a `.study-workbench` at\n * a time — the one that is `.is-active` — and `.study-pane-switch` (phone\n * only, in the footer) picks it. Wider screens show both and no switch. */\nfunction paneSwitch(panes: [label: string, pane: HTMLElement][]): {\n    element: HTMLElement;\n    show(index: number): void;\n} {\n    const buttons = panes.map(([label], index) => {\n        const button = el(\"button\", {\n            class: \"study-pane-switch__btn\",\n            type: \"button\",\n            text: label,\n        });\n        button.addEventListener(\"click\", () => show(index));\n        return button;\n    });\n    function show(index: number): void {\n        panes.forEach(([, pane], i) => {\n            pane.classList.toggle(\"is-active\", i === index);\n            buttons[i].classList.toggle(\"is-active\", i === index);\n            buttons[i].setAttribute(\"aria-pressed\", String(i === index));\n        });\n    }\n    show(0);\n    return {\n        element: el(\n            \"div\",\n            { class: \"study-pane-switch\", role: \"group\" },\n            ...buttons,\n        ),\n        show,\n    };\n}\n\n/** \"The model is working\" / \"that failed\", in one line: the theme's\n * `.study-running` row with its spinner, or its `.study-status` in the\n * error colour. Hidden while there is nothing to say. */\ninterface StatusLine {\n    element: HTMLElement;\n    set(kind: \"idle\" | \"busy\" | \"error\", message?: string): void;\n}\n\nfunction statusLine(): StatusLine {\n    const spinner = el(\"span\", {\n        class: \"study-running__spinner\",\n        \"aria-hidden\": \"true\",\n    });\n    const text = el(\"span\", {});\n    const element = el(\n        \"div\",\n        {\n            class: \"study-running\",\n            role: \"status\",\n            \"aria-live\": \"polite\",\n            hidden: true,\n        },\n        spinner,\n        text,\n    );\n    return {\n        element,\n        set(kind, message = \"\") {\n            element.className =\n                kind === \"error\"\n                    ? \"study-status study-status--error\"\n                    : \"study-running\";\n            element.hidden = kind === \"idle\";\n            spinner.hidden = kind !== \"busy\";\n            text.textContent = message;\n        },\n    };\n}\n\n/** The viewport classes of the preview's device switch. */\nconst DEVICES = [\n    [\n        \"desktop\",\n        '<rect x=\"3\" y=\"4\" width=\"18\" height=\"12\" rx=\"1\"/><path d=\"M8 20h8M12 16v4\"/>',\n    ],\n    [\n        \"tablet\",\n        '<rect x=\"5\" y=\"3\" width=\"14\" height=\"18\" rx=\"2\"/><path d=\"M11 17.5h2\"/>',\n    ],\n    [\n        \"mobile\",\n        '<rect x=\"7\" y=\"3\" width=\"10\" height=\"18\" rx=\"2\"/><path d=\"M11 17.5h2\"/>',\n    ],\n] as const;\ntype Device = (typeof DEVICES)[number][0];\n\n/** The theme's narrow boundary (one pane at a time, the page scrolls). */\nconst NARROW = \"(max-width: 47.98rem)\";\n\nconst AUTOSAVE_MS = 600;\nconst POLL_MS = 5000;\n/** While a generation runs, the group is polled this often (roadmap 0.6 §3). */\nconst GEN_POLL_MS = 2000;\n\n/** What the form step's progress card shows (roadmap 0.6 §3). `mine` is\n * false when another member of the group started it. */\ntype GenPhase =\n    | { phase: \"idle\" }\n    | { phase: \"starting\" }\n    | {\n          phase: \"queued\";\n          position: number | null;\n          since: number;\n          mine: boolean;\n      }\n    | { phase: \"running\"; since: number; mine: boolean }\n    | { phase: \"error\"; message: string };\n\ninterface GenerationView {\n    set(state: GenPhase): void;\n    showPartial(text: string): void;\n}\n\n/** The coding agent of this workshop — linked wherever the prompt is. */\nexport const VIBE_URL = \"https://chat.mistral.ai/chat\";\n\nfunction hashStep(): Step {\n    const route = currentRoute();\n    const raw = route.name === \"work\" ? route.param : \"\";\n    if (raw === \"preview\" || raw === \"submit\") return raw;\n    return \"form\";\n}\n\nexport async function renderWork(root: HTMLElement): Promise<void> {\n    applyStoredTheme();\n\n    const membership = session.membership;\n    if (!membership) {\n        // Through the route: no membership asks where the person went.\n        navigate(\"\");\n        return;\n    }\n\n    if (!(await loadGroup())) return;\n    if (!session.group) {\n        root.replaceChildren(\n            messageScreen(t(\"groupLoadFailed\"), t(\"tryAgain\"), {\n                href: groupPageUrl(membership.code),\n                label: t(\"backToGroup\"),\n            }),\n        );\n        return;\n    }\n\n    // In-app generation (roadmap 0.6) is on when the server has a key. Off,\n    // the form step is the copy-the-prompt / paste-the-HTML flow of 0.5.\n    const generateEnabled = await api\n        .generateStatus()\n        .then((status) => status.enabled)\n        .catch(() => false);\n\n    const status = el(\"span\", { role: \"status\", \"aria-live\": \"polite\" });\n    const notify = createNotifier(status);\n    // A save that failed (busy, offline) says so until a save gets through:\n    // what was typed is kept and sent again with the next save.\n    const saveError = el(\"span\", {\n        class: \"study-status study-status--error\",\n        role: \"alert\",\n        hidden: true,\n    });\n    function setSaveError(message: string): void {\n        saveError.textContent = message;\n        saveError.hidden = !message;\n    }\n    const savedNote = el(\"span\", {\n        class: \"ss-badge ss-badge--success\",\n        hidden: true,\n        text: t(\"saved\"),\n    });\n\n    // ---- local editor state, seeded from the group's page ------------------\n    let page: PageState = session.group.page;\n    const starter = starterHtml();\n    let currentHtml = page.html || starter;\n    let currentAnswers: Answers = (page.answers as Answers) ?? {};\n    let baseAnswers: Answers = { ...currentAnswers }; // snapshot answers were generated from\n    let revisionMode = false;\n    let editor: Editor | null = null;\n    let formHandle: {\n        setAnswer(key: string, value: string | string[]): void;\n    } | null = null;\n    let dirty = false; // true while an autosave is pending\n    let focused = false; // true while the user is typing (editor or form)\n    // Keys this device changed since its last successful save — the only\n    // ones sent (the server merges per key) and the ones a poll must not\n    // overwrite with an older remote value.\n    const pendingKeys = new Set<string>();\n    // The template this device's form last reported: a switch to another\n    // one is saved even when no answer changed, while a remote merge (same\n    // local template) never sends it back over another member's switch.\n    let reportedTemplateId: string | null = page.templateId;\n\n    const tabs: Record<Step, HTMLButtonElement> = {\n        form: stepTab(\"1\", t(\"stepForm\")),\n        preview: stepTab(\"2\", t(\"stepPreview\")),\n        submit: stepTab(\"3\", t(\"stepSubmit\")),\n    };\n\n    function generationBusy(): boolean {\n        return (\n            gen.phase === \"starting\" ||\n            gen.phase === \"queued\" ||\n            gen.phase === \"running\"\n        );\n    }\n\n    function reachable(step: Step): boolean {\n        if (step === \"form\") return true;\n        // The preview is where a generation is watched, so it opens as soon as\n        // one is under way even before there is any HTML (roadmap 0.6 §3).\n        if (step === \"preview\")\n            return currentHtml.trim().length > 0 || generationBusy();\n        if (step === \"submit\")\n            return currentHtml.trim().length > 0 && page.step !== \"form\";\n        return false;\n    }\n\n    function updateTabs(active: Step): void {\n        const order = Object.keys(tabs) as Step[];\n        for (const [key, tab] of Object.entries(tabs) as [\n            Step,\n            HTMLButtonElement,\n        ][]) {\n            tab.disabled = !reachable(key);\n            tab.classList.toggle(\"is-active\", key === active);\n            tab.classList.toggle(\n                \"is-done\",\n                order.indexOf(key) < order.indexOf(active),\n            );\n            if (key === active) tab.setAttribute(\"aria-current\", \"step\");\n            else tab.removeAttribute(\"aria-current\");\n        }\n    }\n\n    // ---- autosave ------------------------------------------------------\n\n    let saveTimer: number | undefined;\n    let queued: PagePatch = {};\n    function scheduleSave(patch: PagePatch): void {\n        dirty = true;\n        // Successive edits before the debounce fires accumulate: answers per\n        // key, other fields last-write-wins.\n        queued = {\n            ...queued,\n            ...patch,\n            ...(patch.answers || queued.answers\n                ? {\n                      answers: {\n                          ...(queued.answers ?? {}),\n                          ...(patch.answers ?? {}),\n                      },\n                  }\n                : {}),\n        };\n        window.clearTimeout(saveTimer);\n        saveTimer = window.setTimeout(() => void doSave(), AUTOSAVE_MS);\n    }\n\n    let lastSave: Promise<void> = Promise.resolve(); // the save on the wire, settled either way\n    async function doSave(): Promise<void> {\n        const patch = queued;\n        queued = {};\n        if (Object.keys(patch).length === 0) return;\n        const sentKeys = Object.keys(patch.answers ?? {});\n        try {\n            const request = patchPage(patch);\n            lastSave = request.then(\n                () => undefined,\n                () => undefined,\n            );\n            const updated = await request;\n            // A poll that already brought a newer page keeps it: the\n            // response must not wind the group's state back.\n            if (!isOlderPage(updated.page.updatedAt, page.updatedAt)) {\n                page = updated.page;\n                currentAnswers = (page.answers as Answers) ?? currentAnswers;\n            }\n            for (const key of sentKeys) pendingKeys.delete(key);\n            dirty = Object.keys(queued).length > 0;\n            setSaveError(\"\");\n            savedNote.hidden = false;\n            window.setTimeout(() => (savedNote.hidden = true), 1200);\n        } catch (error) {\n            // Keep the patch so the next save retries it.\n            queued = {\n                ...patch,\n                ...queued,\n                answers: {\n                    ...(patch.answers ?? {}),\n                    ...(queued.answers ?? {}),\n                },\n            };\n            if (!queued.answers || Object.keys(queued.answers).length === 0)\n                delete queued.answers;\n            const code = errorCode(error);\n            setSaveError(\n                code === \"busy\" || code === \"offline\"\n                    ? errorMessage(error)\n                    : t(\"saveFailed\"),\n            );\n        }\n    }\n\n    /** Sends whatever is still waiting for the autosave and waits for any\n     * save already on the wire. Publishing reads the group's page from the\n     * server, so it must not start before the edits are there. False when\n     * something could not be saved. */\n    async function flushSave(): Promise<boolean> {\n        window.clearTimeout(saveTimer);\n        await lastSave;\n        await doSave();\n        return Object.keys(queued).length === 0;\n    }\n\n    async function saveNow(patch: PagePatch): Promise<void> {\n        window.clearTimeout(saveTimer);\n        scheduleSave(patch);\n        window.clearTimeout(saveTimer);\n        await doSave();\n    }\n\n    // ---- in-app generation: the shell owns the state, the form step shows it\n\n    let gen: GenPhase = { phase: \"idle\" };\n    let genView: GenerationView | null = null;\n    let lastRequest: { kind: \"initial\" | \"revision\"; changes: string } | null =\n        null;\n    let trackedId: number | null = null;\n    let trackedMine = false;\n    /** The generation's poll (lib/poll), while one is tracked. */\n    let genTimer: Poll | null = null;\n\n    function setGen(next: GenPhase): void {\n        gen = next;\n        genView?.set(gen);\n    }\n\n    function genErrorMessage(code: string | null): string {\n        return t(generationErrorKey(code));\n    }\n\n    function track(id: number, mine: boolean): void {\n        trackedId = id;\n        trackedMine = mine;\n        genTimer?.stop();\n        genTimer = startPoll({ run: genPoll, intervalMs: GEN_POLL_MS });\n        genTimer.now();\n    }\n\n    function untrack(): void {\n        genTimer?.stop();\n        genTimer = null;\n        trackedId = null;\n    }\n\n    async function startGeneration(\n        kind: \"initial\" | \"revision\",\n        changes: string,\n    ): Promise<void> {\n        const code = session.group.code;\n        const token = tokenFor(code);\n        if (!token) return;\n        lastRequest = { kind, changes };\n        setGen({ phase: \"starting\" });\n        // The server builds the prompt from its saved copy of the form: an\n        // answer still in the autosave debounce would make it \"incomplete\".\n        if (!(await flushSave())) {\n            setGen({\n                phase: \"error\",\n                message: saveError.textContent || t(\"saveFailed\"),\n            });\n            return;\n        }\n        try {\n            const { generation } = await api.generate(code, token, {\n                kind,\n                changes,\n            });\n            track(generation.id, true);\n            applyGeneration(generation, true);\n            // Watch it build where the page will end up: the preview step.\n            if (currentStep !== \"preview\") await show(\"preview\");\n        } catch (error) {\n            const status = error instanceof ApiError ? error.status : 0;\n            const code = errorCode(error);\n            // The server's reason in the page's language (lib/errors), else the\n            // client's own text for the status.\n            const key = startFailureKey(status);\n            const message =\n                code && code !== \"unknown\"\n                    ? errorMessage(error)\n                    : t(\n                          key === \"detailOrForm\"\n                              ? \"fillFormFirst\"\n                              : key === \"detailOrPaused\"\n                                ? \"genErrorPaused\"\n                                : key,\n                      );\n            setGen({ phase: \"error\", message });\n            if (status === 409 && session.group) {\n                // Someone else beat us to it — follow theirs.\n                await session.refreshGroup().catch(() => undefined);\n                const other = session.group.generating;\n                if (other) track(other.id, false);\n            }\n        }\n    }\n\n    async function genPoll(): Promise<void> {\n        const code = session.group.code;\n        const token = tokenFor(code);\n        const tracked = trackedId;\n        if (!token || tracked === null) return;\n        const latest = await api\n            .generation(code, token)\n            .then((r) => r.generation)\n            .catch(() => undefined);\n        if (trackedGenerationGone(latest, tracked)) {\n            // The tracked generation is gone (an organiser reset the group):\n            // stop waiting for it once the group runs none.\n            await session.refreshGroup().catch(() => undefined);\n            if (trackedId === tracked && !session.group?.generating) {\n                untrack();\n                setGen({ phase: \"idle\" });\n            }\n            return;\n        }\n        if (!latest) return; // unreachable: try again next tick\n        applyGeneration(latest, latest.id === trackedId ? trackedMine : false);\n        if (latest.status === \"running\" && genView) {\n            const partial = await api\n                .generationPartial(code, latest.id, token)\n                .then((r) => r.partial)\n                .catch(() => \"\");\n            if (partial) genView.showPartial(partial);\n        }\n    }\n\n    function applyGeneration(g: GenerationInfo, mine: boolean): void {\n        const since = Date.parse(g.startedAt ?? g.createdAt);\n        if (g.status === \"queued\") {\n            setGen({\n                phase: \"queued\",\n                position: g.queuePosition,\n                since,\n                mine,\n            });\n        } else if (g.status === \"running\") {\n            setGen({ phase: \"running\", since, mine });\n        } else if (g.status === \"error\") {\n            untrack();\n            setGen({ phase: \"error\", message: genErrorMessage(g.error) });\n        } else {\n            untrack();\n            void finishGeneration();\n        }\n    }\n\n    /** The page is on the group now: pick it up and move to the preview —\n     * unless this device is mid-edit, in which case the regular poll brings\n     * the HTML in and the participant moves on when ready. */\n    async function finishGeneration(): Promise<void> {\n        await session.refreshGroup().catch(() => undefined);\n        const remote = session.group?.page;\n        if (remote?.html) {\n            page = remote;\n            currentHtml = remote.html;\n            currentAnswers = (remote.answers as Answers) ?? currentAnswers;\n        }\n        baseAnswers = { ...currentAnswers };\n        revisionMode = false;\n        setGen({ phase: \"idle\" });\n        notify(t(\"generatedDone\"));\n        if (!focused || currentStep === \"form\") await show(\"preview\");\n        else updateTabs(currentStep);\n    }\n\n    window.addEventListener(\"pagehide\", () => genTimer?.stop(), {\n        once: true,\n    });\n\n    // ---- polling: merge remote page state when not locally focused ---------\n\n    // Live group input (roadmap 0.5 §7): the poll always runs, and merges\n    // the other members' answers field by field. A field this device is\n    // typing in (focused) or has unsaved edits for (pendingKeys) keeps the\n    // local value; everything else follows the group. One request at a\n    // time, with a growing pause while the server cannot be reached\n    // (lib/poll).\n    const pollTimer = startPoll({\n        intervalMs: POLL_MS,\n        run: () =>\n            session\n                .refreshGroup()\n                .then(() => {\n                    // Another member's generation shows up here first (roadmap 0.6 §3).\n                    const running = session.group?.generating;\n                    if (\n                        running &&\n                        trackedId === null &&\n                        gen.phase === \"idle\"\n                    ) {\n                        track(\n                            running.id,\n                            running.participantId ===\n                                (session.membership?.participantId ?? null),\n                        );\n                    }\n\n                    const remote = session.group?.page;\n                    if (!remote) return;\n                    // `page` is the newest state seen (save responses and polls):\n                    // a poll that left the server before a save landed but came\n                    // back after it would revert, or clear, the key just saved.\n                    if (remote.updatedAt === page.updatedAt) return;\n                    if (isOlderPage(remote.updatedAt, page.updatedAt)) return;\n                    page = remote;\n\n                    const { answers, changes } = mergeRemoteAnswers(\n                        currentAnswers,\n                        (remote.answers as Answers) ?? {},\n                        pendingKeys,\n                    );\n                    for (const { key, value } of changes)\n                        formHandle?.setAnswer(key, value);\n                    currentAnswers = answers;\n                    formRefresh?.();\n\n                    // The HTML follows the group only while this device is not editing\n                    // it; an empty editor (fresh paste field) never gets remote HTML\n                    // pushed into it — the preview picks it up instead. After an\n                    // organiser reset the view starts again from the form.\n                    const take = remoteHtmlToTake({\n                        remoteHtml: remote.html,\n                        remoteStep: remote.step,\n                        current: currentHtml,\n                        starter,\n                        focused,\n                        dirty,\n                        busy: generationBusy(),\n                    });\n                    if (take?.reset) {\n                        currentHtml = take.html;\n                        baseAnswers = {};\n                        revisionMode = false;\n                        void show(currentStep);\n                        return;\n                    }\n                    if (take) {\n                        currentHtml = take.html;\n                        if (\n                            editor &&\n                            editor.getCode().trim() &&\n                            editor.getCode() !== currentHtml\n                        )\n                            previewSetQuiet?.(currentHtml);\n                        previewRefresh?.(currentHtml);\n                    }\n                    updateTabs(currentStep);\n                })\n                .catch(() => undefined),\n    });\n    let formRefresh: (() => void) | null = null;\n    let previewRefresh: ((html: string) => void) | null = null;\n    let previewSetQuiet: ((html: string) => void) | null = null;\n    window.addEventListener(\"pagehide\", () => pollTimer.stop(), {\n        once: true,\n    });\n\n    // ---- shell ---------------------------------------------------------\n\n    let currentStep: Step = hashStep();\n\n    // The foot of the screen: the pane switch (a phone, on a two-pane step),\n    // the dock with the step's own actions, and the status bar. On a phone\n    // the three stick to the bottom of the viewport together (scss/_app.scss);\n    // the dock is hidden on a step that has no actions.\n    const dock = el(\"div\", { class: \"study-dock\", hidden: true });\n    const autosaveNote = el(\"span\", {\n        class: \"study-statusbar__right\",\n        text: t(\"autosaveNote\"),\n    });\n    const footer = el(\n        \"footer\",\n        { class: \"cocoder-footer\" },\n        dock,\n        el(\n            \"div\",\n            { class: \"study-statusbar\" },\n            status,\n            saveError,\n            savedNote,\n            autosaveNote,\n        ),\n    );\n    // No room for the standing note on a phone: the bar keeps the messages.\n    const narrow = window.matchMedia(NARROW);\n    const syncNarrow = (): void => void (autosaveNote.hidden = narrow.matches);\n    narrow.addEventListener(\"change\", syncNarrow);\n    syncNarrow();\n\n    // The step on screen: swapped as a whole, so the step's own root (a\n    // workbench, a page) is a direct child of the app and fills it.\n    let stepNode: HTMLElement = el(\"div\", {});\n    let stepSwitch: HTMLElement | null = null;\n    let showing = 0;\n\n    function mount(step: StepMount): void {\n        stepNode.replaceWith(step.element);\n        stepNode = step.element;\n        stepSwitch?.remove();\n        stepSwitch = step.paneSwitch ?? null;\n        if (stepSwitch) dock.before(stepSwitch);\n        dock.replaceChildren(...(step.actions ?? []));\n        dock.hidden = dock.childElementCount === 0;\n    }\n\n    async function show(step: Step): Promise<void> {\n        if (!reachable(step)) step = \"form\";\n        currentStep = step;\n        if (currentRoute().param !== step)\n            location.hash = href(`work/${step}`);\n        updateTabs(step);\n        // A step asked for while this one is still being built wins.\n        const ticket = ++showing;\n        mount({\n            element: el(\n                \"div\",\n                { class: \"study-centered\" },\n                el(\n                    \"div\",\n                    { class: \"study-running\" },\n                    el(\"span\", {\n                        class: \"study-running__spinner study-running__spinner--lg\",\n                        \"aria-hidden\": \"true\",\n                    }),\n                ),\n            ),\n        });\n\n        if (step === \"form\") {\n            const built = await buildFormStep({\n                group: session.group,\n                revisionMode,\n                currentHtml,\n                currentAnswers,\n                baseAnswers,\n                notify,\n                onAnswersChange: (answers, templateId) => {\n                    const changed: Answers = {};\n                    for (const [key, value] of Object.entries(answers)) {\n                        if (\n                            JSON.stringify(currentAnswers[key]) !==\n                            JSON.stringify(value)\n                        ) {\n                            changed[key] = value;\n                            pendingKeys.add(key);\n                        }\n                    }\n                    currentAnswers = answers;\n                    const switched = templateId !== reportedTemplateId;\n                    reportedTemplateId = templateId;\n                    if (Object.keys(changed).length === 0 && !switched) return;\n                    scheduleSave({ answers: changed, templateId });\n                },\n                onFocusChange: (isFocused) => (focused = isFocused),\n                onPromptGenerated: () => undefined,\n                onMounted: (handle) => {\n                    formHandle = handle.form;\n                    formRefresh = handle.refresh;\n                },\n                generateEnabled,\n                onGenerate: (kind, changes) =>\n                    void startGeneration(kind, changes),\n                onGenerationView: (view) => {\n                    genView = view;\n                    view.set(gen);\n                },\n                onNext: () => {\n                    // The HTML about to be pasted was made from these answers: they\n                    // are the baseline the next revision's field diff compares to.\n                    baseAnswers = { ...currentAnswers };\n                    void show(\"preview\");\n                },\n            });\n            if (ticket === showing) mount(built);\n            return;\n        }\n\n        genView = null;\n\n        if (step === \"preview\") {\n            formHandle = null;\n            formRefresh = null;\n            const built = await buildPreviewStep({\n                currentHtml,\n                generateEnabled,\n                onGenerationView: (view) => {\n                    genView = view;\n                    view.set(gen);\n                },\n                onRetry: () => {\n                    if (lastRequest)\n                        void startGeneration(\n                            lastRequest.kind,\n                            lastRequest.changes,\n                        );\n                },\n                notify,\n                onHtmlChange: (html) => {\n                    currentHtml = html;\n                    scheduleSave({ html, step: \"preview\" });\n                    updateTabs(currentStep);\n                },\n                onFocusChange: (isFocused) => (focused = isFocused),\n                onChangeSomething: () => {\n                    revisionMode = true;\n                    void show(\"form\");\n                },\n                onLooksGood: () => {\n                    void saveNow({ html: currentHtml, step: \"preview\" }).then(\n                        () => void show(\"submit\"),\n                    );\n                },\n                group: session.group,\n            });\n            if (ticket !== showing) {\n                // Another step was asked for while the editor loaded.\n                built.editor.destroy();\n                return;\n            }\n            editor?.destroy();\n            editor = built.editor;\n            previewRefresh = built.refresh;\n            previewSetQuiet = built.setCodeQuiet;\n            mount(built);\n            return;\n        }\n\n        previewRefresh = null;\n        previewSetQuiet = null;\n        mount({\n            element: buildSubmitStep({\n                group: session.group,\n                getHtml: () => currentHtml,\n                flushSave,\n                notify,\n                onBack: () => void show(\"preview\"),\n            }),\n        });\n    }\n\n    const header = createHeader({\n        onThemeChange: (dark) => editor?.setDark(dark),\n    });\n\n    // The work screen is bound to the viewport from 768px up, each pane\n    // scrolling on its own (the theme's `study-app--fill`).\n    root.classList.add(\"study-app--fill\");\n    const steps = el(\n        \"ol\",\n        { class: \"study-steps\" },\n        el(\"li\", {}, tabs.form),\n        el(\"li\", {}, tabs.preview),\n        el(\"li\", {}, tabs.submit),\n    );\n    const banner = lessonBanner();\n    root.replaceChildren(\n        ...header,\n        steps,\n        ...(banner ? [banner] : []),\n        stepNode,\n        footer,\n    );\n\n    tabs.form.addEventListener(\"click\", () => void show(\"form\"));\n    tabs.preview.addEventListener(\"click\", () => void show(\"preview\"));\n    tabs.submit.addEventListener(\"click\", () => void show(\"submit\"));\n    window.addEventListener(\"hashchange\", () => {\n        if (!isRouteHash(location.hash)) return;\n        const step = hashStep();\n        if (step !== currentStep) void show(step);\n    });\n\n    await show(hashStep());\n}\n\n/** A lesson's instruction (`?prompt=`, kept since boot), shown above the\n * form: the form is template-driven, so there is no free field to pre-fill.\n * It stays (across the reloads between routes) until the group dismisses\n * it, and never generates anything by itself. */\nfunction lessonBanner(): HTMLElement | null {\n    const instruction = pendingLaunchPrompt();\n    if (!instruction) return null;\n    const dismiss = el(\n        \"button\",\n        { class: \"study-banner__dismiss ss-btn ss-btn--sm\", type: \"button\" },\n        t(\"dismissInstruction\"),\n    );\n    // The theme's info banner, capped so a long text never eats the panel.\n    const banner = el(\n        \"aside\",\n        {\n            class: \"study-banner study-banner--info study-banner--capped\",\n            role: \"note\",\n        },\n        el(\"strong\", {\n            class: \"study-banner__title\",\n            text: t(\"lessonInstruction\"),\n        }),\n        el(\"p\", { class: \"study-banner__text\", text: instruction }),\n        dismiss,\n    );\n    dismiss.addEventListener(\"click\", () => {\n        clearLaunchPrompt();\n        banner.remove();\n    });\n    return banner;\n}\n\nfunction stepTab(number: string, label: string): HTMLButtonElement {\n    return el(\n        \"button\",\n        { class: \"study-step\", type: \"button\" },\n        el(\"span\", { class: \"study-step__number\", text: number }),\n        el(\"span\", { text: label }),\n    ) as HTMLButtonElement;\n}\n\n// ---- Step 1: form (initial mode) + the revision view -------------------\n//\n// Initial mode shows the full form. Revision mode (\"Change something\")\n// shows ONLY the \"what should be different?\" field — the whole prompt is\n// regenerated around that one answer — with the full form reachable\n// behind an explicit \"edit all answers\" toggle for real answer changes.\n\ninterface FormStepArgs {\n    group: { code: string; page: PageState };\n    revisionMode: boolean;\n    currentHtml: string;\n    currentAnswers: Answers;\n    baseAnswers: Answers;\n    notify: (message: string) => void;\n    onAnswersChange: (answers: Answers, templateId: string) => void;\n    onFocusChange: (focused: boolean) => void;\n    onPromptGenerated: (prompt: string) => void;\n    onMounted: (handle: { form: PromptForm; refresh: () => void }) => void;\n    onNext: () => void;\n    /** In-app generation (roadmap 0.6): when true the primary action is the\n     * generate button; the copy/paste toolbar is only shown when it is off. */\n    generateEnabled: boolean;\n    onGenerate: (kind: \"initial\" | \"revision\", changes: string) => void;\n    onGenerationView: (view: GenerationView) => void;\n}\n\nasync function buildFormStep(args: FormStepArgs): Promise<StepMount> {\n    const summaries: TemplateSummary[] = await api.templates();\n    const formPane = el(\"section\", { class: \"study-pane\" });\n    const promptPane = el(\"section\", { class: \"study-pane\" });\n    const workbench = el(\n        \"div\",\n        { class: \"study-workbench\" },\n        formPane,\n        promptPane,\n    );\n    // With in-app generation the button is in the dock at the foot of the\n    // screen, so a phone needs no switch: the two panes stack (both\n    // `.is-active`). Without it the prompt pane holds the copy/paste\n    // workflow and a phone switches between the two.\n    const switcher = args.generateEnabled\n        ? null\n        : paneSwitch([\n              [t(\"paneForm\"), formPane],\n              [t(\"panePrompt\"), promptPane],\n          ]);\n    if (!switcher)\n        for (const pane of [formPane, promptPane])\n            pane.classList.add(\"is-active\");\n\n    // A <div>, not a <pre>: core colours every <pre> for a dark code block,\n    // and the theme's `.study-pre` (a light sunken box that keeps the line\n    // breaks itself) does not set the text colour back.\n    const output = el(\"div\", { class: \"study-pre\" });\n    // What is still to fill in: the visible labels, each a link to its field.\n    const missingNote = el(\"div\", {\n        class: \"study-field-error cocoder-missing\",\n        role: \"status\",\n        hidden: true,\n    });\n    const copyButton = el(\n        \"button\",\n        { class: \"ss-btn ss-btn--sm ss-btn--primary\", type: \"button\" },\n        t(\"copyPrompt\"),\n    );\n    const vibeLink = el(\n        \"a\",\n        {\n            class: \"ss-btn ss-btn--sm\",\n            href: VIBE_URL,\n            target: \"_blank\",\n            rel: \"noreferrer\",\n        },\n        t(\"openVibe\"),\n    );\n    const downloadButton = el(\n        \"button\",\n        { class: \"ss-btn ss-btn--sm\", type: \"button\", hidden: true },\n        t(\"downloadCurrentHtml\"),\n    );\n    const nextButton = el(\n        \"button\",\n        { class: \"ss-btn ss-btn--sm\", type: \"button\" },\n        args.revisionMode ? t(\"haveUpdatedHtml\") : t(\"haveHtml\"),\n    );\n\n    // ---- the generate button (roadmap 0.6 §3), in the dock -----------------\n    const generateButton = el(\n        \"button\",\n        { class: \"ss-btn ss-btn--primary\", type: \"button\" },\n        args.revisionMode ? t(\"generateRevision\") : t(\"makeMyPage\"),\n    ) as HTMLButtonElement;\n    const progress = statusLine();\n\n    let ready = false; // the prompt is complete (initial) / there is something to change (revision)\n    let busy = false;\n    let ticker: number | undefined;\n\n    function syncButton(): void {\n        // Never disabled for a missing answer: a press says what is missing.\n        generateButton.disabled = busy;\n    }\n\n    function elapsed(since: number): string {\n        return `${elapsedSeconds(since)} ${t(\"generatingElapsed\")}`;\n    }\n\n    const view: GenerationView = {\n        set(state) {\n            window.clearInterval(ticker);\n            ticker = undefined;\n            busy =\n                state.phase === \"starting\" ||\n                state.phase === \"queued\" ||\n                state.phase === \"running\";\n            generateButton.textContent =\n                state.phase === \"error\"\n                    ? t(\"tryAgainButton\")\n                    : args.revisionMode\n                      ? t(\"generateRevision\")\n                      : t(\"makeMyPage\");\n            if (state.phase === \"idle\") {\n                progress.set(\"idle\");\n            } else if (state.phase === \"starting\") {\n                progress.set(\"busy\", \"…\");\n            } else if (state.phase === \"queued\") {\n                const position = state.position\n                    ? ` · ${t(\"generatingPosition\")} ${state.position}`\n                    : \"\";\n                progress.set(\n                    \"busy\",\n                    `${state.mine ? t(\"generatingQueued\") : t(\"generatingByOther\")}${position}`,\n                );\n            } else if (state.phase === \"running\") {\n                const tick = (): void => {\n                    progress.set(\n                        \"busy\",\n                        `${state.mine ? t(\"generating\") : t(\"generatingByOther\")} · ${elapsed(state.since)}`,\n                    );\n                };\n                tick();\n                ticker = window.setInterval(tick, 1000);\n            } else {\n                progress.set(\n                    \"error\",\n                    `${t(\"generateFailed\")}: ${state.message}`,\n                );\n            }\n            syncButton();\n        },\n        // The build is watched on the preview step, not here.\n        showPartial() {},\n    };\n    window.addEventListener(\"pagehide\", () => window.clearInterval(ticker), {\n        once: true,\n    });\n\n    // \"This is what we send to the AI\", folded: the participants fill in a\n    // form; the prompt is there for whoever wants to see it.\n    const sentPrompt = el(\n        \"details\",\n        { class: \"cocoder-sent\" },\n        el(\"summary\", { class: \"ss-eyebrow\" }, t(\"whatWeSend\")),\n        output,\n    );\n\n    if (args.generateEnabled) {\n        promptPane.append(\n            el(\n                \"header\",\n                { class: \"study-pane__head\" },\n                el(\"h2\", { class: \"study-pane__title\", text: t(\"myPage\") }),\n            ),\n            el(\n                \"div\",\n                { class: \"study-pane__body\" },\n                el(\n                    \"div\",\n                    { class: \"ss-stack ss-stack--loose\" },\n                    el(\"p\", {\n                        class: \"ss-muted\",\n                        text: args.revisionMode\n                            ? t(\"generateHowToRevision\")\n                            : t(\"generateHowTo\"),\n                    }),\n                    sentPrompt,\n                ),\n            ),\n        );\n        args.onGenerationView(view);\n    } else {\n        promptPane.append(\n            el(\n                \"header\",\n                { class: \"study-pane__head\" },\n                el(\"h2\", {\n                    class: \"study-pane__title\",\n                    text: t(\"yourPrompt\"),\n                }),\n                el(\n                    \"div\",\n                    { class: \"ss-toolbar ss-toolbar--wrap\" },\n                    copyButton,\n                    vibeLink,\n                    downloadButton,\n                    nextButton,\n                ),\n            ),\n            el(\n                \"div\",\n                { class: \"study-pane__body\" },\n                el(\n                    \"div\",\n                    { class: \"ss-stack ss-stack--loose\" },\n                    el(\"p\", {\n                        class: \"ss-muted\",\n                        text: args.revisionMode\n                            ? t(\"promptHowToRevision\")\n                            : t(\"promptHowTo\"),\n                    }),\n                    missingNote,\n                    output,\n                ),\n            ),\n        );\n    }\n\n    const storedTemplateId = args.group.page.templateId;\n    let template: PromptTemplate = await api.template(\n        summaries.find((s) => s.id === storedTemplateId)?.id ??\n            summaries[0].id,\n    );\n\n    const picker = el(\"select\", { class: \"ss-select\", id: \"template\" });\n    for (const summary of summaries) {\n        picker.append(\n            el(\"option\", { value: summary.id }, pick(summary.title)),\n        );\n    }\n    picker.value = template.id;\n\n    const formHost = el(\"div\", {});\n    let showFullForm = !args.revisionMode;\n    let form: PromptForm | null = null;\n\n    const changesError = el(\"p\", {\n        class: \"study-field-error\",\n        id: \"changes-error\",\n        hidden: true,\n    });\n    const changesField = args.revisionMode\n        ? el(\n              \"div\",\n              { class: \"ss-field\" },\n              el(\n                  \"label\",\n                  { class: \"ss-label\", for: \"changes\" },\n                  t(\"whatShouldBeDifferent\"),\n              ),\n              el(\"p\", { class: \"study-help\", text: t(\"changesHint\") }),\n              el(\"textarea\", {\n                  class: \"ss-textarea\",\n                  id: \"changes\",\n                  rows: 5,\n                  placeholder: t(\"changesPlaceholder\"),\n              }),\n              changesError,\n          )\n        : null;\n    const changesInput = changesField?.querySelector(\"textarea\") ?? null;\n\n    const editAllToggle = args.revisionMode\n        ? el(\n              \"button\",\n              {\n                  class: \"ss-btn ss-btn--sm\",\n                  type: \"button\",\n                  \"aria-expanded\": \"false\",\n              },\n              t(\"editAllAnswers\"),\n          )\n        : null;\n    function setFullForm(open: boolean): void {\n        showFullForm = open;\n        formHost.hidden = !open;\n        if (!editAllToggle) return;\n        editAllToggle.textContent = open\n            ? t(\"hideAllAnswers\")\n            : t(\"editAllAnswers\");\n        editAllToggle.setAttribute(\"aria-expanded\", String(open));\n    }\n    editAllToggle?.addEventListener(\"click\", () => setFullForm(!showFullForm));\n\n    function labelsOf(tpl: PromptTemplate): Record<string, string> {\n        const out: Record<string, string> = {};\n        for (const q of tpl.questions) out[q.key] = pick(q.label);\n        return out;\n    }\n\n    /** Focus a field of the form (opened first in revision mode). */\n    function focusField(key: string): void {\n        if (!showFullForm) setFullForm(true);\n        form?.focusField(key);\n    }\n\n    /** \"Still to fill in:\" and a link per field, by its visible label. */\n    function showMissing(keys: string[]): void {\n        const labels = labelsOf(template);\n        missingNote.replaceChildren(\n            el(\"span\", { text: `${t(\"stillMissing\")} ` }),\n            ...keys.flatMap((key, index) => {\n                const link = el(\n                    \"a\",\n                    { href: `#q-${key}`, class: \"cocoder-missing__link\" },\n                    labels[key] ?? key,\n                );\n                link.addEventListener(\"click\", (event) => {\n                    event.preventDefault();\n                    focusField(key);\n                });\n                return index === 0\n                    ? [link]\n                    : [document.createTextNode(\" · \"), link];\n            }),\n        );\n        missingNote.hidden = keys.length === 0;\n    }\n\n    /** The prompt as shown: an empty required slot by its label, not its key. */\n    function shownPrompt(text: string): string {\n        const labels = labelsOf(template);\n        return text.replace(\n            /⚠ missing: ([A-Za-z0-9_.]+)/g,\n            (_match, key: string) =>\n                `⚠ ${t(\"missingSlot\")}: ${labels[key] ?? key}`,\n        );\n    }\n\n    generateButton.addEventListener(\"click\", () => {\n        if (!args.revisionMode) {\n            const missing = form?.missing() ?? [];\n            if (missing.length > 0 || !ready) {\n                form?.validate();\n                showMissing(missing);\n                if (missing[0]) focusField(missing[0]);\n                return;\n            }\n        } else if (!ready) {\n            changesError.textContent = t(\"errNothingToChange\");\n            changesError.hidden = false;\n            changesInput?.setAttribute(\"aria-invalid\", \"true\");\n            changesInput?.setAttribute(\"aria-describedby\", \"changes-error\");\n            changesInput?.focus();\n            return;\n        }\n        args.onGenerate(\n            args.revisionMode ? \"revision\" : \"initial\",\n            changesInput?.value ?? \"\",\n        );\n    });\n\n    function mountForm(): void {\n        const saved = { ...args.currentAnswers } as Answers;\n        const built = createPromptForm(template, saved, () =>\n            update(built.getAnswers()),\n        );\n        form = built;\n        clear(formHost);\n        formHost.append(built.element);\n        formHost.hidden = !showFullForm;\n        update(built.getAnswers());\n        args.onMounted({\n            form: built,\n            refresh: () => update(built.getAnswers()),\n        });\n\n        built.element.addEventListener(\"focusin\", () =>\n            args.onFocusChange(true),\n        );\n        built.element.addEventListener(\"focusout\", () =>\n            args.onFocusChange(false),\n        );\n        changesInput?.addEventListener(\"input\", () =>\n            update(built.getAnswers()),\n        );\n        changesInput?.addEventListener(\"focus\", () =>\n            args.onFocusChange(true),\n        );\n        changesInput?.addEventListener(\"blur\", () =>\n            args.onFocusChange(false),\n        );\n\n        function update(answers: Answers): void {\n            args.onAnswersChange(answers, template.id);\n\n            if (!args.revisionMode) {\n                const result = interpolate(\n                    template.prompt,\n                    { ...answers, preset: template.preset },\n                    optionalKeys(template),\n                );\n                output.textContent = shownPrompt(result.text);\n                args.onPromptGenerated(result.text);\n                // The list is there from the start without in-app generation (the\n                // prompt is copied by hand); with it, once a press found gaps, and\n                // it shrinks as they are filled in.\n                if (!args.generateEnabled || !missingNote.hidden)\n                    showMissing(result.missing);\n                downloadButton.hidden = true;\n                ready = result.missing.length === 0;\n                syncButton();\n                return;\n            }\n\n            // Revision mode: the generated prompt wraps the current HTML + a\n            // free-text \"what to change\" + auto-listed field diffs.\n            const diffs = diffAnswers(\n                args.baseAnswers,\n                answers,\n                labelsOf(template),\n            );\n            const diffText = formatDiff(diffs);\n            const revisionTemplate =\n                template.revision ?? DEFAULT_REVISION_PROMPT;\n            const prompt = buildRevisionPrompt({\n                template: revisionTemplate,\n                html: args.currentHtml,\n                changes: changesInput?.value.trim() ?? \"\",\n                diff: diffText,\n            });\n            output.textContent = prompt;\n            args.onPromptGenerated(prompt);\n            missingNote.hidden = true;\n            downloadButton.hidden =\n                new TextEncoder().encode(args.currentHtml).length <= 60_000;\n            ready = Boolean(\n                (changesInput?.value.trim() ?? \"\") || diffs.length,\n            );\n            if (ready) {\n                changesError.hidden = true;\n                changesInput?.removeAttribute(\"aria-invalid\");\n                changesInput?.removeAttribute(\"aria-describedby\");\n            }\n            syncButton();\n        }\n    }\n\n    picker.addEventListener(\"change\", async () => {\n        template = await api.template(picker.value);\n        mountForm();\n    });\n\n    // Besides the statusbar note, confirm on the button itself — that is\n    // where the eyes are when clicking.\n    let copiedTimer: number | undefined;\n    copyButton.addEventListener(\"click\", async () => {\n        const copied = await copyToClipboard(output.textContent ?? \"\");\n        args.notify(copied ? t(\"promptCopied\") : t(\"copyFailed\"));\n        if (copied) {\n            copyButton.textContent = t(\"copied\");\n            window.clearTimeout(copiedTimer);\n            copiedTimer = window.setTimeout(() => {\n                copyButton.textContent = t(\"copyPrompt\");\n            }, 2000);\n        }\n    });\n    downloadButton.addEventListener(\"click\", () =>\n        downloadHtml(args.currentHtml, \"cocoder-current\"),\n    );\n    nextButton.addEventListener(\"click\", args.onNext);\n\n    formPane.append(\n        el(\n            \"header\",\n            { class: \"study-pane__head\" },\n            el(\"h2\", {\n                class: \"study-pane__title\",\n                text: args.revisionMode\n                    ? t(\"whatAreYouChanging\")\n                    : t(\"whatAreYouMaking\"),\n            }),\n            editAllToggle,\n        ),\n        el(\n            \"div\",\n            { class: \"study-pane__body\" },\n            el(\n                \"div\",\n                { class: \"ss-stack ss-stack--loose\" },\n                summaries.length > 1\n                    ? el(\n                          \"div\",\n                          { class: \"ss-field\" },\n                          el(\n                              \"label\",\n                              { class: \"ss-label\", for: \"template\" },\n                              t(\"whatAreYouMaking\"),\n                          ),\n                          picker,\n                      )\n                    : null,\n                changesField,\n                formHost,\n            ),\n        ),\n    );\n\n    mountForm();\n    return {\n        element: workbench,\n        paneSwitch: switcher?.element,\n        // One primary action at the foot of the screen (sticky on a phone):\n        // what is missing, the progress and the button.\n        actions: args.generateEnabled\n            ? [\n                  el(\n                      \"div\",\n                      { class: \"cocoder-dock-status\" },\n                      missingNote,\n                      progress.element,\n                  ),\n                  generateButton,\n              ]\n            : [],\n    };\n}\n\n// ---- Step 2: preview -------------------------------------------------\n\ninterface PreviewStepArgs {\n    /** The group's current HTML: rendered in the preview, NOT put in the\n     * editor — the paste field always starts empty (roadmap 0.5 §5). */\n    currentHtml: string;\n    /** With in-app generation on, the editor is \"your page's code\", not a\n     * paste target (roadmap 0.6 §4): it starts with the current HTML, and a\n     * running generation streams into it and into the preview. */\n    generateEnabled: boolean;\n    onGenerationView: (view: GenerationView) => void;\n    onRetry: () => void;\n    notify: (message: string) => void;\n    onHtmlChange: (html: string) => void;\n    onFocusChange: (focused: boolean) => void;\n    onChangeSomething: () => void;\n    onLooksGood: () => void;\n    group: { code: string };\n}\n\nasync function buildPreviewStep(args: PreviewStepArgs): Promise<\n    StepMount & {\n        editor: Editor;\n        refresh: (html: string) => void;\n        setCodeQuiet: (html: string) => void;\n    }\n> {\n    // The code editor (CodeMirror) is most of the bundle: it is loaded when\n    // the preview step first opens, so the start, group and form screens\n    // stay light.\n    const { createEditor } = await import(\"../components/editor\");\n    const iframe = el(\"iframe\", {\n        class: \"study-preview__frame\",\n        sandbox: EDIT_SANDBOX,\n        title: t(\"livePreview\"),\n    }) as HTMLIFrameElement;\n    const preview = createPreview(iframe, EDIT_SANDBOX);\n\n    // ---- Fullscreen preview (roadmap 0.7.0 §3) ---------------------------\n    // The same iframe (same sandbox) is laid over the whole viewport; a big,\n    // labelled Close button stays pinned in the corner. Escape and the\n    // browser back button close it too (a history entry is pushed on open).\n    const closeButton = el(\n        \"button\",\n        {\n            class: \"ss-btn ss-btn--primary study-preview__close\",\n            type: \"button\",\n            \"aria-label\": t(\"closeFullscreen\"),\n            hidden: true,\n        },\n        el(\"span\", { text: t(\"closeFullscreen\") }),\n        el(\"span\", { \"aria-hidden\": \"true\", text: \"✕\" }),\n    );\n    const stage = el(\"div\", { class: \"study-preview\" }, iframe, closeButton);\n    const fullscreenButton = el(\n        \"button\",\n        { class: \"ss-btn ss-btn--sm\", type: \"button\" },\n        t(\"fullscreen\"),\n    );\n    let fullscreen = false;\n    const FS_STATE = \"cocoder-fullscreen\";\n\n    function onKey(event: KeyboardEvent): void {\n        if (event.key === \"Escape\") closeFullscreen(false);\n    }\n    function onPop(): void {\n        if (fullscreen) closeFullscreen(true);\n    }\n    function openFullscreen(): void {\n        if (fullscreen) return;\n        fullscreen = true;\n        iframe.classList.add(\"study-preview__frame--fullscreen\");\n        closeButton.hidden = false;\n        // Nothing behind the page may scroll meanwhile.\n        document.documentElement.style.overflow = \"hidden\";\n        history.pushState({ [FS_STATE]: true }, \"\");\n        document.addEventListener(\"keydown\", onKey);\n        window.addEventListener(\"popstate\", onPop);\n        closeButton.focus();\n    }\n    function closeFullscreen(fromHistory: boolean): void {\n        if (!fullscreen) return;\n        fullscreen = false;\n        iframe.classList.remove(\"study-preview__frame--fullscreen\");\n        closeButton.hidden = true;\n        document.documentElement.style.overflow = \"\";\n        document.removeEventListener(\"keydown\", onKey);\n        window.removeEventListener(\"popstate\", onPop);\n        if (\n            !fromHistory &&\n            (history.state as Record<string, unknown> | null)?.[FS_STATE]\n        )\n            history.back();\n        fullscreenButton.focus();\n    }\n    fullscreenButton.addEventListener(\"click\", openFullscreen);\n    closeButton.addEventListener(\"click\", () => closeFullscreen(false));\n\n    const editorHost = el(\"div\", { class: \"study-editor\" });\n    const pasteHint = el(\n        \"aside\",\n        { class: \"study-banner study-banner--info\", role: \"note\" },\n        el(\"p\", {\n            class: \"study-banner__text\",\n            text: args.generateEnabled ? t(\"editCodeHint\") : t(\"pasteHint\"),\n        }),\n    );\n    const editButton = el(\n        \"button\",\n        { class: \"ss-btn ss-btn--sm\", type: \"button\" },\n        t(\"editCurrentHtml\"),\n    );\n    let hasCurrent = args.currentHtml.trim().length > 0;\n\n    // An empty editor is the \"paste here\" state: it never saves \"\" over the\n    // group's HTML. The first non-empty content replaces the current HTML\n    // (which stays reachable as a version).\n    // setCode() fires the change listener like a keystroke; `quiet` is on\n    // while code is put in from outside (seeding, a poll, a streaming\n    // generation) so nothing of that is autosaved as the group's page.\n    let quiet = false;\n    function accept(code: string): void {\n        if (quiet || !code.trim()) return;\n        hasCurrent = true;\n        pasteHint.hidden = true;\n        editButton.hidden = true;\n        args.onHtmlChange(code);\n        preview.schedule(code);\n    }\n\n    const editor = createEditor(editorHost, \"\", accept);\n    editor.setDark(isDark());\n    preview.render(args.currentHtml);\n    function setCodeQuiet(code: string): void {\n        quiet = true;\n        try {\n            editor.setCode(code);\n        } finally {\n            quiet = false;\n        }\n    }\n    if (args.generateEnabled && hasCurrent) {\n        // Generated flow: the code is right there, not behind \"edit\" (0.6 §4).\n        setCodeQuiet(args.currentHtml);\n        pasteHint.hidden = true;\n        editButton.hidden = true;\n    } else {\n        pasteHint.hidden = !hasCurrent;\n        editButton.hidden = !hasCurrent;\n    }\n    editButton.addEventListener(\"click\", () => {\n        editor.setCode(args.currentHtml);\n        pasteHint.hidden = true;\n        editButton.hidden = true;\n    });\n    editor.view.dom.addEventListener(\"focusin\", () =>\n        args.onFocusChange(true),\n    );\n    editor.view.dom.addEventListener(\"focusout\", () => {\n        args.onFocusChange(false);\n        if (editor.getCode().trim()) args.onHtmlChange(editor.getCode());\n    });\n\n    const fileInput = el(\"input\", {\n        type: \"file\",\n        accept: \".html,.htm,text/html\",\n        hidden: true,\n    }) as HTMLInputElement;\n\n    // The device switch: the frame's width (the theme's `--tablet` / `--mobile`).\n    const deviceButtons = DEVICES.map(([device, shapes]) => {\n        const button = el(\"button\", {\n            type: \"button\",\n            title: t(device),\n            \"aria-label\": t(device),\n        });\n        button.append(icon(shapes));\n        button.addEventListener(\"click\", () => setDevice(device));\n        return { device, button };\n    });\n    function setDevice(device: Device): void {\n        for (const other of DEVICES)\n            iframe.classList.remove(`study-preview__frame--${other[0]}`);\n        if (device !== \"desktop\")\n            iframe.classList.add(`study-preview__frame--${device}`);\n        for (const b of deviceButtons)\n            b.button.setAttribute(\"aria-pressed\", String(b.device === device));\n    }\n    setDevice(\"desktop\");\n    const devices = el(\n        \"div\",\n        {\n            class: \"study-devices\",\n            role: \"group\",\n            \"aria-label\": t(\"previewSize\"),\n        },\n        ...deviceButtons.map((b) => b.button),\n    );\n\n    // ---- Versions: every pasted/edited HTML state the group saved ----------\n\n    // The list takes the preview's place in its pane while it is open.\n    const versionsButton = el(\n        \"button\",\n        { class: \"ss-btn\", type: \"button\", \"aria-expanded\": \"false\" },\n        t(\"versions\"),\n    );\n    const versionsList = el(\"div\", { class: \"study-revisions\" });\n    const versionsPanel = el(\n        \"div\",\n        { class: \"study-pane__body\", hidden: true },\n        versionsList,\n    );\n\n    function showVersions(open: boolean): void {\n        versionsPanel.hidden = !open;\n        stage.hidden = open;\n        versionsButton.setAttribute(\"aria-expanded\", String(open));\n    }\n\n    async function toggleVersions(): Promise<void> {\n        if (!versionsPanel.hidden) {\n            showVersions(false);\n            return;\n        }\n        const token = tokenFor(args.group.code);\n        if (!token) return;\n        try {\n            const revisions: RevisionSummary[] = await api.revisions(\n                args.group.code,\n                token,\n            );\n            clear(versionsList);\n            if (revisions.length === 0) {\n                versionsList.append(\n                    el(\"p\", {\n                        class: \"study-empty\",\n                        text: t(\"noVersionsYet\"),\n                    }),\n                );\n            }\n            // Newest first; number so the newest is the highest.\n            revisions.forEach((revision, index) => {\n                const number = revisions.length - index;\n                const row = el(\n                    \"div\",\n                    { class: \"study-revisions__row\" },\n                    el(\"strong\", { text: `${t(\"version\")} ${number}` }),\n                    el(\"span\", {\n                        text: new Date(revision.createdAt).toLocaleString(),\n                    }),\n                    el(\"span\", {\n                        class: \"ss-muted\",\n                        text: formatBytes(revision.sizeBytes),\n                    }),\n                    el(\n                        \"button\",\n                        { class: \"ss-btn ss-btn--sm\", type: \"button\" },\n                        t(\"restore\"),\n                    ),\n                );\n                row.querySelector(\"button\")?.addEventListener(\n                    \"click\",\n                    async () => {\n                        let html: string;\n                        try {\n                            ({ html } = await api.revisionHtml(\n                                args.group.code,\n                                revision.id,\n                                token,\n                            ));\n                        } catch {\n                            args.notify(t(\"versionsLoadFailed\"));\n                            return;\n                        }\n                        editor.setCode(html);\n                        accept(html);\n                        preview.render(html);\n                        showVersions(false);\n                        args.notify(t(\"restored\"));\n                    },\n                );\n                versionsList.append(row);\n            });\n            showVersions(true);\n            // On a phone the list is in the preview's pane.\n            switcher.show(1);\n        } catch {\n            args.notify(t(\"versionsLoadFailed\"));\n        }\n    }\n    versionsButton.addEventListener(\"click\", () => void toggleVersions());\n\n    const buttons = [\n        action(t(\"beautify\"), async () => {\n            const code = editor.getCode();\n            if (!code.trim()) return;\n            editor.setCode(await formatHtml(code));\n            accept(editor.getCode());\n            args.notify(t(\"beautified\"));\n        }),\n        action(t(\"importFile\"), () => fileInput.click()),\n        action(t(\"download\"), () =>\n            downloadHtml(\n                editor.getCode().trim() ? editor.getCode() : args.currentHtml,\n                \"cocoder\",\n            ),\n        ),\n        action(t(\"run\"), () => {\n            const code = editor.getCode();\n            accept(code);\n            preview.render(code.trim() ? code : args.currentHtml);\n            args.notify(t(\"previewUpdated\"));\n        }),\n    ];\n\n    async function openFile(file: File): Promise<void> {\n        const text = await readFileAsText(file);\n        editor.setCode(text);\n        accept(text);\n        preview.render(text);\n        args.notify(`${t(\"opened\")} ${file.name}`);\n    }\n\n    fileInput.addEventListener(\"change\", async () => {\n        const file = fileInput.files?.[0];\n        if (!file) return;\n        await openFile(file);\n        fileInput.value = \"\";\n    });\n\n    editorHost.addEventListener(\"dragover\", (event) => {\n        if (!event.dataTransfer?.types.includes(\"Files\")) return;\n        event.preventDefault();\n        editorHost.classList.add(\"is-dropping\");\n    });\n    editorHost.addEventListener(\"dragleave\", () => {\n        editorHost.classList.remove(\"is-dropping\");\n    });\n    editorHost.addEventListener(\"drop\", (event) => {\n        event.preventDefault();\n        editorHost.classList.remove(\"is-dropping\");\n        const file = event.dataTransfer?.files?.[0];\n        if (file) void openFile(file);\n    });\n\n    const changeButton = el(\n        \"button\",\n        { class: \"ss-btn\", type: \"button\" },\n        t(\"changeSomething\"),\n    ) as HTMLButtonElement;\n    changeButton.addEventListener(\"click\", args.onChangeSomething);\n    const looksGoodButton = el(\n        \"button\",\n        { class: \"ss-btn ss-btn--primary\", type: \"button\" },\n        t(\"looksGood\"),\n    ) as HTMLButtonElement;\n    looksGoodButton.addEventListener(\"click\", args.onLooksGood);\n\n    // ---- the generation, watched here (roadmap 0.6 §3) ----------------------\n    const progress = statusLine();\n    const retryButton = el(\n        \"button\",\n        { class: \"ss-btn ss-btn--sm\", type: \"button\", hidden: true },\n        t(\"tryAgainButton\"),\n    );\n    retryButton.addEventListener(\"click\", args.onRetry);\n    // A bar between the pane's head and the frame, there while there is news.\n    const progressBar = el(\n        \"div\",\n        { class: \"study-preview__bar\", hidden: true },\n        progress.element,\n        retryButton,\n    );\n    let ticker: number | undefined;\n    let lastRendered = \"\";\n    const generationView: GenerationView = {\n        set(state) {\n            window.clearInterval(ticker);\n            ticker = undefined;\n            const busy =\n                state.phase === \"starting\" ||\n                state.phase === \"queued\" ||\n                state.phase === \"running\";\n            progressBar.hidden = state.phase === \"idle\";\n            retryButton.hidden = state.phase !== \"error\";\n            changeButton.disabled = busy;\n            looksGoodButton.disabled = busy || !hasCurrent;\n            if (state.phase === \"starting\") {\n                progress.set(\"busy\", \"…\");\n            } else if (state.phase === \"queued\") {\n                const position = state.position\n                    ? ` · ${t(\"generatingPosition\")} ${state.position}`\n                    : \"\";\n                progress.set(\n                    \"busy\",\n                    `${state.mine ? t(\"generatingQueued\") : t(\"generatingByOther\")}${position}`,\n                );\n            } else if (state.phase === \"running\") {\n                const tick = (): void => {\n                    progress.set(\n                        \"busy\",\n                        `${state.mine ? t(\"watchItBuild\") : t(\"generatingByOther\")} · ${elapsedSeconds(state.since)} ${t(\"generatingElapsed\")}`,\n                    );\n                };\n                tick();\n                ticker = window.setInterval(tick, 1000);\n            } else if (state.phase === \"error\") {\n                progress.set(\n                    \"error\",\n                    `${t(\"generateFailed\")}: ${state.message}`,\n                );\n                // Whatever was streaming is gone; the current page comes back.\n                lastRendered = \"\";\n                if (hasCurrent) {\n                    setCodeQuiet(args.currentHtml);\n                    preview.render(args.currentHtml);\n                }\n            } else {\n                progress.set(\"idle\");\n            }\n        },\n        showPartial(text) {\n            const html = documentFromPartial(text);\n            if (html === null || html === lastRendered) return;\n            lastRendered = html;\n            setCodeQuiet(html);\n            preview.render(renderablePartial(html));\n        },\n    };\n    window.addEventListener(\"pagehide\", () => window.clearInterval(ticker), {\n        once: true,\n    });\n    args.onGenerationView(generationView);\n\n    const editorPane = el(\n        \"section\",\n        { class: \"study-pane\" },\n        el(\n            \"header\",\n            { class: \"study-pane__head\" },\n            el(\"h2\", {\n                class: \"study-pane__title\",\n                text: args.generateEnabled\n                    ? t(\"yourCode\")\n                    : t(\"pasteYourHtml\"),\n            }),\n            el(\n                \"div\",\n                { class: \"ss-toolbar ss-toolbar--wrap\" },\n                editButton,\n                ...buttons,\n                fileInput,\n            ),\n        ),\n        pasteHint,\n        editorHost,\n    );\n    const previewPane = el(\n        \"section\",\n        { class: \"study-pane\" },\n        el(\n            \"header\",\n            { class: \"study-pane__head\" },\n            el(\"h2\", { class: \"study-pane__title\", text: t(\"livePreview\") }),\n            el(\"div\", { class: \"ss-toolbar\" }, devices, fullscreenButton),\n        ),\n        progressBar,\n        stage,\n        versionsPanel,\n    );\n    const element = el(\n        \"div\",\n        { class: \"study-workbench\" },\n        editorPane,\n        previewPane,\n    );\n    const switcher = paneSwitch([\n        [t(\"paneHtml\"), editorPane],\n        [t(\"panePreview\"), previewPane],\n    ]);\n    // A phone opens on the page itself, not on its code: the code pane is\n    // the first only when there is nothing to show yet (the paste flow).\n    if (hasCurrent || args.generateEnabled) switcher.show(1);\n    // After a paste on a phone, jump to the preview pane so the result is\n    // visible without hunting for the switch.\n    editor.view.dom.addEventListener(\"paste\", () => {\n        window.setTimeout(() => {\n            if (editor.getCode().trim()) switcher.show(1);\n        }, 50);\n    });\n\n    function refresh(html: string): void {\n        args.currentHtml = html;\n        if (!editor.getCode().trim()) preview.render(html);\n        hasCurrent = html.trim().length > 0;\n        if (!editor.getCode().trim()) {\n            pasteHint.hidden = !hasCurrent;\n            editButton.hidden = !hasCurrent;\n        }\n    }\n\n    return {\n        element,\n        paneSwitch: switcher.element,\n        // The step's actions, in the dock at the foot of the screen.\n        actions: [versionsButton, changeButton, looksGoodButton],\n        editor,\n        refresh,\n        setCodeQuiet,\n    };\n}\n\nfunction action(\n    label: string,\n    handler: () => void | Promise<void>,\n): HTMLElement {\n    const button = el(\n        \"button\",\n        { class: \"ss-btn ss-btn--sm\", type: \"button\" },\n        label,\n    );\n    button.addEventListener(\"click\", () => void handler());\n    return button;\n}\n\nfunction tokenFor(code: string): string | null {\n    const membership = session.identity.membership(code);\n    return membership?.token ?? null;\n}\n\n// ---- Step 3: submit ---------------------------------------------------\n\ninterface SubmitStepArgs {\n    group: {\n        code: string;\n        name: string;\n        participants: { name: string }[];\n        page: PageState;\n        published: { publicId: string } | null;\n    };\n    getHtml: () => string;\n    flushSave: () => Promise<boolean>;\n    notify: (message: string) => void;\n    onBack: () => void;\n}\n\nfunction buildSubmitStep(args: SubmitStepArgs): HTMLElement {\n    // The gallery shows the group's name already: the credits start empty\n    // (a credit that only repeats the group name would show it twice).\n    const savedCredits = (args.group.page.credits || \"\").trim();\n    const defaultCredits =\n        savedCredits === (args.group.name || \"\").trim() ? \"\" : savedCredits;\n\n    // Prefill the title with the solution's name and the description with\n    // its tagline — nobody should retype what the form already has.\n    const answers = args.group.page.answers as Record<string, unknown>;\n    const ideaName =\n        typeof answers?.idea_name === \"string\" ? answers.idea_name.trim() : \"\";\n    const tagline =\n        typeof answers?.tagline === \"string\" ? answers.tagline.trim() : \"\";\n\n    const title = el(\"input\", {\n        class: \"ss-input\",\n        id: \"title\",\n        type: \"text\",\n        maxlength: 120,\n        placeholder: t(\"pageTitlePlaceholder\"),\n    }) as HTMLInputElement;\n    title.value = args.group.page.title || ideaName;\n\n    const description = el(\"input\", {\n        class: \"ss-input\",\n        id: \"description\",\n        type: \"text\",\n        maxlength: 200,\n        placeholder: t(\"descriptionPlaceholder\"),\n    }) as HTMLInputElement;\n    description.value = args.group.page.description || tagline;\n\n    const credits = el(\"input\", {\n        class: \"ss-input\",\n        id: \"credits\",\n        type: \"text\",\n        maxlength: 200,\n        placeholder: t(\"creditsPlaceholder\"),\n    }) as HTMLInputElement;\n    credits.value = defaultCredits;\n\n    const error = el(\"p\", {\n        class: \"study-status study-status--error\",\n        role: \"alert\",\n    });\n    const publishButton = el(\n        \"button\",\n        { class: \"ss-btn ss-btn--primary ss-btn--lg\", type: \"button\" },\n        args.group.published ? t(\"republish\") : t(\"publish\"),\n    );\n    const backButton = el(\n        \"button\",\n        { class: \"ss-btn\", type: \"button\" },\n        t(\"keepWorking\"),\n    );\n    backButton.addEventListener(\"click\", args.onBack);\n\n    publishButton.addEventListener(\"click\", async () => {\n        if (!title.value.trim()) {\n            error.textContent = t(\"titleFirst\");\n            title.focus();\n            return;\n        }\n        const token = tokenFor(args.group.code);\n        if (!token) {\n            error.textContent = t(\"notSignedIn\");\n            return;\n        }\n        error.textContent = \"\";\n        publishButton.disabled = true;\n        try {\n            // The server publishes its saved copy of the page: an edit still in\n            // the autosave debounce (or a save that failed) would be left out.\n            if (!(await args.flushSave())) {\n                error.textContent = t(\"saveFailed\");\n                publishButton.disabled = false;\n                return;\n            }\n            const published = await api.publish(args.group.code, token, {\n                title: title.value.trim(),\n                description: description.value.trim(),\n                credits: credits.value.trim(),\n            });\n            if (!galleryIsPublic()) {\n                // No gallery to go to: the publish is confirmed here.\n                error.textContent = t(\"publishedNoGallery\");\n                publishButton.disabled = false;\n                return;\n            }\n            navigate(`gallery?p=${encodeURIComponent(published.publicId)}`);\n        } catch (cause) {\n            // What was typed stays; the reason stays until the next press.\n            error.textContent =\n                cause instanceof ApiError && cause.status === 413\n                    ? t(\"tooBig\")\n                    : errorCode(cause) && errorCode(cause) !== \"unknown\"\n                      ? errorMessage(cause)\n                      : t(\"publishFailed\");\n            publishButton.disabled = false;\n        }\n    });\n\n    return el(\n        \"div\",\n        { class: \"study-page study-page--narrow\" },\n        el(\n            \"header\",\n            { class: \"study-page-head\" },\n            el(\n                \"div\",\n                { class: \"ss-stack\" },\n                el(\"h2\", {\n                    class: \"study-page-head__title\",\n                    text: t(\"publishYourPage\"),\n                }),\n                el(\"p\", { class: \"ss-muted\", text: t(\"publishExplainer\") }),\n            ),\n        ),\n        el(\n            \"div\",\n            { class: \"ss-card\" },\n            el(\n                \"div\",\n                { class: \"study-form study-form--wide\" },\n                el(\n                    \"div\",\n                    { class: \"ss-field\" },\n                    el(\n                        \"label\",\n                        { class: \"ss-label\", for: \"title\" },\n                        t(\"pageTitle\"),\n                    ),\n                    title,\n                ),\n                el(\n                    \"div\",\n                    { class: \"ss-field\" },\n                    el(\n                        \"label\",\n                        { class: \"ss-label\", for: \"description\" },\n                        t(\"description\"),\n                    ),\n                    description,\n                ),\n                el(\n                    \"div\",\n                    { class: \"ss-field\" },\n                    el(\n                        \"label\",\n                        { class: \"ss-label\", for: \"credits\" },\n                        t(\"credits\"),\n                    ),\n                    credits,\n                ),\n                error,\n                el(\n                    \"div\",\n                    { class: \"study-form__actions\" },\n                    backButton,\n                    publishButton,\n                ),\n            ),\n        ),\n    );\n}\n","/** Study Cocoder — client entry. Reads the `#study-app` mount rendered by\n * study-base's app shell (data-app, data-api-base, data-lang,\n * data-workshop), enters the group (study-base's lib/entry, wired in\n * lib/route: the workshop password and the group are the workshop's\n * groups page's, not this app's; a device without them goes there and\n * comes back with them) and routes on the hash (see lib/router.ts). The\n * gallery routes need only the password (`requireAccess`). Port of\n * studio-cocoder src/client/src/main.ts.\n *\n * Two answers of the server take over the whole screen, whichever call\n * got them (lib/errors): a closed workshop (a calm \"this workshop has\n * ended\" panel) and a workshop that does not exist. `#/`, an old\n * `#/group` and an unknown hash route are the work view (`#/work`). The\n * group itself is the workshop's group page (the app bar's chip), and a\n * device out of its group asks where it went (`followOrLeave`: a move by\n * staff reloads this page in the new group). A server that cannot be\n * reached (a restart, study-base's lib/connection) puts a notice under\n * the bar until it answers again (components/connection), also while the\n * entry waits for it at page load (lib/enter). */\n\nimport {\n    followOrLeave,\n    requireAccess,\n} from \"@starling-study/study-base/lib/entry\";\n\nimport {\n    API_ERROR_EVENT,\n    WORKSHOP,\n    WORKSHOP_FROM_STORAGE,\n    api,\n    errorText,\n} from \"./api\";\nimport { applyStoredTheme, createHeader } from \"./components/chrome\";\nimport { mountConnectionBanner } from \"./components/connection\";\nimport { dropPlaceholderName, watchRemoval } from \"./components/members\";\nimport { messageScreen } from \"./lib/dom\";\nimport {\n    isEmbedded,\n    pageLang,\n    rememberLessonTheme,\n    themeFromMessage,\n} from \"./lib/embed\";\nimport { enterGroup } from \"./lib/enter\";\nimport type { ErrorCode } from \"./lib/errors\";\nimport { setFlash } from \"./lib/flash\";\nimport {\n    closedWithoutGallery,\n    galleryIsPublic,\n    publicGalleryOf,\n    setGalleryPublic,\n} from \"./lib/gallery\";\nimport { setDefaultLang, t } from \"./lib/i18n\";\nimport { stashLaunchPrompt } from \"./lib/launch\";\nimport { joinName } from \"./lib/participants\";\nimport { createRoute } from \"./lib/route\";\nimport { currentRoute, href, isRouteHash, routeKey } from \"./lib/router\";\nimport { searchWithoutStoredWorkshop, workshopOf } from \"./lib/workshop\";\nimport { session } from \"./session\";\nimport { renderGallery } from \"./views/gallery\";\nimport { renderViewer } from \"./views/viewer\";\nimport { renderWork } from \"./views/work\";\n\n// A lesson's `?prompt=` / `?task=` waits in sessionStorage until the work\n// view shows it.\nstashLaunchPrompt();\n\nconst root = document.getElementById(\"study-app\");\n\n/** Once a workshop-wide panel is up, nothing renders over it. */\nlet takenOver = false;\n\n/** The whole screen for a closed or unknown workshop. */\nfunction renderWorkshopPanel(mount: HTMLElement, code: ErrorCode): void {\n    if (takenOver) return;\n    takenOver = true;\n    applyStoredTheme();\n    mount.classList.remove(\"study-app--fill\");\n    const closed = code === \"workshop_closed\";\n    const panel = closed\n        ? messageScreen(t(\"workshopClosedTitle\"), t(\"workshopClosedText\"))\n        : messageScreen(\n              t(\"workshopNotFoundTitle\"),\n              errorText(\"workshop_not_found\"),\n          );\n    mount.replaceChildren(\n        ...createHeader({ showGroup: false, showIntro: false }),\n        panel,\n    );\n}\n\n/** The workshop stored for the active group is closed or gone, and the\n * address named none (a bookmark, or a join link of the default workshop):\n * not the full-page panel, which has no way out, but the default\n * workshop (its groups page, after the reload), with a message. */\nfunction leaveStoredWorkshop(code: ErrorCode): void {\n    if (takenOver) return;\n    takenOver = true;\n    const activeCode = session.membership?.code ?? null;\n    session.leaveToStart();\n    setFlash(\n        t(\n            code === \"workshop_closed\"\n                ? \"errWorkshopClosed\"\n                : \"errWorkshopNotFound\",\n        ),\n    );\n    history.replaceState(\n        history.state,\n        \"\",\n        `${location.pathname}${searchWithoutStoredWorkshop(location.search, activeCode)}${href(\"\")}`,\n    );\n    location.reload();\n}\n\n/** The route of this page load (lib/route); `rendered` is its key, which\n * a hashchange compares with (a move to another top-level route reloads). */\nfunction createAppRoute(\n    mount: HTMLElement,\n    onHomeAddress: () => void,\n): ReturnType<typeof createRoute> {\n    return createRoute({\n        halted: () => takenOver,\n        requireAccess: () => requireAccess(),\n        requireGroup: () => {\n            // A group joined in another workshop is not this page's (cocoder\n            // keeps the workshop per group itself, lib/workshop): not\n            // forgotten, but not entered here either.\n            const active = session.membership;\n            if (\n                active &&\n                workshopOf(active.code) &&\n                workshopOf(active.code) !== WORKSHOP\n            )\n                session.leaveToStart();\n            // A device joins under the name it gave in any app of the\n            // workshop, else under the placeholder (lib/participants). A\n            // server away meanwhile (a restart) puts the notice under the\n            // bar while the entry tries again (lib/enter).\n            return enterGroup({\n                session,\n                joinName: () => joinName(session.userName),\n            });\n        },\n        afterEntry: () => dropPlaceholderName(),\n        hasMembership: () => session.membership !== null,\n        leaveForGroups: () => void followOrLeave(),\n        closedPanel: async (view) => {\n            // The workshop's gallery switch: the bar and the routes read it.\n            setGalleryPublic(\n                publicGalleryOf(await api.generateStatus().catch(() => null)),\n            );\n            if (!closedWithoutGallery(view, galleryIsPublic())) return false;\n            applyStoredTheme();\n            mount.replaceChildren(\n                ...createHeader(),\n                messageScreen(t(\"galleryOffTitle\"), t(\"galleryOffText\"), {\n                    href: href(\"\"),\n                    label: t(\"toStart\"),\n                }),\n            );\n            return true;\n        },\n        showHomeAddress: () => {\n            history.replaceState(\n                history.state,\n                \"\",\n                `${location.pathname}${location.search}${href(\"work\")}`,\n            );\n            onHomeAddress();\n        },\n        render: (view, param) => {\n            if (view === \"gallery\") return renderGallery(mount);\n            if (view === \"view\") return renderViewer(mount, param);\n            return renderWork(mount);\n        },\n    });\n}\n\nif (root) {\n    mountApp(root);\n}\n\nfunction mountApp(mount: HTMLElement): void {\n    const data = mount.dataset;\n    const embedded = isEmbedded();\n    // Inside a lesson the lesson's `&lang=` wins over the address prefix.\n    setDefaultLang(pageLang(location.search, data.lang));\n    if (embedded) {\n        // The lesson posts its theme when it changes (same origin only).\n        window.addEventListener(\"message\", (event) => {\n            if (event.origin !== location.origin) return;\n            const theme = themeFromMessage(event.data);\n            if (!theme) return;\n            // Kept for this tab: a route change reloads the page, and the\n            // address's `?theme=` is the lesson's first theme, not its last.\n            rememberLessonTheme(theme, location.search);\n            document.documentElement.dataset.theme = theme;\n        });\n    }\n    // The scope of the app's own few rules (scss/_app.scss). The work screen\n    // and the viewer also take the theme's `study-app--fill` (their views add\n    // it); the other screens scroll with the page.\n    mount.classList.add(\"cocoder-root\");\n    applyStoredTheme();\n    // While the server cannot be reached (a restart): a notice under the\n    // bar, in the page flow: the first child of the mount's parent (the\n    // shell's <main>), so a screen's re-render keeps it.\n    mountConnectionBanner(mount.parentElement ?? document.body);\n    // Inside a lesson there is no bar: the banner sticks to the top edge\n    // (the theme's fallback is the bar's height, a gap over the page).\n    if (embedded)\n        document.documentElement.style.setProperty(\n            \"--study-sticky-top\",\n            \"0px\",\n        );\n\n    window.addEventListener(API_ERROR_EVENT, (event) => {\n        const code = (event as CustomEvent<ErrorCode>).detail;\n        if (code !== \"workshop_closed\" && code !== \"workshop_not_found\")\n            return;\n        if (WORKSHOP_FROM_STORAGE) leaveStoredWorkshop(code);\n        else renderWorkshopPanel(mount, code);\n    });\n    // A participant removed by the workshop leader asks where they went\n    // (moved by staff: this page in the new group; else the groups page).\n    watchRemoval();\n\n    // A move to another top-level route re-renders from scratch, the way the\n    // studio app's page loads did — the work view's step changes stay inside.\n    let rendered = routeKey(currentRoute());\n    // An in-page anchor (`#q-name`) is no route: it stays on the view.\n    window.addEventListener(\"hashchange\", () => {\n        if (!isRouteHash(location.hash)) return;\n        if (routeKey(currentRoute()) !== rendered) location.reload();\n    });\n\n    // `#/`, an old `#/group` and an unknown route are the work view: the\n    // address says so too (`#/work`, the same route key: no reload).\n    const route = createAppRoute(mount, () => {\n        rendered = routeKey(currentRoute());\n    });\n    void route(currentRoute());\n}\n"],"file":"study_cocoder_script.min.js"}