@eloxiv/registry 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/r/desktop-rune/0.6.10.json +415 -0
- package/r/desktop-rune.json +8 -8
- package/r/registry.json +7 -2
- package/r/shell-foldkit/0.8.5.json +158 -0
- package/r/shell-foldkit/0.8.6.json +158 -0
- package/r/shell-foldkit/0.8.7.json +158 -0
- package/r/shell-foldkit.json +11 -5
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "shell-foldkit",
|
|
4
|
+
"title": "Web shell",
|
|
5
|
+
"description": "The web shell on Foldkit (The Elm Architecture over Effect), StyleX and Vite, as a single-page app: sign-in, organisations, routes from the installed views that have a screen, the views modules contribute to a screen's slots beside it, MAKE modules' sandboxed views (/make/<module>), an appearance dialog (light, dark, right to left). Runs on the client core (@eloxiv/client/runtime, in process): its session, organisation, replica, live queries and optimistic writes reach the screens through @eloxiv/client/foldkit. Screens come from UI items (src/screens/).",
|
|
6
|
+
"dependencies": [
|
|
7
|
+
"@eloxiv/client@^0.1.0",
|
|
8
|
+
"@eloxiv/contracts@^0.1.0",
|
|
9
|
+
"@eloxiv/shell-core@^0.1.0",
|
|
10
|
+
"effect@4.1.2",
|
|
11
|
+
"@effect/platform-browser@4.1.2",
|
|
12
|
+
"foldkit@0.170.0",
|
|
13
|
+
"@foldkit/ui@0.170.0",
|
|
14
|
+
"@stylexjs/stylex@0.19.1"
|
|
15
|
+
],
|
|
16
|
+
"devDependencies": [
|
|
17
|
+
"vite@8.3.5",
|
|
18
|
+
"@foldkit/vite-plugin@0.29.0",
|
|
19
|
+
"@stylexjs/unplugin@0.19.1",
|
|
20
|
+
"unplugin@2.3.11"
|
|
21
|
+
],
|
|
22
|
+
"registryDependencies": [
|
|
23
|
+
"app",
|
|
24
|
+
"theme"
|
|
25
|
+
],
|
|
26
|
+
"files": [
|
|
27
|
+
{
|
|
28
|
+
"path": "app/shell-foldkit/index.html",
|
|
29
|
+
"content": "<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Eloxiv</title>\n <!-- Before anything paints: the person's scheme, preset, direction and language (public/boot.js). -->\n <script src=\"/boot.js\"></script>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"/src/main.ts\"></script>\n </body>\n</html>\n",
|
|
30
|
+
"type": "registry:file",
|
|
31
|
+
"target": "shell-foldkit/index.html"
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
"path": "app/shell-foldkit/public/boot.js",
|
|
35
|
+
"content": "/*\n * The shell's pre-paint boot (B-100): run by the page's head before anything is drawn, so a reload or a new tab\n * paints in the person's scheme, preset, direction and language at once, never light first and then dark. It reads\n * what the shell stores (`shell.ts`: `eloxiv.appearance`, `eloxiv.appearance.preset`, `eloxiv.locale`) and applies\n * it to the document root; the shell takes over on its first render. The backgrounds are the theme's own\n * (`themes/default/tokens.ts`, `registry/test/shell-foldkit-lifecycle.test.ts` checks they agree).\n */\n;(function boot(root, media) {\n var store = null\n try {\n store = window.localStorage\n } catch {}\n var BACKGROUNDS = {\n standard: { light: \"oklch(1 0 0)\", dark: \"oklch(0.145 0 0)\" },\n contrast: { light: \"oklch(1 0 0)\", dark: \"oklch(0 0 0)\" },\n }\n var read = function (key) {\n try {\n return store === null ? null : store.getItem(key)\n } catch {\n return null\n }\n }\n var appearance = { scheme: \"system\", direction: \"ltr\" }\n try {\n var stored = JSON.parse(read(\"eloxiv.appearance\") || \"null\")\n if (stored && (stored.scheme === \"light\" || stored.scheme === \"dark\" || stored.scheme === \"system\"))\n appearance.scheme = stored.scheme\n if (stored && (stored.direction === \"ltr\" || stored.direction === \"rtl\")) appearance.direction = stored.direction\n } catch {}\n var preset = read(\"eloxiv.appearance.preset\") === \"contrast\" ? \"contrast\" : \"standard\"\n var dark =\n appearance.scheme === \"dark\" ||\n (appearance.scheme === \"system\" && !!media && media(\"(prefers-color-scheme: dark)\").matches)\n var scheme = dark ? \"dark\" : \"light\"\n root.setAttribute(\"data-theme\", scheme)\n root.setAttribute(\"data-preset\", preset)\n root.setAttribute(\"dir\", appearance.direction)\n var locale = read(\"eloxiv.locale\")\n if (locale === \"en\" || locale === \"ar\") root.setAttribute(\"lang\", locale)\n root.style.colorScheme = scheme\n root.style.backgroundColor = BACKGROUNDS[preset][scheme]\n})(document.documentElement, window.matchMedia && window.matchMedia.bind(window))\n",
|
|
36
|
+
"type": "registry:file",
|
|
37
|
+
"target": "shell-foldkit/public/boot.js"
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
"path": "app/shell-foldkit/screenMeta.ts",
|
|
41
|
+
"content": "/**\n * The shell's build reads each screen's routing fields from its file, so the screen's code can be a chunk of its own,\n * loaded when a route first needs it (`src/installed.ts`).\n *\n * `src/screens/<name>.ts?eloxiv-screen-meta` is a module of the fields its `export const screen = defineScreen({...})`\n * states as plain literals: `view`, `label`, `route`, `title` (strings), `home` (a boolean) and `slots` (strings).\n * When the declaration is not of that form (no call of the shell's own `defineScreen`, imported from `../screen.ts`,\n * on an object; a local function of that name or another; a spread, one of those fields computed, a constant, a\n * template with expressions), the module answers with the screen itself, which then loads with the shell: a screen is\n * never routed by fields that might not be its own. The shell checks a lazy screen's fields again when it loads.\n */\nimport { readFileSync } from \"node:fs\"\nimport { dirname, resolve } from \"node:path\"\nimport { parseSync, type Plugin } from \"vite\"\n\nconst QUERY = \"?eloxiv-screen-meta\"\nconst STRINGS = new Set([\"view\", \"label\", \"route\", \"title\"])\n\ntype Meta = Record<string, string | boolean | ReadonlyArray<string>>\n\n// The parser's ESTree nodes, as far as this reads them.\ninterface Node {\n readonly type: string\n readonly [key: string]: unknown\n}\n\nconst literalString = (node: Node): string | undefined => {\n if (node.type === \"Literal\" && typeof node[\"value\"] === \"string\") return node[\"value\"]\n if (node.type === \"TemplateLiteral\" && (node[\"expressions\"] as ReadonlyArray<Node>).length === 0) {\n const [quasi] = node[\"quasis\"] as ReadonlyArray<{ readonly value: { readonly cooked: string | null } }>\n return quasi?.value.cooked ?? undefined\n }\n return undefined\n}\n\n/**\n * The local name the file gives the shell's `defineScreen` (`import { defineScreen } from \"../screen.ts\"`, renamed or\n * not), or undefined when it imports none: a module-level import binds the name in the whole module.\n */\nconst defineScreenBinding = (file: string, body: ReadonlyArray<Node>): string | undefined => {\n const shellScreen = resolve(dirname(file), \"../screen\")\n for (const statement of body) {\n if (statement.type !== \"ImportDeclaration\" || statement[\"importKind\"] === \"type\") continue\n const source = (statement[\"source\"] as Node)[\"value\"]\n if (typeof source !== \"string\" || resolve(dirname(file), source).replace(/\\.[jt]s$/u, \"\") !== shellScreen) continue\n for (const specifier of statement[\"specifiers\"] as ReadonlyArray<Node>) {\n if (specifier.type !== \"ImportSpecifier\" || specifier[\"importKind\"] === \"type\") continue\n const imported = specifier[\"imported\"] as Node\n const name = imported.type === \"Identifier\" ? imported[\"name\"] : literalString(imported)\n if (name === \"defineScreen\") return (specifier[\"local\"] as Node)[\"name\"] as string\n }\n }\n return undefined\n}\n\n/** The declaration's fields, or undefined when it does not state them all as plain literals. */\nexport const screenMetaOf = (file: string, source: string): Meta | undefined => {\n const { program, errors } = parseSync(file, source)\n if (errors.length > 0) return undefined\n const body = program.body as unknown as ReadonlyArray<Node>\n const defineScreen = defineScreenBinding(file, body)\n if (defineScreen === undefined) return undefined\n for (const statement of body) {\n if (statement.type !== \"ExportNamedDeclaration\") continue\n const declaration = statement[\"declaration\"] as Node | null\n if (declaration?.type !== \"VariableDeclaration\") continue\n for (const declarator of declaration[\"declarations\"] as ReadonlyArray<Node>) {\n const id = declarator[\"id\"] as Node\n if (id.type !== \"Identifier\" || id[\"name\"] !== \"screen\") continue\n const init = declarator[\"init\"] as Node | null\n if (init?.type !== \"CallExpression\") return undefined\n const callee = init[\"callee\"] as Node\n if (callee.type !== \"Identifier\" || callee[\"name\"] !== defineScreen) return undefined\n const [argument] = init[\"arguments\"] as ReadonlyArray<Node>\n if (argument?.type !== \"ObjectExpression\") return undefined\n const meta: Meta = {}\n for (const property of argument[\"properties\"] as ReadonlyArray<Node>) {\n if (property.type !== \"Property\" || property[\"computed\"] === true) return undefined\n const key = property[\"key\"] as Node\n const name = key.type === \"Identifier\" ? key[\"name\"] : literalString(key)\n if (typeof name !== \"string\") return undefined\n const value = property[\"value\"] as Node\n if (STRINGS.has(name)) {\n const text = literalString(value)\n if (text === undefined) return undefined\n meta[name] = text\n } else if (name === \"home\") {\n if (value.type !== \"Literal\" || typeof value[\"value\"] !== \"boolean\") return undefined\n meta[name] = value[\"value\"]\n } else if (name === \"slots\") {\n if (value.type !== \"ArrayExpression\") return undefined\n const slots: Array<string> = []\n for (const element of value[\"elements\"] as ReadonlyArray<Node | null>) {\n const text = element === null ? undefined : literalString(element)\n if (text === undefined) return undefined\n slots.push(text)\n }\n meta[name] = slots\n }\n }\n return typeof meta[\"view\"] === \"string\" ? meta : undefined\n }\n }\n return undefined\n}\n\n/** The Vite plugin: answers `<screen>.ts?eloxiv-screen-meta` with the screen's fields, or with the screen itself. */\nexport const screenMeta = (): Plugin => ({\n name: \"eloxiv:screen-meta\",\n enforce: \"pre\",\n load(id) {\n if (!id.endsWith(QUERY)) return undefined\n const file = id.slice(0, -QUERY.length)\n this.addWatchFile(file)\n const meta = screenMetaOf(file, readFileSync(file, \"utf8\"))\n return meta === undefined\n ? `export { screen as default } from ${JSON.stringify(file)}\\n`\n : `export default ${JSON.stringify(meta)}\\n`\n },\n})\n",
|
|
42
|
+
"type": "registry:file",
|
|
43
|
+
"target": "shell-foldkit/screenMeta.ts"
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
"path": "app/shell-foldkit/src/installed.ts",
|
|
47
|
+
"content": "/**\n * The screens installed in this app: every file in `screens/` that a UI item (or the app) put there, found when\n * the shell is built. A module installed without its UI item has no file here, so its views get no route.\n *\n * Each screen's code is a chunk of its own, loaded when a route first needs it: the shell routes and links it from\n * its declaration's plain fields, which the build reads from the file (`?eloxiv-screen-meta`, `screenMeta.ts`). A\n * file whose fields the build cannot read that way answers with the screen itself, loaded with the shell.\n */\nimport { type AnyScreen, type InstalledScreen, type ScreenMeta } from \"./screen.ts\"\n\nconst metas = import.meta.glob<ScreenMeta | AnyScreen>(\"./screens/*.ts\", {\n eager: true,\n query: \"?eloxiv-screen-meta\",\n import: \"default\",\n})\nconst loaders = import.meta.glob<AnyScreen>(\"./screens/*.ts\", { import: \"screen\" })\n\nexport const installedScreens: ReadonlyArray<InstalledScreen> = Object.keys(loaders)\n .sort()\n .map((path): InstalledScreen => {\n const meta = metas[`${path}?eloxiv-screen-meta`] ?? metas[path]\n if (meta === undefined) throw new Error(`The shell's build read nothing of ${path} (is screenMeta in its plugins?)`)\n // The screen itself (the build could not read its fields), loaded with the shell.\n if (\"init\" in meta) return meta as AnyScreen\n return { meta, load: loaders[path]! }\n })\n",
|
|
48
|
+
"type": "registry:file",
|
|
49
|
+
"target": "shell-foldkit/src/installed.ts"
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
"path": "app/shell-foldkit/src/locale.ts",
|
|
53
|
+
"content": "/**\n * The shell's locale (the Locale contract, through `@eloxiv/shell-core`): its own text as a message catalog in\n * Paraglide's compiled shape (one function per message, of its parameters and a locale), the locale negotiated from\n * the browser's languages (lookup, never a guess) and the writing direction that follows it. English is the base;\n * Arabic shows the shell right to left. UI items carry their own text.\n *\n * An app with more text compiles a Paraglide project and passes its output instead (`paraglideCatalog(runtime,\n * messages)`); the shell reads messages only through `text`.\n */\nimport { directionOf, lookupLocale, type CompiledMessage, type MessageCatalog } from \"@eloxiv/shell-core\"\n\nexport const LOCALES = [\"en\", \"ar\"] as const\nexport type ShellLocale = (typeof LOCALES)[number]\nexport const BASE_LOCALE: ShellLocale = \"en\"\n\n/** Each locale's own name, for the language setting. */\nexport const LANGUAGES: ReadonlyArray<{ readonly value: ShellLocale; readonly label: string }> = [\n { value: \"en\", label: \"English\" },\n { value: \"ar\", label: \"العربية\" },\n]\n\ntype Params = Readonly<Record<string, string | number>>\ntype Text = string | ((params: Params) => string)\n\nconst TEXTS = {\n \"nav.main\": { en: \"Main\", ar: \"الرئيسية\" },\n \"nav.home\": { en: \"Home\", ar: \"البداية\" },\n \"header.appearance\": { en: \"Appearance\", ar: \"المظهر\" },\n \"header.settings\": { en: \"Settings\", ar: \"الإعدادات\" },\n \"header.organisation\": { en: \"Organisation\", ar: \"المؤسسة\" },\n \"header.signOut\": { en: \"Sign out\", ar: \"تسجيل الخروج\" },\n \"signOut.confirmed\": { en: \"Signed out\", ar: \"تم تسجيل الخروج\" },\n \"signOut.revoking\": { en: \"Signing out…\", ar: \"جارٍ تسجيل الخروج…\" },\n \"signOut.pending\": {\n en: \"Signed out on this device; server sign-out pending, retrying\",\n ar: \"تم تسجيل الخروج على هذا الجهاز؛ تسجيل الخروج من الخادم معلّق، وتجري إعادة المحاولة\",\n },\n \"signIn.title\": { en: \"Sign in\", ar: \"تسجيل الدخول\" },\n \"signIn.description\": { en: \"Local email and password (Better Auth).\", ar: \"بريد إلكتروني وكلمة مرور محليان.\" },\n \"signIn.email\": { en: \"Email\", ar: \"البريد الإلكتروني\" },\n \"signIn.password\": { en: \"Password\", ar: \"كلمة المرور\" },\n \"signIn.submit\": { en: \"Sign in\", ar: \"تسجيل الدخول\" },\n \"launcher.title\": { en: \"Modules\", ar: \"الوحدات\" },\n \"launcher.description\": { en: \"Installed in this app through the registry.\", ar: \"مثبّتة في هذا التطبيق من السجل.\" },\n \"launcher.open\": { en: \"Open\", ar: \"فتح\" },\n \"launcher.commands\": { en: \"Commands\", ar: \"الأوامر\" },\n loading: { en: \"Loading…\", ar: \"جارٍ التحميل…\" },\n \"error.notFound.title\": { en: \"Not found\", ar: \"غير موجود\" },\n \"error.notFound.message\": {\n en: (p: Params) => `Nothing is installed at ${p[\"path\"]}.`,\n ar: (p: Params) => `لا شيء مثبّت في ${p[\"path\"]}.`,\n },\n \"error.replica.title\": { en: \"Data unavailable\", ar: \"البيانات غير متاحة\" },\n \"error.replica.message\": {\n en: (p: Params) => `Could not open the replica: ${p[\"reason\"]}`,\n ar: (p: Params) => `تعذّر فتح النسخة المحلية: ${p[\"reason\"]}`,\n },\n \"error.organisations.title\": { en: \"Organisations unavailable\", ar: \"المؤسسات غير متاحة\" },\n \"error.organisations.message\": {\n en: (p: Params) => `Could not load your organisations: ${p[\"reason\"]}`,\n ar: (p: Params) => `تعذّر تحميل مؤسساتك: ${p[\"reason\"]}`,\n },\n \"error.home\": { en: \"Go home\", ar: \"العودة إلى البداية\" },\n \"error.retry\": { en: \"Try again\", ar: \"حاول مرة أخرى\" },\n \"error.signedOut.title\": { en: \"Signed out\", ar: \"تم تسجيل الخروج\" },\n \"error.signedOut.message\": { en: \"Your session has ended. Sign in again.\", ar: \"انتهت جلستك. سجّل الدخول مرة أخرى.\" },\n \"error.forbidden.title\": { en: \"Not allowed\", ar: \"غير مسموح\" },\n \"error.forbidden.message\": { en: \"You are not allowed to see this here.\", ar: \"لا يُسمح لك برؤية هذا هنا.\" },\n \"error.outdated.title\": { en: \"Out of date\", ar: \"إصدار قديم\" },\n \"error.outdated.message\": {\n en: \"This version of the app is out of date. Reload to continue.\",\n ar: \"هذا الإصدار من التطبيق قديم. أعد التحميل للمتابعة.\",\n },\n \"error.offline.title\": { en: \"Cannot reach the app\", ar: \"تعذّر الوصول إلى التطبيق\" },\n \"error.offline.message\": {\n en: \"The app could not be reached. Check the connection and try again.\",\n ar: \"تعذّر الوصول إلى التطبيق. تحقق من الاتصال وحاول مرة أخرى.\",\n },\n \"error.failed.title\": { en: \"Something went wrong\", ar: \"حدث خطأ ما\" },\n \"error.failed.message\": {\n en: \"This view could not be shown. Try again, or go home.\",\n ar: \"تعذّر عرض هذه الصفحة. حاول مرة أخرى أو عُد إلى البداية.\",\n },\n \"error.chunk.title\": { en: \"This page did not load\", ar: \"لم تُحمَّل هذه الصفحة\" },\n \"error.chunk.message\": {\n en: \"Part of the app could not be loaded. This can happen after an update. Reload to continue.\",\n ar: \"تعذّر تحميل جزء من التطبيق. قد يحدث هذا بعد التحديث. أعد التحميل للمتابعة.\",\n },\n \"error.reload\": { en: \"Reload\", ar: \"إعادة التحميل\" },\n \"offline.badge\": { en: \"Offline\", ar: \"غير متصل\" },\n \"offline.detail\": {\n en: \"Showing what this device last synced. Changes are kept here and sent when the connection is back.\",\n ar: \"يُعرض ما زامنه هذا الجهاز آخر مرة. تُحفظ التغييرات هنا وتُرسل عند عودة الاتصال.\",\n },\n \"backend.unreachable\": {\n en: \"The app's server cannot be reached right now; changes wait until it is back.\",\n ar: \"لا يمكن الوصول إلى خادم التطبيق الآن؛ تنتظر التغييرات حتى يعود.\",\n },\n \"backend.notReady\": {\n en: \"The app's server is starting or being updated; some things may not work yet.\",\n ar: \"خادم التطبيق قيد التشغيل أو التحديث؛ قد لا يعمل بعض الأشياء بعد.\",\n },\n \"consent.title\": { en: \"Cookies and tracking\", ar: \"ملفات تعريف الارتباط والتتبع\" },\n \"consent.message\": {\n en: \"This app uses what is necessary to work. May it also use optional features, analytics and marketing?\",\n ar: \"يستخدم هذا التطبيق ما يلزم لعمله. هل يمكنه أيضاً استخدام الميزات الاختيارية والتحليلات والتسويق؟\",\n },\n \"consent.accept\": { en: \"Allow all\", ar: \"السماح بالكل\" },\n \"consent.necessary\": { en: \"Only necessary\", ar: \"الضروري فقط\" },\n \"appearance.preset\": { en: \"Style\", ar: \"النمط\" },\n \"appearance.standard\": { en: \"Standard\", ar: \"قياسي\" },\n \"appearance.contrast\": { en: \"High contrast\", ar: \"تباين عالٍ\" },\n \"settings.editProfile\": { en: \"Change email\", ar: \"غيّر البريد الإلكتروني\" },\n \"settings.saveName\": { en: \"Save name\", ar: \"احفظ الاسم\" },\n \"settings.saving\": { en: \"Saving…\", ar: \"جارٍ الحفظ…\" },\n \"settings.saved\": { en: \"Saved\", ar: \"تم الحفظ\" },\n \"settings.saveFailed\": {\n en: (p: Params) => `Could not save: ${p[\"reason\"]}`,\n ar: (p: Params) => `تعذّر الحفظ: ${p[\"reason\"]}`,\n },\n \"appearance.title\": { en: \"Appearance\", ar: \"المظهر\" },\n \"appearance.description\": {\n en: \"Colours and writing direction for this device.\",\n ar: \"الألوان واتجاه الكتابة لهذا الجهاز.\",\n },\n \"appearance.scheme\": { en: \"Colour scheme\", ar: \"نظام الألوان\" },\n \"appearance.direction\": { en: \"Direction\", ar: \"الاتجاه\" },\n \"appearance.system\": { en: \"System\", ar: \"النظام\" },\n \"appearance.light\": { en: \"Light\", ar: \"فاتح\" },\n \"appearance.dark\": { en: \"Dark\", ar: \"داكن\" },\n \"appearance.ltr\": { en: \"Left to right\", ar: \"من اليسار إلى اليمين\" },\n \"appearance.rtl\": { en: \"Right to left\", ar: \"من اليمين إلى اليسار\" },\n \"appearance.done\": { en: \"Done\", ar: \"تم\" },\n \"desktop.title\": { en: \"Sign in to the desktop app\", ar: \"تسجيل الدخول إلى تطبيق سطح المكتب\" },\n \"desktop.description\": {\n en: (p: Params) => `A desktop app on this computer asks to sign in as ${p[\"email\"]}.`,\n ar: (p: Params) => `يطلب تطبيق سطح مكتب على هذا الحاسوب تسجيل الدخول باسم ${p[\"email\"]}.`,\n },\n \"desktop.warning\": {\n en: \"Approve only if you started signing in from the app yourself, just now. Approving gives the app a session of its own.\",\n ar: \"وافق فقط إذا بدأت تسجيل الدخول من التطبيق بنفسك الآن. الموافقة تمنح التطبيق جلسة خاصة به.\",\n },\n \"desktop.redirect\": { en: \"The app receives the answer at\", ar: \"يتلقى التطبيق الإجابة على\" },\n \"desktop.fingerprint\": { en: \"Request fingerprint\", ar: \"بصمة الطلب\" },\n \"desktop.approve\": { en: \"Approve\", ar: \"موافقة\" },\n \"desktop.decline\": { en: \"Decline\", ar: \"رفض\" },\n \"desktop.approving\": { en: \"Approving…\", ar: \"جارٍ الموافقة…\" },\n \"desktop.approved\": {\n en: \"Approved. Return to the app; you can close this tab.\",\n ar: \"تمت الموافقة. عد إلى التطبيق؛ يمكنك إغلاق هذه الصفحة.\",\n },\n \"desktop.failed\": {\n en: (p: Params) => `The sign-in could not be approved: ${p[\"reason\"]}`,\n ar: (p: Params) => `تعذّرت الموافقة على تسجيل الدخول: ${p[\"reason\"]}`,\n },\n \"desktop.invalid\": {\n en: \"This address does not hold a desktop sign-in to approve. Start signing in again from the app.\",\n ar: \"لا يحمل هذا العنوان طلب تسجيل دخول لسطح المكتب. ابدأ تسجيل الدخول من التطبيق مجددًا.\",\n },\n \"settings.title\": { en: \"Settings\", ar: \"الإعدادات\" },\n \"settings.profile\": { en: \"Profile\", ar: \"الملف الشخصي\" },\n \"settings.name\": { en: \"Name\", ar: \"الاسم\" },\n \"settings.email\": { en: \"Email\", ar: \"البريد الإلكتروني\" },\n \"settings.members\": { en: \"Members\", ar: \"الأعضاء\" },\n \"settings.membersOf\": {\n en: (p: Params) => `People in ${p[\"organisation\"]}, with their roles.`,\n ar: (p: Params) => `الأشخاص في ${p[\"organisation\"]} وأدوارهم.`,\n },\n \"settings.membersFailed\": {\n en: (p: Params) => `Could not load the members: ${p[\"reason\"]}`,\n ar: (p: Params) => `تعذّر تحميل الأعضاء: ${p[\"reason\"]}`,\n },\n \"settings.language\": { en: \"Language\", ar: \"اللغة\" },\n \"settings.languageDescription\": {\n en: \"The shell's language on this device; the writing direction follows it.\",\n ar: \"لغة الواجهة على هذا الجهاز، ويتبعها اتجاه الكتابة.\",\n },\n} satisfies Readonly<Record<string, Readonly<Record<ShellLocale, Text>>>>\n\nexport type MessageId = keyof typeof TEXTS\n\nconst compile =\n (texts: Readonly<Record<ShellLocale, Text>>): CompiledMessage =>\n (params, { locale }) => {\n const chosen = texts[(LOCALES as ReadonlyArray<string>).includes(locale) ? (locale as ShellLocale) : BASE_LOCALE]\n return typeof chosen === \"function\" ? chosen(params) : chosen\n }\n\n/** The shell's catalog (the Locale contract's `MessageCatalog`, as `paraglideCatalog` would give it). */\nexport const catalog: MessageCatalog = {\n baseLocale: BASE_LOCALE,\n locales: LOCALES,\n messages: Object.fromEntries(Object.entries(TEXTS).map(([id, texts]) => [id, compile(texts)])),\n}\n\n/** A message in `locale` (the base locale's when the catalog lacks the locale). */\nexport const text = (locale: string, id: MessageId, params: Params = {}): string =>\n catalog.messages[id]!(params, { locale })\n\n/** The catalog locale for the browser's languages: each tag in order, then its shorter prefixes; else the base. */\nexport const negotiate = (requested: ReadonlyArray<string>): ShellLocale =>\n lookupLocale(requested, LOCALES, BASE_LOCALE) as ShellLocale\n\n/** The writing direction of a locale's script. */\nexport const directionFor = (locale: string) => directionOf(locale)\n",
|
|
54
|
+
"type": "registry:file",
|
|
55
|
+
"target": "shell-foldkit/src/locale.ts"
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
"path": "app/shell-foldkit/src/main.ts",
|
|
59
|
+
"content": "/**\n * The Foldkit shell's entry: the program over this app's installed modules and screens, run as an application\n * that owns the page and its URL.\n */\nimport { Runtime } from \"foldkit\"\nimport { contracts } from \"../../eloxiv.modules.ts\"\nimport { mutators, queries, schema } from \"../../eloxiv.sync.ts\"\nimport { installedScreens } from \"./installed.ts\"\nimport { makeShell, readFlags } from \"./shell.ts\"\nimport \"./styles.css\"\nimport { makeView } from \"./view.ts\"\n\nconst shell = makeShell({\n kernelUrl: import.meta.env[\"VITE_ELOXIV_URL\"] ?? \"http://localhost:4100\",\n syncUrl: import.meta.env[\"VITE_ELOXIV_SYNC_URL\"] ?? \"http://localhost:4848\",\n // This build's version, sent with every call: the kernel refuses writes from builds older than its minimum.\n clientVersion: import.meta.env[\"VITE_ELOXIV_CLIENT_VERSION\"] as string | undefined,\n contracts,\n schema,\n queries,\n mutators,\n screens: installedScreens,\n development: import.meta.env.DEV,\n})\n\n// Test builds hold every render to the browser suite's checks (`testHooks.ts`); other builds never load it.\nconst view =\n import.meta.env[\"VITE_ELOXIV_TEST_HOOKS\"] === \"1\"\n ? (await import(\"./testHooks.ts\")).withTestHooks(makeView(shell))\n : makeView(shell)\n\nconst application = Runtime.makeApplication({\n Model: shell.Model,\n Flags: shell.Flags,\n init: shell.init,\n update: shell.update,\n view,\n subscriptions: shell.subscriptions,\n managedResources: shell.managedResources,\n container: document.getElementById(\"root\")!,\n routing: {\n onUrlRequest: (request) => shell.Message.ClickedLink({ request }),\n onUrlChange: (url) => shell.Message.ChangedUrl({ url }),\n },\n // Development diagnostics name the slow phase and the Message's tag only, never a Model or a Message's fields\n // (credentials never enter either; the Model still holds the person's email).\n slow: {\n onSlow: (context) =>\n console.warn(\n `[foldkit] slow ${context._tag}: ${context.durationMs.toFixed(1)} ms` +\n (\"message\" in context ? ` (${(context.message as { _tag?: string } | undefined)?._tag ?? \"init\"})` : \"\"),\n ),\n },\n})\n\nRuntime.run(application, { flags: readFlags })\n\n// The pre-paint boot (`public/boot.js`) painted the page in the stored appearance; once the shell has drawn its\n// root, the shell's own (which follows every change) is what shows: the boot's background steps aside.\nrequestAnimationFrame(() => {\n document.documentElement.style.backgroundColor = \"\"\n})\n",
|
|
60
|
+
"type": "registry:file",
|
|
61
|
+
"target": "shell-foldkit/src/main.ts"
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
"path": "app/shell-foldkit/src/make.ts",
|
|
65
|
+
"content": "/**\n * A MAKE module's view as a shell screen (`/make/<module>`), around the view host (`makeView.ts`, whose guarantees it\n * keeps whole: the view's code runs in the kernel's sandbox, the frame where its tree is drawn runs and loads nothing,\n * and only the actions the view may call are called).\n *\n * A Submodel the shell creates for the route, the session and the selected organisation, and discards when any of\n * them changes (so a view never outlives the organisation it was opened in): a Command reads the module's view and\n * the actions it may call (`make.view`), and nothing else; once that is in the Model, a Mount on the screen's\n * container mounts the host for as long as the element lives (the runtime releases it, and the frame goes, when the\n * screen is discarded), running the view's steps (`make.renderView`) and calling the actions it asks for as the\n * signed-in person in that organisation. A view that fails, or a frame the host removed on its own, is reported as a\n * Message. The host's code is a chunk of its own, loaded by the Mount the first time a view is shown (a chunk that\n * cannot be loaded stops the view, saying so, like any failure of the view).\n *\n * **Opening a view runs none of its actions by itself.** Opening it runs only the view's `init`, in the sandbox; the\n * calls it asks for there are its own, made through the invocation path like any other.\n *\n * The session is a handle into the shell's credentials, as everywhere in the Elm state; the token is read only\n * when a request is made.\n */\nimport { makeModuleClient, type MakeViewMessage } from \"@eloxiv/client\"\nimport { Effect, Queue, Schema, Stream } from \"effect\"\nimport { Command, Mount, type Update } from \"foldkit\"\nimport type { Html, HtmlBuilder } from \"foldkit/html\"\nimport { defineMessageUnion } from \"foldkit/message\"\nimport * as stylex from \"@stylexjs/stylex\"\nimport { styles, sx } from \"./styles.ts\"\nimport type { ThemeTokens } from \"@eloxiv/contracts\"\nimport { resolveTheme } from \"@eloxiv/shell-core\"\nimport { contrastTheme, defaultTheme } from \"../../themes/default/tokens.ts\"\n\n/**\n * What a MAKE frame wears: the app's tokens (or their high-contrast preset) resolved for the shell's scheme\n * (`data-theme`), preset (`data-preset`) and direction (`dir`), as they are on the shell's root now.\n */\nexport const frameTheme = (\n root: {\n readonly dataset: { readonly theme?: string | undefined; readonly preset?: string | undefined }\n readonly dir: string\n },\n theme: { readonly standard: ThemeTokens; readonly contrast: ThemeTokens } = {\n standard: defaultTheme,\n contrast: contrastTheme,\n },\n) =>\n resolveTheme(\n root.dataset.preset === \"contrast\" ? theme.contrast : theme.standard,\n root.dataset.theme === \"dark\" ? \"dark\" : \"light\",\n root.dir === \"rtl\" ? \"rtl\" : \"ltr\",\n )\n\nexport const MakeView = Schema.Struct({ title: Schema.String })\nexport type MakeView = typeof MakeView.Type\n\n/** What the screen shows: loading, the view (with what the host needs), why it cannot, or why it closed. */\nexport const Status = Schema.Union([\n Schema.TaggedStruct(\"Loading\", {}),\n Schema.TaggedStruct(\"Shown\", {\n view: MakeView,\n /** The module's version `make.view` answered: the view's steps run for it, and its `actions` are its. */\n version: Schema.String,\n actions: Schema.Array(Schema.String),\n }),\n Schema.TaggedStruct(\"Failed\", { message: Schema.String }),\n Schema.TaggedStruct(\"Closed\", { message: Schema.String }),\n])\nexport type Status = typeof Status.Type\n\nexport const Model = Schema.Struct({\n module: Schema.String,\n /** The session (a handle into the shell's credentials) and the organisation the view acts in. */\n session: Schema.String,\n orgId: Schema.String,\n status: Status,\n})\nexport type Model = typeof Model.Type\n\nexport const Message = defineMessageUnion({\n GotView: {\n view: MakeView,\n version: Schema.String,\n actions: Schema.Array(Schema.String),\n },\n FailedView: { message: Schema.String },\n RemovedFrame: {},\n ViewStopped: { message: Schema.String },\n})\nexport type Message = typeof Message.Type\n\nexport interface MakeScreenConfig {\n readonly kernelUrl: string\n readonly clientVersion?: string | undefined\n /** The bearer token of a session handle, while the shell still holds that session. */\n readonly token: (session: string) => string | undefined\n}\n\n/** The reason a request failed (`make.view`'s and the actions' errors read `<_tag>: <message>`). */\nconst errorText = (error: unknown): string => {\n const cause = (error as { cause?: unknown }).cause\n const inner = cause instanceof Error ? cause : error\n return inner instanceof Error ? inner.message : String(inner)\n}\n\ntype UpdateReturn = Update.Return<Model, Message>\n\nexport const makeMakeScreen = (config: MakeScreenConfig) => {\n const client = (session: string, orgId: string) =>\n makeModuleClient({\n baseUrl: config.kernelUrl,\n token: () => config.token(session),\n orgId,\n clientVersion: config.clientVersion,\n })\n\n /** The module's view and the actions it may call (`make.view`), as the session in the organisation; no action. */\n const LoadView = Command.define(\"LoadMakeView\", {\n args: { module: Schema.String, session: Schema.String, orgId: Schema.String },\n messages: [Message.GotView, Message.FailedView],\n execute: ({ module, session, orgId }) =>\n Effect.tryPromise(async () => {\n const installed = await client(session, orgId).view(module)\n if (installed.view === null) return Message.FailedView({ message: `${module} has no view` })\n return Message.GotView({\n view: { title: installed.view.title },\n version: installed.version,\n actions: [...installed.actions],\n })\n }).pipe(Effect.catch((error) => Effect.succeed(Message.FailedView({ message: errorText(error) })))),\n })\n\n /**\n * The host on the screen's container, for the element's lifetime: mounted when it enters the DOM, removed (the\n * frame, and its reading) when the runtime releases it. A view that fails becomes `ViewStopped`; a frame the host\n * removes on its own becomes `RemovedFrame`.\n */\n const MountView = Mount.defineStream(\"MountMakeView\", {\n args: {\n module: Schema.String,\n version: Schema.String,\n title: Schema.String,\n actions: Schema.Array(Schema.String),\n session: Schema.String,\n orgId: Schema.String,\n },\n messages: [Message.RemovedFrame, Message.ViewStopped],\n execute: ({ element, module, version, title, actions, session, orgId }) =>\n Stream.callback<Schema.Schema.Type<typeof Message.RemovedFrame> | Schema.Schema.Type<typeof Message.ViewStopped>>(\n (queue) =>\n Effect.acquireRelease(\n Effect.tryPromise(() => import(\"./makeView.ts\")).pipe(\n Effect.map(({ mountMakeView }) => {\n const remove = mountMakeView(element as HTMLElement, {\n title,\n actions,\n // Each step in the kernel's sandbox, as the session in the organisation, for the version opened (the\n // kernel refuses a step once another is installed, and the view stops: its actions were that version's).\n step: (state, message) =>\n client(session, orgId).renderView(module, version, state, message as MakeViewMessage | null),\n // Under the view call's idempotency key (`viewCallKey`: the view's own within this mount).\n call: (action, input, idempotencyKey) =>\n client(session, orgId).call(action, input, { idempotencyKey }),\n onFailed: (reason) => Queue.offerUnsafe(queue, Message.ViewStopped({ message: reason })),\n onRemoved: () => Queue.offerUnsafe(queue, Message.RemovedFrame()),\n // The app's theme, for the shell's scheme, preset and direction as they are when asked.\n theme: () =>\n frameTheme((element as HTMLElement).closest<HTMLElement>(\"#shell\") ?? document.documentElement),\n })\n // The frame fills the screen (a class, as everything the shell styles).\n const frame = element.querySelector(\"iframe\")\n if (frame !== null) frame.className = stylex.attrs(styles.makeFrame).class ?? \"\"\n return remove\n }),\n Effect.catch((error) =>\n Effect.sync(() => {\n Queue.offerUnsafe(\n queue,\n Message.ViewStopped({ message: `its code could not be loaded: ${errorText(error)}` }),\n )\n return () => {}\n }),\n ),\n ),\n (remove) => Effect.sync(remove),\n ).pipe(Effect.andThen(Effect.never)),\n ),\n })\n\n const init = (module: string, session: string, orgId: string): UpdateReturn => ({\n model: { module, session, orgId, status: { _tag: \"Loading\" } },\n commands: [LoadView({ module, session, orgId })],\n })\n\n const update = (model: Model, message: Message): UpdateReturn =>\n Message.match<UpdateReturn>(message, {\n GotView: ({ view, version, actions }) => ({\n model: { ...model, status: { _tag: \"Shown\", view, version, actions } },\n }),\n FailedView: ({ message: reason }) => ({ model: { ...model, status: { _tag: \"Failed\", message: reason } } }),\n RemovedFrame: () =>\n model.status._tag === \"Shown\"\n ? { model: { ...model, status: { _tag: \"Closed\", message: `${model.module}'s view was closed` } } }\n : { model },\n ViewStopped: ({ message: reason }) =>\n model.status._tag === \"Shown\"\n ? { model: { ...model, status: { _tag: \"Closed\", message: `${model.module}'s view stopped: ${reason}` } } }\n : { model },\n })\n\n const view = (model: Model, h: HtmlBuilder<Message>): Html => {\n const status = model.status\n switch (status._tag) {\n case \"Loading\":\n return h.p([h.DataAttribute(\"testid\", \"make-loading\"), h.AriaBusy(true), sx(styles.muted)], [\"Loading…\"])\n case \"Failed\":\n case \"Closed\":\n return h.p([h.Role(\"alert\"), h.DataAttribute(\"testid\", \"make-error\"), sx(styles.error)], [status.message])\n case \"Shown\":\n return h.section(\n [h.AriaLabel(status.view.title), sx(styles.form)],\n [\n h.h1([sx(styles.cardTitle)], [status.view.title]),\n h.keyed(\"div\")(\n `${model.module}:${model.orgId}`,\n [\n h.DataAttribute(\"testid\", \"make-view\"),\n h.OnMount(\n MountView({\n module: model.module,\n version: status.version,\n title: status.view.title,\n actions: status.actions,\n session: model.session,\n orgId: model.orgId,\n }),\n ),\n ],\n [],\n ),\n ],\n )\n }\n }\n\n return { init, update, view, LoadView, MountView }\n}\n\nexport type MakeScreen = ReturnType<typeof makeMakeScreen>\n",
|
|
66
|
+
"type": "registry:file",
|
|
67
|
+
"target": "shell-foldkit/src/make.ts"
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
"path": "app/shell-foldkit/src/makeView.ts",
|
|
71
|
+
"content": "/**\n * The shell's host for MAKE views (decisions: \"No iframes, except sandboxed MAKE views\"). A MAKE module's view is\n * code, and it never runs here: it runs in the kernel's sandbox (`make.renderView`: no DOM, no network), and what\n * comes back is a view tree. The host draws that tree, and nothing else, in an iframe where nothing runs and nothing\n * loads:\n *\n * - sandboxed without scripts or forms (`MAKE_VIEW_SANDBOX`: `allow-same-origin` only, so the host can draw into the\n * frame's document and read its fields; no script of the frame's ever runs, it submits nothing, opens nothing and\n * cannot navigate the shell);\n * - under the view CSP (`MAKE_VIEW_CSP`, as the document's `<meta>` and the iframe's `csp` attribute): no script,\n * image, media, font, frame, object, connection or form submission, so even an element that named a URL could\n * load nothing;\n * - drawn by the host from the tree's elements only (`MAKE_VIEW_TAGS`, `MAKE_VIEW_PROPS`, `MAKE_VIEW_INPUT_TYPES`):\n * text as text nodes, no attribute that names a URL, `style` held to a few CSS properties with plain values; a\n * `form` is a group of fields, never submitted.\n *\n * Nothing in the frame can navigate it or load a URL carrying data: a `button` or `link` is a link to a fragment of\n * the frame's own document (`about:srcdoc#e-<n>`, the host's own counter, never the view's text), so activating it\n * (a click, or Enter) changes only the frame's fragment, which the host reads and resets; it routes the event to the\n * view (`update`), with the values of the fields of its form. A field with `on` is reported when its value changes.\n *\n * The frame wears the app's theme (the ThemeTokens contract): the host resolves the app's tokens for the shell's\n * scheme, preset and direction (read from the shell's root, and again whenever they change) and sets them as the\n * frame root's custom properties, which its own sheet draws controls with; a view's `style` may name them\n * (`var(--primary)`), and no other variable.\n * The host reads these from its own side (it registers nothing in the frame: an engine with scripts off in a frame\n * runs no listener there, the desktop hosts' WebKit among them).\n *\n * The calls a view asks for are made only for its module's own actions its capability profile lists (`actions`, from\n * `make.view`), as the signed-in person, through the invocation path (the kernel authorises each as any call), under\n * the call's idempotency key (`viewCallKey`); any other is refused without a request. Each result goes back to the\n * view's `update`, through the kernel, never to code in the browser.\n */\nimport {\n MAKE_VIEW_CSP,\n MAKE_VIEW_INPUT_TYPES,\n MAKE_VIEW_KEY,\n MAKE_VIEW_PROPS,\n MAKE_VIEW_SANDBOX,\n MAKE_VIEW_TAGS,\n MAKE_VIEW_THEME_VARIABLES,\n} from \"@eloxiv/client\"\n\ntype Json = null | boolean | number | string | ReadonlyArray<Json> | { readonly [key: string]: Json }\ntype FieldValue = string | boolean\n\n/** One node of a view tree (the Sandbox contract's `MakeViewNode`). */\nexport type ViewNode =\n | string\n | number\n | boolean\n | null\n | {\n readonly tag: string\n readonly props?: { readonly [key: string]: string | number | boolean }\n readonly children?: ReadonlyArray<ViewNode>\n readonly on?: string\n readonly data?: Json\n }\n\n/** What the view's `update` is told (the contract's `MakeViewMessage`). */\nexport type ViewMessage =\n | {\n readonly type: \"event\"\n readonly name: string\n readonly data?: Json\n readonly value?: FieldValue\n readonly fields: Readonly<Record<string, FieldValue>>\n }\n | { readonly type: \"result\"; readonly id: string; readonly ok: true; readonly result: unknown }\n | {\n readonly type: \"result\"\n readonly id: string\n readonly ok: false\n readonly error: { readonly _tag: string; readonly message: string }\n }\n\n/** One step of the view (`make.renderView`'s answer). */\nexport interface ViewStep {\n readonly state: unknown\n readonly calls: ReadonlyArray<{\n readonly id: string\n readonly action: string\n readonly input?: unknown\n readonly key?: string\n }>\n readonly tree: ViewNode\n}\n\nexport interface MakeViewHost {\n readonly title: string\n /** The module's actions the view may ask for (`make.view`'s `actions`). */\n readonly actions: ReadonlyArray<string>\n /** One step of the view, in the kernel's sandbox (`make.renderView`): `init` with no state or message. */\n readonly step: (state: unknown, message: ViewMessage | null) => Promise<ViewStep>\n /**\n * Call an action as the signed-in person, under `idempotencyKey` (the same on every retry of one request): the\n * result envelope, or throw the standard error.\n */\n readonly call: (action: string, input: unknown, idempotencyKey: string) => Promise<unknown>\n /** Told when the view cannot go on (its code failed, or the kernel refused a step), with why. */\n readonly onFailed?: ((message: string) => void) | undefined\n /** Told when the host removed the frame on its own (another document was in it). */\n readonly onRemoved?: (() => void) | undefined\n /**\n * The app's theme as the frame wears it now: its custom properties, scheme and direction (`make.ts` resolves the\n * app's tokens for the shell's scheme, preset and direction, `frameTheme`), asked again whenever the shell's root\n * changes them.\n */\n readonly theme?:\n | (() => {\n readonly variables: Readonly<Record<string, string>>\n readonly scheme: string\n readonly direction: string\n })\n | undefined\n}\n\n/** The theme variables a view's `style` may name (`var(--primary)`): the ThemeTokens contract's, nothing else. */\nconst THEME_VARIABLES = new Set<string>(MAKE_VIEW_THEME_VARIABLES)\n\nconst TAGS = new Set<string>(MAKE_VIEW_TAGS)\nconst PROPS = new Set<string>(MAKE_VIEW_PROPS)\nconst INPUT_TYPES = new Set<string>(MAKE_VIEW_INPUT_TYPES)\n/** The fragment prefix of the host's links (`about:srcdoc#e-<n>`). */\nconst EVENT = \"#e-\"\n/** How often the host reads the frame's fragment and watched fields. */\nconst POLL_MS = 60\n\n/** The CSS properties a view's `style` may set; nothing that can name a URL. */\nconst STYLE_PROPERTIES = new Set([\n \"color\",\n \"background-color\",\n \"font-weight\",\n \"font-style\",\n \"font-size\",\n \"text-align\",\n \"text-decoration\",\n \"text-transform\",\n \"line-height\",\n \"letter-spacing\",\n \"white-space\",\n \"vertical-align\",\n \"list-style-type\",\n \"margin\",\n \"margin-top\",\n \"margin-right\",\n \"margin-bottom\",\n \"margin-left\",\n \"padding\",\n \"padding-top\",\n \"padding-right\",\n \"padding-bottom\",\n \"padding-left\",\n \"border\",\n \"border-top\",\n \"border-right\",\n \"border-bottom\",\n \"border-left\",\n \"border-color\",\n \"border-width\",\n \"border-style\",\n \"border-radius\",\n \"border-collapse\",\n \"display\",\n \"flex\",\n \"flex-direction\",\n \"flex-wrap\",\n \"align-items\",\n \"justify-content\",\n \"gap\",\n \"grid-template-columns\",\n \"width\",\n \"min-width\",\n \"max-width\",\n \"height\",\n \"min-height\",\n \"max-height\",\n \"opacity\",\n \"overflow\",\n])\n/** A plain CSS value: words, numbers, units, colours and a few functions; no quotes, escapes, colons or URLs. */\nconst STYLE_VALUE = /^[-#%.,()/\\s\\w]*$/u\nconst STYLE_FUNCTIONS = new Set([\n \"rgb\",\n \"rgba\",\n \"hsl\",\n \"hsla\",\n \"calc\",\n \"min\",\n \"max\",\n \"clamp\",\n \"repeat\",\n \"minmax\",\n \"var\",\n])\n\n/**\n * Every `var(...)` in a value (any case, any spacing before the parenthesis) names a theme variable and nothing else:\n * no fallback, no other custom property.\n */\nconst varsOnlyTheme = (value: string): boolean => {\n const calls = /var\\s*\\(([^)]*)\\)?/giu\n for (const call of value.matchAll(calls)) {\n if (!call[0].endsWith(\")\") || !THEME_VARIABLES.has(call[1]!.trim())) return false\n }\n return true\n}\n\n/** The longest `style` value a declaration may have, and the longest `style` the host reads at all. */\nconst STYLE_VALUE_MAX = 200\nconst STYLE_MAX = 4_000\n\n/**\n * Whether every function a CSS value calls (an identifier followed by `(`, spaces allowed between) is one of\n * `STYLE_FUNCTIONS`: one pass over the value, keeping the identifier last seen.\n */\nconst callsOnlyAllowed = (value: string): boolean => {\n let name = \"\"\n let afterName = false\n for (const c of value) {\n if ((c >= \"a\" && c <= \"z\") || (c >= \"A\" && c <= \"Z\") || c === \"-\") {\n if (afterName) name = \"\"\n afterName = false\n name += c\n } else if (c === \" \" || c === \"\\t\" || c === \"\\n\") {\n if (name !== \"\") afterName = true\n } else if (c === \"(\") {\n if (name !== \"\" && !STYLE_FUNCTIONS.has(name.toLowerCase())) return false\n name = \"\"\n afterName = false\n } else {\n name = \"\"\n afterName = false\n }\n }\n return true\n}\n\n/** A view's `style`, kept to the declarations of `STYLE_PROPERTIES` whose values are plain and short. */\nexport const safeStyle = (style: string): string =>\n style.length > STYLE_MAX\n ? \"\"\n : style\n .split(\";\")\n .flatMap((declaration) => {\n const colon = declaration.indexOf(\":\")\n if (colon < 0) return []\n const property = declaration.slice(0, colon).trim().toLowerCase()\n const value = declaration.slice(colon + 1).trim()\n if (!STYLE_PROPERTIES.has(property) || value.length === 0 || value.length > STYLE_VALUE_MAX) return []\n if (!STYLE_VALUE.test(value) || !callsOnlyAllowed(value) || !varsOnlyTheme(value)) return []\n return [`${property}: ${value}`]\n })\n .join(\"; \")\n\n/** The frame's own sheet: plain controls, in the app's theme (the system's colours until it is set). */\nconst BASE_STYLE =\n \"body{margin:0;padding:.5rem;font:14px/1.45 var(--font-sans,system-ui,sans-serif);\" +\n \"color:var(--foreground,CanvasText);background:var(--background,Canvas)}\" +\n \"a[data-eloxiv]{cursor:pointer}a[data-eloxiv][role=link]{color:var(--primary,LinkText);text-decoration:underline}\" +\n \"a[data-eloxiv][role=button]{display:inline-block;padding:.25rem .75rem;border:1px solid var(--border,ButtonBorder);\" +\n \"border-radius:var(--radius,4px);background:var(--secondary,ButtonFace);color:var(--secondary-foreground,ButtonText);\" +\n \"text-decoration:none}input,textarea,select{border:1px solid var(--input,ButtonBorder);\" +\n \"background:var(--background,Field);color:var(--foreground,FieldText)}\" +\n \"a[data-eloxiv][aria-disabled=true]{opacity:.5;pointer-events:none}\" +\n \"input,textarea,select{font:inherit}table{border-collapse:collapse}td,th{padding:.25rem .5rem;text-align:left}\"\n\nconst attribute = (value: string) => value.replaceAll(\"&\", \"&\").replaceAll('\"', \""\")\n\n/** The frame's document: the view CSP, its own sheet, and an empty body the host draws into. */\nexport const viewFrameDocument = (): string =>\n `<!doctype html><html><head><meta charset=\"utf-8\"><meta http-equiv=\"Content-Security-Policy\" content=\"${attribute(MAKE_VIEW_CSP)}\"><meta name=\"referrer\" content=\"no-referrer\"><style>${BASE_STYLE}</style></head><body></body></html>`\n\nconst errorOf = (error: unknown) => {\n const value = (error as { readonly error?: { readonly _tag?: unknown; readonly message?: unknown } }).error\n return {\n _tag: typeof value?._tag === \"string\" ? value._tag : \"ActionFailed\",\n message:\n typeof value?.message === \"string\" ? value.message : error instanceof Error ? error.message : String(error),\n }\n}\n\n/**\n * The idempotency key a view's call runs under, within one mounted view (`instance`, new each time the host mounts\n * it): the view's own (`key`, the same on each retry of one request), so two tabs, or two mounts, that reuse a key\n * never share a receipt; or, for a call that names none, a fresh one. Kept apart from other surfaces' keys.\n */\nexport const viewCallKey = (instance: string, key: unknown): string =>\n `make-view:${instance}:${typeof key === \"string\" && MAKE_VIEW_KEY.test(key) ? key : crypto.randomUUID()}`\n\ntype Field = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement\nconst isField = (element: Element): element is Field =>\n element.localName === \"input\" || element.localName === \"textarea\" || element.localName === \"select\"\nconst valueOf = (field: Field): FieldValue =>\n field.localName === \"input\" &&\n ((field as HTMLInputElement).type === \"checkbox\" || (field as HTMLInputElement).type === \"radio\")\n ? (field as HTMLInputElement).checked\n : field.value\n\n/** What a link or a watched field sends: its event, and the scope whose named fields go with it. */\ninterface Binding {\n readonly name: string\n readonly data: Json | undefined\n readonly scope: Element\n}\n\n/** Render a MAKE view into `container`; returns the function that removes it. */\nexport const mountMakeView = (container: HTMLElement, host: MakeViewHost): (() => void) => {\n // This mount's own: the view's idempotency keys are namespaced by it.\n const instance = crypto.randomUUID()\n const frame = document.createElement(\"iframe\")\n frame.setAttribute(\"sandbox\", MAKE_VIEW_SANDBOX)\n frame.setAttribute(\"csp\", MAKE_VIEW_CSP)\n frame.setAttribute(\"referrerpolicy\", \"no-referrer\")\n frame.title = host.title\n frame.srcdoc = viewFrameDocument()\n\n let removed = false\n let loads = 0\n let state: unknown = null\n let poll: ReturnType<typeof setInterval> | undefined\n /** Links by their number (the host's counter, never reused), and watched fields with their last values. */\n let links = new Map<number, Binding>()\n let watched: Array<{ readonly field: Field; readonly binding: Binding; last: FieldValue }> = []\n let counter = 0\n let queue: Promise<void> = Promise.resolve()\n let ready: () => void = () => {}\n const loaded = new Promise<void>((resolve) => (ready = resolve))\n\n const remove = () => {\n if (removed) return\n removed = true\n if (poll !== undefined) clearInterval(poll)\n frame.removeEventListener(\"load\", onLoad)\n frame.remove()\n }\n const fail = (message: string) => {\n if (removed) return\n host.onFailed?.(message)\n }\n\n /** The values of the named fields under `scope`. */\n const fieldsOf = (scope: Element): Record<string, FieldValue> => {\n const fields: Record<string, FieldValue> = {}\n for (const element of scope.querySelectorAll(\"input, textarea, select\")) {\n const field = element as Field\n const name = field.getAttribute(\"name\")\n if (name === null || name === \"\") continue\n if (field.localName === \"input\" && (field as HTMLInputElement).type === \"radio\") {\n if ((field as HTMLInputElement).checked) fields[name] = field.value\n else if (!(name in fields)) fields[name] = \"\"\n } else fields[name] = valueOf(field)\n }\n return fields\n }\n\n /** Draw `node` into `doc` (the frame's document): only the tree's elements and properties; text as text. */\n const draw = (doc: Document, node: ViewNode, scope: Element | null): Node | null => {\n if (node === null || typeof node === \"boolean\") return null\n if (typeof node === \"string\" || typeof node === \"number\") return doc.createTextNode(String(node))\n if (typeof node !== \"object\" || typeof node.tag !== \"string\" || !TAGS.has(node.tag)) return null\n const tag = node.tag\n const element =\n tag === \"button\" || tag === \"link\" ? doc.createElement(\"a\") : doc.createElement(tag === \"form\" ? \"div\" : tag)\n const props = node.props ?? {}\n for (const [key, value] of Object.entries(props)) {\n if (!PROPS.has(key) || (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\"))\n continue\n if (key === \"value\" || key === \"checked\" || key === \"selected\") continue\n if (key === \"type\") {\n if (tag === \"input\") element.setAttribute(\"type\", INPUT_TYPES.has(String(value)) ? String(value) : \"text\")\n continue\n }\n if (key === \"style\") {\n const style = safeStyle(String(value))\n if (style !== \"\") element.setAttribute(\"style\", style)\n continue\n }\n if (key === \"disabled\") {\n if (value === true)\n element.setAttribute(\n tag === \"button\" || tag === \"link\" ? \"aria-disabled\" : \"disabled\",\n tag === \"button\" || tag === \"link\" ? \"true\" : \"\",\n )\n continue\n }\n element.setAttribute(key === \"ariaLabel\" ? \"aria-label\" : key, String(value))\n }\n const ownScope = tag === \"form\" ? element : scope\n if (tag === \"form\") element.setAttribute(\"role\", \"form\")\n if (tag === \"button\" || tag === \"link\") {\n element.setAttribute(\"data-eloxiv\", \"\")\n element.setAttribute(\"role\", tag)\n if (typeof node.on === \"string\" && props[\"disabled\"] !== true) {\n const n = ++counter\n links.set(n, { name: node.on, data: node.data, scope: ownScope ?? doc.body })\n element.setAttribute(\"href\", `about:srcdoc${EVENT}${n}`)\n }\n }\n for (const child of node.children ?? []) {\n const drawn = draw(doc, child, ownScope)\n if (drawn !== null) element.appendChild(drawn)\n }\n if (isField(element)) {\n // A value the tree gives is the view's; otherwise what the person typed is kept across a redraw.\n if (\"value\" in props || \"checked\" in props) element.setAttribute(\"data-eloxiv-set\", \"\")\n if (\"value\" in props) element.value = String(props[\"value\"])\n if (tag === \"input\" && \"checked\" in props) (element as HTMLInputElement).checked = props[\"checked\"] === true\n if (typeof node.on === \"string\") {\n watched.push({\n field: element,\n binding: { name: node.on, data: node.data, scope: ownScope ?? doc.body },\n last: \"\",\n })\n }\n }\n if (tag === \"option\" && props[\"selected\"] === true) (element as HTMLOptionElement).selected = true\n return element\n }\n\n /** Draw the tree, keeping what the person typed into fields the tree gives no value. */\n const redraw = (tree: ViewNode) => {\n const doc = frame.contentDocument\n if (removed || doc === null) return\n const typed = new Map<string, FieldValue>()\n for (const element of doc.body.querySelectorAll(\"input, textarea, select\")) {\n const name = element.getAttribute(\"name\")\n const field = element as Field\n if (name !== null && !(field.localName === \"input\" && (field as HTMLInputElement).type === \"radio\"))\n typed.set(name, valueOf(field))\n }\n links = new Map()\n watched = []\n const drawn = draw(doc, tree, null)\n doc.body.replaceChildren(...(drawn === null ? [] : [drawn]))\n for (const element of doc.body.querySelectorAll(\"input, textarea, select\")) {\n const field = element as Field\n const name = field.getAttribute(\"name\")\n const given = field.hasAttribute(\"data-eloxiv-set\")\n if (name !== null && typed.has(name) && !given) {\n const value = typed.get(name)!\n if (typeof value === \"boolean\" && field.localName === \"input\") (field as HTMLInputElement).checked = value\n else if (typeof value === \"string\") field.value = value\n }\n }\n for (const entry of watched) entry.last = valueOf(entry.field)\n }\n\n /** Run one step of the view and act on it: draw its tree, make the calls it may ask for. */\n const run = async (message: ViewMessage | null) => {\n if (removed) return\n let next: ViewStep\n try {\n next = await host.step(state, message)\n } catch (error) {\n return fail(errorOf(error).message)\n }\n if (removed) return\n state = next.state\n redraw(next.tree)\n for (const call of next.calls) {\n if (!host.actions.includes(call.action)) {\n send({\n type: \"result\",\n id: call.id,\n ok: false,\n error: { _tag: \"Forbidden\", message: `The view may not call ${call.action}` },\n })\n continue\n }\n host.call(call.action, call.input ?? {}, viewCallKey(instance, call.key)).then(\n (result) => send({ type: \"result\", id: call.id, ok: true, result }),\n (error: unknown) => send({ type: \"result\", id: call.id, ok: false, error: errorOf(error) }),\n )\n }\n }\n /** Steps run one at a time, in order: each from the state the one before returned. */\n const send = (message: ViewMessage | null) => {\n queue = queue.then(() => loaded).then(() => run(message))\n }\n\n /** The host's side: the frame's fragment (an activated link) and the watched fields, read and acted on. */\n const tick = () => {\n const win = frame.contentWindow\n if (removed || win === null) return\n let hash = \"\"\n try {\n hash = win.location.hash\n } catch {\n return\n }\n if (hash.startsWith(EVENT)) {\n try {\n win.history.replaceState(null, \"\", \"about:srcdoc\")\n } catch {\n win.location.hash = \"\"\n }\n const binding = links.get(Number(hash.slice(EVENT.length)))\n if (binding !== undefined) {\n send({\n type: \"event\",\n name: binding.name,\n ...(binding.data === undefined ? {} : { data: binding.data }),\n fields: fieldsOf(binding.scope),\n })\n }\n }\n for (const entry of watched) {\n const now = valueOf(entry.field)\n if (now === entry.last) continue\n entry.last = now\n send({\n type: \"event\",\n name: entry.binding.name,\n ...(entry.binding.data === undefined ? {} : { data: entry.binding.data }),\n value: now,\n fields: fieldsOf(entry.binding.scope),\n })\n }\n }\n\n // The frame's one document is the host's own; it can be in no other (nothing in it navigates), so a second load\n // means something else is there: the frame goes.\n const onLoad = () => {\n loads++\n if (loads > 1) {\n remove()\n host.onRemoved?.()\n return\n }\n poll = setInterval(tick, POLL_MS)\n applyTheme()\n observer?.observe(themeRoot, { attributes: true, attributeFilter: [\"data-theme\", \"data-preset\", \"dir\"] })\n ready()\n }\n // The shell's theme on the frame's root, now and whenever the shell's scheme, preset or direction changes.\n const themeRoot = container.closest<HTMLElement>(\"#shell\") ?? document.documentElement\n const applyTheme = () => {\n const doc = frame.contentDocument\n if (removed || doc === null) return\n if (host.theme === undefined) return\n const resolved = host.theme()\n for (const [name, value] of Object.entries(resolved.variables)) doc.documentElement.style.setProperty(name, value)\n doc.documentElement.style.colorScheme = resolved.scheme\n doc.documentElement.dir = resolved.direction\n }\n const observer = typeof MutationObserver === \"function\" ? new MutationObserver(applyTheme) : undefined\n frame.addEventListener(\"load\", onLoad)\n container.appendChild(frame)\n send(null)\n return () => {\n observer?.disconnect()\n remove()\n }\n}\n",
|
|
72
|
+
"type": "registry:file",
|
|
73
|
+
"target": "shell-foldkit/src/makeView.ts"
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
"path": "app/shell-foldkit/src/screen.ts",
|
|
77
|
+
"content": "/**\n * The contract between the shell and the optional UI items that give installed views their screens.\n *\n * A UI item (`hello-ui-foldkit`, ...) adds one file to `shell-foldkit/src/screens/`, exporting `screen`\n * (`defineScreen`). The shell discovers every file there when it is built (`installed.ts`), and a view\n * declared in an installed module's manifest gets a route only when a screen for it is installed: a module\n * installed without its UI item adds no route and no link. Taking a UI item over (`eloxiv eject`) and editing its\n * file replaces only that screen.\n *\n * A screen is a Foldkit Submodel. The shell creates it when its route is shown and a replica is open, passing the\n * replica's key (`context.replica`); it discards it when the route, the organisation or the session changes, so a\n * screen never holds one organisation's rows after a switch. Its Subscriptions (live queries through\n * `@eloxiv/client/foldkit`) run only while it is the screen shown, for that instance of it: every Message they send\n * names the instance, so one sent before the screen was replaced (a snapshot of the previous organisation's replica,\n * still in flight) is dropped. A screen that keeps rows itself checks each snapshot's replica too (`receive`, or\n * `rowsFrom`).\n *\n * **Slots.** A module declares slots in its manifest (`slots: { \"hello.greetingPanel\": { accepts: \"view\" } }`) and\n * any installed module contributes to them (`contributions`). A screen names the slots it shows (`slots`); the shell\n * resolves each one's contributions (`@eloxiv/shell-core`'s `shellRegistry().slot`, in order) and shows them beside\n * the screen: a contributed view whose screen is installed as a panel (that screen, created and discarded with the\n * one it sits beside, for the same replica, its Subscriptions and Messages its own: a view contributed twice is two\n * panels), a contributed command that opens a view as a link. A contribution whose UI item is not installed shows\n * nothing.\n *\n * **Kernel-provided views.** The kernel's own modules (the agent, approvals, consent) declare views the app's\n * module contracts do not carry (the shell is UI-free of the kernel). A screen for one names its route and title\n * itself (`route`, `title`); the shell routes and links it like any other, and refuses to start with one that is not\n * a plain path or collides with a manifest view's route (or its records), the shell's own (`/`, `/settings`,\n * `/make`) or another screen's.\n *\n * **Home.** One screen may claim the shell's home route, `/` (`home: true`; a launcher): it is shown there in place\n * of the shell's own list of modules, is not listed in the navigation (the header's home link opens it), and names\n * neither a manifest view nor a `route`. A second screen that claims it refuses the shell's start. Without one, `/`\n * shows the shell's own list.\n *\n * **Requests.** A screen that calls the kernel over HTTP (the chat SDK, an approval's decision) gets the session's\n * handle and the kernel's URL in its context; its Command reads the token for the handle (`sessionToken`) only\n * when it runs, so no Model or Message ever holds it.\n *\n * **Loaded on demand.** Each screen file is a chunk of its own in the shell's build, loaded when a route first shows\n * it (or a screen it sits beside as a panel), while the replica opens. Until then the shell routes and links it from\n * the fields its `defineScreen` call states as plain literals (`view`, `label`, `route`, `title`, `home`, `slots`),\n * which the build reads from the file (`screenMeta.ts`); a declaration whose fields are not plain literals (a spread,\n * a constant, a computed value) is loaded with the shell instead, as every screen was before. A chunk that cannot be\n * loaded (the network, or a newer release that replaced it) shows an error with a way to reload, never a blank page.\n */\nimport type { ReplicaKey, ReplicaService } from \"@eloxiv/client/foldkit\"\nimport type { Option } from \"effect\"\nimport type { Subscription, Update } from \"foldkit\"\nimport type { Html, HtmlBuilder } from \"foldkit/html\"\n\nexport { sessionToken } from \"./session.ts\"\n\n/** What the shell tells a screen when it creates it. */\nexport interface ScreenContext {\n /** The open replica the screen reads and writes through (its organisation's). */\n readonly replica: ReplicaKey\n /** A record id when the route names one (`/hello/<id>`). */\n readonly record: Option.Option<string>\n /** The session the screen acts as: a handle into the shell's credentials (`sessionToken`), never the token. */\n readonly session: string\n /** The kernel's URL, and this build's version (sent with every call). */\n readonly kernelUrl: string\n readonly clientVersion: Option.Option<string>\n /** The routed screens' links, as the shell's navigation lists them (what a launcher offers). */\n readonly nav?: ReadonlyArray<{ readonly view: string; readonly label: string; readonly path: string }>\n}\n\nexport interface Screen<Model, Message> {\n /** The manifest view this screen renders (`hello.greetings`): its route and title come from the manifest. */\n readonly view: string\n /** The navigation label (the view's title when absent). */\n readonly label?: string\n readonly init: (context: ScreenContext) => Update.Return<Model, Message, ReplicaService>\n readonly update: (model: Model, message: Message) => Update.Return<Model, Message, ReplicaService>\n readonly render: (model: Model, h: HtmlBuilder<Message>) => Html\n readonly subscriptions?: Subscription.Subscriptions<Model, Message, ReplicaService>\n /** Whether the screen shows its data from the replica: the route-change measurement ends here. */\n readonly isReady: (model: Model) => boolean\n /** The slots (declared in a module's manifest) whose contributions the shell shows beside this screen. */\n readonly slots?: ReadonlyArray<string>\n /** For a kernel-provided view (not in the app's module contracts): its route and title. */\n readonly route?: string\n readonly title?: string\n /** The screen of the shell's home route, `/` (a launcher); at most one is installed. */\n readonly home?: boolean\n}\n\n/** A screen of any Model and Message: what the shell holds, its types erased at the screen boundary. */\nexport type AnyScreen = Screen<any, any>\n\n/** Declares a screen (the export `screen` of a file in `screens/`). */\nexport const defineScreen = <Model, Message>(screen: Screen<Model, Message>): Screen<Model, Message> => screen\n\n/** What the shell routes, links and lays out by before a screen's code is loaded: its declaration's plain fields. */\nexport type ScreenMeta = Pick<AnyScreen, \"view\" | \"label\" | \"slots\" | \"route\" | \"title\" | \"home\">\n\n/**\n * A screen whose code loads when its route is first shown (a chunk of its own in the shell's build): its fields as\n * the build read them from its declaration (`screenMeta.ts`), and how to load the screen itself. The shell routes\n * and links it from `meta`, loads it when a route needs it, and refuses one whose loaded `view` is not `meta.view`.\n */\nexport interface LazyScreen {\n readonly meta: ScreenMeta\n readonly load: () => Promise<AnyScreen>\n}\n\n/** A screen as installed: loaded with the shell, or loaded when a route first needs it. */\nexport type InstalledScreen = AnyScreen | LazyScreen\n\nexport const isLazyScreen = (screen: InstalledScreen): screen is LazyScreen => \"load\" in screen && \"meta\" in screen\n",
|
|
78
|
+
"type": "registry:file",
|
|
79
|
+
"target": "shell-foldkit/src/screen.ts"
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
"path": "app/shell-foldkit/src/session.ts",
|
|
83
|
+
"content": "/**\n * The bearer tokens of this page's sessions, outside the Elm state (`Credentials` of `@eloxiv/client/foldkit`): the\n * client core holds the session, and the shell names its token by a handle here (`runtimeSessionHandle`: a new one\n * for each token, the old one forgotten), and a screen's Command reads the token for the handle it was given\n * (`sessionToken`) only when it makes a request.\n */\nimport { makeCredentials } from \"@eloxiv/client/foldkit\"\n\nexport const credentials = makeCredentials()\n\n/** The token a session handle names, while the session lasts (`undefined` once it has ended). */\nexport const sessionToken = (handle: string): string | undefined => credentials.token(handle)\n",
|
|
84
|
+
"type": "registry:file",
|
|
85
|
+
"target": "shell-foldkit/src/session.ts"
|
|
86
|
+
},
|
|
87
|
+
{
|
|
88
|
+
"path": "app/shell-foldkit/src/shell.ts",
|
|
89
|
+
"content": "/**\n * The shell's program: one Model, the Messages that change it and a pure update (The Elm Architecture, Foldkit).\n *\n * - **One client core.** The session, the selected organisation and its generation, the replica, live queries,\n * optimistic writes and teardown are the client core's (`makeClientRuntime` of `@eloxiv/client/runtime`, decision\n * 14), run in process, the same one the daemon serves to native apps; this program only shows what it announces\n * (`runtimeEvents`: session, context and connection as Messages) and asks it to act (sign-in, sign-out and\n * organisation Commands). Its storage is the browser's: the session (`eloxiv.session`), the replica (IndexedDB).\n * - **Session.** Restoring (a stored session the kernel is checking), signed out (the sign-in form), signing out, or\n * signed in (the Better Auth session, the user's organisations, the one selected and its generation). A sign-out is\n * durable (the core's `revocations`, here `eloxiv.pendingRevocations`): its revocation is kept in storage, and the\n * stored session forgotten, before the signed-out state shows (or, when storage will not keep it, the stored session\n * stays and the token is kept in memory, and a sign-in waits until it is stored or confirmed), and retried (each\n * attempt with a timeout; every 15 s, when the network returns, and at the next start) until the kernel confirms\n * it. A session the replica's server refuses (`needs-auth`) is checked with the kernel at once: refused there, it\n * ends, with the reason.\n * - **Credentials never enter the Elm state.** The Model, Messages and Command arguments name the session by an\n * opaque handle (`Credentials` of `@eloxiv/client/foldkit`, `runtimeSessionHandle`); the token stays in the core\n * and in the browser's storage, and the password is read from its field by the sign-in Command and never held.\n * - **Organisation and replica.** The core opens the replica of the selected organisation and closes it on every\n * context change before announcing the next; the program acts in the generation it announced (`runtimeReplica`,\n * a ManagedResource whose key's `opening` is the generation). Selecting another organisation discards the shown\n * screen and marks the replica as opening in the same update, so no Model, and so no render, pairs the new\n * organisation with the old one's rows; the screen is created again once the new generation's replica is taken.\n * - **Routes** come from the installed views (the manifests, through `@eloxiv/shell-core`'s `shellRegistry`) that\n * have a screen installed (`screen.ts`); `/make/<module>` shows a MAKE module's sandboxed view (`make.ts`).\n * - **Slots.** A screen names the slots it shows; the views other modules contribute to them are shown beside it as\n * panels (their own screens, created and discarded with it, for the same replica), and contributed commands that\n * open a view as links.\n * - **Appearance and locale.** Light, dark or the system's scheme, and the writing direction, chosen in an\n * accessible dialog (Foldkit UI's Dialog) or the settings, applied to the root as StyleX themes and `dir`; the\n * shell's language (`locale.ts`, the Locale contract), negotiated from the browser's languages and chosen in the\n * settings, sets `lang`, and choosing one sets the direction its script writes in.\n * - **Settings** (`/settings`): a minimal frame of the profile, the organisation's members, language and appearance.\n * - **Desktop sign-in** (`/desktop/sign-in?challenge&redirect_uri&state`, the kernel's DesktopSignIn): a native app\n * (the Rune host's daemon) opened this page in the system browser. Signed out, the sign-in form shows first and the\n * page follows; signed in, it shows who is signing in, where the app receives the answer (its redirect, a loopback\n * address or the app's own scheme) and the challenge's fingerprint, and only the person's explicit approval calls\n * `POST /api/desktop/approve` (as the session, by its token) and sends the browser to the redirect it answers.\n */\nimport {\n approveDesktopSignIn,\n changeEmail,\n consentController,\n engineProbe,\n updateProfile,\n listMembers,\n registerWebMcp,\n type ApprovalRequest,\n type ClientAction,\n type ConsentScript,\n type SyncSchema as AnySyncSchema,\n} from \"@eloxiv/client\"\nimport {\n openReplica,\n runtimeEvents,\n runtimeReplica,\n runtimeSessionHandle,\n ReplicaClosed,\n ReplicaKey,\n ReplicaOpening,\n ReplicaState,\n sameReplica,\n type ReplicaService,\n} from \"@eloxiv/client/foldkit\"\nimport { makeClientRuntime, type InitialOrgContext, type RuntimeEvent } from \"@eloxiv/client/runtime\"\nimport { redirected, shellRegistry, type Redirect, type ShellRegistry } from \"@eloxiv/shell-core\"\nimport { webModelContext } from \"@eloxiv/shell-core/web\"\nimport type { AnyModuleContract, ConsentState, LocalClientSessionState, RegionHint, SlotEntry } from \"@eloxiv/contracts\"\nimport { Dialog } from \"@foldkit/ui\"\nimport { Array as Arr, Duration, Effect, Option, Queue, Schema, Stream } from \"effect\"\nimport { Command, Dom, ManagedResource, Subscription, Update } from \"foldkit\"\nimport { defineMessageUnion } from \"foldkit/message\"\nimport { load, pushUrl, replaceUrl, UrlRequest } from \"foldkit/navigation\"\nimport { Url, toString as urlToString } from \"foldkit/url\"\nimport * as Make from \"./make.ts\"\nimport { credentials } from \"./session.ts\"\nimport { isLazyScreen, type AnyScreen, type InstalledScreen, type ScreenMeta } from \"./screen.ts\"\nimport { directionFor, LOCALES, negotiate } from \"./locale.ts\"\nimport { markNavigationStart } from \"./timing.ts\"\nimport { SESSION_KEY, SIGNED_OUT_KEY, webSessionStorage } from \"./webSession.ts\"\n\n// ---------------------------------------------------------------------------------------------------------------\n// Model\n\nexport const Scheme = Schema.Literals([\"system\", \"light\", \"dark\"])\nexport type Scheme = typeof Scheme.Type\nexport const Direction = Schema.Literals([\"ltr\", \"rtl\"])\nexport type Direction = typeof Direction.Type\n\n/** The appearance preset: the app's theme, or its high-contrast variant (`themes/default`'s `contrastTheme`). */\nexport const Preset = Schema.Literals([\"standard\", \"contrast\"])\nexport type Preset = typeof Preset.Type\n\nexport const Appearance = Schema.Struct({\n scheme: Scheme,\n systemDark: Schema.Boolean,\n direction: Direction,\n preset: Preset,\n})\nexport type Appearance = typeof Appearance.Type\n\n/** A signed-in session as the Model holds it: a handle into the shell's credentials (never the token) and the user. */\nexport const Session = Schema.Struct({\n handle: Schema.String,\n user: Schema.Struct({ id: Schema.String, email: Schema.String, name: Schema.String }),\n})\nexport type Session = typeof Session.Type\n\nexport const Membership = Schema.Struct({\n orgId: Schema.String,\n name: Schema.String,\n roles: Schema.Array(Schema.String),\n})\nexport type Membership = typeof Membership.Type\n\n/** The sign-in form: the email the person types (the password stays in its field until the sign-in reads it). */\nexport const SignInForm = Schema.Struct({\n email: Schema.String,\n submitting: Schema.Boolean,\n error: Schema.Option(Schema.String),\n})\nexport type SignInForm = typeof SignInForm.Type\n\nexport const Auth = Schema.Union([\n Schema.TaggedStruct(\"SignedOut\", { form: SignInForm }),\n /** A stored session the kernel is checking; `problem` when it could not be reached (the core checks again). */\n Schema.TaggedStruct(\"Restoring\", { problem: Schema.Option(Schema.String) }),\n /** A sign-out keeping its revocation: nothing of the session is shown, and the form not yet. */\n Schema.TaggedStruct(\"SigningOut\", { email: Schema.String }),\n Schema.TaggedStruct(\"SignedIn\", {\n session: Session,\n memberships: Schema.Array(Membership),\n /** The organisation actions and the replica act in. */\n orgId: Schema.Option(Schema.String),\n /** Its generation, as the core announced it (none while a switch the person asked for is under way). */\n generation: Schema.Option(Schema.Number),\n /** The sync server refused the session and the core is checking it with the kernel: no replica meanwhile. */\n checking: Schema.Boolean,\n /** Why the organisations could not be listed (the core lists them again): `memberships` are unknown, not none. */\n organisationsProblem: Schema.Option(Schema.String),\n /**\n * Shown from this device alone: an offline start, the kernel not reached to check the session, the replica the\n * core remembered for it open from disk (its writes kept there until the connection is back).\n */\n offline: Schema.Boolean,\n }),\n])\nexport type Auth = typeof Auth.Type\n\n/** The session as the core announces it, for `GotSession` (its token stays in the core, named by `session.handle`). */\nconst SessionView = Schema.Union([\n Schema.TaggedStruct(\"SignedIn\", {\n session: Session,\n memberships: Schema.Array(Membership),\n orgId: Schema.Option(Schema.String),\n generation: Schema.Number,\n /** The core could not list the organisations (and lists them again): why. */\n organisationsProblem: Schema.optionalKey(Schema.String),\n /** An offline start: the core opened the remembered replica without reaching the kernel (the session's `offline`). */\n offline: Schema.optionalKey(Schema.Boolean),\n }),\n Schema.TaggedStruct(\"SigningOut\", {}),\n Schema.TaggedStruct(\"SignedOut\", {}),\n Schema.TaggedStruct(\"Restoring\", { problem: Schema.Option(Schema.String) }),\n])\ntype SessionView = typeof SessionView.Type\n\n/** The replica's connection, as the core reports it for a generation. */\nconst Connection = Schema.Struct({\n generation: Schema.Number,\n state: Schema.Literals([\"connecting\", \"connected\", \"disconnected\", \"needsAuth\"]),\n})\ntype Connection = typeof Connection.Type\n\n/** After a sign-out: is the server revoking it, did it confirm, or is revocation pending (and retried)? */\nexport const Revocation = Schema.Literals([\"none\", \"revoking\", \"pending\", \"confirmed\"])\nexport type Revocation = typeof Revocation.Type\n\n/** What a desktop sign-in asks to approve, as the page's address gives it (`challenge`, `redirect_uri`, `state`). */\nexport const DesktopRequest = Schema.Struct({\n challenge: Schema.String,\n redirectUri: Schema.String,\n state: Schema.String,\n})\nexport type DesktopRequest = typeof DesktopRequest.Type\n\nexport const ShellRoute = Schema.Union([\n Schema.TaggedStruct(\"Home\", {}),\n Schema.TaggedStruct(\"View\", { view: Schema.String, path: Schema.String, record: Schema.Option(Schema.String) }),\n /** A MAKE module's sandboxed view (`/make/<module>`). */\n Schema.TaggedStruct(\"Make\", { module: Schema.String }),\n /** The settings frame (`/settings`): profile, members, language and appearance. */\n Schema.TaggedStruct(\"Settings\", {}),\n /** A desktop sign-in to approve (`/desktop/sign-in`): its request, or none when the address does not hold one. */\n Schema.TaggedStruct(\"DesktopSignIn\", { request: Schema.Option(DesktopRequest) }),\n Schema.TaggedStruct(\"NotFound\", { path: Schema.String }),\n])\nexport type ShellRoute = typeof ShellRoute.Type\n\n/** A contributed view's screen beside the screen shown: which slot and contribution, and its own Model. */\nexport const Panel = Schema.Struct({\n slot: Schema.String,\n contribution: Schema.String,\n view: Schema.String,\n instance: Schema.Number,\n model: Schema.Unknown,\n})\nexport type Panel = typeof Panel.Type\n\n/** The screen shown: which view and record, for which replica, and its own Model (the screen's types end here). */\nexport const ScreenSlot = Schema.Struct({\n view: Schema.String,\n record: Schema.Option(Schema.String),\n replica: ReplicaKey,\n instance: Schema.Number,\n model: Schema.Unknown,\n /** The views contributed to the slots it shows, as panels beside it, in the slots' order. */\n panels: Schema.Array(Panel),\n})\nexport type ScreenSlot = typeof ScreenSlot.Type\n\n/** A member of the organisation (the Directory's `listMembers`). */\nexport const Member = Schema.Struct({\n userId: Schema.String,\n email: Schema.String,\n roles: Schema.Array(Schema.String),\n groups: Schema.Array(Schema.String),\n})\nexport type Member = typeof Member.Type\n\n/**\n * The settings frame's members, for the organisation they were loaded in. A load names its request (the shell's\n * numbering), and only that request's answer is taken: an earlier load's, for the same organisation or not (Acme,\n * Globex, Acme again), is dropped.\n */\nexport const Members = Schema.Union([\n Schema.TaggedStruct(\"NotLoaded\", {}),\n Schema.TaggedStruct(\"Loading\", { orgId: Schema.String, request: Schema.Number }),\n Schema.TaggedStruct(\"Loaded\", { orgId: Schema.String, members: Schema.Array(Member) }),\n Schema.TaggedStruct(\"Failed\", { orgId: Schema.String, message: Schema.String }),\n])\nexport type Members = typeof Members.Type\n\n/**\n * The desktop sign-in's approval: not asked yet, sent (its request number, so only that answer is taken), refused by\n * the kernel (why), or approved (the browser is on its way to the app's redirect).\n */\nexport const DesktopApproval = Schema.Union([\n Schema.TaggedStruct(\"Idle\", {}),\n Schema.TaggedStruct(\"Approving\", { request: Schema.Number }),\n Schema.TaggedStruct(\"Failed\", { message: Schema.String }),\n Schema.TaggedStruct(\"Approved\", {}),\n])\nexport type DesktopApproval = typeof DesktopApproval.Type\n\n/** The kernel's readiness (`GET /ready`): checking at first, then ready, degraded, not ready, or not reachable. */\nexport const Backend = Schema.Literals([\"checking\", \"ready\", \"degraded\", \"not-ready\", \"unreachable\"])\nexport type Backend = typeof Backend.Type\n\n/**\n * The settings frame's profile editing: the person's drafts, and the one change in flight (its field and request\n * number, so only that request's answer is taken) or how the last one ended.\n */\nexport const ProfileField = Schema.Literals([\"name\", \"email\"])\nexport const Profile = Schema.Struct({\n name: Schema.Option(Schema.String),\n email: Schema.Option(Schema.String),\n saving: Schema.Option(Schema.Struct({ field: ProfileField, request: Schema.Number })),\n outcome: Schema.Option(Schema.Struct({ field: ProfileField, ok: Schema.Boolean, message: Schema.String })),\n})\nexport type Profile = typeof Profile.Type\n\n/**\n * The consent prompt: off (the app loads nothing that needs consent), not known yet, or the visitor's choices asked\n * for (an optional category unchosen) or made.\n */\nexport const ConsentPrompt = Schema.Literals([\"off\", \"checking\", \"undecided\", \"decided\"])\nexport type ConsentPrompt = typeof ConsentPrompt.Type\n\n/**\n * A screen whose code loads on demand (`screen.ts`, \"Loaded on demand\"): being loaded, loaded, or not loadable (the\n * network, or a newer release that replaced the chunk), with why. Screens loaded with the shell are never listed.\n */\nexport const ScreenLoad = Schema.Union([\n Schema.TaggedStruct(\"Loading\", {}),\n Schema.TaggedStruct(\"Loaded\", {}),\n Schema.TaggedStruct(\"Failed\", { message: Schema.String }),\n])\nexport type ScreenLoad = typeof ScreenLoad.Type\n\nexport const Model = Schema.Struct({\n route: ShellRoute,\n backend: Backend,\n consent: ConsentPrompt,\n /**\n * The organisation the address names (`?org=`, as a record link from MCP or a notification carries it): chosen\n * when the organisations load, and switched to when the address changes, only if the person belongs to it.\n */\n linkedOrg: Schema.Option(Schema.String),\n auth: Auth,\n revocation: Revocation,\n replica: ReplicaState,\n connection: Schema.Option(Connection),\n screen: Schema.Option(ScreenSlot),\n /** The MAKE screen shown, for the session and organisation it was opened in (its instance numbered as screens). */\n make: Schema.Option(Schema.Struct({ instance: Schema.Number, model: Make.Model })),\n /** Screens created so far: each gets the next number, so Commands of a discarded screen are dropped. */\n screens: Schema.Number,\n /** The screens loaded on demand that a route has asked for, by view. */\n loads: Schema.Record(Schema.String, ScreenLoad),\n /** The shell's own requests made so far (the members'): each gets the next number, and its answer names it. */\n requests: Schema.Number,\n appearance: Appearance,\n appearanceDialog: Dialog.Model,\n /** The shell's language (one of the catalog's locales). */\n locale: Schema.String,\n members: Members,\n profile: Profile,\n desktop: DesktopApproval,\n})\nexport type Model = typeof Model.Type\n\n/** What the shell reads from storage when it starts (whether a session is stored: never its token). */\nexport const Flags = Schema.Struct({\n storedSession: Schema.Boolean,\n pendingRevocations: Schema.Boolean,\n appearance: Schema.Struct({ scheme: Scheme, direction: Direction }),\n systemDark: Schema.Boolean,\n /** The appearance preset chosen on this device (the theme's own when none was). */\n preset: Schema.optionalKey(Preset),\n /** The language chosen on this device, or else the one the browser's languages negotiate. */\n locale: Schema.String,\n})\nexport type Flags = typeof Flags.Type\n\n// ---------------------------------------------------------------------------------------------------------------\n// Messages\n\nexport const Message = defineMessageUnion({\n ClickedLink: { request: UrlRequest },\n ChangedUrl: { url: Url },\n CompletedNavigateInternal: {},\n CompletedLoadExternal: {},\n ChangedEmail: { value: Schema.String },\n SubmittedSignIn: {},\n FailedSignIn: { message: Schema.String },\n SelectedOrganisation: { orgId: Schema.String },\n ClickedSignOut: {},\n /** The core's session, as it announced it (or as it stands when a Command needs the Model to hear it again). */\n GotSession: { state: SessionView },\n /** The core reset its context (an organisation change, a sign-out, `needs-auth`): every view of it is gone. */\n ChangedContext: { generation: Schema.Number, reason: Schema.Literals([\"org\", \"signOut\", \"needsAuth\"]) },\n ChangedConnection: { connection: Connection },\n /** Where the last sign-out's revocation stands, as the core reports it. */\n ChangedRevocation: { revocation: Revocation },\n /** A Command the core answers through its events finished (they say what changed). */\n CompletedRuntime: {},\n OpenedReplica: { key: ReplicaKey },\n ClosedReplica: {},\n FailedReplica: { orgId: Schema.String, message: Schema.String },\n /**\n * A screen's Message, naming the instance it is for: its Commands' results and its Subscriptions' Messages alike\n * (a Subscription runs for one instance), so one for a screen since discarded is dropped.\n */\n GotScreenMessage: { view: Schema.String, instance: Schema.Number, message: Schema.Unknown },\n /** A panel's Message, naming its instance in the same way (a view contributed twice is two panels). */\n GotPanelMessage: { view: Schema.String, instance: Schema.Number, message: Schema.Unknown },\n GotMakeMessage: { instance: Schema.Option(Schema.Number), message: Make.Message },\n /** A screen loaded on demand is loaded (the shell holds it), or could not be loaded: why. */\n LoadedScreen: { view: Schema.String },\n FailedScreen: { view: Schema.String, message: Schema.String },\n /** The person asked to reload the page (a part of the app could not be loaded). */\n ClickedReload: {},\n ClickedAppearance: {},\n GotAppearanceDialogMessage: { message: Dialog.Message },\n /** `group`: the radio group chosen in (the dialog's, `scheme`, unless named), so focus follows within it. */\n ChoseScheme: { scheme: Scheme, focus: Schema.Boolean, group: Schema.optionalKey(Schema.String) },\n ChoseDirection: { direction: Direction, focus: Schema.Boolean, group: Schema.optionalKey(Schema.String) },\n ChangedSystemScheme: { dark: Schema.Boolean },\n ChosePreset: { preset: Preset, focus: Schema.Boolean, group: Schema.optionalKey(Schema.String) },\n ChoseLanguage: { locale: Schema.String },\n CheckedBackend: { backend: Backend },\n /** The visitor's consent as the kernel holds it: `undecided` while an optional category is unchosen. */\n GotConsent: { undecided: Schema.Boolean },\n /** The prompt's answer: every optional category, or only what is necessary. */\n ChoseConsent: { accept: Schema.Boolean },\n ChangedProfileName: { value: Schema.String },\n ChangedProfileEmail: { value: Schema.String },\n SubmittedProfile: { field: ProfileField },\n SavedProfile: { request: Schema.Number, session: Schema.String, field: ProfileField, value: Schema.String },\n FailedProfile: { request: Schema.Number, session: Schema.String, field: ProfileField, message: Schema.String },\n GotMembers: { request: Schema.Number, orgId: Schema.String, members: Schema.Array(Member) },\n FailedMembers: { request: Schema.Number, orgId: Schema.String, message: Schema.String },\n ClickedApproveDesktop: {},\n ClickedDeclineDesktop: {},\n ApprovedDesktop: { request: Schema.Number, redirect: Schema.String },\n FailedApproveDesktop: { request: Schema.Number, message: Schema.String },\n CompletedStore: {},\n CompletedMark: {},\n CompletedFocus: {},\n})\nexport type Message = typeof Message.Type\n\ntype UpdateReturn = Update.Return<Model, Message, ReplicaService>\ntype SignedIn = Extract<Auth, { readonly _tag: \"SignedIn\" }>\ntype SignedInView = Extract<SessionView, { readonly _tag: \"SignedIn\" }>\n\n// ---------------------------------------------------------------------------------------------------------------\n// Storage (the shell's own keys, shared with the React shell so a person keeps their session and choice)\n\nexport { SESSION_KEY, PENDING_KEY, CONTEXT_KEY, SIGNED_OUT_KEY } from \"./webSession.ts\"\nexport const APPEARANCE_KEY = \"eloxiv.appearance\"\nexport const LOCALE_KEY = \"eloxiv.locale\"\nexport const PRESET_KEY = \"eloxiv.appearance.preset\"\nexport const orgKey = (userId: string) => `eloxiv.org.${userId}`\n\n/**\n * The browser's storage of the session (`webSession.ts`): the core's session store (the token, with the context last\n * open remembered for an offline start) and its revocation store (a durable sign-out), and the shell's own keys.\n */\nconst webStorage = webSessionStorage()\nconst storage = { get: webStorage.get, set: webStorage.set }\nconst storedSessionToken = webStorage.storedToken\nconst storedPending = webStorage.pending\n\n/** The session as storage keeps it for the next start (the React shell's format): the token and the user. */\nconst StoredSession = Schema.Struct({\n token: Schema.String,\n user: Schema.Struct({ id: Schema.String, email: Schema.String, name: Schema.String }),\n})\n\n/** The Flags Effect: whether a session is stored (the core checks it), pending revocations and the appearance. */\nexport const readFlags: Effect.Effect<Flags> = Effect.sync(() => {\n const appearance = Schema.decodeUnknownOption(\n Schema.fromJsonString(Schema.Struct({ scheme: Scheme, direction: Direction })),\n )(storage.get(APPEARANCE_KEY) ?? \"\")\n return {\n storedSession: storedSessionToken() !== undefined,\n pendingRevocations: storedPending().length > 0,\n appearance: Option.getOrElse(appearance, () => ({ scheme: \"system\" as const, direction: \"ltr\" as const })),\n systemDark: typeof matchMedia === \"function\" && matchMedia(\"(prefers-color-scheme: dark)\").matches,\n preset: storage.get(PRESET_KEY) === \"contrast\" ? \"contrast\" : \"standard\",\n locale: chosenLocale(storage.get(LOCALE_KEY)),\n }\n})\n\n/** The stored language when it is one of the catalog's, else the browser's languages, negotiated. */\nconst chosenLocale = (stored: string | undefined): string =>\n stored !== undefined && (LOCALES as ReadonlyArray<string>).includes(stored)\n ? stored\n : negotiate(typeof navigator === \"object\" && Array.isArray(navigator.languages) ? navigator.languages : [])\n\n// ---------------------------------------------------------------------------------------------------------------\n// The program, over an app's installed modules and screens\n\nexport interface ShellConfig {\n readonly kernelUrl: string\n readonly syncUrl: string\n readonly clientVersion?: string | undefined\n /** The installed modules' contracts (`eloxiv.modules.ts`). */\n readonly contracts: ReadonlyArray<AnyModuleContract>\n /** The app's sync schema, named queries and mutators (`eloxiv.sync.ts`). */\n readonly schema: AnySyncSchema\n readonly queries: object\n readonly mutators: unknown\n /**\n * The installed screens (every `screens/*.ts`'s `screen`): loaded with the shell, or loaded when a route first needs\n * them (`LazyScreen`, as `installed.ts` makes them).\n */\n readonly screens: ReadonlyArray<InstalledScreen>\n /** Where replicas live (IndexedDB in browsers and webviews). */\n readonly storage?: \"idb\" | \"mem\"\n /** Reads (and empties) the password field when the person signs in; the `#password` input by default. */\n readonly readPassword?: Effect.Effect<string>\n /** How long one attempt to revoke a session waits for the kernel before it counts as unanswered (10 s). */\n readonly revocationTimeout?: Duration.Input\n /** How often pending revocations are retried (15 s; also when the network returns, and at the next start). */\n readonly revocationRetry?: Duration.Input\n /**\n * The app's own legacy paths and where they live now (shell-core's `Redirect`), after the shell's: `/home` is the\n * home, `/settings/<section>` the settings, `/agent` the conversation screen and `/access-requests/<id>` the\n * inbox, when those screens are installed.\n */\n readonly redirects?: ReadonlyArray<Redirect> | undefined\n /** A development build: the error view shows a failure's stack (never in production). */\n readonly development?: boolean | undefined\n /**\n * WebMCP (a browser agent working in the page, `navigator.modelContext`): registered while the person is signed in\n * with an organisation chosen, and torn down, its agent session revoked, on a sign-out, a revocation or a switch.\n * Off with `false`; on by default where the browser has a model context. A client action marked `consent` runs\n * only after `approve`.\n */\n readonly webMcp?:\n | false\n | {\n readonly clientActions?: ReadonlyArray<ClientAction<any>> | undefined\n readonly approve?: ((request: ApprovalRequest) => Promise<boolean>) | undefined\n }\n | undefined\n /**\n * The consent prompt (the Privacy contract's visitor consent, `consentController`): shown while an optional\n * category is unchosen, its answer kept by the kernel for the visit and claimed as the person's at sign-in. Each\n * script loads only while its category is granted. Off without it: an app that loads nothing needing consent asks\n * for none.\n */\n readonly consent?:\n | {\n readonly scripts?: ReadonlyArray<ConsentScript> | undefined\n readonly region?: RegionHint | undefined\n }\n | undefined\n}\n\n/** Is any optional category unchosen (its region's default applied, not the visitor's choice)? */\nexport const consentUndecided = (consent: ConsentState): boolean =>\n ([\"functional\", \"analytics\", \"marketing\"] as const).some(\n (category) => consent.categories[category].source === \"region\",\n )\n\n/** The sign-in form's password, read from its field when the sign-in runs, and the field emptied. */\nconst passwordField: Effect.Effect<string> = Effect.sync(() => {\n const field = document.getElementById(\"password\") as { value: string } | null\n if (field === null) return \"\"\n const value = field.value\n field.value = \"\"\n return value\n})\n\n/** The paths the shell routes itself, with whatever follows them (`/` is home): no screen's route may take them. */\n/** The fields of a lazy screen the build reads from its declaration (`screenMeta.ts`), checked again when it loads. */\nconst SCREEN_META_FIELDS = [\"view\", \"label\", \"route\", \"title\", \"home\", \"slots\"] as const satisfies ReadonlyArray<\n keyof ScreenMeta\n>\n\nconst SHELL_ROUTES = [\"/settings\", \"/make\", \"/desktop\"] as const\n\n/** Where a desktop sign-in page lives (the daemon's default `signInPage` is the shell's origin with this path). */\nconst DESKTOP_SIGN_IN_PATH = \"/desktop/sign-in\"\n\n/** An S256 challenge: 43 base64url characters, as the kernel requires. */\nconst DESKTOP_CHALLENGE = /^[A-Za-z0-9_-]{43}$/u\n/** Schemes a redirect may never use, whatever the deployment lists: they would run or load something here. */\nconst UNSAFE_SCHEMES = new Set([\"https\", \"javascript\", \"data\", \"file\", \"blob\", \"about\", \"ftp\", \"ws\", \"wss\", \"vbscript\"])\n\n/**\n * The desktop sign-in an address asks to approve, when it holds a well-formed one: a challenge, a state of up to 256\n * characters, and a redirect the app instance receives on (a loopback address over plain HTTP, `127.0.0.1` or\n * `[::1]`, RFC 8252; or a custom scheme, which the kernel accepts only when the deployment lists it). The kernel checks\n * all of it again; this only keeps the page from offering to approve what it would refuse, or a web address.\n */\nexport const desktopRequestOf = (url: Url): Option.Option<DesktopRequest> =>\n Option.flatMap(url.search, (search) => {\n const query = new URLSearchParams(search)\n const challenge = query.get(\"challenge\") ?? \"\"\n const redirectUri = query.get(\"redirect_uri\") ?? \"\"\n const state = query.get(\"state\") ?? \"\"\n if (!DESKTOP_CHALLENGE.test(challenge) || state === \"\" || state.length > 256) return Option.none()\n let redirect: URL\n try {\n redirect = new URL(redirectUri)\n } catch {\n return Option.none()\n }\n if (redirect.username !== \"\" || redirect.password !== \"\" || redirect.hash !== \"\") return Option.none()\n const scheme = redirect.protocol.slice(0, -1).toLowerCase()\n const allowed =\n scheme === \"http\"\n ? redirect.hostname === \"127.0.0.1\" || redirect.hostname === \"[::1]\"\n : /^[a-z][a-z0-9+.-]*$/u.test(scheme) && !UNSAFE_SCHEMES.has(scheme)\n return allowed ? Option.some({ challenge, redirectUri, state }) : Option.none()\n })\n\n/** Whether `redirect` (the kernel's answer) goes where the request said: the same redirect, with the code added. */\nconst redirectMatches = (redirect: string, redirectUri: string): boolean => {\n try {\n const answered = new URL(redirect)\n const asked = new URL(redirectUri)\n return (\n answered.protocol === asked.protocol &&\n answered.host === asked.host &&\n answered.pathname === asked.pathname &&\n answered.searchParams.has(\"code\")\n )\n } catch {\n return false\n }\n}\n\nexport interface NavEntry {\n readonly view: string\n readonly module: string\n readonly label: string\n readonly path: string\n}\n\n/** A Subscription entry as Foldkit runs it (the shell lifts a screen's, whose types end at the screen boundary). */\ninterface AnyEntry {\n readonly dependenciesSchema: Schema.Top\n readonly modelToDependencies: (model: unknown) => unknown\n readonly dependenciesToStream: (dependencies: unknown, read: () => unknown) => Stream.Stream<unknown, never, any>\n readonly keepAliveEquivalence?: (left: unknown, right: unknown) => boolean\n}\n\n/** A screen's dependencies, for the instance they were read from. */\ninterface Target {\n readonly instance: number\n readonly dependencies: unknown\n}\n\n/**\n * A screen's (or panel's) Subscriptions, run for the instance `read` finds in the shell's Model: each Message names\n * that instance, and a new instance (another record, another organisation's replica) starts them afresh. So a\n * Message one sent before its instance was discarded (a snapshot of the previous organisation's replica, still in\n * flight) names that instance, and is dropped.\n */\nconst forInstance = (\n subscriptions: unknown,\n prefix: string,\n read: (model: Model) => Option.Option<{ readonly instance: number; readonly model: unknown }>,\n toMessage: (instance: number, message: unknown) => Message,\n): Subscription.Subscriptions<Model, Message, ReplicaService> =>\n Object.fromEntries(\n Object.entries(subscriptions as Record<string, AnyEntry>).map(([name, entry]) => {\n const lifted = {\n dependenciesSchema: Schema.Struct({\n target: Schema.Option(Schema.Struct({ instance: Schema.Number, dependencies: entry.dependenciesSchema })),\n }),\n modelToDependencies: (model: Model) => ({\n target: Option.map(read(model), (found): Target => ({\n instance: found.instance,\n dependencies: entry.modelToDependencies(found.model),\n })),\n }),\n dependenciesToStream: (\n { target }: { readonly target: Option.Option<Target> },\n readTarget?: () => { readonly target: Option.Option<Target> },\n ) =>\n Option.match(target, {\n onNone: () => Stream.empty,\n onSome: ({ instance, dependencies }) =>\n Stream.map(\n entry.dependenciesToStream(dependencies, () => {\n const current = readTarget?.().target ?? Option.none()\n return Option.isSome(current) && current.value.instance === instance\n ? current.value.dependencies\n : dependencies\n }),\n (message) => toMessage(instance, message),\n ),\n }),\n ...(entry.keepAliveEquivalence === undefined\n ? {}\n : {\n keepAliveEquivalence: (\n left: { readonly target: Option.Option<Target> },\n right: { readonly target: Option.Option<Target> },\n ) =>\n Option.isSome(left.target) && Option.isSome(right.target)\n ? left.target.value.instance === right.target.value.instance &&\n entry.keepAliveEquivalence!(left.target.value.dependencies, right.target.value.dependencies)\n : Option.isNone(left.target) && Option.isNone(right.target),\n }),\n }\n return [`${prefix}${name}`, lifted]\n }),\n ) as unknown as Subscription.Subscriptions<Model, Message, ReplicaService>\n\n/**\n * The Subscriptions of a screen loaded on demand, in one entry of the shell's: the program's entries are fixed when\n * it starts, before the screen's code (and so its entries) is loaded. The entry runs while `read` finds an instance of\n * a loaded screen and restarts for each new instance; within it, each of the screen's entries runs as the runtime runs\n * an entry (its dependencies read from every Model, its stream restarted only when they change under its equivalence,\n * `read` giving the latest), and every Message names the instance, as `forInstance`'s do.\n *\n * The runtime hands an entry each Model through `modelToDependencies` only, so this entry passes the instance's Model\n * on to the screen's entries from there (a listener per running entry, told synchronously, holding nothing else).\n */\nexport const hostedSubscriptions = (\n entries: () => unknown,\n prefix: string,\n read: (model: Model) => Option.Option<{ readonly instance: number; readonly model: unknown }>,\n toMessage: (instance: number, message: unknown) => Message,\n): Subscription.Subscriptions<Model, Message, ReplicaService> => {\n let latest: Option.Option<{ readonly instance: number; readonly model: unknown }> = Option.none()\n const listeners = new Set<() => void>()\n /** The instance's Models from now on: the latest at once, then each one the runtime reads, while the instance lasts. */\n const models = (instance: number): Stream.Stream<unknown> =>\n Stream.callback<unknown>((queue) =>\n Effect.acquireRelease(\n Effect.sync(() => {\n const offer = () => {\n if (Option.isSome(latest) && latest.value.instance === instance)\n Queue.offerUnsafe(queue, latest.value.model)\n }\n offer()\n listeners.add(offer)\n return offer\n }),\n (offer) => Effect.sync(() => listeners.delete(offer)),\n ).pipe(Effect.andThen(Effect.never)),\n )\n const run = (instance: number): Stream.Stream<Message, never, any> =>\n Stream.mergeAll(\n Object.values((entries() ?? {}) as Record<string, AnyEntry>).map((entry) => {\n const equivalence = entry.keepAliveEquivalence ?? Schema.toEquivalence(entry.dependenciesSchema)\n let dependencies: unknown\n return models(instance).pipe(\n Stream.map((model) => {\n dependencies = entry.modelToDependencies(model)\n return dependencies\n }),\n Stream.changesWith(equivalence),\n Stream.switchMap((current) => entry.dependenciesToStream(current, () => dependencies)),\n Stream.map((message) => toMessage(instance, message)),\n )\n }),\n { concurrency: \"unbounded\" },\n )\n return {\n [`${prefix}*`]: {\n dependenciesSchema: Schema.Struct({ instance: Schema.Option(Schema.Number) }),\n modelToDependencies: (model: Model) => {\n latest = entries() === undefined ? Option.none() : read(model)\n for (const listener of listeners) listener()\n return { instance: Option.map(latest, (found) => found.instance) }\n },\n dependenciesToStream: ({ instance }: { readonly instance: Option.Option<number> }) =>\n Option.match(instance, { onNone: () => Stream.empty, onSome: run }),\n },\n } as unknown as Subscription.Subscriptions<Model, Message, ReplicaService>\n}\n\nexport const makeShell = (config: ShellConfig) => {\n const registry: ShellRegistry = shellRegistry(config.contracts)\n // Only views with an installed screen get a route; a screen for a view no module declares is ignored. Each one's\n // declared fields route and link it (`metas`); its code is in `screens` once loaded: from the start, or when a route\n // first needs it (`loaders`, outside the Model like the credentials; the Model's `loads` says which have loaded).\n const metas = new Map<string, ScreenMeta>()\n const screens = new Map<string, AnyScreen>()\n const loaders = new Map<string, () => Promise<AnyScreen>>()\n /** Screens of kernel-provided views (the agent's, approvals'), routed by the route they name. */\n const kernelViews = new Map<string, { readonly route: string; readonly title: string }>()\n /**\n * Why a route a screen names (a kernel view's) cannot be routed, if it cannot: it must be a plain path, and route\n * nothing else, as the shell resolves paths (its own first, then the screens' routes and what follows them, then\n * the manifests' views and one record segment after each).\n */\n const routeProblem = (route: string): string | undefined => {\n if (!/^(\\/[A-Za-z0-9._~-]+)+$/.test(route))\n return \"it is not a plain path (one or more segments, each after one slash; no trailing slash, query or fragment)\"\n const within = (path: string, base: string) => path === base || path.startsWith(`${base}/`)\n for (const reserved of SHELL_ROUTES) if (within(route, reserved)) return `the shell routes ${reserved} itself`\n for (const view of registry.views()) {\n // Under a manifest view's route (its records), or holding one under it.\n const records =\n view.route === \"/\" ? route.lastIndexOf(\"/\") === 0 : within(route, view.route) && route !== view.route\n if (view.route === route || records || within(view.route, route))\n return `it collides with the view ${view.id} at ${view.route}`\n }\n for (const [other, { route: taken }] of kernelViews)\n if (within(route, taken) || within(taken, route)) return `it collides with the screen of ${other} at ${taken}`\n return undefined\n }\n /** The screen that claims the home route, `/` (a launcher), if one is installed. */\n let home: ScreenMeta | undefined\n const install = (installed: InstalledScreen) => {\n const screen = isLazyScreen(installed) ? installed.meta : installed\n if (isLazyScreen(installed)) loaders.set(screen.view, installed.load)\n else screens.set(screen.view, installed)\n metas.set(screen.view, screen)\n }\n for (const installed of config.screens) {\n const screen = isLazyScreen(installed) ? installed.meta : installed\n if (screen.home === true) {\n if (home !== undefined) throw new Error(`Two screens claim the home route: ${home.view} and ${screen.view}`)\n if (registry.findView(screen.view) !== undefined || screen.route !== undefined)\n throw new Error(`The home screen ${screen.view} names a manifest view or a route: it is shown at / only`)\n if (metas.has(screen.view)) throw new Error(`Two screens render the view ${screen.view}`)\n home = screen\n install(installed)\n continue\n }\n const declared = registry.findView(screen.view) !== undefined\n if (!declared && screen.route === undefined) continue\n if (metas.has(screen.view)) throw new Error(`Two screens render the view ${screen.view}`)\n if (!declared) {\n const problem = routeProblem(screen.route!)\n if (problem !== undefined)\n throw new Error(`The screen of ${screen.view} cannot be routed at ${screen.route}: ${problem}`)\n kernelViews.set(screen.view, { route: screen.route!, title: screen.title ?? screen.label ?? screen.view })\n }\n install(installed)\n }\n const viewTitle = (view: string) =>\n view === home?.view\n ? (home.title ?? home.label ?? view)\n : (kernelViews.get(view)?.title ?? registry.view(view).title)\n const nav: ReadonlyArray<NavEntry> = [\n ...registry\n .views()\n .filter((view) => metas.has(view.id))\n .map((view) => ({\n view: view.id,\n module: view.module,\n label: metas.get(view.id)!.label ?? view.title,\n path: view.route,\n })),\n ...[...kernelViews].map(([view, { route, title }]) => ({\n view,\n module: view.split(\".\")[0]!,\n label: metas.get(view)!.label ?? title,\n path: route,\n })),\n ].sort((a, b) => a.label.localeCompare(b.label))\n\n // The installed modules' commands that open a view with a screen (the Command contract's palette entries); an\n // action command needs its module's UI, which a screen offers itself.\n const commands: ReadonlyArray<{ readonly id: string; readonly title: string; readonly path: string }> = registry\n .commands()\n .flatMap((entry) =>\n entry.run.kind === \"view\" && metas.has(entry.run.view)\n ? [{ id: entry.id, title: entry.title, path: entry.run.route }]\n : [],\n )\n\n /** A slot's contributions the shell can show: views whose screen is installed, and commands that open one. */\n const slotContents = (slotId: string) => {\n let entries: ReadonlyArray<SlotEntry>\n try {\n entries = registry.slot(slotId)\n } catch {\n // A slot no installed module declares: nothing to show.\n return { panels: [], links: [] }\n }\n const panels = entries.flatMap((entry) =>\n \"view\" in entry.target && metas.has(entry.target.view.id)\n ? [{ slot: slotId, contribution: entry.contribution, view: entry.target.view.id }]\n : [],\n )\n const links = entries.flatMap((entry) =>\n \"command\" in entry.target && entry.target.command.run.kind === \"view\" && metas.has(entry.target.command.run.view)\n ? [\n {\n slot: slotId,\n id: entry.target.command.id,\n title: entry.target.command.title,\n path: entry.target.command.run.route,\n },\n ]\n : [],\n )\n return { panels, links }\n }\n const slots = new Map(\n [...metas.values()].flatMap((screen) => (screen.slots ?? []).map((id) => [id, slotContents(id)] as const)),\n )\n\n // Legacy routes: where an older path (a bookmark, a link in an email) lives now. The URL is replaced with the new\n // one (`legacyTarget`), and the route is the new one's, so a link from before never lands on \"not found\".\n const legacy: ReadonlyArray<Redirect> = [\n ...(config.redirects ?? []),\n { from: \"/home\", to: \"/\" },\n { from: \"/settings/*\", to: \"/settings\" },\n ...(kernelViews.has(\"agent.conversation\")\n ? [{ from: \"/agent\", to: kernelViews.get(\"agent.conversation\")!.route }]\n : []),\n ...(kernelViews.has(\"inbox.items\")\n ? [{ from: \"/access-requests/*\", to: kernelViews.get(\"inbox.items\")!.route }]\n : []),\n ]\n /** The path `url` is redirected to, when one of its legacy routes applies (with its query), else undefined. */\n const legacyTarget = (url: Url): string | undefined => {\n if (url.pathname === \"/settings\" || url.pathname === \"/settings/\") return undefined\n const query = Option.getOrElse(url.search, () => \"\")\n const original = `${url.pathname}${query === \"\" ? \"\" : `?${query}`}`\n const target = redirected(legacy, original)\n return target === undefined || target === original ? undefined : target\n }\n\n const routeOf = (requested: Url): ShellRoute => {\n const target = legacyTarget(requested)\n const url = target === undefined ? requested : { ...requested, pathname: target.split(\"?\")[0]! }\n if (url.pathname === \"/\" || url.pathname === \"\")\n return home === undefined ? { _tag: \"Home\" } : { _tag: \"View\", view: home.view, path: \"/\", record: Option.none() }\n if (url.pathname === \"/settings\" || url.pathname === \"/settings/\") return { _tag: \"Settings\" }\n if (url.pathname === DESKTOP_SIGN_IN_PATH || url.pathname === `${DESKTOP_SIGN_IN_PATH}/`)\n return { _tag: \"DesktopSignIn\", request: desktopRequestOf(url) }\n const make = /^\\/make\\/([a-z][a-z0-9_-]*)\\/?$/.exec(url.pathname)\n if (make !== null) return { _tag: \"Make\", module: make[1]! }\n for (const [view, { route }] of kernelViews) {\n if (url.pathname === route) return { _tag: \"View\", view, path: route, record: Option.none() }\n if (url.pathname.startsWith(`${route}/`) && url.pathname.length > route.length + 1)\n return {\n _tag: \"View\",\n view,\n path: route,\n record: Option.some(decodeURIComponent(url.pathname.slice(route.length + 1))),\n }\n }\n try {\n const match = registry.resolve(url.pathname)\n if (!metas.has(match.view.id)) return { _tag: \"NotFound\", path: url.pathname }\n return { _tag: \"View\", view: match.view.id, path: match.view.route, record: Option.fromNullishOr(match.record) }\n } catch {\n return { _tag: \"NotFound\", path: url.pathname }\n }\n }\n\n // -- Commands ---------------------------------------------------------------------------------------------\n\n const NavigateInternal = Command.define(\"NavigateInternal\", {\n args: { url: Schema.String, path: Schema.String },\n messages: [Message.CompletedNavigateInternal],\n execute: ({ url, path }) =>\n Effect.sync(() => markNavigationStart(path)).pipe(\n Effect.andThen(pushUrl(url)),\n Effect.as(Message.CompletedNavigateInternal()),\n ),\n })\n\n /** Put the legacy path's new place in the address bar (replacing it: Back does not return to the old path). */\n const ReplaceLegacyUrl = Command.define(\"ReplaceLegacyUrl\", {\n args: { url: Schema.String },\n messages: [Message.CompletedNavigateInternal],\n execute: ({ url }) => replaceUrl(url).pipe(Effect.as(Message.CompletedNavigateInternal())),\n })\n\n const LoadExternal = Command.define(\"LoadExternal\", {\n args: { href: Schema.String },\n messages: [Message.CompletedLoadExternal],\n execute: ({ href }) => load(href).pipe(Effect.as(Message.CompletedLoadExternal())),\n })\n\n /** MAKE modules' views (`make.ts`): their requests act with the session's token, read only when they run. */\n const makeScreen = Make.makeMakeScreen({\n kernelUrl: config.kernelUrl,\n clientVersion: config.clientVersion,\n token: (session) => credentials.token(session),\n })\n\n // -- The client core --------------------------------------------------------------------------------------\n //\n // One runtime for the shell's life: the session (stored in the browser, its sign-out durable), the organisation and\n // its generation, the replica (IndexedDB), live queries, optimistic writes and teardown. The shell shows what it\n // announces and asks it to act; it never opens a replica, keeps a token in its state or revokes a session itself.\n\n const toMillis = (input: Duration.Input | undefined): number | undefined =>\n input === undefined ? undefined : Duration.toMillis(Duration.fromInputUnsafe(input))\n const runtime = makeClientRuntime({\n kernelUrl: config.kernelUrl,\n zeroUrl: config.syncUrl,\n schema: config.schema,\n queries: config.queries,\n mutators: config.mutators as object,\n modules: config.contracts,\n sessionStore: webStorage.session,\n revocations: webStorage.revocations,\n revocationTimeoutMs: toMillis(config.revocationTimeout),\n revocationRetryMs: toMillis(config.revocationRetry),\n storage: config.storage ?? \"idb\",\n clientVersion: config.clientVersion,\n initialOrg: (context) => initialOrg(context),\n })\n\n /**\n * The organisation a session starts in: the one the address names (`?org=`, as a record link carries it) when the\n * person belongs to it (remembered as their choice), else the one they had selected (the same person's session\n * adopted again), else the one they chose last (remembered across reloads), else their first.\n */\n const initialOrg = ({ user, organizations, previous }: InitialOrgContext): string | null => {\n const member = (orgId: string | null | undefined): orgId is string =>\n typeof orgId === \"string\" && organizations.some((o) => o.orgId === orgId)\n const linked = linkedOrgOfLocation()\n if (member(linked)) {\n storage.set(orgKey(user.id), linked)\n return linked\n }\n return [previous, storage.get(orgKey(user.id)), ...organizations.map((o) => o.orgId)].find(member) ?? null\n }\n\n /** The session's handle in the shell's credentials: a new one for each token the core holds. */\n const sessionHandle = runtimeSessionHandle(runtime, credentials)\n\n /** The core's session as the Model holds it (its token named by a handle). */\n const sessionView = (session: LocalClientSessionState): SessionView => {\n const handle = sessionHandle()\n if (session.state === \"signedIn\" && handle !== undefined) return signedInView(session, handle)\n return session.state === \"signingOut\" ? { _tag: \"SigningOut\" } : checkView()\n }\n /** A signed-in session as the Model holds it. */\n const signedInView = (\n session: Extract<LocalClientSessionState, { readonly state: \"signedIn\" }>,\n handle: string,\n ): SessionView => {\n const organisations = runtime.organizationsStatus()\n return {\n _tag: \"SignedIn\",\n session: { handle, user: { id: session.user.id, email: session.user.email, name: session.user.name } },\n memberships: session.organizations.map((o) => ({ orgId: o.orgId, name: o.name, roles: [...o.roles] })),\n orgId: Option.fromNullishOr(session.orgId),\n generation: session.generation,\n ...(organisations.status === \"unavailable\" ? { organisationsProblem: organisations.reason } : {}),\n // `in`: contracts 0.1.0 (in the item's range) have no `offline` on a signed-in session; absent means online.\n ...(\"offline\" in session && session.offline ? { offline: true } : {}),\n }\n }\n /** Nobody signed in, as the session check stands: being checked, the kernel unreachable, or signed out. */\n const checkView = (): SessionView => {\n const check = runtime.sessionStatus()\n if (check.status === \"loading\") return { _tag: \"Restoring\", problem: Option.none() }\n return check.status === \"unavailable\"\n ? { _tag: \"Restoring\", problem: Option.some(check.reason ?? \"\") }\n : { _tag: \"SignedOut\" }\n }\n\n /** The core's events the Model hears (rows and writes go to the screens' own queries and Commands). */\n const runtimeMessage = (event: RuntimeEvent): Message | undefined => {\n switch (event.type) {\n case \"session\":\n return Message.GotSession({ state: sessionView(event.session) })\n case \"context\":\n return Message.ChangedContext({ generation: event.generation, reason: event.reason })\n case \"connection\":\n return Message.ChangedConnection({ connection: { generation: runtime.generation(), state: event.state } })\n default:\n return undefined\n }\n }\n\n /** Checks the stored session (and retries pending revocations): what it finds arrives as the core's events. */\n const StartSession = Command.define(\"StartSession\", {\n args: {},\n messages: [Message.CompletedRuntime],\n execute: () =>\n Effect.promise(() => runtime.start().catch(() => undefined)).pipe(Effect.as(Message.CompletedRuntime())),\n })\n\n /**\n * Signs in with the email the Model holds and the password read from its field (never held anywhere else): the\n * core adopts the session (stored for the next start, its organisations listed) and announces it. Refused while a\n * sign-out's revocation exists only in memory (the core's `UnsavedSignOut`, said as it is).\n */\n const SignIn = Command.define(\"SignIn\", {\n args: { email: Schema.String },\n messages: [Message.CompletedRuntime, Message.FailedSignIn],\n execute: ({ email }) =>\n (config.readPassword ?? passwordField).pipe(\n Effect.flatMap((password) => Effect.tryPromise(() => runtime.signInWithPassword({ email, password }))),\n Effect.as(Message.CompletedRuntime()),\n Effect.catch((error) => Effect.succeed(Message.FailedSignIn({ message: errorText(error) }))),\n ),\n })\n\n /** Signs out through the core: its revocation kept first, the signed-out state announced after, retried until confirmed. */\n const SignOut = Command.define(\"SignOut\", {\n args: {},\n messages: [Message.CompletedRuntime],\n execute: () =>\n Effect.promise(() => runtime.signOut().catch(() => undefined)).pipe(Effect.as(Message.CompletedRuntime())),\n })\n\n /** Selects the organisation in the core (a new generation, announced); refused, the Model hears the core's again. */\n const SelectOrganisation = Command.define(\"SelectOrganisation\", {\n args: { orgId: Schema.String },\n messages: [Message.CompletedRuntime, Message.GotSession],\n execute: ({ orgId }) =>\n Effect.tryPromise(() => runtime.selectOrg(orgId)).pipe(\n Effect.as(Message.CompletedRuntime()),\n Effect.catch(() => Effect.sync(() => Message.GotSession({ state: sessionView(runtime.session()) }))),\n ),\n })\n\n const StoreOrganisation = Command.define(\"StoreOrganisation\", {\n args: { userId: Schema.String, orgId: Schema.String },\n messages: [Message.CompletedStore],\n execute: ({ userId, orgId }) =>\n Effect.sync(() => {\n storage.set(orgKey(userId), orgId)\n return Message.CompletedStore()\n }),\n })\n\n const StoreLocale = Command.define(\"StoreLocale\", {\n args: { locale: Schema.String },\n messages: [Message.CompletedStore],\n execute: ({ locale }) =>\n Effect.sync(() => {\n storage.set(LOCALE_KEY, locale)\n return Message.CompletedStore()\n }),\n })\n\n /** The members of the organisation, as the session (its token read only now), for the settings frame. */\n const LoadMembers = Command.define(\"LoadMembers\", {\n args: { request: Schema.Number, session: Schema.String, orgId: Schema.String },\n messages: [Message.GotMembers, Message.FailedMembers],\n execute: ({ request, session, orgId }) =>\n Effect.suspend(() => {\n const token = credentials.token(session)\n if (token === undefined) return Effect.succeed(Message.FailedMembers({ request, orgId, message: \"Signed out\" }))\n return Effect.tryPromise(() => listMembers(config.kernelUrl, token, orgId)).pipe(\n Effect.map((members) => Message.GotMembers({ request, orgId, members: members.map((m) => ({ ...m })) })),\n Effect.catch((error) => Effect.succeed(Message.FailedMembers({ request, orgId, message: errorText(error) }))),\n )\n }),\n })\n\n const StoreAppearance = Command.define(\"StoreAppearance\", {\n args: { scheme: Scheme, direction: Direction },\n messages: [Message.CompletedStore],\n execute: ({ scheme, direction }) =>\n Effect.sync(() => {\n storage.set(APPEARANCE_KEY, JSON.stringify({ scheme, direction }))\n return Message.CompletedStore()\n }),\n })\n\n const StorePreset = Command.define(\"StorePreset\", {\n args: { preset: Preset },\n messages: [Message.CompletedStore],\n execute: ({ preset }) =>\n Effect.sync(() => {\n storage.set(PRESET_KEY, preset === \"standard\" ? undefined : preset)\n return Message.CompletedStore()\n }),\n })\n\n // The visitor's consent (one controller for the shell's life), and the scripts that follow it.\n const consent =\n config.consent === undefined\n ? undefined\n : consentController({ baseUrl: config.kernelUrl, region: config.consent.region })\n for (const script of config.consent?.scripts ?? []) void consent?.register(script)\n\n const LoadConsent = Command.define(\"LoadConsent\", {\n args: {},\n messages: [Message.GotConsent],\n execute: () =>\n Effect.tryPromise(() => consent!.load()).pipe(\n Effect.map((state) => Message.GotConsent({ undecided: consentUndecided(state.consent) })),\n // A kernel that cannot answer leaves the prompt down: nothing optional loads before a choice anyway.\n Effect.catch(() => Effect.succeed(Message.GotConsent({ undecided: false }))),\n ),\n })\n\n const SaveConsent = Command.define(\"SaveConsent\", {\n args: { accept: Schema.Boolean },\n messages: [Message.GotConsent],\n execute: ({ accept }) =>\n Effect.tryPromise(() => consent!.choose({ functional: accept, analytics: accept, marketing: accept })).pipe(\n Effect.map((state) => Message.GotConsent({ undecided: consentUndecided(state.consent) })),\n Effect.catch(() => Effect.succeed(Message.GotConsent({ undecided: true }))),\n ),\n })\n\n /** At sign-in, the visit becomes the person's: their choices where they made none (a claim refused changes none). */\n const ClaimConsent = Command.define(\"ClaimConsent\", {\n args: { session: Schema.String },\n messages: [Message.CompletedStore],\n execute: ({ session }) =>\n Effect.tryPromise(async () => {\n const token = credentials.token(session)\n if (token !== undefined) await consent!.claim(token)\n }).pipe(Effect.ignore, Effect.as(Message.CompletedStore())),\n })\n\n /**\n * The person's name, saved (Better Auth's `update-user`, as the session), and kept in the stored session so the next\n * start shows it; or an email change asked for (the new address is verified before it changes, `changeEmail`).\n */\n const SaveProfile = Command.define(\"SaveProfile\", {\n args: { request: Schema.Number, session: Schema.String, field: ProfileField, value: Schema.String },\n messages: [Message.SavedProfile, Message.FailedProfile],\n execute: ({ request, session, field, value }) =>\n Effect.tryPromise(async () => {\n const token = credentials.token(session)\n if (token === undefined) throw new Error(\"Not signed in\")\n if (field === \"name\") await updateProfile(config.kernelUrl, token, { name: value })\n else await changeEmail(config.kernelUrl, token, { newEmail: value })\n if (field === \"name\" && storedSessionToken() === token) {\n const stored = Schema.decodeUnknownOption(Schema.fromJsonString(StoredSession))(\n storage.get(SESSION_KEY) ?? \"\",\n )\n if (Option.isSome(stored))\n storage.set(SESSION_KEY, JSON.stringify({ ...stored.value, user: { ...stored.value.user, name: value } }))\n }\n return Message.SavedProfile({ request, session, field, value })\n }).pipe(\n Effect.catch((error) =>\n Effect.succeed(Message.FailedProfile({ request, session, field, message: errorText(error) })),\n ),\n ),\n })\n\n /**\n * Approves a desktop sign-in as the session (its token, read only when this runs): the kernel answers the app's\n * redirect with a one-time code. The kernel's cookie guard is not involved: the call carries the session as a\n * bearer token, never a cookie.\n */\n const ApproveDesktop = Command.define(\"ApproveDesktop\", {\n args: { request: Schema.Number, session: Schema.String, desktop: DesktopRequest },\n messages: [Message.ApprovedDesktop, Message.FailedApproveDesktop],\n execute: ({ request, session, desktop }) =>\n Effect.suspend(() => {\n const token = credentials.token(session)\n if (token === undefined) return Effect.succeed(Message.FailedApproveDesktop({ request, message: \"Signed out\" }))\n return Effect.tryPromise({\n try: () => approveDesktopSignIn(config.kernelUrl, token, desktop),\n catch: (error) => error,\n }).pipe(\n Effect.map(({ redirect }) => Message.ApprovedDesktop({ request, redirect })),\n Effect.catch((error) => Effect.succeed(Message.FailedApproveDesktop({ request, message: errorText(error) }))),\n )\n }),\n })\n\n /** Focus an element once the render that holds it is committed (Foldkit's `Dom.focus`). */\n const FocusElement = Command.define(\"FocusElement\", {\n args: { selector: Schema.String },\n messages: [Message.CompletedFocus],\n execute: ({ selector }) =>\n Dom.focus(selector).pipe(\n Effect.catch(() => Effect.void),\n Effect.as(Message.CompletedFocus()),\n ),\n })\n\n // -- Screens ----------------------------------------------------------------------------------------------\n\n /**\n * Loads a screen's chunk and holds the screen (outside the Model, as its code is): `LoadedScreen` once it is held,\n * `FailedScreen` when the chunk could not be loaded or is not the screen its declaration said.\n */\n const LoadScreen = Command.define(\"LoadScreen\", {\n args: { view: Schema.String },\n messages: [Message.LoadedScreen, Message.FailedScreen],\n execute: ({ view }) =>\n // A chunk whose module has no `screen` export answers undefined.\n Effect.tryPromise((): Promise<AnyScreen | undefined> => loaders.get(view)!()).pipe(\n Effect.flatMap((screen) => {\n if (screen?.view !== view)\n return Effect.fail(new Error(`The screen loaded for ${view} renders ${String(screen?.view)}`))\n // The shell routed, linked and filled slots by the fields its build read: the screen must declare the same.\n const differs = SCREEN_META_FIELDS.find(\n (field) => JSON.stringify(metas.get(view)?.[field]) !== JSON.stringify(screen[field]),\n )\n if (differs !== undefined)\n return Effect.fail(\n new Error(`The screen loaded for ${view} declares another ${differs} than its build read`),\n )\n return Effect.sync(() => {\n screens.set(view, screen)\n return Message.LoadedScreen({ view })\n })\n }),\n Effect.catch((error) => Effect.succeed(Message.FailedScreen({ view, message: errorText(error) }))),\n ),\n })\n\n /** Reloads the page (the way back from a part of the app that could not be loaded, a newer release's included). */\n const ReloadPage = Command.define(\"ReloadPage\", {\n args: {},\n messages: [Message.CompletedLoadExternal],\n execute: () =>\n Effect.sync(() => {\n globalThis.location.reload()\n return Message.CompletedLoadExternal()\n }),\n })\n\n /** The views a route's screen needs: its own and the views contributed to the slots it shows (its panels). */\n const neededViews = (view: string): ReadonlyArray<string> => [\n view,\n ...(metas.get(view)?.slots ?? []).flatMap((slotId) => (slots.get(slotId)?.panels ?? []).map((p) => p.view)),\n ]\n\n /** Whether a view's screen is held: loaded with the shell, or loaded since (as the Model says). */\n const isLoaded = (model: Model, view: string): boolean =>\n !loaders.has(view) || (model.loads[view]?._tag === \"Loaded\" && screens.has(view))\n\n /** The first of `views` that could not be loaded, with why. */\n const failedLoad = (model: Model, views: ReadonlyArray<string>): { view: string; message: string } | undefined => {\n for (const view of views) {\n const load = model.loads[view]\n if (load?._tag === \"Failed\") return { view, message: load.message }\n }\n return undefined\n }\n\n /** Starts loading those of `views` not asked for yet; a load that failed stays failed until the page reloads. */\n const withLoads = (model: Model, views: ReadonlyArray<string>): UpdateReturn => {\n const wanted = [...new Set(views)].filter((view) => loaders.has(view) && model.loads[view] === undefined)\n if (wanted.length === 0) return { model }\n return {\n model: {\n ...model,\n loads: { ...model.loads, ...Object.fromEntries(wanted.map((view) => [view, { _tag: \"Loading\" as const }])) },\n },\n commands: wanted.map((view) => LoadScreen({ view })),\n }\n }\n\n const liftScreenCommands = (\n view: string,\n instance: number,\n commands: Update.Return<unknown, unknown, ReplicaService>[\"commands\"],\n ): ReadonlyArray<Command.Command<Message, never, ReplicaService>> =>\n (commands ?? []).map((command) =>\n Command.mapMessage(command, (message: unknown) => Message.GotScreenMessage({ view, instance, message })),\n )\n\n const liftPanelCommands = (\n view: string,\n instance: number,\n commands: Update.Return<unknown, unknown, ReplicaService>[\"commands\"],\n ): ReadonlyArray<Command.Command<Message, never, ReplicaService>> =>\n (commands ?? []).map((command) =>\n Command.mapMessage(command, (message: unknown) => Message.GotPanelMessage({ view, instance, message })),\n )\n\n const liftMakeCommands = (\n instance: number,\n commands: Update.Return<unknown, unknown>[\"commands\"],\n ): ReadonlyArray<Command.Command<Message>> =>\n (commands ?? []).map((command) =>\n Command.mapMessage(command, (message: unknown) =>\n Message.GotMakeMessage({ instance: Option.some(instance), message: message as Make.Message }),\n ),\n )\n\n /**\n * The MAKE screen the Model should show: the route's, for the signed-in session and the selected organisation,\n * created afresh when any of them changes (the previous one, and its frame, are discarded); none elsewhere.\n */\n const withMake = (result: UpdateReturn): UpdateReturn => {\n const model = result.model\n const wanted =\n model.route._tag === \"Make\" && model.auth._tag === \"SignedIn\" && Option.isSome(model.auth.orgId)\n ? { module: model.route.module, session: model.auth.session.handle, orgId: model.auth.orgId.value }\n : undefined\n if (wanted === undefined)\n return Option.isNone(model.make) ? result : { ...result, model: { ...model, make: Option.none() } }\n const current = Option.getOrUndefined(model.make)?.model\n if (current?.module === wanted.module && current.session === wanted.session && current.orgId === wanted.orgId)\n return result\n const instance = model.screens + 1\n const created = makeScreen.init(wanted.module, wanted.session, wanted.orgId)\n return {\n model: { ...model, screens: instance, make: Option.some({ instance, model: created.model }) },\n commands: [...(result.commands ?? []), ...liftMakeCommands(instance, created.commands)],\n }\n }\n\n /**\n * The settings frame's members: loaded for the organisation selected when the settings are shown and they are not\n * already that organisation's (another organisation's are dropped in the same update, never shown under it).\n */\n const withSettings = (result: UpdateReturn): UpdateReturn => {\n const model = result.model\n if (model.route._tag !== \"Settings\" || model.auth._tag !== \"SignedIn\" || Option.isNone(model.auth.orgId))\n return model.members._tag === \"NotLoaded\"\n ? result\n : { ...result, model: { ...model, members: { _tag: \"NotLoaded\" } } }\n const orgId = model.auth.orgId.value\n if (model.members._tag !== \"NotLoaded\" && model.members.orgId === orgId) return result\n const request = model.requests + 1\n return {\n model: { ...model, requests: request, members: { _tag: \"Loading\", orgId, request } },\n commands: [...(result.commands ?? []), LoadMembers({ request, session: model.auth.session.handle, orgId })],\n }\n }\n\n /** What the route shows besides a view's screen: its MAKE screen and the settings' members. */\n const withRoute = (result: UpdateReturn): UpdateReturn => withSettings(withMake(result))\n\n /** The screens the Model should show: the route's view screen, its MAKE screen and the settings' members. */\n const withScreen = (model: Model): UpdateReturn => withRoute(withViewScreen(model))\n\n /**\n * The screen the Model should show: the route's, created for the open replica when there is none for it yet;\n * none while signed out, while the replica opens, or on a route without a screen.\n */\n const withViewScreen = (before: Model): UpdateReturn => {\n const noScreen = (model: Model, commands: UpdateReturn[\"commands\"] = []): UpdateReturn => ({\n model: Option.isNone(model.screen) ? model : { ...model, screen: Option.none() },\n commands,\n })\n if (before.route._tag !== \"View\" || before.auth._tag !== \"SignedIn\") return noScreen(before)\n // The screens the route needs load while the replica opens; until both are there, no screen is shown.\n const needed = neededViews(before.route.view)\n const loading = withLoads(before, needed)\n const model = loading.model\n const replica = openReplica(model.replica)\n if (Option.isNone(replica) || !needed.every((view) => isLoaded(model, view)))\n return noScreen(model, loading.commands)\n const route = before.route\n const auth = before.auth\n const current = model.screen\n // A screen is its view's for one record and one replica: another record (`/hello/a` to `/hello/b`) or another\n // replica gets a new one, never the previous record's Model.\n if (\n Option.isSome(current) &&\n current.value.view === route.view &&\n Option.makeEquivalence((a: string, b: string) => a === b)(current.value.record, route.record) &&\n sameReplica(current.value.replica, replica.value)\n ) {\n return { model }\n }\n const screen = screens.get(route.view)!\n const instance = model.screens + 1\n const context = {\n replica: replica.value,\n session: auth.session.handle,\n kernelUrl: config.kernelUrl,\n clientVersion: Option.fromNullishOr(config.clientVersion),\n nav: nav.map(({ view, label, path }) => ({ view, label, path })),\n }\n const created = screen.init({ ...context, record: route.record })\n // The views contributed to the slots it shows, created with it for the same replica (each its own instance).\n let next = instance\n const panels: Array<Panel> = []\n const panelCommands: Array<Command.Command<Message, never, ReplicaService>> = []\n for (const slotId of screen.slots ?? []) {\n for (const contributed of slots.get(slotId)?.panels ?? []) {\n next += 1\n const panel = screens.get(contributed.view)!.init({ ...context, record: Option.none() })\n panels.push({ ...contributed, instance: next, model: panel.model })\n panelCommands.push(...liftPanelCommands(contributed.view, next, panel.commands))\n }\n }\n return {\n model: {\n ...model,\n screens: next,\n screen: Option.some({\n view: route.view,\n record: route.record,\n replica: replica.value,\n instance,\n model: created.model,\n panels,\n }),\n },\n commands: [...liftScreenCommands(route.view, instance, created.commands), ...panelCommands],\n }\n }\n\n /**\n * Nothing of a generation stays: no replica, no connection, no screen (its rows are the replica's). A MAKE screen and\n * the members are the session's and the organisation's, not the replica's: `withRoute` keeps them while those hold.\n */\n const withoutReplica = (model: Model): Model => ({\n ...model,\n replica: ReplicaClosed,\n connection: Option.none(),\n screen: Option.none(),\n })\n\n /** Nothing of a context stays: no replica, no connection, no screen, no MAKE screen, no members. */\n const withoutContext = (model: Model): Model => ({\n ...withoutReplica(model),\n make: Option.none(),\n members: { _tag: \"NotLoaded\" },\n })\n\n /** Nothing of the person stays either: no profile drafts, nor a change's outcome, nor a desktop approval in flight. */\n const withoutPerson = (model: Model): Model => ({\n ...withoutContext(model),\n profile: { name: Option.none(), email: Option.none(), saving: Option.none(), outcome: Option.none() },\n desktop: { _tag: \"Idle\" },\n })\n\n const signedOut = (model: Model, form: Partial<SignInForm> = {}): Model => ({\n ...withoutPerson(model),\n auth: {\n _tag: \"SignedOut\",\n form: { email: \"alice@example.com\", submitting: false, error: Option.none(), ...form },\n },\n })\n\n // -- Init -------------------------------------------------------------------------------------------------\n\n const init = (flags: Flags, url: Url): UpdateReturn => {\n const base: Model = signedOut({\n route: routeOf(url),\n backend: \"checking\",\n consent: consent === undefined ? \"off\" : \"checking\",\n linkedOrg: orgOfUrl(url),\n auth: { _tag: \"SignedOut\", form: { email: \"\", submitting: false, error: Option.none() } },\n revocation: flags.pendingRevocations ? \"pending\" : \"none\",\n replica: ReplicaClosed,\n connection: Option.none(),\n screen: Option.none(),\n make: Option.none(),\n screens: 0,\n loads: {},\n requests: 0,\n appearance: { ...flags.appearance, systemDark: flags.systemDark, preset: flags.preset ?? \"standard\" },\n appearanceDialog: Dialog.init({ id: \"appearance\" }),\n locale: flags.locale,\n members: { _tag: \"NotLoaded\" },\n profile: { name: Option.none(), email: Option.none(), saving: Option.none(), outcome: Option.none() },\n desktop: { _tag: \"Idle\" },\n })\n const legacyUrl = legacyTarget(url)\n return {\n model: starting(base, flags),\n commands: [\n ...(legacyUrl === undefined ? [] : [ReplaceLegacyUrl({ url: legacyUrl })]),\n ...(consent === undefined ? [] : [LoadConsent({})]),\n StartSession({}),\n ],\n }\n }\n\n /** A stored session is the core's to check: nothing of it shows (nor the form) until it has. */\n const starting = (base: Model, flags: Flags): Model =>\n flags.storedSession ? { ...base, auth: { _tag: \"Restoring\", problem: Option.none() } } : base\n\n /** Why the announced session's organisations could not be listed, if they could not. */\n const problemOf = (state: SignedInView): Option.Option<string> => Option.fromNullishOr(state.organisationsProblem)\n\n /** The Model's session when it is the one announced (the same handle). */\n const sameSession = (model: Model, state: SignedInView): SignedIn | undefined =>\n model.auth._tag === \"SignedIn\" && model.auth.session.handle === state.session.handle ? model.auth : undefined\n\n /**\n * An announcement of the session the Model holds that needs no new context: the same organisation and generation\n * (only the memberships may change), or a generation older than the one it acts in (a late answer, ignored).\n */\n const continuing = (model: Model, same: SignedIn, state: SignedInView): UpdateReturn | undefined => {\n if (Option.contains(same.generation, state.generation) && sameOrg(same.orgId, state.orgId))\n return {\n model: {\n ...model,\n auth: {\n ...same,\n memberships: state.memberships,\n organisationsProblem: problemOf(state),\n offline: state.offline === true,\n },\n },\n }\n return Option.exists(same.generation, (current) => state.generation < current) ? { model } : undefined\n }\n\n /**\n * The core announced a session: its organisation and generation. A new context (another session, organisation or\n * generation) discards the shown screen and marks the replica as opening for it in the same update; the screen is\n * created again once the replica of that generation is taken (`OpenedReplica`). The same context changes nothing\n * but the memberships. While the core checks a session the sync server refused, no replica is asked for.\n */\n const signedInAs = (model: Model, state: SignedInView): UpdateReturn => {\n const same = sameSession(model, state)\n const unchanged = same === undefined ? undefined : continuing(model, same, state)\n if (unchanged !== undefined) return unchanged\n return claimed(model, withScreen(inContext(model, state, same)), state.session.handle)\n }\n\n /** The Model in the context announced; the same session keeps what the person changed since (their name). */\n const inContext = (model: Model, state: SignedInView, same: SignedIn | undefined): Model => {\n const kept = same === undefined ? { session: state.session, checking: false } : same\n return {\n ...withoutReplica(model),\n auth: {\n _tag: \"SignedIn\",\n session: kept.session,\n memberships: state.memberships,\n orgId: state.orgId,\n generation: Option.some(state.generation),\n checking: kept.checking,\n organisationsProblem: problemOf(state),\n offline: state.offline === true,\n },\n replica: kept.checking\n ? ReplicaClosed\n : Option.match(state.orgId, { onNone: () => ReplicaClosed, onSome: ReplicaOpening }),\n }\n }\n\n /** A sign-in from the form: the visit's consent becomes the person's (a session restored at start claims nothing). */\n const claimed = (before: Model, shown: UpdateReturn, session: string): UpdateReturn =>\n before.auth._tag === \"SignedOut\" && consent !== undefined\n ? { ...shown, commands: [...(shown.commands ?? []), ClaimConsent({ session })] }\n : shown\n\n /** The person signed out, as the Model was: ended without a sign-out (with the reason), signed out, or restoring. */\n const signedOutFrom: {\n readonly [Tag in Auth[\"_tag\"]]: (model: Model, auth: Extract<Auth, { readonly _tag: Tag }>) => UpdateReturn\n } = {\n // Ended without a sign-out (the kernel refuses it): signed out at once, with the reason.\n SignedIn: (model, auth) => ({\n model: signedOut(model, {\n email: auth.session.user.email,\n error: Option.some(\"Your session has ended. Sign in again.\"),\n }),\n }),\n SigningOut: (model, auth) => ({ model: signedOut(model, { email: auth.email }) }),\n Restoring: (model) => ({ model: signedOut(model) }),\n SignedOut: (model) => ({ model }),\n }\n\n /** The core's session announcement, as the Model shows it. */\n const sessionShown: {\n readonly [Tag in SessionView[\"_tag\"]]: (\n model: Model,\n state: Extract<SessionView, { readonly _tag: Tag }>,\n ) => UpdateReturn\n } = {\n SignedIn: signedInAs,\n // Its revocation is being kept: nothing of the session shows, and the sign-in form only once it is kept.\n SigningOut: (model) =>\n model.auth._tag === \"SignedIn\"\n ? { model: { ...withoutPerson(model), auth: { _tag: \"SigningOut\", email: model.auth.session.user.email } } }\n : { model },\n SignedOut: (model) =>\n (signedOutFrom[model.auth._tag] as (model: Model, auth: Auth) => UpdateReturn)(model, model.auth),\n // The kernel could not be reached to check the session: nothing of it shows, and the core checks again.\n Restoring: (model, state) =>\n Option.isSome(state.problem) && model.auth._tag !== \"SignedOut\"\n ? { model: { ...withoutPerson(model), auth: { _tag: \"Restoring\", problem: state.problem } } }\n : { model },\n }\n const gotSession = (model: Model, state: SessionView): UpdateReturn =>\n (sessionShown[state._tag] as (model: Model, state: SessionView) => UpdateReturn)(model, state)\n\n /** Whether the replica taken (`OpenedReplica`) is the one of the generation the Model acts in. */\n const actsIn = (auth: SignedIn, key: ReplicaKey): boolean =>\n auth.session.user.id === key.userId &&\n Option.contains(auth.orgId, key.orgId) &&\n Option.contains(auth.generation, key.opening)\n\n /** A connection the core reports for the generation the Model acts in; reopened after a check, the replica asked for. */\n const connected = (model: Model, auth: SignedIn, connection: Connection): UpdateReturn =>\n auth.checking && Option.isSome(auth.orgId)\n ? {\n model: {\n ...model,\n auth: { ...auth, checking: false },\n replica: ReplicaOpening(auth.orgId.value),\n connection: Option.some(connection),\n },\n }\n : { model: { ...model, connection: Option.some(connection) } }\n\n // -- Update -----------------------------------------------------------------------------------------------\n\n const foldDialog = Update.foldChild({\n update: Dialog.update,\n read: (model: Model) => Option.some(model.appearanceDialog),\n write: (model: Model, appearanceDialog: Dialog.Model): Model => ({ ...model, appearanceDialog }),\n toParentMessage: (message: Dialog.Message) => Message.GotAppearanceDialogMessage({ message }),\n foldOutMessage: Dialog.OutMessage.match<Update.Step<Model, Message>>({\n Opened: () => (model) => ({ model }),\n Closed: () => (model) => ({ model }),\n }),\n })\n const openDialog = Update.foldChildStep({\n update: Dialog.open,\n read: (model: Model) => Option.some(model.appearanceDialog),\n write: (model: Model, appearanceDialog: Dialog.Model): Model => ({ ...model, appearanceDialog }),\n toParentMessage: (message: Dialog.Message) => Message.GotAppearanceDialogMessage({ message }),\n foldOutMessage: Dialog.OutMessage.match<Update.Step<Model, Message>>({\n Opened: () => (model) => ({ model }),\n Closed: () => (model) => ({ model }),\n }),\n })\n\n const update = (model: Model, message: Message): UpdateReturn =>\n Message.match<UpdateReturn>(message, {\n ClickedLink: ({ request }) =>\n UrlRequest.match<UpdateReturn>(request, {\n Internal: ({ url }) => ({\n model,\n commands: [NavigateInternal({ url: urlToString(url), path: url.pathname })],\n }),\n External: ({ href }) => ({ model, commands: [LoadExternal({ href })] }),\n }),\n ChangedUrl: ({ url }) => {\n const linkedOrg = orgOfUrl(url)\n // Another address forgets a desktop approval's outcome (an answer still in flight is then dropped).\n const routed: Model = { ...model, route: routeOf(url), linkedOrg, desktop: { _tag: \"Idle\" } }\n // A link into another organisation the person belongs to switches to it before the record opens (in the\n // organisation it was made in, not whichever this browser had chosen); any other organisation is ignored.\n const switching =\n routed.auth._tag === \"SignedIn\" &&\n Option.isSome(linkedOrg) &&\n !Option.contains(routed.auth.orgId, linkedOrg.value) &&\n routed.auth.memberships.some((m) => m.orgId === linkedOrg.value)\n const shown = switching\n ? update(routed, Message.SelectedOrganisation({ orgId: Option.getOrThrow(linkedOrg) }))\n : withScreen(routed)\n const target = legacyTarget(url)\n return target === undefined\n ? shown\n : { ...shown, commands: [...(shown.commands ?? []), ReplaceLegacyUrl({ url: target })] }\n },\n CompletedNavigateInternal: () => ({ model }),\n CompletedLoadExternal: () => ({ model }),\n\n ChangedEmail: ({ value }) =>\n model.auth._tag === \"SignedOut\"\n ? { model: { ...model, auth: { ...model.auth, form: { ...model.auth.form, email: value } } } }\n : { model },\n SubmittedSignIn: () => {\n if (model.auth._tag !== \"SignedOut\" || model.auth.form.submitting) return { model }\n const form = model.auth.form\n return {\n model: { ...model, auth: { ...model.auth, form: { ...form, submitting: true, error: Option.none() } } },\n commands: [SignIn({ email: form.email })],\n }\n },\n FailedSignIn: ({ message }) =>\n model.auth._tag === \"SignedOut\"\n ? {\n model: {\n ...model,\n auth: {\n ...model.auth,\n form: { ...model.auth.form, submitting: false, error: Option.some(message) },\n },\n },\n }\n : { model },\n\n SelectedOrganisation: ({ orgId }) => {\n if (model.auth._tag !== \"SignedIn\") return { model }\n if (!model.auth.memberships.some((m) => m.orgId === orgId)) return { model }\n if (Option.contains(model.auth.orgId, orgId)) return { model }\n // One transition: the new organisation, its replica opening, and no screen (so none of the old rows); its\n // generation is the core's to announce, and until then nothing acts in any. A MAKE screen is opened afresh.\n return withRoute({\n model: {\n ...withoutContext(model),\n auth: { ...model.auth, orgId: Option.some(orgId), generation: Option.none(), checking: false },\n replica: ReplicaOpening(orgId),\n },\n commands: [StoreOrganisation({ userId: model.auth.session.user.id, orgId }), SelectOrganisation({ orgId })],\n })\n },\n\n ClickedSignOut: () =>\n // The core keeps the revocation first; only then does it announce the person signed out (backlog 46).\n model.auth._tag === \"SignedIn\" ? { model, commands: [SignOut({})] } : { model },\n\n GotSession: ({ state }) => gotSession(model, state),\n ChangedContext: ({ generation, reason }) => {\n if (model.auth._tag !== \"SignedIn\") return { model }\n // A reset whose generation the Model already acts in (announced first) has nothing more to discard.\n if (reason !== \"needsAuth\" && Option.exists(model.auth.generation, (current) => current >= generation))\n return { model }\n // Every view of the old context is gone in the core already; until it announces the next one, nothing acts in\n // any. The sync server refused the session (`needsAuth`): no replica is asked for until the core reopens it.\n return {\n model: {\n ...withoutReplica(model),\n auth: { ...model.auth, generation: Option.none(), checking: reason === \"needsAuth\" },\n },\n }\n },\n // The kernel still accepts a session the sync server refused when the core reports its reopened replica's connection.\n ChangedConnection: ({ connection }) =>\n model.auth._tag === \"SignedIn\" && Option.contains(model.auth.generation, connection.generation)\n ? connected(model, model.auth, connection)\n : { model },\n // Confirmed only as the kernel confirmed it (the core's word); anything unanswered stays pending, and is retried.\n ChangedRevocation: ({ revocation }) => ({ model: { ...model, revocation } }),\n CompletedRuntime: () => ({ model }),\n\n // Only the generation the Model acts in counts: one taken for an organisation or generation since left is ignored.\n OpenedReplica: ({ key }) =>\n model.auth._tag === \"SignedIn\" && actsIn(model.auth, key)\n ? withScreen({ ...model, replica: { _tag: \"Open\", key } })\n : { model },\n ClosedReplica: () =>\n // A close reported after the next replica opened concerns the previous one.\n model.replica._tag === \"Open\" ? { model } : { model: { ...model, connection: Option.none() } },\n FailedReplica: ({ orgId, message }) =>\n model.auth._tag === \"SignedIn\" && Option.contains(model.auth.orgId, orgId)\n ? { model: { ...model, replica: { _tag: \"Failed\", orgId, message }, screen: Option.none() } }\n : { model },\n\n GotScreenMessage: ({ view, instance, message: screenMessage }) => {\n const slot = model.screen\n // A Message for a screen since discarded (a Command's late result, a Subscription's late snapshot of the\n // previous organisation's replica) is dropped.\n if (Option.isNone(slot) || slot.value.view !== view || slot.value.instance !== instance) return { model }\n const screen = screens.get(view)!\n const next = screen.update(slot.value.model, screenMessage)\n return {\n model: { ...model, screen: Option.some({ ...slot.value, model: next.model }) },\n commands: liftScreenCommands(view, slot.value.instance, next.commands),\n }\n },\n\n GotPanelMessage: ({ view, instance, message: panelMessage }) => {\n const slot = model.screen\n if (Option.isNone(slot)) return { model }\n // By instance: dropped once its panel is discarded.\n const index = slot.value.panels.findIndex((panel) => panel.instance === instance && panel.view === view)\n if (index < 0) return { model }\n const panel = slot.value.panels[index]!\n const next = screens.get(panel.view)!.update(panel.model, panelMessage)\n const panels = slot.value.panels.map((p, i) => (i === index ? { ...p, model: next.model } : p))\n return {\n model: { ...model, screen: Option.some({ ...slot.value, panels }) },\n commands: liftPanelCommands(panel.view, panel.instance, next.commands),\n }\n },\n\n // A screen loaded on demand: shown now if the route still needs it and its replica is open.\n LoadedScreen: ({ view }) =>\n model.loads[view]?._tag === \"Loading\" && screens.has(view)\n ? withScreen({ ...model, loads: { ...model.loads, [view]: { _tag: \"Loaded\" } } })\n : { model },\n FailedScreen: ({ view, message: reason }) =>\n model.loads[view]?._tag === \"Loading\"\n ? { model: { ...model, loads: { ...model.loads, [view]: { _tag: \"Failed\", message: reason } } } }\n : { model },\n ClickedReload: () => ({ model, commands: [ReloadPage({})] }),\n\n GotMakeMessage: ({ instance, message: makeMessage }) => {\n const slot = model.make\n // A result for a MAKE screen since discarded (another route, organisation or session) is dropped.\n if (Option.isNone(slot) || (Option.isSome(instance) && instance.value !== slot.value.instance)) return { model }\n const next = makeScreen.update(slot.value.model, makeMessage)\n return {\n model: { ...model, make: Option.some({ ...slot.value, model: next.model }) },\n commands: liftMakeCommands(slot.value.instance, next.commands),\n }\n },\n\n ClickedAppearance: () => openDialog(model),\n GotAppearanceDialogMessage: ({ message: dialogMessage }) => foldDialog(model, dialogMessage),\n // A choice made with the keyboard moves focus to the chosen option once it is rendered.\n ChoseScheme: ({ scheme, focus, group }) => ({\n model: { ...model, appearance: { ...model.appearance, scheme } },\n commands: [\n StoreAppearance({ scheme, direction: model.appearance.direction }),\n ...(focus ? [FocusElement({ selector: `#${group ?? \"scheme\"}-${scheme}` })] : []),\n ],\n }),\n ChoseDirection: ({ direction, focus, group }) => ({\n model: { ...model, appearance: { ...model.appearance, direction } },\n commands: [\n StoreAppearance({ scheme: model.appearance.scheme, direction }),\n ...(focus ? [FocusElement({ selector: `#${group ?? \"direction\"}-${direction}` })] : []),\n ],\n }),\n ChosePreset: ({ preset, focus, group }) => ({\n model: { ...model, appearance: { ...model.appearance, preset } },\n commands: [\n StorePreset({ preset }),\n ...(focus ? [FocusElement({ selector: `#${group ?? \"preset\"}-${preset}` })] : []),\n ],\n }),\n ChangedSystemScheme: ({ dark }) => ({\n model: { ...model, appearance: { ...model.appearance, systemDark: dark } },\n }),\n // A language writes in its script's direction: choosing one sets it (the appearance can still override it).\n ChoseLanguage: ({ locale }) => {\n if (!(LOCALES as ReadonlyArray<string>).includes(locale)) return { model }\n const direction = directionFor(locale)\n return {\n model: { ...model, locale, appearance: { ...model.appearance, direction } },\n commands: [StoreLocale({ locale }), StoreAppearance({ scheme: model.appearance.scheme, direction })],\n }\n },\n // Members of the organisation they were loaded for, only the load in flight's (its request number).\n GotMembers: ({ request, orgId, members }) =>\n model.members._tag === \"Loading\" && model.members.request === request && model.members.orgId === orgId\n ? { model: { ...model, members: { _tag: \"Loaded\", orgId, members } } }\n : { model },\n FailedMembers: ({ request, orgId, message }) =>\n model.members._tag === \"Loading\" && model.members.request === request && model.members.orgId === orgId\n ? { model: { ...model, members: { _tag: \"Failed\", orgId, message } } }\n : { model },\n // The desktop sign-in: approved only by the person's click, as the session, once at a time.\n ClickedApproveDesktop: () => {\n if (\n model.route._tag !== \"DesktopSignIn\" ||\n Option.isNone(model.route.request) ||\n model.auth._tag !== \"SignedIn\" ||\n model.desktop._tag === \"Approving\" ||\n model.desktop._tag === \"Approved\"\n )\n return { model }\n const request = model.requests + 1\n return {\n model: { ...model, requests: request, desktop: { _tag: \"Approving\", request } },\n commands: [\n ApproveDesktop({ request, session: model.auth.session.handle, desktop: model.route.request.value }),\n ],\n }\n },\n ClickedDeclineDesktop: () =>\n model.route._tag === \"DesktopSignIn\" && model.desktop._tag !== \"Approving\"\n ? { model, commands: [NavigateInternal({ url: \"/\", path: \"/\" })] }\n : { model },\n // Only the request in flight's answer, and only a redirect to where the request said, is followed.\n ApprovedDesktop: ({ request, redirect }) => {\n if (model.desktop._tag !== \"Approving\" || model.desktop.request !== request) return { model }\n if (model.route._tag !== \"DesktopSignIn\" || Option.isNone(model.route.request)) return { model }\n if (!redirectMatches(redirect, model.route.request.value.redirectUri))\n return { model: { ...model, desktop: { _tag: \"Failed\", message: \"The answer named another redirect\" } } }\n return { model: { ...model, desktop: { _tag: \"Approved\" } }, commands: [LoadExternal({ href: redirect })] }\n },\n FailedApproveDesktop: ({ request, message }) =>\n model.desktop._tag === \"Approving\" && model.desktop.request === request\n ? { model: { ...model, desktop: { _tag: \"Failed\", message } } }\n : { model },\n CheckedBackend: ({ backend }) => ({ model: { ...model, backend } }),\n GotConsent: ({ undecided }) =>\n model.consent === \"off\" ? { model } : { model: { ...model, consent: undecided ? \"undecided\" : \"decided\" } },\n // Down at once (the answer is the kernel's to keep; a refusal raises it again).\n ChoseConsent: ({ accept }) =>\n model.consent === \"undecided\"\n ? { model: { ...model, consent: \"decided\" }, commands: [SaveConsent({ accept })] }\n : { model },\n ChangedProfileName: ({ value }) => ({\n model: { ...model, profile: { ...model.profile, name: Option.some(value) } },\n }),\n ChangedProfileEmail: ({ value }) => ({\n model: { ...model, profile: { ...model.profile, email: Option.some(value) } },\n }),\n // One change at a time, of a non-empty value that differs from the account's: nothing else is sent.\n SubmittedProfile: ({ field }) => {\n if (model.auth._tag !== \"SignedIn\" || Option.isSome(model.profile.saving)) return { model }\n const current = field === \"name\" ? model.auth.session.user.name : model.auth.session.user.email\n const value = Option.getOrElse(\n field === \"name\" ? model.profile.name : model.profile.email,\n () => current,\n ).trim()\n if (value === \"\" || value === current) return { model }\n const request = model.requests + 1\n return {\n model: {\n ...model,\n requests: request,\n profile: { ...model.profile, saving: Option.some({ field, request }), outcome: Option.none() },\n },\n commands: [SaveProfile({ request, session: model.auth.session.handle, field, value })],\n }\n },\n // Only the answer of the change in flight, for the session still signed in: a late one (after a sign-out, or\n // a later change) changes nothing.\n SavedProfile: ({ request, session, field, value }) => {\n if (\n model.auth._tag !== \"SignedIn\" ||\n model.auth.session.handle !== session ||\n !Option.exists(model.profile.saving, (s) => s.request === request)\n )\n return { model }\n const auth =\n field === \"name\"\n ? { ...model.auth, session: { ...model.auth.session, user: { ...model.auth.session.user, name: value } } }\n : model.auth\n return {\n model: {\n ...model,\n auth,\n profile: {\n ...model.profile,\n ...(field === \"name\" ? { name: Option.none() } : { email: Option.none() }),\n saving: Option.none(),\n outcome: Option.some({ field, ok: true, message: \"\" }),\n },\n },\n }\n },\n FailedProfile: ({ request, session, field, message }) =>\n model.auth._tag === \"SignedIn\" &&\n model.auth.session.handle === session &&\n Option.exists(model.profile.saving, (s) => s.request === request)\n ? {\n model: {\n ...model,\n profile: {\n ...model.profile,\n saving: Option.none(),\n outcome: Option.some({ field, ok: false, message }),\n },\n },\n }\n : { model },\n CompletedStore: () => ({ model }),\n CompletedMark: () => ({ model }),\n CompletedFocus: () => ({ model }),\n })\n\n // -- Subscriptions and resources --------------------------------------------------------------------------\n\n const shellSubscriptions = Subscription.make<Model, Message, ReplicaService>()((entry) => ({\n // The core's session, context and connection, as Messages (its current session first).\n runtime: entry(\n {},\n runtimeEvents<Message>({\n runtime,\n initial: () => [\n Message.GotSession({ state: sessionView(runtime.session()) }),\n ...(runtime.revocation() === \"none\" ? [] : [Message.ChangedRevocation({ revocation: runtime.revocation() })]),\n ],\n toMessage: runtimeMessage,\n onRevocation: (revocation) => Message.ChangedRevocation({ revocation }),\n }),\n ),\n // Pending revocations: the core retries them every 15 s and at start; here also whenever the network comes back.\n revocations: entry(\n { pending: Schema.Boolean },\n {\n modelToDependencies: (model) => ({ pending: model.revocation === \"pending\" }),\n dependenciesToStream: ({ pending }) =>\n pending\n ? windowEvents(\"online\").pipe(\n Stream.mapEffect(() =>\n Effect.promise(() => runtime.retryRevocations().catch(() => undefined)).pipe(\n Effect.map(() => Message.ChangedRevocation({ revocation: runtime.revocation() })),\n ),\n ),\n )\n : Stream.empty,\n },\n ),\n // Another tab cleared, replaced or marked the shared session signed out: checked again, so this tab's context\n // closes (or follows the new session) instead of staying open, or writing back what the other tab forgot.\n sharedSession: entry(\n { signedIn: Schema.Boolean },\n {\n modelToDependencies: (model) => ({ signedIn: model.auth._tag === \"SignedIn\" }),\n dependenciesToStream: ({ signedIn }) =>\n signedIn\n ? storageEvents([SESSION_KEY, SIGNED_OUT_KEY]).pipe(\n Stream.mapEffect(() =>\n Effect.promise(() => runtime.start().catch(() => undefined)).pipe(\n Effect.as(Message.CompletedRuntime()),\n ),\n ),\n )\n : Stream.empty,\n },\n ),\n systemScheme: entry(\n { following: Schema.Boolean },\n {\n modelToDependencies: (model) => ({ following: model.appearance.scheme === \"system\" }),\n dependenciesToStream: ({ following }) =>\n following && typeof matchMedia === \"function\"\n ? Stream.callback<Message>((queue) =>\n Effect.acquireRelease(\n Effect.sync(() => {\n const query = matchMedia(\"(prefers-color-scheme: dark)\")\n const listener = (event: MediaQueryListEvent) =>\n Queue.offerUnsafe(queue, Message.ChangedSystemScheme({ dark: event.matches }))\n query.addEventListener(\"change\", listener)\n return () => query.removeEventListener(\"change\", listener)\n }),\n (remove) => Effect.sync(remove),\n ).pipe(Effect.andThen(Effect.never)),\n )\n : Stream.empty,\n },\n ),\n // The kernel's readiness: checked at start, then every 10 s until it is ready (a notice while it is not), and at\n // once when an offline start's session is checked (the kernel answered).\n readiness: entry(\n { ready: Schema.Boolean, offline: Schema.Boolean },\n {\n modelToDependencies: (model) => ({\n ready: model.backend === \"ready\",\n offline: model.auth._tag === \"SignedIn\" && model.auth.offline,\n }),\n dependenciesToStream: ({ ready }) =>\n ready\n ? Stream.empty\n : Stream.merge(Stream.make(undefined), Stream.tick(Duration.seconds(10))).pipe(\n Stream.mapEffect(() =>\n Effect.promise(() => engineProbe(config.kernelUrl, { ttlMs: 0, unavailableTtlMs: 0 }).get()).pipe(\n Effect.map((probed) =>\n Message.CheckedBackend({\n backend: probed.status === \"unavailable\" ? \"unreachable\" : probed.value.status,\n }),\n ),\n ),\n ),\n ),\n },\n ),\n // WebMCP while signed in with an organisation: registered once per (session, organisation), and stopped (its\n // agent session revoked) as soon as either changes or goes, so a revoked or switched session leaves no tools.\n webMcp: entry(\n { session: Schema.NullOr(Schema.String), orgId: Schema.NullOr(Schema.String) },\n {\n modelToDependencies: (model) =>\n model.auth._tag === \"SignedIn\" && Option.isSome(model.auth.orgId)\n ? { session: model.auth.session.handle, orgId: model.auth.orgId.value }\n : { session: null, orgId: null },\n dependenciesToStream: ({ session, orgId }) => {\n const context = config.webMcp === false ? undefined : webModelContext()\n if (session === null || orgId === null || context === undefined) return Stream.empty\n const options = config.webMcp === false ? {} : (config.webMcp ?? {})\n return Stream.callback<Message>(() =>\n Effect.acquireRelease(\n Effect.tryPromise(() =>\n registerWebMcp({\n modelContext: context as never,\n baseUrl: config.kernelUrl,\n token: () => credentials.token(session),\n orgId,\n clientVersion: config.clientVersion,\n clientActions: options.clientActions,\n approve: options.approve,\n }),\n ).pipe(Effect.option),\n (registration) =>\n Option.match(registration, {\n onNone: () => Effect.void,\n onSome: (r) => Effect.promise(() => r.stop()),\n }),\n ).pipe(Effect.andThen(Effect.never)),\n )\n },\n },\n ),\n }))\n\n /**\n * A view's Subscriptions, run for the instance `read` finds: a screen loaded with the shell has its entries lifted\n * one by one (`forInstance`); one loaded on demand, whose entries are not known when the program starts, has them\n * run by one entry of the shell's (`hostedSubscriptions`), each entry restarted only when its own dependencies change.\n */\n const viewSubscriptions = (\n view: string,\n prefix: string,\n read: (model: Model) => Option.Option<{ readonly instance: number; readonly model: unknown }>,\n toMessage: (instance: number, message: unknown) => Message,\n ): ReadonlyArray<Subscription.Subscriptions<Model, Message, ReplicaService>> => {\n if (loaders.has(view)) return [hostedSubscriptions(() => screens.get(view)?.subscriptions, prefix, read, toMessage)]\n const screen = screens.get(view)!\n return screen.subscriptions === undefined ? [] : [forInstance(screen.subscriptions, prefix, read, toMessage)]\n }\n\n // Each screen's entries under its view's name (two screens may name theirs alike), run for the instance shown.\n const screenSubscriptions = [...metas.keys()].flatMap((view) =>\n viewSubscriptions(\n view,\n `${view}/`,\n (model) =>\n Option.flatMap(model.screen, (slot) =>\n slot.view === view ? Option.some({ instance: slot.instance, model: slot.model }) : Option.none(),\n ),\n (instance, message) => Message.GotScreenMessage({ view, instance, message }),\n ),\n )\n\n // The same for each panel a screen can show (a slot's contribution of a view with a screen): its Subscriptions run\n // while it is there, for its own instance, so a view contributed twice runs them twice, each for its own panel.\n const panelSubscriptions = [...slots.values()].flatMap(({ panels }) =>\n panels.flatMap((contributed) =>\n viewSubscriptions(\n contributed.view,\n `panel:${contributed.slot}/${contributed.contribution}/`,\n (model) =>\n Option.flatMap(model.screen, (slot) =>\n Option.map(\n Arr.findFirst(\n slot.panels,\n (panel) => panel.slot === contributed.slot && panel.contribution === contributed.contribution,\n ),\n (panel) => ({ instance: panel.instance, model: panel.model }),\n ),\n ),\n (instance, message) => Message.GotPanelMessage({ view: contributed.view, instance, message }),\n ),\n ),\n )\n\n const subscriptions = Subscription.aggregate<Model, Message, ReplicaService>()(\n shellSubscriptions,\n ...screenSubscriptions,\n ...panelSubscriptions,\n )\n\n // The core's replica, in the generation the Model acts in (none while a switch or a check is under way).\n const managedResources = runtimeReplica<Model, Message>({\n runtime,\n requirements: (model) =>\n model.auth._tag === \"SignedIn\" && !model.auth.checking\n ? Option.flatMap(Option.all({ orgId: model.auth.orgId, generation: model.auth.generation }), (context) =>\n Option.some({ userId: (model.auth as { session: Session }).session.user.id, ...context }),\n )\n : Option.none(),\n onOpened: (key) => Message.OpenedReplica({ key }),\n onClosed: () => Message.ClosedReplica(),\n onFailed: ({ orgId, message }) => Message.FailedReplica({ orgId, message }),\n })\n\n return {\n Model,\n Message,\n Flags,\n init,\n update,\n subscriptions,\n managedResources: managedResources as ManagedResource.ManagedResources<Model, Message, ReplicaService>,\n routeOf,\n nav,\n /** The view of the screen at `/`, when one claims it. */\n homeView: home?.view,\n commands,\n screens,\n viewTitle,\n /** Each slot a screen shows: its panels (contributed views with a screen) and links (commands opening one). */\n slots,\n /** A screen the route needs that could not be loaded (its chunk), with why: the view shows it, with a reload. */\n screenLoadProblem: (model: Model) =>\n model.route._tag === \"View\" ? failedLoad(model, neededViews(model.route.view)) : undefined,\n makeScreen,\n registry,\n contracts: config.contracts,\n development: config.development === true,\n /** The client core the shell runs on (tests drive and inspect it). */\n runtime,\n initialOrg,\n commandDefinitions: {\n NavigateInternal,\n ReplaceLegacyUrl,\n StartSession,\n SignIn,\n SignOut,\n SelectOrganisation,\n StoreOrganisation,\n StoreAppearance,\n StorePreset,\n SaveProfile,\n LoadConsent,\n SaveConsent,\n ClaimConsent,\n StoreLocale,\n LoadMembers,\n FocusElement,\n ApproveDesktop,\n LoadExternal,\n LoadScreen,\n ReloadPage,\n },\n }\n}\n\n/** The organisation the page's address names (`?org=`, a record link), as a session starts. */\nconst linkedOrgOfLocation = (): string | null =>\n new URLSearchParams((globalThis as { readonly location?: { readonly search?: string } }).location?.search ?? \"\").get(\n \"org\",\n )\n\nconst sameOrg = Option.makeEquivalence((a: string, b: string) => a === b)\n\n/** The organisation an address names (`?org=`), if any. */\nexport const orgOfUrl = (url: Url): Option.Option<string> =>\n Option.flatMap(url.search, (search) => {\n const org = new URLSearchParams(search).get(\"org\")\n return org === null || org === \"\" ? Option.none() : Option.some(org)\n })\n\n/** Every `name` event on the window, while the stream runs. */\nconst windowEvents = (name: string): Stream.Stream<void> =>\n Stream.callback<void>((queue) =>\n Effect.acquireRelease(\n Effect.sync(() => {\n const listener = () => Queue.offerUnsafe(queue, undefined)\n window.addEventListener(name, listener)\n return listener\n }),\n (listener) => Effect.sync(() => window.removeEventListener(name, listener)),\n ).pipe(Effect.andThen(Effect.never)),\n )\n\n/** Every `storage` event (another tab's write) for one of `keys`, or for all of storage (`clear()`), while it runs. */\nconst storageEvents = (keys: ReadonlyArray<string>): Stream.Stream<void> =>\n Stream.callback<void>((queue) =>\n Effect.acquireRelease(\n Effect.sync(() => {\n const listener = (event: Event) => {\n const key = (event as { readonly key?: string | null }).key\n if (key === null || key === undefined || keys.includes(key)) Queue.offerUnsafe(queue, undefined)\n }\n window.addEventListener(\"storage\", listener)\n return listener\n }),\n (listener) => Effect.sync(() => window.removeEventListener(\"storage\", listener)),\n ).pipe(Effect.andThen(Effect.never)),\n )\n\nconst errorText = (error: unknown): string => {\n const cause = (error as { cause?: unknown }).cause\n const inner = cause instanceof Error ? cause : error\n return inner instanceof Error ? inner.message : String(inner)\n}\n\nexport type Shell = ReturnType<typeof makeShell>\n",
|
|
90
|
+
"type": "registry:file",
|
|
91
|
+
"target": "shell-foldkit/src/shell.ts"
|
|
92
|
+
},
|
|
93
|
+
{
|
|
94
|
+
"path": "app/shell-foldkit/src/styles.css",
|
|
95
|
+
"content": "/*\n * The shell's one stylesheet: a minimal reset. The StyleX plugin appends every StyleX rule (the theme's variables\n * and the shell's and screens' styles) to it when the shell is built.\n */\n*,\n*::before,\n*::after {\n box-sizing: border-box;\n}\n\nhtml,\nbody {\n margin: 0;\n}\n",
|
|
96
|
+
"type": "registry:file",
|
|
97
|
+
"target": "shell-foldkit/src/styles.css"
|
|
98
|
+
},
|
|
99
|
+
{
|
|
100
|
+
"path": "app/shell-foldkit/src/styles.ts",
|
|
101
|
+
"content": "/**\n * The shell's appearance, in StyleX over the app's theme (`themes/default/tokens.stylex.ts`, written from the\n * ThemeTokens by `@eloxiv/shell-core`): every colour, radius and font is a theme variable, so the `dark` and `rtl`\n * themes the root applies restyle everything, and spacing uses logical properties only, so right to left mirrors.\n * UI items style their screens the same way and may reuse these.\n */\nimport * as stylex from \"@stylexjs/stylex\"\nimport { inertHtml } from \"foldkit/html\"\nimport { colors, sizes } from \"../../themes/default/tokens.stylex.ts\"\n\n/** StyleX styles as a Foldkit `class` attribute (StyleX's `attrs`, for frameworks that set `class`). */\nexport const sx = (...styles: ReadonlyArray<stylex.StyleXStyles | false | null | undefined>) =>\n inertHtml.Class(stylex.attrs(...styles).class ?? \"\")\n\nexport const styles = stylex.create({\n root: {\n minHeight: \"100svh\",\n backgroundColor: colors.background,\n color: colors.foreground,\n fontFamily: sizes.fontSans,\n fontSize: \"0.9375rem\",\n lineHeight: 1.5,\n // Native controls (selects, scrollbars) follow the scheme, as the theme's stylesheet says (`color-scheme`).\n colorScheme: \"light\",\n },\n rootDark: { colorScheme: \"dark\" },\n header: {\n display: \"flex\",\n // Many installed screens make a long navigation: it wraps, and the account controls stay in the window.\n flexWrap: \"wrap\",\n alignItems: \"center\",\n gap: \"1rem\",\n paddingBlock: \"0.75rem\",\n paddingInline: \"1.5rem\",\n borderBlockEndWidth: \"1px\",\n borderBlockEndStyle: \"solid\",\n borderBlockEndColor: colors.border,\n },\n brand: { fontWeight: 600, color: colors.foreground, textDecoration: \"none\" },\n nav: { display: \"flex\", flexWrap: \"wrap\", gap: \"0.75rem\", fontSize: \"0.875rem\" },\n navLink: {\n color: colors.mutedForeground,\n textDecoration: { default: \"none\", \":hover\": \"underline\" },\n outline: { default: \"none\", \":focus-visible\": `2px solid ${colors.ring}` },\n outlineOffset: \"2px\",\n borderRadius: sizes.radius,\n },\n navLinkActive: { color: colors.foreground },\n account: { marginInlineStart: \"auto\", display: \"flex\", alignItems: \"center\", gap: \"0.75rem\", fontSize: \"0.875rem\" },\n main: { marginInline: \"auto\", maxWidth: \"42rem\", padding: \"1.5rem\" },\n card: {\n display: \"flex\",\n flexDirection: \"column\",\n gap: \"0.75rem\",\n padding: \"1.25rem\",\n borderRadius: sizes.radius,\n borderWidth: \"1px\",\n borderStyle: \"solid\",\n borderColor: colors.border,\n backgroundColor: colors.card,\n color: colors.cardForeground,\n },\n cardTitle: { margin: 0, fontSize: \"1.0625rem\", fontWeight: 600 },\n muted: { color: colors.mutedForeground, fontSize: \"0.875rem\", margin: 0 },\n form: { display: \"flex\", flexDirection: \"column\", gap: \"0.5rem\" },\n row: { display: \"flex\", gap: \"0.5rem\", alignItems: \"center\" },\n label: { fontSize: \"0.875rem\", fontWeight: 500 },\n input: {\n flexGrow: 1,\n paddingBlock: \"0.375rem\",\n paddingInline: \"0.625rem\",\n borderRadius: sizes.radius,\n borderWidth: \"1px\",\n borderStyle: \"solid\",\n borderColor: colors.input,\n backgroundColor: colors.background,\n color: colors.foreground,\n font: \"inherit\",\n outline: { default: \"none\", \":focus-visible\": `2px solid ${colors.ring}` },\n },\n button: {\n paddingBlock: \"0.375rem\",\n paddingInline: \"0.875rem\",\n borderRadius: sizes.radius,\n borderWidth: \"1px\",\n borderStyle: \"solid\",\n borderColor: colors.primary,\n backgroundColor: colors.primary,\n color: colors.primaryForeground,\n font: \"inherit\",\n fontWeight: 500,\n cursor: { default: \"pointer\", \":disabled\": \"not-allowed\" },\n opacity: { default: 1, \":disabled\": 0.5 },\n outline: { default: \"none\", \":focus-visible\": `2px solid ${colors.ring}` },\n outlineOffset: \"2px\",\n },\n buttonOutline: {\n backgroundColor: { default: colors.background, \":hover\": colors.accent },\n color: colors.foreground,\n borderColor: colors.border,\n },\n error: { color: colors.destructive, fontSize: \"0.875rem\", margin: 0 },\n list: { display: \"flex\", flexDirection: \"column\", gap: \"0.5rem\", listStyle: \"none\", margin: 0, padding: 0 },\n listItem: {\n paddingBlock: \"0.5rem\",\n paddingInline: \"0.75rem\",\n borderRadius: sizes.radius,\n borderWidth: \"1px\",\n borderStyle: \"solid\",\n borderColor: colors.border,\n },\n badge: { marginInlineStart: \"0.5rem\", fontSize: \"0.75rem\", color: colors.mutedForeground },\n /** The offline indicator in the header: a quiet outlined pill beside the account's controls. */\n offline: {\n paddingBlock: \"0.125rem\",\n paddingInline: \"0.5rem\",\n borderRadius: \"999px\",\n borderWidth: \"1px\",\n borderStyle: \"solid\",\n borderColor: colors.border,\n fontSize: \"0.75rem\",\n color: colors.mutedForeground,\n whiteSpace: \"nowrap\",\n },\n select: {\n paddingBlock: \"0.25rem\",\n paddingInline: \"0.5rem\",\n borderRadius: sizes.radius,\n borderWidth: \"1px\",\n borderStyle: \"solid\",\n borderColor: colors.input,\n backgroundColor: colors.background,\n color: colors.foreground,\n font: \"inherit\",\n },\n // The dialog: the native <dialog> fills the viewport (Foldkit UI positions it); backdrop and panel are ours.\n dialog: { display: \"grid\", placeItems: \"center\" },\n backdrop: { position: \"fixed\", inset: 0, backgroundColor: \"oklch(0 0 0 / 50%)\" },\n panel: {\n position: \"relative\",\n display: \"flex\",\n flexDirection: \"column\",\n gap: \"1rem\",\n inlineSize: \"min(28rem, calc(100vw - 2rem))\",\n padding: \"1.5rem\",\n borderRadius: sizes.radius,\n backgroundColor: colors.popover,\n color: colors.popoverForeground,\n boxShadow: \"0 10px 30px oklch(0 0 0 / 25%)\",\n fontFamily: sizes.fontSans,\n },\n fieldset: { display: \"flex\", flexDirection: \"column\", gap: \"0.375rem\", border: \"none\", margin: 0, padding: 0 },\n legend: { fontWeight: 500, fontSize: \"0.875rem\", marginBlockEnd: \"0.25rem\", padding: 0 },\n radio: {\n display: \"flex\",\n alignItems: \"center\",\n gap: \"0.5rem\",\n paddingBlock: \"0.375rem\",\n paddingInline: \"0.625rem\",\n borderRadius: sizes.radius,\n borderWidth: \"1px\",\n borderStyle: \"solid\",\n borderColor: colors.border,\n backgroundColor: colors.background,\n color: colors.foreground,\n font: \"inherit\",\n textAlign: \"start\",\n cursor: \"pointer\",\n outline: { default: \"none\", \":focus-visible\": `2px solid ${colors.ring}` },\n outlineOffset: \"2px\",\n },\n radioChecked: { borderColor: colors.primary, backgroundColor: colors.accent, color: colors.accentForeground },\n actions: { display: \"flex\", justifyContent: \"flex-end\", gap: \"0.5rem\" },\n // A screen with the views its slots hold beside it: one column on narrow screens, the panels beside it on wide ones.\n mainWide: { maxWidth: \"64rem\" },\n withPanels: {\n display: \"grid\",\n gap: \"1.5rem\",\n gridTemplateColumns: { default: \"minmax(0, 1fr)\", \"@media (min-width: 52rem)\": \"minmax(0, 1fr) 18rem\" },\n alignItems: \"start\",\n },\n panels: { display: \"flex\", flexDirection: \"column\", gap: \"1rem\" },\n // A MAKE module's sandboxed view: its frame fills the screen's width.\n makeFrame: {\n display: \"block\",\n inlineSize: \"100%\",\n blockSize: \"60vh\",\n borderWidth: \"1px\",\n borderStyle: \"solid\",\n borderColor: colors.border,\n borderRadius: sizes.radius,\n backgroundColor: colors.background,\n },\n})\n",
|
|
102
|
+
"type": "registry:file",
|
|
103
|
+
"target": "shell-foldkit/src/styles.ts"
|
|
104
|
+
},
|
|
105
|
+
{
|
|
106
|
+
"path": "app/shell-foldkit/src/testHooks.ts",
|
|
107
|
+
"content": "/**\n * Test builds only (`VITE_ELOXIV_TEST_HOOKS=1`; other builds never load this module): a hook after every\n * render, so a browser test can hold every render to a guarantee, not only the DOM it samples.\n *\n * - After each render has patched the DOM, `window.__eloxivRender({ org, rows })` is called (when the test defined\n * it) with the organisation the rendered Model acts in and every greeting row in the DOM. The render frame patches\n * synchronously inside its animation-frame callback, and a microtask queued while the view runs is taken right\n * after that callback: after the patch, before the next render.\n * - `window.__eloxivInjectFlash = true` makes the shell misbehave once, on purpose: the first render after the\n * organisation changes shows the previous organisation's screen (its rows under the new selection), a flash the\n * next render repairs, so a test can show its check catches one. (The new replica often opens before the next\n * animation frame, so that render may already hold the new organisation's screen: the flash replaces it.)\n */\nimport { Option } from \"effect\"\nimport type { Document, HtmlBuilder } from \"foldkit/html\"\nimport type { Message, Model, ScreenSlot } from \"./shell.ts\"\n\ntype View = (model: Model, h: HtmlBuilder<Message>) => Document\n\ninterface Hooks {\n __eloxivRender?: (render: { readonly org: string; readonly rows: ReadonlyArray<string> }) => void\n __eloxivInjectFlash?: boolean\n}\n\nconst orgOf = (model: Model) => (model.auth._tag === \"SignedIn\" ? Option.getOrElse(model.auth.orgId, () => \"\") : \"\")\n\nexport const withTestHooks = (view: View): View => {\n let last: { readonly org: string; readonly slot: ScreenSlot } | undefined\n return (model, h) => {\n const hooks = window as unknown as Hooks\n const org = orgOf(model)\n let rendered = model\n if (hooks.__eloxivInjectFlash === true && last !== undefined && last.org !== org) {\n hooks.__eloxivInjectFlash = false\n rendered = { ...model, screen: Option.some(last.slot) }\n } else if (Option.isSome(model.screen)) {\n last = { org, slot: model.screen.value }\n }\n const document_ = view(rendered, h)\n queueMicrotask(() =>\n hooks.__eloxivRender?.({\n org,\n rows: [...document.querySelectorAll('[data-testid=\"greeting\"]')].map((e) => e.textContent ?? \"\"),\n }),\n )\n return document_\n }\n}\n",
|
|
108
|
+
"type": "registry:file",
|
|
109
|
+
"target": "shell-foldkit/src/testHooks.ts"
|
|
110
|
+
},
|
|
111
|
+
{
|
|
112
|
+
"path": "app/shell-foldkit/src/timing.ts",
|
|
113
|
+
"content": "/**\n * Route-change timing for the \"route change served from the local replica\" budget, the same marks as the React\n * shell's: navigation marks its start, and the route marks when its data from the replica is on screen (a Mount\n * on the rendered list, so after the DOM holds it). Read by the Playwright benchmark through `eloxiv:route-ready`.\n * And the desktop host's launch-to-interactive signal.\n */\nexport const markNavigationStart = (to: string) => {\n performance.mark(`eloxiv:nav:${to}`)\n}\n\nexport const markRouteReady = (route: string) => {\n const start = performance.getEntriesByName(`eloxiv:nav:${route}`, \"mark\").at(-1)\n if (start === undefined) return\n const measure = performance.measure(`eloxiv:route:${route}`, `eloxiv:nav:${route}`)\n performance.clearMarks(`eloxiv:nav:${route}`)\n window.dispatchEvent(new CustomEvent(\"eloxiv:route-ready\", { detail: { route, ms: measure.duration } }))\n}\n\ninterface TauriInternals {\n readonly invoke: (command: string, args?: object) => Promise<unknown>\n}\n\n/** Desktop host: report first render for the launch-to-interactive budget (a no-op in browsers). */\nexport const reportInteractive = () => {\n const tauri = (window as { __TAURI_INTERNALS__?: TauriInternals }).__TAURI_INTERNALS__\n void tauri?.invoke(\"eloxiv_interactive\", { source: \"shell\" })\n}\n",
|
|
114
|
+
"type": "registry:file",
|
|
115
|
+
"target": "shell-foldkit/src/timing.ts"
|
|
116
|
+
},
|
|
117
|
+
{
|
|
118
|
+
"path": "app/shell-foldkit/src/ui.ts",
|
|
119
|
+
"content": "/**\n * The shell's UI kit: a few accessible, themeable primitives over Foldkit's HTML and StyleX (`styles.ts`, over the\n * theme's tokens, logical spacing only, so dark mode and right to left follow). Deliberately small (decision 11):\n * the shell, its settings frame and the reference screens build from these, and an app reshapes or replaces them\n * freely. Foldkit UI supplies the behaviour that is hard to get right (the dialog); everything here is plain markup\n * with its roles, labels and keyboard handled.\n */\nimport { Option } from \"effect\"\nimport type { Attribute, Html, HtmlBuilder } from \"foldkit/html\"\nimport { styles, sx } from \"./styles.ts\"\n\nexport type Variant = \"primary\" | \"outline\"\n\n/** A button: `type=\"button\"` unless it submits a form, with the primary or the outline look. */\nexport const button = <M>(\n h: HtmlBuilder<M>,\n options: {\n readonly label: string\n readonly onClick?: M\n readonly submit?: boolean\n readonly variant?: Variant\n readonly disabled?: boolean\n readonly attributes?: ReadonlyArray<Attribute<M>>\n },\n): Html =>\n h.button(\n [\n h.Type(options.submit === true ? \"submit\" : \"button\"),\n ...(options.onClick === undefined ? [] : [h.OnClick(options.onClick)]),\n ...(options.disabled === undefined ? [] : [h.Disabled(options.disabled)]),\n sx(styles.button, options.variant === \"outline\" && styles.buttonOutline),\n ...(options.attributes ?? []),\n ],\n [options.label],\n )\n\n/** A labelled text input (the label names it for assistive technology). */\nexport const textField = <M>(\n h: HtmlBuilder<M>,\n options: {\n readonly id: string\n readonly label: string\n readonly type?: \"text\" | \"email\" | \"password\" | \"search\"\n readonly value?: string\n readonly onInput?: (value: string) => M\n readonly autocomplete?: string\n readonly placeholder?: string\n readonly attributes?: ReadonlyArray<Attribute<M>>\n },\n): ReadonlyArray<Html> => [\n h.label([h.For(options.id), sx(styles.label)], [options.label]),\n h.input([\n h.Id(options.id),\n h.Type(options.type ?? \"text\"),\n ...(options.value === undefined ? [] : [h.Value(options.value)]),\n ...(options.onInput === undefined ? [] : [h.OnInput(options.onInput)]),\n ...(options.autocomplete === undefined ? [] : [h.Autocomplete(options.autocomplete)]),\n ...(options.placeholder === undefined ? [] : [h.Placeholder(options.placeholder)]),\n sx(styles.input),\n ...(options.attributes ?? []),\n ]),\n]\n\n/** A select named by `label`; `onChange` gets the chosen option's value. */\nexport const select = <M, A extends string>(\n h: HtmlBuilder<M>,\n options: {\n readonly label: string\n readonly value: A\n readonly items: ReadonlyArray<{ readonly value: A; readonly label: string }>\n readonly onChange: (value: A) => M\n readonly attributes?: ReadonlyArray<Attribute<M>>\n },\n): Html =>\n h.select(\n [\n h.AriaLabel(options.label),\n h.Value(options.value),\n h.OnChange((value) => {\n const item = options.items.find((i) => i.value === value) ?? options.items[0]!\n return options.onChange(item.value)\n }),\n sx(styles.select),\n ...(options.attributes ?? []),\n ],\n options.items.map((item) =>\n h.option([h.Value(item.value), h.Selected(item.value === options.value)], [item.label]),\n ),\n )\n\n/** A message assistive technology announces at once (`role=\"alert\"`). */\nexport const alert = <M>(h: HtmlBuilder<M>, text: string, attributes: ReadonlyArray<Attribute<M>> = []): Html =>\n h.p([h.Role(\"alert\"), sx(styles.error), ...attributes], [text])\n\n/** A titled region (`<section>` named by its heading), with an optional description. */\nexport const card = <M>(\n h: HtmlBuilder<M>,\n options: {\n readonly id: string\n readonly title: string\n readonly level?: 1 | 2\n readonly description?: string\n readonly attributes?: ReadonlyArray<Attribute<M>>\n },\n children: ReadonlyArray<Html>,\n): Html =>\n h.section(\n [sx(styles.card), h.AriaLabelledBy(`${options.id}-title`), ...(options.attributes ?? [])],\n [\n (options.level === 2 ? h.h2 : h.h1)([h.Id(`${options.id}-title`), sx(styles.cardTitle)], [options.title]),\n ...(options.description === undefined ? [] : [h.p([sx(styles.muted)], [options.description])]),\n ...children,\n ],\n )\n\n/**\n * The shell's error view: what went wrong, said once to assistive technology, with an optional way on (a link or a\n * retry). Used for a path nothing is installed at, an organisation or replica that cannot be reached, and a view\n * that cannot be shown.\n */\nexport const errorView = <M>(\n h: HtmlBuilder<M>,\n options: { readonly title: string; readonly message: string; readonly action?: Html; readonly testId?: string },\n): Html =>\n h.section(\n [\n sx(styles.card),\n h.Role(\"alert\"),\n h.AriaLabelledBy(\"error-title\"),\n h.DataAttribute(\"testid\", options.testId ?? \"error-view\"),\n ],\n [\n h.h1([h.Id(\"error-title\"), sx(styles.cardTitle)], [options.title]),\n h.p([sx(styles.muted)], [options.message]),\n ...(options.action === undefined ? [] : [options.action]),\n ],\n )\n\n/**\n * A radio group (WAI-ARIA radio group pattern): one tab stop, the checked option; arrow keys move the choice\n * (Down/Right next, Up/Left previous, wrapping; Home and End the ends), and the choice moves focus with it (the caller\n * focuses the chosen option once it is rendered, with a Command, when `choose` says `focus`); other keys are left to\n * the browser.\n */\nexport const radioGroup = <M, A extends string>(\n h: HtmlBuilder<M>,\n options: {\n readonly id: string\n readonly legend: string\n readonly items: ReadonlyArray<{ readonly value: A; readonly label: string }>\n readonly checked: A\n readonly choose: (value: A, focus: boolean) => M\n readonly initialFocus?: ReadonlyArray<Attribute<M>>\n },\n): Html => {\n const index = Math.max(\n 0,\n options.items.findIndex((item) => item.value === options.checked),\n )\n const move = (key: string): Option.Option<M> => {\n const last = options.items.length - 1\n const next =\n key === \"ArrowDown\" || key === \"ArrowRight\"\n ? index === last\n ? 0\n : index + 1\n : key === \"ArrowUp\" || key === \"ArrowLeft\"\n ? index === 0\n ? last\n : index - 1\n : key === \"Home\"\n ? 0\n : key === \"End\"\n ? last\n : undefined\n if (next === undefined) return Option.none()\n return Option.some(options.choose(options.items[next]!.value, true))\n }\n return h.div(\n [h.Role(\"radiogroup\"), h.AriaLabelledBy(`${options.id}-legend`), sx(styles.fieldset)],\n [\n h.span([h.Id(`${options.id}-legend`), sx(styles.legend)], [options.legend]),\n ...options.items.map((item, i) =>\n h.button(\n [\n h.Id(`${options.id}-${item.value}`),\n h.Type(\"button\"),\n h.Role(\"radio\"),\n h.AriaChecked(i === index),\n h.Tabindex(i === index ? 0 : -1),\n h.OnClick(options.choose(item.value, false)),\n h.OnKeyDownPreventDefault(move),\n sx(styles.radio, i === index && styles.radioChecked),\n ...(i === index ? (options.initialFocus ?? []) : []),\n ],\n [item.label],\n ),\n ),\n ],\n )\n}\n",
|
|
120
|
+
"type": "registry:file",
|
|
121
|
+
"target": "shell-foldkit/src/ui.ts"
|
|
122
|
+
},
|
|
123
|
+
{
|
|
124
|
+
"path": "app/shell-foldkit/src/view.ts",
|
|
125
|
+
"content": "/**\n * The shell's view: a pure function of the Model. The root carries the appearance (StyleX's `dark` and `rtl`\n * themes over the app's tokens, and `dir`); the header holds navigation from the installed screens, the\n * organisation switcher, the appearance dialog's trigger and the account; the main area shows sign-in, the\n * launcher, the settings frame, the error view, or the route's screen with the views and commands other modules\n * contribute to its slots beside it. The shell's own text is the locale's (`locale.ts`); its controls are the UI\n * kit's (`ui.ts`).\n */\nimport * as stylex from \"@stylexjs/stylex\"\nimport { Dialog } from \"@foldkit/ui\"\nimport { guardView, type ViewError } from \"@eloxiv/shell-core\"\nimport { Effect, Option } from \"effect\"\nimport { Mount } from \"foldkit\"\nimport type { Document, Html, HtmlBuilder } from \"foldkit/html\"\nimport { defineView } from \"foldkit/submodel\"\nimport { preset as contrast, presetDark as contrastDark } from \"../../themes/default/contrast.stylex.ts\"\nimport { dark, rtl } from \"../../themes/default/tokens.stylex.ts\"\nimport type { Message as MakeMessage } from \"./make.ts\"\nimport { LANGUAGES, text, type MessageId } from \"./locale.ts\"\nimport { Message, type Direction, type Model, type Scheme, type ScreenSlot, type Shell } from \"./shell.ts\"\nimport { styles, sx } from \"./styles.ts\"\nimport { alert, button, card, errorView, radioGroup, select, textField } from \"./ui.ts\"\nimport { markRouteReady, reportInteractive } from \"./timing.ts\"\n\n/**\n * Marks the route ready once its data is in the DOM (the element mounts only when the screen is ready), under the\n * path navigation marked its start with.\n */\nexport const MarkRouteReady = Mount.define(\"MarkRouteReady\", {\n messages: [Message.CompletedMark],\n execute: () =>\n Effect.sync(() => {\n markRouteReady(window.location.pathname)\n return Message.CompletedMark()\n }),\n})\n\n/** Reports the first render to the desktop host. */\nexport const ReportInteractive = Mount.define(\"ReportInteractive\", {\n messages: [Message.CompletedMark],\n execute: () =>\n Effect.sync(() => {\n reportInteractive()\n return Message.CompletedMark()\n }),\n})\n\nexport const isDark = (model: Model) =>\n model.appearance.scheme === \"dark\" || (model.appearance.scheme === \"system\" && model.appearance.systemDark)\n\nconst SCHEMES: ReadonlyArray<{ readonly value: Scheme; readonly label: MessageId }> = [\n { value: \"system\", label: \"appearance.system\" },\n { value: \"light\", label: \"appearance.light\" },\n { value: \"dark\", label: \"appearance.dark\" },\n]\nconst DIRECTIONS: ReadonlyArray<{ readonly value: Direction; readonly label: MessageId }> = [\n { value: \"ltr\", label: \"appearance.ltr\" },\n { value: \"rtl\", label: \"appearance.rtl\" },\n]\n\n/** The appearance's two radio groups (the dialog's and the settings', each under its own ids). */\nconst appearanceGroups = (\n model: Model,\n h: HtmlBuilder<Message>,\n ids: { readonly scheme: string; readonly direction: string },\n initialFocus?: ReadonlyArray<never>,\n): ReadonlyArray<Html> => {\n const t = (id: MessageId) => text(model.locale, id)\n return [\n radioGroup(h, {\n id: ids.scheme,\n legend: t(\"appearance.scheme\"),\n items: SCHEMES.map((item) => ({ value: item.value, label: t(item.label) })),\n checked: model.appearance.scheme,\n choose: (scheme, focus) => Message.ChoseScheme({ scheme, focus, group: ids.scheme }),\n ...(initialFocus === undefined ? {} : { initialFocus }),\n }),\n radioGroup(h, {\n id: ids.direction,\n legend: t(\"appearance.direction\"),\n items: DIRECTIONS.map((item) => ({ value: item.value, label: t(item.label) })),\n checked: model.appearance.direction,\n choose: (direction, focus) => Message.ChoseDirection({ direction, focus, group: ids.direction }),\n }),\n radioGroup(h, {\n id: ids.scheme.replace(\"scheme\", \"preset\"),\n legend: t(\"appearance.preset\"),\n items: PRESETS.map((item) => ({ value: item.value, label: t(item.label) })),\n checked: model.appearance.preset,\n choose: (preset, focus) => Message.ChosePreset({ preset, focus, group: ids.scheme.replace(\"scheme\", \"preset\") }),\n }),\n ]\n}\n\nconst PRESETS: ReadonlyArray<{ readonly value: \"standard\" | \"contrast\"; readonly label: MessageId }> = [\n { value: \"standard\", label: \"appearance.standard\" },\n { value: \"contrast\", label: \"appearance.contrast\" },\n]\n\nconst appearanceDialog = (model: Model, h: HtmlBuilder<Message>): Html =>\n h.submodel({\n slotId: model.appearanceDialog.id,\n model: model.appearanceDialog,\n view: Dialog.view,\n viewInputs: {\n hasDescription: true,\n toView: ({ dialog, backdrop, panel, title, description, initialFocus, closeButton, isVisible }) =>\n h.dialog(\n [...dialog, sx(styles.dialog)],\n isVisible\n ? [\n h.div([...backdrop, sx(styles.backdrop)], []),\n h.div(\n [...panel, sx(styles.panel)],\n [\n h.h2([...title, sx(styles.cardTitle)], [text(model.locale, \"appearance.title\")]),\n h.p([...description, sx(styles.muted)], [text(model.locale, \"appearance.description\")]),\n ...appearanceGroups(model, h, { scheme: \"scheme\", direction: \"direction\" }, initialFocus as never),\n h.div(\n [sx(styles.actions)],\n [\n h.button(\n [...closeButton, sx(styles.button, styles.buttonOutline)],\n [text(model.locale, \"appearance.done\")],\n ),\n ],\n ),\n ],\n ),\n ]\n : [],\n ),\n },\n toParentMessage: (message) => Message.GotAppearanceDialogMessage({ message }),\n })\n\nconst header = (shell: Shell, model: Model, h: HtmlBuilder<Message>): Html => {\n const t = (id: MessageId) => text(model.locale, id)\n const route = model.route\n const link = (path: string, label: string, active: boolean, testId?: string) =>\n h.a(\n [\n h.Href(path),\n sx(styles.navLink, active && styles.navLinkActive),\n ...(active ? [h.AriaCurrent(\"page\")] : []),\n ...(testId === undefined ? [] : [h.DataAttribute(\"testid\", testId)]),\n ],\n [label],\n )\n const auth = model.auth\n return h.header(\n [sx(styles.header)],\n [\n h.a([h.Href(\"/\"), sx(styles.brand)], [\"Eloxiv\"]),\n h.nav(\n [h.AriaLabel(t(\"nav.main\")), sx(styles.nav)],\n [\n link(\"/\", t(\"nav.home\"), route._tag === \"Home\" || (route._tag === \"View\" && route.view === shell.homeView)),\n ...shell.nav.map((entry) =>\n link(entry.path, entry.label, route._tag === \"View\" && route.view === entry.view, `nav-${entry.module}`),\n ),\n ],\n ),\n h.div(\n [sx(styles.account)],\n [\n h.button(\n [\n h.Type(\"button\"),\n h.Id(\"appearance-trigger\"),\n h.OnClick(Message.ClickedAppearance()),\n sx(styles.button, styles.buttonOutline),\n ],\n [t(\"header.appearance\")],\n ),\n ...(auth._tag === \"SignedIn\"\n ? [\n ...offlineIndicator(model, h),\n link(\"/settings\", t(\"header.settings\"), route._tag === \"Settings\", \"nav-settings\"),\n ...(auth.memberships.length > 0\n ? [\n h.select(\n [\n h.AriaLabel(t(\"header.organisation\")),\n h.DataAttribute(\"testid\", \"org-switcher\"),\n h.Value(Option.getOrElse(auth.orgId, () => \"\")),\n h.OnChange((orgId) => Message.SelectedOrganisation({ orgId })),\n sx(styles.select),\n ],\n auth.memberships.map((m) =>\n h.option([h.Value(m.orgId), h.Selected(Option.contains(auth.orgId, m.orgId))], [m.name]),\n ),\n ),\n ]\n : []),\n h.span([h.DataAttribute(\"testid\", \"signed-in-as\")], [auth.session.user.email]),\n h.button(\n [h.Type(\"button\"), h.OnClick(Message.ClickedSignOut()), sx(styles.button, styles.buttonOutline)],\n [t(\"header.signOut\")],\n ),\n ]\n : model.revocation !== \"none\"\n ? [\n h.span(\n [\n h.DataAttribute(\"testid\", \"signout-status\"),\n h.DataAttribute(\"state\", model.revocation),\n sx(styles.muted),\n ],\n [\n model.revocation === \"confirmed\"\n ? t(\"signOut.confirmed\")\n : model.revocation === \"revoking\"\n ? t(\"signOut.revoking\")\n : t(\"signOut.pending\"),\n ],\n ),\n ]\n : []),\n ],\n ),\n ],\n )\n}\n\nconst signIn = (model: Model, h: HtmlBuilder<Message>): Html => {\n if (model.auth._tag !== \"SignedOut\") return h.empty\n const form = model.auth.form\n const t = (id: MessageId) => text(model.locale, id)\n return h.section(\n [sx(styles.card), h.AriaLabelledBy(\"sign-in-title\")],\n [\n h.h1([h.Id(\"sign-in-title\"), sx(styles.cardTitle)], [t(\"signIn.title\")]),\n h.p([sx(styles.muted)], [t(\"signIn.description\")]),\n h.form(\n [h.OnSubmit(Message.SubmittedSignIn()), sx(styles.form)],\n [\n h.label([h.For(\"email\"), sx(styles.label)], [t(\"signIn.email\")]),\n h.input([\n h.Id(\"email\"),\n h.Type(\"email\"),\n h.Autocomplete(\"username\"),\n h.Value(form.email),\n h.OnInput((value) => Message.ChangedEmail({ value })),\n sx(styles.input),\n ]),\n h.label([h.For(\"password\"), sx(styles.label)], [t(\"signIn.password\")]),\n h.input([\n h.Id(\"password\"),\n h.Type(\"password\"),\n h.Autocomplete(\"current-password\"),\n // Not in the Model: the sign-in Command reads the field (and empties it), so the password is held nowhere.\n sx(styles.input),\n ]),\n button(h, { label: t(\"signIn.submit\"), submit: true, disabled: form.submitting }),\n ...Option.match(form.error, { onNone: () => [], onSome: (error) => [alert(h, error)] }),\n ],\n ),\n ],\n )\n}\n\nconst launcher = (shell: Shell, model: Model, h: HtmlBuilder<Message>): Html =>\n card(\n h,\n {\n id: \"modules\",\n title: text(model.locale, \"launcher.title\"),\n description: text(model.locale, \"launcher.description\"),\n },\n [\n h.ul(\n [sx(styles.list)],\n shell.contracts.map((module) => {\n const entry = shell.nav.find((e) => e.module === module.name)\n return h.li(\n [sx(styles.row)],\n [\n h.span([], [module.name, h.span([sx(styles.badge)], [`v${module.version}`])]),\n ...(entry === undefined\n ? []\n : [h.a([h.Href(entry.path), sx(styles.navLink)], [text(model.locale, \"launcher.open\")])]),\n ],\n )\n }),\n ),\n ...(shell.commands.length === 0\n ? []\n : [\n h.h2([h.Id(\"commands-title\"), sx(styles.legend)], [text(model.locale, \"launcher.commands\")]),\n h.ul(\n [h.AriaLabelledBy(\"commands-title\"), sx(styles.list)],\n shell.commands.map((command) =>\n h.li([], [h.a([h.Href(command.path), sx(styles.navLink)], [command.title])]),\n ),\n ),\n ]),\n ],\n )\n\n/**\n * The profile's thin editing controls: the name, saved as it is, and an email change asked for (the new address is\n * verified before it changes), one at a time, with how the last change went.\n */\nconst profileEditing = (\n model: Model,\n user: { readonly name: string; readonly email: string },\n h: HtmlBuilder<Message>,\n): ReadonlyArray<Html> => {\n const t = (id: MessageId, params?: Readonly<Record<string, string>>) => text(model.locale, id, params)\n const saving = Option.getOrUndefined(model.profile.saving)\n const outcome = Option.getOrUndefined(model.profile.outcome)\n const status = (field: \"name\" | \"email\"): ReadonlyArray<Html> =>\n saving?.field === field\n ? [h.p([h.Role(\"status\"), sx(styles.muted)], [t(\"settings.saving\")])]\n : outcome?.field === field\n ? outcome.ok\n ? [h.p([h.Role(\"status\"), h.DataAttribute(\"testid\", `profile-${field}-saved`)], [t(\"settings.saved\")])]\n : [\n alert(h, t(\"settings.saveFailed\", { reason: outcome.message }), [\n h.DataAttribute(\"testid\", `profile-${field}-failed`),\n ]),\n ]\n : []\n const form = (\n field: \"name\" | \"email\",\n label: MessageId,\n action: MessageId,\n value: string,\n onInput: (value: string) => Message,\n ) =>\n h.form(\n [sx(styles.form), h.OnSubmit(Message.SubmittedProfile({ field }))],\n [\n ...textField(h, {\n id: `profile-${field}-input`,\n label: t(label),\n type: field === \"email\" ? \"email\" : \"text\",\n value,\n onInput,\n autocomplete: field === \"email\" ? \"email\" : \"name\",\n }),\n button(h, { label: t(action), submit: true, disabled: saving !== undefined }),\n ...status(field),\n ],\n )\n return [\n form(\n \"name\",\n \"settings.name\",\n \"settings.saveName\",\n Option.getOrElse(model.profile.name, () => user.name),\n (value) => Message.ChangedProfileName({ value }),\n ),\n form(\n \"email\",\n \"settings.email\",\n \"settings.editProfile\",\n Option.getOrElse(model.profile.email, () => user.email),\n (value) => Message.ChangedProfileEmail({ value }),\n ),\n ]\n}\n\n/**\n * The settings frame: a starting point, deliberately minimal (decision 11): who is signed in, the organisation's\n * members, the shell's language and the appearance.\n */\nconst settings = (model: Model, h: HtmlBuilder<Message>): Html => {\n if (model.auth._tag !== \"SignedIn\") return h.empty\n const auth = model.auth\n const t = (id: MessageId, params?: Readonly<Record<string, string>>) => text(model.locale, id, params)\n const organisation = auth.memberships.find((m) => Option.contains(auth.orgId, m.orgId))?.name ?? \"\"\n const members = model.members\n return h.div(\n [sx(styles.form), h.DataAttribute(\"testid\", \"settings\")],\n [\n h.h1([sx(styles.cardTitle)], [t(\"settings.title\")]),\n card(h, { id: \"profile\", title: t(\"settings.profile\"), level: 2 }, [\n h.dl(\n [sx(styles.form)],\n [\n h.dt([sx(styles.label)], [t(\"settings.name\")]),\n h.dd([h.DataAttribute(\"testid\", \"profile-name\")], [auth.session.user.name]),\n h.dt([sx(styles.label)], [t(\"settings.email\")]),\n h.dd([h.DataAttribute(\"testid\", \"profile-email\")], [auth.session.user.email]),\n ],\n ),\n ...profileEditing(model, auth.session.user, h),\n ]),\n card(\n h,\n {\n id: \"members\",\n title: t(\"settings.members\"),\n level: 2,\n description: t(\"settings.membersOf\", { organisation }),\n },\n [\n members._tag === \"Loaded\"\n ? h.ul(\n [h.AriaLabel(t(\"settings.members\")), h.DataAttribute(\"testid\", \"members\"), sx(styles.list)],\n members.members.map((m) =>\n h.keyed(\"li\")(\n m.userId,\n [h.DataAttribute(\"testid\", \"member\"), sx(styles.listItem)],\n [h.span([], [m.email]), h.span([sx(styles.badge)], [m.roles.join(\", \")])],\n ),\n ),\n )\n : members._tag === \"Failed\"\n ? alert(h, t(\"settings.membersFailed\", { reason: members.message }))\n : h.p([h.AriaBusy(true), sx(styles.muted)], [t(\"loading\")]),\n ],\n ),\n card(\n h,\n { id: \"language\", title: t(\"settings.language\"), level: 2, description: t(\"settings.languageDescription\") },\n [\n select(h, {\n label: t(\"settings.language\"),\n value: model.locale,\n items: LANGUAGES,\n onChange: (locale) => Message.ChoseLanguage({ locale }),\n attributes: [h.DataAttribute(\"testid\", \"language\")],\n }),\n ],\n ),\n card(\n h,\n { id: \"settings-appearance\", title: t(\"appearance.title\"), level: 2, description: t(\"appearance.description\") },\n appearanceGroups(model, h, { scheme: \"settings-scheme\", direction: \"settings-direction\" }),\n ),\n ],\n )\n}\n\n/** Where a redirect goes, as the person reads it: `127.0.0.1:4191` for a loopback address, else its scheme. */\nconst redirectTarget = (redirectUri: string): string => {\n const url = new URL(redirectUri)\n return url.protocol === \"http:\" ? url.host : `${url.protocol}//${url.host}`\n}\n\n/**\n * The desktop sign-in's approval (`/desktop/sign-in`): who signs in, where the app receives the answer and the\n * request's fingerprint (the challenge's first characters, which the app can show beside its own), the warning, and\n * the two choices. The approve button is the page's first control; nothing is approved without it.\n */\nconst desktopSignIn = (model: Model, h: HtmlBuilder<Message>): Html => {\n if (model.auth._tag !== \"SignedIn\" || model.route._tag !== \"DesktopSignIn\") return h.empty\n const t = (id: MessageId, params?: Readonly<Record<string, string>>) => text(model.locale, id, params)\n const auth = model.auth\n return Option.match(model.route.request, {\n onNone: () =>\n errorView(h, {\n title: t(\"desktop.title\"),\n message: t(\"desktop.invalid\"),\n action: homeLink(model, h),\n testId: \"desktop-invalid\",\n }),\n onSome: (request) => {\n const approval = model.desktop\n const busy = approval._tag === \"Approving\" || approval._tag === \"Approved\"\n return card(\n h,\n {\n id: \"desktop-sign-in\",\n title: t(\"desktop.title\"),\n description: t(\"desktop.description\", { email: auth.session.user.email }),\n attributes: [h.DataAttribute(\"testid\", \"desktop-sign-in\")],\n },\n [\n h.p([sx(styles.muted)], [t(\"desktop.warning\")]),\n h.dl(\n [sx(styles.form)],\n [\n h.dt([sx(styles.label)], [t(\"desktop.redirect\")]),\n h.dd(\n [h.DataAttribute(\"testid\", \"desktop-redirect\"), h.Dir(\"ltr\")],\n [redirectTarget(request.redirectUri)],\n ),\n h.dt([sx(styles.label)], [t(\"desktop.fingerprint\")]),\n h.dd([h.DataAttribute(\"testid\", \"desktop-fingerprint\"), h.Dir(\"ltr\")], [request.challenge.slice(0, 8)]),\n ],\n ),\n approval._tag === \"Approved\"\n ? h.p([h.Role(\"status\"), h.DataAttribute(\"testid\", \"desktop-approved\")], [t(\"desktop.approved\")])\n : h.div(\n [sx(styles.actions)],\n [\n button(h, {\n label: approval._tag === \"Approving\" ? t(\"desktop.approving\") : t(\"desktop.approve\"),\n onClick: Message.ClickedApproveDesktop(),\n disabled: busy,\n attributes: [h.DataAttribute(\"testid\", \"desktop-approve\")],\n }),\n button(h, {\n label: t(\"desktop.decline\"),\n onClick: Message.ClickedDeclineDesktop(),\n variant: \"outline\",\n disabled: busy,\n attributes: [h.DataAttribute(\"testid\", \"desktop-decline\")],\n }),\n ],\n ),\n ...(approval._tag === \"Failed\"\n ? [\n alert(h, t(\"desktop.failed\", { reason: approval.message }), [\n h.DataAttribute(\"testid\", \"desktop-failed\"),\n ]),\n ]\n : []),\n ],\n )\n },\n })\n}\n\nconst homeLink = (model: Model, h: HtmlBuilder<Message>): Html =>\n h.a([h.Href(\"/\"), sx(styles.navLink)], [text(model.locale, \"error.home\")])\n\n/** What shows while nobody is signed in: the sign-in form, or (a session being checked or signed out) nothing of it. */\nconst withoutSession = (model: Model, h: HtmlBuilder<Message>): Html | undefined =>\n model.auth._tag === \"SignedOut\" ? signIn(model, h) : model.auth._tag === \"SignedIn\" ? undefined : pending(model, h)\n\n/**\n * A stored session the kernel could not be reached to check (the core checks again): why; being checked, or signing\n * out: nothing of any session meanwhile.\n */\nconst pending = (model: Model, h: HtmlBuilder<Message>): Html => {\n const t = (id: MessageId, params?: Readonly<Record<string, string>>) => text(model.locale, id, params)\n return model.auth._tag === \"Restoring\" && Option.isSome(model.auth.problem)\n ? errorView(h, {\n title: t(\"error.organisations.title\"),\n message: t(\"error.organisations.message\", { reason: model.auth.problem.value }),\n })\n : h.p([h.DataAttribute(\"testid\", \"session-loading\"), h.AriaBusy(true), sx(styles.muted)], [t(\"loading\")])\n}\n\nconst content = (shell: Shell, model: Model, h: HtmlBuilder<Message>): Html => {\n const notSignedIn = withoutSession(model, h)\n if (notSignedIn !== undefined) return notSignedIn\n const t = (id: MessageId, params?: Readonly<Record<string, string>>) => text(model.locale, id, params)\n // A desktop sign-in needs the person, not an organisation: shown whatever the organisations' state.\n if (model.route._tag === \"DesktopSignIn\") return desktopSignIn(model, h)\n const route = model.route\n // The organisations could not be listed (the core lists them again): why, not an empty or loading screen. With an\n // organisation open (the one remembered for the session) its rows still show, the reason above them.\n if (\n model.auth._tag === \"SignedIn\" &&\n Option.isSome(model.auth.organisationsProblem) &&\n Option.isNone(model.auth.orgId)\n )\n return errorView(h, {\n title: t(\"error.organisations.title\"),\n message: t(\"error.organisations.message\", { reason: model.auth.organisationsProblem.value }),\n testId: \"organisations-unavailable\",\n })\n if (route._tag === \"Home\") return launcher(shell, model, h)\n if (route._tag === \"Settings\") return settings(model, h)\n if (route._tag === \"NotFound\")\n return errorView(h, {\n title: t(\"error.notFound.title\"),\n message: t(\"error.notFound.message\", { path: route.path }),\n action: homeLink(model, h),\n testId: \"not-found\",\n })\n // A MAKE module's sandboxed view: served by the kernel, not the replica, in the selected organisation.\n if (route._tag === \"Make\")\n return Option.match(model.make, {\n onNone: () =>\n h.p([h.DataAttribute(\"testid\", \"make-loading\"), h.AriaBusy(true), sx(styles.muted)], [t(\"loading\")]),\n onSome: (slot) =>\n h.submodel({\n slotId: `make-${slot.instance}`,\n model: slot.model,\n view: screenView(shell.makeScreen.view),\n toParentMessage: (message: unknown) =>\n Message.GotMakeMessage({ instance: Option.some(slot.instance), message: message as MakeMessage }),\n }),\n })\n if (model.replica._tag === \"Failed\")\n return errorView(h, {\n title: t(\"error.replica.title\"),\n message: t(\"error.replica.message\", { reason: model.replica.message }),\n })\n return Option.match(model.screen, {\n // The replica of the selected organisation is opening, or the screen's code is loading: nothing of any\n // organisation is shown meanwhile. Code that could not be loaded says so, with a way back (a reload).\n onNone: () => {\n const problem = shell.screenLoadProblem(model)\n return problem === undefined\n ? h.p([h.DataAttribute(\"testid\", \"screen-loading\"), h.AriaBusy(true), sx(styles.muted)], [t(\"loading\")])\n : errorView(h, {\n title: t(\"error.chunk.title\"),\n message: t(\"error.chunk.message\"),\n testId: \"screen-load-failed\",\n action: button(h, {\n label: t(\"error.reload\"),\n onClick: Message.ClickedReload(),\n attributes: [h.DataAttribute(\"testid\", \"screen-reload\")],\n }),\n })\n },\n onSome: (slot) => {\n const screen = shell.screens.get(slot.view)!\n const ready = screen.isReady(slot.model)\n const shown = h.div(\n [h.DataAttribute(\"screen\", slot.view)],\n [\n h.submodel({\n slotId: `screen-${slot.view}-${slot.instance}`,\n model: slot.model,\n view: screenView(screen.render),\n toParentMessage: (message: unknown) =>\n Message.GotScreenMessage({ view: slot.view, instance: slot.instance, message }),\n }),\n ...(ready ? [h.span([h.Hidden(true), h.OnMount(MarkRouteReady())], [])] : []),\n ],\n )\n const regions = slotRegions(shell, slot, h)\n return regions.length === 0 ? shown : h.div([sx(styles.withPanels)], [shown, h.div([sx(styles.panels)], regions)])\n },\n })\n}\n\n/**\n * The regions beside a screen, one per slot it shows that has something installed for it: the contributed views'\n * screens (panels, each its own Submodel) and the contributed commands that open a view (links), in order.\n */\nconst slotRegions = (shell: Shell, slot: ScreenSlot, h: HtmlBuilder<Message>): ReadonlyArray<Html> =>\n (shell.screens.get(slot.view)!.slots ?? []).flatMap((slotId) => {\n const panels = slot.panels.filter((panel) => panel.slot === slotId)\n const links = shell.slots.get(slotId)?.links ?? []\n if (panels.length === 0 && links.length === 0) return []\n return [\n h.aside(\n [\n h.AriaLabel(shell.registry.slots().find((s) => s.id === slotId)?.description ?? slotId),\n h.DataAttribute(\"slot\", slotId),\n ],\n [\n ...panels.map((panel) =>\n h.div(\n [h.DataAttribute(\"panel\", panel.view), h.DataAttribute(\"contribution\", panel.contribution)],\n [\n h.submodel({\n slotId: `panel-${panel.view}-${panel.instance}`,\n model: panel.model,\n view: screenView(shell.screens.get(panel.view)!.render),\n toParentMessage: (message: unknown) =>\n Message.GotPanelMessage({ view: panel.view, instance: panel.instance, message }),\n }),\n ],\n ),\n ),\n ...(links.length === 0\n ? []\n : [\n h.ul(\n [sx(styles.list)],\n links.map((link) => h.li([], [h.a([h.Href(link.path), sx(styles.navLink)], [link.title])])),\n ),\n ]),\n ],\n ),\n ]\n })\n\n/** The shell's words for each kind of failure a view meets (shell-core's `viewError`). */\nconst ERROR_TEXT: Readonly<Record<ViewError[\"kind\"], readonly [MessageId, MessageId]>> = {\n \"not-found\": [\"error.notFound.title\", \"error.failed.message\"],\n \"signed-out\": [\"error.signedOut.title\", \"error.signedOut.message\"],\n forbidden: [\"error.forbidden.title\", \"error.forbidden.message\"],\n outdated: [\"error.outdated.title\", \"error.outdated.message\"],\n offline: [\"error.offline.title\", \"error.offline.message\"],\n failed: [\"error.failed.title\", \"error.failed.message\"],\n}\n\n/** What the last render showed in (a screen's own view is drawn without the shell's Model). */\nconst rendering = { locale: \"en\", development: false }\n\n/**\n * The reference error view for a failure: its kind's words in the person's language, a way on (home, and try again\n * where that can help, which reloads), and in development only, the stack.\n */\nexport const failedView = <M>(h: HtmlBuilder<M>, failure: ViewError, locale: string, development: boolean): Html => {\n const [title, message] = ERROR_TEXT[failure.kind]\n return errorView(h, {\n title: text(locale, title),\n message: text(locale, message),\n testId: `error-${failure.kind}`,\n action: h.div(\n [],\n [\n h.a([h.Href(failure.home), sx(styles.navLink)], [text(locale, \"error.home\")]),\n ...(failure.retry ? [h.a([h.Href(\"\"), sx(styles.navLink)], [text(locale, \"error.retry\")])] : []),\n ...(development && failure.stack !== null\n ? [h.pre([h.DataAttribute(\"testid\", \"error-stack\")], [failure.stack])]\n : []),\n ],\n ),\n })\n}\n\n/**\n * A screen's render as a Submodel view, made once per screen so its identity is stable across renders. A render that\n * throws shows the error view in its place (`guardView`), never a broken shell.\n */\nconst screenViews = new WeakMap<object, ReturnType<typeof defineView<unknown, unknown>>>()\nconst screenView = (render: (model: any, h: HtmlBuilder<any>) => Html) => {\n let view = screenViews.get(render)\n if (view === undefined) {\n view = defineView<unknown, unknown>((model, h) =>\n guardView(\n () => render(model, h),\n (failure) => failedView(h, failure, rendering.locale, rendering.development),\n { development: rendering.development },\n ),\n )\n screenViews.set(render, view)\n }\n return view\n}\n\n/**\n * The offline indicator: what shows comes from this device alone (an offline start, the kernel not reached to check\n * the session), changes kept here until the connection is back. A status, so a screen reader hears it change.\n */\nconst offlineIndicator = (model: Model, h: HtmlBuilder<Message>): ReadonlyArray<Html> =>\n model.auth._tag === \"SignedIn\" && model.auth.offline\n ? [\n h.span(\n [\n h.Role(\"status\"),\n h.DataAttribute(\"testid\", \"offline-indicator\"),\n h.Title(text(model.locale, \"offline.detail\")),\n h.AriaDescription(text(model.locale, \"offline.detail\")),\n sx(styles.offline),\n ],\n [text(model.locale, \"offline.badge\")],\n ),\n ]\n : []\n\n/**\n * The organisations could not be listed while one is open (the one remembered for the session): why, above its rows.\n */\nconst organisationsNotice = (model: Model, h: HtmlBuilder<Message>): ReadonlyArray<Html> =>\n model.auth._tag === \"SignedIn\" && Option.isSome(model.auth.organisationsProblem) && Option.isSome(model.auth.orgId)\n ? [\n h.p(\n [h.Role(\"status\"), h.DataAttribute(\"testid\", \"organisations-notice\"), sx(styles.muted)],\n [text(model.locale, \"error.organisations.message\", { reason: model.auth.organisationsProblem.value })],\n ),\n ]\n : []\n\n/** A notice while the kernel is not reachable or not ready (the app still shows what the replica holds). */\nconst backendNotice = (model: Model, h: HtmlBuilder<Message>): ReadonlyArray<Html> =>\n model.backend === \"unreachable\" || model.backend === \"not-ready\"\n ? [\n h.p(\n [h.Role(\"status\"), h.DataAttribute(\"testid\", \"backend-notice\"), sx(styles.muted)],\n [text(model.locale, model.backend === \"unreachable\" ? \"backend.unreachable\" : \"backend.notReady\")],\n ),\n ]\n : []\n\n/**\n * The consent prompt while an optional category is unchosen: every optional category, or only what is necessary\n * (a region in the page's flow, not over it: nothing it covers waits on it).\n */\nconst consentPrompt = (model: Model, h: HtmlBuilder<Message>): ReadonlyArray<Html> =>\n model.consent === \"undecided\"\n ? [\n h.section(\n [\n h.Role(\"region\"),\n h.AriaLabel(text(model.locale, \"consent.title\")),\n h.DataAttribute(\"testid\", \"consent-prompt\"),\n sx(styles.row),\n ],\n [\n h.p([sx(styles.muted)], [text(model.locale, \"consent.message\")]),\n h.button(\n [\n h.Type(\"button\"),\n h.DataAttribute(\"testid\", \"consent-accept\"),\n h.OnClick(Message.ChoseConsent({ accept: true })),\n sx(styles.button),\n ],\n [text(model.locale, \"consent.accept\")],\n ),\n h.button(\n [\n h.Type(\"button\"),\n h.DataAttribute(\"testid\", \"consent-necessary\"),\n h.OnClick(Message.ChoseConsent({ accept: false })),\n sx(styles.button, styles.buttonOutline),\n ],\n [text(model.locale, \"consent.necessary\")],\n ),\n ],\n ),\n ]\n : []\n\nexport const makeView =\n (shell: Shell) =>\n (model: Model, h: HtmlBuilder<Message>): Document => {\n rendering.locale = model.locale\n rendering.development = shell.development\n // The scheme's colours: the theme's, or its high-contrast preset's (each instead of the other, never both).\n const high = model.appearance.preset === \"contrast\"\n const themes =\n stylex.attrs(\n !high && isDark(model) && dark,\n high && (isDark(model) ? contrastDark : contrast),\n model.appearance.direction === \"rtl\" && rtl,\n ).class ?? \"\"\n return {\n title:\n model.route._tag === \"View\"\n ? `${shell.viewTitle(model.route.view)} | Eloxiv`\n : model.route._tag === \"Make\"\n ? `${model.route.module} | Eloxiv`\n : model.route._tag === \"Settings\"\n ? `${text(model.locale, \"settings.title\")} | Eloxiv`\n : model.route._tag === \"DesktopSignIn\"\n ? `${text(model.locale, \"desktop.title\")} | Eloxiv`\n : \"Eloxiv\",\n body: h.div(\n [\n h.Id(\"shell\"),\n h.Dir(model.appearance.direction),\n h.Lang(model.locale),\n h.DataAttribute(\"theme\", isDark(model) ? \"dark\" : \"light\"),\n h.DataAttribute(\"preset\", model.appearance.preset),\n // The organisation the Model acts in, as rendered (what the strict organisation-switch check reads).\n h.DataAttribute(\"org\", model.auth._tag === \"SignedIn\" ? Option.getOrElse(model.auth.orgId, () => \"\") : \"\"),\n h.Class(`${themes} ${stylex.attrs(styles.root, isDark(model) && styles.rootDark).class ?? \"\"}`.trim()),\n h.OnMount(ReportInteractive()),\n ],\n [\n header(shell, model, h),\n ...backendNotice(model, h),\n ...organisationsNotice(model, h),\n ...consentPrompt(model, h),\n h.main(\n [sx(styles.main, Option.exists(model.screen, (slot) => slot.panels.length > 0) && styles.mainWide)],\n [content(shell, model, h)],\n ),\n appearanceDialog(model, h),\n ],\n ),\n }\n }\n",
|
|
126
|
+
"type": "registry:file",
|
|
127
|
+
"target": "shell-foldkit/src/view.ts"
|
|
128
|
+
},
|
|
129
|
+
{
|
|
130
|
+
"path": "app/shell-foldkit/src/webSession.ts",
|
|
131
|
+
"content": "/**\n * The session's storage in the browser: the client core's `SessionStore` and `RevocationStore` (`@eloxiv/client`)\n * over the page's `localStorage`, in the shell's format (shared with the React shell, so a person keeps their session).\n * Framework-free: the storage is read through `storage()` each time (a test swaps it), so it runs on Node and Bun.\n *\n * - **The session** is `eloxiv.session`: `{ token, user }`, the token the core keeps between loads.\n * - **The remembered context goes with its session.** The person and organisation last open (`remember`, for the\n * client core's offline start) are kept in `eloxiv.session.context` with the token they were open with, recalled\n * only while the stored session still holds that token, and forgotten whenever the session is (`clear`, `clearIf`;\n * the context first, so a failure between the two leaves a session that reopens nothing offline). A session saved\n * for another token forgets them too, and `forgetContext` forgets them alone, keeping the session. Never a credential.\n * - **Every tab shares it, so a stale write cannot undo another tab's.** Each change of the context bumps its revision\n * (`eloxiv.session.context.rev`); a `remember` from a tab that has not seen the latest change (its listing began\n * before another tab forgot the context) keeps nothing, once. A sign-out whose revocation storage would not keep\n * (full) leaves a token-scoped mark instead (`eloxiv.session.signedOut`, written once the context is gone, so it\n * fits): no tab recalls or remembers a context for that token again, and the core treats it as a pending revocation\n * (never reopened or reported, retried, dropped once the kernel confirms it). Open tabs re-check the session when\n * another clears, replaces or marks it (`storage` events, `shell.ts`).\n * - **Failures are errors where custody depends on them.** Forgetting (`clear`, `clearIf`, `forgetContext`, the mark)\n * and `remember` reject when storage refuses (full, denied), so the core retries or forgets the context instead (or\n * reports the sign-out not saved); `save` keeps today's behaviour (a session storage will not keep lasts for this page\n * only) but never leaves another token's context behind. Where the page has no storage at all (a sandbox, storage\n * disabled), nothing is kept or recalled and nothing needs forgetting: the session lasts for the page alone. The\n * revocation store's `keep` says whether it holds the token now (read back).\n * - **Limit.** The browser gives `localStorage` no lock across tabs: each check and write is one synchronous step, so\n * a stale write is refused unless two tabs interleave within the same instant.\n */\nimport type { RememberedContext, RevocationStore, SessionStore } from \"@eloxiv/client\"\n\n/** What the page's storage offers (`localStorage`). */\nexport interface WebStorage {\n readonly getItem: (key: string) => string | null\n readonly setItem: (key: string, value: string) => void\n readonly removeItem: (key: string) => void\n}\n\nexport const SESSION_KEY = \"eloxiv.session\"\nexport const CONTEXT_KEY = \"eloxiv.session.context\"\nexport const CONTEXT_REVISION_KEY = \"eloxiv.session.context.rev\"\nexport const SIGNED_OUT_KEY = \"eloxiv.session.signedOut\"\nexport const PENDING_KEY = \"eloxiv.pendingRevocations\"\n\n/** The page's `localStorage`, where there is one and it may be used (a sandbox, a private mode may deny it). */\nexport const pageStorage = (): WebStorage | undefined => {\n try {\n return typeof localStorage === \"object\" && localStorage !== null ? localStorage : undefined\n } catch {\n return undefined\n }\n}\n\nexport interface WebSessionStorage {\n readonly session: SessionStore\n readonly revocations: RevocationStore\n /** Read a key (`undefined` when absent or storage cannot be read). */\n readonly get: (key: string) => string | undefined\n /** Write a key (`undefined` removes it): whether storage took it. */\n readonly set: (key: string, value: string | undefined) => boolean\n /** The stored session's token, if a well-formed one is stored. */\n readonly storedToken: () => string | undefined\n /** The stored pending revocations (a sign-out's mark among them). */\n readonly pending: () => Array<string>\n}\n\nconst refused = (what: string) => new Error(`The browser's storage could not ${what}`)\n\n/** The most sign-out marks kept (the oldest go first: by then their revocations were confirmed or retried long since). */\nconst MARKS = 8\n\nexport const webSessionStorage = (storage: () => WebStorage | undefined = pageStorage): WebSessionStorage => {\n /** The page's storage, or nothing when it has none it may use. */\n const target = (): WebStorage | undefined => {\n try {\n return storage()\n } catch {\n return undefined\n }\n }\n /** Whether the page has no storage at all: nothing is kept, so nothing needs forgetting. */\n const unavailable = () => target() === undefined\n /** A read that tells absent (`undefined`) from refused (it throws): for a check that must not mistake one for the other. */\n const strict = (key: string): string | undefined => target()?.getItem(key) ?? undefined\n const get = (key: string): string | undefined => {\n try {\n return strict(key)\n } catch {\n return undefined\n }\n }\n /** Whether storage took the write: it throws when full, denied or unavailable (private mode, a sandbox). */\n const set = (key: string, value: string | undefined): boolean => {\n try {\n const page = target()\n if (page === undefined) return false\n if (value === undefined) page.removeItem(key)\n else page.setItem(key, value)\n return true\n } catch {\n return false\n }\n }\n /** `set`, or a rejection saying what could not be done. */\n const must = (key: string, value: string | undefined, what: string) => {\n if (!set(key, value)) throw refused(what)\n }\n\n const tokenOf = (raw: string | undefined): string | undefined => {\n if (raw === undefined) return undefined\n try {\n const parsed = JSON.parse(raw) as {\n readonly token?: unknown\n readonly user?: { readonly id?: unknown; readonly email?: unknown; readonly name?: unknown }\n }\n const { token, user } = parsed\n return typeof token === \"string\" &&\n typeof user?.id === \"string\" &&\n typeof user.email === \"string\" &&\n typeof user.name === \"string\"\n ? token\n : undefined\n } catch {\n return undefined\n }\n }\n const storedToken = (): string | undefined => tokenOf(get(SESSION_KEY))\n\n /** The remembered context and the token it was kept with, or nothing (absent, torn, or of another shape). */\n const remembered = (\n raw = get(CONTEXT_KEY),\n ): { readonly token: string; readonly context: RememberedContext } | undefined => {\n if (raw === undefined) return undefined\n try {\n const parsed = JSON.parse(raw) as {\n readonly token?: unknown\n readonly user?: { readonly id?: unknown; readonly email?: unknown; readonly name?: unknown }\n readonly organization?: { readonly orgId?: unknown; readonly name?: unknown; readonly roles?: unknown }\n }\n const { token, user, organization } = parsed\n if (typeof token !== \"string\" || typeof user?.id !== \"string\" || typeof user.email !== \"string\") return undefined\n if (typeof user.name !== \"string\" || typeof organization?.orgId !== \"string\") return undefined\n if (typeof organization.name !== \"string\" || !Array.isArray(organization.roles)) return undefined\n return {\n token,\n context: {\n user: { id: user.id, email: user.email, name: user.name },\n organization: {\n orgId: organization.orgId,\n name: organization.name,\n roles: organization.roles.filter((r): r is string => typeof r === \"string\"),\n },\n },\n }\n } catch {\n return undefined\n }\n }\n\n /** The context's revision this tab last saw (read when it opened, then at each of its own changes and refusals). */\n let seen = get(CONTEXT_REVISION_KEY)\n /** A change of the context: a new revision for every tab to see (best effort: a refused one changes nothing else). */\n const revise = () => {\n const next = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`\n if (set(CONTEXT_REVISION_KEY, next)) seen = next\n }\n\n /** Tokens a sign-out marked (its revocation storage would not keep): never recalled or remembered for again. */\n const marks = (): Array<string> => {\n try {\n const parsed: unknown = JSON.parse(get(SIGNED_OUT_KEY) ?? \"[]\")\n return Array.isArray(parsed) ? parsed.filter((t): t is string => typeof t === \"string\") : []\n } catch {\n return []\n }\n }\n const storeMarks = (tokens: ReadonlyArray<string>): boolean =>\n set(SIGNED_OUT_KEY, tokens.length === 0 ? undefined : JSON.stringify(tokens.slice(-MARKS)))\n /** Tokens whose revocation this tab could not keep: their context's forgetting marks them (`forgetContext`). */\n const unsaved = new Set<string>()\n\n /** Forget the session and its remembered context: the context first; both tried, a rejection if either stays. */\n const forgetSession = () => {\n if (unavailable()) return\n const context = set(CONTEXT_KEY, undefined)\n const session = set(SESSION_KEY, undefined)\n if (context) revise()\n if (!context) throw refused(\"forget the remembered context\")\n if (!session) throw refused(\"forget the session\")\n }\n\n const session: SessionStore = {\n load: async () => storedToken(),\n save: async (token, account) => {\n // No storage: the session lasts for the page alone (in the core's memory), and nothing was kept to forget.\n if (unavailable()) return\n // Another token's context goes first; none kept needs nothing, and one that cannot be read is removed.\n let raw: string | undefined\n let unreadable = false\n try {\n raw = strict(CONTEXT_KEY)\n } catch {\n unreadable = true\n }\n if (unreadable || (raw !== undefined && remembered(raw)?.token !== token)) {\n must(CONTEXT_KEY, undefined, \"forget the remembered context\")\n revise()\n }\n const user =\n account === undefined\n ? { id: \"\", email: \"\", name: \"\" }\n : { id: account.id, email: account.email, name: account.name }\n set(SESSION_KEY, JSON.stringify({ token, user }))\n },\n clear: async () => forgetSession(),\n clearIf: async (token) => {\n if (unavailable()) return\n // A session that cannot be read now is not \"another one's\": the forgetting fails, so the core tries again.\n let stored: string | undefined\n try {\n stored = tokenOf(strict(SESSION_KEY))\n } catch {\n throw refused(\"read the session\")\n }\n if (stored === token) forgetSession()\n },\n recall: async (token) => {\n if (marks().includes(token)) return undefined\n const kept = remembered()\n return kept !== undefined && kept.token === token && storedToken() === token ? kept.context : undefined\n },\n remember: async (token, context) => {\n // Only for the session stored now: a late write for a session forgotten meanwhile keeps nothing, nor one for a\n // session another tab signed out of.\n if (storedToken() !== token || marks().includes(token)) return\n // Another tab changed the context since this one last saw it (it forgot an organisation the person left, say):\n // this write may come from a listing older than that change, so it keeps nothing; the next one counts.\n const current = get(CONTEXT_REVISION_KEY)\n if (current !== undefined && current !== seen) {\n seen = current\n return\n }\n must(CONTEXT_KEY, JSON.stringify({ token, ...context }), \"remember the context\")\n revise()\n },\n forgetContext: async (token) => {\n if (unavailable()) return\n // Another token's context stays (it is recalled only for that token); one that cannot be read goes too.\n const kept = remembered()\n if (kept === undefined || kept.token === token) {\n must(CONTEXT_KEY, undefined, \"forget the remembered context\")\n revise()\n }\n // A sign-out whose revocation this tab could not keep: marked, now that the context's removal made room, so no\n // tab's late `remember` brings it back. Unmarked, the sign-out is not saved (the core says so).\n if (unsaved.has(token) && !marks().includes(token)) {\n if (!storeMarks([...marks(), token]) || !marks().includes(token)) throw refused(\"keep the sign-out\")\n }\n },\n }\n\n /** The revocations storage keeps for the next start (appended to; an entry leaves only when the kernel confirms). */\n const listed = (): Array<string> => {\n try {\n const parsed: unknown = JSON.parse(get(PENDING_KEY) ?? \"[]\")\n return Array.isArray(parsed) ? parsed.filter((t): t is string => typeof t === \"string\") : []\n } catch {\n return []\n }\n }\n const storePending = (tokens: ReadonlyArray<string>): boolean =>\n set(PENDING_KEY, tokens.length === 0 ? undefined : JSON.stringify(tokens))\n /** Every revocation still to confirm: the list, and the sign-outs marked instead. */\n const pending = (): Array<string> => [...new Set([...listed(), ...marks()])]\n\n /** The core's revocation store (a durable sign-out): each write read back, not assumed. */\n const revocations: RevocationStore = {\n load: async () => pending(),\n keep: async (token) => {\n const stored = listed()\n const kept = stored.includes(token) || (storePending([...stored, token]) && listed().includes(token))\n if (!kept) unsaved.add(token)\n return kept\n },\n drop: async (token) => {\n unsaved.delete(token)\n const stored = listed()\n if (stored.includes(token)) storePending(stored.filter((t) => t !== token))\n const marked = marks()\n if (marked.includes(token)) storeMarks(marked.filter((t) => t !== token))\n },\n }\n\n return { session, revocations, get, set, storedToken, pending }\n}\n",
|
|
132
|
+
"type": "registry:file",
|
|
133
|
+
"target": "shell-foldkit/src/webSession.ts"
|
|
134
|
+
},
|
|
135
|
+
{
|
|
136
|
+
"path": "app/shell-foldkit/tsconfig.json",
|
|
137
|
+
"content": "{\n \"compilerOptions\": {\n \"target\": \"es2023\",\n \"lib\": [\"ES2023\", \"DOM\", \"DOM.Iterable\"],\n \"module\": \"esnext\",\n \"moduleResolution\": \"bundler\",\n \"customConditions\": [\"@eloxiv/source\"],\n \"types\": [\"vite/client\"],\n \"allowImportingTsExtensions\": true,\n \"verbatimModuleSyntax\": true,\n \"moduleDetection\": \"force\",\n \"isolatedModules\": true,\n \"erasableSyntaxOnly\": true,\n \"skipLibCheck\": true,\n \"noEmit\": true,\n \"strict\": true,\n \"noUncheckedIndexedAccess\": true,\n \"exactOptionalPropertyTypes\": true,\n \"noImplicitOverride\": true,\n \"noImplicitReturns\": true,\n \"noFallthroughCasesInSwitch\": true,\n \"noPropertyAccessFromIndexSignature\": true,\n \"noUnusedLocals\": true,\n \"noUnusedParameters\": true\n },\n \"include\": [\"src\", \"vite.config.ts\", \"screenMeta.ts\"]\n}\n",
|
|
138
|
+
"type": "registry:file",
|
|
139
|
+
"target": "shell-foldkit/tsconfig.json"
|
|
140
|
+
},
|
|
141
|
+
{
|
|
142
|
+
"path": "app/shell-foldkit/vite.config.ts",
|
|
143
|
+
"content": "import { foldkit } from \"@foldkit/vite-plugin\"\nimport stylexVite from \"@stylexjs/unplugin/vite\"\nimport { resolve } from \"node:path\"\nimport { defineConfig } from \"vite\"\nimport { screenMeta } from \"./screenMeta.ts\"\n\nconst appRoot = resolve(import.meta.dirname, \"..\")\n\n/**\n * Eloxiv's browser packages have no side effects when imported (no registrations, polyfills or globals), so a module\n * of theirs whose exports the shell does not use is left out of the build (in the workspace's sources and in an\n * installed package's `dist` alike). Most of `@eloxiv/contracts` is contracts the shell never touches.\n */\nconst PURE =\n /[\\\\/](?:packages[\\\\/](?:contracts|client|shell-core)[\\\\/]src|@eloxiv[\\\\/](?:contracts|client|shell-core)[\\\\/])/\n\nexport default defineConfig(({ command }) => ({\n plugins: [\n // Each screen's routing fields, read from its file, so its code loads when a route first needs it.\n screenMeta(),\n // StyleX compiles every `stylex.create` and theme at build time and appends the CSS to the shell's\n // stylesheet; its variables are named from each file's path under the app's root, so the theme\n // (`themes/default/tokens.stylex.ts`) resolves to the same names from every file that uses it.\n stylexVite({\n dev: command === \"serve\",\n useCSSLayers: true,\n runtimeInjection: false,\n unstable_moduleResolution: { type: \"commonJS\", rootDir: appRoot },\n }),\n // Foldkit's plugin stamps each view function's identity (route changes replace, never patch, a page).\n foldkit(),\n ],\n resolve: {\n // Inside the Eloxiv repository, workspace packages resolve to their TypeScript source.\n conditions: [\"@eloxiv/source\", \"module\", \"browser\", \"development|production\"],\n },\n // In the dev server StyleX's plugin loads (`this.load`) every import of a file that uses StyleX while\n // transforming it; with Vite's default, the dependency optimizer holds those loads until the import crawl ends,\n // and the crawl waits for that transform: the page never loads. Optimise without waiting for the crawl.\n optimizeDeps: { holdUntilCrawlEnd: false },\n envPrefix: [\"VITE_\", \"TAURI_ENV_\"],\n // The screens load on demand: warmed with the entry, so the first route that needs one finds it transformed.\n server: { port: 5173, strictPort: true, warmup: { clientFiles: [\"./src/main.ts\", \"./src/screens/*.ts\"] } },\n clearScreen: false,\n build: {\n target: \"es2022\",\n rolldownOptions: {\n // Anything else as its package says (`sideEffects` in its package.json).\n treeshake: { moduleSideEffects: (id: string) => (PURE.test(id) ? false : undefined) },\n },\n },\n}))\n",
|
|
144
|
+
"type": "registry:file",
|
|
145
|
+
"target": "shell-foldkit/vite.config.ts"
|
|
146
|
+
}
|
|
147
|
+
],
|
|
148
|
+
"meta": {
|
|
149
|
+
"eloxiv": {
|
|
150
|
+
"kind": "shell",
|
|
151
|
+
"version": "0.8.7",
|
|
152
|
+
"next": [
|
|
153
|
+
"Run it from the app root: cd shell-foldkit && pnpm exec vite (or vite build)"
|
|
154
|
+
]
|
|
155
|
+
}
|
|
156
|
+
},
|
|
157
|
+
"type": "registry:item"
|
|
158
|
+
}
|