@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
package/r/shell-foldkit.json
CHANGED
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
},
|
|
51
51
|
{
|
|
52
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 \"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",
|
|
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
54
|
"type": "registry:file",
|
|
55
55
|
"target": "shell-foldkit/src/locale.ts"
|
|
56
56
|
},
|
|
@@ -86,7 +86,7 @@
|
|
|
86
86
|
},
|
|
87
87
|
{
|
|
88
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 RevocationStore,\n type SessionStore,\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\"\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])\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 }),\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 const SESSION_KEY = \"eloxiv.session\"\nexport const PENDING_KEY = \"eloxiv.pendingRevocations\"\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\nconst storage = {\n get: (key: string): string | undefined => {\n try {\n return localStorage.getItem(key) ?? undefined\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 set: (key: string, value: string | undefined): boolean => {\n try {\n if (value === undefined) localStorage.removeItem(key)\n else localStorage.setItem(key, value)\n return true\n } catch {\n return false\n }\n },\n}\n\n/** The revocations storage keeps for the next start (appended to; an entry leaves only when the kernel confirms). */\nconst storedPending = (): Array<string> => {\n try {\n const parsed: unknown = JSON.parse(storage.get(PENDING_KEY) ?? \"[]\")\n return Array.isArray(parsed) ? parsed.filter((t): t is string => typeof t === \"string\") : []\n } catch {\n return []\n }\n}\nconst storePending = (tokens: ReadonlyArray<string>): boolean =>\n storage.set(PENDING_KEY, tokens.length === 0 ? undefined : JSON.stringify(tokens))\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})\nconst storedSessionToken = (): string | undefined =>\n Option.getOrUndefined(\n Option.flatMap(Option.fromNullishOr(storage.get(SESSION_KEY)), (raw) =>\n Option.map(Schema.decodeUnknownOption(Schema.fromJsonString(StoredSession))(raw), (s) => s.token),\n ),\n )\n\n/**\n * The core's session store over the browser's storage, in the shell's format (`{ token, user }`): the token the\n * core keeps between loads, with the account it was adopted for.\n */\nconst webSessionStore: SessionStore = {\n load: async () => storedSessionToken(),\n save: async (token, account) => {\n const user =\n account === undefined\n ? { id: \"\", email: \"\", name: \"\" }\n : { id: account.id, email: account.email, name: account.name }\n storage.set(SESSION_KEY, JSON.stringify({ token, user }))\n },\n clear: async () => {\n storage.set(SESSION_KEY, undefined)\n },\n clearIf: async (token) => {\n if (storedSessionToken() === token) storage.set(SESSION_KEY, undefined)\n },\n}\n\n/** The core's revocation store (a durable sign-out) over the browser's storage: each write read back, not assumed. */\nconst webRevocationStore: RevocationStore = {\n load: async () => storedPending(),\n keep: async (token) => {\n const stored = storedPending()\n return stored.includes(token) || (storePending([...stored, token]) && storedPending().includes(token))\n },\n drop: async (token) => {\n const stored = storedPending()\n if (stored.includes(token)) storePending(stored.filter((t) => t !== token))\n },\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: webSessionStore,\n revocations: webRevocationStore,\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 }\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: { ...same, memberships: state.memberships, organisationsProblem: problemOf(state) },\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 },\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 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).\n readiness: entry(\n { ready: Schema.Boolean },\n {\n modelToDependencies: (model) => ({ ready: model.backend === \"ready\" }),\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\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",
|
|
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
90
|
"type": "registry:file",
|
|
91
91
|
"target": "shell-foldkit/src/shell.ts"
|
|
92
92
|
},
|
|
@@ -98,7 +98,7 @@
|
|
|
98
98
|
},
|
|
99
99
|
{
|
|
100
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 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",
|
|
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
102
|
"type": "registry:file",
|
|
103
103
|
"target": "shell-foldkit/src/styles.ts"
|
|
104
104
|
},
|
|
@@ -122,10 +122,16 @@
|
|
|
122
122
|
},
|
|
123
123
|
{
|
|
124
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 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.\n if (model.auth._tag === \"SignedIn\" && Option.isSome(model.auth.organisationsProblem))\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/** 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 ...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",
|
|
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
126
|
"type": "registry:file",
|
|
127
127
|
"target": "shell-foldkit/src/view.ts"
|
|
128
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
|
+
},
|
|
129
135
|
{
|
|
130
136
|
"path": "app/shell-foldkit/tsconfig.json",
|
|
131
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",
|
|
@@ -142,7 +148,7 @@
|
|
|
142
148
|
"meta": {
|
|
143
149
|
"eloxiv": {
|
|
144
150
|
"kind": "shell",
|
|
145
|
-
"version": "0.8.
|
|
151
|
+
"version": "0.8.7",
|
|
146
152
|
"next": [
|
|
147
153
|
"Run it from the app root: cd shell-foldkit && pnpm exec vite (or vite build)"
|
|
148
154
|
]
|